blob: 41914e3c2dfaf72ec0c43a797f489277b68a0192 [file] [log] [blame]
Eric Laurent81784c32012-11-19 14:55:58 -08001/*
2**
3** Copyright 2012, The Android Open Source Project
4**
5** Licensed under the Apache License, Version 2.0 (the "License");
6** you may not use this file except in compliance with the License.
7** You may obtain a copy of the License at
8**
9** http://www.apache.org/licenses/LICENSE-2.0
10**
11** Unless required by applicable law or agreed to in writing, software
12** distributed under the License is distributed on an "AS IS" BASIS,
13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14** See the License for the specific language governing permissions and
15** limitations under the License.
16*/
17
18
19#define LOG_TAG "AudioFlinger"
Vlad Popab042ee62022-10-20 18:05:00 +020020// #define LOG_NDEBUG 0
Alex Ray371eb972012-11-30 11:11:54 -080021#define ATRACE_TAG ATRACE_TAG_AUDIO
Eric Laurent81784c32012-11-19 14:55:58 -080022
Andy Hung25a80ac2023-07-19 12:47:35 -070023#include "Threads.h"
24
25#include "Client.h"
26#include "IAfEffect.h"
27#include "MelReporter.h"
28#include "ResamplerBufferProvider.h"
29
30#include <afutils/DumpTryLock.h>
31#include <afutils/Permission.h>
32#include <afutils/TypedLogger.h>
33#include <afutils/Vibrator.h>
34#include <audio_utils/MelProcessor.h>
35#include <audio_utils/Metadata.h>
36#ifdef DEBUG_CPU_USAGE
37#include <audio_utils/Statistics.h>
38#include <cpustats/ThreadCpuUsage.h>
39#endif
40#include <audio_utils/channels.h>
41#include <audio_utils/format.h>
42#include <audio_utils/minifloat.h>
43#include <audio_utils/mono_blend.h>
44#include <audio_utils/primitives.h>
45#include <audio_utils/safe_math.h>
46#include <audiomanager/AudioManager.h>
47#include <binder/IPCThreadState.h>
48#include <binder/IServiceManager.h>
49#include <binder/PersistableBundle.h>
Eric Laurent4eb45d02023-12-20 12:07:17 +010050#include <com_android_media_audio.h>
Glenn Kastenc9a23672020-06-30 12:12:42 -070051#include <cutils/bitops.h>
Eric Laurent81784c32012-11-19 14:55:58 -080052#include <cutils/properties.h>
Andy Hung25a80ac2023-07-19 12:47:35 -070053#include <fastpath/AutoPark.h>
jiabinc52b1ff2019-10-31 17:20:42 -070054#include <media/AudioContainers.h>
55#include <media/AudioDeviceTypeAddr.h>
Glenn Kasten1ab85ec2013-05-31 09:18:43 -070056#include <media/AudioParameter.h>
Andy Hungcd044842014-08-07 11:04:34 -070057#include <media/AudioResamplerPublic.h>
Andy Hung25a80ac2023-07-19 12:47:35 -070058#ifdef ADD_BATTERY_DATA
59#include <media/IMediaPlayerService.h>
60#include <media/IMediaDeathNotifier.h>
61#endif
62#include <media/MmapStreamCallback.h>
Andy Hung89816052017-01-11 17:08:23 -080063#include <media/RecordBufferConverter.h>
Mikhail Naganov913d06c2016-11-01 12:49:22 -070064#include <media/TypeConverter.h>
Andy Hung25a80ac2023-07-19 12:47:35 -070065#include <media/audiohal/EffectsFactoryHalInterface.h>
66#include <media/audiohal/StreamHalInterface.h>
Glenn Kasten6dbb5e32014-05-13 10:38:42 -070067#include <media/nbaio/AudioStreamInSource.h>
Eric Laurent81784c32012-11-19 14:55:58 -080068#include <media/nbaio/AudioStreamOutSink.h>
69#include <media/nbaio/MonoPipe.h>
70#include <media/nbaio/MonoPipeReader.h>
71#include <media/nbaio/Pipe.h>
72#include <media/nbaio/PipeReader.h>
73#include <media/nbaio/SourceAudioBufferProvider.h>
Wei Jia3f273d12015-11-24 09:06:49 -080074#include <mediautils/BatteryNotifier.h>
Andy Hungafc51db2022-04-08 17:33:40 -070075#include <mediautils/Process.h>
Andy Hungab7ef302018-05-15 19:35:29 -070076#include <mediautils/SchedulingPolicyService.h>
77#include <mediautils/ServiceUtilities.h>
Andy Hung25a80ac2023-07-19 12:47:35 -070078#include <powermanager/PowerManager.h>
79#include <private/android_filesystem_config.h>
80#include <private/media/AudioTrackShared.h>
81#include <system/audio_effects/effect_aec.h>
82#include <system/audio_effects/effect_downmix.h>
83#include <system/audio_effects/effect_ns.h>
84#include <system/audio_effects/effect_spatializer.h>
85#include <utils/Log.h>
86#include <utils/Trace.h>
Eric Laurent81784c32012-11-19 14:55:58 -080087
Andy Hung25a80ac2023-07-19 12:47:35 -070088#include <fcntl.h>
89#include <linux/futex.h>
90#include <math.h>
91#include <memory>
Nicolas Rouletfe1e1442017-01-30 12:02:03 -080092#include <pthread.h>
Andy Hung25a80ac2023-07-19 12:47:35 -070093#include <sstream>
94#include <string>
95#include <sys/stat.h>
96#include <sys/syscall.h>
Nicolas Rouletfe1e1442017-01-30 12:02:03 -080097
Eric Laurent81784c32012-11-19 14:55:58 -080098// ----------------------------------------------------------------------------
99
100// Note: the following macro is used for extremely verbose logging message. In
101// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
102// 0; but one side effect of this is to turn all LOGV's as well. Some messages
103// are so verbose that we want to suppress them even when we have ALOG_ASSERT
104// turned on. Do not uncomment the #def below unless you really know what you
105// are doing and want to see all of the extremely verbose messages.
106//#define VERY_VERY_VERBOSE_LOGGING
107#ifdef VERY_VERY_VERBOSE_LOGGING
108#define ALOGVV ALOGV
109#else
110#define ALOGVV(a...) do { } while(0)
111#endif
112
Andy Hung6770c6f2015-04-07 13:43:36 -0700113// TODO: Move these macro/inlines to a header file.
Glenn Kasten49d00ad2014-07-21 11:22:03 -0700114#define max(a, b) ((a) > (b) ? (a) : (b))
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700115
Andy Hung6770c6f2015-04-07 13:43:36 -0700116template <typename T>
117static inline T min(const T& a, const T& b)
118{
119 return a < b ? a : b;
120}
Glenn Kasten49d00ad2014-07-21 11:22:03 -0700121
Eric Laurent81784c32012-11-19 14:55:58 -0800122namespace android {
123
Andy Hungee58e4a2023-07-07 13:47:37 -0700124using audioflinger::SyncEvent;
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -0700125using media::IEffectClient;
Svet Ganov33761132021-05-13 22:51:08 +0000126using content::AttributionSourceState;
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -0700127
Andy Hung25a80ac2023-07-19 12:47:35 -0700128// Keep in sync with java definition in media/java/android/media/AudioRecord.java
129static constexpr int32_t kMaxSharedAudioHistoryMs = 5000;
130
Eric Laurent81784c32012-11-19 14:55:58 -0800131// retry counts for buffer fill timeout
132// 50 * ~20msecs = 1 second
133static const int8_t kMaxTrackRetries = 50;
134static const int8_t kMaxTrackStartupRetries = 50;
Andy Hung455982f2021-04-27 17:46:12 -0700135
Eric Laurent81784c32012-11-19 14:55:58 -0800136// allow less retry attempts on direct output thread.
137// direct outputs can be a scarce resource in audio hardware and should
138// be released as quickly as possible.
Andy Hung455982f2021-04-27 17:46:12 -0700139// Notes:
140// 1) The retry duration kMaxTrackRetriesDirectMs may be increased
141// in case the data write is bursty for the AudioTrack. The application
142// should endeavor to write at least once every kMaxTrackRetriesDirectMs
143// to prevent an underrun situation. If the data is bursty, then
144// the application can also throttle the data sent to be even.
145// 2) For compressed audio data, any data present in the AudioTrack buffer
146// will be sent and reset the retry count. This delivers data as
147// it arrives, with approximately kDirectMinSleepTimeUs = 10ms checking interval.
148// 3) For linear PCM or proportional PCM, we wait one period for a period's worth
149// of data to be available, then any remaining data is delivered.
150// This is required to ensure the last bit of data is delivered before underrun.
151//
152// Sleep time per cycle is kDirectMinSleepTimeUs for compressed tracks
153// or the size of the HAL period for proportional / linear PCM tracks.
154static const int32_t kMaxTrackRetriesDirectMs = 200;
Eric Laurent81784c32012-11-19 14:55:58 -0800155
156// don't warn about blocked writes or record buffer overflows more often than this
157static const nsecs_t kWarningThrottleNs = seconds(5);
158
159// RecordThread loop sleep time upon application overrun or audio HAL read error
160static const int kRecordThreadSleepUs = 5000;
161
Eric Laurent10351942014-05-08 18:49:52 -0700162// maximum time to wait in sendConfigEvent_l() for a status to be received
163static const nsecs_t kConfigEventTimeoutNs = seconds(2);
Eric Laurent81784c32012-11-19 14:55:58 -0800164
165// minimum sleep time for the mixer thread loop when tracks are active but in underrun
166static const uint32_t kMinThreadSleepTimeUs = 5000;
167// maximum divider applied to the active sleep time in the mixer thread loop
168static const uint32_t kMaxThreadSleepTimeShift = 2;
169
Andy Hung09a50072014-02-27 14:30:47 -0800170// minimum normal sink buffer size, expressed in milliseconds rather than frames
Glenn Kasteneb9487e2015-07-22 09:15:17 -0700171// FIXME This should be based on experimentally observed scheduling jitter
Andy Hung09a50072014-02-27 14:30:47 -0800172static const uint32_t kMinNormalSinkBufferSizeMs = 20;
173// maximum normal sink buffer size
174static const uint32_t kMaxNormalSinkBufferSizeMs = 24;
Eric Laurent81784c32012-11-19 14:55:58 -0800175
Glenn Kasteneb9487e2015-07-22 09:15:17 -0700176// minimum capture buffer size in milliseconds to _not_ need a fast capture thread
177// FIXME This should be based on experimentally observed scheduling jitter
178static const uint32_t kMinNormalCaptureBufferSizeMs = 12;
179
Eric Laurent972a1732013-09-04 09:42:59 -0700180// Offloaded output thread standby delay: allows track transition without going to standby
181static const nsecs_t kOffloadStandbyDelayNs = seconds(1);
182
Eric Laurent51716182016-02-29 18:00:56 -0800183// Direct output thread minimum sleep time in idle or active(underrun) state
184static const nsecs_t kDirectMinSleepTimeUs = 10000;
185
Brian Lindahl65e90012022-07-27 18:01:07 +0200186// Minimum amount of time between checking to see if the timestamp is advancing
187// for underrun detection. If we check too frequently, we may not detect a
188// timestamp update and will falsely detect underrun.
Andy Hung0ff14292023-12-20 15:55:16 -0800189static constexpr nsecs_t kMinimumTimeBetweenTimestampChecksNs = 150 /* ms */ * 1'000'000;
Brian Lindahl65e90012022-07-27 18:01:07 +0200190
Glenn Kasten1b291842016-07-18 14:55:21 -0700191// The universal constant for ubiquitous 20ms value. The value of 20ms seems to provide a good
192// balance between power consumption and latency, and allows threads to be scheduled reliably
193// by the CFS scheduler.
194// FIXME Express other hardcoded references to 20ms with references to this constant and move
195// it appropriately.
196#define FMS_20 20
Eric Laurent51716182016-02-29 18:00:56 -0800197
Eric Laurent81784c32012-11-19 14:55:58 -0800198// Whether to use fast mixer
199static const enum {
200 FastMixer_Never, // never initialize or use: for debugging only
201 FastMixer_Always, // always initialize and use, even if not needed: for debugging only
202 // normal mixer multiplier is 1
203 FastMixer_Static, // initialize if needed, then use all the time if initialized,
204 // multiplier is calculated based on min & max normal mixer buffer size
205 FastMixer_Dynamic, // initialize if needed, then use dynamically depending on track load,
206 // multiplier is calculated based on min & max normal mixer buffer size
207 // FIXME for FastMixer_Dynamic:
208 // Supporting this option will require fixing HALs that can't handle large writes.
209 // For example, one HAL implementation returns an error from a large write,
210 // and another HAL implementation corrupts memory, possibly in the sample rate converter.
211 // We could either fix the HAL implementations, or provide a wrapper that breaks
212 // up large writes into smaller ones, and the wrapper would need to deal with scheduler.
213} kUseFastMixer = FastMixer_Static;
214
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700215// Whether to use fast capture
216static const enum {
217 FastCapture_Never, // never initialize or use: for debugging only
218 FastCapture_Always, // always initialize and use, even if not needed: for debugging only
219 FastCapture_Static, // initialize if needed, then use all the time if initialized
220} kUseFastCapture = FastCapture_Static;
221
Eric Laurent81784c32012-11-19 14:55:58 -0800222// Priorities for requestPriority
223static const int kPriorityAudioApp = 2;
224static const int kPriorityFastMixer = 3;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700225static const int kPriorityFastCapture = 3;
Pattara Teerapong9a332c52024-01-26 08:18:05 +0000226// Request real-time priority for PlaybackThread in ARC
227static const int kPriorityPlaybackThreadArc = 1;
Eric Laurent81784c32012-11-19 14:55:58 -0800228
Glenn Kastenea38ee72016-04-18 11:08:01 -0700229// IAudioFlinger::createTrack() has an in/out parameter 'pFrameCount' for the total size of the
230// track buffer in shared memory. Zero on input means to use a default value. For fast tracks,
231// AudioFlinger derives the default from HAL buffer size and 'fast track multiplier'.
Glenn Kasten03490092014-05-27 12:30:54 -0700232
233// This is the default value, if not specified by property.
Glenn Kastenb5fed682013-12-03 09:06:43 -0800234static const int kFastTrackMultiplier = 2;
Eric Laurent81784c32012-11-19 14:55:58 -0800235
Glenn Kasten03490092014-05-27 12:30:54 -0700236// The minimum and maximum allowed values
237static const int kFastTrackMultiplierMin = 1;
238static const int kFastTrackMultiplierMax = 2;
239
240// The actual value to use, which can be specified per-device via property af.fast_track_multiplier.
241static int sFastTrackMultiplier = kFastTrackMultiplier;
242
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700243// See Thread::readOnlyHeap().
244// Initially this heap is used to allocate client buffers for "fast" AudioRecord.
245// Eventually it will be the single buffer that FastCapture writes into via HAL read(),
246// and that all "fast" AudioRecord clients read from. In either case, the size can be small.
Mikhail Naganov79a77822018-05-10 15:57:25 -0700247static const size_t kRecordThreadReadOnlyHeapSize = 0xD000;
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700248
Andy Hung25a80ac2023-07-19 12:47:35 -0700249static const nsecs_t kDefaultStandbyTimeInNsecs = seconds(3);
Andy Hung8fe87eb2023-07-20 21:31:38 -0700250
251static nsecs_t getStandbyTimeInNanos() {
252 static nsecs_t standbyTimeInNanos = []() {
253 const int ms = property_get_int32("ro.audio.flinger_standbytime_ms",
254 kDefaultStandbyTimeInNsecs / NANOS_PER_MILLISECOND);
255 ALOGI("%s: Using %d ms as standby time", __func__, ms);
256 return milliseconds(ms);
257 }();
258 return standbyTimeInNanos;
259}
260
Andy Hung81994d62023-07-20 21:44:14 -0700261// Set kEnableExtendedChannels to true to enable greater than stereo output
262// for the MixerThread and device sink. Number of channels allowed is
263// FCC_2 <= channels <= FCC_LIMIT.
264constexpr bool kEnableExtendedChannels = true;
265
266// Returns true if channel mask is permitted for the PCM sink in the MixerThread
267/* static */
268bool IAfThreadBase::isValidPcmSinkChannelMask(audio_channel_mask_t channelMask) {
269 switch (audio_channel_mask_get_representation(channelMask)) {
270 case AUDIO_CHANNEL_REPRESENTATION_POSITION: {
271 // Haptic channel mask is only applicable for channel position mask.
272 const uint32_t channelCount = audio_channel_count_from_out_mask(
273 static_cast<audio_channel_mask_t>(channelMask & ~AUDIO_CHANNEL_HAPTIC_ALL));
274 const uint32_t maxChannelCount = kEnableExtendedChannels
275 ? FCC_LIMIT : FCC_2;
276 if (channelCount < FCC_2 // mono is not supported at this time
277 || channelCount > maxChannelCount) {
278 return false;
279 }
280 // check that channelMask is the "canonical" one we expect for the channelCount.
281 return audio_channel_position_mask_is_out_canonical(channelMask);
282 }
283 case AUDIO_CHANNEL_REPRESENTATION_INDEX:
284 if (kEnableExtendedChannels) {
285 const uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
286 if (channelCount >= FCC_2 // mono is not supported at this time
287 && channelCount <= FCC_LIMIT) {
288 return true;
289 }
290 }
291 return false;
292 default:
293 return false;
294 }
295}
296
297// Set kEnableExtendedPrecision to true to use extended precision in MixerThread
298constexpr bool kEnableExtendedPrecision = true;
299
300// Returns true if format is permitted for the PCM sink in the MixerThread
301/* static */
302bool IAfThreadBase::isValidPcmSinkFormat(audio_format_t format) {
303 switch (format) {
304 case AUDIO_FORMAT_PCM_16_BIT:
305 return true;
306 case AUDIO_FORMAT_PCM_FLOAT:
307 case AUDIO_FORMAT_PCM_24_BIT_PACKED:
308 case AUDIO_FORMAT_PCM_32_BIT:
309 case AUDIO_FORMAT_PCM_8_24_BIT:
310 return kEnableExtendedPrecision;
311 default:
312 return false;
313 }
314}
315
Eric Laurent81784c32012-11-19 14:55:58 -0800316// ----------------------------------------------------------------------------
317
Andy Hung25a80ac2023-07-19 12:47:35 -0700318// formatToString() needs to be exact for MediaMetrics purposes.
319// Do not use media/TypeConverter.h toString().
320/* static */
321std::string IAfThreadBase::formatToString(audio_format_t format) {
322 std::string result;
323 FormatConverter::toString(format, result);
324 return result;
325}
326
Andy Hungb68f5eb2019-12-03 16:49:17 -0800327// TODO: move all toString helpers to audio.h
328// under #ifdef __cplusplus #endif
329static std::string patchSinksToString(const struct audio_patch *patch)
330{
331 std::stringstream ss;
332 for (size_t i = 0; i < patch->num_sinks; ++i) {
Andy Hungc2b11cb2020-04-22 09:04:01 -0700333 if (i > 0) {
334 ss << "|";
335 }
Andy Hungb68f5eb2019-12-03 16:49:17 -0800336 ss << "(" << toString(patch->sinks[i].ext.device.type)
337 << ", " << patch->sinks[i].ext.device.address << ")";
338 }
339 return ss.str();
340}
341
342static std::string patchSourcesToString(const struct audio_patch *patch)
343{
344 std::stringstream ss;
345 for (size_t i = 0; i < patch->num_sources; ++i) {
Andy Hungc2b11cb2020-04-22 09:04:01 -0700346 if (i > 0) {
347 ss << "|";
348 }
Andy Hungb68f5eb2019-12-03 16:49:17 -0800349 ss << "(" << toString(patch->sources[i].ext.device.type)
350 << ", " << patch->sources[i].ext.device.address << ")";
351 }
352 return ss.str();
353}
354
Andy Hung4bd53e72022-11-17 17:21:45 -0800355static std::string toString(audio_latency_mode_t mode) {
356 // We convert to the AIDL type to print (eventually the legacy type will be removed).
Mikhail Naganovf53e1822022-12-18 02:48:14 +0000357 const auto result = legacy2aidl_audio_latency_mode_t_AudioLatencyMode(mode);
358 return result.has_value() ? media::audio::common::toString(*result) : "UNKNOWN";
Andy Hung4bd53e72022-11-17 17:21:45 -0800359}
360
361// Could be made a template, but other toString overloads for std::vector are confused.
362static std::string toString(const std::vector<audio_latency_mode_t>& elements) {
363 std::string s("{ ");
364 for (const auto& e : elements) {
365 s.append(toString(e));
366 s.append(" ");
367 }
368 s.append("}");
369 return s;
370}
371
Glenn Kasten03490092014-05-27 12:30:54 -0700372static pthread_once_t sFastTrackMultiplierOnce = PTHREAD_ONCE_INIT;
373
374static void sFastTrackMultiplierInit()
375{
376 char value[PROPERTY_VALUE_MAX];
377 if (property_get("af.fast_track_multiplier", value, NULL) > 0) {
378 char *endptr;
379 unsigned long ul = strtoul(value, &endptr, 0);
380 if (*endptr == '\0' && kFastTrackMultiplierMin <= ul && ul <= kFastTrackMultiplierMax) {
381 sFastTrackMultiplier = (int) ul;
382 }
383 }
384}
385
386// ----------------------------------------------------------------------------
387
Eric Laurent81784c32012-11-19 14:55:58 -0800388#ifdef ADD_BATTERY_DATA
389// To collect the amplifier usage
390static void addBatteryData(uint32_t params) {
391 sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService();
392 if (service == NULL) {
393 // it already logged
394 return;
395 }
396
397 service->addBatteryData(params);
398}
399#endif
400
Andy Hung3f0c9022016-01-15 17:49:46 -0800401// Track the CLOCK_BOOTTIME versus CLOCK_MONOTONIC timebase offset
402struct {
403 // call when you acquire a partial wakelock
404 void acquire(const sp<IBinder> &wakeLockToken) {
405 pthread_mutex_lock(&mLock);
406 if (wakeLockToken.get() == nullptr) {
407 adjustTimebaseOffset(&mBoottimeOffset, ExtendedTimestamp::TIMEBASE_BOOTTIME);
408 } else {
409 if (mCount == 0) {
410 adjustTimebaseOffset(&mBoottimeOffset, ExtendedTimestamp::TIMEBASE_BOOTTIME);
411 }
412 ++mCount;
413 }
414 pthread_mutex_unlock(&mLock);
415 }
416
417 // call when you release a partial wakelock.
418 void release(const sp<IBinder> &wakeLockToken) {
419 if (wakeLockToken.get() == nullptr) {
420 return;
421 }
422 pthread_mutex_lock(&mLock);
423 if (--mCount < 0) {
424 ALOGE("negative wakelock count");
425 mCount = 0;
426 }
427 pthread_mutex_unlock(&mLock);
428 }
429
430 // retrieves the boottime timebase offset from monotonic.
431 int64_t getBoottimeOffset() {
432 pthread_mutex_lock(&mLock);
433 int64_t boottimeOffset = mBoottimeOffset;
434 pthread_mutex_unlock(&mLock);
435 return boottimeOffset;
436 }
437
438 // Adjusts the timebase offset between TIMEBASE_MONOTONIC
439 // and the selected timebase.
440 // Currently only TIMEBASE_BOOTTIME is allowed.
441 //
442 // This only needs to be called upon acquiring the first partial wakelock
443 // after all other partial wakelocks are released.
444 //
445 // We do an empirical measurement of the offset rather than parsing
446 // /proc/timer_list since the latter is not a formal kernel ABI.
447 static void adjustTimebaseOffset(int64_t *offset, ExtendedTimestamp::Timebase timebase) {
448 int clockbase;
449 switch (timebase) {
450 case ExtendedTimestamp::TIMEBASE_BOOTTIME:
451 clockbase = SYSTEM_TIME_BOOTTIME;
452 break;
453 default:
454 LOG_ALWAYS_FATAL("invalid timebase %d", timebase);
455 break;
456 }
457 // try three times to get the clock offset, choose the one
458 // with the minimum gap in measurements.
459 const int tries = 3;
Andy Hung920f6572022-10-06 12:09:49 -0700460 nsecs_t bestGap = 0, measured = 0; // not required, initialized for clang-tidy
Andy Hung3f0c9022016-01-15 17:49:46 -0800461 for (int i = 0; i < tries; ++i) {
462 const nsecs_t tmono = systemTime(SYSTEM_TIME_MONOTONIC);
463 const nsecs_t tbase = systemTime(clockbase);
464 const nsecs_t tmono2 = systemTime(SYSTEM_TIME_MONOTONIC);
465 const nsecs_t gap = tmono2 - tmono;
466 if (i == 0 || gap < bestGap) {
467 bestGap = gap;
468 measured = tbase - ((tmono + tmono2) >> 1);
469 }
470 }
471
472 // to avoid micro-adjusting, we don't change the timebase
473 // unless it is significantly different.
474 //
475 // Assumption: It probably takes more than toleranceNs to
476 // suspend and resume the device.
477 static int64_t toleranceNs = 10000; // 10 us
478 if (llabs(*offset - measured) > toleranceNs) {
479 ALOGV("Adjusting timebase offset old: %lld new: %lld",
480 (long long)*offset, (long long)measured);
481 *offset = measured;
482 }
483 }
484
485 pthread_mutex_t mLock;
486 int32_t mCount;
487 int64_t mBoottimeOffset;
488} gBoottime = { PTHREAD_MUTEX_INITIALIZER, 0, 0 }; // static, so use POD initialization
Eric Laurent81784c32012-11-19 14:55:58 -0800489
490// ----------------------------------------------------------------------------
491// CPU Stats
492// ----------------------------------------------------------------------------
493
494class CpuStats {
495public:
496 CpuStats();
497 void sample(const String8 &title);
498#ifdef DEBUG_CPU_USAGE
499private:
500 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns
Andy Hung16698b82018-08-01 10:48:38 -0700501 audio_utils::Statistics<double> mWcStats; // statistics on thread CPU usage in wall clock ns
Eric Laurent81784c32012-11-19 14:55:58 -0800502
Andy Hung16698b82018-08-01 10:48:38 -0700503 audio_utils::Statistics<double> mHzStats; // statistics on thread CPU usage in cycles
Eric Laurent81784c32012-11-19 14:55:58 -0800504
505 int mCpuNum; // thread's current CPU number
506 int mCpukHz; // frequency of thread's current CPU in kHz
507#endif
508};
509
510CpuStats::CpuStats()
511#ifdef DEBUG_CPU_USAGE
512 : mCpuNum(-1), mCpukHz(-1)
513#endif
514{
515}
516
Glenn Kasten0f11b512014-01-31 16:18:54 -0800517void CpuStats::sample(const String8 &title
518#ifndef DEBUG_CPU_USAGE
519 __unused
520#endif
521 ) {
Eric Laurent81784c32012-11-19 14:55:58 -0800522#ifdef DEBUG_CPU_USAGE
523 // get current thread's delta CPU time in wall clock ns
524 double wcNs;
525 bool valid = mCpuUsage.sampleAndEnable(wcNs);
526
527 // record sample for wall clock statistics
528 if (valid) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700529 mWcStats.add(wcNs);
Eric Laurent81784c32012-11-19 14:55:58 -0800530 }
531
532 // get the current CPU number
533 int cpuNum = sched_getcpu();
534
535 // get the current CPU frequency in kHz
536 int cpukHz = mCpuUsage.getCpukHz(cpuNum);
537
538 // check if either CPU number or frequency changed
539 if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
540 mCpuNum = cpuNum;
541 mCpukHz = cpukHz;
542 // ignore sample for purposes of cycles
543 valid = false;
544 }
545
546 // if no change in CPU number or frequency, then record sample for cycle statistics
547 if (valid && mCpukHz > 0) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700548 const double cycles = wcNs * cpukHz * 0.000001;
549 mHzStats.add(cycles);
Eric Laurent81784c32012-11-19 14:55:58 -0800550 }
551
Eric Tan5b13ff82018-07-27 11:20:17 -0700552 const unsigned n = mWcStats.getN();
Eric Laurent81784c32012-11-19 14:55:58 -0800553 // mCpuUsage.elapsed() is expensive, so don't call it every loop
554 if ((n & 127) == 1) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700555 const long long elapsed = mCpuUsage.elapsed();
Eric Laurent81784c32012-11-19 14:55:58 -0800556 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700557 const double perLoop = elapsed / (double) n;
558 const double perLoop100 = perLoop * 0.01;
559 const double perLoop1k = perLoop * 0.001;
560 const double mean = mWcStats.getMean();
561 const double stddev = mWcStats.getStdDev();
562 const double minimum = mWcStats.getMin();
563 const double maximum = mWcStats.getMax();
564 const double meanCycles = mHzStats.getMean();
565 const double stddevCycles = mHzStats.getStdDev();
566 const double minCycles = mHzStats.getMin();
567 const double maxCycles = mHzStats.getMax();
Eric Laurent81784c32012-11-19 14:55:58 -0800568 mCpuUsage.resetElapsed();
569 mWcStats.reset();
570 mHzStats.reset();
571 ALOGD("CPU usage for %s over past %.1f secs\n"
572 " (%u mixer loops at %.1f mean ms per loop):\n"
573 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
574 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
575 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +0000576 title.c_str(),
Eric Laurent81784c32012-11-19 14:55:58 -0800577 elapsed * .000000001, n, perLoop * .000001,
578 mean * .001,
579 stddev * .001,
580 minimum * .001,
581 maximum * .001,
582 mean / perLoop100,
583 stddev / perLoop100,
584 minimum / perLoop100,
585 maximum / perLoop100,
586 meanCycles / perLoop1k,
587 stddevCycles / perLoop1k,
588 minCycles / perLoop1k,
589 maxCycles / perLoop1k);
590
591 }
592 }
593#endif
594};
595
596// ----------------------------------------------------------------------------
597// ThreadBase
598// ----------------------------------------------------------------------------
599
Glenn Kasten97b7b752014-09-28 13:04:24 -0700600// static
Andy Hungee58e4a2023-07-07 13:47:37 -0700601const char* ThreadBase::threadTypeToString(ThreadBase::type_t type)
Glenn Kasten97b7b752014-09-28 13:04:24 -0700602{
603 switch (type) {
604 case MIXER:
605 return "MIXER";
606 case DIRECT:
607 return "DIRECT";
608 case DUPLICATING:
609 return "DUPLICATING";
610 case RECORD:
611 return "RECORD";
612 case OFFLOAD:
613 return "OFFLOAD";
Andy Hungea840382020-05-05 21:50:17 -0700614 case MMAP_PLAYBACK:
615 return "MMAP_PLAYBACK";
616 case MMAP_CAPTURE:
617 return "MMAP_CAPTURE";
Eric Laurent1c5e2e32021-08-18 18:50:28 +0200618 case SPATIALIZER:
619 return "SPATIALIZER";
jiabinc658e452022-10-21 20:52:21 +0000620 case BIT_PERFECT:
621 return "BIT_PERFECT";
Glenn Kasten97b7b752014-09-28 13:04:24 -0700622 default:
623 return "unknown";
624 }
625}
626
Andy Hung583043b2023-07-17 17:05:00 -0700627ThreadBase::ThreadBase(const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
Andy Hungcf10d742020-04-28 15:38:24 -0700628 type_t type, bool systemReady, bool isOut)
Eric Laurent81784c32012-11-19 14:55:58 -0800629 : Thread(false /*canCallJava*/),
630 mType(type),
Andy Hung583043b2023-07-17 17:05:00 -0700631 mAfThreadCallback(afThreadCallback),
Andy Hungcf10d742020-04-28 15:38:24 -0700632 mThreadMetrics(std::string(AMEDIAMETRICS_KEY_PREFIX_AUDIO_THREAD) + std::to_string(id),
633 isOut),
634 mIsOut(isOut),
Glenn Kasten70949c42013-08-06 07:40:12 -0700635 // mSampleRate, mFrameCount, mChannelMask, mChannelCount, mFrameSize, mFormat, mBufferSize
Glenn Kastendeca2ae2014-02-07 10:25:56 -0800636 // are set by PlaybackThread::readOutputParameters_l() or
637 // RecordThread::readInputParameters_l()
Eric Laurentfd477972013-10-25 18:10:40 -0700638 //FIXME: mStandby should be true here. Is this some kind of hack?
jiabinc52b1ff2019-10-31 17:20:42 -0700639 mStandby(false),
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700640 mAudioSource(AUDIO_SOURCE_DEFAULT), mId(id),
Eric Laurent81784c32012-11-19 14:55:58 -0800641 // mName will be set by concrete (non-virtual) subclass
Eric Laurent72e3f392015-05-20 14:43:50 -0700642 mDeathRecipient(new PMDeathRecipient(this)),
Eric Laurent6acd1d42017-01-04 14:23:29 -0800643 mSystemReady(systemReady),
644 mSignalPending(false)
Eric Laurent81784c32012-11-19 14:55:58 -0800645{
Andy Hungcf10d742020-04-28 15:38:24 -0700646 mThreadMetrics.logConstructor(getpid(), threadTypeToString(type), id);
Eric Laurent296fb132015-05-01 11:38:42 -0700647 memset(&mPatch, 0, sizeof(struct audio_patch));
Eric Laurent81784c32012-11-19 14:55:58 -0800648}
649
Andy Hungee58e4a2023-07-07 13:47:37 -0700650ThreadBase::~ThreadBase()
Eric Laurent81784c32012-11-19 14:55:58 -0800651{
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700652 // mConfigEvents should be empty, but just in case it isn't, free the memory it owns
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700653 mConfigEvents.clear();
654
Eric Laurent81784c32012-11-19 14:55:58 -0800655 // do not lock the mutex in destructor
656 releaseWakeLock_l();
657 if (mPowerManager != 0) {
Marco Nelissen06b46062014-11-14 07:58:25 -0800658 sp<IBinder> binder = IInterface::asBinder(mPowerManager);
Eric Laurent81784c32012-11-19 14:55:58 -0800659 binder->unlinkToDeath(mDeathRecipient);
660 }
Andy Hungd0979812019-02-21 15:51:44 -0800661
662 sendStatistics(true /* force */);
Eric Laurent81784c32012-11-19 14:55:58 -0800663}
664
Andy Hungee58e4a2023-07-07 13:47:37 -0700665status_t ThreadBase::readyToRun()
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700666{
667 status_t status = initCheck();
668 if (status == NO_ERROR) {
Glenn Kasten1bfe09a2017-02-21 13:05:56 -0800669 ALOGI("AudioFlinger's thread %p tid=%d ready to run", this, getTid());
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700670 } else {
671 ALOGE("No working audio driver found.");
672 }
673 return status;
674}
675
Andy Hungee58e4a2023-07-07 13:47:37 -0700676void ThreadBase::exit()
Eric Laurent81784c32012-11-19 14:55:58 -0800677{
678 ALOGV("ThreadBase::exit");
679 // do any cleanup required for exit to succeed
680 preExit();
681 {
682 // This lock prevents the following race in thread (uniprocessor for illustration):
683 // if (!exitPending()) {
684 // // context switch from here to exit()
685 // // exit() calls requestExit(), what exitPending() observes
686 // // exit() calls signal(), which is dropped since no waiters
687 // // context switch back from exit() to here
688 // mWaitWorkCV.wait(...);
689 // // now thread is hung
690 // }
Andy Hungc5007f82023-08-29 14:26:09 -0700691 audio_utils::lock_guard lock(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -0800692 requestExit();
Andy Hungc5007f82023-08-29 14:26:09 -0700693 mWaitWorkCV.notify_all();
Eric Laurent81784c32012-11-19 14:55:58 -0800694 }
695 // When Thread::requestExitAndWait is made virtual and this method is renamed to
696 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
697 requestExitAndWait();
698}
699
Andy Hungee58e4a2023-07-07 13:47:37 -0700700status_t ThreadBase::setParameters(const String8& keyValuePairs)
Eric Laurent81784c32012-11-19 14:55:58 -0800701{
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +0000702 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.c_str());
Andy Hung972bec12023-08-31 16:13:39 -0700703 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -0800704
Eric Laurent10351942014-05-08 18:49:52 -0700705 return sendSetParameterConfigEvent_l(keyValuePairs);
706}
707
708// sendConfigEvent_l() must be called with ThreadBase::mLock held
709// Can temporarily release the lock if waiting for a reply from processConfigEvents_l().
Andy Hungee58e4a2023-07-07 13:47:37 -0700710status_t ThreadBase::sendConfigEvent_l(sp<ConfigEvent>& event)
Andy Hung920f6572022-10-06 12:09:49 -0700711NO_THREAD_SAFETY_ANALYSIS // condition variable
Eric Laurent10351942014-05-08 18:49:52 -0700712{
713 status_t status = NO_ERROR;
714
Eric Laurent72e3f392015-05-20 14:43:50 -0700715 if (event->mRequiresSystemReady && !mSystemReady) {
716 event->mWaitStatus = false;
717 mPendingConfigEvents.add(event);
718 return status;
719 }
Eric Laurent10351942014-05-08 18:49:52 -0700720 mConfigEvents.add(event);
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700721 ALOGV("sendConfigEvent_l() num events %zu event %d", mConfigEvents.size(), event->mType);
Andy Hungc5007f82023-08-29 14:26:09 -0700722 mWaitWorkCV.notify_one();
723 mutex().unlock();
Eric Laurent10351942014-05-08 18:49:52 -0700724 {
Andy Hungc5007f82023-08-29 14:26:09 -0700725 audio_utils::unique_lock _l(event->mutex());
Eric Laurent10351942014-05-08 18:49:52 -0700726 while (event->mWaitStatus) {
Andy Hung02ea2a02024-01-25 17:02:30 -0800727 if (event->mCondition.wait_for(
728 _l, std::chrono::nanoseconds(kConfigEventTimeoutNs), getTid())
729 == std::cv_status::timeout) {
Eric Laurent10351942014-05-08 18:49:52 -0700730 event->mStatus = TIMED_OUT;
731 event->mWaitStatus = false;
732 }
733 }
734 status = event->mStatus;
Eric Laurent81784c32012-11-19 14:55:58 -0800735 }
Andy Hungc5007f82023-08-29 14:26:09 -0700736 mutex().lock();
Eric Laurent81784c32012-11-19 14:55:58 -0800737 return status;
738}
739
Andy Hungee58e4a2023-07-07 13:47:37 -0700740void ThreadBase::sendIoConfigEvent(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -0700741 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -0800742{
Andy Hung972bec12023-08-31 16:13:39 -0700743 audio_utils::lock_guard _l(mutex());
Eric Laurent09f1ed22019-04-24 17:45:17 -0700744 sendIoConfigEvent_l(event, pid, portId);
Eric Laurent81784c32012-11-19 14:55:58 -0800745}
746
Andy Hungc5007f82023-08-29 14:26:09 -0700747// sendIoConfigEvent_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -0700748void ThreadBase::sendIoConfigEvent_l(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -0700749 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -0800750{
Andy Hungd0979812019-02-21 15:51:44 -0800751 // The audio statistics history is exponentially weighted to forget events
752 // about five or more seconds in the past. In order to have
753 // crisper statistics for mediametrics, we reset the statistics on
754 // an IoConfigEvent, to reflect different properties for a new device.
755 mIoJitterMs.reset();
756 mLatencyMs.reset();
757 mProcessTimeMs.reset();
Robert Wu06db0a32021-08-10 19:05:34 +0000758 mMonopipePipeDepthStats.reset();
Dean Wheatley12473e92021-03-18 23:00:55 +1100759 mTimestampVerifier.discontinuity(mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS);
Andy Hungd0979812019-02-21 15:51:44 -0800760
Eric Laurent09f1ed22019-04-24 17:45:17 -0700761 sp<ConfigEvent> configEvent = (ConfigEvent *)new IoConfigEvent(event, pid, portId);
Eric Laurent10351942014-05-08 18:49:52 -0700762 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800763}
764
Andy Hungee58e4a2023-07-07 13:47:37 -0700765void ThreadBase::sendPrioConfigEvent(pid_t pid, pid_t tid, int32_t prio, bool forApp)
Eric Laurent72e3f392015-05-20 14:43:50 -0700766{
Andy Hung972bec12023-08-31 16:13:39 -0700767 audio_utils::lock_guard _l(mutex());
Mikhail Naganov83f04272017-02-07 10:45:09 -0800768 sendPrioConfigEvent_l(pid, tid, prio, forApp);
Eric Laurent72e3f392015-05-20 14:43:50 -0700769}
770
Andy Hungc5007f82023-08-29 14:26:09 -0700771// sendPrioConfigEvent_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -0700772void ThreadBase::sendPrioConfigEvent_l(
Mikhail Naganov83f04272017-02-07 10:45:09 -0800773 pid_t pid, pid_t tid, int32_t prio, bool forApp)
Eric Laurent81784c32012-11-19 14:55:58 -0800774{
Mikhail Naganov83f04272017-02-07 10:45:09 -0800775 sp<ConfigEvent> configEvent = (ConfigEvent *)new PrioConfigEvent(pid, tid, prio, forApp);
Eric Laurent10351942014-05-08 18:49:52 -0700776 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800777}
778
Andy Hungc5007f82023-08-29 14:26:09 -0700779// sendSetParameterConfigEvent_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -0700780status_t ThreadBase::sendSetParameterConfigEvent_l(const String8& keyValuePair)
Eric Laurent81784c32012-11-19 14:55:58 -0800781{
Andy Hung2ddee192015-12-18 17:34:44 -0800782 sp<ConfigEvent> configEvent;
783 AudioParameter param(keyValuePair);
784 int value;
Mikhail Naganov00260b52016-10-13 12:54:24 -0700785 if (param.getInt(String8(AudioParameter::keyMonoOutput), value) == NO_ERROR) {
Andy Hung2ddee192015-12-18 17:34:44 -0800786 setMasterMono_l(value != 0);
787 if (param.size() == 1) {
788 return NO_ERROR; // should be a solo parameter - we don't pass down
789 }
Mikhail Naganov00260b52016-10-13 12:54:24 -0700790 param.remove(String8(AudioParameter::keyMonoOutput));
Andy Hung2ddee192015-12-18 17:34:44 -0800791 configEvent = new SetParameterConfigEvent(param.toString());
792 } else {
793 configEvent = new SetParameterConfigEvent(keyValuePair);
794 }
Eric Laurent10351942014-05-08 18:49:52 -0700795 return sendConfigEvent_l(configEvent);
Glenn Kastenf7773312013-08-13 16:00:42 -0700796}
797
Andy Hungee58e4a2023-07-07 13:47:37 -0700798status_t ThreadBase::sendCreateAudioPatchConfigEvent(
Eric Laurent1c333e22014-05-20 10:48:17 -0700799 const struct audio_patch *patch,
800 audio_patch_handle_t *handle)
801{
Andy Hung972bec12023-08-31 16:13:39 -0700802 audio_utils::lock_guard _l(mutex());
Eric Laurent1c333e22014-05-20 10:48:17 -0700803 sp<ConfigEvent> configEvent = (ConfigEvent *)new CreateAudioPatchConfigEvent(*patch, *handle);
804 status_t status = sendConfigEvent_l(configEvent);
805 if (status == NO_ERROR) {
806 CreateAudioPatchConfigEventData *data =
807 (CreateAudioPatchConfigEventData *)configEvent->mData.get();
808 *handle = data->mHandle;
809 }
810 return status;
811}
812
Andy Hungee58e4a2023-07-07 13:47:37 -0700813status_t ThreadBase::sendReleaseAudioPatchConfigEvent(
Eric Laurent1c333e22014-05-20 10:48:17 -0700814 const audio_patch_handle_t handle)
815{
Andy Hung972bec12023-08-31 16:13:39 -0700816 audio_utils::lock_guard _l(mutex());
Eric Laurent1c333e22014-05-20 10:48:17 -0700817 sp<ConfigEvent> configEvent = (ConfigEvent *)new ReleaseAudioPatchConfigEvent(handle);
818 return sendConfigEvent_l(configEvent);
819}
820
Andy Hungee58e4a2023-07-07 13:47:37 -0700821status_t ThreadBase::sendUpdateOutDeviceConfigEvent(
jiabinc52b1ff2019-10-31 17:20:42 -0700822 const DeviceDescriptorBaseVector& outDevices)
823{
824 if (type() != RECORD) {
825 // The update out device operation is only for record thread.
826 return INVALID_OPERATION;
827 }
Andy Hung972bec12023-08-31 16:13:39 -0700828 audio_utils::lock_guard _l(mutex());
jiabinc52b1ff2019-10-31 17:20:42 -0700829 sp<ConfigEvent> configEvent = (ConfigEvent *)new UpdateOutDevicesConfigEvent(outDevices);
830 return sendConfigEvent_l(configEvent);
831}
832
Andy Hungee58e4a2023-07-07 13:47:37 -0700833void ThreadBase::sendResizeBufferConfigEvent_l(int32_t maxSharedAudioHistoryMs)
Eric Laurentec376dc2021-04-08 20:41:22 +0200834{
835 ALOG_ASSERT(type() == RECORD, "sendResizeBufferConfigEvent_l() called on non record thread");
836 sp<ConfigEvent> configEvent =
837 (ConfigEvent *)new ResizeBufferConfigEvent(maxSharedAudioHistoryMs);
838 sendConfigEvent_l(configEvent);
839}
Eric Laurent1c333e22014-05-20 10:48:17 -0700840
Andy Hungee58e4a2023-07-07 13:47:37 -0700841void ThreadBase::sendCheckOutputStageEffectsEvent()
Eric Laurentb3f315a2021-07-13 15:09:05 +0200842{
Andy Hung972bec12023-08-31 16:13:39 -0700843 audio_utils::lock_guard _l(mutex());
Eric Laurentb3f315a2021-07-13 15:09:05 +0200844 sendCheckOutputStageEffectsEvent_l();
845}
846
Andy Hungee58e4a2023-07-07 13:47:37 -0700847void ThreadBase::sendCheckOutputStageEffectsEvent_l()
Eric Laurentb3f315a2021-07-13 15:09:05 +0200848{
849 sp<ConfigEvent> configEvent =
850 (ConfigEvent *)new CheckOutputStageEffectsEvent();
851 sendConfigEvent_l(configEvent);
852}
853
Andy Hungee58e4a2023-07-07 13:47:37 -0700854void ThreadBase::sendHalLatencyModesChangedEvent_l()
Eric Laurent68a40a82022-05-03 18:15:04 +0200855{
856 sp<ConfigEvent> configEvent = sp<HalLatencyModesChangedEvent>::make();
857 sendConfigEvent_l(configEvent);
858}
859
Glenn Kasten2cfbf882013-08-14 13:12:11 -0700860// post condition: mConfigEvents.isEmpty()
Andy Hungee58e4a2023-07-07 13:47:37 -0700861void ThreadBase::processConfigEvents_l()
Glenn Kastenf7773312013-08-13 16:00:42 -0700862{
Eric Laurent10351942014-05-08 18:49:52 -0700863 bool configChanged = false;
864
Eric Laurent81784c32012-11-19 14:55:58 -0800865 while (!mConfigEvents.isEmpty()) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700866 ALOGV("processConfigEvents_l() remaining events %zu", mConfigEvents.size());
Eric Laurent10351942014-05-08 18:49:52 -0700867 sp<ConfigEvent> event = mConfigEvents[0];
Eric Laurent81784c32012-11-19 14:55:58 -0800868 mConfigEvents.removeAt(0);
Eric Laurent10351942014-05-08 18:49:52 -0700869 switch (event->mType) {
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700870 case CFG_EVENT_PRIO: {
Eric Laurent10351942014-05-08 18:49:52 -0700871 PrioConfigEventData *data = (PrioConfigEventData *)event->mData.get();
872 // FIXME Need to understand why this has to be done asynchronously
Mikhail Naganov83f04272017-02-07 10:45:09 -0800873 int err = requestPriority(data->mPid, data->mTid, data->mPrio, data->mForApp,
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700874 true /*asynchronous*/);
875 if (err != 0) {
876 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Eric Laurent10351942014-05-08 18:49:52 -0700877 data->mPrio, data->mPid, data->mTid, err);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700878 }
879 } break;
880 case CFG_EVENT_IO: {
Eric Laurent10351942014-05-08 18:49:52 -0700881 IoConfigEventData *data = (IoConfigEventData *)event->mData.get();
Andy Hungab65b182023-09-06 19:41:47 -0700882 ioConfigChanged_l(data->mEvent, data->mPid, data->mPortId);
Eric Laurent10351942014-05-08 18:49:52 -0700883 } break;
884 case CFG_EVENT_SET_PARAMETER: {
885 SetParameterConfigEventData *data = (SetParameterConfigEventData *)event->mData.get();
886 if (checkForNewParameter_l(data->mKeyValuePairs, event->mStatus)) {
887 configChanged = true;
Andy Hung293558a2017-03-21 12:19:20 -0700888 mLocalLog.log("CFG_EVENT_SET_PARAMETER: (%s) configuration changed",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +0000889 data->mKeyValuePairs.c_str());
Glenn Kastend5418eb2013-08-14 13:11:06 -0700890 }
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700891 } break;
Eric Laurent1c333e22014-05-20 10:48:17 -0700892 case CFG_EVENT_CREATE_AUDIO_PATCH: {
Andy Hungab65b182023-09-06 19:41:47 -0700893 const DeviceTypeSet oldDevices = getDeviceTypes_l();
Eric Laurent1c333e22014-05-20 10:48:17 -0700894 CreateAudioPatchConfigEventData *data =
895 (CreateAudioPatchConfigEventData *)event->mData.get();
896 event->mStatus = createAudioPatch_l(&data->mPatch, &data->mHandle);
Andy Hungab65b182023-09-06 19:41:47 -0700897 const DeviceTypeSet newDevices = getDeviceTypes_l();
Eric Laurent52568142022-10-28 11:23:28 +0200898 configChanged = oldDevices != newDevices;
jiabinc52b1ff2019-10-31 17:20:42 -0700899 mLocalLog.log("CFG_EVENT_CREATE_AUDIO_PATCH: old device %s (%s) new device %s (%s)",
900 dumpDeviceTypes(oldDevices).c_str(), toString(oldDevices).c_str(),
901 dumpDeviceTypes(newDevices).c_str(), toString(newDevices).c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -0700902 } break;
903 case CFG_EVENT_RELEASE_AUDIO_PATCH: {
Andy Hungab65b182023-09-06 19:41:47 -0700904 const DeviceTypeSet oldDevices = getDeviceTypes_l();
Eric Laurent1c333e22014-05-20 10:48:17 -0700905 ReleaseAudioPatchConfigEventData *data =
906 (ReleaseAudioPatchConfigEventData *)event->mData.get();
907 event->mStatus = releaseAudioPatch_l(data->mHandle);
Andy Hungab65b182023-09-06 19:41:47 -0700908 const DeviceTypeSet newDevices = getDeviceTypes_l();
Eric Laurent52568142022-10-28 11:23:28 +0200909 configChanged = oldDevices != newDevices;
jiabinc52b1ff2019-10-31 17:20:42 -0700910 mLocalLog.log("CFG_EVENT_RELEASE_AUDIO_PATCH: old device %s (%s) new device %s (%s)",
911 dumpDeviceTypes(oldDevices).c_str(), toString(oldDevices).c_str(),
912 dumpDeviceTypes(newDevices).c_str(), toString(newDevices).c_str());
913 } break;
914 case CFG_EVENT_UPDATE_OUT_DEVICE: {
915 UpdateOutDevicesConfigEventData *data =
916 (UpdateOutDevicesConfigEventData *)event->mData.get();
917 updateOutDevices(data->mOutDevices);
Eric Laurent1c333e22014-05-20 10:48:17 -0700918 } break;
Eric Laurentec376dc2021-04-08 20:41:22 +0200919 case CFG_EVENT_RESIZE_BUFFER: {
920 ResizeBufferConfigEventData *data =
921 (ResizeBufferConfigEventData *)event->mData.get();
922 resizeInputBuffer_l(data->mMaxSharedAudioHistoryMs);
923 } break;
Eric Laurentb3f315a2021-07-13 15:09:05 +0200924
925 case CFG_EVENT_CHECK_OUTPUT_STAGE_EFFECTS: {
926 setCheckOutputStageEffects();
927 } break;
928
Eric Laurent68a40a82022-05-03 18:15:04 +0200929 case CFG_EVENT_HAL_LATENCY_MODES_CHANGED: {
930 onHalLatencyModesChanged_l();
931 } break;
932
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700933 default:
Eric Laurent10351942014-05-08 18:49:52 -0700934 ALOG_ASSERT(false, "processConfigEvents_l() unknown event type %d", event->mType);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700935 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800936 }
Eric Laurent10351942014-05-08 18:49:52 -0700937 {
Andy Hung972bec12023-08-31 16:13:39 -0700938 audio_utils::lock_guard _l(event->mutex());
Eric Laurent10351942014-05-08 18:49:52 -0700939 if (event->mWaitStatus) {
940 event->mWaitStatus = false;
Andy Hungc5007f82023-08-29 14:26:09 -0700941 event->mCondition.notify_one();
Eric Laurent10351942014-05-08 18:49:52 -0700942 }
943 }
944 ALOGV_IF(mConfigEvents.isEmpty(), "processConfigEvents_l() DONE thread %p", this);
945 }
946
947 if (configChanged) {
948 cacheParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800949 }
Eric Laurent81784c32012-11-19 14:55:58 -0800950}
951
Marco Nelissenb2208842014-02-07 14:00:50 -0800952String8 channelMaskToString(audio_channel_mask_t mask, bool output) {
953 String8 s;
Glenn Kastene1635ec2015-06-08 15:46:49 -0700954 const audio_channel_representation_t representation =
955 audio_channel_mask_get_representation(mask);
Andy Hungf98ec8d2015-05-19 12:53:24 -0700956
957 switch (representation) {
jiabin245cdd92018-12-07 17:55:15 -0800958 // Travel all single bit channel mask to convert channel mask to string.
Andy Hungf98ec8d2015-05-19 12:53:24 -0700959 case AUDIO_CHANNEL_REPRESENTATION_POSITION: {
960 if (output) {
961 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT) s.append("front-left, ");
962 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT) s.append("front-right, ");
963 if (mask & AUDIO_CHANNEL_OUT_FRONT_CENTER) s.append("front-center, ");
Andy Hungfba71252021-05-07 11:58:32 -0700964 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY) s.append("low-frequency, ");
Andy Hungf98ec8d2015-05-19 12:53:24 -0700965 if (mask & AUDIO_CHANNEL_OUT_BACK_LEFT) s.append("back-left, ");
966 if (mask & AUDIO_CHANNEL_OUT_BACK_RIGHT) s.append("back-right, ");
967 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT_OF_CENTER) s.append("front-left-of-center, ");
968 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT_OF_CENTER) s.append("front-right-of-center, ");
969 if (mask & AUDIO_CHANNEL_OUT_BACK_CENTER) s.append("back-center, ");
970 if (mask & AUDIO_CHANNEL_OUT_SIDE_LEFT) s.append("side-left, ");
971 if (mask & AUDIO_CHANNEL_OUT_SIDE_RIGHT) s.append("side-right, ");
972 if (mask & AUDIO_CHANNEL_OUT_TOP_CENTER) s.append("top-center ,");
973 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_LEFT) s.append("top-front-left, ");
974 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_CENTER) s.append("top-front-center, ");
975 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_RIGHT) s.append("top-front-right, ");
976 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_LEFT) s.append("top-back-left, ");
Andy Hungae81b4c2021-05-07 08:54:28 -0700977 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_CENTER) s.append("top-back-center, ");
978 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_RIGHT) s.append("top-back-right, ");
979 if (mask & AUDIO_CHANNEL_OUT_TOP_SIDE_LEFT) s.append("top-side-left, ");
980 if (mask & AUDIO_CHANNEL_OUT_TOP_SIDE_RIGHT) s.append("top-side-right, ");
981 if (mask & AUDIO_CHANNEL_OUT_BOTTOM_FRONT_LEFT) s.append("bottom-front-left, ");
982 if (mask & AUDIO_CHANNEL_OUT_BOTTOM_FRONT_CENTER) s.append("bottom-front-center, ");
983 if (mask & AUDIO_CHANNEL_OUT_BOTTOM_FRONT_RIGHT) s.append("bottom-front-right, ");
Andy Hungfba71252021-05-07 11:58:32 -0700984 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY_2) s.append("low-frequency-2, ");
Andy Hungae81b4c2021-05-07 08:54:28 -0700985 if (mask & AUDIO_CHANNEL_OUT_HAPTIC_B) s.append("haptic-B, ");
986 if (mask & AUDIO_CHANNEL_OUT_HAPTIC_A) s.append("haptic-A, ");
Andy Hungf98ec8d2015-05-19 12:53:24 -0700987 if (mask & ~AUDIO_CHANNEL_OUT_ALL) s.append("unknown, ");
988 } else {
989 if (mask & AUDIO_CHANNEL_IN_LEFT) s.append("left, ");
990 if (mask & AUDIO_CHANNEL_IN_RIGHT) s.append("right, ");
991 if (mask & AUDIO_CHANNEL_IN_FRONT) s.append("front, ");
992 if (mask & AUDIO_CHANNEL_IN_BACK) s.append("back, ");
993 if (mask & AUDIO_CHANNEL_IN_LEFT_PROCESSED) s.append("left-processed, ");
994 if (mask & AUDIO_CHANNEL_IN_RIGHT_PROCESSED) s.append("right-processed, ");
995 if (mask & AUDIO_CHANNEL_IN_FRONT_PROCESSED) s.append("front-processed, ");
996 if (mask & AUDIO_CHANNEL_IN_BACK_PROCESSED) s.append("back-processed, ");
997 if (mask & AUDIO_CHANNEL_IN_PRESSURE) s.append("pressure, ");
998 if (mask & AUDIO_CHANNEL_IN_X_AXIS) s.append("X, ");
999 if (mask & AUDIO_CHANNEL_IN_Y_AXIS) s.append("Y, ");
1000 if (mask & AUDIO_CHANNEL_IN_Z_AXIS) s.append("Z, ");
Mikhail Naganovc9948492018-05-10 17:25:28 -07001001 if (mask & AUDIO_CHANNEL_IN_BACK_LEFT) s.append("back-left, ");
1002 if (mask & AUDIO_CHANNEL_IN_BACK_RIGHT) s.append("back-right, ");
1003 if (mask & AUDIO_CHANNEL_IN_CENTER) s.append("center, ");
Andy Hungfba71252021-05-07 11:58:32 -07001004 if (mask & AUDIO_CHANNEL_IN_LOW_FREQUENCY) s.append("low-frequency, ");
Andy Hungae81b4c2021-05-07 08:54:28 -07001005 if (mask & AUDIO_CHANNEL_IN_TOP_LEFT) s.append("top-left, ");
1006 if (mask & AUDIO_CHANNEL_IN_TOP_RIGHT) s.append("top-right, ");
Andy Hungf98ec8d2015-05-19 12:53:24 -07001007 if (mask & AUDIO_CHANNEL_IN_VOICE_UPLINK) s.append("voice-uplink, ");
1008 if (mask & AUDIO_CHANNEL_IN_VOICE_DNLINK) s.append("voice-dnlink, ");
1009 if (mask & ~AUDIO_CHANNEL_IN_ALL) s.append("unknown, ");
1010 }
1011 const int len = s.length();
1012 if (len > 2) {
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07001013 (void) s.lockBuffer(len); // needed?
Andy Hungf98ec8d2015-05-19 12:53:24 -07001014 s.unlockBuffer(len - 2); // remove trailing ", "
1015 }
1016 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -08001017 }
Andy Hungf98ec8d2015-05-19 12:53:24 -07001018 case AUDIO_CHANNEL_REPRESENTATION_INDEX:
1019 s.appendFormat("index mask, bits:%#x", audio_channel_mask_get_bits(mask));
1020 return s;
1021 default:
1022 s.appendFormat("unknown mask, representation:%d bits:%#x",
1023 representation, audio_channel_mask_get_bits(mask));
1024 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -08001025 }
Marco Nelissenb2208842014-02-07 14:00:50 -08001026}
1027
Andy Hungee58e4a2023-07-07 13:47:37 -07001028void ThreadBase::dump(int fd, const Vector<String16>& args)
Andy Hung920f6572022-10-06 12:09:49 -07001029NO_THREAD_SAFETY_ANALYSIS // conditional try lock
Eric Laurent81784c32012-11-19 14:55:58 -08001030{
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08001031 dprintf(fd, "\n%s thread %p, name %s, tid %d, type %d (%s):\n", isOutput() ? "Output" : "Input",
1032 this, mThreadName, getTid(), type(), threadTypeToString(type()));
1033
Andy Hungc5007f82023-08-29 14:26:09 -07001034 const bool locked = afutils::dumpTryLock(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001035 if (!locked) {
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08001036 dprintf(fd, " Thread may be deadlocked\n");
Eric Laurent81784c32012-11-19 14:55:58 -08001037 }
1038
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001039 dumpBase_l(fd, args);
1040 dumpInternals_l(fd, args);
1041 dumpTracks_l(fd, args);
1042 dumpEffectChains_l(fd, args);
1043
1044 if (locked) {
Andy Hungc5007f82023-08-29 14:26:09 -07001045 mutex().unlock();
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001046 }
1047
1048 dprintf(fd, " Local log:\n");
1049 mLocalLog.dump(fd, " " /* prefix */, 40 /* lines */);
Andy Hungafc51db2022-04-08 17:33:40 -07001050
1051 // --all does the statistics
1052 bool dumpAll = false;
1053 for (const auto &arg : args) {
1054 if (arg == String16("--all")) {
1055 dumpAll = true;
1056 }
1057 }
1058 if (dumpAll || type() == SPATIALIZER) {
Andy Hung44d648b2022-04-08 17:33:40 -07001059 const std::string sched = mThreadSnapshot.toString();
Andy Hungafc51db2022-04-08 17:33:40 -07001060 if (!sched.empty()) {
1061 (void)write(fd, sched.c_str(), sched.size());
1062 }
1063 }
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001064}
1065
Andy Hungee58e4a2023-07-07 13:47:37 -07001066void ThreadBase::dumpBase_l(int fd, const Vector<String16>& /* args */)
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001067{
Elliott Hughes87cebad2014-05-22 10:14:43 -07001068 dprintf(fd, " I/O handle: %d\n", mId);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001069 dprintf(fd, " Standby: %s\n", mStandby ? "yes" : "no");
Glenn Kasten97b7b752014-09-28 13:04:24 -07001070 dprintf(fd, " Sample rate: %u Hz\n", mSampleRate);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001071 dprintf(fd, " HAL frame count: %zu\n", mFrameCount);
Andy Hung25a80ac2023-07-19 12:47:35 -07001072 dprintf(fd, " HAL format: 0x%x (%s)\n", mHALFormat,
1073 IAfThreadBase::formatToString(mHALFormat).c_str());
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001074 dprintf(fd, " HAL buffer size: %zu bytes\n", mBufferSize);
Glenn Kasten97b7b752014-09-28 13:04:24 -07001075 dprintf(fd, " Channel count: %u\n", mChannelCount);
1076 dprintf(fd, " Channel mask: 0x%08x (%s)\n", mChannelMask,
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00001077 channelMaskToString(mChannelMask, mType != RECORD).c_str());
Andy Hung25a80ac2023-07-19 12:47:35 -07001078 dprintf(fd, " Processing format: 0x%x (%s)\n", mFormat,
1079 IAfThreadBase::formatToString(mFormat).c_str());
Glenn Kastenf87c2f52015-08-21 08:03:57 -07001080 dprintf(fd, " Processing frame size: %zu bytes\n", mFrameSize);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001081 dprintf(fd, " Pending config events:");
Marco Nelissenb2208842014-02-07 14:00:50 -08001082 size_t numConfig = mConfigEvents.size();
1083 if (numConfig) {
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001084 const size_t SIZE = 256;
1085 char buffer[SIZE];
Marco Nelissenb2208842014-02-07 14:00:50 -08001086 for (size_t i = 0; i < numConfig; i++) {
1087 mConfigEvents[i]->dump(buffer, SIZE);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001088 dprintf(fd, "\n %s", buffer);
Marco Nelissenb2208842014-02-07 14:00:50 -08001089 }
Elliott Hughes87cebad2014-05-22 10:14:43 -07001090 dprintf(fd, "\n");
Marco Nelissenb2208842014-02-07 14:00:50 -08001091 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07001092 dprintf(fd, " none\n");
Eric Laurent81784c32012-11-19 14:55:58 -08001093 }
Andy Hung293558a2017-03-21 12:19:20 -07001094 // Note: output device may be used by capture threads for effects such as AEC.
jiabinc52b1ff2019-10-31 17:20:42 -07001095 dprintf(fd, " Output devices: %s (%s)\n",
Andy Hungab65b182023-09-06 19:41:47 -07001096 dumpDeviceTypes(outDeviceTypes_l()).c_str(), toString(outDeviceTypes_l()).c_str());
jiabinc52b1ff2019-10-31 17:20:42 -07001097 dprintf(fd, " Input device: %#x (%s)\n",
Andy Hungab65b182023-09-06 19:41:47 -07001098 inDeviceType_l(), toString(inDeviceType_l()).c_str());
Andy Hung9b181952019-02-25 14:53:36 -08001099 dprintf(fd, " Audio source: %d (%s)\n", mAudioSource, toString(mAudioSource).c_str());
Eric Laurent81784c32012-11-19 14:55:58 -08001100
Andy Hung2e2c0bb2018-06-11 19:13:11 -07001101 // Dump timestamp statistics for the Thread types that support it.
1102 if (mType == RECORD
1103 || mType == MIXER
1104 || mType == DUPLICATING
Andy Hungf3234512018-07-03 14:51:47 -07001105 || mType == DIRECT
Andy Hung4b7f54f2022-04-28 17:45:28 -07001106 || mType == OFFLOAD
1107 || mType == SPATIALIZER) {
Andy Hung2e2c0bb2018-06-11 19:13:11 -07001108 dprintf(fd, " Timestamp stats: %s\n", mTimestampVerifier.toString().c_str());
Andy Hungab65b182023-09-06 19:41:47 -07001109 dprintf(fd, " Timestamp corrected: %s\n",
1110 isTimestampCorrectionEnabled_l() ? "yes" : "no");
Andy Hung2e2c0bb2018-06-11 19:13:11 -07001111 }
1112
Andy Hung446f4df2019-02-21 12:26:41 -08001113 if (mLastIoBeginNs > 0) { // MMAP may not set this
1114 dprintf(fd, " Last %s occurred (msecs): %lld\n",
1115 isOutput() ? "write" : "read",
1116 (long long) (systemTime() - mLastIoBeginNs) / NANOS_PER_MILLISECOND);
1117 }
1118
1119 if (mProcessTimeMs.getN() > 0) {
1120 dprintf(fd, " Process time ms stats: %s\n", mProcessTimeMs.toString().c_str());
1121 }
1122
1123 if (mIoJitterMs.getN() > 0) {
1124 dprintf(fd, " Hal %s jitter ms stats: %s\n",
1125 isOutput() ? "write" : "read",
1126 mIoJitterMs.toString().c_str());
1127 }
1128
Andy Hunge6c37112019-02-26 17:38:10 -08001129 if (mLatencyMs.getN() > 0) {
1130 dprintf(fd, " Threadloop %s latency stats: %s\n",
1131 isOutput() ? "write" : "read",
1132 mLatencyMs.toString().c_str());
1133 }
Robert Wu06db0a32021-08-10 19:05:34 +00001134
1135 if (mMonopipePipeDepthStats.getN() > 0) {
1136 dprintf(fd, " Monopipe %s pipe depth stats: %s\n",
1137 isOutput() ? "write" : "read",
1138 mMonopipePipeDepthStats.toString().c_str());
1139 }
Eric Laurent81784c32012-11-19 14:55:58 -08001140}
1141
Andy Hungee58e4a2023-07-07 13:47:37 -07001142void ThreadBase::dumpEffectChains_l(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -08001143{
1144 const size_t SIZE = 256;
1145 char buffer[SIZE];
Eric Laurent81784c32012-11-19 14:55:58 -08001146
Marco Nelissenb2208842014-02-07 14:00:50 -08001147 size_t numEffectChains = mEffectChains.size();
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +00001148 snprintf(buffer, SIZE, " %zu Effect Chains\n", numEffectChains);
Eric Laurent81784c32012-11-19 14:55:58 -08001149 write(fd, buffer, strlen(buffer));
1150
Marco Nelissenb2208842014-02-07 14:00:50 -08001151 for (size_t i = 0; i < numEffectChains; ++i) {
Andy Hung116bc262023-06-20 18:56:17 -07001152 sp<IAfEffectChain> chain = mEffectChains[i];
Eric Laurent81784c32012-11-19 14:55:58 -08001153 if (chain != 0) {
1154 chain->dump(fd, args);
1155 }
1156 }
1157}
1158
Andy Hungee58e4a2023-07-07 13:47:37 -07001159void ThreadBase::acquireWakeLock()
Eric Laurent81784c32012-11-19 14:55:58 -08001160{
Andy Hung972bec12023-08-31 16:13:39 -07001161 audio_utils::lock_guard _l(mutex());
Andy Hungdae27702016-10-31 14:01:16 -07001162 acquireWakeLock_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001163}
1164
Andy Hungee58e4a2023-07-07 13:47:37 -07001165String16 ThreadBase::getWakeLockTag()
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001166{
1167 switch (mType) {
Glenn Kastenbcb14862015-03-05 17:11:21 -08001168 case MIXER:
1169 return String16("AudioMix");
1170 case DIRECT:
1171 return String16("AudioDirectOut");
1172 case DUPLICATING:
1173 return String16("AudioDup");
1174 case RECORD:
1175 return String16("AudioIn");
1176 case OFFLOAD:
1177 return String16("AudioOffload");
Andy Hungea840382020-05-05 21:50:17 -07001178 case MMAP_PLAYBACK:
1179 return String16("MmapPlayback");
1180 case MMAP_CAPTURE:
1181 return String16("MmapCapture");
Eric Laurent1c5e2e32021-08-18 18:50:28 +02001182 case SPATIALIZER:
1183 return String16("AudioSpatial");
Glenn Kastenbcb14862015-03-05 17:11:21 -08001184 default:
1185 ALOG_ASSERT(false);
1186 return String16("AudioUnknown");
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001187 }
1188}
1189
Andy Hungee58e4a2023-07-07 13:47:37 -07001190void ThreadBase::acquireWakeLock_l()
Eric Laurent81784c32012-11-19 14:55:58 -08001191{
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001192 getPowerManager_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001193 if (mPowerManager != 0) {
1194 sp<IBinder> binder = new BBinder();
Andy Hungdae27702016-10-31 14:01:16 -07001195 // Uses AID_AUDIOSERVER for wakelock. updateWakeLockUids_l() updates with client uids.
Chris Ye6597d732020-02-28 22:38:25 -08001196 binder::Status status = mPowerManager->acquireWakeLockAsync(binder,
1197 POWERMANAGER_PARTIAL_WAKE_LOCK,
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001198 getWakeLockTag(),
Marco Nelissendcb346b2015-09-09 10:47:29 -07001199 String16("audioserver"),
Chris Ye6597d732020-02-28 22:38:25 -08001200 {} /* workSource */,
1201 {} /* historyTag */);
1202 if (status.isOk()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001203 mWakeLockToken = binder;
1204 }
Chris Ye6597d732020-02-28 22:38:25 -08001205 ALOGV("acquireWakeLock_l() %s status %d", mThreadName, status.exceptionCode());
Eric Laurent81784c32012-11-19 14:55:58 -08001206 }
Wei Jia3f273d12015-11-24 09:06:49 -08001207
Andy Hung3f0c9022016-01-15 17:49:46 -08001208 gBoottime.acquire(mWakeLockToken);
Andy Hung818e7a32016-02-16 18:08:07 -08001209 mTimestamp.mTimebaseOffset[ExtendedTimestamp::TIMEBASE_BOOTTIME] =
1210 gBoottime.getBoottimeOffset();
Eric Laurent81784c32012-11-19 14:55:58 -08001211}
1212
Andy Hungee58e4a2023-07-07 13:47:37 -07001213void ThreadBase::releaseWakeLock()
Eric Laurent81784c32012-11-19 14:55:58 -08001214{
Andy Hung972bec12023-08-31 16:13:39 -07001215 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001216 releaseWakeLock_l();
1217}
1218
Andy Hungee58e4a2023-07-07 13:47:37 -07001219void ThreadBase::releaseWakeLock_l()
Eric Laurent81784c32012-11-19 14:55:58 -08001220{
Andy Hung3f0c9022016-01-15 17:49:46 -08001221 gBoottime.release(mWakeLockToken);
Eric Laurent81784c32012-11-19 14:55:58 -08001222 if (mWakeLockToken != 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -08001223 ALOGV("releaseWakeLock_l() %s", mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08001224 if (mPowerManager != 0) {
Chris Ye6597d732020-02-28 22:38:25 -08001225 mPowerManager->releaseWakeLockAsync(mWakeLockToken, 0);
Eric Laurent81784c32012-11-19 14:55:58 -08001226 }
1227 mWakeLockToken.clear();
1228 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001229}
1230
Andy Hungee58e4a2023-07-07 13:47:37 -07001231void ThreadBase::getPowerManager_l() {
Eric Laurent72e3f392015-05-20 14:43:50 -07001232 if (mSystemReady && mPowerManager == 0) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001233 // use checkService() to avoid blocking if power service is not up yet
1234 sp<IBinder> binder =
1235 defaultServiceManager()->checkService(String16("power"));
1236 if (binder == 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -08001237 ALOGW("Thread %s cannot connect to the power manager service", mThreadName);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001238 } else {
Chris Ye6597d732020-02-28 22:38:25 -08001239 mPowerManager = interface_cast<os::IPowerManager>(binder);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001240 binder->linkToDeath(mDeathRecipient);
1241 }
1242 }
1243}
1244
Andy Hungee58e4a2023-07-07 13:47:37 -07001245void ThreadBase::updateWakeLockUids_l(const SortedVector<uid_t>& uids) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001246 getPowerManager_l();
Andy Hungdae27702016-10-31 14:01:16 -07001247
1248#if !LOG_NDEBUG
1249 std::stringstream s;
Andy Hungd01b0f12016-11-07 16:10:30 -08001250 for (uid_t uid : uids) {
Andy Hungdae27702016-10-31 14:01:16 -07001251 s << uid << " ";
1252 }
1253 ALOGD("updateWakeLockUids_l %s uids:%s", mThreadName, s.str().c_str());
1254#endif
1255
Andy Hung438e7572015-12-14 15:51:17 -08001256 if (mWakeLockToken == NULL) { // token may be NULL if AudioFlinger::systemReady() not called.
1257 if (mSystemReady) {
1258 ALOGE("no wake lock to update, but system ready!");
1259 } else {
1260 ALOGW("no wake lock to update, system not ready yet");
1261 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001262 return;
1263 }
1264 if (mPowerManager != 0) {
Andy Hung1f12a8a2016-11-07 16:10:30 -08001265 std::vector<int> uidsAsInt(uids.begin(), uids.end()); // powermanager expects uids as ints
Chris Ye6597d732020-02-28 22:38:25 -08001266 binder::Status status = mPowerManager->updateWakeLockUidsAsync(
1267 mWakeLockToken, uidsAsInt);
1268 ALOGV("updateWakeLockUids_l() %s status %d", mThreadName, status.exceptionCode());
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001269 }
1270}
1271
Andy Hungee58e4a2023-07-07 13:47:37 -07001272void ThreadBase::clearPowerManager()
Eric Laurent81784c32012-11-19 14:55:58 -08001273{
Andy Hung972bec12023-08-31 16:13:39 -07001274 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001275 releaseWakeLock_l();
1276 mPowerManager.clear();
1277}
1278
Andy Hungee58e4a2023-07-07 13:47:37 -07001279void ThreadBase::updateOutDevices(
jiabinc52b1ff2019-10-31 17:20:42 -07001280 const DeviceDescriptorBaseVector& outDevices __unused)
1281{
1282 ALOGE("%s should only be called in RecordThread", __func__);
1283}
1284
Andy Hungee58e4a2023-07-07 13:47:37 -07001285void ThreadBase::resizeInputBuffer_l(int32_t /* maxSharedAudioHistoryMs */)
Eric Laurentec376dc2021-04-08 20:41:22 +02001286{
1287 ALOGE("%s should only be called in RecordThread", __func__);
1288}
1289
Andy Hungee58e4a2023-07-07 13:47:37 -07001290void ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& /* who */)
Eric Laurent81784c32012-11-19 14:55:58 -08001291{
1292 sp<ThreadBase> thread = mThread.promote();
1293 if (thread != 0) {
1294 thread->clearPowerManager();
1295 }
1296 ALOGW("power manager service died !!!");
1297}
1298
Andy Hungee58e4a2023-07-07 13:47:37 -07001299void ThreadBase::setEffectSuspended_l(
Glenn Kastend848eb42016-03-08 13:42:11 -08001300 const effect_uuid_t *type, bool suspend, audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001301{
Andy Hung116bc262023-06-20 18:56:17 -07001302 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08001303 if (chain != 0) {
1304 if (type != NULL) {
1305 chain->setEffectSuspended_l(type, suspend);
1306 } else {
1307 chain->setEffectSuspendedAll_l(suspend);
1308 }
1309 }
1310
1311 updateSuspendedSessions_l(type, suspend, sessionId);
1312}
1313
Andy Hungee58e4a2023-07-07 13:47:37 -07001314void ThreadBase::checkSuspendOnAddEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08001315{
1316 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
1317 if (index < 0) {
1318 return;
1319 }
1320
1321 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
1322 mSuspendedSessions.valueAt(index);
1323
1324 for (size_t i = 0; i < sessionEffects.size(); i++) {
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07001325 const sp<SuspendedSessionDesc>& desc = sessionEffects.valueAt(i);
Eric Laurent81784c32012-11-19 14:55:58 -08001326 for (int j = 0; j < desc->mRefCount; j++) {
Andy Hung116bc262023-06-20 18:56:17 -07001327 if (sessionEffects.keyAt(i) == IAfEffectChain::kKeyForSuspendAll) {
Eric Laurent81784c32012-11-19 14:55:58 -08001328 chain->setEffectSuspendedAll_l(true);
1329 } else {
1330 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
1331 desc->mType.timeLow);
1332 chain->setEffectSuspended_l(&desc->mType, true);
1333 }
1334 }
1335 }
1336}
1337
Andy Hungee58e4a2023-07-07 13:47:37 -07001338void ThreadBase::updateSuspendedSessions_l(const effect_uuid_t* type,
Eric Laurent81784c32012-11-19 14:55:58 -08001339 bool suspend,
Glenn Kastend848eb42016-03-08 13:42:11 -08001340 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001341{
1342 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
1343
1344 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1345
1346 if (suspend) {
1347 if (index >= 0) {
1348 sessionEffects = mSuspendedSessions.valueAt(index);
1349 } else {
1350 mSuspendedSessions.add(sessionId, sessionEffects);
1351 }
1352 } else {
1353 if (index < 0) {
1354 return;
1355 }
1356 sessionEffects = mSuspendedSessions.valueAt(index);
1357 }
1358
1359
Andy Hung116bc262023-06-20 18:56:17 -07001360 int key = IAfEffectChain::kKeyForSuspendAll;
Eric Laurent81784c32012-11-19 14:55:58 -08001361 if (type != NULL) {
1362 key = type->timeLow;
1363 }
1364 index = sessionEffects.indexOfKey(key);
1365
1366 sp<SuspendedSessionDesc> desc;
1367 if (suspend) {
1368 if (index >= 0) {
1369 desc = sessionEffects.valueAt(index);
1370 } else {
1371 desc = new SuspendedSessionDesc();
1372 if (type != NULL) {
1373 desc->mType = *type;
1374 }
1375 sessionEffects.add(key, desc);
1376 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
1377 }
1378 desc->mRefCount++;
1379 } else {
1380 if (index < 0) {
1381 return;
1382 }
1383 desc = sessionEffects.valueAt(index);
1384 if (--desc->mRefCount == 0) {
1385 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
1386 sessionEffects.removeItemsAt(index);
1387 if (sessionEffects.isEmpty()) {
1388 ALOGV("updateSuspendedSessions_l() restore removing session %d",
1389 sessionId);
1390 mSuspendedSessions.removeItem(sessionId);
1391 }
1392 }
1393 }
1394 if (!sessionEffects.isEmpty()) {
1395 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1396 }
1397}
1398
Andy Hungee58e4a2023-07-07 13:47:37 -07001399void ThreadBase::checkSuspendOnEffectEnabled(bool enabled,
Eric Laurent6b446ce2019-12-13 10:56:31 -08001400 audio_session_t sessionId,
Andy Hung920f6572022-10-06 12:09:49 -07001401 bool threadLocked)
1402NO_THREAD_SAFETY_ANALYSIS // manual locking
1403{
Eric Laurent6b446ce2019-12-13 10:56:31 -08001404 if (!threadLocked) {
Andy Hungc5007f82023-08-29 14:26:09 -07001405 mutex().lock();
Eric Laurent6b446ce2019-12-13 10:56:31 -08001406 }
Eric Laurent81784c32012-11-19 14:55:58 -08001407
Eric Laurent81784c32012-11-19 14:55:58 -08001408 if (mType != RECORD) {
1409 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1410 // another session. This gives the priority to well behaved effect control panels
1411 // and applications not using global effects.
1412 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
1413 // global effects
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001414 if (!audio_is_global_session(sessionId)) {
Eric Laurent81784c32012-11-19 14:55:58 -08001415 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1416 }
1417 }
1418
Eric Laurent6b446ce2019-12-13 10:56:31 -08001419 if (!threadLocked) {
Andy Hungc5007f82023-08-29 14:26:09 -07001420 mutex().unlock();
Eric Laurent81784c32012-11-19 14:55:58 -08001421 }
1422}
1423
Andy Hungc5007f82023-08-29 14:26:09 -07001424// checkEffectCompatibility_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07001425status_t RecordThread::checkEffectCompatibility_l(
Eric Laurent4c415062016-06-17 16:14:16 -07001426 const effect_descriptor_t *desc, audio_session_t sessionId)
1427{
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001428 // No global output effect sessions on record threads
1429 if (sessionId == AUDIO_SESSION_OUTPUT_MIX
1430 || sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Eric Laurent4c415062016-06-17 16:14:16 -07001431 ALOGW("checkEffectCompatibility_l(): global effect %s on record thread %s",
1432 desc->name, mThreadName);
1433 return BAD_VALUE;
1434 }
1435 // only pre processing effects on record thread
1436 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC) {
1437 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on record thread %s",
1438 desc->name, mThreadName);
1439 return BAD_VALUE;
1440 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001441
1442 // always allow effects without processing load or latency
1443 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1444 return NO_ERROR;
1445 }
1446
Eric Laurent4c415062016-06-17 16:14:16 -07001447 audio_input_flags_t flags = mInput->flags;
1448 if (hasFastCapture() || (flags & AUDIO_INPUT_FLAG_FAST)) {
1449 if (flags & AUDIO_INPUT_FLAG_RAW) {
1450 ALOGW("checkEffectCompatibility_l(): effect %s on record thread %s in raw mode",
1451 desc->name, mThreadName);
1452 return BAD_VALUE;
1453 }
1454 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1455 ALOGW("checkEffectCompatibility_l(): non HW effect %s on record thread %s in fast mode",
1456 desc->name, mThreadName);
1457 return BAD_VALUE;
1458 }
1459 }
jiabineb3bda02020-06-30 14:07:03 -07001460
Andy Hung116bc262023-06-20 18:56:17 -07001461 if (IAfEffectModule::isHapticGenerator(&desc->type)) {
jiabineb3bda02020-06-30 14:07:03 -07001462 ALOGE("%s(): HapticGenerator is not supported in RecordThread", __func__);
1463 return BAD_VALUE;
1464 }
Eric Laurent4c415062016-06-17 16:14:16 -07001465 return NO_ERROR;
1466}
1467
Andy Hungc5007f82023-08-29 14:26:09 -07001468// checkEffectCompatibility_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07001469status_t PlaybackThread::checkEffectCompatibility_l(
Eric Laurent4c415062016-06-17 16:14:16 -07001470 const effect_descriptor_t *desc, audio_session_t sessionId)
1471{
1472 // no preprocessing on playback threads
1473 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001474 ALOGW("%s: pre processing effect %s created on playback"
1475 " thread %s", __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001476 return BAD_VALUE;
1477 }
1478
Eric Laurent3e4de772017-07-16 16:55:08 -07001479 // always allow effects without processing load or latency
1480 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1481 return NO_ERROR;
1482 }
1483
Andy Hung116bc262023-06-20 18:56:17 -07001484 if (IAfEffectModule::isHapticGenerator(&desc->type) && mHapticChannelCount == 0) {
Shunkai Yao4c3af932024-04-26 04:12:21 +00001485 ALOGW("%s: thread (%s) doesn't support haptic playback while the effect is HapticGenerator",
1486 __func__, threadTypeToString(mType));
jiabineb3bda02020-06-30 14:07:03 -07001487 return BAD_VALUE;
1488 }
1489
Eric Laurent4eb45d02023-12-20 12:07:17 +01001490 if (IAfEffectModule::isSpatializer(&desc->type)
Eric Laurentf690c462021-09-17 14:47:03 +02001491 && mType != SPATIALIZER) {
1492 ALOGW("%s: attempt to create a spatializer effect on a thread of type %d",
1493 __func__, mType);
1494 return BAD_VALUE;
1495 }
1496
Eric Laurent4c415062016-06-17 16:14:16 -07001497 switch (mType) {
1498 case MIXER: {
Eric Laurent4c415062016-06-17 16:14:16 -07001499 audio_output_flags_t flags = mOutput->flags;
1500 if (hasFastMixer() || (flags & AUDIO_OUTPUT_FLAG_FAST)) {
1501 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1502 // global effects are applied only to non fast tracks if they are SW
1503 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1504 break;
1505 }
1506 } else if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1507 // only post processing on output stage session
1508 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001509 ALOGW("%s: non post processing effect %s not allowed on output stage session",
1510 __func__, desc->name);
Eric Laurent4c415062016-06-17 16:14:16 -07001511 return BAD_VALUE;
1512 }
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001513 } else if (sessionId == AUDIO_SESSION_DEVICE) {
1514 // only post processing on output stage session
1515 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001516 ALOGW("%s: non post processing effect %s not allowed on device session",
1517 __func__, desc->name);
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001518 return BAD_VALUE;
1519 }
Eric Laurent4c415062016-06-17 16:14:16 -07001520 } else {
1521 // no restriction on effects applied on non fast tracks
1522 if ((hasAudioSession_l(sessionId) & ThreadBase::FAST_SESSION) == 0) {
1523 break;
1524 }
1525 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001526
Eric Laurent4c415062016-06-17 16:14:16 -07001527 if (flags & AUDIO_OUTPUT_FLAG_RAW) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001528 ALOGW("%s: effect %s on playback thread in raw mode", __func__, desc->name);
Eric Laurent4c415062016-06-17 16:14:16 -07001529 return BAD_VALUE;
1530 }
1531 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001532 ALOGW("%s: non HW effect %s on playback thread in fast mode",
1533 __func__, desc->name);
Eric Laurent4c415062016-06-17 16:14:16 -07001534 return BAD_VALUE;
1535 }
1536 }
1537 } break;
1538 case OFFLOAD:
Jean-Michel Trivi773ee952016-07-11 16:53:18 -07001539 // nothing actionable on offload threads, if the effect:
1540 // - is offloadable: the effect can be created
1541 // - is NOT offloadable: the effect should still be created, but EffectHandle::enable()
1542 // will take care of invalidating the tracks of the thread
Eric Laurent4c415062016-06-17 16:14:16 -07001543 break;
1544 case DIRECT:
1545 // Reject any effect on Direct output threads for now, since the format of
1546 // mSinkBuffer is not guaranteed to be compatible with effect processing (PCM 16 stereo).
Eric Laurentb62d0362021-10-26 17:40:18 +02001547 ALOGW("%s: effect %s on DIRECT output thread %s",
1548 __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001549 return BAD_VALUE;
1550 case DUPLICATING:
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001551 if (audio_is_global_session(sessionId)) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001552 ALOGW("%s: global effect %s on DUPLICATING thread %s",
1553 __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001554 return BAD_VALUE;
1555 }
1556 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001557 ALOGW("%s: post processing effect %s on DUPLICATING thread %s",
1558 __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001559 return BAD_VALUE;
1560 }
1561 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) != 0) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001562 ALOGW("%s: HW tunneled effect %s on DUPLICATING thread %s",
1563 __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001564 return BAD_VALUE;
1565 }
1566 break;
Eric Laurent1c5e2e32021-08-18 18:50:28 +02001567 case SPATIALIZER:
Eric Laurentb62d0362021-10-26 17:40:18 +02001568 // Global effects (AUDIO_SESSION_OUTPUT_MIX) are not supported on spatializer mixer
1569 // as there is no common accumulation buffer for sptialized and non sptialized tracks.
1570 // Post processing effects (AUDIO_SESSION_OUTPUT_STAGE or AUDIO_SESSION_DEVICE)
1571 // are supported and added after the spatializer.
1572 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1573 ALOGW("%s: global effect %s not supported on spatializer thread %s",
1574 __func__, desc->name, mThreadName);
Eric Laurentb3f315a2021-07-13 15:09:05 +02001575 return BAD_VALUE;
Eric Laurentb62d0362021-10-26 17:40:18 +02001576 } else if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1577 // only post processing , downmixer or spatializer effects on output stage session
Eric Laurent4eb45d02023-12-20 12:07:17 +01001578 if (IAfEffectModule::isSpatializer(&desc->type)
Eric Laurentb62d0362021-10-26 17:40:18 +02001579 || memcmp(&desc->type, EFFECT_UIID_DOWNMIX, sizeof(effect_uuid_t)) == 0) {
1580 break;
1581 }
1582 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
1583 ALOGW("%s: non post processing effect %s not allowed on output stage session",
1584 __func__, desc->name);
1585 return BAD_VALUE;
1586 }
1587 } else if (sessionId == AUDIO_SESSION_DEVICE) {
1588 // only post processing on output stage session
1589 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
1590 ALOGW("%s: non post processing effect %s not allowed on device session",
1591 __func__, desc->name);
1592 return BAD_VALUE;
1593 }
Eric Laurentb3f315a2021-07-13 15:09:05 +02001594 }
1595 break;
jiabinc658e452022-10-21 20:52:21 +00001596 case BIT_PERFECT:
1597 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) != 0) {
1598 // Allow HW accelerated effects of tunnel type
1599 break;
1600 }
1601 // As bit-perfect tracks will not be allowed to apply audio effect that will touch the audio
1602 // data, effects will not be allowed on 1) global effects (AUDIO_SESSION_OUTPUT_MIX),
1603 // 2) post-processing effects (AUDIO_SESSION_OUTPUT_STAGE or AUDIO_SESSION_DEVICE) and
1604 // 3) there is any bit-perfect track with the given session id.
1605 if (sessionId == AUDIO_SESSION_OUTPUT_MIX || sessionId == AUDIO_SESSION_OUTPUT_STAGE ||
1606 sessionId == AUDIO_SESSION_DEVICE) {
1607 ALOGW("%s: effect %s not supported on bit-perfect thread %s",
1608 __func__, desc->name, mThreadName);
1609 return BAD_VALUE;
1610 } else if ((hasAudioSession_l(sessionId) & ThreadBase::BIT_PERFECT_SESSION) != 0) {
1611 ALOGW("%s: effect %s not supported as there is a bit-perfect track with session as %d",
1612 __func__, desc->name, sessionId);
1613 return BAD_VALUE;
1614 }
1615 break;
Eric Laurent4c415062016-06-17 16:14:16 -07001616 default:
1617 LOG_ALWAYS_FATAL("checkEffectCompatibility_l(): wrong thread type %d", mType);
1618 }
1619
1620 return NO_ERROR;
1621}
1622
Andy Hungc5007f82023-08-29 14:26:09 -07001623// ThreadBase::createEffect_l() must be called with AudioFlinger::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07001624sp<IAfEffectHandle> ThreadBase::createEffect_l(
Andy Hung88035ac2023-06-27 17:05:02 -07001625 const sp<Client>& client,
Eric Laurent81784c32012-11-19 14:55:58 -08001626 const sp<IEffectClient>& effectClient,
1627 int32_t priority,
Glenn Kastend848eb42016-03-08 13:42:11 -08001628 audio_session_t sessionId,
Eric Laurent81784c32012-11-19 14:55:58 -08001629 effect_descriptor_t *desc,
1630 int *enabled,
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001631 status_t *status,
Eric Laurent2fe0acd2020-03-13 14:30:46 -07001632 bool pinned,
Eric Laurentde8caf42021-08-11 17:19:25 +02001633 bool probe,
1634 bool notifyFramesProcessed)
Eric Laurent81784c32012-11-19 14:55:58 -08001635{
Andy Hung116bc262023-06-20 18:56:17 -07001636 sp<IAfEffectModule> effect;
1637 sp<IAfEffectHandle> handle;
Eric Laurent81784c32012-11-19 14:55:58 -08001638 status_t lStatus;
Andy Hung116bc262023-06-20 18:56:17 -07001639 sp<IAfEffectChain> chain;
Eric Laurent81784c32012-11-19 14:55:58 -08001640 bool chainCreated = false;
1641 bool effectCreated = false;
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001642 audio_unique_id_t effectId = AUDIO_UNIQUE_ID_USE_UNSPECIFIED;
Eric Laurent81784c32012-11-19 14:55:58 -08001643
1644 lStatus = initCheck();
1645 if (lStatus != NO_ERROR) {
1646 ALOGW("createEffect_l() Audio driver not initialized.");
1647 goto Exit;
1648 }
1649
Eric Laurent81784c32012-11-19 14:55:58 -08001650 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
1651
Andy Hungc5007f82023-08-29 14:26:09 -07001652 { // scope for mutex()
Andy Hung972bec12023-08-31 16:13:39 -07001653 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001654
Eric Laurent4c415062016-06-17 16:14:16 -07001655 lStatus = checkEffectCompatibility_l(desc, sessionId);
Eric Laurent2fe0acd2020-03-13 14:30:46 -07001656 if (probe || lStatus != NO_ERROR) {
Eric Laurent4c415062016-06-17 16:14:16 -07001657 goto Exit;
1658 }
1659
Eric Laurent81784c32012-11-19 14:55:58 -08001660 // check for existing effect chain with the requested audio session
1661 chain = getEffectChain_l(sessionId);
1662 if (chain == 0) {
1663 // create a new chain for this session
1664 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
François Gaffie541fd402023-11-29 17:16:38 +01001665 chain = IAfEffectChain::create(this, sessionId, mAfThreadCallback);
Eric Laurent81784c32012-11-19 14:55:58 -08001666 addEffectChain_l(chain);
1667 chain->setStrategy(getStrategyForSession_l(sessionId));
1668 chainCreated = true;
1669 } else {
François Gaffie541fd402023-11-29 17:16:38 +01001670 effect = chain->getEffectFromDesc(desc);
Eric Laurent81784c32012-11-19 14:55:58 -08001671 }
1672
1673 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
1674
1675 if (effect == 0) {
Andy Hung583043b2023-07-17 17:05:00 -07001676 effectId = mAfThreadCallback->nextUniqueId(AUDIO_UNIQUE_ID_USE_EFFECT);
Eric Laurent81784c32012-11-19 14:55:58 -08001677 // create a new effect module if none present in the chain
François Gaffie541fd402023-11-29 17:16:38 +01001678 lStatus = chain->createEffect(effect, desc, effectId, sessionId, pinned);
Eric Laurent81784c32012-11-19 14:55:58 -08001679 if (lStatus != NO_ERROR) {
1680 goto Exit;
1681 }
1682 effectCreated = true;
1683
jiabinc52b1ff2019-10-31 17:20:42 -07001684 // FIXME: use vector of device and address when effect interface is ready.
jiabin8f278ee2019-11-11 12:16:27 -08001685 effect->setDevices(outDeviceTypeAddrs());
1686 effect->setInputDevice(inDeviceTypeAddr());
Andy Hung583043b2023-07-17 17:05:00 -07001687 effect->setMode(mAfThreadCallback->getMode());
Eric Laurent81784c32012-11-19 14:55:58 -08001688 effect->setAudioSource(mAudioSource);
1689 }
jiabin1319f5a2021-03-30 22:21:24 +00001690 if (effect->isHapticGenerator()) {
1691 // TODO(b/184194057): Use the vibrator information from the vibrator that will be used
1692 // for the HapticGenerator.
Lais Andradebc3f37a2021-07-02 00:13:19 +01001693 const std::optional<media::AudioVibratorInfo> defaultVibratorInfo =
Andy Hung583043b2023-07-17 17:05:00 -07001694 std::move(mAfThreadCallback->getDefaultVibratorInfo_l());
Lais Andradebc3f37a2021-07-02 00:13:19 +01001695 if (defaultVibratorInfo) {
François Gaffie541fd402023-11-29 17:16:38 +01001696 audio_utils::lock_guard _cl(chain->mutex());
jiabin1319f5a2021-03-30 22:21:24 +00001697 // Only set the vibrator info when it is a valid one.
Shunkai Yaod125e402024-01-20 03:19:06 +00001698 effect->setVibratorInfo_l(*defaultVibratorInfo);
jiabin1319f5a2021-03-30 22:21:24 +00001699 }
1700 }
Eric Laurent81784c32012-11-19 14:55:58 -08001701 // create effect handle and connect it to effect module
Andy Hung116bc262023-06-20 18:56:17 -07001702 handle = IAfEffectHandle::create(
1703 effect, client, effectClient, priority, notifyFramesProcessed);
Glenn Kastene75da402013-11-20 13:54:52 -08001704 lStatus = handle->initCheck();
1705 if (lStatus == OK) {
1706 lStatus = effect->addHandle(handle.get());
Eric Laurentb3f315a2021-07-13 15:09:05 +02001707 sendCheckOutputStageEffectsEvent_l();
Glenn Kastene75da402013-11-20 13:54:52 -08001708 }
Eric Laurent81784c32012-11-19 14:55:58 -08001709 if (enabled != NULL) {
1710 *enabled = (int)effect->isEnabled();
1711 }
1712 }
1713
1714Exit:
Eric Laurent2fe0acd2020-03-13 14:30:46 -07001715 if (!probe && lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Andy Hung972bec12023-08-31 16:13:39 -07001716 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001717 if (effectCreated) {
François Gaffie541fd402023-11-29 17:16:38 +01001718 chain->removeEffect(effect);
Eric Laurent81784c32012-11-19 14:55:58 -08001719 }
Eric Laurent81784c32012-11-19 14:55:58 -08001720 if (chainCreated) {
1721 removeEffectChain_l(chain);
1722 }
haobo101735295ff7b0d2017-03-17 17:44:03 +08001723 // handle must be cleared by caller to avoid deadlock.
Eric Laurent81784c32012-11-19 14:55:58 -08001724 }
1725
Glenn Kasten9156ef32013-08-06 15:39:08 -07001726 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001727 return handle;
1728}
1729
Andy Hungee58e4a2023-07-07 13:47:37 -07001730void ThreadBase::disconnectEffectHandle(IAfEffectHandle* handle,
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001731 bool unpinIfLast)
1732{
1733 bool remove = false;
Andy Hung116bc262023-06-20 18:56:17 -07001734 sp<IAfEffectModule> effect;
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001735 {
Andy Hung972bec12023-08-31 16:13:39 -07001736 audio_utils::lock_guard _l(mutex());
Andy Hung116bc262023-06-20 18:56:17 -07001737 sp<IAfEffectBase> effectBase = handle->effect().promote();
Eric Laurent41709552019-12-16 19:34:05 -08001738 if (effectBase == nullptr) {
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001739 return;
1740 }
Eric Laurentb82e6b72019-11-22 17:25:04 -08001741 effect = effectBase->asEffectModule();
1742 if (effect == nullptr) {
1743 return;
1744 }
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001745 // restore suspended effects if the disconnected handle was enabled and the last one.
1746 remove = (effect->removeHandle(handle) == 0) && (!effect->isPinned() || unpinIfLast);
1747 if (remove) {
1748 removeEffect_l(effect, true);
1749 }
Eric Laurentb3f315a2021-07-13 15:09:05 +02001750 sendCheckOutputStageEffectsEvent_l();
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001751 }
1752 if (remove) {
Andy Hung583043b2023-07-17 17:05:00 -07001753 mAfThreadCallback->updateOrphanEffectChains(effect);
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001754 if (handle->enabled()) {
Eric Laurent6b446ce2019-12-13 10:56:31 -08001755 effect->checkSuspendOnEffectEnabled(false, false /*threadLocked*/);
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001756 }
1757 }
1758}
1759
Andy Hungee58e4a2023-07-07 13:47:37 -07001760void ThreadBase::onEffectEnable(const sp<IAfEffectModule>& effect) {
Andy Hungea840382020-05-05 21:50:17 -07001761 if (isOffloadOrMmap()) {
Andy Hung972bec12023-08-31 16:13:39 -07001762 audio_utils::lock_guard _l(mutex());
Eric Laurent6b446ce2019-12-13 10:56:31 -08001763 broadcast_l();
1764 }
1765 if (!effect->isOffloadable()) {
1766 if (mType == ThreadBase::OFFLOAD) {
1767 PlaybackThread *t = (PlaybackThread *)this;
1768 t->invalidateTracks(AUDIO_STREAM_MUSIC);
1769 }
1770 if (effect->sessionId() == AUDIO_SESSION_OUTPUT_MIX) {
Andy Hung583043b2023-07-17 17:05:00 -07001771 mAfThreadCallback->onNonOffloadableGlobalEffectEnable();
Eric Laurent6b446ce2019-12-13 10:56:31 -08001772 }
1773 }
1774}
1775
Andy Hungee58e4a2023-07-07 13:47:37 -07001776void ThreadBase::onEffectDisable() {
Andy Hungea840382020-05-05 21:50:17 -07001777 if (isOffloadOrMmap()) {
Andy Hung972bec12023-08-31 16:13:39 -07001778 audio_utils::lock_guard _l(mutex());
Eric Laurent6b446ce2019-12-13 10:56:31 -08001779 broadcast_l();
1780 }
1781}
1782
Andy Hungee58e4a2023-07-07 13:47:37 -07001783sp<IAfEffectModule> ThreadBase::getEffect(audio_session_t sessionId,
Andy Hung440901d2023-06-29 21:19:25 -07001784 int effectId) const
Eric Laurent81784c32012-11-19 14:55:58 -08001785{
Andy Hung972bec12023-08-31 16:13:39 -07001786 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001787 return getEffect_l(sessionId, effectId);
1788}
1789
Andy Hungee58e4a2023-07-07 13:47:37 -07001790sp<IAfEffectModule> ThreadBase::getEffect_l(audio_session_t sessionId,
Andy Hung440901d2023-06-29 21:19:25 -07001791 int effectId) const
Eric Laurent81784c32012-11-19 14:55:58 -08001792{
Andy Hung116bc262023-06-20 18:56:17 -07001793 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08001794 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
1795}
1796
Andy Hungee58e4a2023-07-07 13:47:37 -07001797std::vector<int> ThreadBase::getEffectIds_l(audio_session_t sessionId) const
Eric Laurent6c796322019-04-09 14:13:17 -07001798{
Andy Hung116bc262023-06-20 18:56:17 -07001799 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Shunkai Yaod125e402024-01-20 03:19:06 +00001800 return chain != nullptr ? chain->getEffectIds_l() : std::vector<int>{};
Eric Laurent6c796322019-04-09 14:13:17 -07001801}
1802
Andy Hung972bec12023-08-31 16:13:39 -07001803// PlaybackThread::addEffect_ll() must be called with AudioFlinger::mutex() and
1804// ThreadBase::mutex() held
1805status_t ThreadBase::addEffect_ll(const sp<IAfEffectModule>& effect)
Eric Laurent81784c32012-11-19 14:55:58 -08001806{
1807 // check for existing effect chain with the requested audio session
Glenn Kastend848eb42016-03-08 13:42:11 -08001808 audio_session_t sessionId = effect->sessionId();
Andy Hung116bc262023-06-20 18:56:17 -07001809 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08001810 bool chainCreated = false;
1811
Eric Laurent5baf2af2013-09-12 17:37:00 -07001812 ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(),
Andy Hung972bec12023-08-31 16:13:39 -07001813 "%s: on offloaded thread %p: effect %s does not support offload flags %#x",
1814 __func__, this, effect->desc().name, effect->desc().flags);
Eric Laurent5baf2af2013-09-12 17:37:00 -07001815
Eric Laurent81784c32012-11-19 14:55:58 -08001816 if (chain == 0) {
1817 // create a new chain for this session
Andy Hung972bec12023-08-31 16:13:39 -07001818 ALOGV("%s: new effect chain for session %d", __func__, sessionId);
François Gaffie541fd402023-11-29 17:16:38 +01001819 chain = IAfEffectChain::create(this, sessionId, mAfThreadCallback);
Eric Laurent81784c32012-11-19 14:55:58 -08001820 addEffectChain_l(chain);
1821 chain->setStrategy(getStrategyForSession_l(sessionId));
1822 chainCreated = true;
1823 }
Andy Hung972bec12023-08-31 16:13:39 -07001824 ALOGV("%s: %p chain %p effect %p", __func__, this, chain.get(), effect.get());
Eric Laurent81784c32012-11-19 14:55:58 -08001825
1826 if (chain->getEffectFromId_l(effect->id()) != 0) {
Andy Hung972bec12023-08-31 16:13:39 -07001827 ALOGW("%s: %p effect %s already present in chain %p",
1828 __func__, this, effect->desc().name, chain.get());
Eric Laurent81784c32012-11-19 14:55:58 -08001829 return BAD_VALUE;
1830 }
1831
Shunkai Yaod125e402024-01-20 03:19:06 +00001832 effect->setOffloaded_l(mType == OFFLOAD, mId);
Eric Laurent5baf2af2013-09-12 17:37:00 -07001833
François Gaffie541fd402023-11-29 17:16:38 +01001834 status_t status = chain->addEffect(effect);
Eric Laurent81784c32012-11-19 14:55:58 -08001835 if (status != NO_ERROR) {
1836 if (chainCreated) {
1837 removeEffectChain_l(chain);
1838 }
1839 return status;
1840 }
1841
jiabin8f278ee2019-11-11 12:16:27 -08001842 effect->setDevices(outDeviceTypeAddrs());
1843 effect->setInputDevice(inDeviceTypeAddr());
Andy Hung583043b2023-07-17 17:05:00 -07001844 effect->setMode(mAfThreadCallback->getMode());
Eric Laurent81784c32012-11-19 14:55:58 -08001845 effect->setAudioSource(mAudioSource);
Eric Laurentd8365c52017-07-16 15:27:05 -07001846
Eric Laurent81784c32012-11-19 14:55:58 -08001847 return NO_ERROR;
1848}
1849
Andy Hungee58e4a2023-07-07 13:47:37 -07001850void ThreadBase::removeEffect_l(const sp<IAfEffectModule>& effect, bool release) {
Eric Laurent81784c32012-11-19 14:55:58 -08001851
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001852 ALOGV("%s %p effect %p", __FUNCTION__, this, effect.get());
Eric Laurent81784c32012-11-19 14:55:58 -08001853 effect_descriptor_t desc = effect->desc();
1854 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
1855 detachAuxEffect_l(effect->id());
1856 }
1857
Andy Hung116bc262023-06-20 18:56:17 -07001858 sp<IAfEffectChain> chain = effect->getCallback()->chain().promote();
Eric Laurent81784c32012-11-19 14:55:58 -08001859 if (chain != 0) {
1860 // remove effect chain if removing last effect
François Gaffie541fd402023-11-29 17:16:38 +01001861 if (chain->removeEffect(effect, release) == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08001862 removeEffectChain_l(chain);
1863 }
1864 } else {
1865 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
1866 }
1867}
1868
Shunkai Yaof4847652024-01-12 00:25:20 +00001869void ThreadBase::lockEffectChains_l(Vector<sp<IAfEffectChain>>& effectChains)
1870 NO_THREAD_SAFETY_ANALYSIS // calls EffectChain::lock()
Eric Laurent81784c32012-11-19 14:55:58 -08001871{
1872 effectChains = mEffectChains;
Shunkai Yaof4847652024-01-12 00:25:20 +00001873 for (const auto& effectChain : effectChains) {
1874 effectChain->mutex().lock();
Eric Laurent81784c32012-11-19 14:55:58 -08001875 }
1876}
1877
Shunkai Yaof4847652024-01-12 00:25:20 +00001878void ThreadBase::unlockEffectChains(const Vector<sp<IAfEffectChain>>& effectChains)
1879 NO_THREAD_SAFETY_ANALYSIS // calls EffectChain::unlock()
Eric Laurent81784c32012-11-19 14:55:58 -08001880{
Shunkai Yaof4847652024-01-12 00:25:20 +00001881 for (const auto& effectChain : effectChains) {
1882 effectChain->mutex().unlock();
Eric Laurent81784c32012-11-19 14:55:58 -08001883 }
1884}
1885
Andy Hungee58e4a2023-07-07 13:47:37 -07001886sp<IAfEffectChain> ThreadBase::getEffectChain(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08001887{
Andy Hung972bec12023-08-31 16:13:39 -07001888 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001889 return getEffectChain_l(sessionId);
1890}
1891
Andy Hungee58e4a2023-07-07 13:47:37 -07001892sp<IAfEffectChain> ThreadBase::getEffectChain_l(audio_session_t sessionId)
Glenn Kastend848eb42016-03-08 13:42:11 -08001893 const
Eric Laurent81784c32012-11-19 14:55:58 -08001894{
1895 size_t size = mEffectChains.size();
1896 for (size_t i = 0; i < size; i++) {
1897 if (mEffectChains[i]->sessionId() == sessionId) {
1898 return mEffectChains[i];
1899 }
1900 }
1901 return 0;
1902}
1903
Andy Hungee58e4a2023-07-07 13:47:37 -07001904void ThreadBase::setMode(audio_mode_t mode)
Eric Laurent81784c32012-11-19 14:55:58 -08001905{
Andy Hung972bec12023-08-31 16:13:39 -07001906 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001907 size_t size = mEffectChains.size();
1908 for (size_t i = 0; i < size; i++) {
1909 mEffectChains[i]->setMode_l(mode);
1910 }
1911}
1912
Andy Hungee58e4a2023-07-07 13:47:37 -07001913void ThreadBase::toAudioPortConfig(struct audio_port_config* config)
Eric Laurent83b88082014-06-20 18:31:16 -07001914{
1915 config->type = AUDIO_PORT_TYPE_MIX;
1916 config->ext.mix.handle = mId;
1917 config->sample_rate = mSampleRate;
Mikhail Naganov88d54da2023-09-11 11:53:50 -07001918 config->format = mHALFormat;
Eric Laurent83b88082014-06-20 18:31:16 -07001919 config->channel_mask = mChannelMask;
1920 config->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
1921 AUDIO_PORT_CONFIG_FORMAT;
1922}
1923
Andy Hungee58e4a2023-07-07 13:47:37 -07001924void ThreadBase::systemReady()
Eric Laurent72e3f392015-05-20 14:43:50 -07001925{
Andy Hung972bec12023-08-31 16:13:39 -07001926 audio_utils::lock_guard _l(mutex());
Eric Laurent72e3f392015-05-20 14:43:50 -07001927 if (mSystemReady) {
1928 return;
1929 }
1930 mSystemReady = true;
1931
1932 for (size_t i = 0; i < mPendingConfigEvents.size(); i++) {
1933 sendConfigEvent_l(mPendingConfigEvents.editItemAt(i));
1934 }
1935 mPendingConfigEvents.clear();
1936}
1937
Andy Hungdae27702016-10-31 14:01:16 -07001938template <typename T>
Andy Hungee58e4a2023-07-07 13:47:37 -07001939ssize_t ThreadBase::ActiveTracks<T>::add(const sp<T>& track) {
Andy Hungdae27702016-10-31 14:01:16 -07001940 ssize_t index = mActiveTracks.indexOf(track);
1941 if (index >= 0) {
1942 ALOGW("ActiveTracks<T>::add track %p already there", track.get());
1943 return index;
1944 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001945 logTrack("add", track);
Andy Hungdae27702016-10-31 14:01:16 -07001946 mActiveTracksGeneration++;
1947 mLatestActiveTrack = track;
Atneya Nair166663a2023-06-27 19:16:24 -07001948 track->beginBatteryAttribution();
Kevin Rocard069c2712018-03-29 19:09:14 -07001949 mHasChanged = true;
Andy Hungdae27702016-10-31 14:01:16 -07001950 return mActiveTracks.add(track);
1951}
1952
1953template <typename T>
Andy Hungee58e4a2023-07-07 13:47:37 -07001954ssize_t ThreadBase::ActiveTracks<T>::remove(const sp<T>& track) {
Andy Hungdae27702016-10-31 14:01:16 -07001955 ssize_t index = mActiveTracks.remove(track);
1956 if (index < 0) {
1957 ALOGW("ActiveTracks<T>::remove nonexistent track %p", track.get());
1958 return index;
1959 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001960 logTrack("remove", track);
Andy Hungdae27702016-10-31 14:01:16 -07001961 mActiveTracksGeneration++;
Atneya Nair166663a2023-06-27 19:16:24 -07001962 track->endBatteryAttribution();
Andy Hungdae27702016-10-31 14:01:16 -07001963 // mLatestActiveTrack is not cleared even if is the same as track.
Kevin Rocard069c2712018-03-29 19:09:14 -07001964 mHasChanged = true;
Andy Hung8946a282018-04-19 20:04:56 -07001965#ifdef TEE_SINK
1966 track->dumpTee(-1 /* fd */, "_REMOVE");
1967#endif
Andy Hungc2b11cb2020-04-22 09:04:01 -07001968 track->logEndInterval(); // log to MediaMetrics
Andy Hungdae27702016-10-31 14:01:16 -07001969 return index;
1970}
1971
1972template <typename T>
Andy Hungee58e4a2023-07-07 13:47:37 -07001973void ThreadBase::ActiveTracks<T>::clear() {
Andy Hungdae27702016-10-31 14:01:16 -07001974 for (const sp<T> &track : mActiveTracks) {
Atneya Nair166663a2023-06-27 19:16:24 -07001975 track->endBatteryAttribution();
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001976 logTrack("clear", track);
Andy Hungdae27702016-10-31 14:01:16 -07001977 }
1978 mLastActiveTracksGeneration = mActiveTracksGeneration;
Kevin Rocard069c2712018-03-29 19:09:14 -07001979 if (!mActiveTracks.empty()) { mHasChanged = true; }
Andy Hungdae27702016-10-31 14:01:16 -07001980 mActiveTracks.clear();
1981 mLatestActiveTrack.clear();
Andy Hungdae27702016-10-31 14:01:16 -07001982}
1983
1984template <typename T>
Andy Hungab65b182023-09-06 19:41:47 -07001985void ThreadBase::ActiveTracks<T>::updatePowerState_l(
Andy Hung920f6572022-10-06 12:09:49 -07001986 const sp<ThreadBase>& thread, bool force) {
Andy Hungdae27702016-10-31 14:01:16 -07001987 // Updates ActiveTracks client uids to the thread wakelock.
1988 if (mActiveTracksGeneration != mLastActiveTracksGeneration || force) {
1989 thread->updateWakeLockUids_l(getWakeLockUids());
1990 mLastActiveTracksGeneration = mActiveTracksGeneration;
1991 }
Andy Hungdae27702016-10-31 14:01:16 -07001992}
Eric Laurent83b88082014-06-20 18:31:16 -07001993
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001994template <typename T>
Andy Hungee58e4a2023-07-07 13:47:37 -07001995bool ThreadBase::ActiveTracks<T>::readAndClearHasChanged() {
Jasmine Chaeaa10e42021-05-11 10:11:14 +08001996 bool hasChanged = mHasChanged;
Kevin Rocard069c2712018-03-29 19:09:14 -07001997 mHasChanged = false;
Jasmine Chaeaa10e42021-05-11 10:11:14 +08001998
1999 for (const sp<T> &track : mActiveTracks) {
2000 // Do not short-circuit as all hasChanged states must be reset
2001 // as all the metadata are going to be sent
2002 hasChanged |= track->readAndClearHasChanged();
2003 }
Kevin Rocard069c2712018-03-29 19:09:14 -07002004 return hasChanged;
2005}
2006
2007template <typename T>
Andy Hungee58e4a2023-07-07 13:47:37 -07002008void ThreadBase::ActiveTracks<T>::logTrack(
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002009 const char *funcName, const sp<T> &track) const {
2010 if (mLocalLog != nullptr) {
2011 String8 result;
2012 track->appendDump(result, false /* active */);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00002013 mLocalLog->log("AT::%-10s(%p) %s", funcName, track.get(), result.c_str());
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002014 }
2015}
2016
Andy Hungee58e4a2023-07-07 13:47:37 -07002017void ThreadBase::broadcast_l()
Eric Laurent6acd1d42017-01-04 14:23:29 -08002018{
2019 // Thread could be blocked waiting for async
2020 // so signal it to handle state changes immediately
2021 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
2022 // be lost so we also flag to prevent it blocking on mWaitWorkCV
2023 mSignalPending = true;
Andy Hungc5007f82023-08-29 14:26:09 -07002024 mWaitWorkCV.notify_all();
Eric Laurent6acd1d42017-01-04 14:23:29 -08002025}
2026
Andy Hungd0979812019-02-21 15:51:44 -08002027// Call only from threadLoop() or when it is idle.
2028// Do not call from high performance code as this may do binder rpc to the MediaMetrics service.
Andy Hungee58e4a2023-07-07 13:47:37 -07002029void ThreadBase::sendStatistics(bool force)
Andy Hungab65b182023-09-06 19:41:47 -07002030NO_THREAD_SAFETY_ANALYSIS
Andy Hungd0979812019-02-21 15:51:44 -08002031{
2032 // Do not log if we have no stats.
2033 // We choose the timestamp verifier because it is the most likely item to be present.
2034 const int64_t nstats = mTimestampVerifier.getN() - mLastRecordedTimestampVerifierN;
2035 if (nstats == 0) {
2036 return;
2037 }
2038
2039 // Don't log more frequently than once per 12 hours.
2040 // We use BOOTTIME to include suspend time.
2041 const int64_t timeNs = systemTime(SYSTEM_TIME_BOOTTIME);
2042 const int64_t sinceNs = timeNs - mLastRecordedTimeNs; // ok if mLastRecordedTimeNs = 0
2043 if (!force && sinceNs <= 12 * NANOS_PER_HOUR) {
2044 return;
2045 }
2046
2047 mLastRecordedTimestampVerifierN = mTimestampVerifier.getN();
2048 mLastRecordedTimeNs = timeNs;
2049
Ray Essickf27e9872019-12-07 06:28:46 -08002050 std::unique_ptr<mediametrics::Item> item(mediametrics::Item::create("audiothread"));
Andy Hungd0979812019-02-21 15:51:44 -08002051
2052#define MM_PREFIX "android.media.audiothread." // avoid cut-n-paste errors.
2053
2054 // thread configuration
2055 item->setInt32(MM_PREFIX "id", (int32_t)mId); // IO handle
2056 // item->setInt32(MM_PREFIX "portId", (int32_t)mPortId);
2057 item->setCString(MM_PREFIX "type", threadTypeToString(mType));
2058 item->setInt32(MM_PREFIX "sampleRate", (int32_t)mSampleRate);
2059 item->setInt64(MM_PREFIX "channelMask", (int64_t)mChannelMask);
2060 item->setCString(MM_PREFIX "encoding", toString(mFormat).c_str());
2061 item->setInt32(MM_PREFIX "frameCount", (int32_t)mFrameCount);
Andy Hungab65b182023-09-06 19:41:47 -07002062 item->setCString(MM_PREFIX "outDevice", toString(outDeviceTypes_l()).c_str());
2063 item->setCString(MM_PREFIX "inDevice", toString(inDeviceType_l()).c_str());
Andy Hungd0979812019-02-21 15:51:44 -08002064
2065 // thread statistics
2066 if (mIoJitterMs.getN() > 0) {
2067 item->setDouble(MM_PREFIX "ioJitterMs.mean", mIoJitterMs.getMean());
2068 item->setDouble(MM_PREFIX "ioJitterMs.std", mIoJitterMs.getStdDev());
2069 }
2070 if (mProcessTimeMs.getN() > 0) {
2071 item->setDouble(MM_PREFIX "processTimeMs.mean", mProcessTimeMs.getMean());
2072 item->setDouble(MM_PREFIX "processTimeMs.std", mProcessTimeMs.getStdDev());
2073 }
2074 const auto tsjitter = mTimestampVerifier.getJitterMs();
2075 if (tsjitter.getN() > 0) {
2076 item->setDouble(MM_PREFIX "timestampJitterMs.mean", tsjitter.getMean());
2077 item->setDouble(MM_PREFIX "timestampJitterMs.std", tsjitter.getStdDev());
2078 }
2079 if (mLatencyMs.getN() > 0) {
2080 item->setDouble(MM_PREFIX "latencyMs.mean", mLatencyMs.getMean());
2081 item->setDouble(MM_PREFIX "latencyMs.std", mLatencyMs.getStdDev());
2082 }
Robert Wu06db0a32021-08-10 19:05:34 +00002083 if (mMonopipePipeDepthStats.getN() > 0) {
2084 item->setDouble(MM_PREFIX "monopipePipeDepthStats.mean",
2085 mMonopipePipeDepthStats.getMean());
2086 item->setDouble(MM_PREFIX "monopipePipeDepthStats.std",
2087 mMonopipePipeDepthStats.getStdDev());
2088 }
Andy Hungd0979812019-02-21 15:51:44 -08002089
2090 item->selfrecord();
2091}
2092
Andy Hungee58e4a2023-07-07 13:47:37 -07002093product_strategy_t ThreadBase::getStrategyForStream(audio_stream_type_t stream) const
Eric Laurentd66d7a12021-07-13 13:35:32 +02002094{
Andy Hung583043b2023-07-17 17:05:00 -07002095 if (!mAfThreadCallback->isAudioPolicyReady()) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02002096 return PRODUCT_STRATEGY_NONE;
2097 }
2098 return AudioSystem::getStrategyForStream(stream);
2099}
2100
Andy Hungc5007f82023-08-29 14:26:09 -07002101// startMelComputation_l() must be called with AudioFlinger::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07002102void ThreadBase::startMelComputation_l(
Vlad Popa6fbbfbf2023-02-22 15:05:43 +01002103 const sp<audio_utils::MelProcessor>& /*processor*/)
2104{
2105 // Do nothing
2106 ALOGW("%s: ThreadBase does not support CSD", __func__);
2107}
2108
Andy Hungc5007f82023-08-29 14:26:09 -07002109// stopMelComputation_l() must be called with AudioFlinger::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07002110void ThreadBase::stopMelComputation_l()
Vlad Popa6fbbfbf2023-02-22 15:05:43 +01002111{
2112 // Do nothing
2113 ALOGW("%s: ThreadBase does not support CSD", __func__);
2114}
2115
Eric Laurent81784c32012-11-19 14:55:58 -08002116// ----------------------------------------------------------------------------
2117// Playback
2118// ----------------------------------------------------------------------------
2119
Andy Hung583043b2023-07-17 17:05:00 -07002120PlaybackThread::PlaybackThread(const sp<IAfThreadCallback>& afThreadCallback,
Eric Laurent81784c32012-11-19 14:55:58 -08002121 AudioStreamOut* output,
2122 audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -07002123 type_t type,
Eric Laurentf1f22e72021-07-13 14:04:14 +02002124 bool systemReady,
2125 audio_config_base_t *mixerConfig)
Andy Hung583043b2023-07-17 17:05:00 -07002126 : ThreadBase(afThreadCallback, id, type, systemReady, true /* isOut */),
Andy Hung2098f272014-02-27 14:00:06 -08002127 mNormalFrameCount(0), mSinkBuffer(NULL),
Andy Hung81994d62023-07-20 21:44:14 -07002128 mMixerBufferEnabled(kEnableExtendedPrecision || type == SPATIALIZER),
Andy Hung69aed5f2014-02-25 17:24:40 -08002129 mMixerBuffer(NULL),
2130 mMixerBufferSize(0),
2131 mMixerBufferFormat(AUDIO_FORMAT_INVALID),
2132 mMixerBufferValid(false),
Andy Hung81994d62023-07-20 21:44:14 -07002133 mEffectBufferEnabled(kEnableExtendedPrecision || type == SPATIALIZER),
Andy Hung98ef9782014-03-04 14:46:50 -08002134 mEffectBuffer(NULL),
2135 mEffectBufferSize(0),
2136 mEffectBufferFormat(AUDIO_FORMAT_INVALID),
2137 mEffectBufferValid(false),
Glenn Kastenc1fac192013-08-06 07:41:36 -07002138 mSuspended(0), mBytesWritten(0),
Andy Hungc54b1ff2016-02-23 14:07:07 -08002139 mFramesWritten(0),
Andy Hung238fa3d2016-07-28 10:53:22 -07002140 mSuspendedFrames(0),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002141 mActiveTracks(&this->mLocalLog),
Eric Laurent81784c32012-11-19 14:55:58 -08002142 // mStreamTypes[] initialized in constructor body
Andy Hung1bc088a2018-02-09 15:57:31 -08002143 mTracks(type == MIXER),
Eric Laurent81784c32012-11-19 14:55:58 -08002144 mOutput(output),
Andy Hung446f4df2019-02-21 12:26:41 -08002145 mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
Eric Laurent81784c32012-11-19 14:55:58 -08002146 mMixerStatus(MIXER_IDLE),
2147 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
Andy Hung8fe87eb2023-07-20 21:31:38 -07002148 mStandbyDelayNs(getStandbyTimeInNanos()),
Eric Laurentbfb1b832013-01-07 09:53:42 -08002149 mBytesRemaining(0),
2150 mCurrentWriteLength(0),
2151 mUseAsyncWrite(false),
Eric Laurent3b4529e2013-09-05 18:09:19 -07002152 mWriteAckSequence(0),
2153 mDrainSequence(0),
Andy Hung1d2d2aea2023-07-19 16:22:58 -07002154 mScreenState(mAfThreadCallback->getScreenState()),
Eric Laurent81784c32012-11-19 14:55:58 -08002155 // index 0 is reserved for normal mixer's submix
Glenn Kastendc2c50b2016-04-21 08:13:14 -07002156 mFastTrackAvailMask(((1 << FastMixerState::sMaxFastTracks) - 1) & ~1),
Eric Laurent7c29ec92017-09-20 17:54:22 -07002157 mHwSupportsPause(false), mHwPaused(false), mFlushPending(false),
Eric Laurent74c38dc2020-12-23 18:19:44 +01002158 mLeftVolFloat(-1.0), mRightVolFloat(-1.0),
Brian Lindahl65e90012022-07-27 18:01:07 +02002159 mDownStreamPatch{},
Eric Laurentb0463942022-12-20 16:31:10 +01002160 mIsTimestampAdvancing(kMinimumTimeBetweenTimestampChecksNs)
Eric Laurent81784c32012-11-19 14:55:58 -08002161{
Glenn Kastend7dca052015-03-05 16:05:54 -08002162 snprintf(mThreadName, kThreadNameLength, "AudioOut_%X", id);
Andy Hung583043b2023-07-17 17:05:00 -07002163 mNBLogWriter = afThreadCallback->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08002164
Andy Hungc5007f82023-08-29 14:26:09 -07002165 // Assumes constructor is called by AudioFlinger with its mutex() held, but
Eric Laurent81784c32012-11-19 14:55:58 -08002166 // it would be safer to explicitly pass initial masterVolume/masterMute as
2167 // parameter.
2168 //
2169 // If the HAL we are using has support for master volume or master mute,
2170 // then do not attenuate or mute during mixing (just leave the volume at 1.0
2171 // and the mute set to false).
Andy Hung583043b2023-07-17 17:05:00 -07002172 mMasterVolume = afThreadCallback->masterVolume_l();
2173 mMasterMute = afThreadCallback->masterMute_l();
George Burgess IV5e4d86f2020-02-18 12:55:36 -08002174 if (mOutput->audioHwDev) {
Eric Laurent81784c32012-11-19 14:55:58 -08002175 if (mOutput->audioHwDev->canSetMasterVolume()) {
2176 mMasterVolume = 1.0;
2177 }
2178
2179 if (mOutput->audioHwDev->canSetMasterMute()) {
2180 mMasterMute = false;
2181 }
Andy Hungc8fddf32018-08-08 18:32:37 -07002182 mIsMsdDevice = strcmp(
2183 mOutput->audioHwDev->moduleName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002184 }
2185
Eric Laurentf1f22e72021-07-13 14:04:14 +02002186 if (mixerConfig != nullptr && mixerConfig->channel_mask != AUDIO_CHANNEL_NONE) {
2187 mMixerChannelMask = mixerConfig->channel_mask;
2188 }
2189
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002190 readOutputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002191
Eric Laurent1c5e2e32021-08-18 18:50:28 +02002192 if (mType != SPATIALIZER
Eric Laurentb3f315a2021-07-13 15:09:05 +02002193 && mMixerChannelMask != mChannelMask) {
2194 LOG_ALWAYS_FATAL("HAL channel mask %#x does not match mixer channel mask %#x",
2195 mChannelMask, mMixerChannelMask);
2196 }
2197
Andy Hungc8fddf32018-08-08 18:32:37 -07002198 // TODO: We may also match on address as well as device type for
2199 // AUDIO_DEVICE_OUT_BUS, AUDIO_DEVICE_OUT_ALL_A2DP, AUDIO_DEVICE_OUT_REMOTE_SUBMIX
Dean Wheatleyf8726f02019-12-02 14:12:01 +11002200 if (type == MIXER || type == DIRECT || type == OFFLOAD) {
jiabinc52b1ff2019-10-31 17:20:42 -07002201 // TODO: This property should be ensure that only contains one single device type.
2202 mTimestampCorrectedDevice = (audio_devices_t)property_get_int64(
2203 "audio.timestamp.corrected_output_device",
Andy Hungc8fddf32018-08-08 18:32:37 -07002204 (int64_t)(mIsMsdDevice ? AUDIO_DEVICE_OUT_BUS // turn on by default for MSD
2205 : AUDIO_DEVICE_NONE));
2206 }
2207
Mikhail Naganovf33115d2020-09-25 23:03:05 +00002208 for (int i = AUDIO_STREAM_MIN; i < AUDIO_STREAM_FOR_POLICY_CNT; ++i) {
2209 const audio_stream_type_t stream{static_cast<audio_stream_type_t>(i)};
Eric Laurent98e38192018-02-15 18:31:53 -08002210 mStreamTypes[stream].volume = 0.0f;
Andy Hung583043b2023-07-17 17:05:00 -07002211 mStreamTypes[stream].mute = mAfThreadCallback->streamMute_l(stream);
Eric Laurent81784c32012-11-19 14:55:58 -08002212 }
Eric Laurent35f8c7c2020-02-08 11:42:35 -08002213 // Audio patch and call assistant volume are always max
Eric Laurent98e38192018-02-15 18:31:53 -08002214 mStreamTypes[AUDIO_STREAM_PATCH].volume = 1.0f;
2215 mStreamTypes[AUDIO_STREAM_PATCH].mute = false;
Eric Laurent35f8c7c2020-02-08 11:42:35 -08002216 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].volume = 1.0f;
2217 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].mute = false;
Eric Laurent81784c32012-11-19 14:55:58 -08002218}
2219
Andy Hungee58e4a2023-07-07 13:47:37 -07002220PlaybackThread::~PlaybackThread()
Eric Laurent81784c32012-11-19 14:55:58 -08002221{
Andy Hung583043b2023-07-17 17:05:00 -07002222 mAfThreadCallback->unregisterWriter(mNBLogWriter);
Andy Hung010a1a12014-03-13 13:57:33 -07002223 free(mSinkBuffer);
Andy Hung69aed5f2014-02-25 17:24:40 -08002224 free(mMixerBuffer);
Andy Hung98ef9782014-03-04 14:46:50 -08002225 free(mEffectBuffer);
Eric Laurentb62d0362021-10-26 17:40:18 +02002226 free(mPostSpatializerBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08002227}
2228
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002229// Thread virtuals
2230
Andy Hungee58e4a2023-07-07 13:47:37 -07002231void PlaybackThread::onFirstRef()
Eric Laurent81784c32012-11-19 14:55:58 -08002232{
Jasmine Chaeaa10e42021-05-11 10:11:14 +08002233 if (!isStreamInitialized()) {
jiabinf6eb4c32020-02-25 14:06:25 -08002234 ALOGE("The stream is not open yet"); // This should not happen.
2235 } else {
Mikhail Naganovaec565e2023-02-22 16:31:28 -08002236 // Callbacks take strong or weak pointers as a parameter.
2237 // Since PlaybackThread passes itself as a callback handler, it can only
2238 // be done outside of the constructor. Creating weak and especially strong
2239 // pointers to a refcounted object in its own constructor is strongly
2240 // discouraged, see comments in system/core/libutils/include/utils/RefBase.h.
2241 // Even if a function takes a weak pointer, it is possible that it will
2242 // need to convert it to a strong pointer down the line.
2243 if (mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING &&
2244 mOutput->stream->setCallback(this) == OK) {
2245 mUseAsyncWrite = true;
Andy Hungee58e4a2023-07-07 13:47:37 -07002246 mCallbackThread = sp<AsyncCallbackThread>::make(this);
Mikhail Naganovaec565e2023-02-22 16:31:28 -08002247 }
2248
jiabinf6eb4c32020-02-25 14:06:25 -08002249 if (mOutput->stream->setEventCallback(this) != OK) {
jiabinf1a36052020-08-19 14:33:31 -07002250 ALOGD("Failed to add event callback");
jiabinf6eb4c32020-02-25 14:06:25 -08002251 }
2252 }
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002253 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
Andy Hung44d648b2022-04-08 17:33:40 -07002254 mThreadSnapshot.setTid(getTid());
Eric Laurent81784c32012-11-19 14:55:58 -08002255}
2256
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002257// ThreadBase virtuals
Andy Hungee58e4a2023-07-07 13:47:37 -07002258void PlaybackThread::preExit()
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002259{
2260 ALOGV(" preExit()");
Ytai Ben-Tsvi7e0183f2022-02-04 10:49:54 -08002261 status_t result = mOutput->stream->exit();
2262 ALOGE_IF(result != OK, "Error when calling exit(): %d", result);
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002263}
2264
Andy Hungee58e4a2023-07-07 13:47:37 -07002265void PlaybackThread::dumpTracks_l(int fd, const Vector<String16>& /* args */)
Eric Laurent81784c32012-11-19 14:55:58 -08002266{
Eric Laurent81784c32012-11-19 14:55:58 -08002267 String8 result;
2268
Marco Nelissenb2208842014-02-07 14:00:50 -08002269 result.appendFormat(" Stream volumes in dB: ");
Eric Laurent81784c32012-11-19 14:55:58 -08002270 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
2271 const stream_type_t *st = &mStreamTypes[i];
2272 if (i > 0) {
2273 result.appendFormat(", ");
2274 }
2275 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
2276 if (st->mute) {
2277 result.append("M");
2278 }
2279 }
2280 result.append("\n");
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00002281 write(fd, result.c_str(), result.length());
Eric Laurent81784c32012-11-19 14:55:58 -08002282 result.clear();
2283
Eric Laurent81784c32012-11-19 14:55:58 -08002284 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
2285 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
Elliott Hughes87cebad2014-05-22 10:14:43 -07002286 dprintf(fd, " Normal mixer raw underrun counters: partial=%u empty=%u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08002287 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Marco Nelissenb2208842014-02-07 14:00:50 -08002288
2289 size_t numtracks = mTracks.size();
2290 size_t numactive = mActiveTracks.size();
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002291 dprintf(fd, " %zu Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08002292 size_t numactiveseen = 0;
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002293 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08002294 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002295 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002296 result.append(prefix);
Andy Hungf6ab58d2018-05-25 12:50:39 -07002297 mTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08002298 for (size_t i = 0; i < numtracks; ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07002299 sp<IAfTrack> track = mTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08002300 if (track != 0) {
2301 bool active = mActiveTracks.indexOf(track) >= 0;
2302 if (active) {
2303 numactiveseen++;
2304 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002305 result.append(prefix);
2306 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08002307 }
2308 }
2309 } else {
2310 result.append("\n");
2311 }
2312 if (numactiveseen != numactive) {
2313 // some tracks in the active list were not in the tracks list
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002314 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08002315 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002316 result.append(prefix);
Andy Hungf6ab58d2018-05-25 12:50:39 -07002317 mActiveTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08002318 for (size_t i = 0; i < numactive; ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07002319 sp<IAfTrack> track = mActiveTracks[i];
Andy Hungdae27702016-10-31 14:01:16 -07002320 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002321 result.append(prefix);
2322 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08002323 }
2324 }
2325 }
2326
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00002327 write(fd, result.c_str(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08002328}
2329
Andy Hungee58e4a2023-07-07 13:47:37 -07002330void PlaybackThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -08002331{
Andy Hung04cb8f72020-03-20 13:44:33 -07002332 dprintf(fd, " Master volume: %f\n", mMasterVolume);
Mikhail Naganovdfb411f2018-09-11 13:39:56 -07002333 dprintf(fd, " Master mute: %s\n", mMasterMute ? "on" : "off");
Eric Laurentf1f22e72021-07-13 14:04:14 +02002334 dprintf(fd, " Mixer channel Mask: %#x (%s)\n",
2335 mMixerChannelMask, channelMaskToString(mMixerChannelMask, true /* output */).c_str());
jiabin245cdd92018-12-07 17:55:15 -08002336 if (mHapticChannelMask != AUDIO_CHANNEL_NONE) {
2337 dprintf(fd, " Haptic channel mask: %#x (%s)\n", mHapticChannelMask,
2338 channelMaskToString(mHapticChannelMask, true /* output */).c_str());
2339 }
Elliott Hughes87cebad2014-05-22 10:14:43 -07002340 dprintf(fd, " Normal frame count: %zu\n", mNormalFrameCount);
Elliott Hughes87cebad2014-05-22 10:14:43 -07002341 dprintf(fd, " Total writes: %d\n", mNumWrites);
2342 dprintf(fd, " Delayed writes: %d\n", mNumDelayedWrites);
2343 dprintf(fd, " Blocked in write: %s\n", mInWrite ? "yes" : "no");
Andy Hung8d672e02023-09-15 18:19:28 -07002344 dprintf(fd, " Suspend count: %d\n", (int32_t)mSuspended);
Elliott Hughes87cebad2014-05-22 10:14:43 -07002345 dprintf(fd, " Fast track availMask=%#x\n", mFastTrackAvailMask);
Eric Laurent42537be2016-01-08 17:16:42 -08002346 dprintf(fd, " Standby delay ns=%lld\n", (long long)mStandbyDelayNs);
Glenn Kasten97b7b752014-09-28 13:04:24 -07002347 AudioStreamOut *output = mOutput;
2348 audio_output_flags_t flags = output != NULL ? output->flags : AUDIO_OUTPUT_FLAG_NONE;
Mikhail Naganov913d06c2016-11-01 12:49:22 -07002349 dprintf(fd, " AudioStreamOut: %p flags %#x (%s)\n",
Andy Hung9b181952019-02-25 14:53:36 -08002350 output, flags, toString(flags).c_str());
Andy Hungb54c8542016-09-21 12:55:15 -07002351 dprintf(fd, " Frames written: %lld\n", (long long)mFramesWritten);
2352 dprintf(fd, " Suspended frames: %lld\n", (long long)mSuspendedFrames);
2353 if (mPipeSink.get() != nullptr) {
2354 dprintf(fd, " PipeSink frames written: %lld\n", (long long)mPipeSink->framesWritten());
2355 }
2356 if (output != nullptr) {
2357 dprintf(fd, " Hal stream dump:\n");
Andy Hung61589a42021-06-16 09:37:53 -07002358 (void)output->stream->dump(fd, args);
Andy Hungb54c8542016-09-21 12:55:15 -07002359 }
Eric Laurent81784c32012-11-19 14:55:58 -08002360}
2361
Andy Hungc5007f82023-08-29 14:26:09 -07002362// PlaybackThread::createTrack_l() must be called with AudioFlinger::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07002363sp<IAfTrack> PlaybackThread::createTrack_l(
Andy Hung88035ac2023-06-27 17:05:02 -07002364 const sp<Client>& client,
Eric Laurent81784c32012-11-19 14:55:58 -08002365 audio_stream_type_t streamType,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07002366 const audio_attributes_t& attr,
Eric Laurent21da6472017-11-09 16:29:26 -08002367 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08002368 audio_format_t format,
2369 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08002370 size_t *pFrameCount,
Eric Laurent21da6472017-11-09 16:29:26 -08002371 size_t *pNotificationFrameCount,
2372 uint32_t notificationsPerBuffer,
2373 float speed,
Eric Laurent81784c32012-11-19 14:55:58 -08002374 const sp<IMemory>& sharedBuffer,
Glenn Kastend848eb42016-03-08 13:42:11 -08002375 audio_session_t sessionId,
Eric Laurent05067782016-06-01 18:27:28 -07002376 audio_output_flags_t *flags,
Eric Laurent09f1ed22019-04-24 17:45:17 -07002377 pid_t creatorPid,
Svet Ganov33761132021-05-13 22:51:08 +00002378 const AttributionSourceState& attributionSource,
Eric Laurent81784c32012-11-19 14:55:58 -08002379 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002380 status_t *status,
jiabinf6eb4c32020-02-25 14:06:25 -08002381 audio_port_handle_t portId,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02002382 const sp<media::IAudioTrackCallback>& callback,
jiabinc658e452022-10-21 20:52:21 +00002383 bool isSpatialized,
jiabin94ed47c2023-07-27 23:34:20 +00002384 bool isBitPerfect,
2385 audio_output_flags_t *afTrackFlags)
Eric Laurent81784c32012-11-19 14:55:58 -08002386{
Glenn Kasten74935e42013-12-19 08:56:45 -08002387 size_t frameCount = *pFrameCount;
Eric Laurent21da6472017-11-09 16:29:26 -08002388 size_t notificationFrameCount = *pNotificationFrameCount;
Andy Hung8d31fd22023-06-26 19:20:57 -07002389 sp<IAfTrack> track;
Eric Laurent81784c32012-11-19 14:55:58 -08002390 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07002391 audio_output_flags_t outputFlags = mOutput->flags;
Eric Laurent21da6472017-11-09 16:29:26 -08002392 audio_output_flags_t requestedFlags = *flags;
Eric Laurent9b11c022018-06-06 19:19:22 -07002393 uint32_t sampleRate;
2394
2395 if (sharedBuffer != 0 && checkIMemory(sharedBuffer) != NO_ERROR) {
2396 lStatus = BAD_VALUE;
2397 goto Exit;
2398 }
Eric Laurent21da6472017-11-09 16:29:26 -08002399
2400 if (*pSampleRate == 0) {
2401 *pSampleRate = mSampleRate;
2402 }
Eric Laurent9b11c022018-06-06 19:19:22 -07002403 sampleRate = *pSampleRate;
Eric Laurent05067782016-06-01 18:27:28 -07002404
2405 // special case for FAST flag considered OK if fast mixer is present
2406 if (hasFastMixer()) {
2407 outputFlags = (audio_output_flags_t)(outputFlags | AUDIO_OUTPUT_FLAG_FAST);
2408 }
2409
2410 // Check if requested flags are compatible with output stream flags
2411 if ((*flags & outputFlags) != *flags) {
2412 ALOGW("createTrack_l(): mismatch between requested flags (%08x) and output flags (%08x)",
2413 *flags, outputFlags);
2414 *flags = (audio_output_flags_t)(*flags & outputFlags);
2415 }
Eric Laurent81784c32012-11-19 14:55:58 -08002416
jiabinc658e452022-10-21 20:52:21 +00002417 if (isBitPerfect) {
Andy Hung8d672e02023-09-15 18:19:28 -07002418 audio_utils::lock_guard _l(mutex());
Andy Hung116bc262023-06-20 18:56:17 -07002419 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
jiabinc658e452022-10-21 20:52:21 +00002420 if (chain.get() != nullptr) {
2421 // Bit-perfect is required according to the configuration and preferred mixer
2422 // attributes, but it is not in the output flag from the client's request. Explicitly
2423 // adding bit-perfect flag to check the compatibility
2424 audio_output_flags_t flagsToCheck =
2425 (audio_output_flags_t)(*flags & AUDIO_OUTPUT_FLAG_BIT_PERFECT);
2426 chain->checkOutputFlagCompatibility(&flagsToCheck);
2427 if ((flagsToCheck & AUDIO_OUTPUT_FLAG_BIT_PERFECT) == AUDIO_OUTPUT_FLAG_NONE) {
2428 ALOGE("%s cannot create track as there is data-processing effect attached to "
2429 "given session id(%d)", __func__, sessionId);
2430 lStatus = BAD_VALUE;
2431 goto Exit;
2432 }
2433 *flags = flagsToCheck;
2434 }
2435 }
2436
Eric Laurent81784c32012-11-19 14:55:58 -08002437 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07002438 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
Eric Laurent81784c32012-11-19 14:55:58 -08002439 if (
Eric Laurent81784c32012-11-19 14:55:58 -08002440 // PCM data
2441 audio_is_linear_pcm(format) &&
Andy Hung1f439e12015-05-19 12:57:41 -07002442 // TODO: extract as a data library function that checks that a computationally
2443 // expensive downmixer is not required: isFastOutputChannelConversion()
jiabin245cdd92018-12-07 17:55:15 -08002444 (channelMask == (mChannelMask | mHapticChannelMask) ||
Andy Hung1f439e12015-05-19 12:57:41 -07002445 mChannelMask != AUDIO_CHANNEL_OUT_STEREO ||
2446 (channelMask == AUDIO_CHANNEL_OUT_MONO
2447 /* && mChannelMask == AUDIO_CHANNEL_OUT_STEREO */)) &&
Eric Laurent81784c32012-11-19 14:55:58 -08002448 // hardware sample rate
2449 (sampleRate == mSampleRate) &&
Eric Laurent81784c32012-11-19 14:55:58 -08002450 // normal mixer has an associated fast mixer
2451 hasFastMixer() &&
2452 // there are sufficient fast track slots available
2453 (mFastTrackAvailMask != 0)
2454 // FIXME test that MixerThread for this fast track has a capable output HAL
2455 // FIXME add a permission test also?
2456 ) {
Andy Hunge0a269a2016-03-23 15:13:42 -07002457 // static tracks can have any nonzero framecount, streaming tracks check against minimum.
2458 if (sharedBuffer == 0) {
Glenn Kasten03490092014-05-27 12:30:54 -07002459 // read the fast track multiplier property the first time it is needed
2460 int ok = pthread_once(&sFastTrackMultiplierOnce, sFastTrackMultiplierInit);
2461 if (ok != 0) {
2462 ALOGE("%s pthread_once failed: %d", __func__, ok);
2463 }
Andy Hunge0a269a2016-03-23 15:13:42 -07002464 frameCount = max(frameCount, mFrameCount * sFastTrackMultiplier); // incl framecount 0
Eric Laurent81784c32012-11-19 14:55:58 -08002465 }
Eric Laurent4c415062016-06-17 16:14:16 -07002466
2467 // check compatibility with audio effects.
Andy Hungc5007f82023-08-29 14:26:09 -07002468 { // scope for mutex()
Andy Hung972bec12023-08-31 16:13:39 -07002469 audio_utils::lock_guard _l(mutex());
Andy Hungd3bb0ad2016-10-11 17:16:43 -07002470 for (audio_session_t session : {
Eric Laurent3f75a5b2019-11-12 15:55:51 -08002471 AUDIO_SESSION_DEVICE,
Andy Hungd3bb0ad2016-10-11 17:16:43 -07002472 AUDIO_SESSION_OUTPUT_STAGE,
2473 AUDIO_SESSION_OUTPUT_MIX,
2474 sessionId,
2475 }) {
Andy Hung116bc262023-06-20 18:56:17 -07002476 sp<IAfEffectChain> chain = getEffectChain_l(session);
Andy Hungd3bb0ad2016-10-11 17:16:43 -07002477 if (chain.get() != nullptr) {
2478 audio_output_flags_t old = *flags;
2479 chain->checkOutputFlagCompatibility(flags);
2480 if (old != *flags) {
2481 ALOGV("AUDIO_OUTPUT_FLAGS denied by effect, session=%d old=%#x new=%#x",
2482 (int)session, (int)old, (int)*flags);
2483 }
Eric Laurent4c415062016-06-17 16:14:16 -07002484 }
2485 }
2486 }
Eric Laurent122f7e72016-06-29 11:53:29 -07002487 ALOGV_IF((*flags & AUDIO_OUTPUT_FLAG_FAST) != 0,
Eric Laurent4c415062016-06-17 16:14:16 -07002488 "AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
2489 frameCount, mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08002490 } else {
Robert Wu4c7bb7d2021-08-12 18:50:13 +00002491 ALOGD("AUDIO_OUTPUT_FLAG_FAST denied: sharedBuffer=%p frameCount=%zu "
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002492 "mFrameCount=%zu format=%#x mFormat=%#x isLinear=%d channelMask=%#x "
Andy Hung6146c082014-03-18 11:56:15 -07002493 "sampleRate=%u mSampleRate=%u "
Eric Laurent81784c32012-11-19 14:55:58 -08002494 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
Glenn Kastend79072e2016-01-06 08:41:20 -08002495 sharedBuffer.get(), frameCount, mFrameCount, format, mFormat,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07002496 audio_is_linear_pcm(format), channelMask, sampleRate,
2497 mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
Eric Laurent4c415062016-06-17 16:14:16 -07002498 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_FAST);
Andy Hung0e48d252015-01-26 11:43:15 -08002499 }
2500 }
Eric Laurent21da6472017-11-09 16:29:26 -08002501
2502 if (!audio_has_proportional_frames(format)) {
2503 if (sharedBuffer != 0) {
2504 // Same comment as below about ignoring frameCount parameter for set()
2505 frameCount = sharedBuffer->size();
2506 } else if (frameCount == 0) {
2507 frameCount = mNormalFrameCount;
2508 }
2509 if (notificationFrameCount != frameCount) {
2510 notificationFrameCount = frameCount;
2511 }
2512 } else if (sharedBuffer != 0) {
2513 // FIXME: Ensure client side memory buffers need
2514 // not have additional alignment beyond sample
2515 // (e.g. 16 bit stereo accessed as 32 bit frame).
2516 size_t alignment = audio_bytes_per_sample(format);
2517 if (alignment & 1) {
2518 // for AUDIO_FORMAT_PCM_24_BIT_PACKED (not exposed through Java).
2519 alignment = 1;
2520 }
2521 uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
2522 size_t frameSize = channelCount * audio_bytes_per_sample(format);
2523 if (channelCount > 1) {
2524 // More than 2 channels does not require stronger alignment than stereo
2525 alignment <<= 1;
2526 }
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07002527 if (((uintptr_t)sharedBuffer->unsecurePointer() & (alignment - 1)) != 0) {
Eric Laurent21da6472017-11-09 16:29:26 -08002528 ALOGE("Invalid buffer alignment: address %p, channel count %u",
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07002529 sharedBuffer->unsecurePointer(), channelCount);
Eric Laurent21da6472017-11-09 16:29:26 -08002530 lStatus = BAD_VALUE;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002531 goto Exit;
2532 }
Eric Laurent21da6472017-11-09 16:29:26 -08002533
2534 // When initializing a shared buffer AudioTrack via constructors,
2535 // there's no frameCount parameter.
2536 // But when initializing a shared buffer AudioTrack via set(),
2537 // there _is_ a frameCount parameter. We silently ignore it.
2538 frameCount = sharedBuffer->size() / frameSize;
2539 } else {
2540 size_t minFrameCount = 0;
2541 // For fast tracks we try to respect the application's request for notifications per buffer.
2542 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
2543 if (notificationsPerBuffer > 0) {
2544 // Avoid possible arithmetic overflow during multiplication.
2545 if (notificationsPerBuffer > SIZE_MAX / mFrameCount) {
2546 ALOGE("Requested notificationPerBuffer=%u ignored for HAL frameCount=%zu",
2547 notificationsPerBuffer, mFrameCount);
2548 } else {
2549 minFrameCount = mFrameCount * notificationsPerBuffer;
2550 }
2551 }
2552 } else {
2553 // For normal PCM streaming tracks, update minimum frame count.
2554 // Buffer depth is forced to be at least 2 x the normal mixer frame count and
2555 // cover audio hardware latency.
2556 // This is probably too conservative, but legacy application code may depend on it.
2557 // If you change this calculation, also review the start threshold which is related.
2558 uint32_t latencyMs = latency_l();
2559 if (latencyMs == 0) {
2560 ALOGE("Error when retrieving output stream latency");
2561 lStatus = UNKNOWN_ERROR;
2562 goto Exit;
2563 }
2564
2565 minFrameCount = AudioSystem::calculateMinFrameCount(latencyMs, mNormalFrameCount,
2566 mSampleRate, sampleRate, speed /*, 0 mNotificationsPerBufferReq*/);
2567
Eric Laurent81784c32012-11-19 14:55:58 -08002568 }
Eric Laurent21da6472017-11-09 16:29:26 -08002569 if (frameCount < minFrameCount) {
Eric Laurent81784c32012-11-19 14:55:58 -08002570 frameCount = minFrameCount;
2571 }
Eric Laurent81784c32012-11-19 14:55:58 -08002572 }
Eric Laurent21da6472017-11-09 16:29:26 -08002573
2574 // Make sure that application is notified with sufficient margin before underrun.
2575 // The client can divide the AudioTrack buffer into sub-buffers,
2576 // and expresses its desire to server as the notification frame count.
2577 if (sharedBuffer == 0 && audio_is_linear_pcm(format)) {
2578 size_t maxNotificationFrames;
2579 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
2580 // notify every HAL buffer, regardless of the size of the track buffer
2581 maxNotificationFrames = mFrameCount;
2582 } else {
Andy Hungfa117802019-04-12 13:50:39 -07002583 // Triple buffer the notification period for a triple buffered mixer period;
2584 // otherwise, double buffering for the notification period is fine.
2585 //
2586 // TODO: This should be moved to AudioTrack to modify the notification period
2587 // on AudioTrack::setBufferSizeInFrames() changes.
2588 const int nBuffering =
2589 (uint64_t{frameCount} * mSampleRate)
2590 / (uint64_t{mNormalFrameCount} * sampleRate) == 3 ? 3 : 2;
2591
Eric Laurent21da6472017-11-09 16:29:26 -08002592 maxNotificationFrames = frameCount / nBuffering;
2593 // If client requested a fast track but this was denied, then use the smaller maximum.
2594 if (requestedFlags & AUDIO_OUTPUT_FLAG_FAST) {
2595 size_t maxNotificationFramesFastDenied = FMS_20 * sampleRate / 1000;
2596 if (maxNotificationFrames > maxNotificationFramesFastDenied) {
2597 maxNotificationFrames = maxNotificationFramesFastDenied;
2598 }
2599 }
2600 }
2601 if (notificationFrameCount == 0 || notificationFrameCount > maxNotificationFrames) {
2602 if (notificationFrameCount == 0) {
2603 ALOGD("Client defaulted notificationFrames to %zu for frameCount %zu",
2604 maxNotificationFrames, frameCount);
2605 } else {
2606 ALOGW("Client adjusted notificationFrames from %zu to %zu for frameCount %zu",
2607 notificationFrameCount, maxNotificationFrames, frameCount);
2608 }
2609 notificationFrameCount = maxNotificationFrames;
2610 }
2611 }
2612
Glenn Kasten74935e42013-12-19 08:56:45 -08002613 *pFrameCount = frameCount;
Eric Laurent21da6472017-11-09 16:29:26 -08002614 *pNotificationFrameCount = notificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08002615
Glenn Kastenc3df8382014-03-13 15:05:25 -07002616 switch (mType) {
jiabinc658e452022-10-21 20:52:21 +00002617 case BIT_PERFECT:
2618 if (isBitPerfect) {
2619 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
2620 ALOGE("%s, bad parameter when request streaming bit-perfect, sampleRate=%u, "
2621 "format=%#x, channelMask=%#x, mSampleRate=%u, mFormat=%#x, mChannelMask=%#x",
2622 __func__, sampleRate, format, channelMask, mSampleRate, mFormat,
2623 mChannelMask);
2624 lStatus = BAD_VALUE;
2625 goto Exit;
2626 }
2627 }
2628 break;
Glenn Kastenc3df8382014-03-13 15:05:25 -07002629
2630 case DIRECT:
Phil Burkfdb3c072016-02-09 10:47:02 -08002631 if (audio_is_linear_pcm(format)) { // TODO maybe use audio_has_proportional_frames()?
Eric Laurent81784c32012-11-19 14:55:58 -08002632 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002633 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
2634 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08002635 sampleRate, format, channelMask, mOutput, mFormat);
2636 lStatus = BAD_VALUE;
2637 goto Exit;
2638 }
2639 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002640 break;
2641
2642 case OFFLOAD:
Eric Laurentbfb1b832013-01-07 09:53:42 -08002643 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002644 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
2645 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002646 sampleRate, format, channelMask, mOutput, mFormat);
2647 lStatus = BAD_VALUE;
2648 goto Exit;
2649 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002650 break;
2651
2652 default:
Glenn Kasten993fa062014-05-02 11:14:34 -07002653 if (!audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002654 ALOGE("createTrack_l() Bad parameter: format %#x \""
2655 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002656 format, mOutput, mFormat);
2657 lStatus = BAD_VALUE;
2658 goto Exit;
2659 }
Andy Hungcd044842014-08-07 11:04:34 -07002660 if (sampleRate > mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Eric Laurent81784c32012-11-19 14:55:58 -08002661 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
2662 lStatus = BAD_VALUE;
2663 goto Exit;
2664 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002665 break;
2666
Eric Laurent81784c32012-11-19 14:55:58 -08002667 }
2668
2669 lStatus = initCheck();
2670 if (lStatus != NO_ERROR) {
Glenn Kasten15e57982013-09-24 11:52:37 -07002671 ALOGE("createTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08002672 goto Exit;
2673 }
2674
Andy Hungc5007f82023-08-29 14:26:09 -07002675 { // scope for mutex()
Andy Hung972bec12023-08-31 16:13:39 -07002676 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002677
2678 // all tracks in same audio session must share the same routing strategy otherwise
2679 // conflicts will happen when tracks are moved from one output to another by audio policy
2680 // manager
Eric Laurentd66d7a12021-07-13 13:35:32 +02002681 product_strategy_t strategy = getStrategyForStream(streamType);
Eric Laurent81784c32012-11-19 14:55:58 -08002682 for (size_t i = 0; i < mTracks.size(); ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07002683 sp<IAfTrack> t = mTracks[i];
Eric Laurent83b88082014-06-20 18:31:16 -07002684 if (t != 0 && t->isExternalTrack()) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02002685 product_strategy_t actual = getStrategyForStream(t->streamType());
Eric Laurent81784c32012-11-19 14:55:58 -08002686 if (sessionId == t->sessionId() && strategy != actual) {
2687 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
2688 strategy, actual);
2689 lStatus = BAD_VALUE;
2690 goto Exit;
2691 }
2692 }
2693 }
2694
yucliuc9c49cd2020-07-13 16:25:21 -07002695 // Set DIRECT flag if current thread is DirectOutputThread. This can
2696 // happen when the playback is rerouted to direct output thread by
2697 // dynamic audio policy.
2698 // Do NOT report the flag changes back to client, since the client
2699 // doesn't explicitly request a direct flag.
2700 audio_output_flags_t trackFlags = *flags;
2701 if (mType == DIRECT) {
2702 trackFlags = static_cast<audio_output_flags_t>(trackFlags | AUDIO_OUTPUT_FLAG_DIRECT);
2703 }
jiabin94ed47c2023-07-27 23:34:20 +00002704 *afTrackFlags = trackFlags;
yucliuc9c49cd2020-07-13 16:25:21 -07002705
Andy Hung8d31fd22023-06-26 19:20:57 -07002706 track = IAfTrack::create(this, client, streamType, attr, sampleRate, format,
Andy Hung8fe68032017-06-05 16:17:51 -07002707 channelMask, frameCount,
2708 nullptr /* buffer */, (size_t)0 /* bufferSize */, sharedBuffer,
Svet Ganov33761132021-05-13 22:51:08 +00002709 sessionId, creatorPid, attributionSource, trackFlags,
Andy Hung8d31fd22023-06-26 19:20:57 -07002710 IAfTrackBase::TYPE_DEFAULT, portId, SIZE_MAX /*frameCountToBeReady*/,
jiabinc658e452022-10-21 20:52:21 +00002711 speed, isSpatialized, isBitPerfect);
Glenn Kasten03003332013-08-06 15:40:54 -07002712
Glenn Kasten03003332013-08-06 15:40:54 -07002713 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
2714 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08002715 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08002716 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08002717 goto Exit;
2718 }
2719 mTracks.add(track);
jiabinf6eb4c32020-02-25 14:06:25 -08002720 {
Andy Hung972bec12023-08-31 16:13:39 -07002721 audio_utils::lock_guard _atCbL(audioTrackCbMutex());
jiabinf6eb4c32020-02-25 14:06:25 -08002722 if (callback.get() != nullptr) {
jiabin18a4b1c2020-09-17 11:40:42 -07002723 mAudioTrackCallbacks.emplace(track, callback);
jiabinf6eb4c32020-02-25 14:06:25 -08002724 }
2725 }
Eric Laurent81784c32012-11-19 14:55:58 -08002726
Andy Hung116bc262023-06-20 18:56:17 -07002727 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08002728 if (chain != 0) {
2729 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
2730 track->setMainBuffer(chain->inBuffer());
Eric Laurentd66d7a12021-07-13 13:35:32 +02002731 chain->setStrategy(getStrategyForStream(track->streamType()));
Eric Laurent81784c32012-11-19 14:55:58 -08002732 chain->incTrackCnt();
2733 }
2734
Eric Laurent05067782016-06-01 18:27:28 -07002735 if ((*flags & AUDIO_OUTPUT_FLAG_FAST) && (tid != -1)) {
Eric Laurent81784c32012-11-19 14:55:58 -08002736 pid_t callingPid = IPCThreadState::self()->getCallingPid();
2737 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
2738 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07002739 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08002740 }
2741 }
2742
2743 lStatus = NO_ERROR;
2744
2745Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07002746 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08002747 return track;
2748}
2749
Andy Hung1bc088a2018-02-09 15:57:31 -08002750template<typename T>
Andy Hungee58e4a2023-07-07 13:47:37 -07002751ssize_t PlaybackThread::Tracks<T>::remove(const sp<T>& track)
Andy Hung1bc088a2018-02-09 15:57:31 -08002752{
Andy Hungc0691382018-09-12 18:01:57 -07002753 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08002754 const ssize_t index = mTracks.remove(track);
2755 if (index >= 0) {
Andy Hungc0691382018-09-12 18:01:57 -07002756 if (mSaveDeletedTrackIds) {
Andy Hung1bc088a2018-02-09 15:57:31 -08002757 // We can't directly access mAudioMixer since the caller may be outside of threadLoop.
Andy Hungc0691382018-09-12 18:01:57 -07002758 // Instead, we add to mDeletedTrackIds which is solely used for mAudioMixer update,
Andy Hung1bc088a2018-02-09 15:57:31 -08002759 // to be handled when MixerThread::prepareTracks_l() next changes mAudioMixer.
Andy Hungc0691382018-09-12 18:01:57 -07002760 mDeletedTrackIds.emplace(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08002761 }
Andy Hung1bc088a2018-02-09 15:57:31 -08002762 }
2763 return index;
2764}
2765
Andy Hungee58e4a2023-07-07 13:47:37 -07002766uint32_t PlaybackThread::correctLatency_l(uint32_t latency) const
Eric Laurent81784c32012-11-19 14:55:58 -08002767{
2768 return latency;
2769}
2770
Andy Hungee58e4a2023-07-07 13:47:37 -07002771uint32_t PlaybackThread::latency() const
Eric Laurent81784c32012-11-19 14:55:58 -08002772{
Andy Hung972bec12023-08-31 16:13:39 -07002773 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002774 return latency_l();
2775}
Andy Hungee58e4a2023-07-07 13:47:37 -07002776uint32_t PlaybackThread::latency_l() const
Andy Hungab65b182023-09-06 19:41:47 -07002777NO_THREAD_SAFETY_ANALYSIS
2778// Fix later.
Eric Laurent81784c32012-11-19 14:55:58 -08002779{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002780 uint32_t latency;
2781 if (initCheck() == NO_ERROR && mOutput->stream->getLatency(&latency) == OK) {
2782 return correctLatency_l(latency);
Eric Laurent81784c32012-11-19 14:55:58 -08002783 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002784 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002785}
2786
Andy Hungee58e4a2023-07-07 13:47:37 -07002787void PlaybackThread::setMasterVolume(float value)
Eric Laurent81784c32012-11-19 14:55:58 -08002788{
Andy Hung972bec12023-08-31 16:13:39 -07002789 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002790 // Don't apply master volume in SW if our HAL can do it for us.
2791 if (mOutput && mOutput->audioHwDev &&
2792 mOutput->audioHwDev->canSetMasterVolume()) {
2793 mMasterVolume = 1.0;
2794 } else {
2795 mMasterVolume = value;
2796 }
2797}
2798
Andy Hungee58e4a2023-07-07 13:47:37 -07002799void PlaybackThread::setMasterBalance(float balance)
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01002800{
2801 mMasterBalance.store(balance);
2802}
2803
Andy Hungee58e4a2023-07-07 13:47:37 -07002804void PlaybackThread::setMasterMute(bool muted)
Eric Laurent81784c32012-11-19 14:55:58 -08002805{
Eric Laurent6acd1d42017-01-04 14:23:29 -08002806 if (isDuplicating()) {
2807 return;
2808 }
Andy Hung972bec12023-08-31 16:13:39 -07002809 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002810 // Don't apply master mute in SW if our HAL can do it for us.
2811 if (mOutput && mOutput->audioHwDev &&
2812 mOutput->audioHwDev->canSetMasterMute()) {
2813 mMasterMute = false;
2814 } else {
2815 mMasterMute = muted;
2816 }
2817}
2818
Andy Hungee58e4a2023-07-07 13:47:37 -07002819void PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
Eric Laurent81784c32012-11-19 14:55:58 -08002820{
Andy Hung972bec12023-08-31 16:13:39 -07002821 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002822 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002823 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002824}
2825
Andy Hungee58e4a2023-07-07 13:47:37 -07002826void PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
Eric Laurent81784c32012-11-19 14:55:58 -08002827{
Andy Hung972bec12023-08-31 16:13:39 -07002828 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002829 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002830 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002831}
2832
Andy Hungee58e4a2023-07-07 13:47:37 -07002833float PlaybackThread::streamVolume(audio_stream_type_t stream) const
Eric Laurent81784c32012-11-19 14:55:58 -08002834{
Andy Hung972bec12023-08-31 16:13:39 -07002835 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002836 return mStreamTypes[stream].volume;
2837}
2838
Andy Hungee58e4a2023-07-07 13:47:37 -07002839void PlaybackThread::setVolumeForOutput_l(float left, float right) const
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09002840{
2841 mOutput->stream->setVolume(left, right);
2842}
2843
Andy Hungc5007f82023-08-29 14:26:09 -07002844// addTrack_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07002845status_t PlaybackThread::addTrack_l(const sp<IAfTrack>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002846{
2847 status_t status = ALREADY_EXISTS;
2848
Eric Laurent81784c32012-11-19 14:55:58 -08002849 if (mActiveTracks.indexOf(track) < 0) {
2850 // the track is newly added, make sure it fills up all its
2851 // buffers before playing. This is to ensure the client will
2852 // effectively get the latency it requested.
Eric Laurent83b88082014-06-20 18:31:16 -07002853 if (track->isExternalTrack()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07002854 IAfTrackBase::track_state state = track->state();
Andy Hung6c498e92023-12-05 17:28:17 -08002855 // Because the track is not on the ActiveTracks,
2856 // at this point, only the TrackHandle will be adding the track.
Andy Hungc5007f82023-08-29 14:26:09 -07002857 mutex().unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002858 status = AudioSystem::startOutput(track->portId());
Andy Hungc5007f82023-08-29 14:26:09 -07002859 mutex().lock();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002860 // abort track was stopped/paused while we released the lock
Andy Hung8d31fd22023-06-26 19:20:57 -07002861 if (state != track->state()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002862 if (status == NO_ERROR) {
Andy Hungc5007f82023-08-29 14:26:09 -07002863 mutex().unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002864 AudioSystem::stopOutput(track->portId());
Andy Hungc5007f82023-08-29 14:26:09 -07002865 mutex().lock();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002866 }
2867 return INVALID_OPERATION;
2868 }
2869 // abort if start is rejected by audio policy manager
2870 if (status != NO_ERROR) {
jiabina84c3d32022-12-02 18:59:55 +00002871 // Do not replace the error if it is DEAD_OBJECT. When this happens, it indicates
2872 // current playback thread is reopened, which may happen when clients set preferred
2873 // mixer configuration. Returning DEAD_OBJECT will make the client restore track
2874 // immediately.
2875 return status == DEAD_OBJECT ? status : PERMISSION_DENIED;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002876 }
2877#ifdef ADD_BATTERY_DATA
2878 // to track the speaker usage
2879 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
2880#endif
Eric Laurent09f1ed22019-04-24 17:45:17 -07002881 sendIoConfigEvent_l(AUDIO_CLIENT_STARTED, track->creatorPid(), track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002882 }
2883
Eric Laurent51716182016-02-29 18:00:56 -08002884 // set retry count for buffer fill
2885 if (track->isOffloaded()) {
Eric Laurente93cc032016-05-05 10:15:10 -07002886 if (track->isStopping_1()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07002887 track->retryCount() = kMaxTrackStopRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07002888 } else {
Andy Hung8d31fd22023-06-26 19:20:57 -07002889 track->retryCount() = kMaxTrackStartupRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07002890 }
Andy Hung8d31fd22023-06-26 19:20:57 -07002891 track->fillingStatus() = mStandby ? IAfTrack::FS_FILLING : IAfTrack::FS_FILLED;
Eric Laurent51716182016-02-29 18:00:56 -08002892 } else {
Andy Hung8d31fd22023-06-26 19:20:57 -07002893 track->retryCount() = kMaxTrackStartupRetries;
2894 track->fillingStatus() =
2895 track->sharedBuffer() != 0 ? IAfTrack::FS_FILLED : IAfTrack::FS_FILLING;
Eric Laurent51716182016-02-29 18:00:56 -08002896 }
2897
Andy Hung116bc262023-06-20 18:56:17 -07002898 sp<IAfEffectChain> chain = getEffectChain_l(track->sessionId());
jiabineb3bda02020-06-30 14:07:03 -07002899 if (mHapticChannelMask != AUDIO_CHANNEL_NONE
2900 && ((track->channelMask() & AUDIO_CHANNEL_HAPTIC_ALL) != AUDIO_CHANNEL_NONE
François Gaffie541fd402023-11-29 17:16:38 +01002901 || (chain != nullptr && chain->containsHapticGeneratingEffect()))) {
jiabin57303cc2018-12-18 15:45:57 -08002902 // Unlock due to VibratorService will lock for this call and will
2903 // call Tracks.mute/unmute which also require thread's lock.
Andy Hungc5007f82023-08-29 14:26:09 -07002904 mutex().unlock();
Ahmad Khalil229466a2024-02-05 12:15:30 +00002905 const os::HapticScale hapticScale = afutils::onExternalVibrationStart(
jiabin57303cc2018-12-18 15:45:57 -08002906 track->getExternalVibration());
Lais Andradebc3f37a2021-07-02 00:13:19 +01002907 std::optional<media::AudioVibratorInfo> vibratorInfo;
2908 {
2909 // TODO(b/184194780): Use the vibrator information from the vibrator that will be
2910 // used to play this track.
Andy Hung972bec12023-08-31 16:13:39 -07002911 audio_utils::lock_guard _l(mAfThreadCallback->mutex());
Andy Hung583043b2023-07-17 17:05:00 -07002912 vibratorInfo = std::move(mAfThreadCallback->getDefaultVibratorInfo_l());
Lais Andradebc3f37a2021-07-02 00:13:19 +01002913 }
Andy Hungc5007f82023-08-29 14:26:09 -07002914 mutex().lock();
Ahmad Khalil229466a2024-02-05 12:15:30 +00002915 track->setHapticScale(hapticScale);
Lais Andradebc3f37a2021-07-02 00:13:19 +01002916 if (vibratorInfo) {
2917 track->setHapticMaxAmplitude(vibratorInfo->maxAmplitude);
2918 }
2919
jiabin57303cc2018-12-18 15:45:57 -08002920 // Haptic playback should be enabled by vibrator service.
2921 if (track->getHapticPlaybackEnabled()) {
2922 // Disable haptic playback of all active track to ensure only
2923 // one track playing haptic if current track should play haptic.
2924 for (const auto &t : mActiveTracks) {
2925 t->setHapticPlaybackEnabled(false);
2926 }
jiabin245cdd92018-12-07 17:55:15 -08002927 }
jiabine70bc7f2020-06-30 22:07:55 -07002928
2929 // Set haptic intensity for effect
2930 if (chain != nullptr) {
Ahmad Khalil229466a2024-02-05 12:15:30 +00002931 // TODO(b/324559333): Add adaptive haptics scaling support for the HapticGenerator.
2932 chain->setHapticScale_l(track->id(), hapticScale);
jiabine70bc7f2020-06-30 22:07:55 -07002933 }
jiabin245cdd92018-12-07 17:55:15 -08002934 }
2935
Andy Hung8d31fd22023-06-26 19:20:57 -07002936 track->setResetDone(false);
Andy Hung59de4262021-06-14 10:53:54 -07002937 track->resetPresentationComplete();
Andy Hung6c498e92023-12-05 17:28:17 -08002938
2939 // Do not release the ThreadBase mutex after the track is added to mActiveTracks unless
2940 // all key changes are complete. It is possible that the threadLoop will begin
2941 // processing the added track immediately after the ThreadBase mutex is released.
Eric Laurent81784c32012-11-19 14:55:58 -08002942 mActiveTracks.add(track);
Andy Hung6c498e92023-12-05 17:28:17 -08002943
Eric Laurentd0107bc2013-06-11 14:38:48 -07002944 if (chain != 0) {
2945 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
2946 track->sessionId());
2947 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08002948 }
2949
Andy Hungc2b11cb2020-04-22 09:04:01 -07002950 track->logBeginInterval(patchSinksToString(&mPatch)); // log to MediaMetrics
Eric Laurent81784c32012-11-19 14:55:58 -08002951 status = NO_ERROR;
2952 }
2953
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08002954 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002955 return status;
2956}
2957
Andy Hungee58e4a2023-07-07 13:47:37 -07002958bool PlaybackThread::destroyTrack_l(const sp<IAfTrack>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002959{
Eric Laurentbfb1b832013-01-07 09:53:42 -08002960 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08002961 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002962 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
Andy Hung8d31fd22023-06-26 19:20:57 -07002963 track->setState(IAfTrackBase::STOPPED);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002964 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08002965 removeTrack_l(track);
Eric Laurentab5cdba2014-06-09 17:22:27 -07002966 } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) {
Andy Hung916987e2023-03-20 19:08:16 -07002967 if (track->isPausePending()) {
2968 track->pauseAck();
2969 }
Andy Hung8d31fd22023-06-26 19:20:57 -07002970 track->setState(IAfTrackBase::STOPPING_1);
Eric Laurent81784c32012-11-19 14:55:58 -08002971 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002972
2973 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08002974}
2975
Andy Hungee58e4a2023-07-07 13:47:37 -07002976void PlaybackThread::removeTrack_l(const sp<IAfTrack>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002977{
2978 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Andy Hung2148bf02016-11-28 19:01:02 -08002979
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002980 String8 result;
2981 track->appendDump(result, false /* active */);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00002982 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.c_str());
Andy Hung2148bf02016-11-28 19:01:02 -08002983
Eric Laurent81784c32012-11-19 14:55:58 -08002984 mTracks.remove(track);
jiabin18a4b1c2020-09-17 11:40:42 -07002985 {
Andy Hung972bec12023-08-31 16:13:39 -07002986 audio_utils::lock_guard _atCbL(audioTrackCbMutex());
jiabin18a4b1c2020-09-17 11:40:42 -07002987 mAudioTrackCallbacks.erase(track);
2988 }
Eric Laurent81784c32012-11-19 14:55:58 -08002989 if (track->isFastTrack()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07002990 int index = track->fastIndex();
Glenn Kastendc2c50b2016-04-21 08:13:14 -07002991 ALOG_ASSERT(0 < index && index < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08002992 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
2993 mFastTrackAvailMask |= 1 << index;
2994 // redundant as track is about to be destroyed, for dumpsys only
Andy Hung8d31fd22023-06-26 19:20:57 -07002995 track->fastIndex() = -1;
Eric Laurent81784c32012-11-19 14:55:58 -08002996 }
Andy Hung116bc262023-06-20 18:56:17 -07002997 sp<IAfEffectChain> chain = getEffectChain_l(track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08002998 if (chain != 0) {
2999 chain->decTrackCnt();
3000 }
3001}
3002
Andy Hungee58e4a2023-07-07 13:47:37 -07003003String8 PlaybackThread::getParameters(const String8& keys)
Eric Laurent81784c32012-11-19 14:55:58 -08003004{
Andy Hung972bec12023-08-31 16:13:39 -07003005 audio_utils::lock_guard _l(mutex());
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003006 String8 out_s8;
3007 if (initCheck() == NO_ERROR && mOutput->stream->getParameters(keys, &out_s8) == OK) {
3008 return out_s8;
Eric Laurent81784c32012-11-19 14:55:58 -08003009 }
Andy Hung920f6572022-10-06 12:09:49 -07003010 return {};
Eric Laurent81784c32012-11-19 14:55:58 -08003011}
3012
Andy Hungee58e4a2023-07-07 13:47:37 -07003013status_t DirectOutputThread::selectPresentation(int presentationId, int programId) {
Andy Hung972bec12023-08-31 16:13:39 -07003014 audio_utils::lock_guard _l(mutex());
Jasmine Chaeaa10e42021-05-11 10:11:14 +08003015 if (!isStreamInitialized()) {
Mikhail Naganovac917ac2018-11-28 14:03:52 -08003016 return NO_INIT;
3017 }
3018 return mOutput->stream->selectPresentation(presentationId, programId);
3019}
3020
Andy Hungab65b182023-09-06 19:41:47 -07003021void PlaybackThread::ioConfigChanged_l(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -07003022 audio_port_handle_t portId) {
Eric Laurent73e26b62015-04-27 16:55:58 -07003023 ALOGV("PlaybackThread::ioConfigChanged, thread %p, event %d", this, event);
Mikhail Naganov88536df2021-07-26 17:30:29 -07003024 sp<AudioIoDescriptor> desc;
3025 const struct audio_patch patch = isMsdDevice() ? mDownStreamPatch : mPatch;
Eric Laurent81784c32012-11-19 14:55:58 -08003026 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07003027 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07003028 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07003029 case AUDIO_OUTPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07003030 desc = sp<AudioIoDescriptor>::make(mId, patch, false /*isInput*/,
3031 mSampleRate, mFormat, mChannelMask,
3032 // FIXME AudioFlinger::frameCount(audio_io_handle_t) instead of mNormalFrameCount?
3033 mNormalFrameCount, mFrameCount, latency_l());
Eric Laurent81784c32012-11-19 14:55:58 -08003034 break;
Eric Laurent09f1ed22019-04-24 17:45:17 -07003035 case AUDIO_CLIENT_STARTED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07003036 desc = sp<AudioIoDescriptor>::make(mId, patch, portId);
Eric Laurent09f1ed22019-04-24 17:45:17 -07003037 break;
Eric Laurent73e26b62015-04-27 16:55:58 -07003038 case AUDIO_OUTPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08003039 default:
Mikhail Naganov88536df2021-07-26 17:30:29 -07003040 desc = sp<AudioIoDescriptor>::make(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08003041 break;
3042 }
Andy Hungab65b182023-09-06 19:41:47 -07003043 mAfThreadCallback->ioConfigChanged_l(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08003044}
3045
Andy Hungee58e4a2023-07-07 13:47:37 -07003046void PlaybackThread::onWriteReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08003047{
Eric Laurent3b4529e2013-09-05 18:09:19 -07003048 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003049}
3050
Andy Hungee58e4a2023-07-07 13:47:37 -07003051void PlaybackThread::onDrainReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08003052{
Eric Laurent3b4529e2013-09-05 18:09:19 -07003053 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003054}
3055
Andy Hungee58e4a2023-07-07 13:47:37 -07003056void PlaybackThread::onError()
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07003057{
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07003058 mCallbackThread->setAsyncError();
3059}
3060
Andy Hungee58e4a2023-07-07 13:47:37 -07003061void PlaybackThread::onCodecFormatChanged(
Ryan Prichard78c5e452024-02-08 16:16:57 -08003062 const std::vector<uint8_t>& metadataBs)
jiabinf6eb4c32020-02-25 14:06:25 -08003063{
Andy Hungee58e4a2023-07-07 13:47:37 -07003064 const auto weakPointerThis = wp<PlaybackThread>::fromExisting(this);
Kuowei Li9e2f6162022-11-23 16:25:26 +08003065 std::thread([this, metadataBs, weakPointerThis]() {
Andy Hungee58e4a2023-07-07 13:47:37 -07003066 const sp<PlaybackThread> playbackThread = weakPointerThis.promote();
Kuowei Li9e2f6162022-11-23 16:25:26 +08003067 if (playbackThread == nullptr) {
3068 ALOGW("PlaybackThread was destroyed, skip codec format change event");
3069 return;
3070 }
3071
jiabinf6eb4c32020-02-25 14:06:25 -08003072 audio_utils::metadata::Data metadata =
3073 audio_utils::metadata::dataFromByteString(metadataBs);
3074 if (metadata.empty()) {
3075 ALOGW("Can not transform the buffer to audio metadata, %s, %d",
3076 reinterpret_cast<char*>(const_cast<uint8_t*>(metadataBs.data())),
3077 (int)metadataBs.size());
3078 return;
3079 }
3080
3081 audio_utils::metadata::ByteString metaDataStr =
3082 audio_utils::metadata::byteStringFromData(metadata);
3083 std::vector metadataVec(metaDataStr.begin(), metaDataStr.end());
Andy Hung972bec12023-08-31 16:13:39 -07003084 audio_utils::lock_guard _l(audioTrackCbMutex());
jiabin18a4b1c2020-09-17 11:40:42 -07003085 for (const auto& callbackPair : mAudioTrackCallbacks) {
3086 callbackPair.second->onCodecFormatChanged(metadataVec);
jiabinf6eb4c32020-02-25 14:06:25 -08003087 }
3088 }).detach();
3089}
3090
Andy Hungee58e4a2023-07-07 13:47:37 -07003091void PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08003092{
Andy Hung972bec12023-08-31 16:13:39 -07003093 audio_utils::lock_guard _l(mutex());
Eric Laurent3b4529e2013-09-05 18:09:19 -07003094 // reject out of sequence requests
3095 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
3096 mWriteAckSequence &= ~1;
Andy Hungc5007f82023-08-29 14:26:09 -07003097 mWaitWorkCV.notify_one();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003098 }
3099}
3100
Andy Hungee58e4a2023-07-07 13:47:37 -07003101void PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08003102{
Andy Hung972bec12023-08-31 16:13:39 -07003103 audio_utils::lock_guard _l(mutex());
Eric Laurent3b4529e2013-09-05 18:09:19 -07003104 // reject out of sequence requests
3105 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
Andy Hungf3234512018-07-03 14:51:47 -07003106 // Register discontinuity when HW drain is completed because that can cause
3107 // the timestamp frame position to reset to 0 for direct and offload threads.
3108 // (Out of sequence requests are ignored, since the discontinuity would be handled
3109 // elsewhere, e.g. in flush).
Dean Wheatley12473e92021-03-18 23:00:55 +11003110 mTimestampVerifier.discontinuity(mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003111 mDrainSequence &= ~1;
Andy Hungc5007f82023-08-29 14:26:09 -07003112 mWaitWorkCV.notify_one();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003113 }
3114}
3115
Andy Hungee58e4a2023-07-07 13:47:37 -07003116void PlaybackThread::readOutputParameters_l()
Andy Hung972bec12023-08-31 16:13:39 -07003117NO_THREAD_SAFETY_ANALYSIS
3118// 'moveEffectChain_ll' requires holding mutex 'AudioFlinger_Mutex' exclusively
Eric Laurent81784c32012-11-19 14:55:58 -08003119{
Glenn Kastenadad3d72014-02-21 14:51:43 -08003120 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Mikhail Naganov560637e2021-03-31 22:40:13 +00003121 const audio_config_base_t audioConfig = mOutput->getAudioProperties();
3122 mSampleRate = audioConfig.sample_rate;
3123 mChannelMask = audioConfig.channel_mask;
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003124 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08003125 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003126 }
Andy Hung81994d62023-07-20 21:44:14 -07003127 if (hasMixer() && !isValidPcmSinkChannelMask(mChannelMask)) {
Andy Hung9a592762014-07-21 21:56:01 -07003128 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output",
3129 mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003130 }
Eric Laurentf1f22e72021-07-13 14:04:14 +02003131
3132 if (mMixerChannelMask == AUDIO_CHANNEL_NONE) {
3133 mMixerChannelMask = mChannelMask;
3134 }
3135
Andy Hunge5412692014-05-16 11:25:07 -07003136 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01003137 mBalance.setChannelMask(mChannelMask);
Phil Burkca5e6142015-07-14 09:42:29 -07003138
Eric Laurentf1f22e72021-07-13 14:04:14 +02003139 uint32_t mixerChannelCount = audio_channel_count_from_out_mask(mMixerChannelMask);
3140
Phil Burkca5e6142015-07-14 09:42:29 -07003141 // Get actual HAL format.
Mikhail Naganov560637e2021-03-31 22:40:13 +00003142 status_t result = mOutput->stream->getAudioProperties(nullptr, nullptr, &mHALFormat);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003143 LOG_ALWAYS_FATAL_IF(result != OK, "Error when retrieving output stream format: %d", result);
Phil Burkca5e6142015-07-14 09:42:29 -07003144 // Get format from the shim, which will be different than the HAL format
3145 // if playing compressed audio over HDMI passthrough.
Mikhail Naganov560637e2021-03-31 22:40:13 +00003146 mFormat = audioConfig.format;
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003147 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08003148 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003149 }
Andy Hung81994d62023-07-20 21:44:14 -07003150 if (hasMixer() && !isValidPcmSinkFormat(mFormat)) {
Andy Hung6146c082014-03-18 11:56:15 -07003151 LOG_FATAL("HAL format %#x not supported for mixed output",
3152 mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003153 }
Phil Burk062e67a2015-02-11 13:40:50 -08003154 mFrameSize = mOutput->getFrameSize();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003155 result = mOutput->stream->getBufferSize(&mBufferSize);
3156 LOG_ALWAYS_FATAL_IF(result != OK,
3157 "Error when retrieving output stream buffer size: %d", result);
Glenn Kasten70949c42013-08-06 07:40:12 -07003158 mFrameCount = mBufferSize / mFrameSize;
Eric Laurentb3f315a2021-07-13 15:09:05 +02003159 if (hasMixer() && (mFrameCount & 15)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003160 ALOGW("HAL output buffer size is %zu frames but AudioMixer requires multiples of 16 frames",
Eric Laurent81784c32012-11-19 14:55:58 -08003161 mFrameCount);
3162 }
3163
Eric Laurentd1f69b02014-12-15 14:33:13 -08003164 mHwSupportsPause = false;
3165 if (mOutput->flags & AUDIO_OUTPUT_FLAG_DIRECT) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003166 bool supportsPause = false, supportsResume = false;
3167 if (mOutput->stream->supportsPauseAndResume(&supportsPause, &supportsResume) == OK) {
3168 if (supportsPause && supportsResume) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08003169 mHwSupportsPause = true;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003170 } else if (supportsPause) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08003171 ALOGW("direct output implements pause but not resume");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003172 } else if (supportsResume) {
3173 ALOGW("direct output implements resume but not pause");
Eric Laurentd1f69b02014-12-15 14:33:13 -08003174 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08003175 }
3176 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07003177 if (!mHwSupportsPause && mOutput->flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) {
3178 LOG_ALWAYS_FATAL("HW_AV_SYNC requested but HAL does not implement pause and resume");
3179 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08003180
Andy Hungfbfc3952015-01-15 13:33:51 -08003181 if (mType == DUPLICATING && mMixerBufferEnabled && mEffectBufferEnabled) {
3182 // For best precision, we use float instead of the associated output
3183 // device format (typically PCM 16 bit).
3184
3185 mFormat = AUDIO_FORMAT_PCM_FLOAT;
3186 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
3187 mBufferSize = mFrameSize * mFrameCount;
3188
3189 // TODO: We currently use the associated output device channel mask and sample rate.
3190 // (1) Perhaps use the ORed channel mask of all downstream MixerThreads
3191 // (if a valid mask) to avoid premature downmix.
3192 // (2) Perhaps use the maximum sample rate of all downstream MixerThreads
3193 // instead of the output device sample rate to avoid loss of high frequency information.
3194 // This may need to be updated as MixerThread/OutputTracks are added and not here.
3195 }
3196
Andy Hung09a50072014-02-27 14:30:47 -08003197 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08003198 double multiplier = 1.0;
Andy Hungd3639922022-04-28 18:00:49 -07003199 // Note: mType == SPATIALIZER does not support FastMixer.
Eric Laurent81784c32012-11-19 14:55:58 -08003200 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
3201 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08003202 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
3203 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Haynes Mathew George227a14b2016-05-09 12:45:48 -07003204
Eric Laurent81784c32012-11-19 14:55:58 -08003205 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
3206 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
3207 maxNormalFrameCount = maxNormalFrameCount & ~15;
3208 if (maxNormalFrameCount < minNormalFrameCount) {
3209 maxNormalFrameCount = minNormalFrameCount;
3210 }
3211 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
3212 if (multiplier <= 1.0) {
3213 multiplier = 1.0;
3214 } else if (multiplier <= 2.0) {
3215 if (2 * mFrameCount <= maxNormalFrameCount) {
3216 multiplier = 2.0;
3217 } else {
3218 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
3219 }
3220 } else {
Haynes Mathew George227a14b2016-05-09 12:45:48 -07003221 multiplier = floor(multiplier);
Eric Laurent81784c32012-11-19 14:55:58 -08003222 }
3223 }
3224 mNormalFrameCount = multiplier * mFrameCount;
3225 // round up to nearest 16 frames to satisfy AudioMixer
Eric Laurentb3f315a2021-07-13 15:09:05 +02003226 if (hasMixer()) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07003227 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
3228 }
Andy Hungab65b182023-09-06 19:41:47 -07003229 ALOGI("HAL output buffer size %zu frames, normal sink buffer size %zu frames",
3230 (size_t)mFrameCount, mNormalFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08003231
Andy Hung08fb1742015-05-31 23:22:10 -07003232 // Check if we want to throttle the processing to no more than 2x normal rate
3233 mThreadThrottle = property_get_bool("af.thread.throttle", true /* default_value */);
Andy Hung40eb1a12015-06-18 13:42:02 -07003234 mThreadThrottleTimeMs = 0;
3235 mThreadThrottleEndMs = 0;
Andy Hung08fb1742015-05-31 23:22:10 -07003236 mHalfBufferMs = mNormalFrameCount * 1000 / (2 * mSampleRate);
3237
Andy Hung010a1a12014-03-13 13:57:33 -07003238 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
3239 // Originally this was int16_t[] array, need to remove legacy implications.
3240 free(mSinkBuffer);
3241 mSinkBuffer = NULL;
Eric Laurent39095982021-08-24 18:29:27 +02003242
Andy Hung5b10a202014-03-13 13:59:29 -07003243 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
3244 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
3245 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07003246 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08003247
Andy Hung69aed5f2014-02-25 17:24:40 -08003248 // We resize the mMixerBuffer according to the requirements of the sink buffer which
3249 // drives the output.
3250 free(mMixerBuffer);
3251 mMixerBuffer = NULL;
3252 if (mMixerBufferEnabled) {
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01003253 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // no longer valid: AUDIO_FORMAT_PCM_16_BIT.
Eric Laurentf1f22e72021-07-13 14:04:14 +02003254 mMixerBufferSize = mNormalFrameCount * mixerChannelCount
Andy Hung69aed5f2014-02-25 17:24:40 -08003255 * audio_bytes_per_sample(mMixerBufferFormat);
3256 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
3257 }
Andy Hung98ef9782014-03-04 14:46:50 -08003258 free(mEffectBuffer);
3259 mEffectBuffer = NULL;
3260 if (mEffectBufferEnabled) {
Andy Hung319587b2023-05-23 14:01:03 -07003261 mEffectBufferFormat = AUDIO_FORMAT_PCM_FLOAT;
Eric Laurentf1f22e72021-07-13 14:04:14 +02003262 mEffectBufferSize = mNormalFrameCount * mixerChannelCount
Andy Hung98ef9782014-03-04 14:46:50 -08003263 * audio_bytes_per_sample(mEffectBufferFormat);
3264 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
3265 }
Andy Hung69aed5f2014-02-25 17:24:40 -08003266
Eric Laurentb62d0362021-10-26 17:40:18 +02003267 if (mType == SPATIALIZER) {
3268 free(mPostSpatializerBuffer);
3269 mPostSpatializerBuffer = nullptr;
3270 mPostSpatializerBufferSize = mNormalFrameCount * mChannelCount
3271 * audio_bytes_per_sample(mEffectBufferFormat);
3272 (void)posix_memalign(&mPostSpatializerBuffer, 32, mPostSpatializerBufferSize);
3273 }
3274
Mikhail Naganov55773032020-10-01 15:08:13 -07003275 mHapticChannelMask = static_cast<audio_channel_mask_t>(mChannelMask & AUDIO_CHANNEL_HAPTIC_ALL);
3276 mChannelMask = static_cast<audio_channel_mask_t>(mChannelMask & ~mHapticChannelMask);
jiabin245cdd92018-12-07 17:55:15 -08003277 mHapticChannelCount = audio_channel_count_from_out_mask(mHapticChannelMask);
3278 mChannelCount -= mHapticChannelCount;
Eric Laurentf1f22e72021-07-13 14:04:14 +02003279 mMixerChannelMask = static_cast<audio_channel_mask_t>(mMixerChannelMask & ~mHapticChannelMask);
jiabin245cdd92018-12-07 17:55:15 -08003280
Eric Laurent81784c32012-11-19 14:55:58 -08003281 // force reconfiguration of effect chains and engines to take new buffer size and audio
3282 // parameters into account
Andy Hungc5007f82023-08-29 14:26:09 -07003283 // Note that mutex() is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08003284 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
3285 // matter.
Andy Hung972bec12023-08-31 16:13:39 -07003286 // create a copy of mEffectChains as calling moveEffectChain_ll()
3287 // can reorder some effect chains
Andy Hung116bc262023-06-20 18:56:17 -07003288 Vector<sp<IAfEffectChain>> effectChains = mEffectChains;
Eric Laurent81784c32012-11-19 14:55:58 -08003289 for (size_t i = 0; i < effectChains.size(); i ++) {
Andy Hung972bec12023-08-31 16:13:39 -07003290 mAfThreadCallback->moveEffectChain_ll(effectChains[i]->sessionId(),
Eric Laurent6c796322019-04-09 14:13:17 -07003291 this/* srcThread */, this/* dstThread */);
Eric Laurent81784c32012-11-19 14:55:58 -08003292 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08003293
George Burgess IV5e4d86f2020-02-18 12:55:36 -08003294 audio_output_flags_t flags = mOutput->flags;
Andy Hungcf10d742020-04-28 15:38:24 -07003295 mediametrics::LogItem item(mThreadMetrics.getMetricsId()); // TODO: method in ThreadMetrics?
Andy Hungb68f5eb2019-12-03 16:49:17 -08003296 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
Andy Hung25a80ac2023-07-19 12:47:35 -07003297 .set(AMEDIAMETRICS_PROP_ENCODING, IAfThreadBase::formatToString(mFormat).c_str())
Andy Hungb68f5eb2019-12-03 16:49:17 -08003298 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
3299 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
3300 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
3301 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mNormalFrameCount)
3302 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
3303 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELMASK,
3304 (int32_t)mHapticChannelMask)
3305 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELCOUNT,
3306 (int32_t)mHapticChannelCount)
3307 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_ENCODING,
Andy Hung25a80ac2023-07-19 12:47:35 -07003308 IAfThreadBase::formatToString(mHALFormat).c_str())
Andy Hungb68f5eb2019-12-03 16:49:17 -08003309 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_FRAMECOUNT,
3310 (int32_t)mFrameCount) // sic - added HAL
3311 ;
3312 uint32_t latencyMs;
3313 if (mOutput->stream->getLatency(&latencyMs) == NO_ERROR) {
3314 item.set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_LATENCYMS, (double)latencyMs);
3315 }
3316 item.record();
Eric Laurent81784c32012-11-19 14:55:58 -08003317}
3318
Andy Hungee58e4a2023-07-07 13:47:37 -07003319ThreadBase::MetadataUpdate PlaybackThread::updateMetadata_l()
Kevin Rocard069c2712018-03-29 19:09:14 -07003320{
Jasmine Chaeaa10e42021-05-11 10:11:14 +08003321 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
Vlad Popa7e81cea2023-01-19 16:34:16 +01003322 return {}; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -07003323 }
3324 StreamOutHalInterface::SourceMetadata metadata;
Nikhil Bhanu8f4ea772024-01-31 17:15:52 -08003325 static const bool stereo_spatialization_property =
3326 property_get_bool("ro.audio.stereo_spatialization_enabled", false);
3327 const bool stereo_spatialization_enabled =
3328 stereo_spatialization_property && com_android_media_audio_stereo_spatialization();
3329 if (stereo_spatialization_enabled) {
Eric Laurent4eb45d02023-12-20 12:07:17 +01003330 std::map<audio_session_t, std::vector<playback_track_metadata_v7_t> >allSessionsMetadata;
3331 for (const sp<IAfTrack>& track : mActiveTracks) {
3332 std::vector<playback_track_metadata_v7_t>& sessionMetadata =
3333 allSessionsMetadata[track->sessionId()];
3334 auto backInserter = std::back_inserter(sessionMetadata);
3335 // No track is invalid as this is called after prepareTrack_l in the same
3336 // critical section
3337 track->copyMetadataTo(backInserter);
3338 }
3339 std::vector<playback_track_metadata_v7_t> spatializedTracksMetaData;
3340 for (const auto& [session, sessionTrackMetadata] : allSessionsMetadata) {
3341 metadata.tracks.insert(metadata.tracks.end(),
3342 sessionTrackMetadata.begin(), sessionTrackMetadata.end());
3343 if (auto chain = getEffectChain_l(session) ; chain != nullptr) {
3344 chain->sendMetadata_l(sessionTrackMetadata, {});
3345 }
3346 if ((hasAudioSession_l(session) & IAfThreadBase::SPATIALIZED_SESSION) != 0) {
3347 spatializedTracksMetaData.insert(spatializedTracksMetaData.end(),
3348 sessionTrackMetadata.begin(), sessionTrackMetadata.end());
3349 }
3350 }
3351 if (auto chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX); chain != nullptr) {
3352 chain->sendMetadata_l(metadata.tracks, {});
3353 }
3354 if (auto chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_STAGE); chain != nullptr) {
3355 chain->sendMetadata_l(metadata.tracks, spatializedTracksMetaData);
3356 }
3357 if (auto chain = getEffectChain_l(AUDIO_SESSION_DEVICE); chain != nullptr) {
3358 chain->sendMetadata_l(metadata.tracks, {});
3359 }
3360 } else {
3361 auto backInserter = std::back_inserter(metadata.tracks);
3362 for (const sp<IAfTrack>& track : mActiveTracks) {
3363 // No track is invalid as this is called after prepareTrack_l in the same
3364 // critical section
3365 track->copyMetadataTo(backInserter);
3366 }
Kevin Rocard069c2712018-03-29 19:09:14 -07003367 }
Kevin Rocard12381092018-04-11 09:19:59 -07003368 sendMetadataToBackend_l(metadata);
Vlad Popa7e81cea2023-01-19 16:34:16 +01003369 MetadataUpdate change;
3370 change.playbackMetadataUpdate = metadata.tracks;
3371 return change;
Kevin Rocard80ee2722018-04-11 15:53:48 +00003372}
Kevin Rocardc86a7f72018-04-03 09:00:09 -07003373
Andy Hungee58e4a2023-07-07 13:47:37 -07003374void PlaybackThread::sendMetadataToBackend_l(
Kevin Rocard12381092018-04-11 09:19:59 -07003375 const StreamOutHalInterface::SourceMetadata& metadata)
3376{
3377 mOutput->stream->updateSourceMetadata(metadata);
3378};
3379
Andy Hungee58e4a2023-07-07 13:47:37 -07003380status_t PlaybackThread::getRenderPosition(
Andy Hung440901d2023-06-29 21:19:25 -07003381 uint32_t* halFrames, uint32_t* dspFrames) const
Eric Laurent81784c32012-11-19 14:55:58 -08003382{
3383 if (halFrames == NULL || dspFrames == NULL) {
3384 return BAD_VALUE;
3385 }
Andy Hung972bec12023-08-31 16:13:39 -07003386 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08003387 if (initCheck() != NO_ERROR) {
3388 return INVALID_OPERATION;
3389 }
Andy Hung818e7a32016-02-16 18:08:07 -08003390 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08003391 *halFrames = framesWritten;
3392
3393 if (isSuspended()) {
3394 // return an estimation of rendered frames when the output is suspended
3395 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08003396 *dspFrames = (uint32_t)
3397 (framesWritten >= (int64_t)latencyFrames ? framesWritten - latencyFrames : 0);
Eric Laurent81784c32012-11-19 14:55:58 -08003398 return NO_ERROR;
3399 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003400 status_t status;
3401 uint32_t frames;
Phil Burk062e67a2015-02-11 13:40:50 -08003402 status = mOutput->getRenderPosition(&frames);
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003403 *dspFrames = (size_t)frames;
3404 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08003405 }
3406}
3407
Andy Hungee58e4a2023-07-07 13:47:37 -07003408product_strategy_t PlaybackThread::getStrategyForSession_l(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08003409{
3410 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
3411 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
3412 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02003413 return getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurent81784c32012-11-19 14:55:58 -08003414 }
3415 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003416 sp<IAfTrack> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08003417 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02003418 return getStrategyForStream(track->streamType());
Eric Laurent81784c32012-11-19 14:55:58 -08003419 }
3420 }
Eric Laurentd66d7a12021-07-13 13:35:32 +02003421 return getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurent81784c32012-11-19 14:55:58 -08003422}
3423
3424
Andy Hungee58e4a2023-07-07 13:47:37 -07003425AudioStreamOut* PlaybackThread::getOutput() const
Eric Laurent81784c32012-11-19 14:55:58 -08003426{
Andy Hung972bec12023-08-31 16:13:39 -07003427 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08003428 return mOutput;
3429}
3430
Andy Hungee58e4a2023-07-07 13:47:37 -07003431AudioStreamOut* PlaybackThread::clearOutput()
Eric Laurent81784c32012-11-19 14:55:58 -08003432{
Andy Hung972bec12023-08-31 16:13:39 -07003433 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08003434 AudioStreamOut *output = mOutput;
3435 mOutput = NULL;
3436 // FIXME FastMixer might also have a raw ptr to mOutputSink;
3437 // must push a NULL and wait for ack
3438 mOutputSink.clear();
3439 mPipeSink.clear();
3440 mNormalSink.clear();
3441 return output;
3442}
3443
Andy Hungc5007f82023-08-29 14:26:09 -07003444// this method must always be called either with ThreadBase mutex() held or inside the thread loop
Andy Hungee58e4a2023-07-07 13:47:37 -07003445sp<StreamHalInterface> PlaybackThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08003446{
3447 if (mOutput == NULL) {
3448 return NULL;
3449 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003450 return mOutput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08003451}
3452
Andy Hungee58e4a2023-07-07 13:47:37 -07003453uint32_t PlaybackThread::activeSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08003454{
3455 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
3456}
3457
Andy Hungee58e4a2023-07-07 13:47:37 -07003458status_t PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
Eric Laurent81784c32012-11-19 14:55:58 -08003459{
3460 if (!isValidSyncEvent(event)) {
3461 return BAD_VALUE;
3462 }
3463
Andy Hung972bec12023-08-31 16:13:39 -07003464 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08003465
3466 for (size_t i = 0; i < mTracks.size(); ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003467 sp<IAfTrack> track = mTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08003468 if (event->triggerSession() == track->sessionId()) {
3469 (void) track->setSyncEvent(event);
3470 return NO_ERROR;
3471 }
3472 }
3473
3474 return NAME_NOT_FOUND;
3475}
3476
Andy Hungee58e4a2023-07-07 13:47:37 -07003477bool PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
Eric Laurent81784c32012-11-19 14:55:58 -08003478{
3479 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
3480}
3481
Andy Hungee58e4a2023-07-07 13:47:37 -07003482void PlaybackThread::threadLoop_removeTracks(
Andy Hung8d31fd22023-06-26 19:20:57 -07003483 [[maybe_unused]] const Vector<sp<IAfTrack>>& tracksToRemove)
Eric Laurent81784c32012-11-19 14:55:58 -08003484{
Andy Hungfe726a62018-09-27 15:17:25 -07003485 // Miscellaneous track cleanup when removed from the active list,
3486 // called without Thread lock but synchronized with threadLoop processing.
Eric Laurentbfb1b832013-01-07 09:53:42 -08003487#ifdef ADD_BATTERY_DATA
Andy Hungfe726a62018-09-27 15:17:25 -07003488 for (const auto& track : tracksToRemove) {
3489 if (track->isExternalTrack()) {
3490 // to track the speaker usage
3491 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Eric Laurent81784c32012-11-19 14:55:58 -08003492 }
3493 }
Andy Hungfe726a62018-09-27 15:17:25 -07003494#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003495}
3496
Andy Hungee58e4a2023-07-07 13:47:37 -07003497void PlaybackThread::checkSilentMode_l()
Eric Laurent81784c32012-11-19 14:55:58 -08003498{
3499 if (!mMasterMute) {
3500 char value[PROPERTY_VALUE_MAX];
jiabin0a957d32020-04-29 10:56:20 -07003501 if (mOutDeviceTypeAddrs.empty()) {
3502 ALOGD("ro.audio.silent is ignored since no output device is set");
3503 return;
3504 }
Andy Hungab65b182023-09-06 19:41:47 -07003505 if (isSingleDeviceType(outDeviceTypes_l(), AUDIO_DEVICE_OUT_REMOTE_SUBMIX)) {
Jean-Michel Trivi32f37c22016-03-31 16:00:32 -07003506 ALOGD("ro.audio.silent will be ignored for threads on AUDIO_DEVICE_OUT_REMOTE_SUBMIX");
3507 return;
3508 }
Eric Laurent81784c32012-11-19 14:55:58 -08003509 if (property_get("ro.audio.silent", value, "0") > 0) {
3510 char *endptr;
3511 unsigned long ul = strtoul(value, &endptr, 0);
3512 if (*endptr == '\0' && ul != 0) {
3513 ALOGD("Silence is golden");
3514 // The setprop command will not allow a property to be changed after
3515 // the first time it is set, so we don't have to worry about un-muting.
3516 setMasterMute_l(true);
3517 }
3518 }
3519 }
3520}
3521
3522// shared by MIXER and DIRECT, overridden by DUPLICATING
Andy Hungee58e4a2023-07-07 13:47:37 -07003523ssize_t PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08003524{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07003525 LOG_HIST_TS();
Eric Laurent81784c32012-11-19 14:55:58 -08003526 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003527 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07003528 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08003529
3530 // If an NBAIO sink is present, use it to write the normal mixer's submix
3531 if (mNormalSink != 0) {
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003532
Andy Hung010a1a12014-03-13 13:57:33 -07003533 const size_t count = mBytesRemaining / mFrameSize;
3534
Simon Wilson2d590962012-11-29 15:18:50 -08003535 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08003536 // update the setpoint when AudioFlinger::mScreenState changes
Andy Hung1d2d2aea2023-07-19 16:22:58 -07003537 const uint32_t screenState = mAfThreadCallback->getScreenState();
Eric Laurent81784c32012-11-19 14:55:58 -08003538 if (screenState != mScreenState) {
3539 mScreenState = screenState;
3540 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
3541 if (pipe != NULL) {
3542 pipe->setAvgFrames((mScreenState & 1) ?
3543 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
3544 }
3545 }
Andy Hung010a1a12014-03-13 13:57:33 -07003546 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08003547 ATRACE_END();
Vlad Popab042ee62022-10-20 18:05:00 +02003548
Eric Laurent81784c32012-11-19 14:55:58 -08003549 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07003550 bytesWritten = framesWritten * mFrameSize;
Andy Hung58e32872022-11-15 16:12:24 -08003551
Andy Hung8946a282018-04-19 20:04:56 -07003552#ifdef TEE_SINK
3553 mTee.write((char *)mSinkBuffer + offset, framesWritten);
3554#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003555 } else {
3556 bytesWritten = framesWritten;
3557 }
3558 // otherwise use the HAL / AudioStreamOut directly
3559 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003560 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07003561
Eric Laurentbfb1b832013-01-07 09:53:42 -08003562 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003563 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
3564 mWriteAckSequence += 2;
3565 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003566 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003567 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003568 }
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07003569 ATRACE_BEGIN("write");
Glenn Kasten767094d2013-08-23 13:51:43 -07003570 // FIXME We should have an implementation of timestamps for direct output threads.
3571 // They are used e.g for multichannel PCM playback over HDMI.
Phil Burk062e67a2015-02-11 13:40:50 -08003572 bytesWritten = mOutput->write((char *)mSinkBuffer + offset, mBytesRemaining);
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07003573 ATRACE_END();
Eric Laurent51716182016-02-29 18:00:56 -08003574
Eric Laurentbfb1b832013-01-07 09:53:42 -08003575 if (mUseAsyncWrite &&
3576 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
3577 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07003578 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003579 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003580 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003581 }
Eric Laurent81784c32012-11-19 14:55:58 -08003582 }
3583
Eric Laurent81784c32012-11-19 14:55:58 -08003584 mNumWrites++;
3585 mInWrite = false;
Andy Hungcf10d742020-04-28 15:38:24 -07003586 if (mStandby) {
3587 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07003588 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -07003589 mStandby = false;
3590 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003591 return bytesWritten;
3592}
3593
Andy Hungc5007f82023-08-29 14:26:09 -07003594// startMelComputation_l() must be called with AudioFlinger::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07003595void PlaybackThread::startMelComputation_l(
Vlad Popaf09e93f2022-10-31 16:27:12 +01003596 const sp<audio_utils::MelProcessor>& processor)
Vlad Popab042ee62022-10-20 18:05:00 +02003597{
Vlad Popa3c7a2662023-02-14 20:09:47 +01003598 auto outputSink = static_cast<AudioStreamOutSink*>(mOutputSink.get());
Vlad Popa1a0c3ab2023-03-17 01:07:01 +01003599 if (outputSink != nullptr) {
3600 outputSink->startMelComputation(processor);
3601 }
Vlad Popab042ee62022-10-20 18:05:00 +02003602}
3603
Andy Hungc5007f82023-08-29 14:26:09 -07003604// stopMelComputation_l() must be called with AudioFlinger::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07003605void PlaybackThread::stopMelComputation_l()
Vlad Popa3c7a2662023-02-14 20:09:47 +01003606{
3607 auto outputSink = static_cast<AudioStreamOutSink*>(mOutputSink.get());
Vlad Popa1a0c3ab2023-03-17 01:07:01 +01003608 if (outputSink != nullptr) {
3609 outputSink->stopMelComputation();
3610 }
Vlad Popab042ee62022-10-20 18:05:00 +02003611}
3612
Andy Hungee58e4a2023-07-07 13:47:37 -07003613void PlaybackThread::threadLoop_drain()
Eric Laurentbfb1b832013-01-07 09:53:42 -08003614{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003615 bool supportsDrain = false;
3616 if (mOutput->stream->supportsDrain(&supportsDrain) == OK && supportsDrain) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003617 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
3618 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003619 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
3620 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003621 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003622 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003623 }
Mikhail Naganovcbc8f612016-10-11 18:05:13 -07003624 status_t result = mOutput->stream->drain(mMixerStatus == MIXER_DRAIN_TRACK);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003625 ALOGE_IF(result != OK, "Error when draining stream: %d", result);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003626 }
3627}
3628
Andy Hungee58e4a2023-07-07 13:47:37 -07003629void PlaybackThread::threadLoop_exit()
Eric Laurentbfb1b832013-01-07 09:53:42 -08003630{
Eric Laurent275e8e92014-11-30 15:14:47 -08003631 {
Andy Hung972bec12023-08-31 16:13:39 -07003632 audio_utils::lock_guard _l(mutex());
Eric Laurent275e8e92014-11-30 15:14:47 -08003633 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003634 sp<IAfTrack> track = mTracks[i];
Eric Laurent275e8e92014-11-30 15:14:47 -08003635 track->invalidate();
3636 }
Andy Hungdae27702016-10-31 14:01:16 -07003637 // Clear ActiveTracks to update BatteryNotifier in case active tracks remain.
3638 // After we exit there are no more track changes sent to BatteryNotifier
3639 // because that requires an active threadLoop.
3640 // TODO: should we decActiveTrackCnt() of the cleared track effect chain?
3641 mActiveTracks.clear();
Eric Laurent275e8e92014-11-30 15:14:47 -08003642 }
Eric Laurent81784c32012-11-19 14:55:58 -08003643}
3644
3645/*
3646The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08003647 - mSinkBufferSize from frame count * frame size
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003648 - mActiveSleepTimeUs from activeSleepTimeUs()
3649 - mIdleSleepTimeUs from idleSleepTimeUs()
Eric Laurent42537be2016-01-08 17:16:42 -08003650 - mStandbyDelayNs from mActiveSleepTimeUs (DIRECT only) or forced to at least
3651 kDefaultStandbyTimeInNsecs when connected to an A2DP device.
Eric Laurent81784c32012-11-19 14:55:58 -08003652 - maxPeriod from frame count and sample rate (MIXER only)
3653
3654The parameters that affect these derived values are:
3655 - frame count
3656 - frame size
3657 - sample rate
3658 - device type: A2DP or not
3659 - device latency
3660 - format: PCM or not
3661 - active sleep time
3662 - idle sleep time
3663*/
3664
Andy Hungee58e4a2023-07-07 13:47:37 -07003665void PlaybackThread::cacheParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08003666{
Andy Hung25c2dac2014-02-27 14:56:00 -08003667 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003668 mActiveSleepTimeUs = activeSleepTimeUs();
3669 mIdleSleepTimeUs = idleSleepTimeUs();
Eric Laurent42537be2016-01-08 17:16:42 -08003670
Andy Hung8fe87eb2023-07-20 21:31:38 -07003671 mStandbyDelayNs = getStandbyTimeInNanos();
Carter Hsu0ca47c22023-06-02 18:01:45 +08003672
Eric Laurent42537be2016-01-08 17:16:42 -08003673 // make sure standby delay is not too short when connected to an A2DP sink to avoid
3674 // truncating audio when going to standby.
Andy Hungab65b182023-09-06 19:41:47 -07003675 if (!Intersection(outDeviceTypes_l(), getAudioDeviceOutAllA2dpSet()).empty()) {
Eric Laurent42537be2016-01-08 17:16:42 -08003676 if (mStandbyDelayNs < kDefaultStandbyTimeInNsecs) {
3677 mStandbyDelayNs = kDefaultStandbyTimeInNsecs;
3678 }
3679 }
Eric Laurent81784c32012-11-19 14:55:58 -08003680}
3681
Andy Hungee58e4a2023-07-07 13:47:37 -07003682bool PlaybackThread::invalidateTracks_l(audio_stream_type_t streamType)
Eric Laurent81784c32012-11-19 14:55:58 -08003683{
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003684 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %zu",
Eric Laurent81784c32012-11-19 14:55:58 -08003685 this, streamType, mTracks.size());
Eric Laurent13084622016-05-17 10:51:49 -07003686 bool trackMatch = false;
Eric Laurent81784c32012-11-19 14:55:58 -08003687 size_t size = mTracks.size();
3688 for (size_t i = 0; i < size; i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003689 sp<IAfTrack> t = mTracks[i];
Eric Laurentd60560a2015-04-10 11:31:20 -07003690 if (t->streamType() == streamType && t->isExternalTrack()) {
Glenn Kasten5736c352012-12-04 12:12:34 -08003691 t->invalidate();
Eric Laurent13084622016-05-17 10:51:49 -07003692 trackMatch = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003693 }
3694 }
Eric Laurent13084622016-05-17 10:51:49 -07003695 return trackMatch;
Eric Laurent81784c32012-11-19 14:55:58 -08003696}
3697
Andy Hungee58e4a2023-07-07 13:47:37 -07003698void PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
Haynes Mathew George05317d22016-05-03 16:34:26 -07003699{
Andy Hung972bec12023-08-31 16:13:39 -07003700 audio_utils::lock_guard _l(mutex());
Haynes Mathew George05317d22016-05-03 16:34:26 -07003701 invalidateTracks_l(streamType);
3702}
3703
Andy Hungee58e4a2023-07-07 13:47:37 -07003704void PlaybackThread::invalidateTracks(std::set<audio_port_handle_t>& portIds) {
Andy Hung972bec12023-08-31 16:13:39 -07003705 audio_utils::lock_guard _l(mutex());
jiabinc44b3462022-12-08 12:52:31 -08003706 invalidateTracks_l(portIds);
3707}
3708
Andy Hungee58e4a2023-07-07 13:47:37 -07003709bool PlaybackThread::invalidateTracks_l(std::set<audio_port_handle_t>& portIds) {
jiabinc44b3462022-12-08 12:52:31 -08003710 bool trackMatch = false;
3711 const size_t size = mTracks.size();
3712 for (size_t i = 0; i < size; i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003713 sp<IAfTrack> t = mTracks[i];
jiabinc44b3462022-12-08 12:52:31 -08003714 if (t->isExternalTrack() && portIds.find(t->portId()) != portIds.end()) {
3715 t->invalidate();
3716 portIds.erase(t->portId());
3717 trackMatch = true;
3718 }
3719 if (portIds.empty()) {
3720 break;
3721 }
3722 }
3723 return trackMatch;
3724}
3725
jiabinf042b9b2021-05-07 23:46:28 +00003726// getTrackById_l must be called with holding thread lock
Andy Hungee58e4a2023-07-07 13:47:37 -07003727IAfTrack* PlaybackThread::getTrackById_l(
jiabinf042b9b2021-05-07 23:46:28 +00003728 audio_port_handle_t trackPortId) {
3729 for (size_t i = 0; i < mTracks.size(); i++) {
3730 if (mTracks[i]->portId() == trackPortId) {
3731 return mTracks[i].get();
3732 }
3733 }
3734 return nullptr;
3735}
3736
Andy Hungee58e4a2023-07-07 13:47:37 -07003737status_t PlaybackThread::addEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08003738{
Glenn Kastend848eb42016-03-08 13:42:11 -08003739 audio_session_t session = chain->sessionId();
Mikhail Naganov022b9952017-01-04 16:36:51 -08003740 sp<EffectBufferHalInterface> halInBuffer, halOutBuffer;
Andy Hung319587b2023-05-23 14:01:03 -07003741 float *buffer = nullptr; // only used for non global sessions
Eric Laurentb62d0362021-10-26 17:40:18 +02003742
Andy Hungd3639922022-04-28 18:00:49 -07003743 if (mType == SPATIALIZER) {
Eric Laurentb62d0362021-10-26 17:40:18 +02003744 if (!audio_is_global_session(session)) {
3745 // player sessions on a spatializer output will use a dedicated input buffer and
3746 // will either output multi channel to mEffectBuffer if the track is spatilaized
3747 // or stereo to mPostSpatializerBuffer if not spatialized.
3748 uint32_t channelMask;
3749 bool isSessionSpatialized =
3750 (hasAudioSession_l(session) & ThreadBase::SPATIALIZED_SESSION) != 0;
3751 if (isSessionSpatialized) {
3752 channelMask = mMixerChannelMask;
3753 } else {
3754 channelMask = mChannelMask;
3755 }
Eric Laurentf1f22e72021-07-13 14:04:14 +02003756 size_t numSamples = mNormalFrameCount
Eric Laurentb62d0362021-10-26 17:40:18 +02003757 * (audio_channel_count_from_out_mask(channelMask) + mHapticChannelCount);
Andy Hung583043b2023-07-17 17:05:00 -07003758 status_t result = mAfThreadCallback->getEffectsFactoryHal()->allocateBuffer(
Andy Hung319587b2023-05-23 14:01:03 -07003759 numSamples * sizeof(float),
Mikhail Naganov022b9952017-01-04 16:36:51 -08003760 &halInBuffer);
3761 if (result != OK) return result;
Eric Laurentb62d0362021-10-26 17:40:18 +02003762
Andy Hung583043b2023-07-17 17:05:00 -07003763 result = mAfThreadCallback->getEffectsFactoryHal()->mirrorBuffer(
Eric Laurentb62d0362021-10-26 17:40:18 +02003764 isSessionSpatialized ? mEffectBuffer : mPostSpatializerBuffer,
3765 isSessionSpatialized ? mEffectBufferSize : mPostSpatializerBufferSize,
3766 &halOutBuffer);
3767 if (result != OK) return result;
3768
Shunkai Yao44bdbad2023-01-14 05:11:58 +00003769 buffer = halInBuffer ? halInBuffer->audioBuffer()->f32 : buffer;
Andy Hung26836922023-05-22 17:31:57 -07003770
Mikhail Naganov022b9952017-01-04 16:36:51 -08003771 ALOGV("addEffectChain_l() creating new input buffer %p session %d",
3772 buffer, session);
Eric Laurentb62d0362021-10-26 17:40:18 +02003773 } else {
3774 // A global session on a SPATIALIZER thread is either OUTPUT_STAGE or DEVICE
3775 // - OUTPUT_STAGE session uses the mEffectBuffer as input buffer and
3776 // mPostSpatializerBuffer as output buffer
3777 // - DEVICE session uses the mPostSpatializerBuffer as input and output buffer.
Andy Hung583043b2023-07-17 17:05:00 -07003778 status_t result = mAfThreadCallback->getEffectsFactoryHal()->mirrorBuffer(
Eric Laurentb62d0362021-10-26 17:40:18 +02003779 mEffectBuffer, mEffectBufferSize, &halInBuffer);
3780 if (result != OK) return result;
Andy Hung583043b2023-07-17 17:05:00 -07003781 result = mAfThreadCallback->getEffectsFactoryHal()->mirrorBuffer(
Eric Laurentb62d0362021-10-26 17:40:18 +02003782 mPostSpatializerBuffer, mPostSpatializerBufferSize, &halOutBuffer);
3783 if (result != OK) return result;
Eric Laurent81784c32012-11-19 14:55:58 -08003784
Eric Laurentb62d0362021-10-26 17:40:18 +02003785 if (session == AUDIO_SESSION_DEVICE) {
3786 halInBuffer = halOutBuffer;
3787 }
3788 }
3789 } else {
Andy Hung583043b2023-07-17 17:05:00 -07003790 status_t result = mAfThreadCallback->getEffectsFactoryHal()->mirrorBuffer(
Eric Laurentb62d0362021-10-26 17:40:18 +02003791 mEffectBufferEnabled ? mEffectBuffer : mSinkBuffer,
3792 mEffectBufferEnabled ? mEffectBufferSize : mSinkBufferSize,
3793 &halInBuffer);
3794 if (result != OK) return result;
3795 halOutBuffer = halInBuffer;
3796 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
3797 if (!audio_is_global_session(session)) {
Andy Hung319587b2023-05-23 14:01:03 -07003798 buffer = halInBuffer ? reinterpret_cast<float*>(halInBuffer->externalData())
Shunkai Yao44bdbad2023-01-14 05:11:58 +00003799 : buffer;
Eric Laurentb62d0362021-10-26 17:40:18 +02003800 // Only one effect chain can be present in direct output thread and it uses
3801 // the sink buffer as input
3802 if (mType != DIRECT) {
3803 size_t numSamples = mNormalFrameCount
3804 * (audio_channel_count_from_out_mask(mMixerChannelMask)
3805 + mHapticChannelCount);
Andy Hung583043b2023-07-17 17:05:00 -07003806 const status_t allocateStatus =
3807 mAfThreadCallback->getEffectsFactoryHal()->allocateBuffer(
Andy Hung319587b2023-05-23 14:01:03 -07003808 numSamples * sizeof(float),
Eric Laurentb62d0362021-10-26 17:40:18 +02003809 &halInBuffer);
Andy Hung920f6572022-10-06 12:09:49 -07003810 if (allocateStatus != OK) return allocateStatus;
Andy Hung26836922023-05-22 17:31:57 -07003811
Shunkai Yao44bdbad2023-01-14 05:11:58 +00003812 buffer = halInBuffer ? halInBuffer->audioBuffer()->f32 : buffer;
Eric Laurentb62d0362021-10-26 17:40:18 +02003813 ALOGV("addEffectChain_l() creating new input buffer %p session %d",
3814 buffer, session);
3815 }
3816 }
3817 }
3818
3819 if (!audio_is_global_session(session)) {
Eric Laurent81784c32012-11-19 14:55:58 -08003820 // Attach all tracks with same session ID to this chain.
3821 for (size_t i = 0; i < mTracks.size(); ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003822 sp<IAfTrack> track = mTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08003823 if (session == track->sessionId()) {
Eric Laurentb62d0362021-10-26 17:40:18 +02003824 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p",
3825 track.get(), buffer);
Eric Laurent81784c32012-11-19 14:55:58 -08003826 track->setMainBuffer(buffer);
3827 chain->incTrackCnt();
3828 }
3829 }
3830
3831 // indicate all active tracks in the chain
Andy Hung8d31fd22023-06-26 19:20:57 -07003832 for (const sp<IAfTrack>& track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08003833 if (session == track->sessionId()) {
Eric Laurentb62d0362021-10-26 17:40:18 +02003834 ALOGV("addEffectChain_l() activating track %p on session %d",
3835 track.get(), session);
Eric Laurent81784c32012-11-19 14:55:58 -08003836 chain->incActiveTrackCnt();
3837 }
3838 }
3839 }
Eric Laurentb62d0362021-10-26 17:40:18 +02003840
Eric Laurentaaa44472014-09-12 17:41:50 -07003841 chain->setThread(this);
Mikhail Naganov022b9952017-01-04 16:36:51 -08003842 chain->setInBuffer(halInBuffer);
3843 chain->setOutBuffer(halOutBuffer);
Eric Laurent3f75a5b2019-11-12 15:55:51 -08003844 // Effect chain for session AUDIO_SESSION_DEVICE is inserted at end of effect
3845 // chains list in order to be processed last as it contains output device effects.
3846 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted just before to apply post
3847 // processing effects specific to an output stream before effects applied to all streams
3848 // routed to a given device.
Eric Laurent81784c32012-11-19 14:55:58 -08003849 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
3850 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Glenn Kastend848eb42016-03-08 13:42:11 -08003851 // after track specific effects and before output stage.
Eric Laurent81784c32012-11-19 14:55:58 -08003852 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
Glenn Kastend848eb42016-03-08 13:42:11 -08003853 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX.
Eric Laurent81784c32012-11-19 14:55:58 -08003854 // Effect chain for other sessions are inserted at beginning of effect
3855 // chains list to be processed before output mix effects. Relative order between other
Glenn Kastend848eb42016-03-08 13:42:11 -08003856 // sessions is not important.
3857 static_assert(AUDIO_SESSION_OUTPUT_MIX == 0 &&
Eric Laurent3f75a5b2019-11-12 15:55:51 -08003858 AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX &&
3859 AUDIO_SESSION_DEVICE < AUDIO_SESSION_OUTPUT_STAGE,
Glenn Kastend848eb42016-03-08 13:42:11 -08003860 "audio_session_t constants misdefined");
Eric Laurent81784c32012-11-19 14:55:58 -08003861 size_t size = mEffectChains.size();
3862 size_t i = 0;
3863 for (i = 0; i < size; i++) {
3864 if (mEffectChains[i]->sessionId() < session) {
3865 break;
3866 }
3867 }
3868 mEffectChains.insertAt(chain, i);
3869 checkSuspendOnAddEffectChain_l(chain);
3870
3871 return NO_ERROR;
3872}
3873
Andy Hungee58e4a2023-07-07 13:47:37 -07003874size_t PlaybackThread::removeEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08003875{
Glenn Kastend848eb42016-03-08 13:42:11 -08003876 audio_session_t session = chain->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08003877
3878 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
3879
3880 for (size_t i = 0; i < mEffectChains.size(); i++) {
3881 if (chain == mEffectChains[i]) {
3882 mEffectChains.removeAt(i);
3883 // detach all active tracks from the chain
Andy Hung8d31fd22023-06-26 19:20:57 -07003884 for (const sp<IAfTrack>& track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08003885 if (session == track->sessionId()) {
3886 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
3887 chain.get(), session);
3888 chain->decActiveTrackCnt();
3889 }
3890 }
3891
3892 // detach all tracks with same session ID from this chain
Andy Hung920f6572022-10-06 12:09:49 -07003893 for (size_t j = 0; j < mTracks.size(); ++j) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003894 sp<IAfTrack> track = mTracks[j];
Eric Laurent81784c32012-11-19 14:55:58 -08003895 if (session == track->sessionId()) {
Andy Hung319587b2023-05-23 14:01:03 -07003896 track->setMainBuffer(reinterpret_cast<float*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08003897 chain->decTrackCnt();
3898 }
3899 }
3900 break;
3901 }
3902 }
3903 return mEffectChains.size();
3904}
3905
Andy Hungee58e4a2023-07-07 13:47:37 -07003906status_t PlaybackThread::attachAuxEffect(
Andy Hung8d31fd22023-06-26 19:20:57 -07003907 const sp<IAfTrack>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003908{
Andy Hung972bec12023-08-31 16:13:39 -07003909 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08003910 return attachAuxEffect_l(track, EffectId);
3911}
3912
Andy Hungee58e4a2023-07-07 13:47:37 -07003913status_t PlaybackThread::attachAuxEffect_l(
Andy Hung8d31fd22023-06-26 19:20:57 -07003914 const sp<IAfTrack>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003915{
3916 status_t status = NO_ERROR;
3917
3918 if (EffectId == 0) {
3919 track->setAuxBuffer(0, NULL);
3920 } else {
3921 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
Andy Hung116bc262023-06-20 18:56:17 -07003922 sp<IAfEffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Eric Laurent81784c32012-11-19 14:55:58 -08003923 if (effect != 0) {
3924 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
3925 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
3926 } else {
3927 status = INVALID_OPERATION;
3928 }
3929 } else {
3930 status = BAD_VALUE;
3931 }
3932 }
3933 return status;
3934}
3935
Andy Hungee58e4a2023-07-07 13:47:37 -07003936void PlaybackThread::detachAuxEffect_l(int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003937{
3938 for (size_t i = 0; i < mTracks.size(); ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003939 sp<IAfTrack> track = mTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08003940 if (track->auxEffectId() == effectId) {
3941 attachAuxEffect_l(track, 0);
3942 }
3943 }
3944}
3945
Andy Hungee58e4a2023-07-07 13:47:37 -07003946bool PlaybackThread::threadLoop()
Andy Hung920f6572022-10-06 12:09:49 -07003947NO_THREAD_SAFETY_ANALYSIS // manual locking of AudioFlinger
Eric Laurent81784c32012-11-19 14:55:58 -08003948{
Andy Hung78d8d952023-05-30 18:10:23 -07003949 aflog::setThreadWriter(mNBLogWriter.get());
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003950
Andy Hung077d62e2023-10-03 10:49:34 -07003951 if (mType == SPATIALIZER) {
3952 const pid_t tid = getTid();
3953 if (tid == -1) { // odd: we are here, we must be a running thread.
3954 ALOGW("%s: Cannot update Spatializer mixer thread priority, no tid", __func__);
3955 } else {
Andy Hung639dbc92023-11-28 18:21:55 +00003956 const int priorityBoost = requestSpatializerPriority(getpid(), tid);
3957 if (priorityBoost > 0) {
3958 stream()->setHalThreadPriority(priorityBoost);
3959 }
Andy Hung077d62e2023-10-03 10:49:34 -07003960 }
Pattara Teerapong9a332c52024-01-26 08:18:05 +00003961 } else if (property_get_bool("ro.boot.container", false /* default_value */)) {
3962 // In ARC experiments (b/73091832), the latency under using CFS scheduler with any priority
3963 // is not enough for PlaybackThread to process audio data in time. We request the lowest
3964 // real-time priority, SCHED_FIFO=1, for PlaybackThread in ARC. ro.boot.container is true
3965 // only on ARC.
3966 const pid_t tid = getTid();
3967 if (tid == -1) {
3968 ALOGW("%s: Cannot update PlaybackThread priority for ARC, no tid", __func__);
3969 } else {
3970 const status_t status = requestPriority(getpid(),
3971 tid,
3972 kPriorityPlaybackThreadArc,
3973 false /* isForApp */,
3974 true /* asynchronous */);
3975 if (status != OK) {
3976 ALOGW("%s: Cannot update PlaybackThread priority for ARC, status %d", __func__,
3977 status);
3978 } else {
3979 stream()->setHalThreadPriority(kPriorityPlaybackThreadArc);
3980 }
3981 }
Andy Hung077d62e2023-10-03 10:49:34 -07003982 }
3983
Andy Hung8d31fd22023-06-26 19:20:57 -07003984 Vector<sp<IAfTrack>> tracksToRemove;
Eric Laurent81784c32012-11-19 14:55:58 -08003985
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003986 mStandbyTimeNs = systemTime();
Andy Hung446f4df2019-02-21 12:26:41 -08003987 int64_t lastLoopCountWritten = -2; // never matches "previous" loop, when loopCount = 0.
Eric Laurent81784c32012-11-19 14:55:58 -08003988
3989 // MIXER
3990 nsecs_t lastWarning = 0;
3991
3992 // DUPLICATING
3993 // FIXME could this be made local to while loop?
3994 writeFrames = 0;
3995
3996 cacheParameters_l();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003997 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003998
Andy Hungd3639922022-04-28 18:00:49 -07003999 if (mType == MIXER || mType == SPATIALIZER) {
Eric Laurent81784c32012-11-19 14:55:58 -08004000 sleepTimeShift = 0;
4001 }
4002
4003 CpuStats cpuStats;
4004 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
4005
4006 acquireWakeLock();
4007
Glenn Kasteneef598c2017-04-03 14:41:13 -07004008 // mNBLogWriter logging APIs can only be called by a single thread, typically the
4009 // thread associated with this PlaybackThread.
4010 // If you want to share the mNBLogWriter with other threads (for example, binder threads)
4011 // then all such threads must agree to hold a common mutex before logging.
Glenn Kasten9e58b552013-01-18 15:09:48 -08004012 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
4013 // and then that string will be logged at the next convenient opportunity.
Glenn Kasteneef598c2017-04-03 14:41:13 -07004014 // See reference to logString below.
Glenn Kasten9e58b552013-01-18 15:09:48 -08004015 const char *logString = NULL;
4016
rago1bb90822017-05-02 18:31:48 -07004017 // Estimated time for next buffer to be written to hal. This is used only on
4018 // suspended mode (for now) to help schedule the wait time until next iteration.
4019 nsecs_t timeLoopNextNs = 0;
4020
Eric Laurent664539d2013-09-23 18:24:31 -07004021 checkSilentMode_l();
Glenn Kasteneef598c2017-04-03 14:41:13 -07004022
Andy Hung2dbffc22018-08-08 18:50:41 -07004023 audio_patch_handle_t lastDownstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Andy Hungf3234512018-07-03 14:51:47 -07004024
Eric Laurentb3f315a2021-07-13 15:09:05 +02004025 sendCheckOutputStageEffectsEvent();
4026
Andy Hung446f4df2019-02-21 12:26:41 -08004027 // loopCount is used for statistics and diagnostics.
4028 for (int64_t loopCount = 0; !exitPending(); ++loopCount)
Eric Laurent81784c32012-11-19 14:55:58 -08004029 {
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08004030 // Log merge requests are performed during AudioFlinger binder transactions, but
4031 // that does not cover audio playback. It's requested here for that reason.
Andy Hung583043b2023-07-17 17:05:00 -07004032 mAfThreadCallback->requestLogMerge();
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08004033
Eric Laurent81784c32012-11-19 14:55:58 -08004034 cpuStats.sample(myName);
4035
Andy Hung116bc262023-06-20 18:56:17 -07004036 Vector<sp<IAfEffectChain>> effectChains;
Andy Hung6e6a2e62019-04-30 16:38:41 -07004037 audio_session_t activeHapticSessionId = AUDIO_SESSION_NONE;
Eric Laurentb62d0362021-10-26 17:40:18 +02004038 bool isHapticSessionSpatialized = false;
Andy Hung8d31fd22023-06-26 19:20:57 -07004039 std::vector<sp<IAfTrack>> activeTracks;
Eric Laurent81784c32012-11-19 14:55:58 -08004040
Andy Hung2dbffc22018-08-08 18:50:41 -07004041 // If the device is AUDIO_DEVICE_OUT_BUS, check for downstream latency.
4042 //
Andy Hungc5007f82023-08-29 14:26:09 -07004043 // Note: we access outDeviceTypes() outside of mutex().
Andy Hungab65b182023-09-06 19:41:47 -07004044 if (isMsdDevice() && outDeviceTypes_l().count(AUDIO_DEVICE_OUT_BUS) != 0) {
Andy Hung2dbffc22018-08-08 18:50:41 -07004045 // Here, we try for the AF lock, but do not block on it as the latency
4046 // is more informational.
Andy Hung954b9712023-08-28 18:36:53 -07004047 if (mAfThreadCallback->mutex().try_lock()) {
Andy Hungb6692eb2023-07-13 16:52:46 -07004048 std::vector<SoftwarePatch> swPatches;
Andy Hung920f6572022-10-06 12:09:49 -07004049 double latencyMs = 0.; // not required; initialized for clang-tidy
Andy Hung2dbffc22018-08-08 18:50:41 -07004050 status_t status = INVALID_OPERATION;
4051 audio_patch_handle_t downstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Andy Hung583043b2023-07-17 17:05:00 -07004052 if (mAfThreadCallback->getPatchPanel()->getDownstreamSoftwarePatches(
Andy Hungb6692eb2023-07-13 16:52:46 -07004053 id(), &swPatches) == OK
Andy Hung2dbffc22018-08-08 18:50:41 -07004054 && swPatches.size() > 0) {
4055 status = swPatches[0].getLatencyMs_l(&latencyMs);
4056 downstreamPatchHandle = swPatches[0].getPatchHandle();
4057 }
4058 if (downstreamPatchHandle != lastDownstreamPatchHandle) {
Dean Wheatley30d28422018-11-06 10:27:40 +11004059 mDownstreamLatencyStatMs.reset();
Andy Hung2dbffc22018-08-08 18:50:41 -07004060 lastDownstreamPatchHandle = downstreamPatchHandle;
4061 }
4062 if (status == OK) {
4063 // verify downstream latency (we assume a max reasonable
Mikhail Naganov6aa0a312018-11-09 11:00:01 -08004064 // latency of 5 seconds).
4065 const double minLatency = 0., maxLatency = 5000.;
4066 if (latencyMs >= minLatency && latencyMs <= maxLatency) {
Dean Wheatley56a583e2020-05-08 15:12:17 +10004067 ALOGVV("new downstream latency %lf ms", latencyMs);
Andy Hung2dbffc22018-08-08 18:50:41 -07004068 } else {
4069 ALOGD("out of range downstream latency %lf ms", latencyMs);
Andy Hung920f6572022-10-06 12:09:49 -07004070 latencyMs = std::clamp(latencyMs, minLatency, maxLatency);
Andy Hung2dbffc22018-08-08 18:50:41 -07004071 }
Dean Wheatley30d28422018-11-06 10:27:40 +11004072 mDownstreamLatencyStatMs.add(latencyMs);
Andy Hung2dbffc22018-08-08 18:50:41 -07004073 }
Andy Hung583043b2023-07-17 17:05:00 -07004074 mAfThreadCallback->mutex().unlock();
Andy Hung2dbffc22018-08-08 18:50:41 -07004075 }
4076 } else {
4077 if (lastDownstreamPatchHandle != AUDIO_PATCH_HANDLE_NONE) {
4078 // our device is no longer AUDIO_DEVICE_OUT_BUS, reset patch handle and stats.
Dean Wheatley30d28422018-11-06 10:27:40 +11004079 mDownstreamLatencyStatMs.reset();
Andy Hung2dbffc22018-08-08 18:50:41 -07004080 lastDownstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
4081 }
4082 }
4083
Eric Laurentb3f315a2021-07-13 15:09:05 +02004084 if (mCheckOutputStageEffects.exchange(false)) {
4085 checkOutputStageEffects();
4086 }
4087
Vlad Popa7e81cea2023-01-19 16:34:16 +01004088 MetadataUpdate metadataUpdate;
Andy Hungc5007f82023-08-29 14:26:09 -07004089 { // scope for mutex()
Eric Laurent81784c32012-11-19 14:55:58 -08004090
Andy Hungc5007f82023-08-29 14:26:09 -07004091 audio_utils::unique_lock _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08004092
Eric Laurent021cf962014-05-13 10:18:14 -07004093 processConfigEvents_l();
Eric Laurentb3f315a2021-07-13 15:09:05 +02004094 if (mCheckOutputStageEffects.load()) {
4095 continue;
4096 }
Eric Laurent10351942014-05-08 18:49:52 -07004097
Andy Hungc5007f82023-08-29 14:26:09 -07004098 // See comment at declaration of logString for why this is done under mutex()
Glenn Kasten9e58b552013-01-18 15:09:48 -08004099 if (logString != NULL) {
4100 mNBLogWriter->logTimestamp();
4101 mNBLogWriter->log(logString);
4102 logString = NULL;
4103 }
4104
Dean Wheatley12473e92021-03-18 23:00:55 +11004105 collectTimestamps_l();
Andy Hungc8fddf32018-08-08 18:32:37 -07004106
Eric Laurent81784c32012-11-19 14:55:58 -08004107 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004108 if (mSignalPending) {
4109 // A signal was raised while we were unlocked
4110 mSignalPending = false;
4111 } else if (waitingAsyncCallback_l()) {
4112 if (exitPending()) {
4113 break;
4114 }
Marco Nelissen078538c2015-05-12 09:17:57 -07004115 bool released = false;
Eric Laurent64667972016-03-30 18:19:46 -07004116 if (!keepWakeLock()) {
Marco Nelissen078538c2015-05-12 09:17:57 -07004117 releaseWakeLock_l();
4118 released = true;
4119 }
Andy Hung10cbff12017-02-21 17:30:14 -08004120
4121 const int64_t waitNs = computeWaitTimeNs_l();
4122 ALOGV("wait async completion (wait time: %lld)", (long long)waitNs);
Andy Hungc5007f82023-08-29 14:26:09 -07004123 std::cv_status cvstatus =
4124 mWaitWorkCV.wait_for(_l, std::chrono::nanoseconds(waitNs));
4125 if (cvstatus == std::cv_status::timeout) {
Andy Hung10cbff12017-02-21 17:30:14 -08004126 mSignalPending = true; // if timeout recheck everything
4127 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004128 ALOGV("async completion/wake");
Marco Nelissen078538c2015-05-12 09:17:57 -07004129 if (released) {
4130 acquireWakeLock_l();
4131 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004132 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
4133 mSleepTimeUs = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07004134
4135 continue;
4136 }
Eric Tan39ec8d62018-07-24 09:49:29 -07004137 if ((mActiveTracks.isEmpty() && systemTime() > mStandbyTimeNs) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08004138 isSuspended()) {
4139 // put audio hardware into standby after short delay
4140 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004141
4142 threadLoop_standby();
4143
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07004144 // This is where we go into standby
4145 if (!mStandby) {
4146 LOG_AUDIO_STATE();
Andy Hungcf10d742020-04-28 15:38:24 -07004147 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07004148 mThreadSnapshot.onEnd();
Eric Laurent19952e12023-04-20 10:08:29 +02004149 setStandby_l();
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07004150 }
Andy Hungd0979812019-02-21 15:51:44 -08004151 sendStatistics(false /* force */);
Eric Laurent81784c32012-11-19 14:55:58 -08004152 }
4153
Eric Tan39ec8d62018-07-24 09:49:29 -07004154 if (mActiveTracks.isEmpty() && mConfigEvents.isEmpty()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004155 // we're about to wait, flush the binder command buffer
4156 IPCThreadState::self()->flushCommands();
4157
4158 clearOutputTracks();
4159
4160 if (exitPending()) {
4161 break;
4162 }
4163
4164 releaseWakeLock_l();
4165 // wait until we have something to do...
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004166 ALOGV("%s going to sleep", myName.c_str());
Andy Hungc5007f82023-08-29 14:26:09 -07004167 mWaitWorkCV.wait(_l);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004168 ALOGV("%s waking up", myName.c_str());
Eric Laurent81784c32012-11-19 14:55:58 -08004169 acquireWakeLock_l();
4170
4171 mMixerStatus = MIXER_IDLE;
4172 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
4173 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004174 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08004175 checkSilentMode_l();
4176
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004177 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
4178 mSleepTimeUs = mIdleSleepTimeUs;
Andy Hungd3639922022-04-28 18:00:49 -07004179 if (mType == MIXER || mType == SPATIALIZER) {
Eric Laurent81784c32012-11-19 14:55:58 -08004180 sleepTimeShift = 0;
4181 }
4182
4183 continue;
4184 }
4185 }
Eric Laurent81784c32012-11-19 14:55:58 -08004186 // mMixerStatusIgnoringFastTracks is also updated internally
4187 mMixerStatus = prepareTracks_l(&tracksToRemove);
4188
Andy Hungab65b182023-09-06 19:41:47 -07004189 mActiveTracks.updatePowerState_l(this);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08004190
Vlad Popa7e81cea2023-01-19 16:34:16 +01004191 metadataUpdate = updateMetadata_l();
Kevin Rocard069c2712018-03-29 19:09:14 -07004192
Andy Hungf302e812024-01-26 11:55:15 -08004193 // Acquire a local copy of active tracks with lock (release w/o lock).
4194 //
4195 // Control methods on the track acquire the ThreadBase lock (e.g. start()
4196 // stop(), pause(), etc.), but the threadLoop is entitled to call audio
4197 // data / buffer methods on tracks from activeTracks without the ThreadBase lock.
4198 activeTracks.insert(activeTracks.end(), mActiveTracks.begin(), mActiveTracks.end());
4199
4200 setHalLatencyMode_l();
4201
4202 // updateTeePatches_l will acquire the ThreadBase_Mutex of other threads,
4203 // so this is done before we lock our effect chains.
4204 for (const auto& track : mActiveTracks) {
4205 track->updateTeePatches_l();
4206 }
4207
4208 // signal actual start of output stream when the render position reported by
4209 // the kernel starts moving.
4210 if (!mHalStarted && ((isSuspended() && (mBytesWritten != 0)) || (!mStandby
4211 && (mKernelPositionOnStandby
4212 != mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL])))) {
4213 mHalStarted = true;
4214 mWaitHalStartCV.notify_all();
4215 }
4216
Eric Laurent81784c32012-11-19 14:55:58 -08004217 // prevent any changes in effect chain list and in each effect chain
4218 // during mixing and effect process as the audio buffers could be deleted
4219 // or modified if an effect is created or deleted
4220 lockEffectChains_l(effectChains);
Andy Hung6e6a2e62019-04-30 16:38:41 -07004221
4222 // Determine which session to pick up haptic data.
4223 // This must be done under the same lock as prepareTracks_l().
jiabineb3bda02020-06-30 14:07:03 -07004224 // The haptic data from the effect is at a higher priority than the one from track.
Andy Hung6e6a2e62019-04-30 16:38:41 -07004225 // TODO: Write haptic data directly to sink buffer when mixing.
Eric Laurentb62d0362021-10-26 17:40:18 +02004226 if (mHapticChannelCount > 0) {
Andy Hung6e6a2e62019-04-30 16:38:41 -07004227 for (const auto& track : mActiveTracks) {
Andy Hung116bc262023-06-20 18:56:17 -07004228 sp<IAfEffectChain> effectChain = getEffectChain_l(track->sessionId());
Eric Laurentb62d0362021-10-26 17:40:18 +02004229 if (effectChain != nullptr
4230 && effectChain->containsHapticGeneratingEffect_l()) {
jiabineb3bda02020-06-30 14:07:03 -07004231 activeHapticSessionId = track->sessionId();
Eric Laurentb62d0362021-10-26 17:40:18 +02004232 isHapticSessionSpatialized =
Eric Laurentb0a7bc92022-04-05 15:06:08 +02004233 mType == SPATIALIZER && track->isSpatialized();
jiabineb3bda02020-06-30 14:07:03 -07004234 break;
4235 }
Eric Laurentb62d0362021-10-26 17:40:18 +02004236 if (activeHapticSessionId == AUDIO_SESSION_NONE
4237 && track->getHapticPlaybackEnabled()) {
Andy Hung6e6a2e62019-04-30 16:38:41 -07004238 activeHapticSessionId = track->sessionId();
Eric Laurentb62d0362021-10-26 17:40:18 +02004239 isHapticSessionSpatialized =
Eric Laurentb0a7bc92022-04-05 15:06:08 +02004240 mType == SPATIALIZER && track->isSpatialized();
Andy Hung6e6a2e62019-04-30 16:38:41 -07004241 }
4242 }
4243 }
Andy Hungc5007f82023-08-29 14:26:09 -07004244 } // mutex() scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08004245
Eric Laurentbfb1b832013-01-07 09:53:42 -08004246 if (mBytesRemaining == 0) {
4247 mCurrentWriteLength = 0;
4248 if (mMixerStatus == MIXER_TRACKS_READY) {
4249 // threadLoop_mix() sets mCurrentWriteLength
4250 threadLoop_mix();
4251 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
4252 && (mMixerStatus != MIXER_DRAIN_ALL)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004253 // threadLoop_sleepTime sets mSleepTimeUs to 0 if data
Eric Laurentbfb1b832013-01-07 09:53:42 -08004254 // must be written to HAL
4255 threadLoop_sleepTime();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004256 if (mSleepTimeUs == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08004257 mCurrentWriteLength = mSinkBufferSize;
Andy Hungc1646382019-04-30 16:12:10 -07004258
4259 // Tally underrun frames as we are inserting 0s here.
4260 for (const auto& track : activeTracks) {
Andy Hung8d31fd22023-06-26 19:20:57 -07004261 if (track->fillingStatus() == IAfTrack::FS_ACTIVE
Andy Hunge2e830f2019-12-03 12:54:46 -08004262 && !track->isStopped()
4263 && !track->isPaused()
4264 && !track->isTerminated()) {
4265 ALOGV("%s: track(%d) %s underrun due to thread sleep of %zu frames",
4266 __func__, track->id(), track->getTrackStateAsString(),
4267 mNormalFrameCount);
Andy Hung8d31fd22023-06-26 19:20:57 -07004268 track->audioTrackServerProxy()->tallyUnderrunFrames(
4269 mNormalFrameCount);
Andy Hungc1646382019-04-30 16:12:10 -07004270 }
4271 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004272 }
4273 }
Andy Hung98ef9782014-03-04 14:46:50 -08004274 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004275 // mMixerBuffer with data if mMixerBufferValid is true and mSleepTimeUs == 0.
Andy Hung98ef9782014-03-04 14:46:50 -08004276 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
jiabinc658e452022-10-21 20:52:21 +00004277 // or mSinkBuffer (if there are no effects and there is no data already copied to
4278 // mSinkBuffer).
Andy Hung98ef9782014-03-04 14:46:50 -08004279 //
4280 // This is done pre-effects computation; if effects change to
4281 // support higher precision, this needs to move.
4282 //
4283 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004284 // TODO use mSleepTimeUs == 0 as an additional condition.
Eric Laurent39095982021-08-24 18:29:27 +02004285 uint32_t mixerChannelCount = mEffectBufferValid ?
4286 audio_channel_count_from_out_mask(mMixerChannelMask) : mChannelCount;
jiabinc658e452022-10-21 20:52:21 +00004287 if (mMixerBufferValid && (mEffectBufferValid || !mHasDataCopiedToSinkBuffer)) {
Andy Hung98ef9782014-03-04 14:46:50 -08004288 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
4289 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
4290
David Li88ee0902022-06-22 10:01:21 +08004291 // Apply mono blending and balancing if the effect buffer is not valid. Otherwise,
4292 // do these processes after effects are applied.
4293 if (!mEffectBufferValid) {
4294 // mono blend occurs for mixer threads only (not direct or offloaded)
4295 // and is handled here if we're going directly to the sink.
4296 if (requireMonoBlend()) {
4297 mono_blend(mMixerBuffer, mMixerBufferFormat, mChannelCount,
4298 mNormalFrameCount, true /*limit*/);
4299 }
Andy Hung2ddee192015-12-18 17:34:44 -08004300
David Li88ee0902022-06-22 10:01:21 +08004301 if (!hasFastMixer()) {
4302 // Balance must take effect after mono conversion.
4303 // We do it here if there is no FastMixer.
4304 // mBalance detects zero balance within the class for speed
4305 // (not needed here).
4306 mBalance.setBalance(mMasterBalance.load());
4307 mBalance.process((float *)mMixerBuffer, mNormalFrameCount);
4308 }
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01004309 }
4310
Andy Hung98ef9782014-03-04 14:46:50 -08004311 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
Eric Laurent39095982021-08-24 18:29:27 +02004312 mNormalFrameCount * (mixerChannelCount + mHapticChannelCount));
jiabin245cdd92018-12-07 17:55:15 -08004313
4314 // If we're going directly to the sink and there are haptic channels,
4315 // we should adjust channels as the sample data is partially interleaved
4316 // in this case.
4317 if (!mEffectBufferValid && mHapticChannelCount > 0) {
4318 adjust_channels_non_destructive(buffer, mChannelCount, buffer,
4319 mChannelCount + mHapticChannelCount,
4320 audio_bytes_per_sample(format),
4321 audio_bytes_per_frame(mChannelCount, format) * mNormalFrameCount);
4322 }
Andy Hung98ef9782014-03-04 14:46:50 -08004323 }
4324
Eric Laurentbfb1b832013-01-07 09:53:42 -08004325 mBytesRemaining = mCurrentWriteLength;
4326 if (isSuspended()) {
Andy Hung238fa3d2016-07-28 10:53:22 -07004327 // Simulate write to HAL when suspended (e.g. BT SCO phone call).
4328 mSleepTimeUs = suspendSleepTimeUs(); // assumes full buffer.
4329 const size_t framesRemaining = mBytesRemaining / mFrameSize;
4330 mBytesWritten += mBytesRemaining;
4331 mFramesWritten += framesRemaining;
4332 mSuspendedFrames += framesRemaining; // to adjust kernel HAL position
Eric Laurentbfb1b832013-01-07 09:53:42 -08004333 mBytesRemaining = 0;
4334 }
Eric Laurent81784c32012-11-19 14:55:58 -08004335
Eric Laurentbfb1b832013-01-07 09:53:42 -08004336 // only process effects if we're going to write
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004337 if (mSleepTimeUs == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004338 for (size_t i = 0; i < effectChains.size(); i ++) {
4339 effectChains[i]->process_l();
jiabin47affe52019-04-04 18:02:07 -07004340 // TODO: Write haptic data directly to sink buffer when mixing.
Andy Hung6e6a2e62019-04-30 16:38:41 -07004341 if (activeHapticSessionId != AUDIO_SESSION_NONE
4342 && activeHapticSessionId == effectChains[i]->sessionId()) {
jiabin47affe52019-04-04 18:02:07 -07004343 // Haptic data is active in this case, copy it directly from
4344 // in buffer to out buffer.
Eric Laurentb62d0362021-10-26 17:40:18 +02004345 uint32_t hapticSessionChannelCount = mEffectBufferValid ?
4346 audio_channel_count_from_out_mask(mMixerChannelMask) :
4347 mChannelCount;
4348 if (mType == SPATIALIZER && !isHapticSessionSpatialized) {
4349 hapticSessionChannelCount = mChannelCount;
4350 }
4351
jiabin47affe52019-04-04 18:02:07 -07004352 const size_t audioBufferSize = mNormalFrameCount
Eric Laurentb62d0362021-10-26 17:40:18 +02004353 * audio_bytes_per_frame(hapticSessionChannelCount,
Andy Hung319587b2023-05-23 14:01:03 -07004354 AUDIO_FORMAT_PCM_FLOAT);
jiabin47affe52019-04-04 18:02:07 -07004355 memcpy_by_audio_format(
4356 (uint8_t*)effectChains[i]->outBuffer() + audioBufferSize,
Andy Hung319587b2023-05-23 14:01:03 -07004357 AUDIO_FORMAT_PCM_FLOAT,
jiabin47affe52019-04-04 18:02:07 -07004358 (const uint8_t*)effectChains[i]->inBuffer() + audioBufferSize,
Andy Hung319587b2023-05-23 14:01:03 -07004359 AUDIO_FORMAT_PCM_FLOAT, mNormalFrameCount * mHapticChannelCount);
jiabin47affe52019-04-04 18:02:07 -07004360 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004361 }
Eric Laurent81784c32012-11-19 14:55:58 -08004362 }
4363 }
Eric Laurent59fe0102013-09-27 18:48:26 -07004364 // Process effect chains for offloaded thread even if no audio
4365 // was read from audio track: process only updates effect state
4366 // and thus does have to be synchronized with audio writes but may have
4367 // to be called while waiting for async write callback
4368 if (mType == OFFLOAD) {
4369 for (size_t i = 0; i < effectChains.size(); i ++) {
4370 effectChains[i]->process_l();
4371 }
4372 }
Eric Laurent81784c32012-11-19 14:55:58 -08004373
Andy Hung98ef9782014-03-04 14:46:50 -08004374 // Only if the Effects buffer is enabled and there is data in the
4375 // Effects buffer (buffer valid), we need to
4376 // copy into the sink buffer.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004377 // TODO use mSleepTimeUs == 0 as an additional condition.
jiabinc658e452022-10-21 20:52:21 +00004378 if (mEffectBufferValid && !mHasDataCopiedToSinkBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08004379 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
Eric Laurentb62d0362021-10-26 17:40:18 +02004380 void *effectBuffer = (mType == SPATIALIZER) ? mPostSpatializerBuffer : mEffectBuffer;
Andy Hung2ddee192015-12-18 17:34:44 -08004381 if (requireMonoBlend()) {
Eric Laurentb62d0362021-10-26 17:40:18 +02004382 mono_blend(effectBuffer, mEffectBufferFormat, mChannelCount, mNormalFrameCount,
Glenn Kasten03c48d52016-01-27 17:25:17 -08004383 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08004384 }
4385
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01004386 if (!hasFastMixer()) {
4387 // Balance must take effect after mono conversion.
4388 // We do it here if there is no FastMixer.
4389 // mBalance detects zero balance within the class for speed (not needed here).
4390 mBalance.setBalance(mMasterBalance.load());
Eric Laurentb62d0362021-10-26 17:40:18 +02004391 mBalance.process((float *)effectBuffer, mNormalFrameCount);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01004392 }
4393
Eric Laurentb62d0362021-10-26 17:40:18 +02004394 // for SPATIALIZER thread, Move haptics channels from mEffectBuffer to
4395 // mPostSpatializerBuffer if the haptics track is spatialized.
4396 // Otherwise, the haptics channels are already in mPostSpatializerBuffer.
4397 // For other thread types, the haptics channels are already in mEffectBuffer.
4398 if (mType == SPATIALIZER && isHapticSessionSpatialized) {
4399 const size_t srcBufferSize = mNormalFrameCount *
4400 audio_bytes_per_frame(audio_channel_count_from_out_mask(mMixerChannelMask),
4401 mEffectBufferFormat);
4402 const size_t dstBufferSize = mNormalFrameCount
4403 * audio_bytes_per_frame(mChannelCount, mEffectBufferFormat);
4404
4405 memcpy_by_audio_format((uint8_t*)mPostSpatializerBuffer + dstBufferSize,
4406 mEffectBufferFormat,
4407 (uint8_t*)mEffectBuffer + srcBufferSize,
4408 mEffectBufferFormat,
4409 mNormalFrameCount * mHapticChannelCount);
Eric Laurent39095982021-08-24 18:29:27 +02004410 }
Atneya Nairba9a1072022-09-19 17:51:37 -07004411 const size_t framesToCopy = mNormalFrameCount * (mChannelCount + mHapticChannelCount);
4412 if (mFormat == AUDIO_FORMAT_PCM_FLOAT &&
4413 mEffectBufferFormat == AUDIO_FORMAT_PCM_FLOAT) {
4414 // Clamp PCM float values more than this distance from 0 to insulate
4415 // a HAL which doesn't handle NaN correctly.
4416 static constexpr float HAL_FLOAT_SAMPLE_LIMIT = 2.0f;
4417 memcpy_to_float_from_float_with_clamping(static_cast<float*>(mSinkBuffer),
4418 static_cast<const float*>(effectBuffer),
4419 framesToCopy, HAL_FLOAT_SAMPLE_LIMIT /* absMax */);
4420 } else {
4421 memcpy_by_audio_format(mSinkBuffer, mFormat,
4422 effectBuffer, mEffectBufferFormat, framesToCopy);
4423 }
jiabin245cdd92018-12-07 17:55:15 -08004424 // The sample data is partially interleaved when haptic channels exist,
4425 // we need to adjust channels here.
4426 if (mHapticChannelCount > 0) {
4427 adjust_channels_non_destructive(mSinkBuffer, mChannelCount, mSinkBuffer,
4428 mChannelCount + mHapticChannelCount,
4429 audio_bytes_per_sample(mFormat),
4430 audio_bytes_per_frame(mChannelCount, mFormat) * mNormalFrameCount);
4431 }
Andy Hung98ef9782014-03-04 14:46:50 -08004432 }
4433
Eric Laurent81784c32012-11-19 14:55:58 -08004434 // enable changes in effect chain
4435 unlockEffectChains(effectChains);
4436
Vlad Popafce10862023-02-03 10:37:07 +01004437 if (!metadataUpdate.playbackMetadataUpdate.empty()) {
Andy Hung583043b2023-07-17 17:05:00 -07004438 mAfThreadCallback->getMelReporter()->updateMetadataForCsd(id(),
Vlad Popafce10862023-02-03 10:37:07 +01004439 metadataUpdate.playbackMetadataUpdate);
4440 }
4441
Eric Laurentbfb1b832013-01-07 09:53:42 -08004442 if (!waitingAsyncCallback()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004443 // mSleepTimeUs == 0 means we must write to audio hardware
4444 if (mSleepTimeUs == 0) {
Andy Hung08fb1742015-05-31 23:22:10 -07004445 ssize_t ret = 0;
Andy Hung446f4df2019-02-21 12:26:41 -08004446 // writePeriodNs is updated >= 0 when ret > 0.
4447 int64_t writePeriodNs = -1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004448 if (mBytesRemaining) {
Andy Hung69488c42016-05-16 18:43:33 -07004449 // FIXME rewrite to reduce number of system calls
Andy Hung446f4df2019-02-21 12:26:41 -08004450 const int64_t lastIoBeginNs = systemTime();
Andy Hung08fb1742015-05-31 23:22:10 -07004451 ret = threadLoop_write();
Andy Hung446f4df2019-02-21 12:26:41 -08004452 const int64_t lastIoEndNs = systemTime();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004453 if (ret < 0) {
4454 mBytesRemaining = 0;
Andy Hung446f4df2019-02-21 12:26:41 -08004455 } else if (ret > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004456 mBytesWritten += ret;
4457 mBytesRemaining -= ret;
Andy Hung446f4df2019-02-21 12:26:41 -08004458 const int64_t frames = ret / mFrameSize;
4459 mFramesWritten += frames;
4460
4461 writePeriodNs = lastIoEndNs - mLastIoEndNs;
4462 // process information relating to write time.
4463 if (audio_has_proportional_frames(mFormat)) {
4464 // we are in a continuous mixing cycle
4465 if (mMixerStatus == MIXER_TRACKS_READY &&
4466 loopCount == lastLoopCountWritten + 1) {
4467
4468 const double jitterMs =
4469 TimestampVerifier<int64_t, int64_t>::computeJitterMs(
4470 {frames, writePeriodNs},
4471 {0, 0} /* lastTimestamp */, mSampleRate);
4472 const double processMs =
4473 (lastIoBeginNs - mLastIoEndNs) * 1e-6;
4474
Andy Hung972bec12023-08-31 16:13:39 -07004475 audio_utils::lock_guard _l(mutex());
Andy Hung446f4df2019-02-21 12:26:41 -08004476 mIoJitterMs.add(jitterMs);
4477 mProcessTimeMs.add(processMs);
Robert Wu06db0a32021-08-10 19:05:34 +00004478
4479 if (mPipeSink.get() != nullptr) {
4480 // Using the Monopipe availableToWrite, we estimate the current
4481 // buffer size.
4482 MonoPipe* monoPipe = static_cast<MonoPipe*>(mPipeSink.get());
4483 const ssize_t
4484 availableToWrite = mPipeSink->availableToWrite();
4485 const size_t pipeFrames = monoPipe->maxFrames();
4486 const size_t
4487 remainingFrames = pipeFrames - max(availableToWrite, 0);
4488 mMonopipePipeDepthStats.add(remainingFrames);
4489 }
Andy Hung446f4df2019-02-21 12:26:41 -08004490 }
4491
4492 // write blocked detection
4493 const int64_t deltaWriteNs = lastIoEndNs - lastIoBeginNs;
Andy Hungd3639922022-04-28 18:00:49 -07004494 if ((mType == MIXER || mType == SPATIALIZER)
4495 && deltaWriteNs > maxPeriod) {
Andy Hung446f4df2019-02-21 12:26:41 -08004496 mNumDelayedWrites++;
4497 if ((lastIoEndNs - lastWarning) > kWarningThrottleNs) {
4498 ATRACE_NAME("underrun");
4499 ALOGW("write blocked for %lld msecs, "
4500 "%d delayed writes, thread %d",
4501 (long long)deltaWriteNs / NANOS_PER_MILLISECOND,
4502 mNumDelayedWrites, mId);
4503 lastWarning = lastIoEndNs;
4504 }
4505 }
4506 }
4507 // update timing info.
4508 mLastIoBeginNs = lastIoBeginNs;
4509 mLastIoEndNs = lastIoEndNs;
4510 lastLoopCountWritten = loopCount;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004511 }
4512 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
4513 (mMixerStatus == MIXER_DRAIN_ALL)) {
4514 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08004515 }
Andy Hungd3639922022-04-28 18:00:49 -07004516 if ((mType == MIXER || mType == SPATIALIZER) && !mStandby) {
Andy Hung08fb1742015-05-31 23:22:10 -07004517
4518 if (mThreadThrottle
4519 && mMixerStatus == MIXER_TRACKS_READY // we are mixing (active tracks)
Andy Hung446f4df2019-02-21 12:26:41 -08004520 && writePeriodNs > 0) { // we have write period info
Andy Hung08fb1742015-05-31 23:22:10 -07004521 // Limit MixerThread data processing to no more than twice the
4522 // expected processing rate.
4523 //
4524 // This helps prevent underruns with NuPlayer and other applications
4525 // which may set up buffers that are close to the minimum size, or use
4526 // deep buffers, and rely on a double-buffering sleep strategy to fill.
4527 //
4528 // The throttle smooths out sudden large data drains from the device,
4529 // e.g. when it comes out of standby, which often causes problems with
4530 // (1) mixer threads without a fast mixer (which has its own warm-up)
4531 // (2) minimum buffer sized tracks (even if the track is full,
4532 // the app won't fill fast enough to handle the sudden draw).
Haynes Mathew Georgef92b2172016-05-09 11:34:15 -07004533 //
4534 // Total time spent in last processing cycle equals time spent in
4535 // 1. threadLoop_write, as well as time spent in
4536 // 2. threadLoop_mix (significant for heavy mixing, especially
4537 // on low tier processors)
Andy Hung08fb1742015-05-31 23:22:10 -07004538
Andy Hung446f4df2019-02-21 12:26:41 -08004539 // it's OK if deltaMs is an overestimate.
4540
4541 const int32_t deltaMs = writePeriodNs / NANOS_PER_MILLISECOND;
Ivan Lozanoe02bc542017-10-26 09:51:54 -07004542
Ivan Lozanoea04d392017-11-07 14:37:07 -08004543 const int32_t throttleMs = (int32_t)mHalfBufferMs - deltaMs;
Andy Hung08fb1742015-05-31 23:22:10 -07004544 if ((signed)mHalfBufferMs >= throttleMs && throttleMs > 0) {
Andy Hungcf10d742020-04-28 15:38:24 -07004545 mThreadMetrics.logThrottleMs((double)throttleMs);
Andy Hungb68f5eb2019-12-03 16:49:17 -08004546
Andy Hung08fb1742015-05-31 23:22:10 -07004547 usleep(throttleMs * 1000);
Andy Hung40eb1a12015-06-18 13:42:02 -07004548 // notify of throttle start on verbose log
4549 ALOGV_IF(mThreadThrottleEndMs == mThreadThrottleTimeMs,
4550 "mixer(%p) throttle begin:"
4551 " ret(%zd) deltaMs(%d) requires sleep %d ms",
Andy Hung08fb1742015-05-31 23:22:10 -07004552 this, ret, deltaMs, throttleMs);
Andy Hung40eb1a12015-06-18 13:42:02 -07004553 mThreadThrottleTimeMs += throttleMs;
Andy Hung0a31ddd2016-07-06 19:10:29 -07004554 // Throttle must be attributed to the previous mixer loop's write time
4555 // to allow back-to-back throttling.
Andy Hung446f4df2019-02-21 12:26:41 -08004556 // This also ensures proper timing statistics.
4557 mLastIoEndNs = systemTime(); // we fetch the write end time again.
Andy Hung40eb1a12015-06-18 13:42:02 -07004558 } else {
4559 uint32_t diff = mThreadThrottleTimeMs - mThreadThrottleEndMs;
4560 if (diff > 0) {
4561 // notify of throttle end on debug log
Andy Hung3ea004d2016-05-05 16:48:37 -07004562 // but prevent spamming for bluetooth
jiabinc52b1ff2019-10-31 17:20:42 -07004563 ALOGD_IF(!isSingleDeviceType(
Andy Hungab65b182023-09-06 19:41:47 -07004564 outDeviceTypes_l(), audio_is_a2dp_out_device) &&
jiabinc52b1ff2019-10-31 17:20:42 -07004565 !isSingleDeviceType(
Andy Hungab65b182023-09-06 19:41:47 -07004566 outDeviceTypes_l(),
4567 audio_is_hearing_aid_out_device),
Andy Hung3ea004d2016-05-05 16:48:37 -07004568 "mixer(%p) throttle end: throttle time(%u)", this, diff);
Andy Hung40eb1a12015-06-18 13:42:02 -07004569 mThreadThrottleEndMs = mThreadThrottleTimeMs;
4570 }
Andy Hung08fb1742015-05-31 23:22:10 -07004571 }
4572 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004573 }
Eric Laurent81784c32012-11-19 14:55:58 -08004574
Eric Laurentbfb1b832013-01-07 09:53:42 -08004575 } else {
Glenn Kastene7754022014-10-31 12:11:26 -07004576 ATRACE_BEGIN("sleep");
Andy Hungc5007f82023-08-29 14:26:09 -07004577 audio_utils::unique_lock _l(mutex());
rago1bb90822017-05-02 18:31:48 -07004578 // suspended requires accurate metering of sleep time.
4579 if (isSuspended()) {
4580 // advance by expected sleepTime
4581 timeLoopNextNs += microseconds((nsecs_t)mSleepTimeUs);
4582 const nsecs_t nowNs = systemTime();
4583
4584 // compute expected next time vs current time.
4585 // (negative deltas are treated as delays).
4586 nsecs_t deltaNs = timeLoopNextNs - nowNs;
4587 if (deltaNs < -kMaxNextBufferDelayNs) {
4588 // Delays longer than the max allowed trigger a reset.
4589 ALOGV("DelayNs: %lld, resetting timeLoopNextNs", (long long) deltaNs);
4590 deltaNs = microseconds((nsecs_t)mSleepTimeUs);
4591 timeLoopNextNs = nowNs + deltaNs;
4592 } else if (deltaNs < 0) {
4593 // Delays within the max delay allowed: zero the delta/sleepTime
4594 // to help the system catch up in the next iteration(s)
4595 ALOGV("DelayNs: %lld, catching-up", (long long) deltaNs);
4596 deltaNs = 0;
4597 }
4598 // update sleep time (which is >= 0)
4599 mSleepTimeUs = deltaNs / 1000;
4600 }
Eric Laurente93cc032016-05-05 10:15:10 -07004601 if (!mSignalPending && mConfigEvents.isEmpty() && !exitPending()) {
Andy Hungc5007f82023-08-29 14:26:09 -07004602 mWaitWorkCV.wait_for(_l, std::chrono::microseconds(mSleepTimeUs));
Eric Laurent51716182016-02-29 18:00:56 -08004603 }
Glenn Kastene7754022014-10-31 12:11:26 -07004604 ATRACE_END();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004605 }
Eric Laurent81784c32012-11-19 14:55:58 -08004606 }
4607
4608 // Finally let go of removed track(s), without the lock held
4609 // since we can't guarantee the destructors won't acquire that
4610 // same lock. This will also mutate and push a new fast mixer state.
4611 threadLoop_removeTracks(tracksToRemove);
4612 tracksToRemove.clear();
4613
4614 // FIXME I don't understand the need for this here;
4615 // it was in the original code but maybe the
4616 // assignment in saveOutputTracks() makes this unnecessary?
4617 clearOutputTracks();
4618
4619 // Effect chains will be actually deleted here if they were removed from
4620 // mEffectChains list during mixing or effects processing
4621 effectChains.clear();
4622
4623 // FIXME Note that the above .clear() is no longer necessary since effectChains
4624 // is now local to this block, but will keep it for now (at least until merge done).
4625 }
4626
Eric Laurentbfb1b832013-01-07 09:53:42 -08004627 threadLoop_exit();
4628
Eric Laurentcf817a22014-08-04 20:36:31 -07004629 if (!mStandby) {
4630 threadLoop_standby();
Eric Laurent19952e12023-04-20 10:08:29 +02004631 setStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08004632 }
4633
4634 releaseWakeLock();
4635
4636 ALOGV("Thread %p type %d exiting", this, mType);
4637 return false;
4638}
4639
Andy Hungee58e4a2023-07-07 13:47:37 -07004640void PlaybackThread::collectTimestamps_l()
Dean Wheatley12473e92021-03-18 23:00:55 +11004641{
Dean Wheatley12473e92021-03-18 23:00:55 +11004642 if (mStandby) {
4643 mTimestampVerifier.discontinuity(discontinuityForStandbyOrFlush());
4644 return;
4645 } else if (mHwPaused) {
4646 mTimestampVerifier.discontinuity(mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS);
4647 return;
4648 }
4649
4650 // Gather the framesReleased counters for all active tracks,
4651 // and associate with the sink frames written out. We need
4652 // this to convert the sink timestamp to the track timestamp.
4653 bool kernelLocationUpdate = false;
4654 ExtendedTimestamp timestamp; // use private copy to fetch
4655
4656 // Always query HAL timestamp and update timestamp verifier. In standby or pause,
4657 // HAL may be draining some small duration buffered data for fade out.
4658 if (threadloop_getHalTimestamp_l(&timestamp) == OK) {
4659 mTimestampVerifier.add(timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL],
4660 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4661 mSampleRate);
4662
Andy Hungab65b182023-09-06 19:41:47 -07004663 if (isTimestampCorrectionEnabled_l()) {
Dean Wheatley12473e92021-03-18 23:00:55 +11004664 ALOGVV("TS_BEFORE: %d %lld %lld", id(),
4665 (long long)timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4666 (long long)timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]);
4667 auto correctedTimestamp = mTimestampVerifier.getLastCorrectedTimestamp();
4668 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4669 = correctedTimestamp.mFrames;
4670 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]
4671 = correctedTimestamp.mTimeNs;
4672 ALOGVV("TS_AFTER: %d %lld %lld", id(),
4673 (long long)timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4674 (long long)timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]);
4675
4676 // Note: Downstream latency only added if timestamp correction enabled.
4677 if (mDownstreamLatencyStatMs.getN() > 0) { // we have latency info.
4678 const int64_t newPosition =
4679 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4680 - int64_t(mDownstreamLatencyStatMs.getMean() * mSampleRate * 1e-3);
4681 // prevent retrograde
4682 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = max(
4683 newPosition,
4684 (mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4685 - mSuspendedFrames));
4686 }
4687 }
4688
4689 // We always fetch the timestamp here because often the downstream
4690 // sink will block while writing.
4691
4692 // We keep track of the last valid kernel position in case we are in underrun
4693 // and the normal mixer period is the same as the fast mixer period, or there
4694 // is some error from the HAL.
4695 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
4696 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
4697 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
4698 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
4699 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4700
4701 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
4702 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER];
4703 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
4704 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER];
4705 }
4706
4707 if (timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
4708 kernelLocationUpdate = true;
4709 } else {
4710 ALOGVV("getTimestamp error - no valid kernel position");
4711 }
4712
4713 // copy over kernel info
4714 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] =
4715 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4716 + mSuspendedFrames; // add frames discarded when suspended
4717 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] =
4718 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4719 } else {
4720 mTimestampVerifier.error();
4721 }
4722
4723 // mFramesWritten for non-offloaded tracks are contiguous
4724 // even after standby() is called. This is useful for the track frame
4725 // to sink frame mapping.
4726 bool serverLocationUpdate = false;
4727 if (mFramesWritten != mLastFramesWritten) {
4728 serverLocationUpdate = true;
4729 mLastFramesWritten = mFramesWritten;
4730 }
4731 // Only update timestamps if there is a meaningful change.
4732 // Either the kernel timestamp must be valid or we have written something.
4733 if (kernelLocationUpdate || serverLocationUpdate) {
4734 if (serverLocationUpdate) {
4735 // use the time before we called the HAL write - it is a bit more accurate
4736 // to when the server last read data than the current time here.
4737 //
4738 // If we haven't written anything, mLastIoBeginNs will be -1
4739 // and we use systemTime().
4740 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] = mFramesWritten;
4741 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = mLastIoBeginNs == -1
Andy Hung8d672e02023-09-15 18:19:28 -07004742 ? systemTime() : (int64_t)mLastIoBeginNs;
Dean Wheatley12473e92021-03-18 23:00:55 +11004743 }
4744
Andy Hung8d31fd22023-06-26 19:20:57 -07004745 for (const sp<IAfTrack>& t : mActiveTracks) {
Dean Wheatley12473e92021-03-18 23:00:55 +11004746 if (!t->isFastTrack()) {
4747 t->updateTrackFrameInfo(
Andy Hung8d31fd22023-06-26 19:20:57 -07004748 t->audioTrackServerProxy()->framesReleased(),
Dean Wheatley12473e92021-03-18 23:00:55 +11004749 mFramesWritten,
4750 mSampleRate,
4751 mTimestamp);
4752 }
4753 }
4754 }
4755
4756 if (audio_has_proportional_frames(mFormat)) {
4757 const double latencyMs = mTimestamp.getOutputServerLatencyMs(mSampleRate);
4758 if (latencyMs != 0.) { // note 0. means timestamp is empty.
4759 mLatencyMs.add(latencyMs);
4760 }
4761 }
4762#if 0
4763 // logFormat example
4764 if (z % 100 == 0) {
4765 timespec ts;
4766 clock_gettime(CLOCK_MONOTONIC, &ts);
4767 LOGT("This is an integer %d, this is a float %f, this is my "
4768 "pid %p %% %s %t", 42, 3.14, "and this is a timestamp", ts);
4769 LOGT("A deceptive null-terminated string %\0");
4770 }
4771 ++z;
4772#endif
4773}
4774
Andy Hungc5007f82023-08-29 14:26:09 -07004775// removeTracks_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07004776void PlaybackThread::removeTracks_l(const Vector<sp<IAfTrack>>& tracksToRemove)
Andy Hungc5007f82023-08-29 14:26:09 -07004777NO_THREAD_SAFETY_ANALYSIS // release and re-acquire mutex()
Eric Laurentbfb1b832013-01-07 09:53:42 -08004778{
Andy Hung6c498e92023-12-05 17:28:17 -08004779 if (tracksToRemove.empty()) return;
4780
4781 // Block all incoming TrackHandle requests until we are finished with the release.
4782 setThreadBusy_l(true);
4783
Andy Hungfe726a62018-09-27 15:17:25 -07004784 for (const auto& track : tracksToRemove) {
Andy Hungfe726a62018-09-27 15:17:25 -07004785 ALOGV("%s(%d): removing track on session %d", __func__, track->id(), track->sessionId());
Andy Hung116bc262023-06-20 18:56:17 -07004786 sp<IAfEffectChain> chain = getEffectChain_l(track->sessionId());
Andy Hungfe726a62018-09-27 15:17:25 -07004787 if (chain != 0) {
4788 ALOGV("%s(%d): stopping track on chain %p for session Id: %d",
4789 __func__, track->id(), chain.get(), track->sessionId());
4790 chain->decActiveTrackCnt();
4791 }
Andy Hung6c498e92023-12-05 17:28:17 -08004792
Andy Hungfe726a62018-09-27 15:17:25 -07004793 // If an external client track, inform APM we're no longer active, and remove if needed.
Andy Hung6c498e92023-12-05 17:28:17 -08004794 // Since the track is active, we do it here instead of TrackBase::destroy().
Andy Hungfe726a62018-09-27 15:17:25 -07004795 if (track->isExternalTrack()) {
Andy Hung6c498e92023-12-05 17:28:17 -08004796 mutex().unlock();
Andy Hungfe726a62018-09-27 15:17:25 -07004797 AudioSystem::stopOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08004798 if (track->isTerminated()) {
Andy Hungfe726a62018-09-27 15:17:25 -07004799 AudioSystem::releaseOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08004800 }
Andy Hung6c498e92023-12-05 17:28:17 -08004801 mutex().lock();
Andy Hungfe726a62018-09-27 15:17:25 -07004802 }
jiabineb3bda02020-06-30 14:07:03 -07004803 if (mHapticChannelCount > 0 &&
4804 ((track->channelMask() & AUDIO_CHANNEL_HAPTIC_ALL) != AUDIO_CHANNEL_NONE
François Gaffie541fd402023-11-29 17:16:38 +01004805 || (chain != nullptr && chain->containsHapticGeneratingEffect()))) {
Andy Hungc5007f82023-08-29 14:26:09 -07004806 mutex().unlock();
jiabin57303cc2018-12-18 15:45:57 -08004807 // Unlock due to VibratorService will lock for this call and will
4808 // call Tracks.mute/unmute which also require thread's lock.
Andy Hung7fb97e12023-07-20 21:23:42 -07004809 afutils::onExternalVibrationStop(track->getExternalVibration());
Andy Hungc5007f82023-08-29 14:26:09 -07004810 mutex().lock();
jiabine70bc7f2020-06-30 22:07:55 -07004811
4812 // When the track is stop, set the haptic intensity as MUTE
4813 // for the HapticGenerator effect.
4814 if (chain != nullptr) {
Ahmad Khalil229466a2024-02-05 12:15:30 +00004815 chain->setHapticScale_l(track->id(), os::HapticScale::mute());
jiabine70bc7f2020-06-30 22:07:55 -07004816 }
jiabin245cdd92018-12-07 17:55:15 -08004817 }
Andy Hung6c498e92023-12-05 17:28:17 -08004818
4819 // Under lock, the track is removed from the active tracks list.
4820 //
4821 // Once the track is no longer active, the TrackHandle may directly
4822 // modify it as the threadLoop() is no longer responsible for its maintenance.
4823 // Do not modify the track from threadLoop after the mutex is unlocked
4824 // if it is not active.
4825 mActiveTracks.remove(track);
4826
4827 if (track->isTerminated()) {
4828 // remove from our tracks vector
4829 removeTrack_l(track);
4830 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004831 }
Andy Hung6c498e92023-12-05 17:28:17 -08004832
4833 // Allow incoming TrackHandle requests. We still hold the mutex,
4834 // so pending TrackHandle requests will occur after we unlock it.
4835 setThreadBusy_l(false);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004836}
Eric Laurent81784c32012-11-19 14:55:58 -08004837
Andy Hungee58e4a2023-07-07 13:47:37 -07004838status_t PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
Eric Laurentaccc1472013-09-20 09:36:34 -07004839{
4840 if (mNormalSink != 0) {
Andy Hung818e7a32016-02-16 18:08:07 -08004841 ExtendedTimestamp ets;
4842 status_t status = mNormalSink->getTimestamp(ets);
4843 if (status == NO_ERROR) {
4844 status = ets.getBestTimestamp(&timestamp);
4845 }
4846 return status;
Eric Laurentaccc1472013-09-20 09:36:34 -07004847 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004848 if ((mType == OFFLOAD || mType == DIRECT) && mOutput != NULL) {
Dean Wheatley12473e92021-03-18 23:00:55 +11004849 collectTimestamps_l();
4850 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] <= 0) {
4851 return INVALID_OPERATION;
Eric Laurentaccc1472013-09-20 09:36:34 -07004852 }
Dean Wheatley12473e92021-03-18 23:00:55 +11004853 timestamp.mPosition = mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
4854 const int64_t timeNs = mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4855 timestamp.mTime.tv_sec = timeNs / NANOS_PER_SECOND;
4856 timestamp.mTime.tv_nsec = timeNs - (timestamp.mTime.tv_sec * NANOS_PER_SECOND);
4857 return NO_ERROR;
Eric Laurentaccc1472013-09-20 09:36:34 -07004858 }
4859 return INVALID_OPERATION;
4860}
Eric Laurent1c333e22014-05-20 10:48:17 -07004861
Eric Laurenteab90452019-06-24 15:17:46 -07004862// For dedicated VoIP outputs, let the HAL apply the stream volume. Track volume is
4863// still applied by the mixer.
4864// All tracks attached to a mixer with flag VOIP_RX are tied to the same
4865// stream type STREAM_VOICE_CALL so this will only change the HAL volume once even
4866// if more than one track are active
Andy Hungee58e4a2023-07-07 13:47:37 -07004867status_t PlaybackThread::handleVoipVolume_l(float* volume)
Eric Laurenteab90452019-06-24 15:17:46 -07004868{
4869 status_t result = NO_ERROR;
4870 if ((mOutput->flags & AUDIO_OUTPUT_FLAG_VOIP_RX) != 0) {
4871 if (*volume != mLeftVolFloat) {
4872 result = mOutput->stream->setVolume(*volume, *volume);
Alex Leungc5dedb22023-05-10 08:00:50 -07004873 // HAL can return INVALID_OPERATION if operation is not supported.
4874 ALOGE_IF(result != OK && result != INVALID_OPERATION,
Eric Laurenteab90452019-06-24 15:17:46 -07004875 "Error when setting output stream volume: %d", result);
4876 if (result == NO_ERROR) {
4877 mLeftVolFloat = *volume;
4878 }
4879 }
4880 // if stream volume was successfully sent to the HAL, mLeftVolFloat == v here and we
4881 // remove stream volume contribution from software volume.
4882 if (mLeftVolFloat == *volume) {
4883 *volume = 1.0f;
4884 }
4885 }
4886 return result;
4887}
4888
Andy Hungee58e4a2023-07-07 13:47:37 -07004889status_t MixerThread::createAudioPatch_l(const struct audio_patch* patch,
Eric Laurent054d9d32015-04-24 08:48:48 -07004890 audio_patch_handle_t *handle)
4891{
Andy Hungf60abce2016-08-26 11:37:54 -07004892 status_t status;
4893 if (property_get_bool("af.patch_park", false /* default_value */)) {
4894 // Park FastMixer to avoid potential DOS issues with writing to the HAL
4895 // or if HAL does not properly lock against access.
4896 AutoPark<FastMixer> park(mFastMixer);
4897 status = PlaybackThread::createAudioPatch_l(patch, handle);
4898 } else {
4899 status = PlaybackThread::createAudioPatch_l(patch, handle);
4900 }
Eric Laurentb0463942022-12-20 16:31:10 +01004901
4902 updateHalSupportedLatencyModes_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07004903 return status;
4904}
4905
Andy Hungee58e4a2023-07-07 13:47:37 -07004906status_t PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
Eric Laurent1c333e22014-05-20 10:48:17 -07004907 audio_patch_handle_t *handle)
4908{
4909 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07004910
4911 // store new device and send to effects
4912 audio_devices_t type = AUDIO_DEVICE_NONE;
jiabinc52b1ff2019-10-31 17:20:42 -07004913 AudioDeviceTypeAddrVector deviceTypeAddrs;
Eric Laurent054d9d32015-04-24 08:48:48 -07004914 for (unsigned int i = 0; i < patch->num_sinks; i++) {
jiabinc52b1ff2019-10-31 17:20:42 -07004915 LOG_ALWAYS_FATAL_IF(popcount(patch->sinks[i].ext.device.type) > 1
4916 && !mOutput->audioHwDev->supportsAudioPatches(),
4917 "Enumerated device type(%#x) must not be used "
4918 "as it does not support audio patches",
4919 patch->sinks[i].ext.device.type);
Mikhail Naganov55773032020-10-01 15:08:13 -07004920 type = static_cast<audio_devices_t>(type | patch->sinks[i].ext.device.type);
Andy Hung920f6572022-10-06 12:09:49 -07004921 deviceTypeAddrs.emplace_back(patch->sinks[i].ext.device.type,
4922 patch->sinks[i].ext.device.address);
Eric Laurent054d9d32015-04-24 08:48:48 -07004923 }
4924
François Gaffie0c280aa2018-07-25 10:02:15 +02004925 audio_port_handle_t sinkPortId = patch->sinks[0].id;
Eric Laurent054d9d32015-04-24 08:48:48 -07004926#ifdef ADD_BATTERY_DATA
4927 // when changing the audio output device, call addBatteryData to notify
4928 // the change
jiabinc52b1ff2019-10-31 17:20:42 -07004929 if (outDeviceTypes() != deviceTypes) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004930 uint32_t params = 0;
4931 // check whether speaker is on
jiabinc52b1ff2019-10-31 17:20:42 -07004932 if (deviceTypes.count(AUDIO_DEVICE_OUT_SPEAKER) > 0) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004933 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent1c333e22014-05-20 10:48:17 -07004934 }
4935
Eric Laurent054d9d32015-04-24 08:48:48 -07004936 // check if any other device (except speaker) is on
jiabinc52b1ff2019-10-31 17:20:42 -07004937 if (!isSingleDeviceType(deviceTypes, AUDIO_DEVICE_OUT_SPEAKER)) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004938 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
4939 }
4940
4941 if (params != 0) {
4942 addBatteryData(params);
4943 }
4944 }
4945#endif
4946
4947 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08004948 mEffectChains[i]->setDevices_l(deviceTypeAddrs);
Eric Laurent054d9d32015-04-24 08:48:48 -07004949 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07004950
jiabinc52b1ff2019-10-31 17:20:42 -07004951 // mPatch.num_sinks is not set when the thread is created so that
4952 // the first patch creation triggers an ioConfigChanged callback
4953 bool configChanged = (mPatch.num_sinks == 0) ||
4954 (mPatch.sinks[0].id != sinkPortId);
Eric Laurent296fb132015-05-01 11:38:42 -07004955 mPatch = *patch;
jiabinc52b1ff2019-10-31 17:20:42 -07004956 mOutDeviceTypeAddrs = deviceTypeAddrs;
jiabin0a957d32020-04-29 10:56:20 -07004957 checkSilentMode_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07004958
Mikhail Naganov9ee05402016-10-13 15:58:17 -07004959 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07004960 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
4961 status = hwDevice->createAudioPatch(patch->num_sources,
4962 patch->sources,
4963 patch->num_sinks,
4964 patch->sinks,
4965 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07004966 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08004967 status = mOutput->stream->legacyCreateAudioPatch(patch->sinks[0], std::nullopt, type);
Eric Laurent054d9d32015-04-24 08:48:48 -07004968 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07004969 }
Andy Hungc2b11cb2020-04-22 09:04:01 -07004970 const std::string patchSinksAsString = patchSinksToString(patch);
Andy Hungcf10d742020-04-28 15:38:24 -07004971
4972 mThreadMetrics.logEndInterval();
Andy Hungea840382020-05-05 21:50:17 -07004973 mThreadMetrics.logCreatePatch(/* inDevices */ {}, patchSinksAsString);
Andy Hungcf10d742020-04-28 15:38:24 -07004974 mThreadMetrics.logBeginInterval();
Andy Hungc2b11cb2020-04-22 09:04:01 -07004975 // also dispatch to active AudioTracks for MediaMetrics
4976 for (const auto &track : mActiveTracks) {
4977 track->logEndInterval();
4978 track->logBeginInterval(patchSinksAsString);
4979 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08004980
Eric Laurente8726fe2015-06-26 09:39:24 -07004981 if (configChanged) {
4982 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
4983 }
Vlad Popa7e81cea2023-01-19 16:34:16 +01004984 // Force metadata update after a route change
Eric Laurentdda206a2022-07-08 17:28:35 +02004985 mActiveTracks.setHasChanged();
4986
Eric Laurent1c333e22014-05-20 10:48:17 -07004987 return status;
4988}
4989
Andy Hungee58e4a2023-07-07 13:47:37 -07004990status_t MixerThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
Eric Laurent054d9d32015-04-24 08:48:48 -07004991{
Andy Hungf60abce2016-08-26 11:37:54 -07004992 status_t status;
4993 if (property_get_bool("af.patch_park", false /* default_value */)) {
4994 // Park FastMixer to avoid potential DOS issues with writing to the HAL
4995 // or if HAL does not properly lock against access.
4996 AutoPark<FastMixer> park(mFastMixer);
4997 status = PlaybackThread::releaseAudioPatch_l(handle);
4998 } else {
4999 status = PlaybackThread::releaseAudioPatch_l(handle);
5000 }
Eric Laurent054d9d32015-04-24 08:48:48 -07005001 return status;
5002}
5003
Andy Hungee58e4a2023-07-07 13:47:37 -07005004status_t PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005005{
5006 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07005007
jiabinc52b1ff2019-10-31 17:20:42 -07005008 mPatch = audio_patch{};
5009 mOutDeviceTypeAddrs.clear();
Eric Laurent054d9d32015-04-24 08:48:48 -07005010
Mikhail Naganov9ee05402016-10-13 15:58:17 -07005011 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07005012 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
5013 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07005014 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08005015 status = mOutput->stream->legacyReleaseAudioPatch();
Eric Laurent1c333e22014-05-20 10:48:17 -07005016 }
Eric Laurentdda206a2022-07-08 17:28:35 +02005017 // Force meteadata update after a route change
5018 mActiveTracks.setHasChanged();
5019
Eric Laurent1c333e22014-05-20 10:48:17 -07005020 return status;
5021}
5022
Andy Hungee58e4a2023-07-07 13:47:37 -07005023void PlaybackThread::addPatchTrack(const sp<IAfPatchTrack>& track)
Eric Laurent83b88082014-06-20 18:31:16 -07005024{
Andy Hung972bec12023-08-31 16:13:39 -07005025 audio_utils::lock_guard _l(mutex());
Eric Laurent83b88082014-06-20 18:31:16 -07005026 mTracks.add(track);
5027}
5028
Andy Hungee58e4a2023-07-07 13:47:37 -07005029void PlaybackThread::deletePatchTrack(const sp<IAfPatchTrack>& track)
Eric Laurent83b88082014-06-20 18:31:16 -07005030{
Andy Hung972bec12023-08-31 16:13:39 -07005031 audio_utils::lock_guard _l(mutex());
Eric Laurent83b88082014-06-20 18:31:16 -07005032 destroyTrack_l(track);
5033}
5034
Andy Hungee58e4a2023-07-07 13:47:37 -07005035void PlaybackThread::toAudioPortConfig(struct audio_port_config* config)
Eric Laurent83b88082014-06-20 18:31:16 -07005036{
Mikhail Naganovdc769682018-05-04 15:34:08 -07005037 ThreadBase::toAudioPortConfig(config);
Eric Laurent83b88082014-06-20 18:31:16 -07005038 config->role = AUDIO_PORT_ROLE_SOURCE;
5039 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
5040 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07005041 if (mOutput && mOutput->flags != AUDIO_OUTPUT_FLAG_NONE) {
5042 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
5043 config->flags.output = mOutput->flags;
5044 }
Eric Laurent83b88082014-06-20 18:31:16 -07005045}
5046
Eric Laurent81784c32012-11-19 14:55:58 -08005047// ----------------------------------------------------------------------------
5048
Andy Hungee58e4a2023-07-07 13:47:37 -07005049/* static */
5050sp<IAfPlaybackThread> IAfPlaybackThread::createMixerThread(
Andy Hung583043b2023-07-17 17:05:00 -07005051 const sp<IAfThreadCallback>& afThreadCallback, AudioStreamOut* output,
Andy Hungee58e4a2023-07-07 13:47:37 -07005052 audio_io_handle_t id, bool systemReady, type_t type, audio_config_base_t* mixerConfig) {
Andy Hung583043b2023-07-17 17:05:00 -07005053 return sp<MixerThread>::make(afThreadCallback, output, id, systemReady, type, mixerConfig);
Andy Hungee58e4a2023-07-07 13:47:37 -07005054}
5055
Andy Hung583043b2023-07-17 17:05:00 -07005056MixerThread::MixerThread(const sp<IAfThreadCallback>& afThreadCallback, AudioStreamOut* output,
Eric Laurentf1f22e72021-07-13 14:04:14 +02005057 audio_io_handle_t id, bool systemReady, type_t type, audio_config_base_t *mixerConfig)
Andy Hung583043b2023-07-17 17:05:00 -07005058 : PlaybackThread(afThreadCallback, output, id, type, systemReady, mixerConfig),
Eric Laurent81784c32012-11-19 14:55:58 -08005059 // mAudioMixer below
5060 // mFastMixer below
Eric Laurentb0463942022-12-20 16:31:10 +01005061 mBluetoothLatencyModesEnabled(false),
Andy Hung2ddee192015-12-18 17:34:44 -08005062 mFastMixerFutex(0),
5063 mMasterMono(false)
Eric Laurent81784c32012-11-19 14:55:58 -08005064 // mOutputSink below
5065 // mPipeSink below
5066 // mNormalSink below
5067{
Andy Hung583043b2023-07-17 17:05:00 -07005068 setMasterBalance(afThreadCallback->getMasterBalance_l());
jiabinc52b1ff2019-10-31 17:20:42 -07005069 ALOGV("MixerThread() id=%d type=%d", id, type);
Glenn Kasten49f36ba2017-12-06 13:02:02 -08005070 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%#x, mFrameSize=%zu, "
Glenn Kastenc42e9b42016-03-21 11:35:03 -07005071 "mFrameCount=%zu, mNormalFrameCount=%zu",
Eric Laurent81784c32012-11-19 14:55:58 -08005072 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
5073 mNormalFrameCount);
5074 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
5075
Andy Hungfbfc3952015-01-15 13:33:51 -08005076 if (type == DUPLICATING) {
5077 // The Duplicating thread uses the AudioMixer and delivers data to OutputTracks
5078 // (downstream MixerThreads) in DuplicatingThread::threadLoop_write().
5079 // Do not create or use mFastMixer, mOutputSink, mPipeSink, or mNormalSink.
5080 return;
5081 }
Eric Laurent81784c32012-11-19 14:55:58 -08005082 // create an NBAIO sink for the HAL output stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07005083 mOutputSink = new AudioStreamOutSink(output->stream);
Eric Laurent81784c32012-11-19 14:55:58 -08005084 size_t numCounterOffers = 0;
jiabin245cdd92018-12-07 17:55:15 -08005085 const NBAIO_Format offers[1] = {Format_from_SR_C(
5086 mSampleRate, mChannelCount + mHapticChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005087#if !LOG_NDEBUG
5088 ssize_t index =
5089#else
5090 (void)
5091#endif
5092 mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08005093 ALOG_ASSERT(index == 0);
5094
5095 // initialize fast mixer depending on configuration
5096 bool initFastMixer;
jiabinc658e452022-10-21 20:52:21 +00005097 if (mType == SPATIALIZER || mType == BIT_PERFECT) {
Eric Laurent81784c32012-11-19 14:55:58 -08005098 initFastMixer = false;
Eric Laurentb62d0362021-10-26 17:40:18 +02005099 } else {
5100 switch (kUseFastMixer) {
5101 case FastMixer_Never:
5102 initFastMixer = false;
5103 break;
5104 case FastMixer_Always:
5105 initFastMixer = true;
5106 break;
5107 case FastMixer_Static:
5108 case FastMixer_Dynamic:
5109 initFastMixer = mFrameCount < mNormalFrameCount;
5110 break;
5111 }
5112 ALOGW_IF(initFastMixer == false && mFrameCount < mNormalFrameCount,
5113 "FastMixer is preferred for this sink as frameCount %zu is less than threshold %zu",
5114 mFrameCount, mNormalFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08005115 }
5116 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07005117 audio_format_t fastMixerFormat;
5118 if (mMixerBufferEnabled && mEffectBufferEnabled) {
5119 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
5120 } else {
5121 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
5122 }
5123 if (mFormat != fastMixerFormat) {
5124 // change our Sink format to accept our intermediate precision
5125 mFormat = fastMixerFormat;
5126 free(mSinkBuffer);
jiabin245cdd92018-12-07 17:55:15 -08005127 mFrameSize = audio_bytes_per_frame(mChannelCount + mHapticChannelCount, mFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07005128 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
5129 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
5130 }
Eric Laurent81784c32012-11-19 14:55:58 -08005131
5132 // create a MonoPipe to connect our submix to FastMixer
5133 NBAIO_Format format = mOutputSink->format();
Andy Hung8946a282018-04-19 20:04:56 -07005134
Andy Hung1258c1a2014-05-23 21:22:17 -07005135 // adjust format to match that of the Fast Mixer
Glenn Kasten49f36ba2017-12-06 13:02:02 -08005136 ALOGV("format changed from %#x to %#x", format.mFormat, fastMixerFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07005137 format.mFormat = fastMixerFormat;
5138 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
5139
Eric Laurent81784c32012-11-19 14:55:58 -08005140 // This pipe depth compensates for scheduling latency of the normal mixer thread.
5141 // When it wakes up after a maximum latency, it runs a few cycles quickly before
5142 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
5143 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
Andy Hung920f6572022-10-06 12:09:49 -07005144 const NBAIO_Format offersFast[1] = {format};
5145 size_t numCounterOffersFast = 0;
Andy Hung8946a282018-04-19 20:04:56 -07005146#if !LOG_NDEBUG
Eric Laurent1e28aaa2023-04-16 19:34:23 +02005147 index =
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005148#else
5149 (void)
5150#endif
Andy Hung920f6572022-10-06 12:09:49 -07005151 monoPipe->negotiate(offersFast, std::size(offersFast),
5152 nullptr /* counterOffers */, numCounterOffersFast);
Eric Laurent81784c32012-11-19 14:55:58 -08005153 ALOG_ASSERT(index == 0);
5154 monoPipe->setAvgFrames((mScreenState & 1) ?
5155 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
5156 mPipeSink = monoPipe;
5157
Eric Laurent81784c32012-11-19 14:55:58 -08005158 // create fast mixer and configure it initially with just one fast track for our submix
Andy Hung8946a282018-04-19 20:04:56 -07005159 mFastMixer = new FastMixer(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08005160 FastMixerStateQueue *sq = mFastMixer->sq();
5161#ifdef STATE_QUEUE_DUMP
5162 sq->setObserverDump(&mStateQueueObserverDump);
5163 sq->setMutatorDump(&mStateQueueMutatorDump);
5164#endif
5165 FastMixerState *state = sq->begin();
5166 FastTrack *fastTrack = &state->mFastTracks[0];
5167 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
5168 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
5169 fastTrack->mVolumeProvider = NULL;
Mikhail Naganov55773032020-10-01 15:08:13 -07005170 fastTrack->mChannelMask = static_cast<audio_channel_mask_t>(
5171 mChannelMask | mHapticChannelMask); // mPipeSink channel mask for
5172 // audio to FastMixer
Andy Hunge8a1ced2014-05-09 15:02:21 -07005173 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
jiabin245cdd92018-12-07 17:55:15 -08005174 fastTrack->mHapticPlaybackEnabled = mHapticChannelMask != AUDIO_CHANNEL_NONE;
Ahmad Khalil229466a2024-02-05 12:15:30 +00005175 fastTrack->mHapticScale = {/*level=*/os::HapticLevel::NONE };
Lais Andradebc3f37a2021-07-02 00:13:19 +01005176 fastTrack->mHapticMaxAmplitude = NAN;
Eric Laurent81784c32012-11-19 14:55:58 -08005177 fastTrack->mGeneration++;
5178 state->mFastTracksGen++;
5179 state->mTrackMask = 1;
5180 // fast mixer will use the HAL output sink
5181 state->mOutputSink = mOutputSink.get();
5182 state->mOutputSinkGen++;
5183 state->mFrameCount = mFrameCount;
jiabin245cdd92018-12-07 17:55:15 -08005184 // specify sink channel mask when haptic channel mask present as it can not
5185 // be calculated directly from channel count
5186 state->mSinkChannelMask = mHapticChannelMask == AUDIO_CHANNEL_NONE
Mikhail Naganov55773032020-10-01 15:08:13 -07005187 ? AUDIO_CHANNEL_NONE
5188 : static_cast<audio_channel_mask_t>(mChannelMask | mHapticChannelMask);
Eric Laurent81784c32012-11-19 14:55:58 -08005189 state->mCommand = FastMixerState::COLD_IDLE;
5190 // already done in constructor initialization list
5191 //mFastMixerFutex = 0;
5192 state->mColdFutexAddr = &mFastMixerFutex;
5193 state->mColdGen++;
5194 state->mDumpState = &mFastMixerDumpState;
Andy Hung583043b2023-07-17 17:05:00 -07005195 mFastMixerNBLogWriter = afThreadCallback->newWriter_l(kFastMixerLogSize, "FastMixer");
Glenn Kasten9e58b552013-01-18 15:09:48 -08005196 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08005197 sq->end();
5198 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
5199
Eric Tan0513b5d2018-09-17 10:32:48 -07005200 NBLog::thread_info_t info;
5201 info.id = mId;
5202 info.type = NBLog::FASTMIXER;
5203 mFastMixerNBLogWriter->log<NBLog::EVENT_THREAD_INFO>(info);
5204
Eric Laurent81784c32012-11-19 14:55:58 -08005205 // start the fast mixer
5206 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
5207 pid_t tid = mFastMixer->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07005208 sendPrioConfigEvent(getpid(), tid, kPriorityFastMixer, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08005209 stream()->setHalThreadPriority(kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08005210
5211#ifdef AUDIO_WATCHDOG
5212 // create and start the watchdog
5213 mAudioWatchdog = new AudioWatchdog();
5214 mAudioWatchdog->setDump(&mAudioWatchdogDump);
5215 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
5216 tid = mAudioWatchdog->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07005217 sendPrioConfigEvent(getpid(), tid, kPriorityFastMixer, false /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08005218#endif
Andy Hung8946a282018-04-19 20:04:56 -07005219 } else {
5220#ifdef TEE_SINK
5221 // Only use the MixerThread tee if there is no FastMixer.
5222 mTee.set(mOutputSink->format(), NBAIO_Tee::TEE_FLAG_OUTPUT_THREAD);
5223 mTee.setId(std::string("_") + std::to_string(mId) + "_M");
5224#endif
Eric Laurent81784c32012-11-19 14:55:58 -08005225 }
5226
5227 switch (kUseFastMixer) {
5228 case FastMixer_Never:
5229 case FastMixer_Dynamic:
5230 mNormalSink = mOutputSink;
5231 break;
5232 case FastMixer_Always:
5233 mNormalSink = mPipeSink;
5234 break;
5235 case FastMixer_Static:
5236 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
5237 break;
5238 }
5239}
5240
Andy Hungee58e4a2023-07-07 13:47:37 -07005241MixerThread::~MixerThread()
Eric Laurent81784c32012-11-19 14:55:58 -08005242{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005243 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005244 FastMixerStateQueue *sq = mFastMixer->sq();
5245 FastMixerState *state = sq->begin();
5246 if (state->mCommand == FastMixerState::COLD_IDLE) {
5247 int32_t old = android_atomic_inc(&mFastMixerFutex);
5248 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07005249 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08005250 }
5251 }
5252 state->mCommand = FastMixerState::EXIT;
5253 sq->end();
5254 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
5255 mFastMixer->join();
5256 // Though the fast mixer thread has exited, it's state queue is still valid.
5257 // We'll use that extract the final state which contains one remaining fast track
5258 // corresponding to our sub-mix.
5259 state = sq->begin();
5260 ALOG_ASSERT(state->mTrackMask == 1);
5261 FastTrack *fastTrack = &state->mFastTracks[0];
5262 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
5263 delete fastTrack->mBufferProvider;
5264 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005265 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08005266#ifdef AUDIO_WATCHDOG
5267 if (mAudioWatchdog != 0) {
5268 mAudioWatchdog->requestExit();
5269 mAudioWatchdog->requestExitAndWait();
5270 mAudioWatchdog.clear();
5271 }
5272#endif
5273 }
Andy Hung583043b2023-07-17 17:05:00 -07005274 mAfThreadCallback->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08005275 delete mAudioMixer;
5276}
5277
Andy Hungee58e4a2023-07-07 13:47:37 -07005278void MixerThread::onFirstRef() {
Eric Laurentb0463942022-12-20 16:31:10 +01005279 PlaybackThread::onFirstRef();
5280
Andy Hung972bec12023-08-31 16:13:39 -07005281 audio_utils::lock_guard _l(mutex());
Eric Laurentb0463942022-12-20 16:31:10 +01005282 if (mOutput != nullptr && mOutput->stream != nullptr) {
5283 status_t status = mOutput->stream->setLatencyModeCallback(this);
5284 if (status != INVALID_OPERATION) {
5285 updateHalSupportedLatencyModes_l();
5286 }
5287 // Default to enabled if the HAL supports it. This can be changed by Audioflinger after
5288 // the thread construction according to AudioFlinger::mBluetoothLatencyModesEnabled
5289 mBluetoothLatencyModesEnabled.store(
5290 mOutput->audioHwDev->supportsBluetoothVariableLatency());
5291 }
5292}
Eric Laurent81784c32012-11-19 14:55:58 -08005293
Andy Hungee58e4a2023-07-07 13:47:37 -07005294uint32_t MixerThread::correctLatency_l(uint32_t latency) const
Eric Laurent81784c32012-11-19 14:55:58 -08005295{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005296 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005297 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
5298 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
5299 }
5300 return latency;
5301}
5302
Andy Hungee58e4a2023-07-07 13:47:37 -07005303ssize_t MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08005304{
5305 // FIXME we should only do one push per cycle; confirm this is true
5306 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005307 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005308 FastMixerStateQueue *sq = mFastMixer->sq();
5309 FastMixerState *state = sq->begin();
5310 if (state->mCommand != FastMixerState::MIX_WRITE &&
5311 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
5312 if (state->mCommand == FastMixerState::COLD_IDLE) {
Eric Laurenta2ab4502015-09-09 12:25:51 -07005313
5314 // FIXME workaround for first HAL write being CPU bound on some devices
5315 ATRACE_BEGIN("write");
5316 mOutput->write((char *)mSinkBuffer, 0);
5317 ATRACE_END();
5318
Eric Laurent81784c32012-11-19 14:55:58 -08005319 int32_t old = android_atomic_inc(&mFastMixerFutex);
5320 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07005321 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08005322 }
5323#ifdef AUDIO_WATCHDOG
5324 if (mAudioWatchdog != 0) {
5325 mAudioWatchdog->resume();
5326 }
5327#endif
5328 }
5329 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kastend797a9d2015-03-02 14:19:25 -08005330#ifdef FAST_THREAD_STATISTICS
Andy Hung583043b2023-07-17 17:05:00 -07005331 mFastMixerDumpState.increaseSamplingN(mAfThreadCallback->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08005332 FastThreadDumpState::kSamplingNforLowRamDevice : FastThreadDumpState::kSamplingN);
Glenn Kastend797a9d2015-03-02 14:19:25 -08005333#endif
Eric Laurent81784c32012-11-19 14:55:58 -08005334 sq->end();
5335 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
5336 if (kUseFastMixer == FastMixer_Dynamic) {
5337 mNormalSink = mPipeSink;
5338 }
5339 } else {
5340 sq->end(false /*didModify*/);
5341 }
5342 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005343 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08005344}
5345
Andy Hungee58e4a2023-07-07 13:47:37 -07005346void MixerThread::threadLoop_standby()
Eric Laurent81784c32012-11-19 14:55:58 -08005347{
5348 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005349 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005350 FastMixerStateQueue *sq = mFastMixer->sq();
5351 FastMixerState *state = sq->begin();
5352 if (!(state->mCommand & FastMixerState::IDLE)) {
Andy Hung2148bf02016-11-28 19:01:02 -08005353 // Report any frames trapped in the Monopipe
5354 MonoPipe *monoPipe = (MonoPipe *)mPipeSink.get();
5355 const long long pipeFrames = monoPipe->maxFrames() - monoPipe->availableToWrite();
5356 mLocalLog.log("threadLoop_standby: framesWritten:%lld suspendedFrames:%lld "
5357 "monoPipeWritten:%lld monoPipeLeft:%lld",
5358 (long long)mFramesWritten, (long long)mSuspendedFrames,
5359 (long long)mPipeSink->framesWritten(), pipeFrames);
5360 mLocalLog.log("threadLoop_standby: %s", mTimestamp.toString().c_str());
5361
Eric Laurent81784c32012-11-19 14:55:58 -08005362 state->mCommand = FastMixerState::COLD_IDLE;
5363 state->mColdFutexAddr = &mFastMixerFutex;
5364 state->mColdGen++;
5365 mFastMixerFutex = 0;
5366 sq->end();
5367 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
5368 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
5369 if (kUseFastMixer == FastMixer_Dynamic) {
5370 mNormalSink = mOutputSink;
5371 }
5372#ifdef AUDIO_WATCHDOG
5373 if (mAudioWatchdog != 0) {
5374 mAudioWatchdog->pause();
5375 }
5376#endif
5377 } else {
5378 sq->end(false /*didModify*/);
5379 }
5380 }
5381 PlaybackThread::threadLoop_standby();
5382}
5383
Andy Hungee58e4a2023-07-07 13:47:37 -07005384bool PlaybackThread::waitingAsyncCallback_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08005385{
5386 return false;
5387}
5388
Andy Hungee58e4a2023-07-07 13:47:37 -07005389bool PlaybackThread::shouldStandby_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08005390{
5391 return !mStandby;
5392}
5393
Andy Hungee58e4a2023-07-07 13:47:37 -07005394bool PlaybackThread::waitingAsyncCallback()
Eric Laurentbfb1b832013-01-07 09:53:42 -08005395{
Andy Hung972bec12023-08-31 16:13:39 -07005396 audio_utils::lock_guard _l(mutex());
Eric Laurentbfb1b832013-01-07 09:53:42 -08005397 return waitingAsyncCallback_l();
5398}
5399
Eric Laurent81784c32012-11-19 14:55:58 -08005400// shared by MIXER and DIRECT, overridden by DUPLICATING
Andy Hungee58e4a2023-07-07 13:47:37 -07005401void PlaybackThread::threadLoop_standby()
Eric Laurent81784c32012-11-19 14:55:58 -08005402{
Andy Hung8d672e02023-09-15 18:19:28 -07005403 ALOGV("%s: audio hardware entering standby, mixer %p, suspend count %d",
5404 __func__, this, (int32_t)mSuspended);
Phil Burk062e67a2015-02-11 13:40:50 -08005405 mOutput->standby();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005406 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005407 // discard any pending drain or write ack by incrementing sequence
5408 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
5409 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005410 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005411 mCallbackThread->setWriteBlocked(mWriteAckSequence);
5412 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005413 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08005414 mHwPaused = false;
Eric Laurent68a40a82022-05-03 18:15:04 +02005415 setHalLatencyMode_l();
Eric Laurent81784c32012-11-19 14:55:58 -08005416}
5417
Andy Hungee58e4a2023-07-07 13:47:37 -07005418void PlaybackThread::onAddNewTrack_l()
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08005419{
5420 ALOGV("signal playback thread");
5421 broadcast_l();
5422}
5423
Andy Hungee58e4a2023-07-07 13:47:37 -07005424void PlaybackThread::onAsyncError()
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005425{
5426 for (int i = AUDIO_STREAM_SYSTEM; i < (int)AUDIO_STREAM_CNT; i++) {
5427 invalidateTracks((audio_stream_type_t)i);
5428 }
5429}
5430
Andy Hungee58e4a2023-07-07 13:47:37 -07005431void MixerThread::threadLoop_mix()
Eric Laurent81784c32012-11-19 14:55:58 -08005432{
Eric Laurent81784c32012-11-19 14:55:58 -08005433 // mix buffers...
Glenn Kastend79072e2016-01-06 08:41:20 -08005434 mAudioMixer->process();
Andy Hung25c2dac2014-02-27 14:56:00 -08005435 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005436 // increase sleep time progressively when application underrun condition clears.
5437 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
5438 // that a steady state of alternating ready/not ready conditions keeps the sleep time
5439 // such that we would underrun the audio HAL.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005440 if ((mSleepTimeUs == 0) && (sleepTimeShift > 0)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005441 sleepTimeShift--;
5442 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005443 mSleepTimeUs = 0;
5444 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08005445 //TODO: delay standby when effects have a tail
Glenn Kasten4c053ea2014-09-28 14:41:07 -07005446
Eric Laurent81784c32012-11-19 14:55:58 -08005447}
5448
Andy Hungee58e4a2023-07-07 13:47:37 -07005449void MixerThread::threadLoop_sleepTime()
Eric Laurent81784c32012-11-19 14:55:58 -08005450{
5451 // If no tracks are ready, sleep once for the duration of an output
5452 // buffer size, then write 0s to the output
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005453 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005454 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Andy Hung06d13222018-05-03 20:13:31 -07005455 if (mPipeSink.get() != nullptr && mPipeSink == mNormalSink) {
5456 // Using the Monopipe availableToWrite, we estimate the
5457 // sleep time to retry for more data (before we underrun).
5458 MonoPipe *monoPipe = static_cast<MonoPipe *>(mPipeSink.get());
5459 const ssize_t availableToWrite = mPipeSink->availableToWrite();
5460 const size_t pipeFrames = monoPipe->maxFrames();
5461 const size_t framesLeft = pipeFrames - max(availableToWrite, 0);
5462 // HAL_framecount <= framesDelay ~ framesLeft / 2 <= Normal_Mixer_framecount
5463 const size_t framesDelay = std::min(
5464 mNormalFrameCount, max(framesLeft / 2, mFrameCount));
5465 ALOGV("pipeFrames:%zu framesLeft:%zu framesDelay:%zu",
5466 pipeFrames, framesLeft, framesDelay);
5467 mSleepTimeUs = framesDelay * MICROS_PER_SECOND / mSampleRate;
5468 } else {
5469 mSleepTimeUs = mActiveSleepTimeUs >> sleepTimeShift;
5470 if (mSleepTimeUs < kMinThreadSleepTimeUs) {
5471 mSleepTimeUs = kMinThreadSleepTimeUs;
5472 }
5473 // reduce sleep time in case of consecutive application underruns to avoid
5474 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
5475 // duration we would end up writing less data than needed by the audio HAL if
5476 // the condition persists.
5477 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
5478 sleepTimeShift++;
5479 }
Eric Laurent81784c32012-11-19 14:55:58 -08005480 }
5481 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005482 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005483 }
5484 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08005485 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
5486 // before effects processing or output.
5487 if (mMixerBufferValid) {
5488 memset(mMixerBuffer, 0, mMixerBufferSize);
Eric Laurent39095982021-08-24 18:29:27 +02005489 if (mType == SPATIALIZER) {
5490 memset(mSinkBuffer, 0, mSinkBufferSize);
5491 }
Andy Hung98ef9782014-03-04 14:46:50 -08005492 } else {
5493 memset(mSinkBuffer, 0, mSinkBufferSize);
5494 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005495 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005496 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
5497 "anticipated start");
5498 }
5499 // TODO add standby time extension fct of effect tail
5500}
5501
Andy Hungc5007f82023-08-29 14:26:09 -07005502// prepareTracks_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07005503PlaybackThread::mixer_state MixerThread::prepareTracks_l(
Andy Hung8d31fd22023-06-26 19:20:57 -07005504 Vector<sp<IAfTrack>>* tracksToRemove)
Eric Laurent81784c32012-11-19 14:55:58 -08005505{
Andy Hungc0691382018-09-12 18:01:57 -07005506 // clean up deleted track ids in AudioMixer before allocating new tracks
5507 (void)mTracks.processDeletedTrackIds([this](int trackId) {
5508 // for each trackId, destroy it in the AudioMixer
5509 if (mAudioMixer->exists(trackId)) {
5510 mAudioMixer->destroy(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08005511 }
5512 });
Andy Hungc0691382018-09-12 18:01:57 -07005513 mTracks.clearDeletedTrackIds();
Eric Laurent81784c32012-11-19 14:55:58 -08005514
5515 mixer_state mixerStatus = MIXER_IDLE;
5516 // find out which tracks need to be processed
5517 size_t count = mActiveTracks.size();
5518 size_t mixedTracks = 0;
5519 size_t tracksWithEffect = 0;
5520 // counts only _active_ fast tracks
5521 size_t fastTracks = 0;
5522 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
5523
5524 float masterVolume = mMasterVolume;
5525 bool masterMute = mMasterMute;
5526
5527 if (masterMute) {
5528 masterVolume = 0;
5529 }
5530 // Delegate master volume control to effect in output mix effect chain if needed
Andy Hung116bc262023-06-20 18:56:17 -07005531 sp<IAfEffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Eric Laurent81784c32012-11-19 14:55:58 -08005532 if (chain != 0) {
5533 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
Shunkai Yaof4847652024-01-12 00:25:20 +00005534 chain->setVolume(&v, &v);
Eric Laurent81784c32012-11-19 14:55:58 -08005535 masterVolume = (float)((v + (1 << 23)) >> 24);
5536 chain.clear();
5537 }
5538
5539 // prepare a new state to push
5540 FastMixerStateQueue *sq = NULL;
5541 FastMixerState *state = NULL;
5542 bool didModify = false;
5543 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Andy Hungf2285312017-02-14 18:31:59 -08005544 bool coldIdle = false;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005545 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005546 sq = mFastMixer->sq();
5547 state = sq->begin();
Andy Hungf2285312017-02-14 18:31:59 -08005548 coldIdle = state->mCommand == FastMixerState::COLD_IDLE;
Eric Laurent81784c32012-11-19 14:55:58 -08005549 }
5550
Andy Hung69aed5f2014-02-25 17:24:40 -08005551 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08005552 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08005553
Andy Hungbd3b2b02018-05-21 10:53:11 -07005554 // DeferredOperations handles statistics after setting mixerStatus.
5555 class DeferredOperations {
5556 public:
Andy Hungea840382020-05-05 21:50:17 -07005557 DeferredOperations(mixer_state *mixerStatus, ThreadMetrics *threadMetrics)
5558 : mMixerStatus(mixerStatus)
5559 , mThreadMetrics(threadMetrics) {}
Andy Hungbd3b2b02018-05-21 10:53:11 -07005560
5561 // when leaving scope, tally frames properly.
5562 ~DeferredOperations() {
5563 // Tally underrun frames only if we are actually mixing (MIXER_TRACKS_READY)
5564 // because that is when the underrun occurs.
5565 // We do not distinguish between FastTracks and NormalTracks here.
Andy Hungea840382020-05-05 21:50:17 -07005566 size_t maxUnderrunFrames = 0;
Andy Hungb68f5eb2019-12-03 16:49:17 -08005567 if (*mMixerStatus == MIXER_TRACKS_READY && mUnderrunFrames.size() > 0) {
Andy Hungbd3b2b02018-05-21 10:53:11 -07005568 for (const auto &underrun : mUnderrunFrames) {
Andy Hungc2b11cb2020-04-22 09:04:01 -07005569 underrun.first->tallyUnderrunFrames(underrun.second);
Andy Hungea840382020-05-05 21:50:17 -07005570 maxUnderrunFrames = max(underrun.second, maxUnderrunFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07005571 }
5572 }
Andy Hungea840382020-05-05 21:50:17 -07005573 // send the max underrun frames for this mixer period
5574 mThreadMetrics->logUnderrunFrames(maxUnderrunFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07005575 }
5576
5577 // tallyUnderrunFrames() is called to update the track counters
5578 // with the number of underrun frames for a particular mixer period.
5579 // We defer tallying until we know the final mixer status.
Andy Hung8d31fd22023-06-26 19:20:57 -07005580 void tallyUnderrunFrames(const sp<IAfTrack>& track, size_t underrunFrames) {
Andy Hungbd3b2b02018-05-21 10:53:11 -07005581 mUnderrunFrames.emplace_back(track, underrunFrames);
5582 }
5583
5584 private:
5585 const mixer_state * const mMixerStatus;
Andy Hungea840382020-05-05 21:50:17 -07005586 ThreadMetrics * const mThreadMetrics;
Andy Hung8d31fd22023-06-26 19:20:57 -07005587 std::vector<std::pair<sp<IAfTrack>, size_t>> mUnderrunFrames;
Andy Hungea840382020-05-05 21:50:17 -07005588 } deferredOperations(&mixerStatus, &mThreadMetrics);
Andy Hungb68f5eb2019-12-03 16:49:17 -08005589 // implicit nested scope for variable capture
Andy Hungbd3b2b02018-05-21 10:53:11 -07005590
jiabin245cdd92018-12-07 17:55:15 -08005591 bool noFastHapticTrack = true;
Eric Laurent81784c32012-11-19 14:55:58 -08005592 for (size_t i=0 ; i<count ; i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07005593 const sp<IAfTrack> t = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08005594
5595 // this const just means the local variable doesn't change
Andy Hung8d31fd22023-06-26 19:20:57 -07005596 IAfTrack* const track = t.get();
Eric Laurent81784c32012-11-19 14:55:58 -08005597
5598 // process fast tracks
5599 if (track->isFastTrack()) {
Andy Hungae22b482019-05-09 15:38:55 -07005600 LOG_ALWAYS_FATAL_IF(mFastMixer.get() == nullptr,
5601 "%s(%d): FastTrack(%d) present without FastMixer",
5602 __func__, id(), track->id());
5603
jiabin245cdd92018-12-07 17:55:15 -08005604 if (track->getHapticPlaybackEnabled()) {
5605 noFastHapticTrack = false;
5606 }
Eric Laurent81784c32012-11-19 14:55:58 -08005607
5608 // It's theoretically possible (though unlikely) for a fast track to be created
5609 // and then removed within the same normal mix cycle. This is not a problem, as
5610 // the track never becomes active so it's fast mixer slot is never touched.
5611 // The converse, of removing an (active) track and then creating a new track
5612 // at the identical fast mixer slot within the same normal mix cycle,
5613 // is impossible because the slot isn't marked available until the end of each cycle.
Andy Hung8d31fd22023-06-26 19:20:57 -07005614 int j = track->fastIndex();
Glenn Kastendc2c50b2016-04-21 08:13:14 -07005615 ALOG_ASSERT(0 < j && j < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08005616 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
5617 FastTrack *fastTrack = &state->mFastTracks[j];
5618
5619 // Determine whether the track is currently in underrun condition,
5620 // and whether it had a recent underrun.
5621 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
5622 FastTrackUnderruns underruns = ftDump->mUnderruns;
5623 uint32_t recentFull = (underruns.mBitFields.mFull -
Andy Hung8d31fd22023-06-26 19:20:57 -07005624 track->fastTrackUnderruns().mBitFields.mFull) & UNDERRUN_MASK;
Eric Laurent81784c32012-11-19 14:55:58 -08005625 uint32_t recentPartial = (underruns.mBitFields.mPartial -
Andy Hung8d31fd22023-06-26 19:20:57 -07005626 track->fastTrackUnderruns().mBitFields.mPartial) & UNDERRUN_MASK;
Eric Laurent81784c32012-11-19 14:55:58 -08005627 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
Andy Hung8d31fd22023-06-26 19:20:57 -07005628 track->fastTrackUnderruns().mBitFields.mEmpty) & UNDERRUN_MASK;
Eric Laurent81784c32012-11-19 14:55:58 -08005629 uint32_t recentUnderruns = recentPartial + recentEmpty;
Andy Hung8d31fd22023-06-26 19:20:57 -07005630 track->fastTrackUnderruns() = underruns;
Eric Laurent81784c32012-11-19 14:55:58 -08005631 // don't count underruns that occur while stopping or pausing
5632 // or stopped which can occur when flush() is called while active
Andy Hungbd3b2b02018-05-21 10:53:11 -07005633 size_t underrunFrames = 0;
Glenn Kasten82aaf942013-07-17 16:05:07 -07005634 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
5635 recentUnderruns > 0) {
5636 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
Andy Hungbd3b2b02018-05-21 10:53:11 -07005637 underrunFrames = recentUnderruns * mFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08005638 }
Andy Hungbd3b2b02018-05-21 10:53:11 -07005639 // Immediately account for FastTrack underruns.
Andy Hung8d31fd22023-06-26 19:20:57 -07005640 track->audioTrackServerProxy()->tallyUnderrunFrames(underrunFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08005641
5642 // This is similar to the state machine for normal tracks,
5643 // with a few modifications for fast tracks.
5644 bool isActive = true;
Andy Hung8d31fd22023-06-26 19:20:57 -07005645 switch (track->state()) {
5646 case IAfTrackBase::STOPPING_1:
Eric Laurent81784c32012-11-19 14:55:58 -08005647 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08005648 if (recentUnderruns > 0 || track->isTerminated()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07005649 track->setState(IAfTrackBase::STOPPING_2);
Eric Laurent81784c32012-11-19 14:55:58 -08005650 }
5651 break;
Andy Hung8d31fd22023-06-26 19:20:57 -07005652 case IAfTrackBase::PAUSING:
Eric Laurent81784c32012-11-19 14:55:58 -08005653 // ramp down is not yet implemented
5654 track->setPaused();
5655 break;
Andy Hung8d31fd22023-06-26 19:20:57 -07005656 case IAfTrackBase::RESUMING:
Eric Laurent81784c32012-11-19 14:55:58 -08005657 // ramp up is not yet implemented
Andy Hung8d31fd22023-06-26 19:20:57 -07005658 track->setState(IAfTrackBase::ACTIVE);
Eric Laurent81784c32012-11-19 14:55:58 -08005659 break;
Andy Hung8d31fd22023-06-26 19:20:57 -07005660 case IAfTrackBase::ACTIVE:
Eric Laurent81784c32012-11-19 14:55:58 -08005661 if (recentFull > 0 || recentPartial > 0) {
5662 // track has provided at least some frames recently: reset retry count
Andy Hung8d31fd22023-06-26 19:20:57 -07005663 track->retryCount() = kMaxTrackRetries;
Eric Laurent81784c32012-11-19 14:55:58 -08005664 }
5665 if (recentUnderruns == 0) {
5666 // no recent underruns: stay active
5667 break;
5668 }
5669 // there has recently been an underrun of some kind
5670 if (track->sharedBuffer() == 0) {
5671 // were any of the recent underruns "empty" (no frames available)?
5672 if (recentEmpty == 0) {
5673 // no, then ignore the partial underruns as they are allowed indefinitely
5674 break;
5675 }
5676 // there has recently been an "empty" underrun: decrement the retry counter
Andy Hung8d31fd22023-06-26 19:20:57 -07005677 if (--(track->retryCount()) > 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005678 break;
5679 }
5680 // indicate to client process that the track was disabled because of underrun;
5681 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08005682 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08005683 // remove from active list, but state remains ACTIVE [confusing but true]
5684 isActive = false;
5685 break;
5686 }
Chih-Hung Hsieh2b487032018-09-13 14:16:02 -07005687 FALLTHROUGH_INTENDED;
Andy Hung8d31fd22023-06-26 19:20:57 -07005688 case IAfTrackBase::STOPPING_2:
5689 case IAfTrackBase::PAUSED:
5690 case IAfTrackBase::STOPPED:
5691 case IAfTrackBase::FLUSHED: // flush() while active
Eric Laurent81784c32012-11-19 14:55:58 -08005692 // Check for presentation complete if track is inactive
5693 // We have consumed all the buffers of this track.
5694 // This would be incomplete if we auto-paused on underrun
5695 {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005696 uint32_t latency = 0;
5697 status_t result = mOutput->stream->getLatency(&latency);
5698 ALOGE_IF(result != OK,
5699 "Error when retrieving output stream latency: %d", result);
5700 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08005701 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005702 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
5703 // track stays in active list until presentation is complete
5704 break;
5705 }
5706 }
5707 if (track->isStopping_2()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07005708 track->setState(IAfTrackBase::STOPPED);
Eric Laurent81784c32012-11-19 14:55:58 -08005709 }
5710 if (track->isStopped()) {
5711 // Can't reset directly, as fast mixer is still polling this track
5712 // track->reset();
5713 // So instead mark this track as needing to be reset after push with ack
5714 resetMask |= 1 << i;
5715 }
5716 isActive = false;
5717 break;
Andy Hung8d31fd22023-06-26 19:20:57 -07005718 case IAfTrackBase::IDLE:
Eric Laurent81784c32012-11-19 14:55:58 -08005719 default:
Andy Hung8d31fd22023-06-26 19:20:57 -07005720 LOG_ALWAYS_FATAL("unexpected track state %d", (int)track->state());
Eric Laurent81784c32012-11-19 14:55:58 -08005721 }
5722
5723 if (isActive) {
5724 // was it previously inactive?
5725 if (!(state->mTrackMask & (1 << j))) {
Andy Hung8d31fd22023-06-26 19:20:57 -07005726 ExtendedAudioBufferProvider *eabp = track->asExtendedAudioBufferProvider();
5727 VolumeProvider *vp = track->asVolumeProvider();
Eric Laurent81784c32012-11-19 14:55:58 -08005728 fastTrack->mBufferProvider = eabp;
5729 fastTrack->mVolumeProvider = vp;
Andy Hung8d31fd22023-06-26 19:20:57 -07005730 fastTrack->mChannelMask = track->channelMask();
5731 fastTrack->mFormat = track->format();
jiabin245cdd92018-12-07 17:55:15 -08005732 fastTrack->mHapticPlaybackEnabled = track->getHapticPlaybackEnabled();
Ahmad Khalil229466a2024-02-05 12:15:30 +00005733 fastTrack->mHapticScale = track->getHapticScale();
Lais Andradebc3f37a2021-07-02 00:13:19 +01005734 fastTrack->mHapticMaxAmplitude = track->getHapticMaxAmplitude();
Eric Laurent81784c32012-11-19 14:55:58 -08005735 fastTrack->mGeneration++;
5736 state->mTrackMask |= 1 << j;
5737 didModify = true;
5738 // no acknowledgement required for newly active tracks
5739 }
Andy Hung8d31fd22023-06-26 19:20:57 -07005740 sp<AudioTrackServerProxy> proxy = track->audioTrackServerProxy();
Eric Laurenteab90452019-06-24 15:17:46 -07005741 float volume;
5742 if (track->isPlaybackRestricted() || mStreamTypes[track->streamType()].mute) {
5743 volume = 0.f;
5744 } else {
5745 volume = masterVolume * mStreamTypes[track->streamType()].volume;
5746 }
5747
5748 handleVoipVolume_l(&volume);
5749
Eric Laurent81784c32012-11-19 14:55:58 -08005750 // cache the combined master volume and stream type volume for fast mixer; this
5751 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005752 const float vh = track->getVolumeHandler()->getVolume(
Eric Laurenteab90452019-06-24 15:17:46 -07005753 proxy->framesReleased()).first;
5754 volume *= vh;
Andy Hung8d31fd22023-06-26 19:20:57 -07005755 track->setCachedVolume(volume);
Kevin Rocard12381092018-04-11 09:19:59 -07005756 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Vlad Popae2f5aef2022-07-25 16:00:20 +02005757 float vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
5758 float vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
5759
Andy Hung583043b2023-07-17 17:05:00 -07005760 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
Vlad Popae2f5aef2022-07-25 16:00:20 +02005761 /*muteState=*/{masterVolume == 0.f,
5762 mStreamTypes[track->streamType()].volume == 0.f,
5763 mStreamTypes[track->streamType()].mute,
5764 track->isPlaybackRestricted(),
Vlad Popa436c9172022-08-02 15:25:08 +02005765 vlf == 0.f && vrf == 0.f,
5766 vh == 0.f});
Vlad Popae2f5aef2022-07-25 16:00:20 +02005767
5768 vlf *= volume;
5769 vrf *= volume;
Eric Laurenteab90452019-06-24 15:17:46 -07005770
jiabin76d94692022-12-15 21:51:21 +00005771 track->setFinalVolume(vlf, vrf);
Eric Laurent81784c32012-11-19 14:55:58 -08005772 ++fastTracks;
5773 } else {
5774 // was it previously active?
5775 if (state->mTrackMask & (1 << j)) {
5776 fastTrack->mBufferProvider = NULL;
5777 fastTrack->mGeneration++;
5778 state->mTrackMask &= ~(1 << j);
5779 didModify = true;
5780 // If any fast tracks were removed, we must wait for acknowledgement
5781 // because we're about to decrement the last sp<> on those tracks.
5782 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
5783 } else {
Glenn Kastenbf848af2017-12-22 11:55:01 -08005784 // ALOGW rather than LOG_ALWAYS_FATAL because it seems there are cases where an
5785 // AudioTrack may start (which may not be with a start() but with a write()
5786 // after underrun) and immediately paused or released. In that case the
5787 // FastTrack state hasn't had time to update.
5788 // TODO Remove the ALOGW when this theory is confirmed.
5789 ALOGW("fast track %d should have been active; "
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08005790 "mState=%d, mTrackMask=%#x, recentUnderruns=%u, isShared=%d",
Andy Hung8d31fd22023-06-26 19:20:57 -07005791 j, (int)track->state(), state->mTrackMask, recentUnderruns,
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08005792 track->sharedBuffer() != 0);
Glenn Kastenbf848af2017-12-22 11:55:01 -08005793 // Since the FastMixer state already has the track inactive, do nothing here.
Eric Laurent81784c32012-11-19 14:55:58 -08005794 }
5795 tracksToRemove->add(track);
5796 // Avoids a misleading display in dumpsys
Andy Hung8d31fd22023-06-26 19:20:57 -07005797 track->fastTrackUnderruns().mBitFields.mMostRecent = UNDERRUN_FULL;
Eric Laurent81784c32012-11-19 14:55:58 -08005798 }
jiabin245cdd92018-12-07 17:55:15 -08005799 if (fastTrack->mHapticPlaybackEnabled != track->getHapticPlaybackEnabled()) {
5800 fastTrack->mHapticPlaybackEnabled = track->getHapticPlaybackEnabled();
5801 didModify = true;
5802 }
Eric Laurent81784c32012-11-19 14:55:58 -08005803 continue;
5804 }
5805
5806 { // local variable scope to avoid goto warning
5807
5808 audio_track_cblk_t* cblk = track->cblk();
5809
5810 // The first time a track is added we wait
5811 // for all its buffers to be filled before processing it
Andy Hungc0691382018-09-12 18:01:57 -07005812 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08005813
5814 // if an active track doesn't exist in the AudioMixer, create it.
Andy Hungc0691382018-09-12 18:01:57 -07005815 // use the trackId as the AudioMixer name.
5816 if (!mAudioMixer->exists(trackId)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08005817 status_t status = mAudioMixer->create(
Andy Hungc0691382018-09-12 18:01:57 -07005818 trackId,
Andy Hung8d31fd22023-06-26 19:20:57 -07005819 track->channelMask(),
5820 track->format(),
5821 track->sessionId());
Andy Hung1bc088a2018-02-09 15:57:31 -08005822 if (status != OK) {
Andy Hungc0691382018-09-12 18:01:57 -07005823 ALOGW("%s(): AudioMixer cannot create track(%d)"
5824 " mask %#x, format %#x, sessionId %d",
5825 __func__, trackId,
Andy Hung8d31fd22023-06-26 19:20:57 -07005826 track->channelMask(), track->format(), track->sessionId());
Andy Hung1bc088a2018-02-09 15:57:31 -08005827 tracksToRemove->add(track);
5828 track->invalidate(); // consider it dead.
5829 continue;
5830 }
5831 }
5832
Eric Laurent81784c32012-11-19 14:55:58 -08005833 // make sure that we have enough frames to mix one full buffer.
5834 // enforce this condition only once to enable draining the buffer in case the client
5835 // app does not call stop() and relies on underrun to stop:
5836 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
5837 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005838 size_t desiredFrames;
Andy Hung8d31fd22023-06-26 19:20:57 -07005839 const uint32_t sampleRate = track->audioTrackServerProxy()->getSampleRate();
5840 const AudioPlaybackRate playbackRate = track->audioTrackServerProxy()->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07005841
5842 desiredFrames = sourceFramesNeededWithTimestretch(
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07005843 sampleRate, mNormalFrameCount, mSampleRate, playbackRate.mSpeed);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005844 // TODO: ONLY USED FOR LEGACY RESAMPLERS, remove when they are removed.
5845 // add frames already consumed but not yet released by the resampler
5846 // because mAudioTrackServerProxy->framesReady() will include these frames
Andy Hungc0691382018-09-12 18:01:57 -07005847 desiredFrames += mAudioMixer->getUnreleasedFrames(trackId);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005848
Eric Laurent81784c32012-11-19 14:55:58 -08005849 uint32_t minFrames = 1;
5850 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
5851 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005852 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08005853 }
Eric Laurent13e4c962013-12-20 17:36:01 -08005854
5855 size_t framesReady = track->framesReady();
Glenn Kastene7754022014-10-31 12:11:26 -07005856 if (ATRACE_ENABLED()) {
5857 // I wish we had formatted trace names
Andy Hung1bc088a2018-02-09 15:57:31 -08005858 std::string traceName("nRdy");
Andy Hungc0691382018-09-12 18:01:57 -07005859 traceName += std::to_string(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08005860 ATRACE_INT(traceName.c_str(), framesReady);
Glenn Kastene7754022014-10-31 12:11:26 -07005861 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005862 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08005863 !track->isPaused() && !track->isTerminated())
5864 {
Andy Hungc0691382018-09-12 18:01:57 -07005865 ALOGVV("track(%d) s=%08x [OK] on thread %p", trackId, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08005866
5867 mixedTracks++;
5868
Shunkai Yaof4847652024-01-12 00:25:20 +00005869 // track->mainBuffer() != mSinkBuffer and mMixerBuffer means
Andy Hung69aed5f2014-02-25 17:24:40 -08005870 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08005871 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08005872 if (track->mainBuffer() != mSinkBuffer &&
5873 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08005874 if (mEffectBufferEnabled) {
5875 mEffectBufferValid = true; // Later can set directly.
5876 }
Eric Laurent81784c32012-11-19 14:55:58 -08005877 chain = getEffectChain_l(track->sessionId());
5878 // Delegate volume control to effect in track effect chain if needed
5879 if (chain != 0) {
5880 tracksWithEffect++;
5881 } else {
Andy Hungc0691382018-09-12 18:01:57 -07005882 ALOGW("prepareTracks_l(): track(%d) attached to effect but no chain found on "
Eric Laurent81784c32012-11-19 14:55:58 -08005883 "session %d",
Andy Hungc0691382018-09-12 18:01:57 -07005884 trackId, track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08005885 }
5886 }
5887
5888
5889 int param = AudioMixer::VOLUME;
Andy Hung8d31fd22023-06-26 19:20:57 -07005890 if (track->fillingStatus() == IAfTrack::FS_FILLED) {
Eric Laurent81784c32012-11-19 14:55:58 -08005891 // no ramp for the first volume setting
Andy Hung8d31fd22023-06-26 19:20:57 -07005892 track->fillingStatus() = IAfTrack::FS_ACTIVE;
5893 if (track->state() == IAfTrackBase::RESUMING) {
5894 track->setState(IAfTrackBase::ACTIVE);
Revathi Uddaraju453bcb52017-08-14 14:19:40 +08005895 // If a new track is paused immediately after start, do not ramp on resume.
5896 if (cblk->mServer != 0) {
5897 param = AudioMixer::RAMP_VOLUME;
5898 }
Eric Laurent81784c32012-11-19 14:55:58 -08005899 }
Andy Hungc0691382018-09-12 18:01:57 -07005900 mAudioMixer->setParameter(trackId, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Eric Laurent7c29ec92017-09-20 17:54:22 -07005901 mLeftVolFloat = -1.0;
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005902 // FIXME should not make a decision based on mServer
5903 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005904 // If the track is stopped before the first frame was mixed,
5905 // do not apply ramp
5906 param = AudioMixer::RAMP_VOLUME;
5907 }
5908
5909 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07005910 uint32_t vl, vr; // in U8.24 integer format
5911 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Eric Laurent7c29ec92017-09-20 17:54:22 -07005912 // read original volumes with volume control
Eric Laurenteab90452019-06-24 15:17:46 -07005913 float v = masterVolume * mStreamTypes[track->streamType()].volume;
Andy Hung333ab962019-05-28 20:23:35 -07005914 // Always fetch volumeshaper volume to ensure state is updated.
Andy Hung8d31fd22023-06-26 19:20:57 -07005915 const sp<AudioTrackServerProxy> proxy = track->audioTrackServerProxy();
Andy Hung333ab962019-05-28 20:23:35 -07005916 const float vh = track->getVolumeHandler()->getVolume(
Andy Hung8d31fd22023-06-26 19:20:57 -07005917 track->audioTrackServerProxy()->framesReleased()).first;
Eric Laurent7c29ec92017-09-20 17:54:22 -07005918
Eric Laurenteab90452019-06-24 15:17:46 -07005919 if (mStreamTypes[track->streamType()].mute || track->isPlaybackRestricted()) {
5920 v = 0;
5921 }
5922
5923 handleVoipVolume_l(&v);
5924
5925 if (track->isPausing()) {
Andy Hung6be49402014-05-30 10:42:03 -07005926 vl = vr = 0;
5927 vlf = vrf = vaf = 0.;
Eric Laurenteab90452019-06-24 15:17:46 -07005928 track->setPaused();
Eric Laurent81784c32012-11-19 14:55:58 -08005929 } else {
Glenn Kastenc56f3422014-03-21 17:53:17 -07005930 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07005931 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
5932 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08005933 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07005934 if (vlf > GAIN_FLOAT_UNITY) {
5935 ALOGV("Track left volume out of range: %.3g", vlf);
5936 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08005937 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07005938 if (vrf > GAIN_FLOAT_UNITY) {
5939 ALOGV("Track right volume out of range: %.3g", vrf);
5940 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08005941 }
Vlad Popae2f5aef2022-07-25 16:00:20 +02005942
Andy Hung583043b2023-07-17 17:05:00 -07005943 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
Vlad Popae2f5aef2022-07-25 16:00:20 +02005944 /*muteState=*/{masterVolume == 0.f,
5945 mStreamTypes[track->streamType()].volume == 0.f,
5946 mStreamTypes[track->streamType()].mute,
5947 track->isPlaybackRestricted(),
Vlad Popa436c9172022-08-02 15:25:08 +02005948 vlf == 0.f && vrf == 0.f,
5949 vh == 0.f});
Vlad Popae2f5aef2022-07-25 16:00:20 +02005950
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005951 // now apply the master volume and stream type volume and shaper volume
5952 vlf *= v * vh;
5953 vrf *= v * vh;
Eric Laurent81784c32012-11-19 14:55:58 -08005954 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07005955 // then derive vl and vr as U8.24 versions for the effect chain
5956 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
5957 vl = (uint32_t) (scaleto8_24 * vlf);
5958 vr = (uint32_t) (scaleto8_24 * vrf);
5959 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08005960 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08005961 // send level comes from shared memory and so may be corrupt
5962 if (sendLevel > MAX_GAIN_INT) {
5963 ALOGV("Track send level out of range: %04X", sendLevel);
5964 sendLevel = MAX_GAIN_INT;
5965 }
Andy Hung6be49402014-05-30 10:42:03 -07005966 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
5967 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08005968 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005969
jiabin76d94692022-12-15 21:51:21 +00005970 track->setFinalVolume(vrf, vlf);
Kevin Rocard12381092018-04-11 09:19:59 -07005971
Eric Laurent81784c32012-11-19 14:55:58 -08005972 // Delegate volume control to effect in track effect chain if needed
Shunkai Yaof4847652024-01-12 00:25:20 +00005973 if (chain != 0 && chain->setVolume(&vl, &vr)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005974 // Do not ramp volume if volume is controlled by effect
5975 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08005976 // Update remaining floating point volume levels
5977 vlf = (float)vl / (1 << 24);
5978 vrf = (float)vr / (1 << 24);
Andy Hung8d31fd22023-06-26 19:20:57 -07005979 track->setHasVolumeController(true);
Eric Laurent81784c32012-11-19 14:55:58 -08005980 } else {
5981 // force no volume ramp when volume controller was just disabled or removed
5982 // from effect chain to avoid volume spike
Andy Hung8d31fd22023-06-26 19:20:57 -07005983 if (track->hasVolumeController()) {
Eric Laurent81784c32012-11-19 14:55:58 -08005984 param = AudioMixer::VOLUME;
5985 }
Andy Hung8d31fd22023-06-26 19:20:57 -07005986 track->setHasVolumeController(false);
Eric Laurent81784c32012-11-19 14:55:58 -08005987 }
5988
Eric Laurent81784c32012-11-19 14:55:58 -08005989 // XXX: these things DON'T need to be done each time
Andy Hung8d31fd22023-06-26 19:20:57 -07005990 mAudioMixer->setBufferProvider(trackId, track->asExtendedAudioBufferProvider());
Andy Hungc0691382018-09-12 18:01:57 -07005991 mAudioMixer->enable(trackId);
Eric Laurent81784c32012-11-19 14:55:58 -08005992
Andy Hungc0691382018-09-12 18:01:57 -07005993 mAudioMixer->setParameter(trackId, param, AudioMixer::VOLUME0, &vlf);
5994 mAudioMixer->setParameter(trackId, param, AudioMixer::VOLUME1, &vrf);
5995 mAudioMixer->setParameter(trackId, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08005996 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005997 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005998 AudioMixer::TRACK,
5999 AudioMixer::FORMAT, (void *)track->format());
6000 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07006001 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08006002 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00006003 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Eric Laurent39095982021-08-24 18:29:27 +02006004
Eric Laurentb0a7bc92022-04-05 15:06:08 +02006005 if (mType == SPATIALIZER && !track->isSpatialized()) {
Eric Laurent39095982021-08-24 18:29:27 +02006006 mAudioMixer->setParameter(
6007 trackId,
6008 AudioMixer::TRACK,
6009 AudioMixer::MIXER_CHANNEL_MASK,
6010 (void *)(uintptr_t)(mChannelMask | mHapticChannelMask));
6011 } else {
6012 mAudioMixer->setParameter(
6013 trackId,
6014 AudioMixer::TRACK,
6015 AudioMixer::MIXER_CHANNEL_MASK,
6016 (void *)(uintptr_t)(mMixerChannelMask | mHapticChannelMask));
6017 }
6018
Glenn Kastene3aa6592012-12-04 12:22:46 -08006019 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07006020 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Andy Hung333ab962019-05-28 20:23:35 -07006021 uint32_t reqSampleRate = proxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08006022 if (reqSampleRate == 0) {
6023 reqSampleRate = mSampleRate;
6024 } else if (reqSampleRate > maxSampleRate) {
6025 reqSampleRate = maxSampleRate;
6026 }
Eric Laurent81784c32012-11-19 14:55:58 -08006027 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07006028 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08006029 AudioMixer::RESAMPLE,
6030 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00006031 (void *)(uintptr_t)reqSampleRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07006032
Andy Hung8edb8dc2015-03-26 19:13:55 -07006033 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07006034 trackId,
Andy Hung8edb8dc2015-03-26 19:13:55 -07006035 AudioMixer::TIMESTRETCH,
6036 AudioMixer::PLAYBACK_RATE,
Andy Hung920f6572022-10-06 12:09:49 -07006037 // cast away constness for this generic API.
6038 const_cast<void *>(reinterpret_cast<const void *>(&playbackRate)));
Andy Hung8edb8dc2015-03-26 19:13:55 -07006039
Andy Hung69aed5f2014-02-25 17:24:40 -08006040 /*
6041 * Select the appropriate output buffer for the track.
6042 *
Andy Hung98ef9782014-03-04 14:46:50 -08006043 * Tracks with effects go into their own effects chain buffer
6044 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08006045 *
6046 * Other tracks can use mMixerBuffer for higher precision
6047 * channel accumulation. If this buffer is enabled
6048 * (mMixerBufferEnabled true), then selected tracks will accumulate
6049 * into it.
6050 *
6051 */
6052 if (mMixerBufferEnabled
6053 && (track->mainBuffer() == mSinkBuffer
6054 || track->mainBuffer() == mMixerBuffer)) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02006055 if (mType == SPATIALIZER && !track->isSpatialized()) {
Eric Laurent39095982021-08-24 18:29:27 +02006056 mAudioMixer->setParameter(
6057 trackId,
6058 AudioMixer::TRACK,
Eric Laurentb62d0362021-10-26 17:40:18 +02006059 AudioMixer::MIXER_FORMAT, (void *)mEffectBufferFormat);
Eric Laurent39095982021-08-24 18:29:27 +02006060 mAudioMixer->setParameter(
6061 trackId,
6062 AudioMixer::TRACK,
Eric Laurentb62d0362021-10-26 17:40:18 +02006063 AudioMixer::MAIN_BUFFER, (void *)mPostSpatializerBuffer);
Eric Laurent39095982021-08-24 18:29:27 +02006064 } else {
6065 mAudioMixer->setParameter(
6066 trackId,
6067 AudioMixer::TRACK,
6068 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
6069 mAudioMixer->setParameter(
6070 trackId,
6071 AudioMixer::TRACK,
6072 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
6073 // TODO: override track->mainBuffer()?
6074 mMixerBufferValid = true;
6075 }
Andy Hung69aed5f2014-02-25 17:24:40 -08006076 } else {
6077 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07006078 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08006079 AudioMixer::TRACK,
Andy Hung319587b2023-05-23 14:01:03 -07006080 AudioMixer::MIXER_FORMAT, (void *)AUDIO_FORMAT_PCM_FLOAT);
Andy Hung69aed5f2014-02-25 17:24:40 -08006081 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07006082 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08006083 AudioMixer::TRACK,
6084 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
6085 }
Eric Laurent81784c32012-11-19 14:55:58 -08006086 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07006087 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08006088 AudioMixer::TRACK,
6089 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
jiabin245cdd92018-12-07 17:55:15 -08006090 mAudioMixer->setParameter(
6091 trackId,
6092 AudioMixer::TRACK,
6093 AudioMixer::HAPTIC_ENABLED, (void *)(uintptr_t)track->getHapticPlaybackEnabled());
Ahmad Khalil229466a2024-02-05 12:15:30 +00006094 const os::HapticScale hapticScale = track->getHapticScale();
jiabin77270b82018-12-18 15:41:29 -08006095 mAudioMixer->setParameter(
Ahmad Khalil229466a2024-02-05 12:15:30 +00006096 trackId,
6097 AudioMixer::TRACK,
6098 AudioMixer::HAPTIC_SCALE, (void *)&hapticScale);
Andy Hung8d31fd22023-06-26 19:20:57 -07006099 const float hapticMaxAmplitude = track->getHapticMaxAmplitude();
Lais Andradebc3f37a2021-07-02 00:13:19 +01006100 mAudioMixer->setParameter(
6101 trackId,
6102 AudioMixer::TRACK,
Andy Hung8d31fd22023-06-26 19:20:57 -07006103 AudioMixer::HAPTIC_MAX_AMPLITUDE, (void *)&hapticMaxAmplitude);
Eric Laurent81784c32012-11-19 14:55:58 -08006104
6105 // reset retry count
Andy Hung8d31fd22023-06-26 19:20:57 -07006106 track->retryCount() = kMaxTrackRetries;
Eric Laurent81784c32012-11-19 14:55:58 -08006107
6108 // If one track is ready, set the mixer ready if:
6109 // - the mixer was not ready during previous round OR
6110 // - no other track is not ready
6111 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
6112 mixerStatus != MIXER_TRACKS_ENABLED) {
6113 mixerStatus = MIXER_TRACKS_READY;
6114 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08006115
6116 // Enable the next few lines to instrument a test for underrun log handling.
6117 // TODO: Remove when we have a better way of testing the underrun log.
6118#if 0
6119 static int i;
6120 if ((++i & 0xf) == 0) {
6121 deferredOperations.tallyUnderrunFrames(track, 10 /* underrunFrames */);
6122 }
6123#endif
Eric Laurent81784c32012-11-19 14:55:58 -08006124 } else {
Andy Hungbd3b2b02018-05-21 10:53:11 -07006125 size_t underrunFrames = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08006126 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Andy Hungb68f5eb2019-12-03 16:49:17 -08006127 ALOGV("track(%d) underrun, track state %s framesReady(%zu) < framesDesired(%zd)",
6128 trackId, track->getTrackStateAsString(), framesReady, desiredFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07006129 underrunFrames = desiredFrames;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08006130 }
Andy Hungbd3b2b02018-05-21 10:53:11 -07006131 deferredOperations.tallyUnderrunFrames(track, underrunFrames);
Phil Burk2812d9e2016-01-04 10:34:30 -08006132
Eric Laurent81784c32012-11-19 14:55:58 -08006133 // clear effect chain input buffer if an active track underruns to avoid sending
6134 // previous audio buffer again to effects
6135 chain = getEffectChain_l(track->sessionId());
6136 if (chain != 0) {
6137 chain->clearInputBuffer();
6138 }
6139
Andy Hungc0691382018-09-12 18:01:57 -07006140 ALOGVV("track(%d) s=%08x [NOT READY] on thread %p", trackId, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08006141 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
6142 track->isStopped() || track->isPaused()) {
6143 // We have consumed all the buffers of this track.
6144 // Remove it from the list of active tracks.
6145 // TODO: use actual buffer filling status instead of latency when available from
6146 // audio HAL
6147 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08006148 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08006149 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
6150 if (track->isStopped()) {
6151 track->reset();
6152 }
6153 tracksToRemove->add(track);
6154 }
6155 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08006156 // No buffers for this track. Give it a few chances to
6157 // fill a buffer, then remove it from active list.
Andy Hung8d31fd22023-06-26 19:20:57 -07006158 if (--(track->retryCount()) <= 0) {
Eric Laurent46b6b5d2024-04-12 17:02:51 +00006159 ALOGI("%s BUFFER TIMEOUT: remove track(%d) from active list due to underrun"
6160 " on thread %d", __func__, trackId, mId);
Eric Laurent81784c32012-11-19 14:55:58 -08006161 tracksToRemove->add(track);
6162 // indicate to client process that the track was disabled because of underrun;
6163 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08006164 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08006165 // If one track is not ready, mark the mixer also not ready if:
6166 // - the mixer was ready during previous round OR
6167 // - no other track is ready
6168 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
6169 mixerStatus != MIXER_TRACKS_READY) {
6170 mixerStatus = MIXER_TRACKS_ENABLED;
6171 }
6172 }
Andy Hungc0691382018-09-12 18:01:57 -07006173 mAudioMixer->disable(trackId);
Eric Laurent81784c32012-11-19 14:55:58 -08006174 }
6175
6176 } // local variable scope to avoid goto warning
Eric Laurent81784c32012-11-19 14:55:58 -08006177
6178 }
6179
jiabin245cdd92018-12-07 17:55:15 -08006180 if (mHapticChannelMask != AUDIO_CHANNEL_NONE && sq != NULL) {
6181 // When there is no fast track playing haptic and FastMixer exists,
6182 // enabling the first FastTrack, which provides mixed data from normal
6183 // tracks, to play haptic data.
6184 FastTrack *fastTrack = &state->mFastTracks[0];
6185 if (fastTrack->mHapticPlaybackEnabled != noFastHapticTrack) {
6186 fastTrack->mHapticPlaybackEnabled = noFastHapticTrack;
6187 didModify = true;
6188 }
6189 }
6190
Eric Laurent81784c32012-11-19 14:55:58 -08006191 // Push the new FastMixer state if necessary
Jing Mike537412f2023-03-12 11:01:47 +08006192 [[maybe_unused]] bool pauseAudioWatchdog = false;
Eric Laurent81784c32012-11-19 14:55:58 -08006193 if (didModify) {
6194 state->mFastTracksGen++;
6195 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
6196 if (kUseFastMixer == FastMixer_Dynamic &&
6197 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
6198 state->mCommand = FastMixerState::COLD_IDLE;
6199 state->mColdFutexAddr = &mFastMixerFutex;
6200 state->mColdGen++;
6201 mFastMixerFutex = 0;
6202 if (kUseFastMixer == FastMixer_Dynamic) {
6203 mNormalSink = mOutputSink;
6204 }
6205 // If we go into cold idle, need to wait for acknowledgement
6206 // so that fast mixer stops doing I/O.
6207 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
6208 pauseAudioWatchdog = true;
6209 }
Eric Laurent81784c32012-11-19 14:55:58 -08006210 }
6211 if (sq != NULL) {
6212 sq->end(didModify);
Andy Hungf2285312017-02-14 18:31:59 -08006213 // No need to block if the FastMixer is in COLD_IDLE as the FastThread
6214 // is not active. (We BLOCK_UNTIL_ACKED when entering COLD_IDLE
6215 // when bringing the output sink into standby.)
6216 //
6217 // We will get the latest FastMixer state when we come out of COLD_IDLE.
6218 //
6219 // This occurs with BT suspend when we idle the FastMixer with
6220 // active tracks, which may be added or removed.
6221 sq->push(coldIdle ? FastMixerStateQueue::BLOCK_NEVER : block);
Eric Laurent81784c32012-11-19 14:55:58 -08006222 }
6223#ifdef AUDIO_WATCHDOG
6224 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
6225 mAudioWatchdog->pause();
6226 }
6227#endif
6228
6229 // Now perform the deferred reset on fast tracks that have stopped
6230 while (resetMask != 0) {
6231 size_t i = __builtin_ctz(resetMask);
6232 ALOG_ASSERT(i < count);
6233 resetMask &= ~(1 << i);
Andy Hung8d31fd22023-06-26 19:20:57 -07006234 sp<IAfTrack> track = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08006235 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
6236 track->reset();
6237 }
6238
Andy Hung80d03d22018-04-10 10:32:11 -07006239 // Track destruction may occur outside of threadLoop once it is removed from active tracks.
6240 // Ensure the AudioMixer doesn't have a raw "buffer provider" pointer to the track if
6241 // it ceases to be active, to allow safe removal from the AudioMixer at the start
6242 // of prepareTracks_l(); this releases any outstanding buffer back to the track.
6243 // See also the implementation of destroyTrack_l().
6244 for (const auto &track : *tracksToRemove) {
Andy Hungc0691382018-09-12 18:01:57 -07006245 const int trackId = track->id();
6246 if (mAudioMixer->exists(trackId)) { // Normal tracks here, fast tracks in FastMixer.
6247 mAudioMixer->setBufferProvider(trackId, nullptr /* bufferProvider */);
Andy Hung80d03d22018-04-10 10:32:11 -07006248 }
6249 }
6250
Eric Laurent81784c32012-11-19 14:55:58 -08006251 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08006252 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08006253
Eric Laurentb3f315a2021-07-13 15:09:05 +02006254 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0 ||
6255 getEffectChain_l(AUDIO_SESSION_OUTPUT_STAGE) != 0) {
Eric Laurent97d547d2014-09-02 14:45:53 -07006256 mEffectBufferValid = true;
Marco Nelissenac302142014-10-20 13:15:38 -07006257 }
6258
6259 if (mEffectBufferValid) {
Marco Nelissen57088b52014-10-17 16:39:39 -07006260 // as long as there are effects we should clear the effects buffer, to avoid
6261 // passing a non-clean buffer to the effect chain
6262 memset(mEffectBuffer, 0, mEffectBufferSize);
Eric Laurentb62d0362021-10-26 17:40:18 +02006263 if (mType == SPATIALIZER) {
6264 memset(mPostSpatializerBuffer, 0, mPostSpatializerBufferSize);
6265 }
Eric Laurent97d547d2014-09-02 14:45:53 -07006266 }
Andy Hung69aed5f2014-02-25 17:24:40 -08006267 // sink or mix buffer must be cleared if all tracks are connected to an
6268 // effect chain as in this case the mixer will not write to the sink or mix buffer
6269 // and track effects will accumulate into it
Eric Laurent39095982021-08-24 18:29:27 +02006270 // always clear sink buffer for spatializer output as the output of the spatializer
6271 // effect will be accumulated into it
6272 if ((mBytesRemaining == 0) && (((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
6273 (mixedTracks == 0 && fastTracks > 0)) || (mType == SPATIALIZER))) {
Eric Laurent81784c32012-11-19 14:55:58 -08006274 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08006275 if (mMixerBufferValid) {
6276 memset(mMixerBuffer, 0, mMixerBufferSize);
6277 // TODO: In testing, mSinkBuffer below need not be cleared because
6278 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
6279 // after mixing.
6280 //
6281 // To enforce this guarantee:
6282 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
6283 // (mixedTracks == 0 && fastTracks > 0))
6284 // must imply MIXER_TRACKS_READY.
6285 // Later, we may clear buffers regardless, and skip much of this logic.
6286 }
Andy Hung98ef9782014-03-04 14:46:50 -08006287 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07006288 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08006289 }
6290
6291 // if any fast tracks, then status is ready
6292 mMixerStatusIgnoringFastTracks = mixerStatus;
6293 if (fastTracks > 0) {
6294 mixerStatus = MIXER_TRACKS_READY;
6295 }
6296 return mixerStatus;
6297}
6298
Andy Hungc5007f82023-08-29 14:26:09 -07006299// trackCountForUid_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07006300uint32_t PlaybackThread::trackCountForUid_l(uid_t uid) const
Eric Laurentad7dd962016-09-22 12:38:37 -07006301{
6302 uint32_t trackCount = 0;
6303 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hung1f12a8a2016-11-07 16:10:30 -08006304 if (mTracks[i]->uid() == uid) {
Eric Laurentad7dd962016-09-22 12:38:37 -07006305 trackCount++;
6306 }
6307 }
6308 return trackCount;
6309}
6310
Andy Hungee58e4a2023-07-07 13:47:37 -07006311bool PlaybackThread::IsTimestampAdvancing::check(AudioStreamOut* output)
ziyangch8f194f12021-12-01 13:48:04 -08006312{
Brian Lindahl65e90012022-07-27 18:01:07 +02006313 // Check the timestamp to see if it's advancing once every 150ms. If we check too frequently, we
6314 // could falsely detect that the frame position has stalled due to underrun because we haven't
6315 // given the Audio HAL enough time to update.
6316 const nsecs_t nowNs = systemTime();
6317 if (nowNs - mPreviousNs < mMinimumTimeBetweenChecksNs) {
6318 return mLatchedValue;
6319 }
6320 mPreviousNs = nowNs;
6321 mLatchedValue = false;
6322 // Determine if the presentation position is still advancing.
ziyangch8f194f12021-12-01 13:48:04 -08006323 uint64_t position = 0;
6324 struct timespec unused;
Brian Lindahl65e90012022-07-27 18:01:07 +02006325 const status_t ret = output->getPresentationPosition(&position, &unused);
ziyangch8f194f12021-12-01 13:48:04 -08006326 if (ret == NO_ERROR) {
Brian Lindahl65e90012022-07-27 18:01:07 +02006327 if (position != mPreviousPosition) {
6328 mPreviousPosition = position;
6329 mLatchedValue = true;
ziyangch8f194f12021-12-01 13:48:04 -08006330 }
6331 }
Brian Lindahl65e90012022-07-27 18:01:07 +02006332 return mLatchedValue;
6333}
6334
Andy Hungee58e4a2023-07-07 13:47:37 -07006335void PlaybackThread::IsTimestampAdvancing::clear()
Brian Lindahl65e90012022-07-27 18:01:07 +02006336{
6337 mLatchedValue = true;
6338 mPreviousPosition = 0;
6339 mPreviousNs = 0;
ziyangch8f194f12021-12-01 13:48:04 -08006340}
6341
Andy Hungc5007f82023-08-29 14:26:09 -07006342// isTrackAllowed_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07006343bool MixerThread::isTrackAllowed_l(
Andy Hung1bc088a2018-02-09 15:57:31 -08006344 audio_channel_mask_t channelMask, audio_format_t format,
6345 audio_session_t sessionId, uid_t uid) const
Eric Laurent81784c32012-11-19 14:55:58 -08006346{
Andy Hung1bc088a2018-02-09 15:57:31 -08006347 if (!PlaybackThread::isTrackAllowed_l(channelMask, format, sessionId, uid)) {
6348 return false;
Eric Laurentad7dd962016-09-22 12:38:37 -07006349 }
Andy Hung1bc088a2018-02-09 15:57:31 -08006350 // Check validity as we don't call AudioMixer::create() here.
Mikhail Naganov7ad7a252019-07-30 14:42:32 -07006351 if (!mAudioMixer->isValidFormat(format)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08006352 ALOGW("%s: invalid format: %#x", __func__, format);
6353 return false;
6354 }
Mikhail Naganov7ad7a252019-07-30 14:42:32 -07006355 if (!mAudioMixer->isValidChannelMask(channelMask)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08006356 ALOGW("%s: invalid channelMask: %#x", __func__, channelMask);
6357 return false;
6358 }
6359 return true;
Eric Laurent81784c32012-11-19 14:55:58 -08006360}
6361
Andy Hungc5007f82023-08-29 14:26:09 -07006362// checkForNewParameter_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07006363bool MixerThread::checkForNewParameter_l(const String8& keyValuePair,
Eric Laurent10351942014-05-08 18:49:52 -07006364 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08006365{
Eric Laurent81784c32012-11-19 14:55:58 -08006366 bool reconfig = false;
Eric Laurent10351942014-05-08 18:49:52 -07006367 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006368
Glenn Kastenc05b8d72016-03-24 09:48:17 -07006369 AutoPark<FastMixer> park(mFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08006370
Eric Laurent10351942014-05-08 18:49:52 -07006371 AudioParameter param = AudioParameter(keyValuePair);
6372 int value;
6373 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
6374 reconfig = true;
6375 }
6376 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung81994d62023-07-20 21:44:14 -07006377 if (!isValidPcmSinkFormat(static_cast<audio_format_t>(value))) {
Eric Laurent10351942014-05-08 18:49:52 -07006378 status = BAD_VALUE;
6379 } else {
6380 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08006381 reconfig = true;
6382 }
Eric Laurent10351942014-05-08 18:49:52 -07006383 }
6384 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hung81994d62023-07-20 21:44:14 -07006385 if (!isValidPcmSinkChannelMask(static_cast<audio_channel_mask_t>(value))) {
Eric Laurent10351942014-05-08 18:49:52 -07006386 status = BAD_VALUE;
6387 } else {
6388 // no need to save value, since it's constant
6389 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006390 }
Eric Laurent10351942014-05-08 18:49:52 -07006391 }
6392 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6393 // do not accept frame count changes if tracks are open as the track buffer
6394 // size depends on frame count and correct behavior would not be guaranteed
6395 // if frame count is changed after track creation
6396 if (!mTracks.isEmpty()) {
6397 status = INVALID_OPERATION;
6398 } else {
6399 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006400 }
Eric Laurent10351942014-05-08 18:49:52 -07006401 }
6402 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07006403 LOG_FATAL("Should not set routing device in MixerThread");
Eric Laurent10351942014-05-08 18:49:52 -07006404 }
Eric Laurent81784c32012-11-19 14:55:58 -08006405
Eric Laurent10351942014-05-08 18:49:52 -07006406 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006407 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07006408 if (!mStandby && status == INVALID_OPERATION) {
Andy Hungdda7aed2023-03-27 15:53:06 -07006409 ALOGW("%s: setParameters failed with keyValuePair %s, entering standby",
6410 __func__, keyValuePair.c_str());
Phil Burk062e67a2015-02-11 13:40:50 -08006411 mOutput->standby();
Andy Hungdda7aed2023-03-27 15:53:06 -07006412 mThreadMetrics.logEndInterval();
6413 mThreadSnapshot.onEnd();
6414 setStandby_l();
Eric Laurent10351942014-05-08 18:49:52 -07006415 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006416 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent81784c32012-11-19 14:55:58 -08006417 }
Eric Laurent10351942014-05-08 18:49:52 -07006418 if (status == NO_ERROR && reconfig) {
6419 readOutputParameters_l();
6420 delete mAudioMixer;
6421 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
Andy Hung1bc088a2018-02-09 15:57:31 -08006422 for (const auto &track : mTracks) {
Andy Hungc0691382018-09-12 18:01:57 -07006423 const int trackId = track->id();
Andy Hung920f6572022-10-06 12:09:49 -07006424 const status_t createStatus = mAudioMixer->create(
Andy Hungc0691382018-09-12 18:01:57 -07006425 trackId,
Andy Hung8d31fd22023-06-26 19:20:57 -07006426 track->channelMask(),
6427 track->format(),
6428 track->sessionId());
Andy Hung920f6572022-10-06 12:09:49 -07006429 ALOGW_IF(createStatus != NO_ERROR,
Andy Hungc0691382018-09-12 18:01:57 -07006430 "%s(): AudioMixer cannot create track(%d)"
6431 " mask %#x, format %#x, sessionId %d",
Andy Hung1bc088a2018-02-09 15:57:31 -08006432 __func__,
Andy Hung8d31fd22023-06-26 19:20:57 -07006433 trackId, track->channelMask(), track->format(), track->sessionId());
Eric Laurent10351942014-05-08 18:49:52 -07006434 }
Eric Laurent73e26b62015-04-27 16:55:58 -07006435 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07006436 }
Eric Laurent81784c32012-11-19 14:55:58 -08006437 }
6438
Dean Wheatley68918102021-03-19 22:09:19 +11006439 return reconfig;
Eric Laurent81784c32012-11-19 14:55:58 -08006440}
6441
6442
Andy Hungee58e4a2023-07-07 13:47:37 -07006443void MixerThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -08006444{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07006445 PlaybackThread::dumpInternals_l(fd, args);
Andy Hung8d672e02023-09-15 18:19:28 -07006446 dprintf(fd, " Thread throttle time (msecs): %u\n", (uint32_t)mThreadThrottleTimeMs);
Andy Hung8ed196a2018-01-05 13:21:11 -08006447 dprintf(fd, " AudioMixer tracks: %s\n", mAudioMixer->trackNames().c_str());
Andy Hung2ddee192015-12-18 17:34:44 -08006448 dprintf(fd, " Master mono: %s\n", mMasterMono ? "on" : "off");
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006449 dprintf(fd, " Master balance: %f (%s)\n", mMasterBalance.load(),
6450 (hasFastMixer() ? std::to_string(mFastMixer->getMasterBalance())
6451 : mBalance.toString()).c_str());
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006452 if (hasFastMixer()) {
6453 dprintf(fd, " FastMixer thread %p tid=%d", mFastMixer.get(), mFastMixer->getTid());
6454
6455 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
6456 // while we are dumping it. It may be inconsistent, but it won't mutate!
6457 // This is a large object so we place it on the heap.
6458 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
Eric Tan2942a4e2018-09-12 17:41:27 -07006459 const std::unique_ptr<FastMixerDumpState> copy =
6460 std::make_unique<FastMixerDumpState>(mFastMixerDumpState);
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006461 copy->dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08006462
6463#ifdef STATE_QUEUE_DUMP
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006464 // Similar for state queue
6465 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
6466 observerCopy.dump(fd);
6467 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
6468 mutatorCopy.dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08006469#endif
6470
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006471#ifdef AUDIO_WATCHDOG
6472 if (mAudioWatchdog != 0) {
6473 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
6474 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
6475 wdCopy.dump(fd);
6476 }
6477#endif
6478
6479 } else {
6480 dprintf(fd, " No FastMixer\n");
6481 }
Eric Laurent90cea102023-05-15 15:08:27 +02006482
6483 dprintf(fd, "Bluetooth latency modes are %senabled\n",
6484 mBluetoothLatencyModesEnabled ? "" : "not ");
6485 dprintf(fd, "HAL does %ssupport Bluetooth latency modes\n", mOutput != nullptr &&
6486 mOutput->audioHwDev->supportsBluetoothVariableLatency() ? "" : "not ");
6487 dprintf(fd, "Supported latency modes: %s\n", toString(mSupportedLatencyModes).c_str());
Eric Laurent81784c32012-11-19 14:55:58 -08006488}
6489
Andy Hungee58e4a2023-07-07 13:47:37 -07006490uint32_t MixerThread::idleSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08006491{
6492 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
6493}
6494
Andy Hungee58e4a2023-07-07 13:47:37 -07006495uint32_t MixerThread::suspendSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08006496{
6497 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
6498}
6499
Andy Hungee58e4a2023-07-07 13:47:37 -07006500void MixerThread::cacheParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08006501{
6502 PlaybackThread::cacheParameters_l();
6503
6504 // FIXME: Relaxed timing because of a certain device that can't meet latency
6505 // Should be reduced to 2x after the vendor fixes the driver issue
6506 // increase threshold again due to low power audio mode. The way this warning
6507 // threshold is calculated and its usefulness should be reconsidered anyway.
6508 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
6509}
6510
Andy Hungee58e4a2023-07-07 13:47:37 -07006511void MixerThread::onHalLatencyModesChanged_l() {
Andy Hung583043b2023-07-17 17:05:00 -07006512 mAfThreadCallback->onSupportedLatencyModesChanged(mId, mSupportedLatencyModes);
Eric Laurentb0463942022-12-20 16:31:10 +01006513}
6514
Andy Hungee58e4a2023-07-07 13:47:37 -07006515void MixerThread::setHalLatencyMode_l() {
Eric Laurentb0463942022-12-20 16:31:10 +01006516 // Only handle latency mode if:
6517 // - mBluetoothLatencyModesEnabled is true
6518 // - the HAL supports latency modes
6519 // - the selected device is Bluetooth LE or A2DP
6520 if (!mBluetoothLatencyModesEnabled.load() || mSupportedLatencyModes.empty()) {
6521 return;
6522 }
6523 if (mOutDeviceTypeAddrs.size() != 1
6524 || !(audio_is_a2dp_out_device(mOutDeviceTypeAddrs[0].mType)
6525 || audio_is_ble_out_device(mOutDeviceTypeAddrs[0].mType))) {
6526 return;
6527 }
6528
6529 audio_latency_mode_t latencyMode = AUDIO_LATENCY_MODE_FREE;
6530 if (mSupportedLatencyModes.size() == 1) {
6531 // If the HAL only support one latency mode currently, confirm the choice
6532 latencyMode = mSupportedLatencyModes[0];
6533 } else if (mSupportedLatencyModes.size() > 1) {
6534 // Request low latency if:
6535 // - At least one active track is either:
6536 // - a fast track with gaming usage or
6537 // - a track with acessibility usage
6538 for (const auto& track : mActiveTracks) {
6539 if ((track->isFastTrack() && track->attributes().usage == AUDIO_USAGE_GAME)
6540 || track->attributes().usage == AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY) {
6541 latencyMode = AUDIO_LATENCY_MODE_LOW;
6542 break;
6543 }
6544 }
6545 }
6546
6547 if (latencyMode != mSetLatencyMode) {
6548 status_t status = mOutput->stream->setLatencyMode(latencyMode);
6549 ALOGD("%s: thread(%d) setLatencyMode(%s) returned %d",
6550 __func__, mId, toString(latencyMode).c_str(), status);
6551 if (status == NO_ERROR) {
6552 mSetLatencyMode = latencyMode;
6553 }
6554 }
6555}
6556
Andy Hungee58e4a2023-07-07 13:47:37 -07006557void MixerThread::updateHalSupportedLatencyModes_l() {
Eric Laurentb0463942022-12-20 16:31:10 +01006558
6559 if (mOutput == nullptr || mOutput->stream == nullptr) {
6560 return;
6561 }
6562 std::vector<audio_latency_mode_t> latencyModes;
6563 const status_t status = mOutput->stream->getRecommendedLatencyModes(&latencyModes);
6564 if (status != NO_ERROR) {
6565 latencyModes.clear();
6566 }
6567 if (latencyModes != mSupportedLatencyModes) {
6568 ALOGD("%s: thread(%d) status %d supported latency modes: %s",
6569 __func__, mId, status, toString(latencyModes).c_str());
6570 mSupportedLatencyModes.swap(latencyModes);
6571 sendHalLatencyModesChangedEvent_l();
6572 }
6573}
6574
Andy Hungee58e4a2023-07-07 13:47:37 -07006575status_t MixerThread::getSupportedLatencyModes(
Eric Laurentb0463942022-12-20 16:31:10 +01006576 std::vector<audio_latency_mode_t>* modes) {
6577 if (modes == nullptr) {
6578 return BAD_VALUE;
6579 }
Andy Hung972bec12023-08-31 16:13:39 -07006580 audio_utils::lock_guard _l(mutex());
Eric Laurentb0463942022-12-20 16:31:10 +01006581 *modes = mSupportedLatencyModes;
6582 return NO_ERROR;
6583}
6584
Andy Hungee58e4a2023-07-07 13:47:37 -07006585void MixerThread::onRecommendedLatencyModeChanged(
Eric Laurentb0463942022-12-20 16:31:10 +01006586 std::vector<audio_latency_mode_t> modes) {
Andy Hung972bec12023-08-31 16:13:39 -07006587 audio_utils::lock_guard _l(mutex());
Eric Laurentb0463942022-12-20 16:31:10 +01006588 if (modes != mSupportedLatencyModes) {
6589 ALOGD("%s: thread(%d) supported latency modes: %s",
6590 __func__, mId, toString(modes).c_str());
6591 mSupportedLatencyModes.swap(modes);
6592 sendHalLatencyModesChangedEvent_l();
6593 }
6594}
6595
Andy Hungee58e4a2023-07-07 13:47:37 -07006596status_t MixerThread::setBluetoothVariableLatencyEnabled(bool enabled) {
Eric Laurentb0463942022-12-20 16:31:10 +01006597 if (mOutput == nullptr || mOutput->audioHwDev == nullptr
6598 || !mOutput->audioHwDev->supportsBluetoothVariableLatency()) {
6599 return INVALID_OPERATION;
6600 }
6601 mBluetoothLatencyModesEnabled.store(enabled);
6602 return NO_ERROR;
6603}
6604
Eric Laurent81784c32012-11-19 14:55:58 -08006605// ----------------------------------------------------------------------------
6606
Andy Hungee58e4a2023-07-07 13:47:37 -07006607/* static */
6608sp<IAfPlaybackThread> IAfPlaybackThread::createDirectOutputThread(
Andy Hung583043b2023-07-17 17:05:00 -07006609 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hungee58e4a2023-07-07 13:47:37 -07006610 AudioStreamOut* output, audio_io_handle_t id, bool systemReady,
6611 const audio_offload_info_t& offloadInfo) {
6612 return sp<DirectOutputThread>::make(
Andy Hung583043b2023-07-17 17:05:00 -07006613 afThreadCallback, output, id, systemReady, offloadInfo);
Andy Hungee58e4a2023-07-07 13:47:37 -07006614}
6615
Andy Hung583043b2023-07-17 17:05:00 -07006616DirectOutputThread::DirectOutputThread(const sp<IAfThreadCallback>& afThreadCallback,
Gareth Fennb18c1a32022-10-05 13:42:36 -07006617 AudioStreamOut* output, audio_io_handle_t id, ThreadBase::type_t type, bool systemReady,
6618 const audio_offload_info_t& offloadInfo)
Andy Hung583043b2023-07-17 17:05:00 -07006619 : PlaybackThread(afThreadCallback, output, id, type, systemReady)
Gareth Fennb18c1a32022-10-05 13:42:36 -07006620 , mOffloadInfo(offloadInfo)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006621{
Andy Hung583043b2023-07-17 17:05:00 -07006622 setMasterBalance(afThreadCallback->getMasterBalance_l());
Eric Laurentbfb1b832013-01-07 09:53:42 -08006623}
6624
Andy Hungee58e4a2023-07-07 13:47:37 -07006625DirectOutputThread::~DirectOutputThread()
Eric Laurent81784c32012-11-19 14:55:58 -08006626{
6627}
6628
Andy Hungee58e4a2023-07-07 13:47:37 -07006629void DirectOutputThread::dumpInternals_l(int fd, const Vector<String16>& args)
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006630{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07006631 PlaybackThread::dumpInternals_l(fd, args);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006632 dprintf(fd, " Master balance: %f Left: %f Right: %f\n",
6633 mMasterBalance.load(), mMasterBalanceLeft, mMasterBalanceRight);
6634}
6635
Andy Hungee58e4a2023-07-07 13:47:37 -07006636void DirectOutputThread::setMasterBalance(float balance)
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006637{
Andy Hung972bec12023-08-31 16:13:39 -07006638 audio_utils::lock_guard _l(mutex());
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006639 if (mMasterBalance != balance) {
6640 mMasterBalance.store(balance);
6641 mBalance.computeStereoBalance(balance, &mMasterBalanceLeft, &mMasterBalanceRight);
6642 broadcast_l();
6643 }
6644}
6645
Andy Hungee58e4a2023-07-07 13:47:37 -07006646void DirectOutputThread::processVolume_l(IAfTrack* track, bool lastTrack)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006647{
Eric Laurentbfb1b832013-01-07 09:53:42 -08006648 float left, right;
6649
Andy Hung333ab962019-05-28 20:23:35 -07006650 // Ensure volumeshaper state always advances even when muted.
Andy Hung8d31fd22023-06-26 19:20:57 -07006651 const sp<AudioTrackServerProxy> proxy = track->audioTrackServerProxy();
Andy Hung398ffa22022-12-13 19:19:53 -08006652
Andy Hung398ffa22022-12-13 19:19:53 -08006653 const int64_t frames = mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
6654 const int64_t time = mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
6655
Dean Wheatleyb11b0022023-09-12 04:07:35 +10006656 ALOGVV("%s: Direct/Offload bufferConsumed:%zu timestamp frames:%lld time:%lld",
6657 __func__, proxy->framesReleased(), (long long)frames, (long long)time);
Andy Hung398ffa22022-12-13 19:19:53 -08006658
6659 const int64_t volumeShaperFrames =
6660 mMonotonicFrameCounter.updateAndGetMonotonicFrameCount(frames, time);
6661 const auto [shaperVolume, shaperActive] =
6662 track->getVolumeHandler()->getVolume(volumeShaperFrames);
Andy Hung333ab962019-05-28 20:23:35 -07006663 mVolumeShaperActive = shaperActive;
6664
Vlad Popae2f5aef2022-07-25 16:00:20 +02006665 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
6666 left = float_from_gain(gain_minifloat_unpack_left(vlr));
6667 right = float_from_gain(gain_minifloat_unpack_right(vlr));
6668
6669 const bool clientVolumeMute = (left == 0.f && right == 0.f);
6670
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08006671 if (mMasterMute || mStreamTypes[track->streamType()].mute || track->isPlaybackRestricted()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08006672 left = right = 0;
6673 } else {
6674 float typeVolume = mStreamTypes[track->streamType()].volume;
Andy Hung333ab962019-05-28 20:23:35 -07006675 const float v = mMasterVolume * typeVolume * shaperVolume;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08006676
Glenn Kastenc56f3422014-03-21 17:53:17 -07006677 if (left > GAIN_FLOAT_UNITY) {
6678 left = GAIN_FLOAT_UNITY;
6679 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07006680 if (right > GAIN_FLOAT_UNITY) {
6681 right = GAIN_FLOAT_UNITY;
6682 }
zhangjincheng86cb3bc2023-01-16 17:17:38 +08006683 left *= v;
6684 right *= v;
Andy Hung583043b2023-07-17 17:05:00 -07006685 if (mAfThreadCallback->getMode() != AUDIO_MODE_IN_COMMUNICATION
zhangjincheng86cb3bc2023-01-16 17:17:38 +08006686 || audio_channel_count_from_out_mask(mChannelMask) > 1) {
6687 left *= mMasterBalanceLeft; // DirectOutputThread balance applied as track volume
6688 right *= mMasterBalanceRight;
6689 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006690 }
6691
Andy Hung583043b2023-07-17 17:05:00 -07006692 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
Vlad Popae8d99472022-06-30 16:02:48 +02006693 /*muteState=*/{mMasterMute,
6694 mStreamTypes[track->streamType()].volume == 0.f,
6695 mStreamTypes[track->streamType()].mute,
Vlad Popae2f5aef2022-07-25 16:00:20 +02006696 track->isPlaybackRestricted(),
Vlad Popa436c9172022-08-02 15:25:08 +02006697 clientVolumeMute,
6698 shaperVolume == 0.f});
Vlad Popae8d99472022-06-30 16:02:48 +02006699
Eric Laurentbfb1b832013-01-07 09:53:42 -08006700 if (lastTrack) {
jiabin76d94692022-12-15 21:51:21 +00006701 track->setFinalVolume(left, right);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006702 if (left != mLeftVolFloat || right != mRightVolFloat) {
6703 mLeftVolFloat = left;
6704 mRightVolFloat = right;
6705
Eric Laurentbfb1b832013-01-07 09:53:42 -08006706 // Delegate volume control to effect in track effect chain if needed
6707 // only one effect chain can be present on DirectOutputThread, so if
6708 // there is one, the track is connected to it
6709 if (!mEffectChains.isEmpty()) {
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09006710 // if effect chain exists, volume is handled by it.
6711 // Convert volumes from float to 8.24
6712 uint32_t vl = (uint32_t)(left * (1 << 24));
6713 uint32_t vr = (uint32_t)(right * (1 << 24));
Shunkai Yaof4847652024-01-12 00:25:20 +00006714 // Direct/Offload effect chains set output volume in setVolume().
6715 (void)mEffectChains[0]->setVolume(&vl, &vr);
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09006716 } else {
6717 // otherwise we directly set the volume.
6718 setVolumeForOutput_l(left, right);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006719 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006720 }
6721 }
6722}
6723
Andy Hungee58e4a2023-07-07 13:47:37 -07006724void DirectOutputThread::onAddNewTrack_l()
Phil Burk43b4dcc2015-06-09 16:53:44 -07006725{
Andy Hung8d31fd22023-06-26 19:20:57 -07006726 sp<IAfTrack> previousTrack = mPreviousTrack.promote();
6727 sp<IAfTrack> latestTrack = mActiveTracks.getLatest();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006728
Eric Laurent0f0631e2015-07-06 18:01:25 -07006729 if (previousTrack != 0 && latestTrack != 0) {
6730 if (mType == DIRECT) {
6731 if (previousTrack.get() != latestTrack.get()) {
6732 mFlushPending = true;
6733 }
6734 } else /* mType == OFFLOAD */ {
Dean Wheatley0f51fd02022-08-31 16:41:40 +10006735 if (previousTrack->sessionId() != latestTrack->sessionId() ||
6736 previousTrack->isFlushPending()) {
Eric Laurent0f0631e2015-07-06 18:01:25 -07006737 mFlushPending = true;
6738 }
6739 }
Revathi Uddaraju20413a92016-10-13 17:16:14 +08006740 } else if (previousTrack == 0) {
6741 // there could be an old track added back during track transition for direct
6742 // output, so always issues flush to flush data of the previous track if it
6743 // was already destroyed with HAL paused, then flush can resume the playback
6744 mFlushPending = true;
Phil Burk43b4dcc2015-06-09 16:53:44 -07006745 }
6746 PlaybackThread::onAddNewTrack_l();
6747}
Eric Laurentbfb1b832013-01-07 09:53:42 -08006748
Andy Hungee58e4a2023-07-07 13:47:37 -07006749PlaybackThread::mixer_state DirectOutputThread::prepareTracks_l(
Andy Hung8d31fd22023-06-26 19:20:57 -07006750 Vector<sp<IAfTrack>>* tracksToRemove
Eric Laurent81784c32012-11-19 14:55:58 -08006751)
6752{
Eric Laurentd595b7c2013-04-03 17:27:56 -07006753 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08006754 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006755 bool doHwPause = false;
6756 bool doHwResume = false;
Eric Laurent81784c32012-11-19 14:55:58 -08006757
6758 // find out which tracks need to be processed
Andy Hung8d31fd22023-06-26 19:20:57 -07006759 for (const sp<IAfTrack>& t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08006760 if (t->isInvalid()) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07006761 ALOGW("An invalidated track shouldn't be in active list");
Eric Laurent5850c4c2016-11-10 13:04:31 -08006762 tracksToRemove->add(t);
Phil Burk43b4dcc2015-06-09 16:53:44 -07006763 continue;
6764 }
6765
Andy Hung8d31fd22023-06-26 19:20:57 -07006766 IAfTrack* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006767#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurent81784c32012-11-19 14:55:58 -08006768 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006769#endif
Eric Laurentfd477972013-10-25 18:10:40 -07006770 // Only consider last track started for volume and mixer state control.
6771 // In theory an older track could underrun and restart after the new one starts
6772 // but as we only care about the transition phase between two tracks on a
6773 // direct output, it is not a problem to ignore the underrun case.
Andy Hung8d31fd22023-06-26 19:20:57 -07006774 sp<IAfTrack> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08006775 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08006776
Kuowei Li23666472021-01-20 10:23:25 +08006777 if (track->isPausePending()) {
6778 track->pauseAck();
6779 // It is possible a track might have been flushed or stopped.
6780 // Other operations such as flush pending might occur on the next prepare.
6781 if (track->isPausing()) {
6782 track->setPaused();
6783 }
6784 // Always perform pause, as an immediate flush will change
6785 // the pause state to be no longer isPausing().
Phil Burk6fc2a7c2015-04-30 16:08:10 -07006786 if (mHwSupportsPause && last && !mHwPaused) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006787 doHwPause = true;
6788 mHwPaused = true;
6789 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08006790 } else if (track->isFlushPending()) {
6791 track->flushAck();
6792 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07006793 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006794 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07006795 } else if (track->isResumePending()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006796 track->resumeAck();
Eric Laurent3df841a2016-07-15 15:15:40 -07006797 if (last) {
6798 mLeftVolFloat = mRightVolFloat = -1.0;
6799 if (mHwPaused) {
6800 doHwResume = true;
6801 mHwPaused = false;
6802 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08006803 }
6804 }
6805
Eric Laurent81784c32012-11-19 14:55:58 -08006806 // The first time a track is added we wait
Phil Burk99adee32014-12-10 16:46:30 -08006807 // for all its buffers to be filled before processing it.
6808 // Allow draining the buffer in case the client
6809 // app does not call stop() and relies on underrun to stop:
Andy Hung8d31fd22023-06-26 19:20:57 -07006810 // hence the test on (track->retryCount() > 1).
6811 // If track->retryCount() <= 1 then track is about to be disabled, paused, removed,
Andy Hung455982f2021-04-27 17:46:12 -07006812 // so we accept any nonzero amount of data delivered by the AudioTrack (which will
6813 // reset the retry counter).
Phil Burkca5e6142015-07-14 09:42:29 -07006814 // Do not use a high threshold for compressed audio.
Andy Hung455982f2021-04-27 17:46:12 -07006815
6816 // target retry count that we will use is based on the time we wait for retries.
6817 const int32_t targetRetryCount = kMaxTrackRetriesDirectMs * 1000 / mActiveSleepTimeUs;
6818 // the retry threshold is when we accept any size for PCM data. This is slightly
6819 // smaller than the retry count so we can push small bits of data without a glitch.
6820 const int32_t retryThreshold = targetRetryCount > 2 ? targetRetryCount - 1 : 1;
Eric Laurent81784c32012-11-19 14:55:58 -08006821 uint32_t minFrames;
Phil Burk99adee32014-12-10 16:46:30 -08006822 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
Andy Hung8d31fd22023-06-26 19:20:57 -07006823 && (track->retryCount() > retryThreshold) && audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006824 minFrames = mNormalFrameCount;
6825 } else {
6826 minFrames = 1;
6827 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006828
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07006829 const size_t framesReady = track->framesReady();
6830 const int trackId = track->id();
6831 if (ATRACE_ENABLED()) {
6832 std::string traceName("nRdy");
6833 traceName += std::to_string(trackId);
6834 ATRACE_INT(traceName.c_str(), framesReady);
6835 }
6836 if ((framesReady >= minFrames) && track->isReady() && !track->isPaused() &&
Eric Laurentab5cdba2014-06-09 17:22:27 -07006837 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08006838 {
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07006839 ALOGVV("track(%d) s=%08x [OK]", trackId, cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08006840
Andy Hung8d31fd22023-06-26 19:20:57 -07006841 if (track->fillingStatus() == IAfTrack::FS_FILLED) {
6842 track->fillingStatus() = IAfTrack::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07006843 if (last) {
6844 // make sure processVolume_l() will apply new volume even if 0
6845 mLeftVolFloat = mRightVolFloat = -1.0;
6846 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08006847 if (!mHwSupportsPause) {
6848 track->resumeAck();
Eric Laurent81784c32012-11-19 14:55:58 -08006849 }
6850 }
6851
6852 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08006853 processVolume_l(track, last);
6854 if (last) {
Andy Hung8d31fd22023-06-26 19:20:57 -07006855 sp<IAfTrack> previousTrack = mPreviousTrack.promote();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006856 if (previousTrack != 0) {
6857 if (track != previousTrack.get()) {
6858 // Flush any data still being written from last track
6859 mBytesRemaining = 0;
Eric Laurent0f0631e2015-07-06 18:01:25 -07006860 // Invalidate previous track to force a seek when resuming.
6861 previousTrack->invalidate();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006862 }
6863 }
6864 mPreviousTrack = track;
6865
Eric Laurentd595b7c2013-04-03 17:27:56 -07006866 // reset retry count
Andy Hung8d31fd22023-06-26 19:20:57 -07006867 track->retryCount() = targetRetryCount;
Eric Laurent5850c4c2016-11-10 13:04:31 -08006868 mActiveTrack = t;
Eric Laurentd595b7c2013-04-03 17:27:56 -07006869 mixerStatus = MIXER_TRACKS_READY;
Eric Laurent5cff4032015-05-26 13:49:58 -07006870 if (mHwPaused) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08006871 doHwResume = true;
6872 mHwPaused = false;
6873 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07006874 }
Eric Laurent81784c32012-11-19 14:55:58 -08006875 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07006876 // clear effect chain input buffer if the last active track started underruns
6877 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07006878 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08006879 mEffectChains[0]->clearInputBuffer();
6880 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07006881 if (track->isStopping_1()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07006882 track->setState(IAfTrackBase::STOPPING_2);
Eric Laurentb369caf2015-03-30 20:51:47 -07006883 if (last && mHwPaused) {
6884 doHwResume = true;
6885 mHwPaused = false;
6886 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07006887 }
6888 if ((track->sharedBuffer() != 0) || track->isStopped() ||
6889 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08006890 // We have consumed all the buffers of this track.
6891 // Remove it from the list of active tracks.
Atneya Nair0cae0432022-05-10 18:12:12 -04006892 bool presComplete = false;
Eric Laurentfd477972013-10-25 18:10:40 -07006893 if (mStandby || !last ||
Atneya Nair0cae0432022-05-10 18:12:12 -04006894 (presComplete = track->presentationComplete(latency_l())) ||
Jindong32dc26e2019-11-11 18:10:01 +08006895 track->isPaused() || mHwPaused) {
Atneya Nair0cae0432022-05-10 18:12:12 -04006896 if (presComplete) {
6897 mOutput->presentationComplete();
6898 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07006899 if (track->isStopping_2()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07006900 track->setState(IAfTrackBase::STOPPED);
Eric Laurentab5cdba2014-06-09 17:22:27 -07006901 }
Eric Laurent81784c32012-11-19 14:55:58 -08006902 if (track->isStopped()) {
6903 track->reset();
6904 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07006905 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08006906 }
6907 } else {
6908 // No buffers for this track. Give it a few chances to
6909 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07006910 // Only consider last track started for mixer state control
Brian Lindahl65e90012022-07-27 18:01:07 +02006911 bool isTimestampAdvancing = mIsTimestampAdvancing.check(mOutput);
Gareth Fennb18c1a32022-10-05 13:42:36 -07006912 if (!isTunerStream() // tuner streams remain active in underrun
Andy Hung8d31fd22023-06-26 19:20:57 -07006913 && --(track->retryCount()) <= 0) {
Brian Lindahl65e90012022-07-27 18:01:07 +02006914 if (isTimestampAdvancing) { // HAL is still playing audio, give us more time.
Andy Hung8d31fd22023-06-26 19:20:57 -07006915 track->retryCount() = kMaxTrackRetriesOffload;
ziyangch8f194f12021-12-01 13:48:04 -08006916 } else {
Eric Laurent46b6b5d2024-04-12 17:02:51 +00006917 ALOGI("%s BUFFER TIMEOUT: remove track(%d) from active list due to"
6918 " underrun on thread %d", __func__, trackId, mId);
ziyangch8f194f12021-12-01 13:48:04 -08006919 tracksToRemove->add(track);
6920 // indicate to client process that the track was disabled because of
6921 // underrun; it will then automatically call start() when data is available
6922 track->disable();
6923 // only do hw pause when track is going to be removed due to BUFFER TIMEOUT.
6924 // unlike mixerthread, HAL can be paused for direct output
6925 ALOGW("pause because of UNDERRUN, framesReady = %zu,"
6926 "minFrames = %u, mFormat = %#x",
6927 framesReady, minFrames, mFormat);
6928 if (last && mHwSupportsPause && !mHwPaused && !mStandby) {
6929 doHwPause = true;
6930 mHwPaused = true;
6931 }
Eric Laurent0f7b5f22014-12-19 10:43:21 -08006932 }
Haynes Mathew George5c6daae2017-01-24 20:06:05 -08006933 } else if (last) {
6934 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurent81784c32012-11-19 14:55:58 -08006935 }
6936 }
6937 }
6938 }
6939
Eric Laurentd1f69b02014-12-15 14:33:13 -08006940 // if an active track did not command a flush, check for pending flush on stopped tracks
Phil Burk43b4dcc2015-06-09 16:53:44 -07006941 if (!mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006942 for (size_t i = 0; i < mTracks.size(); i++) {
6943 if (mTracks[i]->isFlushPending()) {
6944 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006945 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006946 }
6947 }
6948 }
6949
6950 // make sure the pause/flush/resume sequence is executed in the right order.
6951 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
6952 // before flush and then resume HW. This can happen in case of pause/flush/resume
6953 // if resume is received before pause is executed.
6954 if (mHwSupportsPause && !mStandby &&
Phil Burk43b4dcc2015-06-09 16:53:44 -07006955 (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006956 status_t result = mOutput->stream->pause();
6957 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Gareth Fenncd1e1622022-10-05 11:45:45 -07006958 doHwResume = !doHwPause; // resume if pause is due to flush.
Eric Laurentd1f69b02014-12-15 14:33:13 -08006959 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07006960 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006961 flushHw_l();
6962 }
6963 if (mHwSupportsPause && !mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006964 status_t result = mOutput->stream->resume();
6965 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08006966 }
Eric Laurent81784c32012-11-19 14:55:58 -08006967 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08006968 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08006969
6970 return mixerStatus;
6971}
6972
Andy Hungee58e4a2023-07-07 13:47:37 -07006973void DirectOutputThread::threadLoop_mix()
Eric Laurent81784c32012-11-19 14:55:58 -08006974{
Eric Laurent81784c32012-11-19 14:55:58 -08006975 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08006976 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08006977 // output audio to hardware
6978 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07006979 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08006980 buffer.frameCount = frameCount;
Phil Burk062e67a2015-02-11 13:40:50 -08006981 status_t status = mActiveTrack->getNextBuffer(&buffer);
6982 if (status != NO_ERROR || buffer.raw == NULL) {
Eric Laurent51716182016-02-29 18:00:56 -08006983 // no need to pad with 0 for compressed audio
6984 if (audio_has_proportional_frames(mFormat)) {
6985 memset(curBuf, 0, frameCount * mFrameSize);
6986 }
Eric Laurent81784c32012-11-19 14:55:58 -08006987 break;
6988 }
6989 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
6990 frameCount -= buffer.frameCount;
6991 curBuf += buffer.frameCount * mFrameSize;
6992 mActiveTrack->releaseBuffer(&buffer);
6993 }
Andy Hung2098f272014-02-27 14:00:06 -08006994 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006995 mSleepTimeUs = 0;
6996 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08006997 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08006998}
6999
Andy Hungee58e4a2023-07-07 13:47:37 -07007000void DirectOutputThread::threadLoop_sleepTime()
Eric Laurent81784c32012-11-19 14:55:58 -08007001{
Eric Laurentd1f69b02014-12-15 14:33:13 -08007002 // do not write to HAL when paused
Eric Laurent0f7b5f22014-12-19 10:43:21 -08007003 if (mHwPaused || (usesHwAvSync() && mStandby)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007004 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurentd1f69b02014-12-15 14:33:13 -08007005 return;
7006 }
Andy Hung85ba3332021-04-27 17:40:26 -07007007 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
7008 mSleepTimeUs = mActiveSleepTimeUs;
7009 } else {
7010 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007011 }
Andy Hung85ba3332021-04-27 17:40:26 -07007012 // Note: In S or later, we do not write zeroes for
7013 // linear or proportional PCM direct tracks in underrun.
Eric Laurent81784c32012-11-19 14:55:58 -08007014}
7015
Andy Hungee58e4a2023-07-07 13:47:37 -07007016void DirectOutputThread::threadLoop_exit()
Eric Laurentd1f69b02014-12-15 14:33:13 -08007017{
7018 {
Andy Hung972bec12023-08-31 16:13:39 -07007019 audio_utils::lock_guard _l(mutex());
Eric Laurentd1f69b02014-12-15 14:33:13 -08007020 for (size_t i = 0; i < mTracks.size(); i++) {
7021 if (mTracks[i]->isFlushPending()) {
7022 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07007023 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08007024 }
7025 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07007026 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08007027 flushHw_l();
7028 }
7029 }
7030 PlaybackThread::threadLoop_exit();
7031}
7032
7033// must be called with thread mutex locked
Andy Hungee58e4a2023-07-07 13:47:37 -07007034bool DirectOutputThread::shouldStandby_l()
Eric Laurentd1f69b02014-12-15 14:33:13 -08007035{
7036 bool trackPaused = false;
Eric Laurentb369caf2015-03-30 20:51:47 -07007037 bool trackStopped = false;
Eric Laurent46b6b5d2024-04-12 17:02:51 +00007038 bool trackDisabled = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08007039
Eric Laurent46b6b5d2024-04-12 17:02:51 +00007040 // do not put the HAL in standby when paused. NuPlayer clear the offloaded AudioTrack
Eric Laurentd1f69b02014-12-15 14:33:13 -08007041 // after a timeout and we will enter standby then.
Eric Laurent46b6b5d2024-04-12 17:02:51 +00007042 // On offload threads, do not enter standby if the main track is still underrunning.
Eric Laurentd1f69b02014-12-15 14:33:13 -08007043 if (mTracks.size() > 0) {
Eric Laurent46b6b5d2024-04-12 17:02:51 +00007044 const auto& mainTrack = mTracks[mTracks.size() - 1];
7045
7046 trackPaused = mainTrack->isPaused();
7047 trackStopped = mainTrack->isStopped() || mainTrack->state() == IAfTrackBase::IDLE;
7048 trackDisabled = (mType == OFFLOAD) && mainTrack->isDisabled();
Eric Laurentd1f69b02014-12-15 14:33:13 -08007049 }
7050
Eric Laurent46b6b5d2024-04-12 17:02:51 +00007051 return !mStandby && !(trackPaused || (mHwPaused && !trackStopped) || trackDisabled);
Eric Laurentd1f69b02014-12-15 14:33:13 -08007052}
7053
Andy Hungc5007f82023-08-29 14:26:09 -07007054// checkForNewParameter_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07007055bool DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
Eric Laurent10351942014-05-08 18:49:52 -07007056 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08007057{
7058 bool reconfig = false;
Eric Laurent10351942014-05-08 18:49:52 -07007059 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08007060
Eric Laurent10351942014-05-08 18:49:52 -07007061 AudioParameter param = AudioParameter(keyValuePair);
7062 int value;
7063 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07007064 LOG_FATAL("Should not set routing device in DirectOutputThread");
Eric Laurent81784c32012-11-19 14:55:58 -08007065 }
Eric Laurent10351942014-05-08 18:49:52 -07007066 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
7067 // do not accept frame count changes if tracks are open as the track buffer
7068 // size depends on frame count and correct behavior would not be garantied
7069 // if frame count is changed after track creation
7070 if (!mTracks.isEmpty()) {
7071 status = INVALID_OPERATION;
7072 } else {
7073 reconfig = true;
7074 }
7075 }
7076 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007077 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07007078 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08007079 mOutput->standby();
Andy Hungcf10d742020-04-28 15:38:24 -07007080 if (!mStandby) {
7081 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07007082 mThreadSnapshot.onEnd();
Eric Laurent19952e12023-04-20 10:08:29 +02007083 setStandby_l();
Andy Hungcf10d742020-04-28 15:38:24 -07007084 }
Eric Laurent10351942014-05-08 18:49:52 -07007085 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007086 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07007087 }
7088 if (status == NO_ERROR && reconfig) {
7089 readOutputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07007090 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07007091 }
7092 }
7093
Dean Wheatley68918102021-03-19 22:09:19 +11007094 return reconfig;
Eric Laurent81784c32012-11-19 14:55:58 -08007095}
7096
Andy Hungee58e4a2023-07-07 13:47:37 -07007097uint32_t DirectOutputThread::activeSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08007098{
7099 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08007100 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08007101 time = PlaybackThread::activeSleepTimeUs();
7102 } else {
Eric Laurent51716182016-02-29 18:00:56 -08007103 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007104 }
7105 return time;
7106}
7107
Andy Hungee58e4a2023-07-07 13:47:37 -07007108uint32_t DirectOutputThread::idleSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08007109{
7110 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08007111 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08007112 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
7113 } else {
Eric Laurent51716182016-02-29 18:00:56 -08007114 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007115 }
7116 return time;
7117}
7118
Andy Hungee58e4a2023-07-07 13:47:37 -07007119uint32_t DirectOutputThread::suspendSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08007120{
7121 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08007122 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08007123 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
7124 } else {
Eric Laurent51716182016-02-29 18:00:56 -08007125 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007126 }
7127 return time;
7128}
7129
Andy Hungee58e4a2023-07-07 13:47:37 -07007130void DirectOutputThread::cacheParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08007131{
7132 PlaybackThread::cacheParameters_l();
7133
7134 // use shorter standby delay as on normal output to release
7135 // hardware resources as soon as possible
Eric Laurentb369caf2015-03-30 20:51:47 -07007136 // no delay on outputs with HW A/V sync
7137 if (usesHwAvSync()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007138 mStandbyDelayNs = 0;
Phil Burkfdb3c072016-02-09 10:47:02 -08007139 } else if ((mType == OFFLOAD) && !audio_has_proportional_frames(mFormat)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007140 mStandbyDelayNs = kOffloadStandbyDelayNs;
Eric Laurent5cff4032015-05-26 13:49:58 -07007141 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007142 mStandbyDelayNs = microseconds(mActiveSleepTimeUs*2);
Eric Laurent972a1732013-09-04 09:42:59 -07007143 }
Eric Laurent81784c32012-11-19 14:55:58 -08007144}
7145
Andy Hungee58e4a2023-07-07 13:47:37 -07007146void DirectOutputThread::flushHw_l()
Eric Laurente659ef42014-09-29 13:06:46 -07007147{
ziyangch8f194f12021-12-01 13:48:04 -08007148 PlaybackThread::flushHw_l();
Phil Burk062e67a2015-02-11 13:40:50 -08007149 mOutput->flush();
Eric Laurentd1f69b02014-12-15 14:33:13 -08007150 mHwPaused = false;
Phil Burk43b4dcc2015-06-09 16:53:44 -07007151 mFlushPending = false;
Dean Wheatley12473e92021-03-18 23:00:55 +11007152 mTimestampVerifier.discontinuity(discontinuityForStandbyOrFlush());
Sampath Shetty999f0e82020-01-15 10:19:06 +11007153 mTimestamp.clear();
Andy Hung398ffa22022-12-13 19:19:53 -08007154 mMonotonicFrameCounter.onFlush();
Eric Laurente659ef42014-09-29 13:06:46 -07007155}
7156
Andy Hungee58e4a2023-07-07 13:47:37 -07007157int64_t DirectOutputThread::computeWaitTimeNs_l() const {
Andy Hung10cbff12017-02-21 17:30:14 -08007158 // If a VolumeShaper is active, we must wake up periodically to update volume.
7159 const int64_t NS_PER_MS = 1000000;
7160 return mVolumeShaperActive ?
7161 kMinNormalSinkBufferSizeMs * NS_PER_MS : PlaybackThread::computeWaitTimeNs_l();
7162}
7163
Eric Laurent81784c32012-11-19 14:55:58 -08007164// ----------------------------------------------------------------------------
7165
Andy Hungee58e4a2023-07-07 13:47:37 -07007166AsyncCallbackThread::AsyncCallbackThread(
7167 const wp<PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08007168 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07007169 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07007170 mWriteAckSequence(0),
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007171 mDrainSequence(0),
7172 mAsyncError(false)
Eric Laurentbfb1b832013-01-07 09:53:42 -08007173{
7174}
7175
Andy Hungee58e4a2023-07-07 13:47:37 -07007176void AsyncCallbackThread::onFirstRef()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007177{
7178 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
7179}
7180
Andy Hungee58e4a2023-07-07 13:47:37 -07007181bool AsyncCallbackThread::threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007182{
7183 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07007184 uint32_t writeAckSequence;
7185 uint32_t drainSequence;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007186 bool asyncError;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007187
7188 {
Andy Hungc5007f82023-08-29 14:26:09 -07007189 audio_utils::unique_lock _l(mutex());
Haynes Mathew George24a325d2013-12-03 21:26:02 -08007190 while (!((mWriteAckSequence & 1) ||
7191 (mDrainSequence & 1) ||
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007192 mAsyncError ||
Haynes Mathew George24a325d2013-12-03 21:26:02 -08007193 exitPending())) {
Andy Hungc5007f82023-08-29 14:26:09 -07007194 mWaitWorkCV.wait(_l);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08007195 }
7196
Eric Laurentbfb1b832013-01-07 09:53:42 -08007197 if (exitPending()) {
7198 break;
7199 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07007200 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
7201 mWriteAckSequence, mDrainSequence);
7202 writeAckSequence = mWriteAckSequence;
7203 mWriteAckSequence &= ~1;
7204 drainSequence = mDrainSequence;
7205 mDrainSequence &= ~1;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007206 asyncError = mAsyncError;
7207 mAsyncError = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007208 }
7209 {
Andy Hungee58e4a2023-07-07 13:47:37 -07007210 const sp<PlaybackThread> playbackThread = mPlaybackThread.promote();
Eric Laurent4de95592013-09-26 15:28:21 -07007211 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07007212 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07007213 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007214 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07007215 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07007216 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007217 }
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007218 if (asyncError) {
7219 playbackThread->onAsyncError();
7220 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007221 }
7222 }
7223 }
7224 return false;
7225}
7226
Andy Hungee58e4a2023-07-07 13:47:37 -07007227void AsyncCallbackThread::exit()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007228{
7229 ALOGV("AsyncCallbackThread::exit");
Andy Hung972bec12023-08-31 16:13:39 -07007230 audio_utils::lock_guard _l(mutex());
Eric Laurentbfb1b832013-01-07 09:53:42 -08007231 requestExit();
Andy Hungc5007f82023-08-29 14:26:09 -07007232 mWaitWorkCV.notify_all();
Eric Laurentbfb1b832013-01-07 09:53:42 -08007233}
7234
Andy Hungee58e4a2023-07-07 13:47:37 -07007235void AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08007236{
Andy Hung972bec12023-08-31 16:13:39 -07007237 audio_utils::lock_guard _l(mutex());
Eric Laurent3b4529e2013-09-05 18:09:19 -07007238 // bit 0 is cleared
7239 mWriteAckSequence = sequence << 1;
7240}
7241
Andy Hungee58e4a2023-07-07 13:47:37 -07007242void AsyncCallbackThread::resetWriteBlocked()
Eric Laurent3b4529e2013-09-05 18:09:19 -07007243{
Andy Hung972bec12023-08-31 16:13:39 -07007244 audio_utils::lock_guard _l(mutex());
Eric Laurent3b4529e2013-09-05 18:09:19 -07007245 // ignore unexpected callbacks
7246 if (mWriteAckSequence & 2) {
7247 mWriteAckSequence |= 1;
Andy Hungc5007f82023-08-29 14:26:09 -07007248 mWaitWorkCV.notify_one();
Eric Laurentbfb1b832013-01-07 09:53:42 -08007249 }
7250}
7251
Andy Hungee58e4a2023-07-07 13:47:37 -07007252void AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08007253{
Andy Hung972bec12023-08-31 16:13:39 -07007254 audio_utils::lock_guard _l(mutex());
Eric Laurent3b4529e2013-09-05 18:09:19 -07007255 // bit 0 is cleared
7256 mDrainSequence = sequence << 1;
7257}
7258
Andy Hungee58e4a2023-07-07 13:47:37 -07007259void AsyncCallbackThread::resetDraining()
Eric Laurent3b4529e2013-09-05 18:09:19 -07007260{
Andy Hung972bec12023-08-31 16:13:39 -07007261 audio_utils::lock_guard _l(mutex());
Eric Laurent3b4529e2013-09-05 18:09:19 -07007262 // ignore unexpected callbacks
7263 if (mDrainSequence & 2) {
7264 mDrainSequence |= 1;
Andy Hungc5007f82023-08-29 14:26:09 -07007265 mWaitWorkCV.notify_one();
Eric Laurentbfb1b832013-01-07 09:53:42 -08007266 }
7267}
7268
Andy Hungee58e4a2023-07-07 13:47:37 -07007269void AsyncCallbackThread::setAsyncError()
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007270{
Andy Hung972bec12023-08-31 16:13:39 -07007271 audio_utils::lock_guard _l(mutex());
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007272 mAsyncError = true;
Andy Hungc5007f82023-08-29 14:26:09 -07007273 mWaitWorkCV.notify_one();
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007274}
7275
Eric Laurentbfb1b832013-01-07 09:53:42 -08007276
7277// ----------------------------------------------------------------------------
Andy Hungee58e4a2023-07-07 13:47:37 -07007278
7279/* static */
7280sp<IAfPlaybackThread> IAfPlaybackThread::createOffloadThread(
Andy Hung583043b2023-07-17 17:05:00 -07007281 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hungee58e4a2023-07-07 13:47:37 -07007282 AudioStreamOut* output, audio_io_handle_t id, bool systemReady,
7283 const audio_offload_info_t& offloadInfo) {
Andy Hung583043b2023-07-17 17:05:00 -07007284 return sp<OffloadThread>::make(afThreadCallback, output, id, systemReady, offloadInfo);
Andy Hungee58e4a2023-07-07 13:47:37 -07007285}
7286
Andy Hung583043b2023-07-17 17:05:00 -07007287OffloadThread::OffloadThread(const sp<IAfThreadCallback>& afThreadCallback,
Gareth Fennb18c1a32022-10-05 13:42:36 -07007288 AudioStreamOut* output, audio_io_handle_t id, bool systemReady,
7289 const audio_offload_info_t& offloadInfo)
Andy Hung583043b2023-07-17 17:05:00 -07007290 : DirectOutputThread(afThreadCallback, output, id, OFFLOAD, systemReady, offloadInfo),
ziyangch8f194f12021-12-01 13:48:04 -08007291 mPausedWriteLength(0), mPausedBytesRemaining(0), mKeepWakeLock(true)
Eric Laurentbfb1b832013-01-07 09:53:42 -08007292{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07007293 //FIXME: mStandby should be set to true by ThreadBase constructo
Eric Laurentfd477972013-10-25 18:10:40 -07007294 mStandby = true;
Eric Laurent64667972016-03-30 18:19:46 -07007295 mKeepWakeLock = property_get_bool("ro.audio.offload_wakelock", true /* default_value */);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007296}
7297
Andy Hungee58e4a2023-07-07 13:47:37 -07007298void OffloadThread::threadLoop_exit()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007299{
7300 if (mFlushPending || mHwPaused) {
7301 // If a flush is pending or track was paused, just discard buffered data
Andy Hungab65b182023-09-06 19:41:47 -07007302 audio_utils::lock_guard l(mutex());
Eric Laurentbfb1b832013-01-07 09:53:42 -08007303 flushHw_l();
7304 } else {
7305 mMixerStatus = MIXER_DRAIN_ALL;
7306 threadLoop_drain();
7307 }
Uday Gupta56604aa2014-05-13 11:19:17 -07007308 if (mUseAsyncWrite) {
7309 ALOG_ASSERT(mCallbackThread != 0);
7310 mCallbackThread->exit();
7311 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007312 PlaybackThread::threadLoop_exit();
7313}
7314
Andy Hungee58e4a2023-07-07 13:47:37 -07007315PlaybackThread::mixer_state OffloadThread::prepareTracks_l(
Andy Hung8d31fd22023-06-26 19:20:57 -07007316 Vector<sp<IAfTrack>>* tracksToRemove
Eric Laurentbfb1b832013-01-07 09:53:42 -08007317)
7318{
Eric Laurentbfb1b832013-01-07 09:53:42 -08007319 size_t count = mActiveTracks.size();
7320
7321 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07007322 bool doHwPause = false;
7323 bool doHwResume = false;
7324
Glenn Kastenc42e9b42016-03-21 11:35:03 -07007325 ALOGV("OffloadThread::prepareTracks_l active tracks %zu", count);
Eric Laurentede6c3b2013-09-19 14:37:46 -07007326
Eric Laurentbfb1b832013-01-07 09:53:42 -08007327 // find out which tracks need to be processed
Andy Hung8d31fd22023-06-26 19:20:57 -07007328 for (const sp<IAfTrack>& t : mActiveTracks) {
7329 IAfTrack* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07007330#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurentbfb1b832013-01-07 09:53:42 -08007331 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07007332#endif
Eric Laurentfd477972013-10-25 18:10:40 -07007333 // Only consider last track started for volume and mixer state control.
7334 // In theory an older track could underrun and restart after the new one starts
7335 // but as we only care about the transition phase between two tracks on a
7336 // direct output, it is not a problem to ignore the underrun case.
Andy Hung8d31fd22023-06-26 19:20:57 -07007337 sp<IAfTrack> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08007338 bool last = l.get() == track;
Eric Laurentfd477972013-10-25 18:10:40 -07007339
Haynes Mathew George7844f672014-01-15 12:32:55 -08007340 if (track->isInvalid()) {
7341 ALOGW("An invalidated track shouldn't be in active list");
7342 tracksToRemove->add(track);
7343 continue;
7344 }
7345
Andy Hung8d31fd22023-06-26 19:20:57 -07007346 if (track->state() == IAfTrackBase::IDLE) {
Haynes Mathew George7844f672014-01-15 12:32:55 -08007347 ALOGW("An idle track shouldn't be in active list");
7348 continue;
7349 }
7350
Kuowei Li23666472021-01-20 10:23:25 +08007351 if (track->isPausePending()) {
7352 track->pauseAck();
7353 // It is possible a track might have been flushed or stopped.
7354 // Other operations such as flush pending might occur on the next prepare.
7355 if (track->isPausing()) {
7356 track->setPaused();
7357 }
7358 // Always perform pause if last, as an immediate flush will change
7359 // the pause state to be no longer isPausing().
Eric Laurentbfb1b832013-01-07 09:53:42 -08007360 if (last) {
Eric Laurent5cff4032015-05-26 13:49:58 -07007361 if (mHwSupportsPause && !mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07007362 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007363 mHwPaused = true;
7364 }
7365 // If we were part way through writing the mixbuffer to
7366 // the HAL we must save this until we resume
7367 // BUG - this will be wrong if a different track is made active,
7368 // in that case we want to discard the pending data in the
7369 // mixbuffer and tell the client to present it again when the
7370 // track is resumed
7371 mPausedWriteLength = mCurrentWriteLength;
7372 mPausedBytesRemaining = mBytesRemaining;
7373 mBytesRemaining = 0; // stop writing
7374 }
7375 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08007376 } else if (track->isFlushPending()) {
Eric Laurente93cc032016-05-05 10:15:10 -07007377 if (track->isStopping_1()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07007378 track->retryCount() = kMaxTrackStopRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07007379 } else {
Andy Hung8d31fd22023-06-26 19:20:57 -07007380 track->retryCount() = kMaxTrackRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07007381 }
Haynes Mathew George7844f672014-01-15 12:32:55 -08007382 track->flushAck();
7383 if (last) {
7384 mFlushPending = true;
7385 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08007386 } else if (track->isResumePending()){
7387 track->resumeAck();
7388 if (last) {
7389 if (mPausedBytesRemaining) {
7390 // Need to continue write that was interrupted
7391 mCurrentWriteLength = mPausedWriteLength;
7392 mBytesRemaining = mPausedBytesRemaining;
7393 mPausedBytesRemaining = 0;
7394 }
7395 if (mHwPaused) {
7396 doHwResume = true;
7397 mHwPaused = false;
7398 // threadLoop_mix() will handle the case that we need to
7399 // resume an interrupted write
7400 }
7401 // enable write to audio HAL
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007402 mSleepTimeUs = 0;
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08007403
Eric Laurent3df841a2016-07-15 15:15:40 -07007404 mLeftVolFloat = mRightVolFloat = -1.0;
7405
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08007406 // Do not handle new data in this iteration even if track->framesReady()
7407 mixerStatus = MIXER_TRACKS_ENABLED;
7408 }
7409 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07007410 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Andy Hungc0691382018-09-12 18:01:57 -07007411 ALOGVV("OffloadThread: track(%d) s=%08x [OK]", track->id(), cblk->mServer);
Andy Hung8d31fd22023-06-26 19:20:57 -07007412 if (track->fillingStatus() == IAfTrack::FS_FILLED) {
7413 track->fillingStatus() = IAfTrack::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07007414 if (last) {
7415 // make sure processVolume_l() will apply new volume even if 0
7416 mLeftVolFloat = mRightVolFloat = -1.0;
7417 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007418 }
7419
7420 if (last) {
Andy Hung8d31fd22023-06-26 19:20:57 -07007421 sp<IAfTrack> previousTrack = mPreviousTrack.promote();
Eric Laurentd7e59222013-11-15 12:02:28 -08007422 if (previousTrack != 0) {
7423 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08007424 // Flush any data still being written from last track
7425 mBytesRemaining = 0;
7426 if (mPausedBytesRemaining) {
7427 // Last track was paused so we also need to flush saved
7428 // mixbuffer state and invalidate track so that it will
7429 // re-submit that unwritten data when it is next resumed
7430 mPausedBytesRemaining = 0;
7431 // Invalidate is a bit drastic - would be more efficient
7432 // to have a flag to tell client that some of the
7433 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08007434 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08007435 }
7436 // flush data already sent to the DSP if changing audio session as audio
7437 // comes from a different source. Also invalidate previous track to force a
7438 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08007439 if (previousTrack->sessionId() != track->sessionId()) {
7440 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08007441 }
7442 }
7443 }
7444 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007445 // reset retry count
Eric Laurente93cc032016-05-05 10:15:10 -07007446 if (track->isStopping_1()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07007447 track->retryCount() = kMaxTrackStopRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07007448 } else {
Andy Hung8d31fd22023-06-26 19:20:57 -07007449 track->retryCount() = kMaxTrackRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07007450 }
Eric Laurent5850c4c2016-11-10 13:04:31 -08007451 mActiveTrack = t;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007452 mixerStatus = MIXER_TRACKS_READY;
7453 }
7454 } else {
Andy Hungc0691382018-09-12 18:01:57 -07007455 ALOGVV("OffloadThread: track(%d) s=%08x [NOT READY]", track->id(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007456 if (track->isStopping_1()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07007457 if (--(track->retryCount()) <= 0) {
Eric Laurente93cc032016-05-05 10:15:10 -07007458 // Hardware buffer can hold a large amount of audio so we must
7459 // wait for all current track's data to drain before we say
7460 // that the track is stopped.
7461 if (mBytesRemaining == 0) {
7462 // Only start draining when all data in mixbuffer
7463 // has been written
7464 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
Andy Hung8d31fd22023-06-26 19:20:57 -07007465 track->setState(IAfTrackBase::STOPPING_2);
7466 // so presentation completes after
Eric Laurente93cc032016-05-05 10:15:10 -07007467 // drain do not drain if no data was ever sent to HAL (mStandby == true)
7468 if (last && !mStandby) {
7469 // do not modify drain sequence if we are already draining. This happens
7470 // when resuming from pause after drain.
7471 if ((mDrainSequence & 1) == 0) {
7472 mSleepTimeUs = 0;
7473 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
7474 mixerStatus = MIXER_DRAIN_TRACK;
7475 mDrainSequence += 2;
7476 }
7477 if (mHwPaused) {
7478 // It is possible to move from PAUSED to STOPPING_1 without
7479 // a resume so we must ensure hardware is running
7480 doHwResume = true;
7481 mHwPaused = false;
7482 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007483 }
7484 }
Eric Laurente93cc032016-05-05 10:15:10 -07007485 } else if (last) {
Andy Hung8d31fd22023-06-26 19:20:57 -07007486 ALOGV("stopping1 underrun retries left %d", track->retryCount());
Eric Laurente93cc032016-05-05 10:15:10 -07007487 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007488 }
7489 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07007490 // Drain has completed or we are in standby, signal presentation complete
7491 if (!(mDrainSequence & 1) || !last || mStandby) {
Andy Hung8d31fd22023-06-26 19:20:57 -07007492 track->setState(IAfTrackBase::STOPPED);
Atneya Nair0cae0432022-05-10 18:12:12 -04007493 mOutput->presentationComplete();
7494 track->presentationComplete(latency_l()); // always returns true
Eric Laurentbfb1b832013-01-07 09:53:42 -08007495 track->reset();
7496 tracksToRemove->add(track);
Dean Wheatley12473e92021-03-18 23:00:55 +11007497 // OFFLOADED stop resets frame counts.
Andy Hungf3234512018-07-03 14:51:47 -07007498 if (!mUseAsyncWrite) {
7499 // If we don't get explicit drain notification we must
7500 // register discontinuity regardless of whether this is
7501 // the previous (!last) or the upcoming (last) track
7502 // to avoid skipping the discontinuity.
Dean Wheatley12473e92021-03-18 23:00:55 +11007503 mTimestampVerifier.discontinuity(
7504 mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Andy Hungf3234512018-07-03 14:51:47 -07007505 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007506 }
7507 } else {
7508 // No buffers for this track. Give it a few chances to
7509 // fill a buffer, then remove it from active list.
Brian Lindahl65e90012022-07-27 18:01:07 +02007510 bool isTimestampAdvancing = mIsTimestampAdvancing.check(mOutput);
Gareth Fennb18c1a32022-10-05 13:42:36 -07007511 if (!isTunerStream() // tuner streams remain active in underrun
Andy Hung8d31fd22023-06-26 19:20:57 -07007512 && --(track->retryCount()) <= 0) {
Brian Lindahl65e90012022-07-27 18:01:07 +02007513 if (isTimestampAdvancing) { // HAL is still playing audio, give us more time.
Andy Hung8d31fd22023-06-26 19:20:57 -07007514 track->retryCount() = kMaxTrackRetriesOffload;
Andy Hungf8044752016-07-27 14:58:11 -07007515 } else {
Eric Laurent46b6b5d2024-04-12 17:02:51 +00007516 ALOGI("%s BUFFER TIMEOUT: remove track(%d) from active list due to"
7517 " underrun on thread %d", __func__, track->id(), mId);
Andy Hungf8044752016-07-27 14:58:11 -07007518 tracksToRemove->add(track);
Glenn Kastend3bb6452016-12-05 18:14:37 -08007519 // tell client process that the track was disabled because of underrun;
Andy Hungf8044752016-07-27 14:58:11 -07007520 // it will then automatically call start() when data is available
7521 track->disable();
7522 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007523 } else if (last){
7524 mixerStatus = MIXER_TRACKS_ENABLED;
7525 }
7526 }
7527 }
7528 // compute volume for this track
Wenfeng Sun79458332019-05-29 20:12:43 +08007529 if (track->isReady()) { // check ready to prevent premature start.
7530 processVolume_l(track, last);
7531 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007532 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007533
Eric Laurentea0fade2013-10-04 16:23:48 -07007534 // make sure the pause/flush/resume sequence is executed in the right order.
7535 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
7536 // before flush and then resume HW. This can happen in case of pause/flush/resume
7537 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07007538 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007539 status_t result = mOutput->stream->pause();
7540 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Gareth Fenncd1e1622022-10-05 11:45:45 -07007541 doHwResume = !doHwPause; // resume if pause is due to flush.
Eric Laurent972a1732013-09-04 09:42:59 -07007542 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007543 if (mFlushPending) {
7544 flushHw_l();
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007545 }
Eric Laurentfd477972013-10-25 18:10:40 -07007546 if (!mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007547 status_t result = mOutput->stream->resume();
7548 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07007549 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007550
Eric Laurentbfb1b832013-01-07 09:53:42 -08007551 // remove all the tracks that need to be...
7552 removeTracks_l(*tracksToRemove);
7553
7554 return mixerStatus;
7555}
7556
Eric Laurentbfb1b832013-01-07 09:53:42 -08007557// must be called with thread mutex locked
Andy Hungee58e4a2023-07-07 13:47:37 -07007558bool OffloadThread::waitingAsyncCallback_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007559{
Eric Laurent3b4529e2013-09-05 18:09:19 -07007560 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
7561 mWriteAckSequence, mDrainSequence);
7562 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08007563 return true;
7564 }
7565 return false;
7566}
7567
Andy Hungee58e4a2023-07-07 13:47:37 -07007568bool OffloadThread::waitingAsyncCallback()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007569{
Andy Hung972bec12023-08-31 16:13:39 -07007570 audio_utils::lock_guard _l(mutex());
Eric Laurentbfb1b832013-01-07 09:53:42 -08007571 return waitingAsyncCallback_l();
7572}
7573
Andy Hungee58e4a2023-07-07 13:47:37 -07007574void OffloadThread::flushHw_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007575{
Eric Laurente659ef42014-09-29 13:06:46 -07007576 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08007577 // Flush anything still waiting in the mixbuffer
7578 mCurrentWriteLength = 0;
7579 mBytesRemaining = 0;
7580 mPausedWriteLength = 0;
7581 mPausedBytesRemaining = 0;
Eric Laurent3eaf66b2016-04-01 14:44:17 -07007582 // reset bytes written count to reflect that DSP buffers are empty after flush.
7583 mBytesWritten = 0;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08007584
Eric Laurentbfb1b832013-01-07 09:53:42 -08007585 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07007586 // discard any pending drain or write ack by incrementing sequence
7587 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
7588 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007589 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07007590 mCallbackThread->setWriteBlocked(mWriteAckSequence);
7591 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007592 }
7593}
7594
Andy Hungee58e4a2023-07-07 13:47:37 -07007595void OffloadThread::invalidateTracks(audio_stream_type_t streamType)
Haynes Mathew George05317d22016-05-03 16:34:26 -07007596{
Andy Hung972bec12023-08-31 16:13:39 -07007597 audio_utils::lock_guard _l(mutex());
Eric Laurent13084622016-05-17 10:51:49 -07007598 if (PlaybackThread::invalidateTracks_l(streamType)) {
7599 mFlushPending = true;
7600 }
Haynes Mathew George05317d22016-05-03 16:34:26 -07007601}
7602
Andy Hungee58e4a2023-07-07 13:47:37 -07007603void OffloadThread::invalidateTracks(std::set<audio_port_handle_t>& portIds) {
Andy Hung972bec12023-08-31 16:13:39 -07007604 audio_utils::lock_guard _l(mutex());
jiabinc44b3462022-12-08 12:52:31 -08007605 if (PlaybackThread::invalidateTracks_l(portIds)) {
7606 mFlushPending = true;
7607 }
7608}
7609
Eric Laurentbfb1b832013-01-07 09:53:42 -08007610// ----------------------------------------------------------------------------
7611
Andy Hungee58e4a2023-07-07 13:47:37 -07007612/* static */
7613sp<IAfDuplicatingThread> IAfDuplicatingThread::create(
Andy Hung583043b2023-07-17 17:05:00 -07007614 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hungee58e4a2023-07-07 13:47:37 -07007615 IAfPlaybackThread* mainThread, audio_io_handle_t id, bool systemReady) {
Andy Hung583043b2023-07-17 17:05:00 -07007616 return sp<DuplicatingThread>::make(afThreadCallback, mainThread, id, systemReady);
Andy Hungee58e4a2023-07-07 13:47:37 -07007617}
7618
Andy Hung583043b2023-07-17 17:05:00 -07007619DuplicatingThread::DuplicatingThread(const sp<IAfThreadCallback>& afThreadCallback,
Andy Hung87c693c2023-07-06 20:56:16 -07007620 IAfPlaybackThread* mainThread, audio_io_handle_t id, bool systemReady)
Andy Hung583043b2023-07-17 17:05:00 -07007621 : MixerThread(afThreadCallback, mainThread->getOutput(), id,
Eric Laurent72e3f392015-05-20 14:43:50 -07007622 systemReady, DUPLICATING),
Eric Laurent81784c32012-11-19 14:55:58 -08007623 mWaitTimeMs(UINT_MAX)
7624{
7625 addOutputTrack(mainThread);
7626}
7627
Andy Hungee58e4a2023-07-07 13:47:37 -07007628DuplicatingThread::~DuplicatingThread()
Eric Laurent81784c32012-11-19 14:55:58 -08007629{
7630 for (size_t i = 0; i < mOutputTracks.size(); i++) {
7631 mOutputTracks[i]->destroy();
7632 }
7633}
7634
Andy Hungee58e4a2023-07-07 13:47:37 -07007635void DuplicatingThread::threadLoop_mix()
Eric Laurent81784c32012-11-19 14:55:58 -08007636{
7637 // mix buffers...
Andy Hung920f6572022-10-06 12:09:49 -07007638 if (outputsReady()) {
Glenn Kastend79072e2016-01-06 08:41:20 -08007639 mAudioMixer->process();
Eric Laurent81784c32012-11-19 14:55:58 -08007640 } else {
Eric Laurent02b57082014-11-07 17:28:28 -08007641 if (mMixerBufferValid) {
7642 memset(mMixerBuffer, 0, mMixerBufferSize);
7643 } else {
7644 memset(mSinkBuffer, 0, mSinkBufferSize);
7645 }
Eric Laurent81784c32012-11-19 14:55:58 -08007646 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007647 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007648 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08007649 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007650 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08007651}
7652
Andy Hungee58e4a2023-07-07 13:47:37 -07007653void DuplicatingThread::threadLoop_sleepTime()
Eric Laurent81784c32012-11-19 14:55:58 -08007654{
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007655 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08007656 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007657 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007658 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007659 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007660 }
7661 } else if (mBytesWritten != 0) {
7662 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
7663 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08007664 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08007665 } else {
7666 // flush remaining overflow buffers in output tracks
7667 writeFrames = 0;
7668 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007669 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007670 }
7671}
7672
Andy Hungee58e4a2023-07-07 13:47:37 -07007673ssize_t DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08007674{
7675 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hung1c86ebe2018-05-29 20:29:08 -07007676 const ssize_t actualWritten = outputTracks[i]->write(mSinkBuffer, writeFrames);
7677
7678 // Consider the first OutputTrack for timestamp and frame counting.
7679
7680 // The threadLoop() generally assumes writing a full sink buffer size at a time.
7681 // Here, we correct for writeFrames of 0 (a stop) or underruns because
7682 // we always claim success.
7683 if (i == 0) {
7684 const ssize_t correction = mSinkBufferSize / mFrameSize - actualWritten;
7685 ALOGD_IF(correction != 0 && writeFrames != 0,
7686 "%s: writeFrames:%u actualWritten:%zd correction:%zd mFramesWritten:%lld",
7687 __func__, writeFrames, actualWritten, correction, (long long)mFramesWritten);
7688 mFramesWritten -= correction;
7689 }
7690
7691 // TODO: Report correction for the other output tracks and show in the dump.
Eric Laurent81784c32012-11-19 14:55:58 -08007692 }
Andy Hungcf10d742020-04-28 15:38:24 -07007693 if (mStandby) {
7694 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07007695 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -07007696 mStandby = false;
7697 }
Andy Hung25c2dac2014-02-27 14:56:00 -08007698 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08007699}
7700
Andy Hungee58e4a2023-07-07 13:47:37 -07007701void DuplicatingThread::threadLoop_standby()
Eric Laurent81784c32012-11-19 14:55:58 -08007702{
7703 // DuplicatingThread implements standby by stopping all tracks
7704 for (size_t i = 0; i < outputTracks.size(); i++) {
7705 outputTracks[i]->stop();
7706 }
7707}
7708
Andy Hung8a5abfd2023-12-07 19:35:12 -08007709void DuplicatingThread::threadLoop_exit()
7710{
7711 // Prevent calling the OutputTrack dtor in the DuplicatingThread dtor
7712 // where other mutexes (i.e. AudioPolicyService_Mutex) may be held.
7713 // Do so here in the threadLoop_exit().
7714
7715 SortedVector <sp<IAfOutputTrack>> localTracks;
7716 {
7717 audio_utils::lock_guard l(mutex());
7718 localTracks = std::move(mOutputTracks);
7719 mOutputTracks.clear();
7720 }
7721 localTracks.clear();
7722 outputTracks.clear();
7723 PlaybackThread::threadLoop_exit();
7724}
7725
Andy Hungee58e4a2023-07-07 13:47:37 -07007726void DuplicatingThread::dumpInternals_l(int fd, const Vector<String16>& args)
Andy Hung1bc088a2018-02-09 15:57:31 -08007727{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07007728 MixerThread::dumpInternals_l(fd, args);
Andy Hung1bc088a2018-02-09 15:57:31 -08007729
7730 std::stringstream ss;
7731 const size_t numTracks = mOutputTracks.size();
7732 ss << " " << numTracks << " OutputTracks";
7733 if (numTracks > 0) {
7734 ss << ":";
7735 for (const auto &track : mOutputTracks) {
Andy Hung87c693c2023-07-06 20:56:16 -07007736 const auto thread = track->thread().promote();
Andy Hungc0691382018-09-12 18:01:57 -07007737 ss << " (" << track->id() << " : ";
Andy Hung1bc088a2018-02-09 15:57:31 -08007738 if (thread.get() != nullptr) {
7739 ss << thread.get() << ", " << thread->id();
7740 } else {
7741 ss << "null";
7742 }
7743 ss << ")";
7744 }
7745 }
7746 ss << "\n";
7747 std::string result = ss.str();
7748 write(fd, result.c_str(), result.size());
7749}
7750
Andy Hungee58e4a2023-07-07 13:47:37 -07007751void DuplicatingThread::saveOutputTracks()
Eric Laurent81784c32012-11-19 14:55:58 -08007752{
7753 outputTracks = mOutputTracks;
7754}
7755
Andy Hungee58e4a2023-07-07 13:47:37 -07007756void DuplicatingThread::clearOutputTracks()
Eric Laurent81784c32012-11-19 14:55:58 -08007757{
7758 outputTracks.clear();
7759}
7760
Andy Hungee58e4a2023-07-07 13:47:37 -07007761void DuplicatingThread::addOutputTrack(IAfPlaybackThread* thread)
Eric Laurent81784c32012-11-19 14:55:58 -08007762{
Andy Hung972bec12023-08-31 16:13:39 -07007763 audio_utils::lock_guard _l(mutex());
Andy Hungc25b84a2015-01-14 19:04:10 -08007764 // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
7765 // Adjust for thread->sampleRate() to determine minimum buffer frame count.
7766 // Then triple buffer because Threads do not run synchronously and may not be clock locked.
7767 const size_t frameCount =
7768 3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
7769 // TODO: Consider asynchronous sample rate conversion to handle clock disparity
7770 // from different OutputTracks and their associated MixerThreads (e.g. one may
7771 // nearly empty and the other may be dropping data).
7772
Svet Ganov33761132021-05-13 22:51:08 +00007773 // TODO b/182392769: use attribution source util, move to server edge
7774 AttributionSourceState attributionSource = AttributionSourceState();
7775 attributionSource.uid = VALUE_OR_FATAL(legacy2aidl_uid_t_int32_t(
Philip P. Moltmannbda45752020-07-17 16:41:18 -07007776 IPCThreadState::self()->getCallingUid()));
Svet Ganov33761132021-05-13 22:51:08 +00007777 attributionSource.pid = VALUE_OR_FATAL(legacy2aidl_pid_t_int32_t(
Philip P. Moltmannbda45752020-07-17 16:41:18 -07007778 IPCThreadState::self()->getCallingPid()));
Svet Ganov33761132021-05-13 22:51:08 +00007779 attributionSource.token = sp<BBinder>::make();
Andy Hung8d31fd22023-06-26 19:20:57 -07007780 sp<IAfOutputTrack> outputTrack = IAfOutputTrack::create(thread,
Eric Laurent81784c32012-11-19 14:55:58 -08007781 this,
7782 mSampleRate,
Andy Hungc25b84a2015-01-14 19:04:10 -08007783 mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08007784 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08007785 frameCount,
Svet Ganov33761132021-05-13 22:51:08 +00007786 attributionSource);
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07007787 status_t status = outputTrack != 0 ? outputTrack->initCheck() : (status_t) NO_MEMORY;
7788 if (status != NO_ERROR) {
7789 ALOGE("addOutputTrack() initCheck failed %d", status);
7790 return;
Eric Laurent81784c32012-11-19 14:55:58 -08007791 }
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07007792 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
7793 mOutputTracks.add(outputTrack);
7794 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
7795 updateWaitTime_l();
Eric Laurent81784c32012-11-19 14:55:58 -08007796}
7797
Andy Hungee58e4a2023-07-07 13:47:37 -07007798void DuplicatingThread::removeOutputTrack(IAfPlaybackThread* thread)
Eric Laurent81784c32012-11-19 14:55:58 -08007799{
Andy Hung972bec12023-08-31 16:13:39 -07007800 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08007801 for (size_t i = 0; i < mOutputTracks.size(); i++) {
7802 if (mOutputTracks[i]->thread() == thread) {
7803 mOutputTracks[i]->destroy();
7804 mOutputTracks.removeAt(i);
7805 updateWaitTime_l();
Andy Hung8d672e02023-09-15 18:19:28 -07007806 // NO_THREAD_SAFETY_ANALYSIS
7807 // Lambda workaround: as thread != this
7808 // we can safely call the remote thread getOutput.
7809 const bool equalOutput =
7810 [&](){ return thread->getOutput() == mOutput; }();
7811 if (equalOutput) {
7812 mOutput = nullptr;
Eric Laurentf6870ae2015-05-08 10:50:03 -07007813 }
Eric Laurent81784c32012-11-19 14:55:58 -08007814 return;
7815 }
7816 }
Eric Laurentf6870ae2015-05-08 10:50:03 -07007817 ALOGV("removeOutputTrack(): unknown thread: %p", thread);
Eric Laurent81784c32012-11-19 14:55:58 -08007818}
7819
Andy Hungc5007f82023-08-29 14:26:09 -07007820// caller must hold mutex()
Andy Hungee58e4a2023-07-07 13:47:37 -07007821void DuplicatingThread::updateWaitTime_l()
Eric Laurent81784c32012-11-19 14:55:58 -08007822{
7823 mWaitTimeMs = UINT_MAX;
7824 for (size_t i = 0; i < mOutputTracks.size(); i++) {
Andy Hung87c693c2023-07-06 20:56:16 -07007825 const auto strong = mOutputTracks[i]->thread().promote();
Eric Laurent81784c32012-11-19 14:55:58 -08007826 if (strong != 0) {
7827 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
7828 if (waitTimeMs < mWaitTimeMs) {
7829 mWaitTimeMs = waitTimeMs;
7830 }
7831 }
7832 }
7833}
7834
Andy Hungee58e4a2023-07-07 13:47:37 -07007835bool DuplicatingThread::outputsReady()
Eric Laurent81784c32012-11-19 14:55:58 -08007836{
7837 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hung87c693c2023-07-06 20:56:16 -07007838 const auto thread = outputTracks[i]->thread().promote();
Eric Laurent81784c32012-11-19 14:55:58 -08007839 if (thread == 0) {
7840 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
7841 outputTracks[i].get());
7842 return false;
7843 }
Andy Hung87c693c2023-07-06 20:56:16 -07007844 IAfPlaybackThread* const playbackThread = thread->asIAfPlaybackThread().get();
Eric Laurent81784c32012-11-19 14:55:58 -08007845 // see note at standby() declaration
Andy Hung440901d2023-06-29 21:19:25 -07007846 if (playbackThread->inStandby() && !playbackThread->isSuspended()) {
Eric Laurent81784c32012-11-19 14:55:58 -08007847 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
7848 thread.get());
7849 return false;
7850 }
7851 }
7852 return true;
7853}
7854
Andy Hungee58e4a2023-07-07 13:47:37 -07007855void DuplicatingThread::sendMetadataToBackend_l(
Kevin Rocard12381092018-04-11 09:19:59 -07007856 const StreamOutHalInterface::SourceMetadata& metadata)
Kevin Rocard069c2712018-03-29 19:09:14 -07007857{
Kevin Rocard12381092018-04-11 09:19:59 -07007858 for (auto& outputTrack : outputTracks) { // not mOutputTracks
7859 outputTrack->setMetadatas(metadata.tracks);
7860 }
Kevin Rocard069c2712018-03-29 19:09:14 -07007861}
7862
Andy Hungee58e4a2023-07-07 13:47:37 -07007863uint32_t DuplicatingThread::activeSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08007864{
Andy Hung7a6a0f02023-11-29 13:42:08 -08007865 // return half the wait time in microseconds.
7866 return std::min(mWaitTimeMs * 500ULL, (unsigned long long)UINT32_MAX); // prevent overflow.
Eric Laurent81784c32012-11-19 14:55:58 -08007867}
7868
Andy Hungee58e4a2023-07-07 13:47:37 -07007869void DuplicatingThread::cacheParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08007870{
7871 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
7872 updateWaitTime_l();
7873
7874 MixerThread::cacheParameters_l();
7875}
7876
Eric Laurentb3f315a2021-07-13 15:09:05 +02007877// ----------------------------------------------------------------------------
7878
Andy Hungee58e4a2023-07-07 13:47:37 -07007879/* static */
7880sp<IAfPlaybackThread> IAfPlaybackThread::createSpatializerThread(
Andy Hung583043b2023-07-17 17:05:00 -07007881 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hungee58e4a2023-07-07 13:47:37 -07007882 AudioStreamOut* output,
7883 audio_io_handle_t id,
7884 bool systemReady,
7885 audio_config_base_t* mixerConfig) {
Andy Hung583043b2023-07-17 17:05:00 -07007886 return sp<SpatializerThread>::make(afThreadCallback, output, id, systemReady, mixerConfig);
Andy Hungee58e4a2023-07-07 13:47:37 -07007887}
7888
Andy Hung583043b2023-07-17 17:05:00 -07007889SpatializerThread::SpatializerThread(const sp<IAfThreadCallback>& afThreadCallback,
Eric Laurentb3f315a2021-07-13 15:09:05 +02007890 AudioStreamOut* output,
7891 audio_io_handle_t id,
7892 bool systemReady,
7893 audio_config_base_t *mixerConfig)
Andy Hung583043b2023-07-17 17:05:00 -07007894 : MixerThread(afThreadCallback, output, id, systemReady, SPATIALIZER, mixerConfig)
Eric Laurentb3f315a2021-07-13 15:09:05 +02007895{
7896}
7897
Andy Hungee58e4a2023-07-07 13:47:37 -07007898void SpatializerThread::setHalLatencyMode_l() {
Eric Laurent68a40a82022-05-03 18:15:04 +02007899 // if mSupportedLatencyModes is empty, the HAL stream does not support
7900 // latency mode control and we can exit.
7901 if (mSupportedLatencyModes.empty()) {
7902 return;
7903 }
7904 audio_latency_mode_t latencyMode = AUDIO_LATENCY_MODE_FREE;
7905 if (mSupportedLatencyModes.size() == 1) {
7906 // If the HAL only support one latency mode currently, confirm the choice
7907 latencyMode = mSupportedLatencyModes[0];
7908 } else if (mSupportedLatencyModes.size() > 1) {
7909 // Request low latency if:
7910 // - The low latency mode is requested by the spatializer controller
7911 // (mRequestedLatencyMode = AUDIO_LATENCY_MODE_LOW)
7912 // AND
7913 // - At least one active track is spatialized
Eric Laurent68a40a82022-05-03 18:15:04 +02007914 for (const auto& track : mActiveTracks) {
7915 if (track->isSpatialized()) {
Eric Laurentb0241572024-02-01 21:03:49 +01007916 latencyMode = mRequestedLatencyMode;
Eric Laurent68a40a82022-05-03 18:15:04 +02007917 break;
7918 }
7919 }
Eric Laurent68a40a82022-05-03 18:15:04 +02007920 }
7921
7922 if (latencyMode != mSetLatencyMode) {
7923 status_t status = mOutput->stream->setLatencyMode(latencyMode);
Andy Hung4bd53e72022-11-17 17:21:45 -08007924 ALOGD("%s: thread(%d) setLatencyMode(%s) returned %d",
7925 __func__, mId, toString(latencyMode).c_str(), status);
Eric Laurent68a40a82022-05-03 18:15:04 +02007926 if (status == NO_ERROR) {
7927 mSetLatencyMode = latencyMode;
7928 }
7929 }
7930}
7931
Andy Hungee58e4a2023-07-07 13:47:37 -07007932status_t SpatializerThread::setRequestedLatencyMode(audio_latency_mode_t mode) {
Eric Laurentb0241572024-02-01 21:03:49 +01007933 if (mode < 0 || mode >= AUDIO_LATENCY_MODE_CNT) {
Eric Laurent68a40a82022-05-03 18:15:04 +02007934 return BAD_VALUE;
7935 }
Andy Hung972bec12023-08-31 16:13:39 -07007936 audio_utils::lock_guard _l(mutex());
Eric Laurent68a40a82022-05-03 18:15:04 +02007937 mRequestedLatencyMode = mode;
7938 return NO_ERROR;
7939}
7940
Andy Hungee58e4a2023-07-07 13:47:37 -07007941void SpatializerThread::checkOutputStageEffects()
Andy Hung972bec12023-08-31 16:13:39 -07007942NO_THREAD_SAFETY_ANALYSIS
7943// 'createEffect_l' requires holding mutex 'AudioFlinger_Mutex' exclusively
Eric Laurentb3f315a2021-07-13 15:09:05 +02007944{
7945 bool hasVirtualizer = false;
7946 bool hasDownMixer = false;
Andy Hung116bc262023-06-20 18:56:17 -07007947 sp<IAfEffectHandle> finalDownMixer;
Eric Laurentb3f315a2021-07-13 15:09:05 +02007948 {
Andy Hung972bec12023-08-31 16:13:39 -07007949 audio_utils::lock_guard _l(mutex());
Andy Hung116bc262023-06-20 18:56:17 -07007950 sp<IAfEffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_STAGE);
Eric Laurentb3f315a2021-07-13 15:09:05 +02007951 if (chain != 0) {
Eric Laurent1c5e2e32021-08-18 18:50:28 +02007952 hasVirtualizer = chain->getEffectFromType_l(FX_IID_SPATIALIZER) != nullptr;
Eric Laurentb3f315a2021-07-13 15:09:05 +02007953 hasDownMixer = chain->getEffectFromType_l(EFFECT_UIID_DOWNMIX) != nullptr;
7954 }
7955
7956 finalDownMixer = mFinalDownMixer;
7957 mFinalDownMixer.clear();
7958 }
7959
7960 if (hasVirtualizer) {
7961 if (finalDownMixer != nullptr) {
7962 int32_t ret;
Andy Hung116bc262023-06-20 18:56:17 -07007963 finalDownMixer->asIEffect()->disable(&ret);
Eric Laurentb3f315a2021-07-13 15:09:05 +02007964 }
7965 finalDownMixer.clear();
7966 } else if (!hasDownMixer) {
7967 std::vector<effect_descriptor_t> descriptors;
Andy Hung583043b2023-07-17 17:05:00 -07007968 status_t status = mAfThreadCallback->getEffectsFactoryHal()->getDescriptors(
Eric Laurentb3f315a2021-07-13 15:09:05 +02007969 EFFECT_UIID_DOWNMIX, &descriptors);
7970 if (status != NO_ERROR) {
7971 return;
7972 }
7973 ALOG_ASSERT(!descriptors.empty(),
7974 "%s getDescriptors() returned no error but empty list", __func__);
7975
7976 finalDownMixer = createEffect_l(nullptr /*client*/, nullptr /*effectClient*/,
7977 0 /*priority*/, AUDIO_SESSION_OUTPUT_STAGE, &descriptors[0], nullptr /*enabled*/,
Eric Laurentde8caf42021-08-11 17:19:25 +02007978 &status, false /*pinned*/, false /*probe*/, false /*notifyFramesProcessed*/);
Eric Laurentb3f315a2021-07-13 15:09:05 +02007979
7980 if (finalDownMixer == nullptr || (status != NO_ERROR && status != ALREADY_EXISTS)) {
7981 ALOGW("%s error creating downmixer %d", __func__, status);
7982 finalDownMixer.clear();
7983 } else {
7984 int32_t ret;
Andy Hung116bc262023-06-20 18:56:17 -07007985 finalDownMixer->asIEffect()->enable(&ret);
Eric Laurentb3f315a2021-07-13 15:09:05 +02007986 }
7987 }
7988
7989 {
Andy Hung972bec12023-08-31 16:13:39 -07007990 audio_utils::lock_guard _l(mutex());
Eric Laurentb3f315a2021-07-13 15:09:05 +02007991 mFinalDownMixer = finalDownMixer;
7992 }
7993}
7994
Andy Hunge2514462023-12-06 14:59:24 -08007995void SpatializerThread::threadLoop_exit()
7996{
7997 // The Spatializer EffectHandle must be released on the PlaybackThread
7998 // threadLoop() to prevent lock inversion in the SpatializerThread dtor.
7999 mFinalDownMixer.clear();
8000
8001 PlaybackThread::threadLoop_exit();
8002}
8003
Eric Laurent81784c32012-11-19 14:55:58 -08008004// ----------------------------------------------------------------------------
8005// Record
8006// ----------------------------------------------------------------------------
8007
Andy Hung583043b2023-07-17 17:05:00 -07008008sp<IAfRecordThread> IAfRecordThread::create(const sp<IAfThreadCallback>& afThreadCallback,
Andy Hung87c693c2023-07-06 20:56:16 -07008009 AudioStreamIn* input,
8010 audio_io_handle_t id,
8011 bool systemReady) {
Andy Hung583043b2023-07-17 17:05:00 -07008012 return sp<RecordThread>::make(afThreadCallback, input, id, systemReady);
Andy Hung87c693c2023-07-06 20:56:16 -07008013}
8014
Andy Hung583043b2023-07-17 17:05:00 -07008015RecordThread::RecordThread(const sp<IAfThreadCallback>& afThreadCallback,
Eric Laurent81784c32012-11-19 14:55:58 -08008016 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08008017 audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -07008018 bool systemReady
Glenn Kasten46909e72013-02-26 09:20:22 -08008019 ) :
Andy Hung583043b2023-07-17 17:05:00 -07008020 ThreadBase(afThreadCallback, id, RECORD, systemReady, false /* isOut */),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008021 mInput(input),
Mikhail Naganov2534b382019-09-25 13:05:02 -07008022 mSource(mInput),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008023 mActiveTracks(&this->mLocalLog),
8024 mRsmpInBuffer(NULL),
Glenn Kasten1b291842016-07-18 14:55:21 -07008025 // mRsmpInFrames, mRsmpInFramesP2, and mRsmpInFramesOA are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08008026 mRsmpInRear(0)
Glenn Kastenb880f5e2014-05-07 08:43:45 -07008027 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
8028 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008029 // mFastCapture below
8030 , mFastCaptureFutex(0)
8031 // mInputSource
8032 // mPipeSink
8033 // mPipeSource
8034 , mPipeFramesP2(0)
8035 // mPipeMemory
8036 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07008037 , mFastTrackAvail(false)
Eric Laurentd8365c52017-07-16 15:27:05 -07008038 , mBtNrecSuspended(false)
Eric Laurent81784c32012-11-19 14:55:58 -08008039{
Glenn Kastend7dca052015-03-05 16:05:54 -08008040 snprintf(mThreadName, kThreadNameLength, "AudioIn_%X", id);
Andy Hung583043b2023-07-17 17:05:00 -07008041 mNBLogWriter = afThreadCallback->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08008042
George Burgess IVa8f90c12020-05-14 11:27:19 -07008043 if (mInput->audioHwDev != nullptr) {
Andy Hungc8fddf32018-08-08 18:32:37 -07008044 mIsMsdDevice = strcmp(
8045 mInput->audioHwDev->moduleName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0;
8046 }
8047
Glenn Kastendeca2ae2014-02-07 10:25:56 -08008048 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008049
Andy Hungc8fddf32018-08-08 18:32:37 -07008050 // TODO: We may also match on address as well as device type for
8051 // AUDIO_DEVICE_IN_BUS, AUDIO_DEVICE_IN_BLUETOOTH_A2DP, AUDIO_DEVICE_IN_REMOTE_SUBMIX
jiabinc52b1ff2019-10-31 17:20:42 -07008052 // TODO: This property should be ensure that only contains one single device type.
8053 mTimestampCorrectedDevice = (audio_devices_t)property_get_int64(
8054 "audio.timestamp.corrected_input_device",
Andy Hungc8fddf32018-08-08 18:32:37 -07008055 (int64_t)(mIsMsdDevice ? AUDIO_DEVICE_IN_BUS // turn on by default for MSD
8056 : AUDIO_DEVICE_NONE));
8057
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008058 // create an NBAIO source for the HAL input stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07008059 mInputSource = new AudioStreamInSource(input->stream);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008060 size_t numCounterOffers = 0;
8061 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07008062#if !LOG_NDEBUG
Jing Mike537412f2023-03-12 11:01:47 +08008063 [[maybe_unused]] ssize_t index =
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07008064#else
8065 (void)
8066#endif
8067 mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008068 ALOG_ASSERT(index == 0);
8069
8070 // initialize fast capture depending on configuration
8071 bool initFastCapture;
8072 switch (kUseFastCapture) {
8073 case FastCapture_Never:
8074 initFastCapture = false;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008075 ALOGV("%p kUseFastCapture = Never, initFastCapture = false", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008076 break;
8077 case FastCapture_Always:
8078 initFastCapture = true;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008079 ALOGV("%p kUseFastCapture = Always, initFastCapture = true", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008080 break;
8081 case FastCapture_Static:
Sampath6fac2332022-12-16 17:34:37 +11008082 initFastCapture = !mIsMsdDevice // Disable fast capture for MSD BUS devices.
Dean Wheatley8e5d9e42023-11-03 12:37:27 +11008083 && audio_is_linear_pcm(mFormat)
Sampath6fac2332022-12-16 17:34:37 +11008084 && (mFrameCount * 1000) / mSampleRate < kMinNormalCaptureBufferSizeMs;
Dean Wheatley8e5d9e42023-11-03 12:37:27 +11008085 ALOGV("%p kUseFastCapture = Static, format = 0x%x, (%lld * 1000) / %u vs %u, "
8086 "initFastCapture = %d, mIsMsdDevice = %d", this, mFormat, (long long)mFrameCount,
8087 mSampleRate, kMinNormalCaptureBufferSizeMs, initFastCapture, mIsMsdDevice);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008088 break;
8089 // case FastCapture_Dynamic:
8090 }
8091
8092 if (initFastCapture) {
Glenn Kastend198b852015-03-16 14:55:53 -07008093 // create a Pipe for FastCapture to write to, and for us and fast tracks to read from
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008094 NBAIO_Format format = mInputSource->format();
Glenn Kasten1b291842016-07-18 14:55:21 -07008095 // quadruple-buffering of 20 ms each; this ensures we can sleep for 20ms in RecordThread
8096 size_t pipeFramesP2 = roundup(4 * FMS_20 * mSampleRate / 1000);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008097 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008098 void *pipeBuffer = nullptr;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008099 const sp<MemoryDealer> roHeap(readOnlyHeap());
8100 sp<IMemory> pipeMemory;
8101 if ((roHeap == 0) ||
8102 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07008103 (pipeBuffer = pipeMemory->unsecurePointer()) == nullptr) {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008104 ALOGE("not enough memory for pipe buffer size=%zu; "
8105 "roHeap=%p, pipeMemory=%p, pipeBuffer=%p; roHeapSize: %lld",
8106 pipeSize, roHeap.get(), pipeMemory.get(), pipeBuffer,
8107 (long long)kRecordThreadReadOnlyHeapSize);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008108 goto failed;
8109 }
8110 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
8111 memset(pipeBuffer, 0, pipeSize);
8112 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
Andy Hung920f6572022-10-06 12:09:49 -07008113 const NBAIO_Format offersFast[1] = {format};
8114 size_t numCounterOffersFast = 0;
Eric Laurent1e28aaa2023-04-16 19:34:23 +02008115 [[maybe_unused]] ssize_t index2 = pipe->negotiate(offersFast, std::size(offersFast),
Andy Hung920f6572022-10-06 12:09:49 -07008116 nullptr /* counterOffers */, numCounterOffersFast);
Eric Laurent1e28aaa2023-04-16 19:34:23 +02008117 ALOG_ASSERT(index2 == 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008118 mPipeSink = pipe;
8119 PipeReader *pipeReader = new PipeReader(*pipe);
Andy Hung920f6572022-10-06 12:09:49 -07008120 numCounterOffersFast = 0;
Eric Laurent1e28aaa2023-04-16 19:34:23 +02008121 index2 = pipeReader->negotiate(offersFast, std::size(offersFast),
Andy Hung920f6572022-10-06 12:09:49 -07008122 nullptr /* counterOffers */, numCounterOffersFast);
Eric Laurent1e28aaa2023-04-16 19:34:23 +02008123 ALOG_ASSERT(index2 == 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008124 mPipeSource = pipeReader;
8125 mPipeFramesP2 = pipeFramesP2;
8126 mPipeMemory = pipeMemory;
8127
8128 // create fast capture
8129 mFastCapture = new FastCapture();
8130 FastCaptureStateQueue *sq = mFastCapture->sq();
8131#ifdef STATE_QUEUE_DUMP
8132 // FIXME
8133#endif
8134 FastCaptureState *state = sq->begin();
8135 state->mCblk = NULL;
8136 state->mInputSource = mInputSource.get();
8137 state->mInputSourceGen++;
8138 state->mPipeSink = pipe;
8139 state->mPipeSinkGen++;
8140 state->mFrameCount = mFrameCount;
8141 state->mCommand = FastCaptureState::COLD_IDLE;
8142 // already done in constructor initialization list
8143 //mFastCaptureFutex = 0;
8144 state->mColdFutexAddr = &mFastCaptureFutex;
8145 state->mColdGen++;
8146 state->mDumpState = &mFastCaptureDumpState;
8147#ifdef TEE_SINK
8148 // FIXME
8149#endif
Andy Hung583043b2023-07-17 17:05:00 -07008150 mFastCaptureNBLogWriter =
8151 afThreadCallback->newWriter_l(kFastCaptureLogSize, "FastCapture");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008152 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
8153 sq->end();
8154 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
8155
8156 // start the fast capture
8157 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
8158 pid_t tid = mFastCapture->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07008159 sendPrioConfigEvent(getpid(), tid, kPriorityFastCapture, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08008160 stream()->setHalThreadPriority(kPriorityFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008161#ifdef AUDIO_WATCHDOG
8162 // FIXME
8163#endif
8164
Glenn Kasten6e6704c2014-07-03 10:20:00 -07008165 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008166 }
Andy Hung8946a282018-04-19 20:04:56 -07008167#ifdef TEE_SINK
8168 mTee.set(mInputSource->format(), NBAIO_Tee::TEE_FLAG_INPUT_THREAD);
8169 mTee.setId(std::string("_") + std::to_string(mId) + "_C");
8170#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008171failed: ;
8172
8173 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08008174}
8175
Andy Hungee58e4a2023-07-07 13:47:37 -07008176RecordThread::~RecordThread()
Eric Laurent81784c32012-11-19 14:55:58 -08008177{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008178 if (mFastCapture != 0) {
8179 FastCaptureStateQueue *sq = mFastCapture->sq();
8180 FastCaptureState *state = sq->begin();
8181 if (state->mCommand == FastCaptureState::COLD_IDLE) {
8182 int32_t old = android_atomic_inc(&mFastCaptureFutex);
8183 if (old == -1) {
8184 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
8185 }
8186 }
8187 state->mCommand = FastCaptureState::EXIT;
8188 sq->end();
8189 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
8190 mFastCapture->join();
8191 mFastCapture.clear();
8192 }
Andy Hung583043b2023-07-17 17:05:00 -07008193 mAfThreadCallback->unregisterWriter(mFastCaptureNBLogWriter);
8194 mAfThreadCallback->unregisterWriter(mNBLogWriter);
Andy Hung57446612015-04-19 23:56:46 -07008195 free(mRsmpInBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08008196}
8197
Andy Hungee58e4a2023-07-07 13:47:37 -07008198void RecordThread::onFirstRef()
Eric Laurent81784c32012-11-19 14:55:58 -08008199{
Glenn Kastend7dca052015-03-05 16:05:54 -08008200 run(mThreadName, PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08008201}
8202
Andy Hungee58e4a2023-07-07 13:47:37 -07008203void RecordThread::preExit()
Eric Laurent555530a2017-02-07 18:17:24 -08008204{
8205 ALOGV(" preExit()");
Andy Hung972bec12023-08-31 16:13:39 -07008206 audio_utils::lock_guard _l(mutex());
Eric Laurent555530a2017-02-07 18:17:24 -08008207 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07008208 sp<IAfRecordTrack> track = mTracks[i];
Eric Laurent555530a2017-02-07 18:17:24 -08008209 track->invalidate();
8210 }
8211 mActiveTracks.clear();
Andy Hungc5007f82023-08-29 14:26:09 -07008212 mStartStopCV.notify_all();
Eric Laurent555530a2017-02-07 18:17:24 -08008213}
8214
Andy Hungee58e4a2023-07-07 13:47:37 -07008215bool RecordThread::threadLoop()
Eric Laurent81784c32012-11-19 14:55:58 -08008216{
Eric Laurent81784c32012-11-19 14:55:58 -08008217 nsecs_t lastWarning = 0;
8218
8219 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08008220
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008221reacquire_wakelock:
Andy Hung8d31fd22023-06-26 19:20:57 -07008222 sp<IAfRecordTrack> activeTrack;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008223 {
Andy Hung972bec12023-08-31 16:13:39 -07008224 audio_utils::lock_guard _l(mutex());
Andy Hungdae27702016-10-31 14:01:16 -07008225 acquireWakeLock_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008226 }
8227
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008228 // used to request a deferred sleep, to be executed later while mutex is unlocked
8229 uint32_t sleepUs = 0;
8230
Andy Hung95c94a22023-10-20 16:41:18 -07008231 // timestamp correction enable is determined under lock, used in processing step.
8232 bool timestampCorrectionEnabled = false;
8233
Andy Hung446f4df2019-02-21 12:26:41 -08008234 int64_t lastLoopCountRead = -2; // never matches "previous" loop, when loopCount = 0.
8235
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008236 // loop while there is work to do
Andy Hung446f4df2019-02-21 12:26:41 -08008237 for (int64_t loopCount = 0;; ++loopCount) { // loopCount used for statistics tracking
Andy Hung116bc262023-06-20 18:56:17 -07008238 Vector<sp<IAfEffectChain>> effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07008239
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008240 // activeTracks accumulates a copy of a subset of mActiveTracks
Andy Hung8d31fd22023-06-26 19:20:57 -07008241 Vector<sp<IAfRecordTrack>> activeTracks;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008242
Glenn Kasten735f45f2014-08-18 15:51:59 -07008243 // reference to the (first and only) active fast track
Andy Hung8d31fd22023-06-26 19:20:57 -07008244 sp<IAfRecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07008245
Glenn Kasten735f45f2014-08-18 15:51:59 -07008246 // reference to a fast track which is about to be removed
Andy Hung8d31fd22023-06-26 19:20:57 -07008247 sp<IAfRecordTrack> fastTrackToRemove;
Glenn Kasten735f45f2014-08-18 15:51:59 -07008248
Eric Laurent33403f02020-05-29 18:35:06 -07008249 bool silenceFastCapture = false;
8250
Andy Hungc5007f82023-08-29 14:26:09 -07008251 { // scope for mutex()
8252 audio_utils::unique_lock _l(mutex());
Eric Laurent000a4192014-01-29 15:17:32 -08008253
Eric Laurent021cf962014-05-13 10:18:14 -07008254 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008255
Eric Laurent000a4192014-01-29 15:17:32 -08008256 // check exitPending here because checkForNewParameters_l() and
Andy Hungc5007f82023-08-29 14:26:09 -07008257 // checkForNewParameters_l() can temporarily release mutex()
Eric Laurent000a4192014-01-29 15:17:32 -08008258 if (exitPending()) {
8259 break;
8260 }
8261
Eric Laurent5c25d562016-07-13 17:17:45 -07008262 // sleep with mutex unlocked
8263 if (sleepUs > 0) {
Glenn Kastenf9715e42016-07-13 14:02:03 -07008264 ATRACE_BEGIN("sleepC");
Andy Hungc5007f82023-08-29 14:26:09 -07008265 (void)mWaitWorkCV.wait_for(_l, std::chrono::microseconds(sleepUs));
Eric Laurent5c25d562016-07-13 17:17:45 -07008266 ATRACE_END();
8267 sleepUs = 0;
8268 continue;
8269 }
8270
Glenn Kasten2b806402013-11-20 16:37:38 -08008271 // if no active track(s), then standby and release wakelock
8272 size_t size = mActiveTracks.size();
8273 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07008274 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07008275 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08008276 releaseWakeLock_l();
8277 ALOGV("RecordThread: loop stopping");
8278 // go to sleep
Andy Hungc5007f82023-08-29 14:26:09 -07008279 mWaitWorkCV.wait(_l);
Eric Laurent81784c32012-11-19 14:55:58 -08008280 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008281 goto reacquire_wakelock;
8282 }
8283
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008284 bool doBroadcast = false;
Eric Laurent5c25d562016-07-13 17:17:45 -07008285 bool allStopped = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008286 for (size_t i = 0; i < size; ) {
Glenn Kasten9e982352013-08-14 14:39:50 -07008287
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008288 activeTrack = mActiveTracks[i];
8289 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07008290 if (activeTrack->isFastTrack()) {
8291 ALOG_ASSERT(fastTrackToRemove == 0);
8292 fastTrackToRemove = activeTrack;
8293 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008294 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08008295 mActiveTracks.remove(activeTrack);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008296 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07008297 continue;
8298 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008299
Andy Hung8d31fd22023-06-26 19:20:57 -07008300 IAfTrackBase::track_state activeTrackState = activeTrack->state();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008301 switch (activeTrackState) {
8302
Andy Hung8d31fd22023-06-26 19:20:57 -07008303 case IAfTrackBase::PAUSING:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008304 mActiveTracks.remove(activeTrack);
Andy Hung8d31fd22023-06-26 19:20:57 -07008305 activeTrack->setState(IAfTrackBase::PAUSED);
François Gaffie39634e42023-10-17 12:13:32 +02008306 if (activeTrack->isFastTrack()) {
8307 ALOGV("%s fast track is paused, thus removed from active list", __func__);
8308 // Keep a ref on fast track to wait for FastCapture thread to get updated
8309 // state before potential track removal
8310 fastTrackToRemove = activeTrack;
8311 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008312 doBroadcast = true;
8313 size--;
8314 continue;
8315
Andy Hung8d31fd22023-06-26 19:20:57 -07008316 case IAfTrackBase::STARTING_1:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008317 sleepUs = 10000;
8318 i++;
Eric Laurent5c25d562016-07-13 17:17:45 -07008319 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008320 continue;
8321
Andy Hung8d31fd22023-06-26 19:20:57 -07008322 case IAfTrackBase::STARTING_2:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008323 doBroadcast = true;
Andy Hungcf10d742020-04-28 15:38:24 -07008324 if (mStandby) {
8325 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07008326 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -07008327 mStandby = false;
8328 }
Andy Hung8d31fd22023-06-26 19:20:57 -07008329 activeTrack->setState(IAfTrackBase::ACTIVE);
Eric Laurent5c25d562016-07-13 17:17:45 -07008330 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008331 break;
8332
Andy Hung8d31fd22023-06-26 19:20:57 -07008333 case IAfTrackBase::ACTIVE:
Eric Laurent5c25d562016-07-13 17:17:45 -07008334 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008335 break;
8336
Andy Hung8d31fd22023-06-26 19:20:57 -07008337 case IAfTrackBase::IDLE: // cannot be on ActiveTracks if idle
8338 case IAfTrackBase::PAUSED: // cannot be on ActiveTracks if paused
8339 case IAfTrackBase::STOPPED: // cannot be on ActiveTracks if destroyed/terminated
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008340 default:
Andy Hungce685402018-10-05 17:23:27 -07008341 LOG_ALWAYS_FATAL("%s: Unexpected active track state:%d, id:%d, tracks:%zu",
8342 __func__, activeTrackState, activeTrack->id(), size);
Glenn Kasten9e982352013-08-14 14:39:50 -07008343 }
Glenn Kasten9e982352013-08-14 14:39:50 -07008344
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008345 if (activeTrack->isFastTrack()) {
8346 ALOG_ASSERT(!mFastTrackAvail);
8347 ALOG_ASSERT(fastTrack == 0);
Eric Laurent33403f02020-05-29 18:35:06 -07008348 // if the active fast track is silenced either:
8349 // 1) silence the whole capture from fast capture buffer if this is
8350 // the only active track
8351 // 2) invalidate this track: this will cause the client to reconnect and possibly
8352 // be invalidated again until unsilenced
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008353 bool invalidate = false;
Eric Laurent33403f02020-05-29 18:35:06 -07008354 if (activeTrack->isSilenced()) {
8355 if (size > 1) {
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008356 invalidate = true;
Eric Laurent33403f02020-05-29 18:35:06 -07008357 } else {
8358 silenceFastCapture = true;
8359 }
8360 }
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008361 // Invalidate fast tracks if access to audio history is required as this is not
8362 // possible with fast tracks. Once the fast track has been invalidated, no new
8363 // fast track will be created until mMaxSharedAudioHistoryMs is cleared.
8364 if (mMaxSharedAudioHistoryMs != 0) {
8365 invalidate = true;
8366 }
8367 if (invalidate) {
8368 activeTrack->invalidate();
8369 ALOG_ASSERT(fastTrackToRemove == 0);
8370 fastTrackToRemove = activeTrack;
8371 removeTrack_l(activeTrack);
8372 mActiveTracks.remove(activeTrack);
8373 size--;
8374 continue;
8375 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008376 fastTrack = activeTrack;
8377 }
Eric Laurent33403f02020-05-29 18:35:06 -07008378
8379 activeTracks.add(activeTrack);
8380 i++;
8381
Glenn Kasten9e982352013-08-14 14:39:50 -07008382 }
Eric Laurent5c25d562016-07-13 17:17:45 -07008383
Andy Hungab65b182023-09-06 19:41:47 -07008384 mActiveTracks.updatePowerState_l(this);
Andy Hungdae27702016-10-31 14:01:16 -07008385
Kevin Rocard069c2712018-03-29 19:09:14 -07008386 updateMetadata_l();
8387
Eric Laurent5c25d562016-07-13 17:17:45 -07008388 if (allStopped) {
8389 standbyIfNotAlreadyInStandby();
8390 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008391 if (doBroadcast) {
Andy Hungc5007f82023-08-29 14:26:09 -07008392 mStartStopCV.notify_all();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008393 }
8394
8395 // sleep if there are no active tracks to process
Eric Tan39ec8d62018-07-24 09:49:29 -07008396 if (activeTracks.isEmpty()) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008397 if (sleepUs == 0) {
8398 sleepUs = kRecordThreadSleepUs;
8399 }
8400 continue;
8401 }
8402 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07008403
Andy Hung95c94a22023-10-20 16:41:18 -07008404 timestampCorrectionEnabled = isTimestampCorrectionEnabled_l();
Eric Laurent81784c32012-11-19 14:55:58 -08008405 lockEffectChains_l(effectChains);
8406 }
8407
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008408 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07008409
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008410 size_t size = effectChains.size();
8411 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008412 // thread mutex is not locked, but effect chain is locked
8413 effectChains[i]->process_l();
8414 }
8415
Glenn Kasten735f45f2014-08-18 15:51:59 -07008416 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008417 if (mFastCapture != 0) {
8418 FastCaptureStateQueue *sq = mFastCapture->sq();
8419 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07008420 bool didModify = false;
8421 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008422 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
8423 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
8424 if (state->mCommand == FastCaptureState::COLD_IDLE) {
8425 int32_t old = android_atomic_inc(&mFastCaptureFutex);
8426 if (old == -1) {
8427 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
8428 }
8429 }
8430 state->mCommand = FastCaptureState::READ_WRITE;
8431#if 0 // FIXME
Andy Hung583043b2023-07-17 17:05:00 -07008432 mFastCaptureDumpState.increaseSamplingN(mAfThreadCallback->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08008433 FastThreadDumpState::kSamplingNforLowRamDevice :
8434 FastThreadDumpState::kSamplingN);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008435#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07008436 didModify = true;
8437 }
8438 audio_track_cblk_t *cblkOld = state->mCblk;
8439 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
8440 if (cblkNew != cblkOld) {
8441 state->mCblk = cblkNew;
8442 // block until acked if removing a fast track
8443 if (cblkOld != NULL) {
8444 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
8445 }
8446 didModify = true;
8447 }
jiabin01c8f562018-07-19 17:47:28 -07008448 AudioBufferProvider* abp = (fastTrack != 0 && fastTrack->isPatchTrack()) ?
8449 reinterpret_cast<AudioBufferProvider*>(fastTrack.get()) : nullptr;
8450 if (state->mFastPatchRecordBufferProvider != abp) {
8451 state->mFastPatchRecordBufferProvider = abp;
8452 state->mFastPatchRecordFormat = fastTrack == 0 ?
8453 AUDIO_FORMAT_INVALID : fastTrack->format();
8454 didModify = true;
8455 }
Eric Laurent33403f02020-05-29 18:35:06 -07008456 if (state->mSilenceCapture != silenceFastCapture) {
8457 state->mSilenceCapture = silenceFastCapture;
8458 didModify = true;
8459 }
Glenn Kasten735f45f2014-08-18 15:51:59 -07008460 sq->end(didModify);
8461 if (didModify) {
8462 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008463#if 0
8464 if (kUseFastCapture == FastCapture_Dynamic) {
8465 mNormalSource = mPipeSource;
8466 }
8467#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008468 }
8469 }
8470
Glenn Kasten735f45f2014-08-18 15:51:59 -07008471 // now run the fast track destructor with thread mutex unlocked
8472 fastTrackToRemove.clear();
8473
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008474 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
8475 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
8476 // slow, then this RecordThread will overrun by not calling HAL read often enough.
8477 // If destination is non-contiguous, first read past the nominal end of buffer, then
8478 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008479
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008480 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Andy Hung920f6572022-10-06 12:09:49 -07008481 ssize_t framesRead = 0; // not needed, remove clang-tidy warning.
Andy Hung446f4df2019-02-21 12:26:41 -08008482 const int64_t lastIoBeginNs = systemTime(); // start IO timing
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008483
8484 // If an NBAIO source is present, use it to read the normal capture's data
8485 if (mPipeSource != 0) {
Andy Hung156317a2018-08-02 11:49:29 -07008486 size_t framesToRead = min(mRsmpInFramesOA - rear, mRsmpInFramesP2 / 2);
Andy Hungd5b638f2018-04-30 13:56:10 -07008487
8488 // The audio fifo read() returns OVERRUN on overflow, and advances the read pointer
8489 // to the full buffer point (clearing the overflow condition). Upon OVERRUN error,
8490 // we immediately retry the read() to get data and prevent another overflow.
8491 for (int retries = 0; retries <= 2; ++retries) {
8492 ALOGW_IF(retries > 0, "overrun on read from pipe, retry #%d", retries);
8493 framesRead = mPipeSource->read((uint8_t*)mRsmpInBuffer + rear * mFrameSize,
8494 framesToRead);
8495 if (framesRead != OVERRUN) break;
8496 }
8497
Andy Hung7a3dc6b2018-05-01 16:39:51 -07008498 const ssize_t availableToRead = mPipeSource->availableToRead();
8499 if (availableToRead >= 0) {
Robert Wu06db0a32021-08-10 19:05:34 +00008500 mMonopipePipeDepthStats.add(availableToRead);
Glenn Kastena2f59b32020-08-03 16:37:24 -07008501 // PipeSource is the primary clock. It is up to the AudioRecord client to keep up.
Andy Hung7a3dc6b2018-05-01 16:39:51 -07008502 LOG_ALWAYS_FATAL_IF((size_t)availableToRead > mPipeFramesP2,
8503 "more frames to read than fifo size, %zd > %zu",
8504 availableToRead, mPipeFramesP2);
8505 const size_t pipeFramesFree = mPipeFramesP2 - availableToRead;
8506 const size_t sleepFrames = min(pipeFramesFree, mRsmpInFramesP2) / 2;
8507 ALOGVV("mPipeFramesP2:%zu mRsmpInFramesP2:%zu sleepFrames:%zu availableToRead:%zd",
8508 mPipeFramesP2, mRsmpInFramesP2, sleepFrames, availableToRead);
Glenn Kasten1b291842016-07-18 14:55:21 -07008509 sleepUs = (sleepFrames * 1000000LL) / mSampleRate;
8510 }
8511 if (framesRead < 0) {
8512 status_t status = (status_t) framesRead;
8513 switch (status) {
8514 case OVERRUN:
8515 ALOGW("overrun on read from pipe");
8516 framesRead = 0;
8517 break;
8518 case NEGOTIATE:
8519 ALOGE("re-negotiation is needed");
8520 framesRead = -1; // Will cause an attempt to recover.
8521 break;
8522 default:
8523 ALOGE("unknown error %d on read from pipe", status);
8524 break;
8525 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008526 }
8527 // otherwise use the HAL / AudioStreamIn directly
8528 } else {
Glenn Kastenec6a7032016-03-14 07:40:23 -07008529 ATRACE_BEGIN("read");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008530 size_t bytesRead;
Mikhail Naganov2534b382019-09-25 13:05:02 -07008531 status_t result = mSource->read(
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008532 (uint8_t*)mRsmpInBuffer + rear * mFrameSize, mBufferSize, &bytesRead);
Glenn Kastenec6a7032016-03-14 07:40:23 -07008533 ATRACE_END();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008534 if (result < 0) {
8535 framesRead = result;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008536 } else {
8537 framesRead = bytesRead / mFrameSize;
8538 }
8539 }
8540
Andy Hung446f4df2019-02-21 12:26:41 -08008541 const int64_t lastIoEndNs = systemTime(); // end IO timing
8542
Andy Hung3f0c9022016-01-15 17:49:46 -08008543 // Update server timestamp with server stats
8544 // systemTime() is optional if the hardware supports timestamps.
Andy Hung743f6402020-06-03 13:17:04 -07008545 if (framesRead >= 0) {
8546 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += framesRead;
8547 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = lastIoEndNs;
8548 }
Andy Hung3f0c9022016-01-15 17:49:46 -08008549
8550 // Update server timestamp with kernel stats
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008551 if (mPipeSource.get() == nullptr /* don't obtain for FastCapture, could block */) {
Andy Hung3f0c9022016-01-15 17:49:46 -08008552 int64_t position, time;
Andy Hung2e2c0bb2018-06-11 19:13:11 -07008553 if (mStandby) {
Dean Wheatley12473e92021-03-18 23:00:55 +11008554 mTimestampVerifier.discontinuity(audio_is_linear_pcm(mFormat) ?
8555 mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS :
8556 mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Mikhail Naganov2534b382019-09-25 13:05:02 -07008557 } else if (mSource->getCapturePosition(&position, &time) == NO_ERROR
Andy Hungc8fddf32018-08-08 18:32:37 -07008558 && time > mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]) {
8559
8560 mTimestampVerifier.add(position, time, mSampleRate);
Andy Hungab65b182023-09-06 19:41:47 -07008561 if (timestampCorrectionEnabled) {
Dean Wheatley56a583e2020-05-08 15:12:17 +10008562 ALOGVV("TS_BEFORE: %d %lld %lld",
Andy Hungc8fddf32018-08-08 18:32:37 -07008563 id(), (long long)time, (long long)position);
8564 auto correctedTimestamp = mTimestampVerifier.getLastCorrectedTimestamp();
8565 position = correctedTimestamp.mFrames;
8566 time = correctedTimestamp.mTimeNs;
Dean Wheatley56a583e2020-05-08 15:12:17 +10008567 ALOGVV("TS_AFTER: %d %lld %lld",
Andy Hungc8fddf32018-08-08 18:32:37 -07008568 id(), (long long)time, (long long)position);
8569 }
8570
Andy Hung3f0c9022016-01-15 17:49:46 -08008571 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = position;
8572 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] = time;
8573 // Note: In general record buffers should tend to be empty in
8574 // a properly running pipeline.
8575 //
8576 // Also, it is not advantageous to call get_presentation_position during the read
8577 // as the read obtains a lock, preventing the timestamp call from executing.
Andy Hung2e2c0bb2018-06-11 19:13:11 -07008578 } else {
8579 mTimestampVerifier.error();
Andy Hung3f0c9022016-01-15 17:49:46 -08008580 }
8581 }
Andy Hunge6c37112019-02-26 17:38:10 -08008582
8583 // From the timestamp, input read latency is negative output write latency.
8584 const audio_input_flags_t flags = mInput != NULL ? mInput->flags : AUDIO_INPUT_FLAG_NONE;
Andy Hung8d31fd22023-06-26 19:20:57 -07008585 const double latencyMs = IAfRecordTrack::checkServerLatencySupported(mFormat, flags)
Andy Hunge6c37112019-02-26 17:38:10 -08008586 ? - mTimestamp.getOutputServerLatencyMs(mSampleRate) : 0.;
8587 if (latencyMs != 0.) { // note 0. means timestamp is empty.
8588 mLatencyMs.add(latencyMs);
8589 }
8590
Andy Hung3f0c9022016-01-15 17:49:46 -08008591 // Use this to track timestamp information
8592 // ALOGD("%s", mTimestamp.toString().c_str());
8593
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008594 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07008595 ALOGE("read failed: framesRead=%zd", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008596 // Force input into standby so that it tries to recover at next read attempt
8597 inputStandBy();
8598 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008599 }
8600 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008601 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008602 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008603 ALOG_ASSERT(framesRead > 0);
Andy Hung6427e442018-08-09 12:51:02 -07008604 mFramesRead += framesRead;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008605
Andy Hung8946a282018-04-19 20:04:56 -07008606#ifdef TEE_SINK
8607 (void)mTee.write((uint8_t*)mRsmpInBuffer + rear * mFrameSize, framesRead);
8608#endif
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008609 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008610 {
8611 size_t part1 = mRsmpInFramesP2 - rear;
8612 if ((size_t) framesRead > part1) {
Andy Hung57446612015-04-19 23:56:46 -07008613 memcpy(mRsmpInBuffer, (uint8_t*)mRsmpInBuffer + mRsmpInFramesP2 * mFrameSize,
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008614 (framesRead - part1) * mFrameSize);
8615 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008616 }
Dean Wheatleyfd56e812020-11-06 22:32:21 +11008617 mRsmpInRear = audio_utils::safe_add_overflow(mRsmpInRear, (int32_t)framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008618
8619 size = activeTracks.size();
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008620
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008621 // loop over each active track
8622 for (size_t i = 0; i < size; i++) {
8623 activeTrack = activeTracks[i];
8624
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008625 // skip fast tracks, as those are handled directly by FastCapture
8626 if (activeTrack->isFastTrack()) {
8627 continue;
8628 }
8629
Andy Hung73c02e42015-03-29 01:13:58 -07008630 // TODO: This code probably should be moved to RecordTrack.
Andy Hung97a893e2015-03-29 01:03:07 -07008631 // TODO: Update the activeTrack buffer converter in case of reconfigure.
8632
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008633 enum {
8634 OVERRUN_UNKNOWN,
8635 OVERRUN_TRUE,
8636 OVERRUN_FALSE
8637 } overrun = OVERRUN_UNKNOWN;
8638
8639 // loop over getNextBuffer to handle circular sink
8640 for (;;) {
8641
Andy Hung8d31fd22023-06-26 19:20:57 -07008642 activeTrack->sinkBuffer().frameCount = ~0;
8643 status_t status = activeTrack->getNextBuffer(&activeTrack->sinkBuffer());
8644 size_t framesOut = activeTrack->sinkBuffer().frameCount;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008645 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
8646
Andy Hung73c02e42015-03-29 01:13:58 -07008647 // check available frames and handle overrun conditions
8648 // if the record track isn't draining fast enough.
8649 bool hasOverrun;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008650 size_t framesIn;
Andy Hung8d31fd22023-06-26 19:20:57 -07008651 activeTrack->resamplerBufferProvider()->sync(&framesIn, &hasOverrun);
Andy Hung73c02e42015-03-29 01:13:58 -07008652 if (hasOverrun) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008653 overrun = OVERRUN_TRUE;
8654 }
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08008655 if (framesOut == 0 || framesIn == 0) {
8656 break;
8657 }
8658
Andy Hung6770c6f2015-04-07 13:43:36 -07008659 // Don't allow framesOut to be larger than what is possible with resampling
8660 // from framesIn.
8661 // This isn't strictly necessary but helps limit buffer resizing in
8662 // RecordBufferConverter. TODO: remove when no longer needed.
Dean Wheatleydea650c2023-11-01 22:49:01 +11008663 if (audio_is_linear_pcm(activeTrack->format())) {
8664 framesOut = min(framesOut,
8665 destinationFramesPossible(
8666 framesIn, mSampleRate, activeTrack->sampleRate()));
8667 }
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008668
8669 if (activeTrack->isDirect()) {
Daniel Van Veen9e2376e2018-09-27 14:37:58 +10008670 // No RecordBufferConverter used for direct streams. Pass
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008671 // straight from RecordThread buffer to RecordTrack buffer.
8672 AudioBufferProvider::Buffer buffer;
8673 buffer.frameCount = framesOut;
Andy Hung920f6572022-10-06 12:09:49 -07008674 const status_t getNextBufferStatus =
Andy Hung8d31fd22023-06-26 19:20:57 -07008675 activeTrack->resamplerBufferProvider()->getNextBuffer(&buffer);
Andy Hung920f6572022-10-06 12:09:49 -07008676 if (getNextBufferStatus == OK && buffer.frameCount != 0) {
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008677 ALOGV_IF(buffer.frameCount != framesOut,
8678 "%s() read less than expected (%zu vs %zu)",
8679 __func__, buffer.frameCount, framesOut);
8680 framesOut = buffer.frameCount;
Andy Hung8d31fd22023-06-26 19:20:57 -07008681 memcpy(activeTrack->sinkBuffer().raw,
8682 buffer.raw, buffer.frameCount * mFrameSize);
8683 activeTrack->resamplerBufferProvider()->releaseBuffer(&buffer);
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008684 } else {
8685 framesOut = 0;
8686 ALOGE("%s() cannot fill request, status: %d, frameCount: %zu",
Andy Hung920f6572022-10-06 12:09:49 -07008687 __func__, getNextBufferStatus, buffer.frameCount);
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008688 }
8689 } else {
8690 // process frames from the RecordThread buffer provider to the RecordTrack
8691 // buffer
Andy Hung8d31fd22023-06-26 19:20:57 -07008692 framesOut = activeTrack->recordBufferConverter()->convert(
8693 activeTrack->sinkBuffer().raw,
8694 activeTrack->resamplerBufferProvider(),
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008695 framesOut);
8696 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008697
8698 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
8699 overrun = OVERRUN_FALSE;
8700 }
8701
Andy Hung93bb5732023-05-04 21:16:34 -07008702 // MediaSyncEvent handling: Synchronize AudioRecord to AudioTrack completion.
8703 const ssize_t framesToDrop =
Andy Hung8d31fd22023-06-26 19:20:57 -07008704 activeTrack->synchronizedRecordState().updateRecordFrames(framesOut);
Andy Hung93bb5732023-05-04 21:16:34 -07008705 if (framesToDrop == 0) {
8706 // no sync event, process normally, otherwise ignore.
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008707 if (framesOut > 0) {
Andy Hung8d31fd22023-06-26 19:20:57 -07008708 activeTrack->sinkBuffer().frameCount = framesOut;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008709 // Sanitize before releasing if the track has no access to the source data
8710 // An idle UID receives silence from non virtual devices until active
8711 if (activeTrack->isSilenced()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07008712 memset(activeTrack->sinkBuffer().raw,
8713 0, framesOut * activeTrack->frameSize());
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008714 }
Andy Hung8d31fd22023-06-26 19:20:57 -07008715 activeTrack->releaseBuffer(&activeTrack->sinkBuffer());
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008716 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008717 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008718 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008719 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008720 }
8721 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008722
8723 switch (overrun) {
8724 case OVERRUN_TRUE:
8725 // client isn't retrieving buffers fast enough
8726 if (!activeTrack->setOverflow()) {
8727 nsecs_t now = systemTime();
8728 // FIXME should lastWarning per track?
8729 if ((now - lastWarning) > kWarningThrottleNs) {
8730 ALOGW("RecordThread: buffer overflow");
8731 lastWarning = now;
8732 }
8733 }
8734 break;
8735 case OVERRUN_FALSE:
8736 activeTrack->clearOverflow();
8737 break;
8738 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008739 break;
8740 }
8741
Andy Hung3f0c9022016-01-15 17:49:46 -08008742 // update frame information and push timestamp out
8743 activeTrack->updateTrackFrameInfo(
Andy Hung8d31fd22023-06-26 19:20:57 -07008744 activeTrack->serverProxy()->framesReleased(),
Andy Hung3f0c9022016-01-15 17:49:46 -08008745 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER],
8746 mSampleRate, mTimestamp);
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008747 }
8748
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008749unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08008750 // enable changes in effect chain
8751 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07008752 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurentcccbc762019-04-05 14:20:05 -07008753 if (audio_has_proportional_frames(mFormat)
8754 && loopCount == lastLoopCountRead + 1) {
8755 const int64_t readPeriodNs = lastIoEndNs - mLastIoEndNs;
8756 const double jitterMs =
8757 TimestampVerifier<int64_t, int64_t>::computeJitterMs(
8758 {framesRead, readPeriodNs},
8759 {0, 0} /* lastTimestamp */, mSampleRate);
8760 const double processMs = (lastIoBeginNs - mLastIoEndNs) * 1e-6;
8761
Andy Hung972bec12023-08-31 16:13:39 -07008762 audio_utils::lock_guard _l(mutex());
Eric Laurentcccbc762019-04-05 14:20:05 -07008763 mIoJitterMs.add(jitterMs);
8764 mProcessTimeMs.add(processMs);
8765 }
8766 // update timing info.
8767 mLastIoBeginNs = lastIoBeginNs;
8768 mLastIoEndNs = lastIoEndNs;
8769 lastLoopCountRead = loopCount;
Eric Laurent81784c32012-11-19 14:55:58 -08008770 }
8771
Glenn Kasten93e471f2013-08-19 08:40:07 -07008772 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08008773
8774 {
Andy Hung972bec12023-08-31 16:13:39 -07008775 audio_utils::lock_guard _l(mutex());
Eric Laurent9a54bc22013-09-09 09:08:44 -07008776 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07008777 sp<IAfRecordTrack> track = mTracks[i];
Eric Laurent9a54bc22013-09-09 09:08:44 -07008778 track->invalidate();
8779 }
Glenn Kasten2b806402013-11-20 16:37:38 -08008780 mActiveTracks.clear();
Andy Hungc5007f82023-08-29 14:26:09 -07008781 mStartStopCV.notify_all();
Eric Laurent81784c32012-11-19 14:55:58 -08008782 }
8783
8784 releaseWakeLock();
8785
8786 ALOGV("RecordThread %p exiting", this);
8787 return false;
8788}
8789
Andy Hungee58e4a2023-07-07 13:47:37 -07008790void RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08008791{
8792 if (!mStandby) {
8793 inputStandBy();
Andy Hungcf10d742020-04-28 15:38:24 -07008794 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07008795 mThreadSnapshot.onEnd();
Eric Laurent81784c32012-11-19 14:55:58 -08008796 mStandby = true;
8797 }
8798}
8799
Andy Hungee58e4a2023-07-07 13:47:37 -07008800void RecordThread::inputStandBy()
Eric Laurent81784c32012-11-19 14:55:58 -08008801{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008802 // Idle the fast capture if it's currently running
8803 if (mFastCapture != 0) {
8804 FastCaptureStateQueue *sq = mFastCapture->sq();
8805 FastCaptureState *state = sq->begin();
8806 if (!(state->mCommand & FastCaptureState::IDLE)) {
8807 state->mCommand = FastCaptureState::COLD_IDLE;
8808 state->mColdFutexAddr = &mFastCaptureFutex;
8809 state->mColdGen++;
8810 mFastCaptureFutex = 0;
8811 sq->end();
8812 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
8813 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
8814#if 0
8815 if (kUseFastCapture == FastCapture_Dynamic) {
8816 // FIXME
8817 }
8818#endif
8819#ifdef AUDIO_WATCHDOG
8820 // FIXME
8821#endif
8822 } else {
8823 sq->end(false /*didModify*/);
8824 }
8825 }
Mikhail Naganov2534b382019-09-25 13:05:02 -07008826 status_t result = mSource->standby();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008827 ALOGE_IF(result != OK, "Error when putting input stream into standby: %d", result);
Andy Hungad6d52d2016-07-18 13:42:03 -07008828
8829 // If going into standby, flush the pipe source.
8830 if (mPipeSource.get() != nullptr) {
8831 const ssize_t flushed = mPipeSource->flush();
8832 if (flushed > 0) {
8833 ALOGV("Input standby flushed PipeSource %zd frames", flushed);
8834 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += flushed;
8835 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
8836 }
8837 }
Eric Laurent81784c32012-11-19 14:55:58 -08008838}
8839
Andy Hungc5007f82023-08-29 14:26:09 -07008840// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07008841sp<IAfRecordTrack> RecordThread::createRecordTrack_l(
Andy Hung88035ac2023-06-27 17:05:02 -07008842 const sp<Client>& client,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07008843 const audio_attributes_t& attr,
Eric Laurentf14db3c2017-12-08 14:20:36 -08008844 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08008845 audio_format_t format,
8846 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08008847 size_t *pFrameCount,
Glenn Kastend848eb42016-03-08 13:42:11 -08008848 audio_session_t sessionId,
Eric Laurentf14db3c2017-12-08 14:20:36 -08008849 size_t *pNotificationFrameCount,
Eric Laurent09f1ed22019-04-24 17:45:17 -07008850 pid_t creatorPid,
Svet Ganov33761132021-05-13 22:51:08 +00008851 const AttributionSourceState& attributionSource,
Eric Laurent05067782016-06-01 18:27:28 -07008852 audio_input_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08008853 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08008854 status_t *status,
Eric Laurentec376dc2021-04-08 20:41:22 +02008855 audio_port_handle_t portId,
8856 int32_t maxSharedAudioHistoryMs)
Eric Laurent81784c32012-11-19 14:55:58 -08008857{
Glenn Kasten74935e42013-12-19 08:56:45 -08008858 size_t frameCount = *pFrameCount;
Eric Laurentf14db3c2017-12-08 14:20:36 -08008859 size_t notificationFrameCount = *pNotificationFrameCount;
Andy Hung8d31fd22023-06-26 19:20:57 -07008860 sp<IAfRecordTrack> track;
Eric Laurent81784c32012-11-19 14:55:58 -08008861 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07008862 audio_input_flags_t inputFlags = mInput->flags;
Eric Laurentf14db3c2017-12-08 14:20:36 -08008863 audio_input_flags_t requestedFlags = *flags;
8864 uint32_t sampleRate;
8865
8866 lStatus = initCheck();
8867 if (lStatus != NO_ERROR) {
8868 ALOGE("createRecordTrack_l() audio driver not initialized");
8869 goto Exit;
8870 }
8871
Mikhail Naganovce9f2652018-07-16 11:09:24 -07008872 if (!audio_is_linear_pcm(mFormat) && (*flags & AUDIO_INPUT_FLAG_DIRECT) == 0) {
8873 ALOGE("createRecordTrack_l() on an encoded stream requires AUDIO_INPUT_FLAG_DIRECT");
8874 lStatus = BAD_VALUE;
8875 goto Exit;
8876 }
8877
Eric Laurentec376dc2021-04-08 20:41:22 +02008878 if (maxSharedAudioHistoryMs != 0) {
Eric Laurent9ff3e532022-11-10 16:04:44 +01008879 if (!captureHotwordAllowed(attributionSource)) {
Eric Laurentec376dc2021-04-08 20:41:22 +02008880 lStatus = PERMISSION_DENIED;
8881 goto Exit;
8882 }
Eric Laurentec376dc2021-04-08 20:41:22 +02008883 if (maxSharedAudioHistoryMs < 0
Andy Hung25a80ac2023-07-19 12:47:35 -07008884 || maxSharedAudioHistoryMs > kMaxSharedAudioHistoryMs) {
Eric Laurentec376dc2021-04-08 20:41:22 +02008885 lStatus = BAD_VALUE;
8886 goto Exit;
8887 }
8888 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08008889 if (*pSampleRate == 0) {
8890 *pSampleRate = mSampleRate;
8891 }
8892 sampleRate = *pSampleRate;
Eric Laurent05067782016-06-01 18:27:28 -07008893
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008894 // special case for FAST flag considered OK if fast capture is present and access to
8895 // audio history is not required
8896 if (hasFastCapture() && mMaxSharedAudioHistoryMs == 0) {
Eric Laurent05067782016-06-01 18:27:28 -07008897 inputFlags = (audio_input_flags_t)(inputFlags | AUDIO_INPUT_FLAG_FAST);
8898 }
8899
Eric Laurentf14db3c2017-12-08 14:20:36 -08008900 // Check if requested flags are compatible with input stream flags
Eric Laurent05067782016-06-01 18:27:28 -07008901 if ((*flags & inputFlags) != *flags) {
8902 ALOGW("createRecordTrack_l(): mismatch between requested flags (%08x) and"
8903 " input flags (%08x)",
8904 *flags, inputFlags);
8905 *flags = (audio_input_flags_t)(*flags & inputFlags);
8906 }
Eric Laurent81784c32012-11-19 14:55:58 -08008907
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008908 // client expresses a preference for FAST and no access to audio history,
8909 // but we get the final say
8910 if (*flags & AUDIO_INPUT_FLAG_FAST && maxSharedAudioHistoryMs == 0) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07008911 if (
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07008912 // we formerly checked for a callback handler (non-0 tid),
8913 // but that is no longer required for TRANSFER_OBTAIN mode
jiabinb00edc32021-08-16 16:27:54 +00008914 // No need to match hardware format, format conversion will be done in client side.
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07008915 //
Phil Burk7ed66a12019-04-18 13:20:30 -07008916 // Frame count is not specified (0), or is less than or equal the pipe depth.
8917 // It is OK to provide a higher capacity than requested.
8918 // We will force it to mPipeFramesP2 below.
8919 (frameCount <= mPipeFramesP2) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07008920 // PCM data
8921 audio_is_linear_pcm(format) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08008922 // hardware channel mask
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008923 (channelMask == mChannelMask) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08008924 // hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07008925 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07008926 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008927 hasFastCapture() &&
8928 // there are sufficient fast track slots available
8929 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07008930 ) {
Eric Laurent4c415062016-06-17 16:14:16 -07008931 // check compatibility with audio effects.
Andy Hung972bec12023-08-31 16:13:39 -07008932 audio_utils::lock_guard _l(mutex());
Eric Laurent4c415062016-06-17 16:14:16 -07008933 // Do not accept FAST flag if the session has software effects
Andy Hung116bc262023-06-20 18:56:17 -07008934 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent4c415062016-06-17 16:14:16 -07008935 if (chain != 0) {
Andy Hungd3bb0ad2016-10-11 17:16:43 -07008936 audio_input_flags_t old = *flags;
8937 chain->checkInputFlagCompatibility(flags);
8938 if (old != *flags) {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008939 ALOGV("%p AUDIO_INPUT_FLAGS denied by effect old=%#x new=%#x",
8940 this, (int)old, (int)*flags);
Eric Laurent4c415062016-06-17 16:14:16 -07008941 }
8942 }
Eric Laurent122f7e72016-06-29 11:53:29 -07008943 ALOGV_IF((*flags & AUDIO_INPUT_FLAG_FAST) != 0,
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008944 "%p AUDIO_INPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
8945 this, frameCount, mFrameCount);
Glenn Kasten90e58b12013-07-31 16:16:02 -07008946 } else {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008947 ALOGV("%p AUDIO_INPUT_FLAG_FAST denied: frameCount=%zu mFrameCount=%zu mPipeFramesP2=%zu "
8948 "format=%#x isLinear=%d mFormat=%#x channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008949 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008950 this, frameCount, mFrameCount, mPipeFramesP2,
8951 format, audio_is_linear_pcm(format), mFormat, channelMask, sampleRate, mSampleRate,
Glenn Kasten74105912014-07-03 12:28:53 -07008952 hasFastCapture(), tid, mFastTrackAvail);
Eric Laurent05067782016-06-01 18:27:28 -07008953 *flags = (audio_input_flags_t)(*flags & ~AUDIO_INPUT_FLAG_FAST);
Glenn Kasten74105912014-07-03 12:28:53 -07008954 }
8955 }
8956
Eric Laurentf14db3c2017-12-08 14:20:36 -08008957 // If FAST or RAW flags were corrected, ask caller to request new input from audio policy
8958 if ((*flags & AUDIO_INPUT_FLAG_FAST) !=
8959 (requestedFlags & AUDIO_INPUT_FLAG_FAST)) {
8960 *flags = (audio_input_flags_t) (*flags & ~(AUDIO_INPUT_FLAG_FAST | AUDIO_INPUT_FLAG_RAW));
8961 lStatus = BAD_TYPE;
8962 goto Exit;
8963 }
8964
Glenn Kasten74105912014-07-03 12:28:53 -07008965 // compute track buffer size in frames, and suggest the notification frame count
Eric Laurent05067782016-06-01 18:27:28 -07008966 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten74105912014-07-03 12:28:53 -07008967 // fast track: frame count is exactly the pipe depth
8968 frameCount = mPipeFramesP2;
8969 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
Eric Laurentf14db3c2017-12-08 14:20:36 -08008970 notificationFrameCount = mFrameCount;
Glenn Kasten74105912014-07-03 12:28:53 -07008971 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07008972 // not fast track: max notification period is resampled equivalent of one HAL buffer time
8973 // or 20 ms if there is a fast capture
8974 // TODO This could be a roundupRatio inline, and const
8975 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
8976 * sampleRate + mSampleRate - 1) / mSampleRate;
8977 // minimum number of notification periods is at least kMinNotifications,
8978 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
8979 static const size_t kMinNotifications = 3;
8980 static const uint32_t kMinMs = 30;
8981 // TODO This could be a roundupRatio inline
8982 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
8983 // TODO This could be a roundupRatio inline
8984 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
8985 maxNotificationFrames;
8986 const size_t minFrameCount = maxNotificationFrames *
8987 max(kMinNotifications, minNotificationsByMs);
8988 frameCount = max(frameCount, minFrameCount);
Eric Laurentf14db3c2017-12-08 14:20:36 -08008989 if (notificationFrameCount == 0 || notificationFrameCount > maxNotificationFrames) {
8990 notificationFrameCount = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07008991 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07008992 }
Glenn Kasten74935e42013-12-19 08:56:45 -08008993 *pFrameCount = frameCount;
Eric Laurentf14db3c2017-12-08 14:20:36 -08008994 *pNotificationFrameCount = notificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08008995
Andy Hungc5007f82023-08-29 14:26:09 -07008996 { // scope for mutex()
Andy Hung972bec12023-08-31 16:13:39 -07008997 audio_utils::lock_guard _l(mutex());
Eric Laurent2407ce32021-04-26 14:56:03 +02008998 int32_t startFrames = -1;
Eric Laurentec376dc2021-04-08 20:41:22 +02008999 if (!mSharedAudioPackageName.empty()
Eric Laurent9ff3e532022-11-10 16:04:44 +01009000 && mSharedAudioPackageName == attributionSource.packageName
Eric Laurentec376dc2021-04-08 20:41:22 +02009001 && mSharedAudioSessionId == sessionId
Eric Laurent9ff3e532022-11-10 16:04:44 +01009002 && captureHotwordAllowed(attributionSource)) {
Eric Laurent2407ce32021-04-26 14:56:03 +02009003 startFrames = mSharedAudioStartFrames;
Eric Laurentec376dc2021-04-08 20:41:22 +02009004 }
Eric Laurent81784c32012-11-19 14:55:58 -08009005
Andy Hung8d31fd22023-06-26 19:20:57 -07009006 track = IAfRecordTrack::create(this, client, attr, sampleRate,
Andy Hung8fe68032017-06-05 16:17:51 -07009007 format, channelMask, frameCount,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07009008 nullptr /* buffer */, (size_t)0 /* bufferSize */, sessionId, creatorPid,
Andy Hung8d31fd22023-06-26 19:20:57 -07009009 attributionSource, *flags, IAfTrackBase::TYPE_DEFAULT, portId,
Svet Ganov33761132021-05-13 22:51:08 +00009010 startFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08009011
Glenn Kasten03003332013-08-06 15:40:54 -07009012 lStatus = track->initCheck();
9013 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07009014 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08009015 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08009016 goto Exit;
9017 }
9018 mTracks.add(track);
9019
Eric Laurent05067782016-06-01 18:27:28 -07009020 if ((*flags & AUDIO_INPUT_FLAG_FAST) && (tid != -1)) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07009021 pid_t callingPid = IPCThreadState::self()->getCallingPid();
9022 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
9023 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07009024 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Glenn Kasten90e58b12013-07-31 16:16:02 -07009025 }
Eric Laurentec376dc2021-04-08 20:41:22 +02009026
9027 if (maxSharedAudioHistoryMs != 0) {
9028 sendResizeBufferConfigEvent_l(maxSharedAudioHistoryMs);
9029 }
Eric Laurent81784c32012-11-19 14:55:58 -08009030 }
Glenn Kasten05997e22014-03-13 15:08:33 -07009031
Eric Laurent81784c32012-11-19 14:55:58 -08009032 lStatus = NO_ERROR;
9033
9034Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07009035 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08009036 return track;
9037}
9038
Andy Hungee58e4a2023-07-07 13:47:37 -07009039status_t RecordThread::start(IAfRecordTrack* recordTrack,
Eric Laurent81784c32012-11-19 14:55:58 -08009040 AudioSystem::sync_event_t event,
Glenn Kastend848eb42016-03-08 13:42:11 -08009041 audio_session_t triggerSession)
Eric Laurent81784c32012-11-19 14:55:58 -08009042{
9043 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
9044 sp<ThreadBase> strongMe = this;
9045 status_t status = NO_ERROR;
9046
9047 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08009048 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08009049 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Andy Hung8d31fd22023-06-26 19:20:57 -07009050 recordTrack->synchronizedRecordState().startRecording(
Andy Hung583043b2023-07-17 17:05:00 -07009051 mAfThreadCallback->createSyncEvent(
Andy Hung93bb5732023-05-04 21:16:34 -07009052 event, triggerSession,
9053 recordTrack->sessionId(), syncStartEventCallback, recordTrack));
Eric Laurent81784c32012-11-19 14:55:58 -08009054 }
9055
9056 {
Glenn Kasten47c20702013-08-13 15:37:35 -07009057 // This section is a rendezvous between binder thread executing start() and RecordThread
Andy Hung972bec12023-08-31 16:13:39 -07009058 audio_utils::lock_guard lock(mutex());
Andy Hungce685402018-10-05 17:23:27 -07009059 if (recordTrack->isInvalid()) {
9060 recordTrack->clearSyncStartEvent();
Eric Laurentd52a28c2020-08-21 17:10:39 -07009061 ALOGW("%s track %d: invalidated before startInput", __func__, recordTrack->portId());
9062 return DEAD_OBJECT;
Andy Hungce685402018-10-05 17:23:27 -07009063 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009064 if (mActiveTracks.indexOf(recordTrack) >= 0) {
Andy Hung8d31fd22023-06-26 19:20:57 -07009065 if (recordTrack->state() == IAfTrackBase::PAUSING) {
Andy Hungce685402018-10-05 17:23:27 -07009066 // We haven't stopped yet (moved to PAUSED and not in mActiveTracks)
9067 // so no need to startInput().
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009068 ALOGV("active record track PAUSING -> ACTIVE");
Andy Hung8d31fd22023-06-26 19:20:57 -07009069 recordTrack->setState(IAfTrackBase::ACTIVE);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009070 } else {
Andy Hung8d31fd22023-06-26 19:20:57 -07009071 ALOGV("active record track state %d", (int)recordTrack->state());
Eric Laurent81784c32012-11-19 14:55:58 -08009072 }
9073 return status;
9074 }
9075
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08009076 // TODO consider other ways of handling this, such as changing the state to :STARTING and
9077 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
9078 // or using a separate command thread
Andy Hung8d31fd22023-06-26 19:20:57 -07009079 recordTrack->setState(IAfTrackBase::STARTING_1);
Glenn Kasten2b806402013-11-20 16:37:38 -08009080 mActiveTracks.add(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07009081 if (recordTrack->isExternalTrack()) {
Andy Hungc5007f82023-08-29 14:26:09 -07009082 mutex().unlock();
Eric Laurent4eb58f12018-12-07 16:41:02 -08009083 status = AudioSystem::startInput(recordTrack->portId());
Andy Hungc5007f82023-08-29 14:26:09 -07009084 mutex().lock();
Andy Hungce685402018-10-05 17:23:27 -07009085 if (recordTrack->isInvalid()) {
9086 recordTrack->clearSyncStartEvent();
Andy Hung8d31fd22023-06-26 19:20:57 -07009087 if (status == NO_ERROR && recordTrack->state() == IAfTrackBase::STARTING_1) {
9088 recordTrack->setState(IAfTrackBase::STARTING_2);
Andy Hungce685402018-10-05 17:23:27 -07009089 // STARTING_2 forces destroy to call stopInput.
9090 }
Eric Laurentd52a28c2020-08-21 17:10:39 -07009091 ALOGW("%s track %d: invalidated after startInput", __func__, recordTrack->portId());
9092 return DEAD_OBJECT;
Andy Hungce685402018-10-05 17:23:27 -07009093 }
Andy Hung8d31fd22023-06-26 19:20:57 -07009094 if (recordTrack->state() != IAfTrackBase::STARTING_1) {
Andy Hungce685402018-10-05 17:23:27 -07009095 ALOGW("%s(%d): unsynchronized mState:%d change",
Andy Hung8d31fd22023-06-26 19:20:57 -07009096 __func__, recordTrack->id(), (int)recordTrack->state());
Andy Hungce685402018-10-05 17:23:27 -07009097 // Someone else has changed state, let them take over,
9098 // leave mState in the new state.
9099 recordTrack->clearSyncStartEvent();
9100 return INVALID_OPERATION;
9101 }
9102 // we're ok, but perhaps startInput has failed
Eric Laurent83b88082014-06-20 18:31:16 -07009103 if (status != NO_ERROR) {
Andy Hungce685402018-10-05 17:23:27 -07009104 ALOGW("%s(%d): startInput failed, status %d",
9105 __func__, recordTrack->id(), status);
9106 // We are in ActiveTracks if STARTING_1 and valid, so remove from ActiveTracks,
9107 // leave in STARTING_1, so destroy() will not call stopInput.
Eric Laurent83b88082014-06-20 18:31:16 -07009108 mActiveTracks.remove(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07009109 recordTrack->clearSyncStartEvent();
Eric Laurent83b88082014-06-20 18:31:16 -07009110 return status;
9111 }
Eric Laurent09f1ed22019-04-24 17:45:17 -07009112 sendIoConfigEvent_l(
9113 AUDIO_CLIENT_STARTED, recordTrack->creatorPid(), recordTrack->portId());
Eric Laurent81784c32012-11-19 14:55:58 -08009114 }
Andy Hungc2b11cb2020-04-22 09:04:01 -07009115
9116 recordTrack->logBeginInterval(patchSourcesToString(&mPatch)); // log to MediaMetrics
9117
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009118 // Catch up with current buffer indices if thread is already running.
9119 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
9120 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
9121 // see previously buffered data before it called start(), but with greater risk of overrun.
9122
Andy Hung8d31fd22023-06-26 19:20:57 -07009123 recordTrack->resamplerBufferProvider()->reset();
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07009124 if (!recordTrack->isDirect()) {
9125 // clear any converter state as new data will be discontinuous
Andy Hung8d31fd22023-06-26 19:20:57 -07009126 recordTrack->recordBufferConverter()->reset();
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07009127 }
Andy Hung8d31fd22023-06-26 19:20:57 -07009128 recordTrack->setState(IAfTrackBase::STARTING_2);
Eric Laurent81784c32012-11-19 14:55:58 -08009129 // signal thread to start
Andy Hungc5007f82023-08-29 14:26:09 -07009130 mWaitWorkCV.notify_all();
Eric Laurent81784c32012-11-19 14:55:58 -08009131 return status;
9132 }
Eric Laurent81784c32012-11-19 14:55:58 -08009133}
9134
Andy Hungee58e4a2023-07-07 13:47:37 -07009135void RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
Eric Laurent81784c32012-11-19 14:55:58 -08009136{
Andy Hungee58e4a2023-07-07 13:47:37 -07009137 const sp<SyncEvent> strongEvent = event.promote();
Eric Laurent81784c32012-11-19 14:55:58 -08009138
9139 if (strongEvent != 0) {
Andy Hungd29af632023-06-23 19:27:19 -07009140 sp<IAfTrackBase> ptr =
9141 std::any_cast<const wp<IAfTrackBase>>(strongEvent->cookie()).promote();
9142 if (ptr != nullptr) {
Andy Hung99b1ba62023-07-14 11:00:08 -07009143 // TODO(b/291317898) handleSyncStartEvent is in IAfTrackBase not IAfRecordTrack.
Andy Hungd29af632023-06-23 19:27:19 -07009144 ptr->handleSyncStartEvent(strongEvent);
Eric Laurent8ea16e42014-02-20 16:26:11 -08009145 }
Eric Laurent81784c32012-11-19 14:55:58 -08009146 }
9147}
9148
Andy Hungee58e4a2023-07-07 13:47:37 -07009149bool RecordThread::stop(IAfRecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08009150 ALOGV("RecordThread::stop");
Andy Hungc5007f82023-08-29 14:26:09 -07009151 audio_utils::unique_lock _l(mutex());
Andy Hungce685402018-10-05 17:23:27 -07009152 // if we're invalid, we can't be on the ActiveTracks.
Andy Hung8d31fd22023-06-26 19:20:57 -07009153 if (mActiveTracks.indexOf(recordTrack) < 0 || recordTrack->state() == IAfTrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08009154 return false;
9155 }
Glenn Kasten47c20702013-08-13 15:37:35 -07009156 // note that threadLoop may still be processing the track at this point [without lock]
Andy Hung8d31fd22023-06-26 19:20:57 -07009157 recordTrack->setState(IAfTrackBase::PAUSING);
Andy Hungce685402018-10-05 17:23:27 -07009158
Andy Hungabfab202019-03-07 19:45:54 -08009159 // NOTE: Waiting here is important to keep stop synchronous.
9160 // This is needed for proper patchRecord peer release.
Andy Hung8d31fd22023-06-26 19:20:57 -07009161 while (recordTrack->state() == IAfTrackBase::PAUSING && !recordTrack->isInvalid()) {
Andy Hungc5007f82023-08-29 14:26:09 -07009162 mWaitWorkCV.notify_all(); // signal thread to stop
9163 mStartStopCV.wait(_l);
Eric Laurent81784c32012-11-19 14:55:58 -08009164 }
Andy Hungce685402018-10-05 17:23:27 -07009165
Andy Hung8d31fd22023-06-26 19:20:57 -07009166 if (recordTrack->state() == IAfTrackBase::PAUSED) { // successful stop
Eric Laurent81784c32012-11-19 14:55:58 -08009167 ALOGV("Record stopped OK");
9168 return true;
9169 }
Andy Hungce685402018-10-05 17:23:27 -07009170
9171 // don't handle anything - we've been invalidated or restarted and in a different state
9172 ALOGW_IF("%s(%d): unsynchronized stop, state: %d",
Andy Hung8d31fd22023-06-26 19:20:57 -07009173 __func__, recordTrack->id(), recordTrack->state());
Eric Laurent81784c32012-11-19 14:55:58 -08009174 return false;
9175}
9176
Andy Hungee58e4a2023-07-07 13:47:37 -07009177bool RecordThread::isValidSyncEvent(const sp<SyncEvent>& /* event */) const
Eric Laurent81784c32012-11-19 14:55:58 -08009178{
9179 return false;
9180}
9181
Andy Hungee58e4a2023-07-07 13:47:37 -07009182status_t RecordThread::setSyncEvent(const sp<SyncEvent>& /* event */)
Eric Laurent81784c32012-11-19 14:55:58 -08009183{
9184#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
9185 if (!isValidSyncEvent(event)) {
9186 return BAD_VALUE;
9187 }
9188
Glenn Kastend848eb42016-03-08 13:42:11 -08009189 audio_session_t eventSession = event->triggerSession();
Eric Laurent81784c32012-11-19 14:55:58 -08009190 status_t ret = NAME_NOT_FOUND;
9191
Andy Hung972bec12023-08-31 16:13:39 -07009192 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08009193
9194 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07009195 sp<IAfRecordTrack> track = mTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08009196 if (eventSession == track->sessionId()) {
9197 (void) track->setSyncEvent(event);
9198 ret = NO_ERROR;
9199 }
9200 }
9201 return ret;
9202#else
9203 return BAD_VALUE;
9204#endif
9205}
9206
Andy Hungee58e4a2023-07-07 13:47:37 -07009207status_t RecordThread::getActiveMicrophones(
Andy Hung87c693c2023-07-06 20:56:16 -07009208 std::vector<media::MicrophoneInfoFw>* activeMicrophones) const
jiabin653cc0a2018-01-17 17:54:10 -08009209{
9210 ALOGV("RecordThread::getActiveMicrophones");
Andy Hung972bec12023-08-31 16:13:39 -07009211 audio_utils::lock_guard _l(mutex());
Jasmine Chaeaa10e42021-05-11 10:11:14 +08009212 if (!isStreamInitialized()) {
Paul McLean8a661a32021-04-12 10:21:42 -06009213 return NO_INIT;
9214 }
jiabin9ff780e2018-03-19 18:19:52 -07009215 status_t status = mInput->stream->getActiveMicrophones(activeMicrophones);
9216 return status;
jiabin653cc0a2018-01-17 17:54:10 -08009217}
9218
Andy Hungee58e4a2023-07-07 13:47:37 -07009219status_t RecordThread::setPreferredMicrophoneDirection(
Paul McLean12340082019-03-19 09:35:05 -06009220 audio_microphone_direction_t direction)
Paul McLean03a6e6a2018-12-04 10:54:13 -07009221{
Paul McLean12340082019-03-19 09:35:05 -06009222 ALOGV("setPreferredMicrophoneDirection(%d)", direction);
Andy Hung972bec12023-08-31 16:13:39 -07009223 audio_utils::lock_guard _l(mutex());
Jasmine Chaeaa10e42021-05-11 10:11:14 +08009224 if (!isStreamInitialized()) {
Paul McLean8a661a32021-04-12 10:21:42 -06009225 return NO_INIT;
9226 }
Paul McLean12340082019-03-19 09:35:05 -06009227 return mInput->stream->setPreferredMicrophoneDirection(direction);
Paul McLean03a6e6a2018-12-04 10:54:13 -07009228}
9229
Andy Hungee58e4a2023-07-07 13:47:37 -07009230status_t RecordThread::setPreferredMicrophoneFieldDimension(float zoom)
Paul McLean03a6e6a2018-12-04 10:54:13 -07009231{
Paul McLean12340082019-03-19 09:35:05 -06009232 ALOGV("setPreferredMicrophoneFieldDimension(%f)", zoom);
Andy Hung972bec12023-08-31 16:13:39 -07009233 audio_utils::lock_guard _l(mutex());
Jasmine Chaeaa10e42021-05-11 10:11:14 +08009234 if (!isStreamInitialized()) {
Paul McLean8a661a32021-04-12 10:21:42 -06009235 return NO_INIT;
9236 }
Paul McLean12340082019-03-19 09:35:05 -06009237 return mInput->stream->setPreferredMicrophoneFieldDimension(zoom);
Paul McLean03a6e6a2018-12-04 10:54:13 -07009238}
9239
Andy Hungee58e4a2023-07-07 13:47:37 -07009240status_t RecordThread::shareAudioHistory(
Eric Laurentec376dc2021-04-08 20:41:22 +02009241 const std::string& sharedAudioPackageName, audio_session_t sharedSessionId,
9242 int64_t sharedAudioStartMs) {
Andy Hung972bec12023-08-31 16:13:39 -07009243 audio_utils::lock_guard _l(mutex());
Eric Laurentec376dc2021-04-08 20:41:22 +02009244 return shareAudioHistory_l(sharedAudioPackageName, sharedSessionId, sharedAudioStartMs);
9245}
9246
Andy Hungee58e4a2023-07-07 13:47:37 -07009247status_t RecordThread::shareAudioHistory_l(
Eric Laurentec376dc2021-04-08 20:41:22 +02009248 const std::string& sharedAudioPackageName, audio_session_t sharedSessionId,
9249 int64_t sharedAudioStartMs) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009250
Eric Laurentec376dc2021-04-08 20:41:22 +02009251 if ((hasAudioSession_l(sharedSessionId) & ThreadBase::TRACK_SESSION) == 0) {
9252 return BAD_VALUE;
9253 }
Eric Laurent2407ce32021-04-26 14:56:03 +02009254
9255 if (sharedAudioStartMs < 0
9256 || sharedAudioStartMs > INT64_MAX / mSampleRate) {
Eric Laurentec376dc2021-04-08 20:41:22 +02009257 return BAD_VALUE;
9258 }
9259
Eric Laurent2407ce32021-04-26 14:56:03 +02009260 // Current implementation of the input resampling buffer wraps around indexes at 32 bit.
9261 // As we cannot detect more than one wraparound, only accept values up current write position
9262 // after one wraparound
9263 // We assume recent wraparounds on mRsmpInRear only given it is unlikely that the requesting
9264 // app waits several hours after the start time was computed.
Eric Laurent92d0a322021-07-16 15:32:33 +02009265 int64_t sharedAudioStartFrames = sharedAudioStartMs * mSampleRate / 1000;
Eric Laurent2407ce32021-04-26 14:56:03 +02009266 const int32_t sharedOffset = audio_utils::safe_sub_overflow(mRsmpInRear,
9267 (int32_t)sharedAudioStartFrames);
Eric Laurent92d0a322021-07-16 15:32:33 +02009268 // Bring the start frame position within the input buffer to match the documented
9269 // "best effort" behavior of the API.
9270 if (sharedOffset < 0) {
9271 sharedAudioStartFrames = mRsmpInRear;
Andy Hung920f6572022-10-06 12:09:49 -07009272 } else if (sharedOffset > static_cast<signed>(mRsmpInFrames)) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009273 sharedAudioStartFrames =
9274 audio_utils::safe_sub_overflow(mRsmpInRear, (int32_t)mRsmpInFrames);
Eric Laurent2407ce32021-04-26 14:56:03 +02009275 }
9276
Eric Laurentec376dc2021-04-08 20:41:22 +02009277 mSharedAudioPackageName = sharedAudioPackageName;
9278 if (mSharedAudioPackageName.empty()) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009279 resetAudioHistory_l();
Eric Laurentec376dc2021-04-08 20:41:22 +02009280 } else {
9281 mSharedAudioSessionId = sharedSessionId;
Eric Laurent2407ce32021-04-26 14:56:03 +02009282 mSharedAudioStartFrames = (int32_t)sharedAudioStartFrames;
Eric Laurentec376dc2021-04-08 20:41:22 +02009283 }
9284 return NO_ERROR;
9285}
9286
Andy Hungee58e4a2023-07-07 13:47:37 -07009287void RecordThread::resetAudioHistory_l() {
Eric Laurent92d0a322021-07-16 15:32:33 +02009288 mSharedAudioSessionId = AUDIO_SESSION_NONE;
9289 mSharedAudioStartFrames = -1;
9290 mSharedAudioPackageName = "";
9291}
9292
Andy Hungee58e4a2023-07-07 13:47:37 -07009293ThreadBase::MetadataUpdate RecordThread::updateMetadata_l()
Kevin Rocard069c2712018-03-29 19:09:14 -07009294{
Jasmine Chaeaa10e42021-05-11 10:11:14 +08009295 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
Vlad Popa7e81cea2023-01-19 16:34:16 +01009296 return {}; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -07009297 }
9298 StreamInHalInterface::SinkMetadata metadata;
Eric Laurent78b07302022-10-07 16:20:34 +02009299 auto backInserter = std::back_inserter(metadata.tracks);
Andy Hung8d31fd22023-06-26 19:20:57 -07009300 for (const sp<IAfRecordTrack>& track : mActiveTracks) {
Eric Laurent78b07302022-10-07 16:20:34 +02009301 track->copyMetadataTo(backInserter);
Kevin Rocard069c2712018-03-29 19:09:14 -07009302 }
9303 mInput->stream->updateSinkMetadata(metadata);
Vlad Popa7e81cea2023-01-19 16:34:16 +01009304 MetadataUpdate change;
9305 change.recordMetadataUpdate = metadata.tracks;
9306 return change;
Kevin Rocard069c2712018-03-29 19:09:14 -07009307}
9308
Andy Hungc5007f82023-08-29 14:26:09 -07009309// destroyTrack_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07009310void RecordThread::destroyTrack_l(const sp<IAfRecordTrack>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08009311{
Eric Laurentbfb1b832013-01-07 09:53:42 -08009312 track->terminate();
Andy Hung8d31fd22023-06-26 19:20:57 -07009313 track->setState(IAfTrackBase::STOPPED);
Eric Laurentec376dc2021-04-08 20:41:22 +02009314
Eric Laurent81784c32012-11-19 14:55:58 -08009315 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08009316 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08009317 removeTrack_l(track);
9318 }
9319}
9320
Andy Hungee58e4a2023-07-07 13:47:37 -07009321void RecordThread::removeTrack_l(const sp<IAfRecordTrack>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08009322{
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009323 String8 result;
9324 track->appendDump(result, false /* active */);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00009325 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.c_str());
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009326
Eric Laurent81784c32012-11-19 14:55:58 -08009327 mTracks.remove(track);
9328 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07009329 if (track->isFastTrack()) {
9330 ALOG_ASSERT(!mFastTrackAvail);
9331 mFastTrackAvail = true;
9332 }
Eric Laurent81784c32012-11-19 14:55:58 -08009333}
9334
Andy Hungee58e4a2023-07-07 13:47:37 -07009335void RecordThread::dumpInternals_l(int fd, const Vector<String16>& /* args */)
Eric Laurent81784c32012-11-19 14:55:58 -08009336{
Mikhail Naganov913d06c2016-11-01 12:49:22 -07009337 AudioStreamIn *input = mInput;
9338 audio_input_flags_t flags = input != NULL ? input->flags : AUDIO_INPUT_FLAG_NONE;
9339 dprintf(fd, " AudioStreamIn: %p flags %#x (%s)\n",
Andy Hung9b181952019-02-25 14:53:36 -08009340 input, flags, toString(flags).c_str());
Andy Hung6427e442018-08-09 12:51:02 -07009341 dprintf(fd, " Frames read: %lld\n", (long long)mFramesRead);
Eric Tan39ec8d62018-07-24 09:49:29 -07009342 if (mActiveTracks.isEmpty()) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07009343 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08009344 }
Andy Hungbfa64962017-06-12 14:43:19 -07009345
9346 if (input != nullptr) {
9347 dprintf(fd, " Hal stream dump:\n");
9348 (void)input->stream->dump(fd);
9349 }
9350
Glenn Kasten6e6704c2014-07-03 10:20:00 -07009351 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07009352 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Glenn Kasten17c9c992015-03-02 15:53:01 -08009353
Glenn Kasten2f90c512015-12-02 11:40:09 -08009354 // Make a non-atomic copy of fast capture dump state so it won't change underneath us
9355 // while we are dumping it. It may be inconsistent, but it won't mutate!
9356 // This is a large object so we place it on the heap.
9357 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
Eric Tan2942a4e2018-09-12 17:41:27 -07009358 const std::unique_ptr<FastCaptureDumpState> copy =
9359 std::make_unique<FastCaptureDumpState>(mFastCaptureDumpState);
Glenn Kasten2f90c512015-12-02 11:40:09 -08009360 copy->dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08009361}
9362
Andy Hungee58e4a2023-07-07 13:47:37 -07009363void RecordThread::dumpTracks_l(int fd, const Vector<String16>& /* args */)
Eric Laurent81784c32012-11-19 14:55:58 -08009364{
Eric Laurent81784c32012-11-19 14:55:58 -08009365 String8 result;
Marco Nelissenb2208842014-02-07 14:00:50 -08009366 size_t numtracks = mTracks.size();
9367 size_t numactive = mActiveTracks.size();
9368 size_t numactiveseen = 0;
Glenn Kastenc42e9b42016-03-21 11:35:03 -07009369 dprintf(fd, " %zu Tracks", numtracks);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009370 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08009371 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07009372 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009373 result.append(prefix);
Andy Hung000adb52018-06-01 15:43:26 -07009374 mTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08009375 for (size_t i = 0; i < numtracks ; ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07009376 sp<IAfRecordTrack> track = mTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08009377 if (track != 0) {
9378 bool active = mActiveTracks.indexOf(track) >= 0;
9379 if (active) {
9380 numactiveseen++;
9381 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009382 result.append(prefix);
9383 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08009384 }
Eric Laurent81784c32012-11-19 14:55:58 -08009385 }
Marco Nelissenb2208842014-02-07 14:00:50 -08009386 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07009387 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08009388 }
9389
Marco Nelissenb2208842014-02-07 14:00:50 -08009390 if (numactiveseen != numactive) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009391 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08009392 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009393 result.append(prefix);
Andy Hung000adb52018-06-01 15:43:26 -07009394 mActiveTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08009395 for (size_t i = 0; i < numactive; ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07009396 sp<IAfRecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08009397 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009398 result.append(prefix);
9399 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08009400 }
Glenn Kasten2b806402013-11-20 16:37:38 -08009401 }
Eric Laurent81784c32012-11-19 14:55:58 -08009402
9403 }
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00009404 write(fd, result.c_str(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08009405}
9406
Andy Hungee58e4a2023-07-07 13:47:37 -07009407void RecordThread::setRecordSilenced(audio_port_handle_t portId, bool silenced)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08009408{
Andy Hung972bec12023-08-31 16:13:39 -07009409 audio_utils::lock_guard _l(mutex());
Svet Ganovf4ddfef2018-01-16 07:37:58 -08009410 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07009411 sp<IAfRecordTrack> track = mTracks[i];
Eric Laurent5ada82e2019-08-29 17:53:54 -07009412 if (track != 0 && track->portId() == portId) {
Svet Ganovf4ddfef2018-01-16 07:37:58 -08009413 track->setSilenced(silenced);
9414 }
9415 }
9416}
Andy Hung73c02e42015-03-29 01:13:58 -07009417
Andy Hung8d31fd22023-06-26 19:20:57 -07009418void ResamplerBufferProvider::reset()
Andy Hung73c02e42015-03-29 01:13:58 -07009419{
Andy Hung87c693c2023-07-06 20:56:16 -07009420 const auto threadBase = mRecordTrack->thread().promote();
Andy Hungee58e4a2023-07-07 13:47:37 -07009421 auto* const recordThread = static_cast<RecordThread *>(threadBase->asIAfRecordThread().get());
Andy Hung73c02e42015-03-29 01:13:58 -07009422 mRsmpInUnrel = 0;
Eric Laurentec376dc2021-04-08 20:41:22 +02009423 const int32_t rear = recordThread->mRsmpInRear;
9424 ssize_t deltaFrames = 0;
Eric Laurent2407ce32021-04-26 14:56:03 +02009425 if (mRecordTrack->startFrames() >= 0) {
9426 int32_t startFrames = mRecordTrack->startFrames();
9427 // Accept a recent wraparound of mRsmpInRear
9428 if (startFrames <= rear) {
9429 deltaFrames = rear - startFrames;
9430 } else {
9431 deltaFrames = (int32_t)((int64_t)rear + UINT32_MAX + 1 - startFrames);
Eric Laurentec376dc2021-04-08 20:41:22 +02009432 }
Eric Laurentec376dc2021-04-08 20:41:22 +02009433 // start frame cannot be further in the past than start of resampling buffer
9434 if ((size_t) deltaFrames > recordThread->mRsmpInFrames) {
9435 deltaFrames = recordThread->mRsmpInFrames;
9436 }
9437 }
9438 mRsmpInFront = audio_utils::safe_sub_overflow(rear, static_cast<int32_t>(deltaFrames));
Andy Hung73c02e42015-03-29 01:13:58 -07009439}
9440
Andy Hung8d31fd22023-06-26 19:20:57 -07009441void ResamplerBufferProvider::sync(
Andy Hung73c02e42015-03-29 01:13:58 -07009442 size_t *framesAvailable, bool *hasOverrun)
9443{
Andy Hung87c693c2023-07-06 20:56:16 -07009444 const auto threadBase = mRecordTrack->thread().promote();
Andy Hungee58e4a2023-07-07 13:47:37 -07009445 auto* const recordThread = static_cast<RecordThread *>(threadBase->asIAfRecordThread().get());
Andy Hung73c02e42015-03-29 01:13:58 -07009446 const int32_t rear = recordThread->mRsmpInRear;
9447 const int32_t front = mRsmpInFront;
Hongwei Wang95e37682019-04-12 11:13:36 -07009448 const ssize_t filled = audio_utils::safe_sub_overflow(rear, front);
Andy Hung73c02e42015-03-29 01:13:58 -07009449
9450 size_t framesIn;
9451 bool overrun = false;
9452 if (filled < 0) {
9453 // should not happen, but treat like a massive overrun and re-sync
9454 framesIn = 0;
9455 mRsmpInFront = rear;
9456 overrun = true;
9457 } else if ((size_t) filled <= recordThread->mRsmpInFrames) {
9458 framesIn = (size_t) filled;
9459 } else {
9460 // client is not keeping up with server, but give it latest data
9461 framesIn = recordThread->mRsmpInFrames;
Hongwei Wang95e37682019-04-12 11:13:36 -07009462 mRsmpInFront = /* front = */ audio_utils::safe_sub_overflow(
9463 rear, static_cast<int32_t>(framesIn));
Andy Hung73c02e42015-03-29 01:13:58 -07009464 overrun = true;
9465 }
9466 if (framesAvailable != NULL) {
9467 *framesAvailable = framesIn;
9468 }
9469 if (hasOverrun != NULL) {
9470 *hasOverrun = overrun;
9471 }
9472}
9473
Eric Laurent81784c32012-11-19 14:55:58 -08009474// AudioBufferProvider interface
Andy Hung8d31fd22023-06-26 19:20:57 -07009475status_t ResamplerBufferProvider::getNextBuffer(
Glenn Kastend79072e2016-01-06 08:41:20 -08009476 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08009477{
Andy Hung87c693c2023-07-06 20:56:16 -07009478 const auto threadBase = mRecordTrack->thread().promote();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009479 if (threadBase == 0) {
9480 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08009481 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009482 return NOT_ENOUGH_DATA;
9483 }
Andy Hungee58e4a2023-07-07 13:47:37 -07009484 auto* const recordThread = static_cast<RecordThread *>(threadBase->asIAfRecordThread().get());
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009485 int32_t rear = recordThread->mRsmpInRear;
Andy Hung73c02e42015-03-29 01:13:58 -07009486 int32_t front = mRsmpInFront;
Hongwei Wang95e37682019-04-12 11:13:36 -07009487 ssize_t filled = audio_utils::safe_sub_overflow(rear, front);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009488 // FIXME should not be P2 (don't want to increase latency)
9489 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08009490 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07009491 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009492
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009493 front &= recordThread->mRsmpInFramesP2 - 1;
9494 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07009495 if (part1 > (size_t) filled) {
9496 part1 = filled;
9497 }
9498 size_t ask = buffer->frameCount;
9499 ALOG_ASSERT(ask > 0);
9500 if (part1 > ask) {
9501 part1 = ask;
9502 }
9503 if (part1 == 0) {
Andy Hung73c02e42015-03-29 01:13:58 -07009504 // out of data is fine since the resampler will return a short-count.
Glenn Kasten85948432013-08-19 12:09:05 -07009505 buffer->raw = NULL;
9506 buffer->frameCount = 0;
Andy Hung73c02e42015-03-29 01:13:58 -07009507 mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07009508 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08009509 }
9510
Andy Hung57446612015-04-19 23:56:46 -07009511 buffer->raw = (uint8_t*)recordThread->mRsmpInBuffer + front * recordThread->mFrameSize;
Glenn Kasten85948432013-08-19 12:09:05 -07009512 buffer->frameCount = part1;
Andy Hung73c02e42015-03-29 01:13:58 -07009513 mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08009514 return NO_ERROR;
9515}
9516
9517// AudioBufferProvider interface
Andy Hung8d31fd22023-06-26 19:20:57 -07009518void ResamplerBufferProvider::releaseBuffer(
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009519 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08009520{
Hongwei Wang95e37682019-04-12 11:13:36 -07009521 int32_t stepCount = static_cast<int32_t>(buffer->frameCount);
Glenn Kasten85948432013-08-19 12:09:05 -07009522 if (stepCount == 0) {
9523 return;
9524 }
Eric Laurent1e28aaa2023-04-16 19:34:23 +02009525 ALOG_ASSERT(stepCount <= (int32_t)mRsmpInUnrel);
Andy Hung73c02e42015-03-29 01:13:58 -07009526 mRsmpInUnrel -= stepCount;
Hongwei Wang95e37682019-04-12 11:13:36 -07009527 mRsmpInFront = audio_utils::safe_add_overflow(mRsmpInFront, stepCount);
Glenn Kasten85948432013-08-19 12:09:05 -07009528 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08009529 buffer->frameCount = 0;
9530}
9531
Andy Hungee58e4a2023-07-07 13:47:37 -07009532void RecordThread::checkBtNrec()
Eric Laurentd8365c52017-07-16 15:27:05 -07009533{
Andy Hung972bec12023-08-31 16:13:39 -07009534 audio_utils::lock_guard _l(mutex());
Eric Laurentd8365c52017-07-16 15:27:05 -07009535 checkBtNrec_l();
9536}
9537
Andy Hungee58e4a2023-07-07 13:47:37 -07009538void RecordThread::checkBtNrec_l()
Eric Laurentd8365c52017-07-16 15:27:05 -07009539{
9540 // disable AEC and NS if the device is a BT SCO headset supporting those
9541 // pre processings
Andy Hungab65b182023-09-06 19:41:47 -07009542 bool suspend = audio_is_bluetooth_sco_device(inDeviceType_l()) &&
Andy Hung583043b2023-07-17 17:05:00 -07009543 mAfThreadCallback->btNrecIsOff();
Eric Laurentd8365c52017-07-16 15:27:05 -07009544 if (mBtNrecSuspended.exchange(suspend) != suspend) {
9545 for (size_t i = 0; i < mEffectChains.size(); i++) {
9546 setEffectSuspended_l(FX_IID_AEC, suspend, mEffectChains[i]->sessionId());
9547 setEffectSuspended_l(FX_IID_NS, suspend, mEffectChains[i]->sessionId());
9548 }
9549 }
9550}
9551
Andy Hung97a893e2015-03-29 01:03:07 -07009552
Andy Hungee58e4a2023-07-07 13:47:37 -07009553bool RecordThread::checkForNewParameter_l(const String8& keyValuePair,
Eric Laurent10351942014-05-08 18:49:52 -07009554 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08009555{
9556 bool reconfig = false;
9557
Eric Laurent10351942014-05-08 18:49:52 -07009558 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08009559
Eric Laurent10351942014-05-08 18:49:52 -07009560 audio_format_t reqFormat = mFormat;
9561 uint32_t samplingRate = mSampleRate;
Glenn Kastene1635ec2015-06-08 15:46:49 -07009562 // 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 +08009563 [[maybe_unused]] audio_channel_mask_t channelMask =
9564 audio_channel_in_mask_from_count(mChannelCount);
Eric Laurent10351942014-05-08 18:49:52 -07009565
9566 AudioParameter param = AudioParameter(keyValuePair);
9567 int value;
Haynes Mathew George9ce67b52015-09-30 11:40:47 -07009568
9569 // scope for AutoPark extends to end of method
9570 AutoPark<FastCapture> park(mFastCapture);
9571
Eric Laurent10351942014-05-08 18:49:52 -07009572 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
9573 // channel count change can be requested. Do we mandate the first client defines the
9574 // HAL sampling rate and channel count or do we allow changes on the fly?
9575 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
9576 samplingRate = value;
9577 reconfig = true;
9578 }
9579 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung97a893e2015-03-29 01:03:07 -07009580 if (!audio_is_linear_pcm((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07009581 status = BAD_VALUE;
9582 } else {
9583 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08009584 reconfig = true;
9585 }
Eric Laurent10351942014-05-08 18:49:52 -07009586 }
9587 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
9588 audio_channel_mask_t mask = (audio_channel_mask_t) value;
Andy Hungd330ee42015-04-20 13:23:41 -07009589 if (!audio_is_input_channel(mask) ||
Andy Hung936845a2021-06-08 00:09:06 -07009590 audio_channel_count_from_in_mask(mask) > FCC_LIMIT) {
Eric Laurent10351942014-05-08 18:49:52 -07009591 status = BAD_VALUE;
9592 } else {
9593 channelMask = mask;
9594 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08009595 }
Eric Laurent10351942014-05-08 18:49:52 -07009596 }
9597 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
9598 // do not accept frame count changes if tracks are open as the track buffer
9599 // size depends on frame count and correct behavior would not be guaranteed
9600 // if frame count is changed after track creation
9601 if (mActiveTracks.size() > 0) {
9602 status = INVALID_OPERATION;
9603 } else {
9604 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08009605 }
Eric Laurent10351942014-05-08 18:49:52 -07009606 }
9607 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07009608 LOG_FATAL("Should not set routing device in RecordThread");
Eric Laurent10351942014-05-08 18:49:52 -07009609 }
9610 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
9611 mAudioSource != (audio_source_t)value) {
jiabinc52b1ff2019-10-31 17:20:42 -07009612 LOG_FATAL("Should not set audio source in RecordThread");
Eric Laurent10351942014-05-08 18:49:52 -07009613 }
Glenn Kastene198c362013-08-13 09:13:36 -07009614
Eric Laurent10351942014-05-08 18:49:52 -07009615 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009616 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07009617 if (status == INVALID_OPERATION) {
9618 inputStandBy();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009619 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07009620 }
9621 if (reconfig) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009622 if (status == BAD_VALUE) {
Mikhail Naganov560637e2021-03-31 22:40:13 +00009623 audio_config_base_t config = AUDIO_CONFIG_BASE_INITIALIZER;
9624 if (mInput->stream->getAudioProperties(&config) == OK &&
9625 audio_is_linear_pcm(config.format) && audio_is_linear_pcm(reqFormat) &&
9626 config.sample_rate <= (AUDIO_RESAMPLER_DOWN_RATIO_MAX * samplingRate) &&
Andy Hung936845a2021-06-08 00:09:06 -07009627 audio_channel_count_from_in_mask(config.channel_mask) <= FCC_LIMIT) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009628 status = NO_ERROR;
9629 }
Eric Laurent81784c32012-11-19 14:55:58 -08009630 }
Eric Laurent10351942014-05-08 18:49:52 -07009631 if (status == NO_ERROR) {
9632 readInputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07009633 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08009634 }
9635 }
Eric Laurent81784c32012-11-19 14:55:58 -08009636 }
Eric Laurent10351942014-05-08 18:49:52 -07009637
Eric Laurent81784c32012-11-19 14:55:58 -08009638 return reconfig;
9639}
9640
Andy Hungee58e4a2023-07-07 13:47:37 -07009641String8 RecordThread::getParameters(const String8& keys)
Eric Laurent81784c32012-11-19 14:55:58 -08009642{
Andy Hung972bec12023-08-31 16:13:39 -07009643 audio_utils::lock_guard _l(mutex());
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009644 if (initCheck() == NO_ERROR) {
9645 String8 out_s8;
9646 if (mInput->stream->getParameters(keys, &out_s8) == OK) {
9647 return out_s8;
9648 }
Eric Laurent81784c32012-11-19 14:55:58 -08009649 }
Andy Hung920f6572022-10-06 12:09:49 -07009650 return {};
Eric Laurent81784c32012-11-19 14:55:58 -08009651}
9652
Andy Hungab65b182023-09-06 19:41:47 -07009653void RecordThread::ioConfigChanged_l(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -07009654 audio_port_handle_t portId) {
Mikhail Naganov88536df2021-07-26 17:30:29 -07009655 sp<AudioIoDescriptor> desc;
Eric Laurent81784c32012-11-19 14:55:58 -08009656 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07009657 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07009658 case AUDIO_INPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07009659 case AUDIO_INPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07009660 desc = sp<AudioIoDescriptor>::make(mId, mPatch, true /*isInput*/,
9661 mSampleRate, mFormat, mChannelMask, mFrameCount, mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08009662 break;
Eric Laurent09f1ed22019-04-24 17:45:17 -07009663 case AUDIO_CLIENT_STARTED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07009664 desc = sp<AudioIoDescriptor>::make(mId, mPatch, portId);
Eric Laurent09f1ed22019-04-24 17:45:17 -07009665 break;
Eric Laurent73e26b62015-04-27 16:55:58 -07009666 case AUDIO_INPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08009667 default:
Mikhail Naganov88536df2021-07-26 17:30:29 -07009668 desc = sp<AudioIoDescriptor>::make(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08009669 break;
9670 }
Andy Hungab65b182023-09-06 19:41:47 -07009671 mAfThreadCallback->ioConfigChanged_l(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08009672}
9673
Andy Hungee58e4a2023-07-07 13:47:37 -07009674void RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08009675{
Dean Wheatley6c009512023-10-23 09:34:14 +11009676 const audio_config_base_t audioConfig = mInput->getAudioProperties();
9677 mSampleRate = audioConfig.sample_rate;
9678 mChannelMask = audioConfig.channel_mask;
9679 if (!audio_is_input_channel(mChannelMask)) {
9680 LOG_ALWAYS_FATAL("Channel mask %#x not valid for input", mChannelMask);
9681 }
9682
Mikhail Naganovce9f2652018-07-16 11:09:24 -07009683 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
Dean Wheatley6c009512023-10-23 09:34:14 +11009684
9685 // Get actual HAL format.
9686 status_t result = mInput->stream->getAudioProperties(nullptr, nullptr, &mHALFormat);
9687 LOG_ALWAYS_FATAL_IF(result != OK, "Error when retrieving input stream format: %d", result);
9688 // Get format from the shim, which will be different than the HAL format
9689 // if recording compressed audio from IEC61937 wrapped sources.
9690 mFormat = audioConfig.format;
9691 if (!audio_is_valid_format(mFormat)) {
9692 LOG_ALWAYS_FATAL("Format %#x not valid for input", mFormat);
9693 }
Mikhail Naganovce9f2652018-07-16 11:09:24 -07009694 if (audio_is_linear_pcm(mFormat)) {
Andy Hung936845a2021-06-08 00:09:06 -07009695 LOG_ALWAYS_FATAL_IF(mChannelCount > FCC_LIMIT, "HAL channel count %d > %d",
9696 mChannelCount, FCC_LIMIT);
Mikhail Naganovce9f2652018-07-16 11:09:24 -07009697 } else {
Andy Hung936845a2021-06-08 00:09:06 -07009698 // Can have more that FCC_LIMIT channels in encoded streams.
Mikhail Naganovce9f2652018-07-16 11:09:24 -07009699 ALOGI("HAL format %#x is not linear pcm", mFormat);
9700 }
Dean Wheatley6c009512023-10-23 09:34:14 +11009701 mFrameSize = mInput->getFrameSize();
Hayden Gomes1a89ab32020-06-12 11:05:47 -07009702 LOG_ALWAYS_FATAL_IF(mFrameSize <= 0, "Error frame size was %zu but must be greater than zero",
9703 mFrameSize);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009704 result = mInput->stream->getBufferSize(&mBufferSize);
9705 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
Glenn Kasten548efc92012-11-29 08:48:51 -08009706 mFrameCount = mBufferSize / mFrameSize;
Hayden Gomes1a89ab32020-06-12 11:05:47 -07009707 ALOGV("%p RecordThread params: mChannelCount=%u, mFormat=%#x, mFrameSize=%zu, "
9708 "mBufferSize=%zu, mFrameCount=%zu",
9709 this, mChannelCount, mFormat, mFrameSize, mBufferSize, mFrameCount);
Glenn Kasten49d00ad2014-07-21 11:22:03 -07009710
Eric Laurentec376dc2021-04-08 20:41:22 +02009711 // mRsmpInFrames must be 0 before calling resizeInputBuffer_l for the first time
9712 mRsmpInFrames = 0;
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009713 resizeInputBuffer_l(0 /*maxSharedAudioHistoryMs*/);
Eric Laurent81784c32012-11-19 14:55:58 -08009714
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08009715 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
9716 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Andy Hungea840382020-05-05 21:50:17 -07009717
9718 audio_input_flags_t flags = mInput->flags;
9719 mediametrics::LogItem item(mThreadMetrics.getMetricsId());
9720 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
Andy Hung25a80ac2023-07-19 12:47:35 -07009721 .set(AMEDIAMETRICS_PROP_ENCODING, IAfThreadBase::formatToString(mFormat).c_str())
Andy Hungea840382020-05-05 21:50:17 -07009722 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
9723 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
9724 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
9725 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
9726 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mFrameCount)
9727 .record();
Eric Laurent81784c32012-11-19 14:55:58 -08009728}
9729
Andy Hungee58e4a2023-07-07 13:47:37 -07009730uint32_t RecordThread::getInputFramesLost() const
Eric Laurent81784c32012-11-19 14:55:58 -08009731{
Andy Hung972bec12023-08-31 16:13:39 -07009732 audio_utils::lock_guard _l(mutex());
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009733 uint32_t result;
9734 if (initCheck() == NO_ERROR && mInput->stream->getInputFramesLost(&result) == OK) {
9735 return result;
Eric Laurent81784c32012-11-19 14:55:58 -08009736 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009737 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08009738}
9739
Andy Hungee58e4a2023-07-07 13:47:37 -07009740KeyedVector<audio_session_t, bool> RecordThread::sessionIds() const
Eric Laurent81784c32012-11-19 14:55:58 -08009741{
Glenn Kastend848eb42016-03-08 13:42:11 -08009742 KeyedVector<audio_session_t, bool> ids;
Andy Hung972bec12023-08-31 16:13:39 -07009743 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08009744 for (size_t j = 0; j < mTracks.size(); ++j) {
Andy Hung8d31fd22023-06-26 19:20:57 -07009745 sp<IAfRecordTrack> track = mTracks[j];
Glenn Kastend848eb42016-03-08 13:42:11 -08009746 audio_session_t sessionId = track->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08009747 if (ids.indexOfKey(sessionId) < 0) {
9748 ids.add(sessionId, true);
9749 }
9750 }
9751 return ids;
9752}
9753
Andy Hungee58e4a2023-07-07 13:47:37 -07009754AudioStreamIn* RecordThread::clearInput()
Eric Laurent81784c32012-11-19 14:55:58 -08009755{
Andy Hung972bec12023-08-31 16:13:39 -07009756 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08009757 AudioStreamIn *input = mInput;
9758 mInput = NULL;
Mikhail Naganov49aecf02023-09-08 15:14:34 -07009759 mInputSource.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08009760 return input;
9761}
9762
Andy Hungc5007f82023-08-29 14:26:09 -07009763// this method must always be called either with ThreadBase mutex() held or inside the thread loop
Andy Hungee58e4a2023-07-07 13:47:37 -07009764sp<StreamHalInterface> RecordThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08009765{
9766 if (mInput == NULL) {
9767 return NULL;
9768 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009769 return mInput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08009770}
9771
Andy Hungee58e4a2023-07-07 13:47:37 -07009772status_t RecordThread::addEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08009773{
Eric Laurent81784c32012-11-19 14:55:58 -08009774 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurentaaa44472014-09-12 17:41:50 -07009775 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08009776 chain->setInBuffer(NULL);
9777 chain->setOutBuffer(NULL);
9778
9779 checkSuspendOnAddEffectChain_l(chain);
9780
Eric Laurent1b928682014-10-02 19:41:47 -07009781 // make sure enabled pre processing effects state is communicated to the HAL as we
9782 // just moved them to a new input stream.
Shunkai Yaod125e402024-01-20 03:19:06 +00009783 chain->syncHalEffectsState_l();
Eric Laurent1b928682014-10-02 19:41:47 -07009784
Eric Laurent81784c32012-11-19 14:55:58 -08009785 mEffectChains.add(chain);
9786
9787 return NO_ERROR;
9788}
9789
Andy Hungee58e4a2023-07-07 13:47:37 -07009790size_t RecordThread::removeEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08009791{
9792 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
Eric Laurentb20cf7d2019-04-05 19:37:34 -07009793
9794 for (size_t i = 0; i < mEffectChains.size(); i++) {
9795 if (chain == mEffectChains[i]) {
9796 mEffectChains.removeAt(i);
9797 break;
9798 }
Eric Laurent81784c32012-11-19 14:55:58 -08009799 }
Eric Laurentb20cf7d2019-04-05 19:37:34 -07009800 return mEffectChains.size();
Eric Laurent81784c32012-11-19 14:55:58 -08009801}
9802
Andy Hungee58e4a2023-07-07 13:47:37 -07009803status_t RecordThread::createAudioPatch_l(const struct audio_patch* patch,
Eric Laurent1c333e22014-05-20 10:48:17 -07009804 audio_patch_handle_t *handle)
9805{
9806 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07009807
9808 // store new device and send to effects
jiabinc52b1ff2019-10-31 17:20:42 -07009809 mInDeviceTypeAddr.mType = patch->sources[0].ext.device.type;
jiabin0a488932020-08-07 17:32:40 -07009810 mInDeviceTypeAddr.setAddress(patch->sources[0].ext.device.address);
François Gaffie0c280aa2018-07-25 10:02:15 +02009811 audio_port_handle_t deviceId = patch->sources[0].id;
Eric Laurent054d9d32015-04-24 08:48:48 -07009812 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08009813 mEffectChains[i]->setInputDevice_l(inDeviceTypeAddr());
Eric Laurent054d9d32015-04-24 08:48:48 -07009814 }
9815
Eric Laurentd8365c52017-07-16 15:27:05 -07009816 checkBtNrec_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07009817
9818 // store new source and send to effects
9819 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
9820 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent1c333e22014-05-20 10:48:17 -07009821 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent054d9d32015-04-24 08:48:48 -07009822 mEffectChains[i]->setAudioSource_l(mAudioSource);
Eric Laurent1c333e22014-05-20 10:48:17 -07009823 }
Eric Laurent054d9d32015-04-24 08:48:48 -07009824 }
Eric Laurent1c333e22014-05-20 10:48:17 -07009825
Mikhail Naganov9ee05402016-10-13 15:58:17 -07009826 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07009827 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
9828 status = hwDevice->createAudioPatch(patch->num_sources,
9829 patch->sources,
9830 patch->num_sinks,
9831 patch->sinks,
9832 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07009833 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08009834 status = mInput->stream->legacyCreateAudioPatch(patch->sources[0],
9835 patch->sinks[0].ext.mix.usecase.source,
9836 patch->sources[0].ext.device.type);
Eric Laurent054d9d32015-04-24 08:48:48 -07009837 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07009838 }
Eric Laurent054d9d32015-04-24 08:48:48 -07009839
jiabinc52b1ff2019-10-31 17:20:42 -07009840 if ((mPatch.num_sources == 0) || (mPatch.sources[0].id != deviceId)) {
Eric Laurente8726fe2015-06-26 09:39:24 -07009841 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
jiabinc52b1ff2019-10-31 17:20:42 -07009842 mPatch = *patch;
Eric Laurente8726fe2015-06-26 09:39:24 -07009843 }
Eric Laurent296fb132015-05-01 11:38:42 -07009844
Andy Hungc2b11cb2020-04-22 09:04:01 -07009845 const std::string pathSourcesAsString = patchSourcesToString(patch);
Andy Hungcf10d742020-04-28 15:38:24 -07009846 mThreadMetrics.logEndInterval();
Andy Hungea840382020-05-05 21:50:17 -07009847 mThreadMetrics.logCreatePatch(pathSourcesAsString, /* outDevices */ {});
Andy Hungcf10d742020-04-28 15:38:24 -07009848 mThreadMetrics.logBeginInterval();
Andy Hungc2b11cb2020-04-22 09:04:01 -07009849 // also dispatch to active AudioRecords
9850 for (const auto &track : mActiveTracks) {
9851 track->logEndInterval();
9852 track->logBeginInterval(pathSourcesAsString);
9853 }
Eric Laurentdda206a2022-07-08 17:28:35 +02009854 // Force meteadata update after a route change
9855 mActiveTracks.setHasChanged();
9856
Eric Laurent1c333e22014-05-20 10:48:17 -07009857 return status;
9858}
9859
Andy Hungee58e4a2023-07-07 13:47:37 -07009860status_t RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
Eric Laurent1c333e22014-05-20 10:48:17 -07009861{
9862 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07009863
jiabinc52b1ff2019-10-31 17:20:42 -07009864 mPatch = audio_patch{};
9865 mInDeviceTypeAddr.reset();
Eric Laurent054d9d32015-04-24 08:48:48 -07009866
Mikhail Naganov9ee05402016-10-13 15:58:17 -07009867 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07009868 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
9869 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07009870 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08009871 status = mInput->stream->legacyReleaseAudioPatch();
Eric Laurent1c333e22014-05-20 10:48:17 -07009872 }
Eric Laurentdda206a2022-07-08 17:28:35 +02009873 // Force meteadata update after a route change
9874 mActiveTracks.setHasChanged();
9875
Eric Laurent1c333e22014-05-20 10:48:17 -07009876 return status;
9877}
9878
Andy Hungee58e4a2023-07-07 13:47:37 -07009879void RecordThread::updateOutDevices(const DeviceDescriptorBaseVector& outDevices)
jiabinc52b1ff2019-10-31 17:20:42 -07009880{
Andy Hung972bec12023-08-31 16:13:39 -07009881 audio_utils::lock_guard _l(mutex());
jiabinc52b1ff2019-10-31 17:20:42 -07009882 mOutDevices = outDevices;
9883 mOutDeviceTypeAddrs = deviceTypeAddrsFromDescriptors(mOutDevices);
9884 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08009885 mEffectChains[i]->setDevices_l(outDeviceTypeAddrs());
jiabinc52b1ff2019-10-31 17:20:42 -07009886 }
9887}
9888
Andy Hungee58e4a2023-07-07 13:47:37 -07009889int32_t RecordThread::getOldestFront_l()
Eric Laurentec376dc2021-04-08 20:41:22 +02009890{
9891 if (mTracks.size() == 0) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009892 return mRsmpInRear;
Eric Laurentec376dc2021-04-08 20:41:22 +02009893 }
Eric Laurent2407ce32021-04-26 14:56:03 +02009894 int32_t oldestFront = mRsmpInRear;
9895 int32_t maxFilled = 0;
Eric Laurentec376dc2021-04-08 20:41:22 +02009896 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07009897 int32_t front = mTracks[i]->resamplerBufferProvider()->getFront();
Eric Laurent2407ce32021-04-26 14:56:03 +02009898 int32_t filled;
Eric Laurent92d0a322021-07-16 15:32:33 +02009899 (void)__builtin_sub_overflow(mRsmpInRear, front, &filled);
Eric Laurent2407ce32021-04-26 14:56:03 +02009900 if (filled > maxFilled) {
9901 oldestFront = front;
9902 maxFilled = filled;
9903 }
Eric Laurentec376dc2021-04-08 20:41:22 +02009904 }
Andy Hung920f6572022-10-06 12:09:49 -07009905 if (maxFilled > static_cast<signed>(mRsmpInFrames)) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009906 (void)__builtin_sub_overflow(mRsmpInRear, mRsmpInFrames, &oldestFront);
9907 }
Eric Laurent2407ce32021-04-26 14:56:03 +02009908 return oldestFront;
Eric Laurentec376dc2021-04-08 20:41:22 +02009909}
9910
Andy Hungee58e4a2023-07-07 13:47:37 -07009911void RecordThread::updateFronts_l(int32_t offset)
Eric Laurentec376dc2021-04-08 20:41:22 +02009912{
9913 if (offset == 0) {
9914 return;
9915 }
9916 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07009917 int32_t front = mTracks[i]->resamplerBufferProvider()->getFront();
Eric Laurentec376dc2021-04-08 20:41:22 +02009918 front = audio_utils::safe_sub_overflow(front, offset);
Andy Hung8d31fd22023-06-26 19:20:57 -07009919 mTracks[i]->resamplerBufferProvider()->setFront(front);
Eric Laurentec376dc2021-04-08 20:41:22 +02009920 }
9921}
9922
Andy Hungee58e4a2023-07-07 13:47:37 -07009923void RecordThread::resizeInputBuffer_l(int32_t maxSharedAudioHistoryMs)
Eric Laurentec376dc2021-04-08 20:41:22 +02009924{
9925 // This is the formula for calculating the temporary buffer size.
9926 // With 7 HAL buffers, we can guarantee ability to down-sample the input by ratio of 6:1 to
9927 // 1 full output buffer, regardless of the alignment of the available input.
9928 // The value is somewhat arbitrary, and could probably be even larger.
9929 // A larger value should allow more old data to be read after a track calls start(),
9930 // without increasing latency.
9931 //
9932 // Note this is independent of the maximum downsampling ratio permitted for capture.
9933 size_t minRsmpInFrames = mFrameCount * 7;
9934
9935 // maxSharedAudioHistoryMs != 0 indicates a request to possibly make some part of the audio
9936 // capture history available to another client using the same session ID:
9937 // dimension the resampler input buffer accordingly.
9938
9939 // Get oldest client read position: getOldestFront_l() must be called before altering
9940 // mRsmpInRear, or mRsmpInFrames
9941 int32_t previousFront = getOldestFront_l();
9942 size_t previousRsmpInFramesP2 = mRsmpInFramesP2;
9943 int32_t previousRear = mRsmpInRear;
9944 mRsmpInRear = 0;
9945
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009946 ALOG_ASSERT(maxSharedAudioHistoryMs >= 0
Andy Hungee58e4a2023-07-07 13:47:37 -07009947 && maxSharedAudioHistoryMs <= kMaxSharedAudioHistoryMs,
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009948 "resizeInputBuffer_l() called with invalid max shared history %d",
9949 maxSharedAudioHistoryMs);
Eric Laurentec376dc2021-04-08 20:41:22 +02009950 if (maxSharedAudioHistoryMs != 0) {
9951 // resizeInputBuffer_l should never be called with a non zero shared history if the
9952 // buffer was not already allocated
9953 ALOG_ASSERT(mRsmpInBuffer != nullptr && mRsmpInFrames != 0,
9954 "resizeInputBuffer_l() called with shared history and unallocated buffer");
9955 size_t rsmpInFrames = (size_t)maxSharedAudioHistoryMs * mSampleRate / 1000;
9956 // never reduce resampler input buffer size
Eric Laurent92d0a322021-07-16 15:32:33 +02009957 if (rsmpInFrames <= mRsmpInFrames) {
Eric Laurentec376dc2021-04-08 20:41:22 +02009958 return;
9959 }
9960 mRsmpInFrames = rsmpInFrames;
9961 }
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009962 mMaxSharedAudioHistoryMs = maxSharedAudioHistoryMs;
Eric Laurentec376dc2021-04-08 20:41:22 +02009963 // Note: mRsmpInFrames is 0 when called with maxSharedAudioHistoryMs equals to 0 so it is always
9964 // initialized
9965 if (mRsmpInFrames < minRsmpInFrames) {
9966 mRsmpInFrames = minRsmpInFrames;
9967 }
9968 mRsmpInFramesP2 = roundup(mRsmpInFrames);
9969
9970 // TODO optimize audio capture buffer sizes ...
9971 // Here we calculate the size of the sliding buffer used as a source
9972 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
9973 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
9974 // be better to have it derived from the pipe depth in the long term.
9975 // The current value is higher than necessary. However it should not add to latency.
9976
9977 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
9978 mRsmpInFramesOA = mRsmpInFramesP2 + mFrameCount - 1;
9979
9980 void *rsmpInBuffer;
9981 (void)posix_memalign(&rsmpInBuffer, 32, mRsmpInFramesOA * mFrameSize);
9982 // if posix_memalign fails, will segv here.
9983 memset(rsmpInBuffer, 0, mRsmpInFramesOA * mFrameSize);
9984
9985 // Copy audio history if any from old buffer before freeing it
9986 if (previousRear != 0) {
9987 ALOG_ASSERT(mRsmpInBuffer != nullptr,
9988 "resizeInputBuffer_l() called with null buffer but frames already read from HAL");
9989
9990 ssize_t unread = audio_utils::safe_sub_overflow(previousRear, previousFront);
9991 previousFront &= previousRsmpInFramesP2 - 1;
9992 size_t part1 = previousRsmpInFramesP2 - previousFront;
9993 if (part1 > (size_t) unread) {
9994 part1 = unread;
9995 }
9996 if (part1 != 0) {
9997 memcpy(rsmpInBuffer, (const uint8_t*)mRsmpInBuffer + previousFront * mFrameSize,
9998 part1 * mFrameSize);
9999 mRsmpInRear = part1;
10000 part1 = unread - part1;
10001 if (part1 != 0) {
10002 memcpy((uint8_t*)rsmpInBuffer + mRsmpInRear * mFrameSize,
10003 (const uint8_t*)mRsmpInBuffer, part1 * mFrameSize);
10004 mRsmpInRear += part1;
10005 }
10006 }
10007 // Update front for all clients according to new rear
10008 updateFronts_l(audio_utils::safe_sub_overflow(previousRear, mRsmpInRear));
10009 } else {
10010 mRsmpInRear = 0;
10011 }
10012 free(mRsmpInBuffer);
10013 mRsmpInBuffer = rsmpInBuffer;
10014}
10015
Andy Hungee58e4a2023-07-07 13:47:37 -070010016void RecordThread::addPatchTrack(const sp<IAfPatchRecord>& record)
Eric Laurent83b88082014-06-20 18:31:16 -070010017{
Andy Hung972bec12023-08-31 16:13:39 -070010018 audio_utils::lock_guard _l(mutex());
Eric Laurent83b88082014-06-20 18:31:16 -070010019 mTracks.add(record);
Mikhail Naganov2534b382019-09-25 13:05:02 -070010020 if (record->getSource()) {
10021 mSource = record->getSource();
10022 }
Eric Laurent83b88082014-06-20 18:31:16 -070010023}
10024
Andy Hungee58e4a2023-07-07 13:47:37 -070010025void RecordThread::deletePatchTrack(const sp<IAfPatchRecord>& record)
Eric Laurent83b88082014-06-20 18:31:16 -070010026{
Andy Hung972bec12023-08-31 16:13:39 -070010027 audio_utils::lock_guard _l(mutex());
Mikhail Naganov2534b382019-09-25 13:05:02 -070010028 if (mSource == record->getSource()) {
10029 mSource = mInput;
10030 }
Eric Laurent83b88082014-06-20 18:31:16 -070010031 destroyTrack_l(record);
10032}
10033
Andy Hungee58e4a2023-07-07 13:47:37 -070010034void RecordThread::toAudioPortConfig(struct audio_port_config* config)
Eric Laurent83b88082014-06-20 18:31:16 -070010035{
Mikhail Naganovdc769682018-05-04 15:34:08 -070010036 ThreadBase::toAudioPortConfig(config);
Eric Laurent83b88082014-06-20 18:31:16 -070010037 config->role = AUDIO_PORT_ROLE_SINK;
10038 config->ext.mix.hw_module = mInput->audioHwDev->handle();
10039 config->ext.mix.usecase.source = mAudioSource;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -070010040 if (mInput && mInput->flags != AUDIO_INPUT_FLAG_NONE) {
10041 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
10042 config->flags.input = mInput->flags;
10043 }
Eric Laurent83b88082014-06-20 18:31:16 -070010044}
Eric Laurent1c333e22014-05-20 10:48:17 -070010045
Eric Laurent6acd1d42017-01-04 14:23:29 -080010046// ----------------------------------------------------------------------------
10047// Mmap
10048// ----------------------------------------------------------------------------
10049
Andy Hung7aa7d102023-07-07 15:58:48 -070010050// Mmap stream control interface implementation. Each MmapThreadHandle controls one
10051// MmapPlaybackThread or MmapCaptureThread instance.
10052class MmapThreadHandle : public MmapStreamInterface {
10053public:
10054 explicit MmapThreadHandle(const sp<IAfMmapThread>& thread);
10055 ~MmapThreadHandle() override;
10056
10057 // MmapStreamInterface virtuals
10058 status_t createMmapBuffer(int32_t minSizeFrames,
10059 struct audio_mmap_buffer_info* info) final;
10060 status_t getMmapPosition(struct audio_mmap_position* position) final;
10061 status_t getExternalPosition(uint64_t* position, int64_t* timeNanos) final;
10062 status_t start(const AudioClient& client,
10063 const audio_attributes_t* attr, audio_port_handle_t* handle) final;
10064 status_t stop(audio_port_handle_t handle) final;
10065 status_t standby() final;
10066 status_t reportData(const void* buffer, size_t frameCount) final;
10067private:
10068 const sp<IAfMmapThread> mThread;
10069};
10070
10071/* static */
10072sp<MmapStreamInterface> IAfMmapThread::createMmapStreamInterfaceAdapter(
10073 const sp<IAfMmapThread>& mmapThread) {
10074 return sp<MmapThreadHandle>::make(mmapThread);
10075}
10076
10077MmapThreadHandle::MmapThreadHandle(const sp<IAfMmapThread>& thread)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010078 : mThread(thread)
10079{
Phil Burk9fabbf82017-08-03 12:02:00 -070010080 assert(thread != 0); // thread must start non-null and stay non-null
Eric Laurent6acd1d42017-01-04 14:23:29 -080010081}
10082
Andy Hung7aa7d102023-07-07 15:58:48 -070010083// MmapStreamInterface could be directly implemented by MmapThread excepting this
10084// special handling on adapter dtor.
10085MmapThreadHandle::~MmapThreadHandle()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010086{
Phil Burk9fabbf82017-08-03 12:02:00 -070010087 mThread->disconnect();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010088}
10089
Andy Hung7aa7d102023-07-07 15:58:48 -070010090status_t MmapThreadHandle::createMmapBuffer(int32_t minSizeFrames,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010091 struct audio_mmap_buffer_info *info)
10092{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010093 return mThread->createMmapBuffer(minSizeFrames, info);
10094}
10095
Andy Hung7aa7d102023-07-07 15:58:48 -070010096status_t MmapThreadHandle::getMmapPosition(struct audio_mmap_position* position)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010097{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010098 return mThread->getMmapPosition(position);
10099}
10100
Andy Hung7aa7d102023-07-07 15:58:48 -070010101status_t MmapThreadHandle::getExternalPosition(uint64_t* position,
jiabinb7d8c5a2020-08-26 17:24:52 -070010102 int64_t *timeNanos) {
10103 return mThread->getExternalPosition(position, timeNanos);
10104}
10105
Andy Hung7aa7d102023-07-07 15:58:48 -070010106status_t MmapThreadHandle::start(const AudioClient& client,
jiabind1f1cb62020-03-24 11:57:57 -070010107 const audio_attributes_t *attr, audio_port_handle_t *handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010108{
jiabind1f1cb62020-03-24 11:57:57 -070010109 return mThread->start(client, attr, handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010110}
10111
Andy Hung7aa7d102023-07-07 15:58:48 -070010112status_t MmapThreadHandle::stop(audio_port_handle_t handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010113{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010114 return mThread->stop(handle);
10115}
10116
Andy Hung7aa7d102023-07-07 15:58:48 -070010117status_t MmapThreadHandle::standby()
Eric Laurent18b57012017-02-13 16:23:52 -080010118{
Eric Laurent18b57012017-02-13 16:23:52 -080010119 return mThread->standby();
10120}
10121
Andy Hung7aa7d102023-07-07 15:58:48 -070010122status_t MmapThreadHandle::reportData(const void* buffer, size_t frameCount)
10123{
jiabinfc791ee2023-02-15 19:43:40 +000010124 return mThread->reportData(buffer, frameCount);
10125}
10126
Eric Laurent6acd1d42017-01-04 14:23:29 -080010127
Andy Hungee58e4a2023-07-07 13:47:37 -070010128MmapThread::MmapThread(
Andy Hung583043b2023-07-17 17:05:00 -070010129 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
Andy Hung920f6572022-10-06 12:09:49 -070010130 AudioHwDevice *hwDev, const sp<StreamHalInterface>& stream, bool systemReady, bool isOut)
Andy Hung583043b2023-07-17 17:05:00 -070010131 : ThreadBase(afThreadCallback, id, (isOut ? MMAP_PLAYBACK : MMAP_CAPTURE), systemReady, isOut),
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010132 mSessionId(AUDIO_SESSION_NONE),
François Gaffie0c280aa2018-07-25 10:02:15 +020010133 mPortId(AUDIO_PORT_HANDLE_NONE),
Andy Hung2c6c3bb2017-06-16 14:01:45 -070010134 mHalStream(stream), mHalDevice(hwDev->hwDevice()), mAudioHwDev(hwDev),
Eric Laurent67f97292018-04-20 18:05:41 -070010135 mActiveTracks(&this->mLocalLog),
10136 mHalVolFloat(-1.0f), // Initialize to illegal value so it always gets set properly later.
10137 mNoCallbackWarningCount(0)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010138{
Eric Laurent18b57012017-02-13 16:23:52 -080010139 mStandby = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010140 readHalParameters_l();
10141}
10142
Andy Hungee58e4a2023-07-07 13:47:37 -070010143void MmapThread::onFirstRef()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010144{
10145 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
10146}
10147
Andy Hungee58e4a2023-07-07 13:47:37 -070010148void MmapThread::disconnect()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010149{
Andy Hung8d31fd22023-06-26 19:20:57 -070010150 ActiveTracks<IAfMmapTrack> activeTracks;
Andy Hung3f49ebb2023-09-19 14:48:41 -070010151 audio_port_handle_t localPortId;
Eric Laurent331679c2018-04-16 17:03:16 -070010152 {
Andy Hung972bec12023-08-31 16:13:39 -070010153 audio_utils::lock_guard _l(mutex());
Andy Hung8d31fd22023-06-26 19:20:57 -070010154 for (const sp<IAfMmapTrack>& t : mActiveTracks) {
Eric Laurent331679c2018-04-16 17:03:16 -070010155 activeTracks.add(t);
10156 }
Andy Hung3f49ebb2023-09-19 14:48:41 -070010157 localPortId = mPortId;
Eric Laurent331679c2018-04-16 17:03:16 -070010158 }
Andy Hung8d31fd22023-06-26 19:20:57 -070010159 for (const sp<IAfMmapTrack>& t : activeTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010160 stop(t->portId());
10161 }
Phil Burk9fabbf82017-08-03 12:02:00 -070010162 // This will decrement references and may cause the destruction of this thread.
Eric Laurent6acd1d42017-01-04 14:23:29 -080010163 if (isOutput()) {
Andy Hung3f49ebb2023-09-19 14:48:41 -070010164 AudioSystem::releaseOutput(localPortId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010165 } else {
Andy Hung3f49ebb2023-09-19 14:48:41 -070010166 AudioSystem::releaseInput(localPortId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010167 }
10168}
10169
10170
Andy Hung8d672e02023-09-15 18:19:28 -070010171void MmapThread::configure_l(const audio_attributes_t* attr,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010172 audio_stream_type_t streamType __unused,
10173 audio_session_t sessionId,
10174 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010175 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010176 audio_port_handle_t portId)
10177{
10178 mAttr = *attr;
10179 mSessionId = sessionId;
10180 mCallback = callback;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010181 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010182 mPortId = portId;
10183}
10184
Andy Hungee58e4a2023-07-07 13:47:37 -070010185status_t MmapThread::createMmapBuffer(int32_t minSizeFrames,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010186 struct audio_mmap_buffer_info *info)
10187{
Andy Hung3f49ebb2023-09-19 14:48:41 -070010188 audio_utils::lock_guard l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010189 if (mHalStream == 0) {
10190 return NO_INIT;
10191 }
Eric Laurent18b57012017-02-13 16:23:52 -080010192 mStandby = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010193 return mHalStream->createMmapBuffer(minSizeFrames, info);
10194}
10195
Andy Hungee58e4a2023-07-07 13:47:37 -070010196status_t MmapThread::getMmapPosition(struct audio_mmap_position* position) const
Eric Laurent6acd1d42017-01-04 14:23:29 -080010197{
Andy Hung3f49ebb2023-09-19 14:48:41 -070010198 audio_utils::lock_guard l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010199 if (mHalStream == 0) {
10200 return NO_INIT;
10201 }
10202 return mHalStream->getMmapPosition(position);
10203}
10204
Andy Hungee58e4a2023-07-07 13:47:37 -070010205status_t MmapThread::exitStandby_l()
Eric Laurent331679c2018-04-16 17:03:16 -070010206{
Eric Laurentdda206a2022-07-08 17:28:35 +020010207 // The HAL must receive track metadata before starting the stream
10208 updateMetadata_l();
Eric Laurent331679c2018-04-16 17:03:16 -070010209 status_t ret = mHalStream->start();
10210 if (ret != NO_ERROR) {
10211 ALOGE("%s: error mHalStream->start() = %d for first track", __FUNCTION__, ret);
10212 return ret;
10213 }
Andy Hungcf10d742020-04-28 15:38:24 -070010214 if (mStandby) {
10215 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -070010216 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -070010217 mStandby = false;
10218 }
Eric Laurent331679c2018-04-16 17:03:16 -070010219 return NO_ERROR;
10220}
10221
Andy Hungee58e4a2023-07-07 13:47:37 -070010222status_t MmapThread::start(const AudioClient& client,
jiabind1f1cb62020-03-24 11:57:57 -070010223 const audio_attributes_t *attr,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010224 audio_port_handle_t *handle)
10225{
Andy Hung3f49ebb2023-09-19 14:48:41 -070010226 audio_utils::lock_guard l(mutex());
Eric Laurenta54f1282017-07-01 19:39:32 -070010227 ALOGV("%s clientUid %d mStandby %d mPortId %d *handle %d", __FUNCTION__,
Svet Ganov33761132021-05-13 22:51:08 +000010228 client.attributionSource.uid, mStandby, mPortId, *handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010229 if (mHalStream == 0) {
10230 return NO_INIT;
10231 }
10232
10233 status_t ret;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010234
Eric Laurentdda206a2022-07-08 17:28:35 +020010235 // For the first track, reuse portId and session allocated when the stream was opened.
Eric Laurenta54f1282017-07-01 19:39:32 -070010236 if (*handle == mPortId) {
Andy Hung3f49ebb2023-09-19 14:48:41 -070010237 acquireWakeLock_l();
Eric Laurentdda206a2022-07-08 17:28:35 +020010238 return NO_ERROR;
Eric Laurenta54f1282017-07-01 19:39:32 -070010239 }
10240
10241 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
10242
10243 audio_io_handle_t io = mId;
Andy Hung6cd79802023-07-19 16:56:19 -070010244 const AttributionSourceState adjAttributionSource = afutils::checkAttributionSourcePackage(
Atneya Nairf59db5c2023-05-10 21:37:41 -070010245 client.attributionSource);
10246
Andy Hung3f49ebb2023-09-19 14:48:41 -070010247 const auto localSessionId = mSessionId;
10248 auto localAttr = mAttr;
Eric Laurenta54f1282017-07-01 19:39:32 -070010249 if (isOutput()) {
10250 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
10251 config.sample_rate = mSampleRate;
10252 config.channel_mask = mChannelMask;
10253 config.format = mFormat;
Andy Hung3f49ebb2023-09-19 14:48:41 -070010254 audio_stream_type_t stream = streamType_l();
Eric Laurenta54f1282017-07-01 19:39:32 -070010255 audio_output_flags_t flags =
10256 (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010257 audio_port_handle_t deviceId = mDeviceId;
Kevin Rocard153f92d2018-12-18 18:33:28 -080010258 std::vector<audio_io_handle_t> secondaryOutputs;
Eric Laurentb0a7bc92022-04-05 15:06:08 +020010259 bool isSpatialized;
jiabinc658e452022-10-21 20:52:21 +000010260 bool isBitPerfect;
Andy Hung3f49ebb2023-09-19 14:48:41 -070010261 mutex().unlock();
10262 ret = AudioSystem::getOutputForAttr(&localAttr, &io,
10263 localSessionId,
Eric Laurenta54f1282017-07-01 19:39:32 -070010264 &stream,
Atneya Nairf59db5c2023-05-10 21:37:41 -070010265 adjAttributionSource,
Eric Laurenta54f1282017-07-01 19:39:32 -070010266 &config,
10267 flags,
10268 &deviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -080010269 &portId,
Eric Laurentb0a7bc92022-04-05 15:06:08 +020010270 &secondaryOutputs,
jiabinc658e452022-10-21 20:52:21 +000010271 &isSpatialized,
10272 &isBitPerfect);
Andy Hung3f49ebb2023-09-19 14:48:41 -070010273 mutex().lock();
10274 mAttr = localAttr;
Kevin Rocard153f92d2018-12-18 18:33:28 -080010275 ALOGD_IF(!secondaryOutputs.empty(),
10276 "MmapThread::start does not support secondary outputs, ignoring them");
Eric Laurent6acd1d42017-01-04 14:23:29 -080010277 } else {
Eric Laurenta54f1282017-07-01 19:39:32 -070010278 audio_config_base_t config;
10279 config.sample_rate = mSampleRate;
10280 config.channel_mask = mChannelMask;
10281 config.format = mFormat;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010282 audio_port_handle_t deviceId = mDeviceId;
Andy Hung3f49ebb2023-09-19 14:48:41 -070010283 mutex().unlock();
10284 ret = AudioSystem::getInputForAttr(&localAttr, &io,
Mikhail Naganov2996f672019-04-18 12:29:59 -070010285 RECORD_RIID_INVALID,
Andy Hung3f49ebb2023-09-19 14:48:41 -070010286 localSessionId,
Atneya Nairf59db5c2023-05-10 21:37:41 -070010287 adjAttributionSource,
Eric Laurenta54f1282017-07-01 19:39:32 -070010288 &config,
10289 AUDIO_INPUT_FLAG_MMAP_NOIRQ,
10290 &deviceId,
10291 &portId);
Andy Hung3f49ebb2023-09-19 14:48:41 -070010292 mutex().lock();
10293 // localAttr is const for getInputForAttr.
Eric Laurenta54f1282017-07-01 19:39:32 -070010294 }
10295 // APM should not chose a different input or output stream for the same set of attributes
10296 // and audo configuration
10297 if (ret != NO_ERROR || io != mId) {
10298 ALOGE("%s: error getting output or input from APM (error %d, io %d expected io %d)",
10299 __FUNCTION__, ret, io, mId);
10300 return BAD_VALUE;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010301 }
10302
10303 if (isOutput()) {
Andy Hung3f49ebb2023-09-19 14:48:41 -070010304 mutex().unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -070010305 ret = AudioSystem::startOutput(portId);
Andy Hung3f49ebb2023-09-19 14:48:41 -070010306 mutex().lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010307 } else {
jiabin09609032022-06-15 19:26:01 +000010308 {
10309 // Add the track record before starting input so that the silent status for the
10310 // client can be cached.
jiabin09609032022-06-15 19:26:01 +000010311 setClientSilencedState_l(portId, false /*silenced*/);
10312 }
Andy Hung3f49ebb2023-09-19 14:48:41 -070010313 mutex().unlock();
Eric Laurent4eb58f12018-12-07 16:41:02 -080010314 ret = AudioSystem::startInput(portId);
Andy Hung3f49ebb2023-09-19 14:48:41 -070010315 mutex().lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010316 }
10317
10318 // abort if start is rejected by audio policy manager
10319 if (ret != NO_ERROR) {
Phil Burk7f6b40d2017-02-09 13:18:38 -080010320 ALOGE("%s: error start rejected by AudioPolicyManager = %d", __FUNCTION__, ret);
Eric Tan39ec8d62018-07-24 09:49:29 -070010321 if (!mActiveTracks.isEmpty()) {
Andy Hungc5007f82023-08-29 14:26:09 -070010322 mutex().unlock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010323 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -070010324 AudioSystem::releaseOutput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010325 } else {
Eric Laurentfee19762018-01-29 18:44:13 -080010326 AudioSystem::releaseInput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010327 }
Andy Hungc5007f82023-08-29 14:26:09 -070010328 mutex().lock();
Eric Laurent18b57012017-02-13 16:23:52 -080010329 } else {
10330 mHalStream->stop();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010331 }
jiabin09609032022-06-15 19:26:01 +000010332 eraseClientSilencedState_l(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010333 return PERMISSION_DENIED;
10334 }
10335
Kevin Rocard1f564ac2018-03-29 13:53:10 -070010336 // Given that MmapThread::mAttr is mutable, should a MmapTrack have attributes ?
Andy Hung8d31fd22023-06-26 19:20:57 -070010337 sp<IAfMmapTrack> track = IAfMmapTrack::create(
10338 this, attr == nullptr ? mAttr : *attr, mSampleRate, mFormat,
Svet Ganov33761132021-05-13 22:51:08 +000010339 mChannelMask, mSessionId, isOutput(),
10340 client.attributionSource,
Philip P. Moltmannbda45752020-07-17 16:41:18 -070010341 IPCThreadState::self()->getCallingPid(), portId);
jiabin09609032022-06-15 19:26:01 +000010342 if (!isOutput()) {
10343 track->setSilenced_l(isClientSilenced_l(portId));
10344 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010345
Eric Laurent4eb58f12018-12-07 16:41:02 -080010346 if (isOutput()) {
10347 // force volume update when a new track is added
10348 mHalVolFloat = -1.0f;
10349 } else if (!track->isSilenced_l()) {
Andy Hung8d31fd22023-06-26 19:20:57 -070010350 for (const sp<IAfMmapTrack>& t : mActiveTracks) {
Andy Hung920f6572022-10-06 12:09:49 -070010351 if (t->isSilenced_l()
10352 && t->uid() != static_cast<uid_t>(client.attributionSource.uid)) {
Eric Laurent4eb58f12018-12-07 16:41:02 -080010353 t->invalidate();
Andy Hung920f6572022-10-06 12:09:49 -070010354 }
Eric Laurent4eb58f12018-12-07 16:41:02 -080010355 }
10356 }
10357
Eric Laurent6acd1d42017-01-04 14:23:29 -080010358 mActiveTracks.add(track);
Andy Hung116bc262023-06-20 18:56:17 -070010359 sp<IAfEffectChain> chain = getEffectChain_l(mSessionId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010360 if (chain != 0) {
Andy Hung3f49ebb2023-09-19 14:48:41 -070010361 chain->setStrategy(getStrategyForStream(streamType_l()));
Eric Laurent6acd1d42017-01-04 14:23:29 -080010362 chain->incTrackCnt();
10363 chain->incActiveTrackCnt();
10364 }
10365
Andy Hungc2b11cb2020-04-22 09:04:01 -070010366 track->logBeginInterval(patchSinksToString(&mPatch)); // log to MediaMetrics
Eric Laurent6acd1d42017-01-04 14:23:29 -080010367 *handle = portId;
Eric Laurentdda206a2022-07-08 17:28:35 +020010368
10369 if (mActiveTracks.size() == 1) {
10370 ret = exitStandby_l();
10371 }
10372
Eric Laurent6acd1d42017-01-04 14:23:29 -080010373 broadcast_l();
10374
Eric Laurentdda206a2022-07-08 17:28:35 +020010375 ALOGV("%s DONE status %d handle %d stream %p", __FUNCTION__, ret, *handle, mHalStream.get());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010376
Eric Laurentdda206a2022-07-08 17:28:35 +020010377 return ret;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010378}
10379
Andy Hungee58e4a2023-07-07 13:47:37 -070010380status_t MmapThread::stop(audio_port_handle_t handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010381{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010382 ALOGV("%s handle %d", __FUNCTION__, handle);
Andy Hung3f49ebb2023-09-19 14:48:41 -070010383 audio_utils::lock_guard l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010384
10385 if (mHalStream == 0) {
10386 return NO_INIT;
10387 }
10388
Eric Laurenta54f1282017-07-01 19:39:32 -070010389 if (handle == mPortId) {
Andy Hung3f49ebb2023-09-19 14:48:41 -070010390 releaseWakeLock_l();
Eric Laurenta54f1282017-07-01 19:39:32 -070010391 return NO_ERROR;
10392 }
10393
Andy Hung8d31fd22023-06-26 19:20:57 -070010394 sp<IAfMmapTrack> track;
10395 for (const sp<IAfMmapTrack>& t : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010396 if (handle == t->portId()) {
10397 track = t;
10398 break;
10399 }
10400 }
10401 if (track == 0) {
10402 return BAD_VALUE;
10403 }
10404
10405 mActiveTracks.remove(track);
jiabin09609032022-06-15 19:26:01 +000010406 eraseClientSilencedState_l(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010407
Andy Hungc5007f82023-08-29 14:26:09 -070010408 mutex().unlock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010409 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -070010410 AudioSystem::stopOutput(track->portId());
10411 AudioSystem::releaseOutput(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010412 } else {
Eric Laurentfee19762018-01-29 18:44:13 -080010413 AudioSystem::stopInput(track->portId());
10414 AudioSystem::releaseInput(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010415 }
Andy Hungc5007f82023-08-29 14:26:09 -070010416 mutex().lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010417
Andy Hung116bc262023-06-20 18:56:17 -070010418 sp<IAfEffectChain> chain = getEffectChain_l(track->sessionId());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010419 if (chain != 0) {
10420 chain->decActiveTrackCnt();
10421 chain->decTrackCnt();
10422 }
10423
Eric Laurentdda206a2022-07-08 17:28:35 +020010424 if (mActiveTracks.isEmpty()) {
10425 mHalStream->stop();
10426 }
10427
Eric Laurent6acd1d42017-01-04 14:23:29 -080010428 broadcast_l();
10429
Eric Laurent6acd1d42017-01-04 14:23:29 -080010430 return NO_ERROR;
10431}
10432
Andy Hungee58e4a2023-07-07 13:47:37 -070010433status_t MmapThread::standby()
Andy Hung3f49ebb2023-09-19 14:48:41 -070010434NO_THREAD_SAFETY_ANALYSIS // clang bug
Eric Laurent18b57012017-02-13 16:23:52 -080010435{
10436 ALOGV("%s", __FUNCTION__);
Atneya Nair97a73882023-10-30 20:26:21 -070010437 audio_utils::lock_guard l_{mutex()};
Eric Laurent18b57012017-02-13 16:23:52 -080010438
10439 if (mHalStream == 0) {
10440 return NO_INIT;
10441 }
Eric Tan39ec8d62018-07-24 09:49:29 -070010442 if (!mActiveTracks.isEmpty()) {
Eric Laurent18b57012017-02-13 16:23:52 -080010443 return INVALID_OPERATION;
10444 }
10445 mHalStream->standby();
Andy Hungcf10d742020-04-28 15:38:24 -070010446 if (!mStandby) {
10447 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -070010448 mThreadSnapshot.onEnd();
Andy Hungcf10d742020-04-28 15:38:24 -070010449 mStandby = true;
10450 }
Andy Hung3f49ebb2023-09-19 14:48:41 -070010451 releaseWakeLock_l();
Eric Laurent18b57012017-02-13 16:23:52 -080010452 return NO_ERROR;
10453}
10454
Andy Hungee58e4a2023-07-07 13:47:37 -070010455status_t MmapThread::reportData(const void* /*buffer*/, size_t /*frameCount*/) {
jiabinfc791ee2023-02-15 19:43:40 +000010456 // This is a stub implementation. The MmapPlaybackThread overrides this function.
10457 return INVALID_OPERATION;
10458}
10459
Andy Hungee58e4a2023-07-07 13:47:37 -070010460void MmapThread::readHalParameters_l()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010461{
10462 status_t result = mHalStream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
10463 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
10464 mFormat = mHALFormat;
10465 LOG_ALWAYS_FATAL_IF(!audio_is_linear_pcm(mFormat), "HAL format %#x is not linear pcm", mFormat);
10466 result = mHalStream->getFrameSize(&mFrameSize);
10467 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
Hayden Gomes1a89ab32020-06-12 11:05:47 -070010468 LOG_ALWAYS_FATAL_IF(mFrameSize <= 0, "Error frame size was %zu but must be greater than zero",
10469 mFrameSize);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010470 result = mHalStream->getBufferSize(&mBufferSize);
10471 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
10472 mFrameCount = mBufferSize / mFrameSize;
Andy Hungc2b11cb2020-04-22 09:04:01 -070010473
Andy Hungcf10d742020-04-28 15:38:24 -070010474 // TODO: make a readHalParameters call?
10475 mediametrics::LogItem item(mThreadMetrics.getMetricsId());
Andy Hungc2b11cb2020-04-22 09:04:01 -070010476 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
Andy Hung25a80ac2023-07-19 12:47:35 -070010477 .set(AMEDIAMETRICS_PROP_ENCODING, IAfThreadBase::formatToString(mFormat).c_str())
Andy Hungc2b11cb2020-04-22 09:04:01 -070010478 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
10479 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
10480 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
10481 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mFrameCount)
10482 /*
10483 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
10484 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELMASK,
10485 (int32_t)mHapticChannelMask)
10486 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELCOUNT,
10487 (int32_t)mHapticChannelCount)
10488 */
10489 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_ENCODING,
Andy Hung25a80ac2023-07-19 12:47:35 -070010490 IAfThreadBase::formatToString(mHALFormat).c_str())
Andy Hungc2b11cb2020-04-22 09:04:01 -070010491 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_FRAMECOUNT,
10492 (int32_t)mFrameCount) // sic - added HAL
10493 .record();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010494}
10495
Andy Hungee58e4a2023-07-07 13:47:37 -070010496bool MmapThread::threadLoop()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010497{
Andy Hungab65b182023-09-06 19:41:47 -070010498 {
10499 audio_utils::unique_lock _l(mutex());
10500 checkSilentMode_l();
10501 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010502
10503 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
10504
10505 while (!exitPending())
10506 {
Andy Hung116bc262023-06-20 18:56:17 -070010507 Vector<sp<IAfEffectChain>> effectChains;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010508
Andy Hung13850be2019-03-14 11:33:09 -070010509 { // under Thread lock
Andy Hungc5007f82023-08-29 14:26:09 -070010510 audio_utils::unique_lock _l(mutex());
Andy Hung13850be2019-03-14 11:33:09 -070010511
Eric Laurent6acd1d42017-01-04 14:23:29 -080010512 if (mSignalPending) {
10513 // A signal was raised while we were unlocked
10514 mSignalPending = false;
10515 } else {
10516 if (mConfigEvents.isEmpty()) {
10517 // we're about to wait, flush the binder command buffer
10518 IPCThreadState::self()->flushCommands();
10519
10520 if (exitPending()) {
10521 break;
10522 }
10523
Eric Laurent6acd1d42017-01-04 14:23:29 -080010524 // wait until we have something to do...
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +000010525 ALOGV("%s going to sleep", myName.c_str());
Andy Hungc5007f82023-08-29 14:26:09 -070010526 mWaitWorkCV.wait(_l);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +000010527 ALOGV("%s waking up", myName.c_str());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010528
10529 checkSilentMode_l();
10530
10531 continue;
10532 }
10533 }
10534
10535 processConfigEvents_l();
10536
10537 processVolume_l();
10538
10539 checkInvalidTracks_l();
10540
Andy Hungab65b182023-09-06 19:41:47 -070010541 mActiveTracks.updatePowerState_l(this);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010542
Kevin Rocard069c2712018-03-29 19:09:14 -070010543 updateMetadata_l();
10544
Eric Laurent6acd1d42017-01-04 14:23:29 -080010545 lockEffectChains_l(effectChains);
Andy Hung13850be2019-03-14 11:33:09 -070010546 } // release Thread lock
10547
Eric Laurent6acd1d42017-01-04 14:23:29 -080010548 for (size_t i = 0; i < effectChains.size(); i ++) {
Andy Hung13850be2019-03-14 11:33:09 -070010549 effectChains[i]->process_l(); // Thread is not locked, but effect chain is locked
Eric Laurent6acd1d42017-01-04 14:23:29 -080010550 }
Andy Hung13850be2019-03-14 11:33:09 -070010551
10552 // enable changes in effect chain, including moving to another thread.
Eric Laurent6acd1d42017-01-04 14:23:29 -080010553 unlockEffectChains(effectChains);
10554 // Effect chains will be actually deleted here if they were removed from
10555 // mEffectChains list during mixing or effects processing
10556 }
10557
10558 threadLoop_exit();
10559
10560 if (!mStandby) {
10561 threadLoop_standby();
10562 mStandby = true;
10563 }
10564
Eric Laurent6acd1d42017-01-04 14:23:29 -080010565 ALOGV("Thread %p type %d exiting", this, mType);
10566 return false;
10567}
10568
Andy Hungc5007f82023-08-29 14:26:09 -070010569// checkForNewParameter_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -070010570bool MmapThread::checkForNewParameter_l(const String8& keyValuePair,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010571 status_t& status)
10572{
10573 AudioParameter param = AudioParameter(keyValuePair);
10574 int value;
Eric Laurente6e9a482017-07-25 19:26:02 -070010575 bool sendToHal = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010576 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -070010577 LOG_FATAL("Should not happen set routing device in MmapThread");
Eric Laurent6acd1d42017-01-04 14:23:29 -080010578 }
Eric Laurente6e9a482017-07-25 19:26:02 -070010579 if (sendToHal) {
10580 status = mHalStream->setParameters(keyValuePair);
10581 } else {
10582 status = NO_ERROR;
10583 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010584
10585 return false;
10586}
10587
Andy Hungee58e4a2023-07-07 13:47:37 -070010588String8 MmapThread::getParameters(const String8& keys)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010589{
Andy Hung972bec12023-08-31 16:13:39 -070010590 audio_utils::lock_guard _l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010591 String8 out_s8;
10592 if (initCheck() == NO_ERROR && mHalStream->getParameters(keys, &out_s8) == OK) {
10593 return out_s8;
10594 }
Andy Hung920f6572022-10-06 12:09:49 -070010595 return {};
Eric Laurent6acd1d42017-01-04 14:23:29 -080010596}
10597
Andy Hungab65b182023-09-06 19:41:47 -070010598void MmapThread::ioConfigChanged_l(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -070010599 audio_port_handle_t portId __unused) {
Mikhail Naganov88536df2021-07-26 17:30:29 -070010600 sp<AudioIoDescriptor> desc;
10601 bool isInput = false;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010602 switch (event) {
10603 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -070010604 case AUDIO_INPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -080010605 case AUDIO_INPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -070010606 isInput = true;
10607 FALLTHROUGH_INTENDED;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010608 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -070010609 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -080010610 case AUDIO_OUTPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -070010611 desc = sp<AudioIoDescriptor>::make(mId, mPatch, isInput,
10612 mSampleRate, mFormat, mChannelMask, mFrameCount, mFrameCount);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010613 break;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010614 case AUDIO_INPUT_CLOSED:
10615 case AUDIO_OUTPUT_CLOSED:
10616 default:
Mikhail Naganov88536df2021-07-26 17:30:29 -070010617 desc = sp<AudioIoDescriptor>::make(mId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010618 break;
10619 }
Andy Hungab65b182023-09-06 19:41:47 -070010620 mAfThreadCallback->ioConfigChanged_l(event, desc, pid);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010621}
10622
Andy Hungee58e4a2023-07-07 13:47:37 -070010623status_t MmapThread::createAudioPatch_l(const struct audio_patch* patch,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010624 audio_patch_handle_t *handle)
Andy Hungc5007f82023-08-29 14:26:09 -070010625NO_THREAD_SAFETY_ANALYSIS // elease and re-acquire mutex()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010626{
10627 status_t status = NO_ERROR;
10628
10629 // store new device and send to effects
10630 audio_devices_t type = AUDIO_DEVICE_NONE;
10631 audio_port_handle_t deviceId;
jiabinc52b1ff2019-10-31 17:20:42 -070010632 AudioDeviceTypeAddrVector sinkDeviceTypeAddrs;
10633 AudioDeviceTypeAddr sourceDeviceTypeAddr;
10634 uint32_t numDevices = 0;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010635 if (isOutput()) {
10636 for (unsigned int i = 0; i < patch->num_sinks; i++) {
jiabinc52b1ff2019-10-31 17:20:42 -070010637 LOG_ALWAYS_FATAL_IF(popcount(patch->sinks[i].ext.device.type) > 1
10638 && !mAudioHwDev->supportsAudioPatches(),
10639 "Enumerated device type(%#x) must not be used "
10640 "as it does not support audio patches",
10641 patch->sinks[i].ext.device.type);
Mikhail Naganov55773032020-10-01 15:08:13 -070010642 type = static_cast<audio_devices_t>(type | patch->sinks[i].ext.device.type);
Andy Hung920f6572022-10-06 12:09:49 -070010643 sinkDeviceTypeAddrs.emplace_back(patch->sinks[i].ext.device.type,
10644 patch->sinks[i].ext.device.address);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010645 }
10646 deviceId = patch->sinks[0].id;
jiabinc52b1ff2019-10-31 17:20:42 -070010647 numDevices = mPatch.num_sinks;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010648 } else {
10649 type = patch->sources[0].ext.device.type;
10650 deviceId = patch->sources[0].id;
jiabinc52b1ff2019-10-31 17:20:42 -070010651 numDevices = mPatch.num_sources;
10652 sourceDeviceTypeAddr.mType = patch->sources[0].ext.device.type;
jiabin0a488932020-08-07 17:32:40 -070010653 sourceDeviceTypeAddr.setAddress(patch->sources[0].ext.device.address);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010654 }
10655
10656 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -080010657 if (isOutput()) {
10658 mEffectChains[i]->setDevices_l(sinkDeviceTypeAddrs);
10659 } else {
10660 mEffectChains[i]->setInputDevice_l(sourceDeviceTypeAddr);
10661 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010662 }
10663
jiabinc52b1ff2019-10-31 17:20:42 -070010664 if (!isOutput()) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010665 // store new source and send to effects
10666 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
10667 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
10668 for (size_t i = 0; i < mEffectChains.size(); i++) {
10669 mEffectChains[i]->setAudioSource_l(mAudioSource);
10670 }
10671 }
10672 }
10673
jiabin78b86f22024-02-22 00:39:29 +000010674 // For mmap streams, once the routing has changed, they will be disconnected. It should be
10675 // okay to notify the client earlier before the new patch creation.
10676 if (mDeviceId != deviceId) {
10677 if (const sp<MmapStreamCallback> callback = mCallback.promote()) {
10678 // The aaudioservice handle the routing changed event asynchronously. In that case,
10679 // it is safe to hold the lock here.
10680 callback->onRoutingChanged(deviceId);
10681 }
10682 }
10683
Eric Laurent6acd1d42017-01-04 14:23:29 -080010684 if (mAudioHwDev->supportsAudioPatches()) {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010685 status = mHalDevice->createAudioPatch(patch->num_sources, patch->sources, patch->num_sinks,
10686 patch->sinks, handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010687 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010688 audio_port_config port;
10689 std::optional<audio_source_t> source;
10690 if (isOutput()) {
10691 port = patch->sinks[0];
Eric Laurent6acd1d42017-01-04 14:23:29 -080010692 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010693 port = patch->sources[0];
10694 source = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010695 }
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010696 status = mHalStream->legacyCreateAudioPatch(port, source, type);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010697 *handle = AUDIO_PATCH_HANDLE_NONE;
10698 }
10699
jiabinc52b1ff2019-10-31 17:20:42 -070010700 if (numDevices == 0 || mDeviceId != deviceId) {
10701 if (isOutput()) {
10702 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
10703 mOutDeviceTypeAddrs = sinkDeviceTypeAddrs;
jiabin0a957d32020-04-29 10:56:20 -070010704 checkSilentMode_l();
jiabinc52b1ff2019-10-31 17:20:42 -070010705 } else {
10706 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
10707 mInDeviceTypeAddr = sourceDeviceTypeAddr;
10708 }
jiabinc52b1ff2019-10-31 17:20:42 -070010709 mPatch = *patch;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010710 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010711 }
Eric Laurentdda206a2022-07-08 17:28:35 +020010712 // Force meteadata update after a route change
10713 mActiveTracks.setHasChanged();
10714
Eric Laurent6acd1d42017-01-04 14:23:29 -080010715 return status;
10716}
10717
Andy Hungee58e4a2023-07-07 13:47:37 -070010718status_t MmapThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010719{
10720 status_t status = NO_ERROR;
10721
jiabinc52b1ff2019-10-31 17:20:42 -070010722 mPatch = audio_patch{};
10723 mOutDeviceTypeAddrs.clear();
10724 mInDeviceTypeAddr.reset();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010725
10726 bool supportsAudioPatches = mHalDevice->supportsAudioPatches(&supportsAudioPatches) == OK ?
10727 supportsAudioPatches : false;
10728
10729 if (supportsAudioPatches) {
10730 status = mHalDevice->releaseAudioPatch(handle);
10731 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010732 status = mHalStream->legacyReleaseAudioPatch();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010733 }
Eric Laurentdda206a2022-07-08 17:28:35 +020010734 // Force meteadata update after a route change
10735 mActiveTracks.setHasChanged();
10736
Eric Laurent6acd1d42017-01-04 14:23:29 -080010737 return status;
10738}
10739
Andy Hungee58e4a2023-07-07 13:47:37 -070010740void MmapThread::toAudioPortConfig(struct audio_port_config* config)
Andy Hung3f49ebb2023-09-19 14:48:41 -070010741NO_THREAD_SAFETY_ANALYSIS // mAudioHwDev handle access
Eric Laurent6acd1d42017-01-04 14:23:29 -080010742{
Mikhail Naganovdc769682018-05-04 15:34:08 -070010743 ThreadBase::toAudioPortConfig(config);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010744 if (isOutput()) {
10745 config->role = AUDIO_PORT_ROLE_SOURCE;
10746 config->ext.mix.hw_module = mAudioHwDev->handle();
10747 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
10748 } else {
10749 config->role = AUDIO_PORT_ROLE_SINK;
10750 config->ext.mix.hw_module = mAudioHwDev->handle();
10751 config->ext.mix.usecase.source = mAudioSource;
10752 }
10753}
10754
Andy Hungee58e4a2023-07-07 13:47:37 -070010755status_t MmapThread::addEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010756{
10757 audio_session_t session = chain->sessionId();
10758
10759 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
10760 // Attach all tracks with same session ID to this chain.
10761 // indicate all active tracks in the chain
Andy Hung8d31fd22023-06-26 19:20:57 -070010762 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010763 if (session == track->sessionId()) {
10764 chain->incTrackCnt();
10765 chain->incActiveTrackCnt();
10766 }
10767 }
10768
10769 chain->setThread(this);
10770 chain->setInBuffer(nullptr);
10771 chain->setOutBuffer(nullptr);
Shunkai Yaod125e402024-01-20 03:19:06 +000010772 chain->syncHalEffectsState_l();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010773
10774 mEffectChains.add(chain);
10775 checkSuspendOnAddEffectChain_l(chain);
10776 return NO_ERROR;
10777}
10778
Andy Hungee58e4a2023-07-07 13:47:37 -070010779size_t MmapThread::removeEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010780{
10781 audio_session_t session = chain->sessionId();
10782
10783 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
10784
10785 for (size_t i = 0; i < mEffectChains.size(); i++) {
10786 if (chain == mEffectChains[i]) {
10787 mEffectChains.removeAt(i);
10788 // detach all active tracks from the chain
10789 // detach all tracks with same session ID from this chain
Andy Hung8d31fd22023-06-26 19:20:57 -070010790 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010791 if (session == track->sessionId()) {
10792 chain->decActiveTrackCnt();
10793 chain->decTrackCnt();
10794 }
10795 }
10796 break;
10797 }
10798 }
10799 return mEffectChains.size();
10800}
10801
Andy Hungee58e4a2023-07-07 13:47:37 -070010802void MmapThread::threadLoop_standby()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010803{
10804 mHalStream->standby();
10805}
10806
Andy Hungee58e4a2023-07-07 13:47:37 -070010807void MmapThread::threadLoop_exit()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010808{
Phil Burk7dce7282017-09-27 13:51:41 -070010809 // Do not call callback->onTearDown() because it is redundant for thread exit
10810 // and because it can cause a recursive mutex lock on stop().
Eric Laurent6acd1d42017-01-04 14:23:29 -080010811}
10812
Andy Hungee58e4a2023-07-07 13:47:37 -070010813status_t MmapThread::setSyncEvent(const sp<SyncEvent>& /* event */)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010814{
10815 return BAD_VALUE;
10816}
10817
Andy Hungee58e4a2023-07-07 13:47:37 -070010818bool MmapThread::isValidSyncEvent(
10819 const sp<SyncEvent>& /* event */) const
Eric Laurent6acd1d42017-01-04 14:23:29 -080010820{
10821 return false;
10822}
10823
Andy Hungee58e4a2023-07-07 13:47:37 -070010824status_t MmapThread::checkEffectCompatibility_l(
Eric Laurent6acd1d42017-01-04 14:23:29 -080010825 const effect_descriptor_t *desc, audio_session_t sessionId)
10826{
10827 // No global effect sessions on mmap threads
Eric Laurent3f75a5b2019-11-12 15:55:51 -080010828 if (audio_is_global_session(sessionId)) {
10829 ALOGW("checkEffectCompatibility_l(): global effect %s on MMAP thread %s",
Eric Laurent6acd1d42017-01-04 14:23:29 -080010830 desc->name, mThreadName);
10831 return BAD_VALUE;
10832 }
10833
10834 if (!isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC)) {
10835 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on capture mmap thread",
10836 desc->name);
10837 return BAD_VALUE;
10838 }
10839 if (isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Glenn Kastend3bb6452016-12-05 18:14:37 -080010840 ALOGW("checkEffectCompatibility_l(): pre processing effect %s created on playback mmap "
10841 "thread", desc->name);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010842 return BAD_VALUE;
10843 }
10844
10845 // Only allow effects without processing load or latency
10846 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) != EFFECT_FLAG_NO_PROCESS) {
10847 return BAD_VALUE;
10848 }
10849
Andy Hung116bc262023-06-20 18:56:17 -070010850 if (IAfEffectModule::isHapticGenerator(&desc->type)) {
jiabineb3bda02020-06-30 14:07:03 -070010851 ALOGE("%s(): HapticGenerator is not supported for MmapThread", __func__);
10852 return BAD_VALUE;
10853 }
10854
Eric Laurent6acd1d42017-01-04 14:23:29 -080010855 return NO_ERROR;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010856}
10857
Andy Hungee58e4a2023-07-07 13:47:37 -070010858void MmapThread::checkInvalidTracks_l()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010859{
Andy Hung8d31fd22023-06-26 19:20:57 -070010860 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010861 if (track->isInvalid()) {
jiabin78b86f22024-02-22 00:39:29 +000010862 if (const sp<MmapStreamCallback> callback = mCallback.promote()) {
10863 // The aaudioservice handle the routing changed event asynchronously. In that case,
10864 // it is safe to hold the lock here.
10865 callback->onRoutingChanged(AUDIO_PORT_HANDLE_NONE);
10866 } else if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
Eric Laurent039c24a2022-10-07 14:01:59 +020010867 ALOGW("Could not notify MMAP stream tear down: no onRoutingChanged callback!");
10868 mNoCallbackWarningCount++;
10869 }
10870 break;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010871 }
10872 }
10873}
10874
Andy Hungee58e4a2023-07-07 13:47:37 -070010875void MmapThread::dumpInternals_l(int fd, const Vector<String16>& /* args */)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010876{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010877 dprintf(fd, " Attributes: content type %d usage %d source %d\n",
10878 mAttr.content_type, mAttr.usage, mAttr.source);
10879 dprintf(fd, " Session: %d port Id: %d\n", mSessionId, mPortId);
Eric Tan39ec8d62018-07-24 09:49:29 -070010880 if (mActiveTracks.isEmpty()) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010881 dprintf(fd, " No active clients\n");
10882 }
10883}
10884
Andy Hungee58e4a2023-07-07 13:47:37 -070010885void MmapThread::dumpTracks_l(int fd, const Vector<String16>& /* args */)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010886{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010887 String8 result;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010888 size_t numtracks = mActiveTracks.size();
Andy Hung2c6c3bb2017-06-16 14:01:45 -070010889 dprintf(fd, " %zu Tracks\n", numtracks);
10890 const char *prefix = " ";
Eric Laurent6acd1d42017-01-04 14:23:29 -080010891 if (numtracks) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -070010892 result.append(prefix);
Kevin Rocard5f2136e2018-05-11 22:03:00 -070010893 mActiveTracks[0]->appendDumpHeader(result);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010894 for (size_t i = 0; i < numtracks ; ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -070010895 sp<IAfMmapTrack> track = mActiveTracks[i];
Andy Hung2c6c3bb2017-06-16 14:01:45 -070010896 result.append(prefix);
10897 track->appendDump(result, true /* active */);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010898 }
10899 } else {
10900 dprintf(fd, "\n");
10901 }
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +000010902 write(fd, result.c_str(), result.size());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010903}
10904
Andy Hungee58e4a2023-07-07 13:47:37 -070010905/* static */
10906sp<IAfMmapPlaybackThread> IAfMmapPlaybackThread::create(
Andy Hung583043b2023-07-17 17:05:00 -070010907 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
Andy Hungee58e4a2023-07-07 13:47:37 -070010908 AudioHwDevice* hwDev, AudioStreamOut* output, bool systemReady) {
Andy Hung583043b2023-07-17 17:05:00 -070010909 return sp<MmapPlaybackThread>::make(afThreadCallback, id, hwDev, output, systemReady);
Andy Hungee58e4a2023-07-07 13:47:37 -070010910}
10911
10912MmapPlaybackThread::MmapPlaybackThread(
Andy Hung583043b2023-07-17 17:05:00 -070010913 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
jiabinc52b1ff2019-10-31 17:20:42 -070010914 AudioHwDevice *hwDev, AudioStreamOut *output, bool systemReady)
Andy Hung583043b2023-07-17 17:05:00 -070010915 : MmapThread(afThreadCallback, id, hwDev, output->stream, systemReady, true /* isOut */),
Eric Laurent6acd1d42017-01-04 14:23:29 -080010916 mStreamType(AUDIO_STREAM_MUSIC),
Phil Burk56ecf3e2018-03-12 15:38:17 -070010917 mOutput(output)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010918{
10919 snprintf(mThreadName, kThreadNameLength, "AudioMmapOut_%X", id);
10920 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Andy Hung583043b2023-07-17 17:05:00 -070010921 mMasterVolume = afThreadCallback->masterVolume_l();
10922 mMasterMute = afThreadCallback->masterMute_l();
Eric Laurent1f9b5e62023-07-03 18:14:07 +020010923
10924 for (int i = AUDIO_STREAM_MIN; i < AUDIO_STREAM_FOR_POLICY_CNT; ++i) {
10925 const audio_stream_type_t stream{static_cast<audio_stream_type_t>(i)};
10926 mStreamTypes[stream].volume = 0.0f;
Andy Hung583043b2023-07-17 17:05:00 -070010927 mStreamTypes[stream].mute = mAfThreadCallback->streamMute_l(stream);
Eric Laurent1f9b5e62023-07-03 18:14:07 +020010928 }
10929 // Audio patch and call assistant volume are always max
10930 mStreamTypes[AUDIO_STREAM_PATCH].volume = 1.0f;
10931 mStreamTypes[AUDIO_STREAM_PATCH].mute = false;
10932 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].volume = 1.0f;
10933 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].mute = false;
10934
Eric Laurent6acd1d42017-01-04 14:23:29 -080010935 if (mAudioHwDev) {
10936 if (mAudioHwDev->canSetMasterVolume()) {
10937 mMasterVolume = 1.0;
10938 }
10939
10940 if (mAudioHwDev->canSetMasterMute()) {
10941 mMasterMute = false;
10942 }
10943 }
10944}
10945
Andy Hungee58e4a2023-07-07 13:47:37 -070010946void MmapPlaybackThread::configure(const audio_attributes_t* attr,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010947 audio_stream_type_t streamType,
10948 audio_session_t sessionId,
10949 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010950 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010951 audio_port_handle_t portId)
10952{
Andy Hung8d672e02023-09-15 18:19:28 -070010953 audio_utils::lock_guard l(mutex());
10954 MmapThread::configure_l(attr, streamType, sessionId, callback, deviceId, portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010955 mStreamType = streamType;
10956}
10957
Andy Hungee58e4a2023-07-07 13:47:37 -070010958AudioStreamOut* MmapPlaybackThread::clearOutput()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010959{
Andy Hung972bec12023-08-31 16:13:39 -070010960 audio_utils::lock_guard _l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010961 AudioStreamOut *output = mOutput;
10962 mOutput = NULL;
10963 return output;
10964}
10965
Andy Hungee58e4a2023-07-07 13:47:37 -070010966void MmapPlaybackThread::setMasterVolume(float value)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010967{
Andy Hung972bec12023-08-31 16:13:39 -070010968 audio_utils::lock_guard _l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010969 // Don't apply master volume in SW if our HAL can do it for us.
10970 if (mAudioHwDev &&
10971 mAudioHwDev->canSetMasterVolume()) {
10972 mMasterVolume = 1.0;
10973 } else {
10974 mMasterVolume = value;
10975 }
10976}
10977
Andy Hungee58e4a2023-07-07 13:47:37 -070010978void MmapPlaybackThread::setMasterMute(bool muted)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010979{
Andy Hung972bec12023-08-31 16:13:39 -070010980 audio_utils::lock_guard _l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010981 // Don't apply master mute in SW if our HAL can do it for us.
10982 if (mAudioHwDev && mAudioHwDev->canSetMasterMute()) {
10983 mMasterMute = false;
10984 } else {
10985 mMasterMute = muted;
10986 }
10987}
10988
Andy Hungee58e4a2023-07-07 13:47:37 -070010989void MmapPlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010990{
Andy Hung972bec12023-08-31 16:13:39 -070010991 audio_utils::lock_guard _l(mutex());
Eric Laurent1f9b5e62023-07-03 18:14:07 +020010992 mStreamTypes[stream].volume = value;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010993 if (stream == mStreamType) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010994 broadcast_l();
10995 }
10996}
10997
Andy Hungee58e4a2023-07-07 13:47:37 -070010998float MmapPlaybackThread::streamVolume(audio_stream_type_t stream) const
Eric Laurent6acd1d42017-01-04 14:23:29 -080010999{
Andy Hung972bec12023-08-31 16:13:39 -070011000 audio_utils::lock_guard _l(mutex());
Eric Laurent1f9b5e62023-07-03 18:14:07 +020011001 return mStreamTypes[stream].volume;
Eric Laurent6acd1d42017-01-04 14:23:29 -080011002}
11003
Andy Hungee58e4a2023-07-07 13:47:37 -070011004void MmapPlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
Eric Laurent6acd1d42017-01-04 14:23:29 -080011005{
Andy Hung972bec12023-08-31 16:13:39 -070011006 audio_utils::lock_guard _l(mutex());
Eric Laurent1f9b5e62023-07-03 18:14:07 +020011007 mStreamTypes[stream].mute = muted;
Eric Laurent6acd1d42017-01-04 14:23:29 -080011008 if (stream == mStreamType) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080011009 broadcast_l();
11010 }
11011}
11012
Andy Hungee58e4a2023-07-07 13:47:37 -070011013void MmapPlaybackThread::invalidateTracks(audio_stream_type_t streamType)
Eric Laurent6acd1d42017-01-04 14:23:29 -080011014{
Andy Hung972bec12023-08-31 16:13:39 -070011015 audio_utils::lock_guard _l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080011016 if (streamType == mStreamType) {
Andy Hung8d31fd22023-06-26 19:20:57 -070011017 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080011018 track->invalidate();
11019 }
11020 broadcast_l();
11021 }
11022}
11023
Andy Hungee58e4a2023-07-07 13:47:37 -070011024void MmapPlaybackThread::invalidateTracks(std::set<audio_port_handle_t>& portIds)
jiabinc44b3462022-12-08 12:52:31 -080011025{
Andy Hung972bec12023-08-31 16:13:39 -070011026 audio_utils::lock_guard _l(mutex());
jiabinc44b3462022-12-08 12:52:31 -080011027 bool trackMatch = false;
Andy Hung8d31fd22023-06-26 19:20:57 -070011028 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
jiabinc44b3462022-12-08 12:52:31 -080011029 if (portIds.find(track->portId()) != portIds.end()) {
11030 track->invalidate();
11031 trackMatch = true;
11032 portIds.erase(track->portId());
11033 }
11034 if (portIds.empty()) {
11035 break;
11036 }
11037 }
11038 if (trackMatch) {
11039 broadcast_l();
11040 }
11041}
11042
Andy Hungee58e4a2023-07-07 13:47:37 -070011043void MmapPlaybackThread::processVolume_l()
Andy Hung920f6572022-10-06 12:09:49 -070011044NO_THREAD_SAFETY_ANALYSIS // access of track->processMuteEvent_l
Eric Laurent6acd1d42017-01-04 14:23:29 -080011045{
11046 float volume;
11047
Eric Laurent1f9b5e62023-07-03 18:14:07 +020011048 if (mMasterMute || streamMuted_l()) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080011049 volume = 0;
11050 } else {
Eric Laurent1f9b5e62023-07-03 18:14:07 +020011051 volume = mMasterVolume * streamVolume_l();
Eric Laurent6acd1d42017-01-04 14:23:29 -080011052 }
11053
11054 if (volume != mHalVolFloat) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080011055 // Convert volumes from float to 8.24
11056 uint32_t vol = (uint32_t)(volume * (1 << 24));
11057
11058 // Delegate volume control to effect in track effect chain if needed
11059 // only one effect chain can be present on DirectOutputThread, so if
11060 // there is one, the track is connected to it
11061 if (!mEffectChains.isEmpty()) {
Shunkai Yaof4847652024-01-12 00:25:20 +000011062 mEffectChains[0]->setVolume(&vol, &vol);
Eric Laurent6acd1d42017-01-04 14:23:29 -080011063 volume = (float)vol / (1 << 24);
11064 }
Eric Laurentdff774a2017-04-21 15:29:38 -070011065 // Try to use HW volume control and fall back to SW control if not implemented
Phil Burk56ecf3e2018-03-12 15:38:17 -070011066 if (mOutput->stream->setVolume(volume, volume) == NO_ERROR) {
11067 mHalVolFloat = volume; // HW volume control worked, so update value.
11068 mNoCallbackWarningCount = 0;
11069 } else {
Eric Laurentdff774a2017-04-21 15:29:38 -070011070 sp<MmapStreamCallback> callback = mCallback.promote();
11071 if (callback != 0) {
Phil Burk56ecf3e2018-03-12 15:38:17 -070011072 mHalVolFloat = volume; // SW volume control worked, so update value.
11073 mNoCallbackWarningCount = 0;
Andy Hungc5007f82023-08-29 14:26:09 -070011074 mutex().unlock();
Robert Wu4389ae62022-02-17 18:39:41 +000011075 callback->onVolumeChanged(volume);
Andy Hungc5007f82023-08-29 14:26:09 -070011076 mutex().lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080011077 } else {
Phil Burk56ecf3e2018-03-12 15:38:17 -070011078 if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
11079 ALOGW("Could not set MMAP stream volume: no volume callback!");
11080 mNoCallbackWarningCount++;
11081 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080011082 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080011083 }
Andy Hung8d31fd22023-06-26 19:20:57 -070011084 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Jasmine Chaeaa10e42021-05-11 10:11:14 +080011085 track->setMetadataHasChanged();
Andy Hung583043b2023-07-17 17:05:00 -070011086 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
Vlad Popaec1788e2022-08-04 11:23:30 +020011087 /*muteState=*/{mMasterMute,
Eric Laurent1f9b5e62023-07-03 18:14:07 +020011088 streamVolume_l() == 0.f,
11089 streamMuted_l(),
Vlad Popaec1788e2022-08-04 11:23:30 +020011090 // TODO(b/241533526): adjust logic to include mute from AppOps
11091 false /*muteFromPlaybackRestricted*/,
11092 false /*muteFromClientVolume*/,
11093 false /*muteFromVolumeShaper*/});
Jasmine Chaeaa10e42021-05-11 10:11:14 +080011094 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080011095 }
11096}
11097
Andy Hungee58e4a2023-07-07 13:47:37 -070011098ThreadBase::MetadataUpdate MmapPlaybackThread::updateMetadata_l()
Kevin Rocard069c2712018-03-29 19:09:14 -070011099{
Jasmine Chaeaa10e42021-05-11 10:11:14 +080011100 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
Vlad Popa7e81cea2023-01-19 16:34:16 +010011101 return {}; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -070011102 }
11103 StreamOutHalInterface::SourceMetadata metadata;
Andy Hung8d31fd22023-06-26 19:20:57 -070011104 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Kevin Rocard069c2712018-03-29 19:09:14 -070011105 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurent94579172020-11-20 18:41:04 +010011106 playback_track_metadata_v7_t trackMetadata;
11107 trackMetadata.base = {
Kevin Rocard069c2712018-03-29 19:09:14 -070011108 .usage = track->attributes().usage,
11109 .content_type = track->attributes().content_type,
11110 .gain = mHalVolFloat, // TODO: propagate from aaudio pre-mix volume
Eric Laurent94579172020-11-20 18:41:04 +010011111 };
11112 trackMetadata.channel_mask = track->channelMask(),
11113 strncpy(trackMetadata.tags, track->attributes().tags, AUDIO_ATTRIBUTES_TAGS_MAX_SIZE);
11114 metadata.tracks.push_back(trackMetadata);
Kevin Rocard069c2712018-03-29 19:09:14 -070011115 }
11116 mOutput->stream->updateSourceMetadata(metadata);
Vlad Popa7e81cea2023-01-19 16:34:16 +010011117
11118 MetadataUpdate change;
11119 change.playbackMetadataUpdate = metadata.tracks;
11120 return change;
11121};
Kevin Rocard069c2712018-03-29 19:09:14 -070011122
Andy Hungee58e4a2023-07-07 13:47:37 -070011123void MmapPlaybackThread::checkSilentMode_l()
Eric Laurent6acd1d42017-01-04 14:23:29 -080011124{
11125 if (!mMasterMute) {
11126 char value[PROPERTY_VALUE_MAX];
11127 if (property_get("ro.audio.silent", value, "0") > 0) {
11128 char *endptr;
11129 unsigned long ul = strtoul(value, &endptr, 0);
11130 if (*endptr == '\0' && ul != 0) {
Andy Hung0e26ec62024-02-20 16:32:57 -080011131 ALOGW("%s: mute from ro.audio.silent. Silence is golden", __func__);
Eric Laurent6acd1d42017-01-04 14:23:29 -080011132 // The setprop command will not allow a property to be changed after
11133 // the first time it is set, so we don't have to worry about un-muting.
11134 setMasterMute_l(true);
11135 }
11136 }
11137 }
11138}
11139
Andy Hungee58e4a2023-07-07 13:47:37 -070011140void MmapPlaybackThread::toAudioPortConfig(struct audio_port_config* config)
Mikhail Naganov32abc2b2018-05-24 12:57:11 -070011141{
11142 MmapThread::toAudioPortConfig(config);
11143 if (mOutput && mOutput->flags != AUDIO_OUTPUT_FLAG_NONE) {
11144 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
11145 config->flags.output = mOutput->flags;
11146 }
11147}
11148
Andy Hungee58e4a2023-07-07 13:47:37 -070011149status_t MmapPlaybackThread::getExternalPosition(uint64_t* position,
Andy Hung440901d2023-06-29 21:19:25 -070011150 int64_t* timeNanos) const
jiabinb7d8c5a2020-08-26 17:24:52 -070011151{
11152 if (mOutput == nullptr) {
11153 return NO_INIT;
11154 }
11155 struct timespec timestamp;
11156 status_t status = mOutput->getPresentationPosition(position, &timestamp);
11157 if (status == NO_ERROR) {
11158 *timeNanos = timestamp.tv_sec * NANOS_PER_SECOND + timestamp.tv_nsec;
11159 }
11160 return status;
11161}
11162
Andy Hungee58e4a2023-07-07 13:47:37 -070011163status_t MmapPlaybackThread::reportData(const void* buffer, size_t frameCount) {
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010011164 // Send to MelProcessor for sound dose measurement.
11165 auto processor = mMelProcessor.load();
11166 if (processor) {
11167 processor->process(buffer, frameCount * mFrameSize);
11168 }
11169
jiabinfc791ee2023-02-15 19:43:40 +000011170 return NO_ERROR;
11171}
11172
Andy Hungc5007f82023-08-29 14:26:09 -070011173// startMelComputation_l() must be called with AudioFlinger::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -070011174void MmapPlaybackThread::startMelComputation_l(
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010011175 const sp<audio_utils::MelProcessor>& processor)
11176{
11177 ALOGV("%s: starting mel processor for thread %d", __func__, id());
Vlad Popa1c2f7e12023-03-28 02:08:56 +020011178 mMelProcessor.store(processor);
11179 if (processor) {
11180 processor->resume();
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010011181 }
Vlad Popa1c2f7e12023-03-28 02:08:56 +020011182
11183 // no need to update output format for MMapPlaybackThread since it is
11184 // assigned constant for each thread
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010011185}
11186
Andy Hungc5007f82023-08-29 14:26:09 -070011187// stopMelComputation_l() must be called with AudioFlinger::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -070011188void MmapPlaybackThread::stopMelComputation_l()
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010011189{
Vlad Popa1c2f7e12023-03-28 02:08:56 +020011190 ALOGV("%s: pausing mel processor for thread %d", __func__, id());
11191 auto melProcessor = mMelProcessor.load();
11192 if (melProcessor != nullptr) {
11193 melProcessor->pause();
11194 }
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010011195}
11196
Andy Hungee58e4a2023-07-07 13:47:37 -070011197void MmapPlaybackThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent6acd1d42017-01-04 14:23:29 -080011198{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -070011199 MmapThread::dumpInternals_l(fd, args);
Eric Laurent6acd1d42017-01-04 14:23:29 -080011200
Glenn Kastend3bb6452016-12-05 18:14:37 -080011201 dprintf(fd, " Stream type: %d Stream volume: %f HAL volume: %f Stream mute %d\n",
Eric Laurent1f9b5e62023-07-03 18:14:07 +020011202 mStreamType, streamVolume_l(), mHalVolFloat, streamMuted_l());
Eric Laurent6acd1d42017-01-04 14:23:29 -080011203 dprintf(fd, " Master volume: %f Master mute %d\n", mMasterVolume, mMasterMute);
11204}
11205
Andy Hungee58e4a2023-07-07 13:47:37 -070011206/* static */
11207sp<IAfMmapCaptureThread> IAfMmapCaptureThread::create(
Andy Hung583043b2023-07-17 17:05:00 -070011208 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
Andy Hungee58e4a2023-07-07 13:47:37 -070011209 AudioHwDevice* hwDev, AudioStreamIn* input, bool systemReady) {
Andy Hung583043b2023-07-17 17:05:00 -070011210 return sp<MmapCaptureThread>::make(afThreadCallback, id, hwDev, input, systemReady);
Andy Hungee58e4a2023-07-07 13:47:37 -070011211}
11212
11213MmapCaptureThread::MmapCaptureThread(
Andy Hung583043b2023-07-17 17:05:00 -070011214 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
jiabinc52b1ff2019-10-31 17:20:42 -070011215 AudioHwDevice *hwDev, AudioStreamIn *input, bool systemReady)
Andy Hung583043b2023-07-17 17:05:00 -070011216 : MmapThread(afThreadCallback, id, hwDev, input->stream, systemReady, false /* isOut */),
Eric Laurent6acd1d42017-01-04 14:23:29 -080011217 mInput(input)
11218{
11219 snprintf(mThreadName, kThreadNameLength, "AudioMmapIn_%X", id);
11220 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
11221}
11222
Andy Hungee58e4a2023-07-07 13:47:37 -070011223status_t MmapCaptureThread::exitStandby_l()
Eric Laurent331679c2018-04-16 17:03:16 -070011224{
Phil Burkf054fc32018-12-06 09:45:59 -080011225 {
11226 // mInput might have been cleared by clearInput()
Phil Burkf054fc32018-12-06 09:45:59 -080011227 if (mInput != nullptr && mInput->stream != nullptr) {
11228 mInput->stream->setGain(1.0f);
11229 }
11230 }
Eric Laurentdda206a2022-07-08 17:28:35 +020011231 return MmapThread::exitStandby_l();
Eric Laurent331679c2018-04-16 17:03:16 -070011232}
11233
Andy Hungee58e4a2023-07-07 13:47:37 -070011234AudioStreamIn* MmapCaptureThread::clearInput()
Eric Laurent6acd1d42017-01-04 14:23:29 -080011235{
Andy Hung972bec12023-08-31 16:13:39 -070011236 audio_utils::lock_guard _l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080011237 AudioStreamIn *input = mInput;
11238 mInput = NULL;
11239 return input;
11240}
Kevin Rocard069c2712018-03-29 19:09:14 -070011241
Andy Hungee58e4a2023-07-07 13:47:37 -070011242void MmapCaptureThread::processVolume_l()
Eric Laurent331679c2018-04-16 17:03:16 -070011243{
11244 bool changed = false;
11245 bool silenced = false;
11246
11247 sp<MmapStreamCallback> callback = mCallback.promote();
11248 if (callback == 0) {
11249 if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
11250 ALOGW("Could not set MMAP stream silenced: no onStreamSilenced callback!");
11251 mNoCallbackWarningCount++;
11252 }
11253 }
11254
11255 // After a change occurred in track silenced state, mute capture in audio DSP if at least one
11256 // track is silenced and unmute otherwise
11257 for (size_t i = 0; i < mActiveTracks.size() && !silenced; i++) {
11258 if (!mActiveTracks[i]->getAndSetSilencedNotified_l()) {
11259 changed = true;
11260 silenced = mActiveTracks[i]->isSilenced_l();
11261 }
11262 }
11263
11264 if (changed) {
11265 mInput->stream->setGain(silenced ? 0.0f: 1.0f);
11266 }
11267}
11268
Andy Hungee58e4a2023-07-07 13:47:37 -070011269ThreadBase::MetadataUpdate MmapCaptureThread::updateMetadata_l()
Kevin Rocard069c2712018-03-29 19:09:14 -070011270{
Jasmine Chaeaa10e42021-05-11 10:11:14 +080011271 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
Vlad Popa7e81cea2023-01-19 16:34:16 +010011272 return {}; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -070011273 }
11274 StreamInHalInterface::SinkMetadata metadata;
Andy Hung8d31fd22023-06-26 19:20:57 -070011275 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Kevin Rocard069c2712018-03-29 19:09:14 -070011276 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurent94579172020-11-20 18:41:04 +010011277 record_track_metadata_v7_t trackMetadata;
11278 trackMetadata.base = {
Kevin Rocard069c2712018-03-29 19:09:14 -070011279 .source = track->attributes().source,
11280 .gain = 1, // capture tracks do not have volumes
Eric Laurent94579172020-11-20 18:41:04 +010011281 };
11282 trackMetadata.channel_mask = track->channelMask(),
11283 strncpy(trackMetadata.tags, track->attributes().tags, AUDIO_ATTRIBUTES_TAGS_MAX_SIZE);
11284 metadata.tracks.push_back(trackMetadata);
Kevin Rocard069c2712018-03-29 19:09:14 -070011285 }
11286 mInput->stream->updateSinkMetadata(metadata);
Vlad Popa7e81cea2023-01-19 16:34:16 +010011287 MetadataUpdate change;
11288 change.recordMetadataUpdate = metadata.tracks;
11289 return change;
Kevin Rocard069c2712018-03-29 19:09:14 -070011290}
11291
Andy Hungee58e4a2023-07-07 13:47:37 -070011292void MmapCaptureThread::setRecordSilenced(audio_port_handle_t portId, bool silenced)
Eric Laurent331679c2018-04-16 17:03:16 -070011293{
Andy Hung972bec12023-08-31 16:13:39 -070011294 audio_utils::lock_guard _l(mutex());
Eric Laurent331679c2018-04-16 17:03:16 -070011295 for (size_t i = 0; i < mActiveTracks.size() ; i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -070011296 if (mActiveTracks[i]->portId() == portId) {
Eric Laurent331679c2018-04-16 17:03:16 -070011297 mActiveTracks[i]->setSilenced_l(silenced);
11298 broadcast_l();
11299 }
11300 }
jiabin09609032022-06-15 19:26:01 +000011301 setClientSilencedIfExists_l(portId, silenced);
Eric Laurent331679c2018-04-16 17:03:16 -070011302}
11303
Andy Hungee58e4a2023-07-07 13:47:37 -070011304void MmapCaptureThread::toAudioPortConfig(struct audio_port_config* config)
Mikhail Naganov32abc2b2018-05-24 12:57:11 -070011305{
11306 MmapThread::toAudioPortConfig(config);
11307 if (mInput && mInput->flags != AUDIO_INPUT_FLAG_NONE) {
11308 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
11309 config->flags.input = mInput->flags;
11310 }
11311}
11312
Andy Hungee58e4a2023-07-07 13:47:37 -070011313status_t MmapCaptureThread::getExternalPosition(
Andy Hung440901d2023-06-29 21:19:25 -070011314 uint64_t* position, int64_t* timeNanos) const
jiabinb7d8c5a2020-08-26 17:24:52 -070011315{
11316 if (mInput == nullptr) {
11317 return NO_INIT;
11318 }
11319 return mInput->getCapturePosition((int64_t*)position, timeNanos);
11320}
11321
jiabinc658e452022-10-21 20:52:21 +000011322// ----------------------------------------------------------------------------
11323
Andy Hungee58e4a2023-07-07 13:47:37 -070011324/* static */
11325sp<IAfPlaybackThread> IAfPlaybackThread::createBitPerfectThread(
Andy Hung583043b2023-07-17 17:05:00 -070011326 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hungee58e4a2023-07-07 13:47:37 -070011327 AudioStreamOut* output, audio_io_handle_t id, bool systemReady) {
Andy Hung583043b2023-07-17 17:05:00 -070011328 return sp<BitPerfectThread>::make(afThreadCallback, output, id, systemReady);
Andy Hungee58e4a2023-07-07 13:47:37 -070011329}
11330
Andy Hung583043b2023-07-17 17:05:00 -070011331BitPerfectThread::BitPerfectThread(const sp<IAfThreadCallback> &afThreadCallback,
jiabinc658e452022-10-21 20:52:21 +000011332 AudioStreamOut *output, audio_io_handle_t id, bool systemReady)
Andy Hung583043b2023-07-17 17:05:00 -070011333 : MixerThread(afThreadCallback, output, id, systemReady, BIT_PERFECT) {}
jiabinc658e452022-10-21 20:52:21 +000011334
Andy Hungee58e4a2023-07-07 13:47:37 -070011335PlaybackThread::mixer_state BitPerfectThread::prepareTracks_l(
Andy Hung8d31fd22023-06-26 19:20:57 -070011336 Vector<sp<IAfTrack>>* tracksToRemove) {
jiabinc658e452022-10-21 20:52:21 +000011337 mixer_state result = MixerThread::prepareTracks_l(tracksToRemove);
11338 // If there is only one active track and it is bit-perfect, enable tee buffer.
jiabin76d94692022-12-15 21:51:21 +000011339 float volumeLeft = 1.0f;
11340 float volumeRight = 1.0f;
jiabinc658e452022-10-21 20:52:21 +000011341 if (mActiveTracks.size() == 1 && mActiveTracks[0]->isBitPerfect()) {
11342 const int trackId = mActiveTracks[0]->id();
11343 mAudioMixer->setParameter(
11344 trackId, AudioMixer::TRACK, AudioMixer::TEE_BUFFER, (void *)mSinkBuffer);
11345 mAudioMixer->setParameter(
11346 trackId, AudioMixer::TRACK, AudioMixer::TEE_BUFFER_FRAME_COUNT,
11347 (void *)(uintptr_t)mNormalFrameCount);
jiabin76d94692022-12-15 21:51:21 +000011348 mActiveTracks[0]->getFinalVolume(&volumeLeft, &volumeRight);
jiabinc658e452022-10-21 20:52:21 +000011349 mIsBitPerfect = true;
11350 } else {
11351 mIsBitPerfect = false;
11352 // No need to copy bit-perfect data directly to sink buffer given there are multiple tracks
11353 // active.
11354 for (const auto& track : mActiveTracks) {
11355 const int trackId = track->id();
11356 mAudioMixer->setParameter(
11357 trackId, AudioMixer::TRACK, AudioMixer::TEE_BUFFER, nullptr);
11358 }
11359 }
jiabin76d94692022-12-15 21:51:21 +000011360 if (mVolumeLeft != volumeLeft || mVolumeRight != volumeRight) {
11361 mVolumeLeft = volumeLeft;
11362 mVolumeRight = volumeRight;
11363 setVolumeForOutput_l(volumeLeft, volumeRight);
11364 }
jiabinc658e452022-10-21 20:52:21 +000011365 return result;
11366}
11367
Andy Hungee58e4a2023-07-07 13:47:37 -070011368void BitPerfectThread::threadLoop_mix() {
jiabinc658e452022-10-21 20:52:21 +000011369 MixerThread::threadLoop_mix();
11370 mHasDataCopiedToSinkBuffer = mIsBitPerfect;
11371}
11372
Glenn Kasten63238ef2015-03-02 15:50:29 -080011373} // namespace android