blob: 860a4e464ecd638640c51fcb6e550df2de713092 [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>
Glenn Kastenc9a23672020-06-30 12:12:42 -070050#include <cutils/bitops.h>
Eric Laurent81784c32012-11-19 14:55:58 -080051#include <cutils/properties.h>
Andy Hung25a80ac2023-07-19 12:47:35 -070052#include <fastpath/AutoPark.h>
jiabinc52b1ff2019-10-31 17:20:42 -070053#include <media/AudioContainers.h>
54#include <media/AudioDeviceTypeAddr.h>
Glenn Kasten1ab85ec2013-05-31 09:18:43 -070055#include <media/AudioParameter.h>
Andy Hungcd044842014-08-07 11:04:34 -070056#include <media/AudioResamplerPublic.h>
Andy Hung25a80ac2023-07-19 12:47:35 -070057#ifdef ADD_BATTERY_DATA
58#include <media/IMediaPlayerService.h>
59#include <media/IMediaDeathNotifier.h>
60#endif
61#include <media/MmapStreamCallback.h>
Andy Hung89816052017-01-11 17:08:23 -080062#include <media/RecordBufferConverter.h>
Mikhail Naganov913d06c2016-11-01 12:49:22 -070063#include <media/TypeConverter.h>
Andy Hung25a80ac2023-07-19 12:47:35 -070064#include <media/audiohal/EffectsFactoryHalInterface.h>
65#include <media/audiohal/StreamHalInterface.h>
Glenn Kasten6dbb5e32014-05-13 10:38:42 -070066#include <media/nbaio/AudioStreamInSource.h>
Eric Laurent81784c32012-11-19 14:55:58 -080067#include <media/nbaio/AudioStreamOutSink.h>
68#include <media/nbaio/MonoPipe.h>
69#include <media/nbaio/MonoPipeReader.h>
70#include <media/nbaio/Pipe.h>
71#include <media/nbaio/PipeReader.h>
72#include <media/nbaio/SourceAudioBufferProvider.h>
Wei Jia3f273d12015-11-24 09:06:49 -080073#include <mediautils/BatteryNotifier.h>
Andy Hungafc51db2022-04-08 17:33:40 -070074#include <mediautils/Process.h>
Andy Hungab7ef302018-05-15 19:35:29 -070075#include <mediautils/SchedulingPolicyService.h>
76#include <mediautils/ServiceUtilities.h>
Andy Hung25a80ac2023-07-19 12:47:35 -070077#include <powermanager/PowerManager.h>
78#include <private/android_filesystem_config.h>
79#include <private/media/AudioTrackShared.h>
80#include <system/audio_effects/effect_aec.h>
81#include <system/audio_effects/effect_downmix.h>
82#include <system/audio_effects/effect_ns.h>
83#include <system/audio_effects/effect_spatializer.h>
84#include <utils/Log.h>
85#include <utils/Trace.h>
Eric Laurent81784c32012-11-19 14:55:58 -080086
Andy Hung25a80ac2023-07-19 12:47:35 -070087#include <fcntl.h>
Andy Hungc00c06b2023-11-07 19:51:12 -080088#include <future>
Andy Hung25a80ac2023-07-19 12:47:35 -070089#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.
189static const nsecs_t kMinimumTimeBetweenTimestampChecksNs = 150 /* ms */ * 1000;
190
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;
Eric Laurent81784c32012-11-19 14:55:58 -0800226
Glenn Kastenea38ee72016-04-18 11:08:01 -0700227// IAudioFlinger::createTrack() has an in/out parameter 'pFrameCount' for the total size of the
228// track buffer in shared memory. Zero on input means to use a default value. For fast tracks,
229// AudioFlinger derives the default from HAL buffer size and 'fast track multiplier'.
Glenn Kasten03490092014-05-27 12:30:54 -0700230
231// This is the default value, if not specified by property.
Glenn Kastenb5fed682013-12-03 09:06:43 -0800232static const int kFastTrackMultiplier = 2;
Eric Laurent81784c32012-11-19 14:55:58 -0800233
Glenn Kasten03490092014-05-27 12:30:54 -0700234// The minimum and maximum allowed values
235static const int kFastTrackMultiplierMin = 1;
236static const int kFastTrackMultiplierMax = 2;
237
238// The actual value to use, which can be specified per-device via property af.fast_track_multiplier.
239static int sFastTrackMultiplier = kFastTrackMultiplier;
240
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700241// See Thread::readOnlyHeap().
242// Initially this heap is used to allocate client buffers for "fast" AudioRecord.
243// Eventually it will be the single buffer that FastCapture writes into via HAL read(),
244// and that all "fast" AudioRecord clients read from. In either case, the size can be small.
Mikhail Naganov79a77822018-05-10 15:57:25 -0700245static const size_t kRecordThreadReadOnlyHeapSize = 0xD000;
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700246
Andy Hung25a80ac2023-07-19 12:47:35 -0700247static const nsecs_t kDefaultStandbyTimeInNsecs = seconds(3);
Andy Hung8fe87eb2023-07-20 21:31:38 -0700248
249static nsecs_t getStandbyTimeInNanos() {
250 static nsecs_t standbyTimeInNanos = []() {
251 const int ms = property_get_int32("ro.audio.flinger_standbytime_ms",
252 kDefaultStandbyTimeInNsecs / NANOS_PER_MILLISECOND);
253 ALOGI("%s: Using %d ms as standby time", __func__, ms);
254 return milliseconds(ms);
255 }();
256 return standbyTimeInNanos;
257}
258
Andy Hung81994d62023-07-20 21:44:14 -0700259// Set kEnableExtendedChannels to true to enable greater than stereo output
260// for the MixerThread and device sink. Number of channels allowed is
261// FCC_2 <= channels <= FCC_LIMIT.
262constexpr bool kEnableExtendedChannels = true;
263
264// Returns true if channel mask is permitted for the PCM sink in the MixerThread
265/* static */
266bool IAfThreadBase::isValidPcmSinkChannelMask(audio_channel_mask_t channelMask) {
267 switch (audio_channel_mask_get_representation(channelMask)) {
268 case AUDIO_CHANNEL_REPRESENTATION_POSITION: {
269 // Haptic channel mask is only applicable for channel position mask.
270 const uint32_t channelCount = audio_channel_count_from_out_mask(
271 static_cast<audio_channel_mask_t>(channelMask & ~AUDIO_CHANNEL_HAPTIC_ALL));
272 const uint32_t maxChannelCount = kEnableExtendedChannels
273 ? FCC_LIMIT : FCC_2;
274 if (channelCount < FCC_2 // mono is not supported at this time
275 || channelCount > maxChannelCount) {
276 return false;
277 }
278 // check that channelMask is the "canonical" one we expect for the channelCount.
279 return audio_channel_position_mask_is_out_canonical(channelMask);
280 }
281 case AUDIO_CHANNEL_REPRESENTATION_INDEX:
282 if (kEnableExtendedChannels) {
283 const uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
284 if (channelCount >= FCC_2 // mono is not supported at this time
285 && channelCount <= FCC_LIMIT) {
286 return true;
287 }
288 }
289 return false;
290 default:
291 return false;
292 }
293}
294
295// Set kEnableExtendedPrecision to true to use extended precision in MixerThread
296constexpr bool kEnableExtendedPrecision = true;
297
298// Returns true if format is permitted for the PCM sink in the MixerThread
299/* static */
300bool IAfThreadBase::isValidPcmSinkFormat(audio_format_t format) {
301 switch (format) {
302 case AUDIO_FORMAT_PCM_16_BIT:
303 return true;
304 case AUDIO_FORMAT_PCM_FLOAT:
305 case AUDIO_FORMAT_PCM_24_BIT_PACKED:
306 case AUDIO_FORMAT_PCM_32_BIT:
307 case AUDIO_FORMAT_PCM_8_24_BIT:
308 return kEnableExtendedPrecision;
309 default:
310 return false;
311 }
312}
313
Eric Laurent81784c32012-11-19 14:55:58 -0800314// ----------------------------------------------------------------------------
315
Andy Hung25a80ac2023-07-19 12:47:35 -0700316// formatToString() needs to be exact for MediaMetrics purposes.
317// Do not use media/TypeConverter.h toString().
318/* static */
319std::string IAfThreadBase::formatToString(audio_format_t format) {
320 std::string result;
321 FormatConverter::toString(format, result);
322 return result;
323}
324
Andy Hungb68f5eb2019-12-03 16:49:17 -0800325// TODO: move all toString helpers to audio.h
326// under #ifdef __cplusplus #endif
327static std::string patchSinksToString(const struct audio_patch *patch)
328{
329 std::stringstream ss;
330 for (size_t i = 0; i < patch->num_sinks; ++i) {
Andy Hungc2b11cb2020-04-22 09:04:01 -0700331 if (i > 0) {
332 ss << "|";
333 }
Andy Hungb68f5eb2019-12-03 16:49:17 -0800334 ss << "(" << toString(patch->sinks[i].ext.device.type)
335 << ", " << patch->sinks[i].ext.device.address << ")";
336 }
337 return ss.str();
338}
339
340static std::string patchSourcesToString(const struct audio_patch *patch)
341{
342 std::stringstream ss;
343 for (size_t i = 0; i < patch->num_sources; ++i) {
Andy Hungc2b11cb2020-04-22 09:04:01 -0700344 if (i > 0) {
345 ss << "|";
346 }
Andy Hungb68f5eb2019-12-03 16:49:17 -0800347 ss << "(" << toString(patch->sources[i].ext.device.type)
348 << ", " << patch->sources[i].ext.device.address << ")";
349 }
350 return ss.str();
351}
352
Andy Hung4bd53e72022-11-17 17:21:45 -0800353static std::string toString(audio_latency_mode_t mode) {
354 // We convert to the AIDL type to print (eventually the legacy type will be removed).
Mikhail Naganovf53e1822022-12-18 02:48:14 +0000355 const auto result = legacy2aidl_audio_latency_mode_t_AudioLatencyMode(mode);
356 return result.has_value() ? media::audio::common::toString(*result) : "UNKNOWN";
Andy Hung4bd53e72022-11-17 17:21:45 -0800357}
358
359// Could be made a template, but other toString overloads for std::vector are confused.
360static std::string toString(const std::vector<audio_latency_mode_t>& elements) {
361 std::string s("{ ");
362 for (const auto& e : elements) {
363 s.append(toString(e));
364 s.append(" ");
365 }
366 s.append("}");
367 return s;
368}
369
Glenn Kasten03490092014-05-27 12:30:54 -0700370static pthread_once_t sFastTrackMultiplierOnce = PTHREAD_ONCE_INIT;
371
372static void sFastTrackMultiplierInit()
373{
374 char value[PROPERTY_VALUE_MAX];
375 if (property_get("af.fast_track_multiplier", value, NULL) > 0) {
376 char *endptr;
377 unsigned long ul = strtoul(value, &endptr, 0);
378 if (*endptr == '\0' && kFastTrackMultiplierMin <= ul && ul <= kFastTrackMultiplierMax) {
379 sFastTrackMultiplier = (int) ul;
380 }
381 }
382}
383
384// ----------------------------------------------------------------------------
385
Eric Laurent81784c32012-11-19 14:55:58 -0800386#ifdef ADD_BATTERY_DATA
387// To collect the amplifier usage
388static void addBatteryData(uint32_t params) {
389 sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService();
390 if (service == NULL) {
391 // it already logged
392 return;
393 }
394
395 service->addBatteryData(params);
396}
397#endif
398
Andy Hung3f0c9022016-01-15 17:49:46 -0800399// Track the CLOCK_BOOTTIME versus CLOCK_MONOTONIC timebase offset
400struct {
401 // call when you acquire a partial wakelock
402 void acquire(const sp<IBinder> &wakeLockToken) {
403 pthread_mutex_lock(&mLock);
404 if (wakeLockToken.get() == nullptr) {
405 adjustTimebaseOffset(&mBoottimeOffset, ExtendedTimestamp::TIMEBASE_BOOTTIME);
406 } else {
407 if (mCount == 0) {
408 adjustTimebaseOffset(&mBoottimeOffset, ExtendedTimestamp::TIMEBASE_BOOTTIME);
409 }
410 ++mCount;
411 }
412 pthread_mutex_unlock(&mLock);
413 }
414
415 // call when you release a partial wakelock.
416 void release(const sp<IBinder> &wakeLockToken) {
417 if (wakeLockToken.get() == nullptr) {
418 return;
419 }
420 pthread_mutex_lock(&mLock);
421 if (--mCount < 0) {
422 ALOGE("negative wakelock count");
423 mCount = 0;
424 }
425 pthread_mutex_unlock(&mLock);
426 }
427
428 // retrieves the boottime timebase offset from monotonic.
429 int64_t getBoottimeOffset() {
430 pthread_mutex_lock(&mLock);
431 int64_t boottimeOffset = mBoottimeOffset;
432 pthread_mutex_unlock(&mLock);
433 return boottimeOffset;
434 }
435
436 // Adjusts the timebase offset between TIMEBASE_MONOTONIC
437 // and the selected timebase.
438 // Currently only TIMEBASE_BOOTTIME is allowed.
439 //
440 // This only needs to be called upon acquiring the first partial wakelock
441 // after all other partial wakelocks are released.
442 //
443 // We do an empirical measurement of the offset rather than parsing
444 // /proc/timer_list since the latter is not a formal kernel ABI.
445 static void adjustTimebaseOffset(int64_t *offset, ExtendedTimestamp::Timebase timebase) {
446 int clockbase;
447 switch (timebase) {
448 case ExtendedTimestamp::TIMEBASE_BOOTTIME:
449 clockbase = SYSTEM_TIME_BOOTTIME;
450 break;
451 default:
452 LOG_ALWAYS_FATAL("invalid timebase %d", timebase);
453 break;
454 }
455 // try three times to get the clock offset, choose the one
456 // with the minimum gap in measurements.
457 const int tries = 3;
Andy Hung920f6572022-10-06 12:09:49 -0700458 nsecs_t bestGap = 0, measured = 0; // not required, initialized for clang-tidy
Andy Hung3f0c9022016-01-15 17:49:46 -0800459 for (int i = 0; i < tries; ++i) {
460 const nsecs_t tmono = systemTime(SYSTEM_TIME_MONOTONIC);
461 const nsecs_t tbase = systemTime(clockbase);
462 const nsecs_t tmono2 = systemTime(SYSTEM_TIME_MONOTONIC);
463 const nsecs_t gap = tmono2 - tmono;
464 if (i == 0 || gap < bestGap) {
465 bestGap = gap;
466 measured = tbase - ((tmono + tmono2) >> 1);
467 }
468 }
469
470 // to avoid micro-adjusting, we don't change the timebase
471 // unless it is significantly different.
472 //
473 // Assumption: It probably takes more than toleranceNs to
474 // suspend and resume the device.
475 static int64_t toleranceNs = 10000; // 10 us
476 if (llabs(*offset - measured) > toleranceNs) {
477 ALOGV("Adjusting timebase offset old: %lld new: %lld",
478 (long long)*offset, (long long)measured);
479 *offset = measured;
480 }
481 }
482
483 pthread_mutex_t mLock;
484 int32_t mCount;
485 int64_t mBoottimeOffset;
486} gBoottime = { PTHREAD_MUTEX_INITIALIZER, 0, 0 }; // static, so use POD initialization
Eric Laurent81784c32012-11-19 14:55:58 -0800487
488// ----------------------------------------------------------------------------
489// CPU Stats
490// ----------------------------------------------------------------------------
491
492class CpuStats {
493public:
494 CpuStats();
495 void sample(const String8 &title);
496#ifdef DEBUG_CPU_USAGE
497private:
498 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns
Andy Hung16698b82018-08-01 10:48:38 -0700499 audio_utils::Statistics<double> mWcStats; // statistics on thread CPU usage in wall clock ns
Eric Laurent81784c32012-11-19 14:55:58 -0800500
Andy Hung16698b82018-08-01 10:48:38 -0700501 audio_utils::Statistics<double> mHzStats; // statistics on thread CPU usage in cycles
Eric Laurent81784c32012-11-19 14:55:58 -0800502
503 int mCpuNum; // thread's current CPU number
504 int mCpukHz; // frequency of thread's current CPU in kHz
505#endif
506};
507
508CpuStats::CpuStats()
509#ifdef DEBUG_CPU_USAGE
510 : mCpuNum(-1), mCpukHz(-1)
511#endif
512{
513}
514
Glenn Kasten0f11b512014-01-31 16:18:54 -0800515void CpuStats::sample(const String8 &title
516#ifndef DEBUG_CPU_USAGE
517 __unused
518#endif
519 ) {
Eric Laurent81784c32012-11-19 14:55:58 -0800520#ifdef DEBUG_CPU_USAGE
521 // get current thread's delta CPU time in wall clock ns
522 double wcNs;
523 bool valid = mCpuUsage.sampleAndEnable(wcNs);
524
525 // record sample for wall clock statistics
526 if (valid) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700527 mWcStats.add(wcNs);
Eric Laurent81784c32012-11-19 14:55:58 -0800528 }
529
530 // get the current CPU number
531 int cpuNum = sched_getcpu();
532
533 // get the current CPU frequency in kHz
534 int cpukHz = mCpuUsage.getCpukHz(cpuNum);
535
536 // check if either CPU number or frequency changed
537 if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
538 mCpuNum = cpuNum;
539 mCpukHz = cpukHz;
540 // ignore sample for purposes of cycles
541 valid = false;
542 }
543
544 // if no change in CPU number or frequency, then record sample for cycle statistics
545 if (valid && mCpukHz > 0) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700546 const double cycles = wcNs * cpukHz * 0.000001;
547 mHzStats.add(cycles);
Eric Laurent81784c32012-11-19 14:55:58 -0800548 }
549
Eric Tan5b13ff82018-07-27 11:20:17 -0700550 const unsigned n = mWcStats.getN();
Eric Laurent81784c32012-11-19 14:55:58 -0800551 // mCpuUsage.elapsed() is expensive, so don't call it every loop
552 if ((n & 127) == 1) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700553 const long long elapsed = mCpuUsage.elapsed();
Eric Laurent81784c32012-11-19 14:55:58 -0800554 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700555 const double perLoop = elapsed / (double) n;
556 const double perLoop100 = perLoop * 0.01;
557 const double perLoop1k = perLoop * 0.001;
558 const double mean = mWcStats.getMean();
559 const double stddev = mWcStats.getStdDev();
560 const double minimum = mWcStats.getMin();
561 const double maximum = mWcStats.getMax();
562 const double meanCycles = mHzStats.getMean();
563 const double stddevCycles = mHzStats.getStdDev();
564 const double minCycles = mHzStats.getMin();
565 const double maxCycles = mHzStats.getMax();
Eric Laurent81784c32012-11-19 14:55:58 -0800566 mCpuUsage.resetElapsed();
567 mWcStats.reset();
568 mHzStats.reset();
569 ALOGD("CPU usage for %s over past %.1f secs\n"
570 " (%u mixer loops at %.1f mean ms per loop):\n"
571 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
572 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
573 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +0000574 title.c_str(),
Eric Laurent81784c32012-11-19 14:55:58 -0800575 elapsed * .000000001, n, perLoop * .000001,
576 mean * .001,
577 stddev * .001,
578 minimum * .001,
579 maximum * .001,
580 mean / perLoop100,
581 stddev / perLoop100,
582 minimum / perLoop100,
583 maximum / perLoop100,
584 meanCycles / perLoop1k,
585 stddevCycles / perLoop1k,
586 minCycles / perLoop1k,
587 maxCycles / perLoop1k);
588
589 }
590 }
591#endif
592};
593
594// ----------------------------------------------------------------------------
595// ThreadBase
596// ----------------------------------------------------------------------------
597
Glenn Kasten97b7b752014-09-28 13:04:24 -0700598// static
Andy Hungee58e4a2023-07-07 13:47:37 -0700599const char* ThreadBase::threadTypeToString(ThreadBase::type_t type)
Glenn Kasten97b7b752014-09-28 13:04:24 -0700600{
601 switch (type) {
602 case MIXER:
603 return "MIXER";
604 case DIRECT:
605 return "DIRECT";
606 case DUPLICATING:
607 return "DUPLICATING";
608 case RECORD:
609 return "RECORD";
610 case OFFLOAD:
611 return "OFFLOAD";
Andy Hungea840382020-05-05 21:50:17 -0700612 case MMAP_PLAYBACK:
613 return "MMAP_PLAYBACK";
614 case MMAP_CAPTURE:
615 return "MMAP_CAPTURE";
Eric Laurent1c5e2e32021-08-18 18:50:28 +0200616 case SPATIALIZER:
617 return "SPATIALIZER";
jiabinc658e452022-10-21 20:52:21 +0000618 case BIT_PERFECT:
619 return "BIT_PERFECT";
Glenn Kasten97b7b752014-09-28 13:04:24 -0700620 default:
621 return "unknown";
622 }
623}
624
Andy Hung583043b2023-07-17 17:05:00 -0700625ThreadBase::ThreadBase(const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
Andy Hungcf10d742020-04-28 15:38:24 -0700626 type_t type, bool systemReady, bool isOut)
Eric Laurent81784c32012-11-19 14:55:58 -0800627 : Thread(false /*canCallJava*/),
628 mType(type),
Andy Hung583043b2023-07-17 17:05:00 -0700629 mAfThreadCallback(afThreadCallback),
Andy Hungcf10d742020-04-28 15:38:24 -0700630 mThreadMetrics(std::string(AMEDIAMETRICS_KEY_PREFIX_AUDIO_THREAD) + std::to_string(id),
631 isOut),
632 mIsOut(isOut),
Glenn Kasten70949c42013-08-06 07:40:12 -0700633 // mSampleRate, mFrameCount, mChannelMask, mChannelCount, mFrameSize, mFormat, mBufferSize
Glenn Kastendeca2ae2014-02-07 10:25:56 -0800634 // are set by PlaybackThread::readOutputParameters_l() or
635 // RecordThread::readInputParameters_l()
Eric Laurentfd477972013-10-25 18:10:40 -0700636 //FIXME: mStandby should be true here. Is this some kind of hack?
jiabinc52b1ff2019-10-31 17:20:42 -0700637 mStandby(false),
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700638 mAudioSource(AUDIO_SOURCE_DEFAULT), mId(id),
Eric Laurent81784c32012-11-19 14:55:58 -0800639 // mName will be set by concrete (non-virtual) subclass
Eric Laurent72e3f392015-05-20 14:43:50 -0700640 mDeathRecipient(new PMDeathRecipient(this)),
Eric Laurent6acd1d42017-01-04 14:23:29 -0800641 mSystemReady(systemReady),
642 mSignalPending(false)
Eric Laurent81784c32012-11-19 14:55:58 -0800643{
Andy Hungcf10d742020-04-28 15:38:24 -0700644 mThreadMetrics.logConstructor(getpid(), threadTypeToString(type), id);
Eric Laurent296fb132015-05-01 11:38:42 -0700645 memset(&mPatch, 0, sizeof(struct audio_patch));
Eric Laurent81784c32012-11-19 14:55:58 -0800646}
647
Andy Hungee58e4a2023-07-07 13:47:37 -0700648ThreadBase::~ThreadBase()
Eric Laurent81784c32012-11-19 14:55:58 -0800649{
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700650 // mConfigEvents should be empty, but just in case it isn't, free the memory it owns
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700651 mConfigEvents.clear();
652
Eric Laurent81784c32012-11-19 14:55:58 -0800653 // do not lock the mutex in destructor
654 releaseWakeLock_l();
655 if (mPowerManager != 0) {
Marco Nelissen06b46062014-11-14 07:58:25 -0800656 sp<IBinder> binder = IInterface::asBinder(mPowerManager);
Eric Laurent81784c32012-11-19 14:55:58 -0800657 binder->unlinkToDeath(mDeathRecipient);
658 }
Andy Hungd0979812019-02-21 15:51:44 -0800659
660 sendStatistics(true /* force */);
Eric Laurent81784c32012-11-19 14:55:58 -0800661}
662
Andy Hungee58e4a2023-07-07 13:47:37 -0700663status_t ThreadBase::readyToRun()
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700664{
665 status_t status = initCheck();
666 if (status == NO_ERROR) {
Glenn Kasten1bfe09a2017-02-21 13:05:56 -0800667 ALOGI("AudioFlinger's thread %p tid=%d ready to run", this, getTid());
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700668 } else {
669 ALOGE("No working audio driver found.");
670 }
671 return status;
672}
673
Andy Hungee58e4a2023-07-07 13:47:37 -0700674void ThreadBase::exit()
Eric Laurent81784c32012-11-19 14:55:58 -0800675{
676 ALOGV("ThreadBase::exit");
677 // do any cleanup required for exit to succeed
678 preExit();
679 {
680 // This lock prevents the following race in thread (uniprocessor for illustration):
681 // if (!exitPending()) {
682 // // context switch from here to exit()
683 // // exit() calls requestExit(), what exitPending() observes
684 // // exit() calls signal(), which is dropped since no waiters
685 // // context switch back from exit() to here
686 // mWaitWorkCV.wait(...);
687 // // now thread is hung
688 // }
Andy Hungc5007f82023-08-29 14:26:09 -0700689 audio_utils::lock_guard lock(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -0800690 requestExit();
Andy Hungc5007f82023-08-29 14:26:09 -0700691 mWaitWorkCV.notify_all();
Eric Laurent81784c32012-11-19 14:55:58 -0800692 }
693 // When Thread::requestExitAndWait is made virtual and this method is renamed to
694 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
695 requestExitAndWait();
696}
697
Andy Hungee58e4a2023-07-07 13:47:37 -0700698status_t ThreadBase::setParameters(const String8& keyValuePairs)
Eric Laurent81784c32012-11-19 14:55:58 -0800699{
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +0000700 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.c_str());
Andy Hung972bec12023-08-31 16:13:39 -0700701 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -0800702
Eric Laurent10351942014-05-08 18:49:52 -0700703 return sendSetParameterConfigEvent_l(keyValuePairs);
704}
705
706// sendConfigEvent_l() must be called with ThreadBase::mLock held
707// Can temporarily release the lock if waiting for a reply from processConfigEvents_l().
Andy Hungee58e4a2023-07-07 13:47:37 -0700708status_t ThreadBase::sendConfigEvent_l(sp<ConfigEvent>& event)
Andy Hung920f6572022-10-06 12:09:49 -0700709NO_THREAD_SAFETY_ANALYSIS // condition variable
Eric Laurent10351942014-05-08 18:49:52 -0700710{
711 status_t status = NO_ERROR;
712
Eric Laurent72e3f392015-05-20 14:43:50 -0700713 if (event->mRequiresSystemReady && !mSystemReady) {
714 event->mWaitStatus = false;
715 mPendingConfigEvents.add(event);
716 return status;
717 }
Eric Laurent10351942014-05-08 18:49:52 -0700718 mConfigEvents.add(event);
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700719 ALOGV("sendConfigEvent_l() num events %zu event %d", mConfigEvents.size(), event->mType);
Andy Hungc5007f82023-08-29 14:26:09 -0700720 mWaitWorkCV.notify_one();
721 mutex().unlock();
Eric Laurent10351942014-05-08 18:49:52 -0700722 {
Andy Hungc5007f82023-08-29 14:26:09 -0700723 audio_utils::unique_lock _l(event->mutex());
Eric Laurent10351942014-05-08 18:49:52 -0700724 while (event->mWaitStatus) {
Andy Hungc5007f82023-08-29 14:26:09 -0700725 if (event->mCondition.wait_for(_l, std::chrono::nanoseconds(kConfigEventTimeoutNs))
726 == std::cv_status::timeout) {
Eric Laurent10351942014-05-08 18:49:52 -0700727 event->mStatus = TIMED_OUT;
728 event->mWaitStatus = false;
729 }
730 }
731 status = event->mStatus;
Eric Laurent81784c32012-11-19 14:55:58 -0800732 }
Andy Hungc5007f82023-08-29 14:26:09 -0700733 mutex().lock();
Eric Laurent81784c32012-11-19 14:55:58 -0800734 return status;
735}
736
Andy Hungee58e4a2023-07-07 13:47:37 -0700737void ThreadBase::sendIoConfigEvent(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -0700738 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -0800739{
Andy Hung972bec12023-08-31 16:13:39 -0700740 audio_utils::lock_guard _l(mutex());
Eric Laurent09f1ed22019-04-24 17:45:17 -0700741 sendIoConfigEvent_l(event, pid, portId);
Eric Laurent81784c32012-11-19 14:55:58 -0800742}
743
Andy Hungc5007f82023-08-29 14:26:09 -0700744// sendIoConfigEvent_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -0700745void ThreadBase::sendIoConfigEvent_l(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -0700746 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -0800747{
Andy Hungd0979812019-02-21 15:51:44 -0800748 // The audio statistics history is exponentially weighted to forget events
749 // about five or more seconds in the past. In order to have
750 // crisper statistics for mediametrics, we reset the statistics on
751 // an IoConfigEvent, to reflect different properties for a new device.
752 mIoJitterMs.reset();
753 mLatencyMs.reset();
754 mProcessTimeMs.reset();
Robert Wu06db0a32021-08-10 19:05:34 +0000755 mMonopipePipeDepthStats.reset();
Dean Wheatley12473e92021-03-18 23:00:55 +1100756 mTimestampVerifier.discontinuity(mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS);
Andy Hungd0979812019-02-21 15:51:44 -0800757
Eric Laurent09f1ed22019-04-24 17:45:17 -0700758 sp<ConfigEvent> configEvent = (ConfigEvent *)new IoConfigEvent(event, pid, portId);
Eric Laurent10351942014-05-08 18:49:52 -0700759 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800760}
761
Andy Hungee58e4a2023-07-07 13:47:37 -0700762void ThreadBase::sendPrioConfigEvent(pid_t pid, pid_t tid, int32_t prio, bool forApp)
Eric Laurent72e3f392015-05-20 14:43:50 -0700763{
Andy Hung972bec12023-08-31 16:13:39 -0700764 audio_utils::lock_guard _l(mutex());
Mikhail Naganov83f04272017-02-07 10:45:09 -0800765 sendPrioConfigEvent_l(pid, tid, prio, forApp);
Eric Laurent72e3f392015-05-20 14:43:50 -0700766}
767
Andy Hungc5007f82023-08-29 14:26:09 -0700768// sendPrioConfigEvent_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -0700769void ThreadBase::sendPrioConfigEvent_l(
Mikhail Naganov83f04272017-02-07 10:45:09 -0800770 pid_t pid, pid_t tid, int32_t prio, bool forApp)
Eric Laurent81784c32012-11-19 14:55:58 -0800771{
Mikhail Naganov83f04272017-02-07 10:45:09 -0800772 sp<ConfigEvent> configEvent = (ConfigEvent *)new PrioConfigEvent(pid, tid, prio, forApp);
Eric Laurent10351942014-05-08 18:49:52 -0700773 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800774}
775
Andy Hungc5007f82023-08-29 14:26:09 -0700776// sendSetParameterConfigEvent_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -0700777status_t ThreadBase::sendSetParameterConfigEvent_l(const String8& keyValuePair)
Eric Laurent81784c32012-11-19 14:55:58 -0800778{
Andy Hung2ddee192015-12-18 17:34:44 -0800779 sp<ConfigEvent> configEvent;
780 AudioParameter param(keyValuePair);
781 int value;
Mikhail Naganov00260b52016-10-13 12:54:24 -0700782 if (param.getInt(String8(AudioParameter::keyMonoOutput), value) == NO_ERROR) {
Andy Hung2ddee192015-12-18 17:34:44 -0800783 setMasterMono_l(value != 0);
784 if (param.size() == 1) {
785 return NO_ERROR; // should be a solo parameter - we don't pass down
786 }
Mikhail Naganov00260b52016-10-13 12:54:24 -0700787 param.remove(String8(AudioParameter::keyMonoOutput));
Andy Hung2ddee192015-12-18 17:34:44 -0800788 configEvent = new SetParameterConfigEvent(param.toString());
789 } else {
790 configEvent = new SetParameterConfigEvent(keyValuePair);
791 }
Eric Laurent10351942014-05-08 18:49:52 -0700792 return sendConfigEvent_l(configEvent);
Glenn Kastenf7773312013-08-13 16:00:42 -0700793}
794
Andy Hungee58e4a2023-07-07 13:47:37 -0700795status_t ThreadBase::sendCreateAudioPatchConfigEvent(
Eric Laurent1c333e22014-05-20 10:48:17 -0700796 const struct audio_patch *patch,
797 audio_patch_handle_t *handle)
798{
Andy Hung972bec12023-08-31 16:13:39 -0700799 audio_utils::lock_guard _l(mutex());
Eric Laurent1c333e22014-05-20 10:48:17 -0700800 sp<ConfigEvent> configEvent = (ConfigEvent *)new CreateAudioPatchConfigEvent(*patch, *handle);
801 status_t status = sendConfigEvent_l(configEvent);
802 if (status == NO_ERROR) {
803 CreateAudioPatchConfigEventData *data =
804 (CreateAudioPatchConfigEventData *)configEvent->mData.get();
805 *handle = data->mHandle;
806 }
807 return status;
808}
809
Andy Hungee58e4a2023-07-07 13:47:37 -0700810status_t ThreadBase::sendReleaseAudioPatchConfigEvent(
Eric Laurent1c333e22014-05-20 10:48:17 -0700811 const audio_patch_handle_t handle)
812{
Andy Hung972bec12023-08-31 16:13:39 -0700813 audio_utils::lock_guard _l(mutex());
Eric Laurent1c333e22014-05-20 10:48:17 -0700814 sp<ConfigEvent> configEvent = (ConfigEvent *)new ReleaseAudioPatchConfigEvent(handle);
815 return sendConfigEvent_l(configEvent);
816}
817
Andy Hungee58e4a2023-07-07 13:47:37 -0700818status_t ThreadBase::sendUpdateOutDeviceConfigEvent(
jiabinc52b1ff2019-10-31 17:20:42 -0700819 const DeviceDescriptorBaseVector& outDevices)
820{
821 if (type() != RECORD) {
822 // The update out device operation is only for record thread.
823 return INVALID_OPERATION;
824 }
Andy Hung972bec12023-08-31 16:13:39 -0700825 audio_utils::lock_guard _l(mutex());
jiabinc52b1ff2019-10-31 17:20:42 -0700826 sp<ConfigEvent> configEvent = (ConfigEvent *)new UpdateOutDevicesConfigEvent(outDevices);
827 return sendConfigEvent_l(configEvent);
828}
829
Andy Hungee58e4a2023-07-07 13:47:37 -0700830void ThreadBase::sendResizeBufferConfigEvent_l(int32_t maxSharedAudioHistoryMs)
Eric Laurentec376dc2021-04-08 20:41:22 +0200831{
832 ALOG_ASSERT(type() == RECORD, "sendResizeBufferConfigEvent_l() called on non record thread");
833 sp<ConfigEvent> configEvent =
834 (ConfigEvent *)new ResizeBufferConfigEvent(maxSharedAudioHistoryMs);
835 sendConfigEvent_l(configEvent);
836}
Eric Laurent1c333e22014-05-20 10:48:17 -0700837
Andy Hungee58e4a2023-07-07 13:47:37 -0700838void ThreadBase::sendCheckOutputStageEffectsEvent()
Eric Laurentb3f315a2021-07-13 15:09:05 +0200839{
Andy Hung972bec12023-08-31 16:13:39 -0700840 audio_utils::lock_guard _l(mutex());
Eric Laurentb3f315a2021-07-13 15:09:05 +0200841 sendCheckOutputStageEffectsEvent_l();
842}
843
Andy Hungee58e4a2023-07-07 13:47:37 -0700844void ThreadBase::sendCheckOutputStageEffectsEvent_l()
Eric Laurentb3f315a2021-07-13 15:09:05 +0200845{
846 sp<ConfigEvent> configEvent =
847 (ConfigEvent *)new CheckOutputStageEffectsEvent();
848 sendConfigEvent_l(configEvent);
849}
850
Andy Hungee58e4a2023-07-07 13:47:37 -0700851void ThreadBase::sendHalLatencyModesChangedEvent_l()
Eric Laurent68a40a82022-05-03 18:15:04 +0200852{
853 sp<ConfigEvent> configEvent = sp<HalLatencyModesChangedEvent>::make();
854 sendConfigEvent_l(configEvent);
855}
856
Glenn Kasten2cfbf882013-08-14 13:12:11 -0700857// post condition: mConfigEvents.isEmpty()
Andy Hungee58e4a2023-07-07 13:47:37 -0700858void ThreadBase::processConfigEvents_l()
Glenn Kastenf7773312013-08-13 16:00:42 -0700859{
Eric Laurent10351942014-05-08 18:49:52 -0700860 bool configChanged = false;
861
Eric Laurent81784c32012-11-19 14:55:58 -0800862 while (!mConfigEvents.isEmpty()) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700863 ALOGV("processConfigEvents_l() remaining events %zu", mConfigEvents.size());
Eric Laurent10351942014-05-08 18:49:52 -0700864 sp<ConfigEvent> event = mConfigEvents[0];
Eric Laurent81784c32012-11-19 14:55:58 -0800865 mConfigEvents.removeAt(0);
Eric Laurent10351942014-05-08 18:49:52 -0700866 switch (event->mType) {
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700867 case CFG_EVENT_PRIO: {
Eric Laurent10351942014-05-08 18:49:52 -0700868 PrioConfigEventData *data = (PrioConfigEventData *)event->mData.get();
869 // FIXME Need to understand why this has to be done asynchronously
Mikhail Naganov83f04272017-02-07 10:45:09 -0800870 int err = requestPriority(data->mPid, data->mTid, data->mPrio, data->mForApp,
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700871 true /*asynchronous*/);
872 if (err != 0) {
873 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Eric Laurent10351942014-05-08 18:49:52 -0700874 data->mPrio, data->mPid, data->mTid, err);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700875 }
876 } break;
877 case CFG_EVENT_IO: {
Eric Laurent10351942014-05-08 18:49:52 -0700878 IoConfigEventData *data = (IoConfigEventData *)event->mData.get();
Andy Hungab65b182023-09-06 19:41:47 -0700879 ioConfigChanged_l(data->mEvent, data->mPid, data->mPortId);
Eric Laurent10351942014-05-08 18:49:52 -0700880 } break;
881 case CFG_EVENT_SET_PARAMETER: {
882 SetParameterConfigEventData *data = (SetParameterConfigEventData *)event->mData.get();
883 if (checkForNewParameter_l(data->mKeyValuePairs, event->mStatus)) {
884 configChanged = true;
Andy Hung293558a2017-03-21 12:19:20 -0700885 mLocalLog.log("CFG_EVENT_SET_PARAMETER: (%s) configuration changed",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +0000886 data->mKeyValuePairs.c_str());
Glenn Kastend5418eb2013-08-14 13:11:06 -0700887 }
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700888 } break;
Eric Laurent1c333e22014-05-20 10:48:17 -0700889 case CFG_EVENT_CREATE_AUDIO_PATCH: {
Andy Hungab65b182023-09-06 19:41:47 -0700890 const DeviceTypeSet oldDevices = getDeviceTypes_l();
Eric Laurent1c333e22014-05-20 10:48:17 -0700891 CreateAudioPatchConfigEventData *data =
892 (CreateAudioPatchConfigEventData *)event->mData.get();
893 event->mStatus = createAudioPatch_l(&data->mPatch, &data->mHandle);
Andy Hungab65b182023-09-06 19:41:47 -0700894 const DeviceTypeSet newDevices = getDeviceTypes_l();
Eric Laurent52568142022-10-28 11:23:28 +0200895 configChanged = oldDevices != newDevices;
jiabinc52b1ff2019-10-31 17:20:42 -0700896 mLocalLog.log("CFG_EVENT_CREATE_AUDIO_PATCH: old device %s (%s) new device %s (%s)",
897 dumpDeviceTypes(oldDevices).c_str(), toString(oldDevices).c_str(),
898 dumpDeviceTypes(newDevices).c_str(), toString(newDevices).c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -0700899 } break;
900 case CFG_EVENT_RELEASE_AUDIO_PATCH: {
Andy Hungab65b182023-09-06 19:41:47 -0700901 const DeviceTypeSet oldDevices = getDeviceTypes_l();
Eric Laurent1c333e22014-05-20 10:48:17 -0700902 ReleaseAudioPatchConfigEventData *data =
903 (ReleaseAudioPatchConfigEventData *)event->mData.get();
904 event->mStatus = releaseAudioPatch_l(data->mHandle);
Andy Hungab65b182023-09-06 19:41:47 -0700905 const DeviceTypeSet newDevices = getDeviceTypes_l();
Eric Laurent52568142022-10-28 11:23:28 +0200906 configChanged = oldDevices != newDevices;
jiabinc52b1ff2019-10-31 17:20:42 -0700907 mLocalLog.log("CFG_EVENT_RELEASE_AUDIO_PATCH: old device %s (%s) new device %s (%s)",
908 dumpDeviceTypes(oldDevices).c_str(), toString(oldDevices).c_str(),
909 dumpDeviceTypes(newDevices).c_str(), toString(newDevices).c_str());
910 } break;
911 case CFG_EVENT_UPDATE_OUT_DEVICE: {
912 UpdateOutDevicesConfigEventData *data =
913 (UpdateOutDevicesConfigEventData *)event->mData.get();
914 updateOutDevices(data->mOutDevices);
Eric Laurent1c333e22014-05-20 10:48:17 -0700915 } break;
Eric Laurentec376dc2021-04-08 20:41:22 +0200916 case CFG_EVENT_RESIZE_BUFFER: {
917 ResizeBufferConfigEventData *data =
918 (ResizeBufferConfigEventData *)event->mData.get();
919 resizeInputBuffer_l(data->mMaxSharedAudioHistoryMs);
920 } break;
Eric Laurentb3f315a2021-07-13 15:09:05 +0200921
922 case CFG_EVENT_CHECK_OUTPUT_STAGE_EFFECTS: {
923 setCheckOutputStageEffects();
924 } break;
925
Eric Laurent68a40a82022-05-03 18:15:04 +0200926 case CFG_EVENT_HAL_LATENCY_MODES_CHANGED: {
927 onHalLatencyModesChanged_l();
928 } break;
929
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700930 default:
Eric Laurent10351942014-05-08 18:49:52 -0700931 ALOG_ASSERT(false, "processConfigEvents_l() unknown event type %d", event->mType);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700932 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800933 }
Eric Laurent10351942014-05-08 18:49:52 -0700934 {
Andy Hung972bec12023-08-31 16:13:39 -0700935 audio_utils::lock_guard _l(event->mutex());
Eric Laurent10351942014-05-08 18:49:52 -0700936 if (event->mWaitStatus) {
937 event->mWaitStatus = false;
Andy Hungc5007f82023-08-29 14:26:09 -0700938 event->mCondition.notify_one();
Eric Laurent10351942014-05-08 18:49:52 -0700939 }
940 }
941 ALOGV_IF(mConfigEvents.isEmpty(), "processConfigEvents_l() DONE thread %p", this);
942 }
943
944 if (configChanged) {
945 cacheParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800946 }
Eric Laurent81784c32012-11-19 14:55:58 -0800947}
948
Marco Nelissenb2208842014-02-07 14:00:50 -0800949String8 channelMaskToString(audio_channel_mask_t mask, bool output) {
950 String8 s;
Glenn Kastene1635ec2015-06-08 15:46:49 -0700951 const audio_channel_representation_t representation =
952 audio_channel_mask_get_representation(mask);
Andy Hungf98ec8d2015-05-19 12:53:24 -0700953
954 switch (representation) {
jiabin245cdd92018-12-07 17:55:15 -0800955 // Travel all single bit channel mask to convert channel mask to string.
Andy Hungf98ec8d2015-05-19 12:53:24 -0700956 case AUDIO_CHANNEL_REPRESENTATION_POSITION: {
957 if (output) {
958 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT) s.append("front-left, ");
959 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT) s.append("front-right, ");
960 if (mask & AUDIO_CHANNEL_OUT_FRONT_CENTER) s.append("front-center, ");
Andy Hungfba71252021-05-07 11:58:32 -0700961 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY) s.append("low-frequency, ");
Andy Hungf98ec8d2015-05-19 12:53:24 -0700962 if (mask & AUDIO_CHANNEL_OUT_BACK_LEFT) s.append("back-left, ");
963 if (mask & AUDIO_CHANNEL_OUT_BACK_RIGHT) s.append("back-right, ");
964 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT_OF_CENTER) s.append("front-left-of-center, ");
965 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT_OF_CENTER) s.append("front-right-of-center, ");
966 if (mask & AUDIO_CHANNEL_OUT_BACK_CENTER) s.append("back-center, ");
967 if (mask & AUDIO_CHANNEL_OUT_SIDE_LEFT) s.append("side-left, ");
968 if (mask & AUDIO_CHANNEL_OUT_SIDE_RIGHT) s.append("side-right, ");
969 if (mask & AUDIO_CHANNEL_OUT_TOP_CENTER) s.append("top-center ,");
970 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_LEFT) s.append("top-front-left, ");
971 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_CENTER) s.append("top-front-center, ");
972 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_RIGHT) s.append("top-front-right, ");
973 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_LEFT) s.append("top-back-left, ");
Andy Hungae81b4c2021-05-07 08:54:28 -0700974 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_CENTER) s.append("top-back-center, ");
975 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_RIGHT) s.append("top-back-right, ");
976 if (mask & AUDIO_CHANNEL_OUT_TOP_SIDE_LEFT) s.append("top-side-left, ");
977 if (mask & AUDIO_CHANNEL_OUT_TOP_SIDE_RIGHT) s.append("top-side-right, ");
978 if (mask & AUDIO_CHANNEL_OUT_BOTTOM_FRONT_LEFT) s.append("bottom-front-left, ");
979 if (mask & AUDIO_CHANNEL_OUT_BOTTOM_FRONT_CENTER) s.append("bottom-front-center, ");
980 if (mask & AUDIO_CHANNEL_OUT_BOTTOM_FRONT_RIGHT) s.append("bottom-front-right, ");
Andy Hungfba71252021-05-07 11:58:32 -0700981 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY_2) s.append("low-frequency-2, ");
Andy Hungae81b4c2021-05-07 08:54:28 -0700982 if (mask & AUDIO_CHANNEL_OUT_HAPTIC_B) s.append("haptic-B, ");
983 if (mask & AUDIO_CHANNEL_OUT_HAPTIC_A) s.append("haptic-A, ");
Andy Hungf98ec8d2015-05-19 12:53:24 -0700984 if (mask & ~AUDIO_CHANNEL_OUT_ALL) s.append("unknown, ");
985 } else {
986 if (mask & AUDIO_CHANNEL_IN_LEFT) s.append("left, ");
987 if (mask & AUDIO_CHANNEL_IN_RIGHT) s.append("right, ");
988 if (mask & AUDIO_CHANNEL_IN_FRONT) s.append("front, ");
989 if (mask & AUDIO_CHANNEL_IN_BACK) s.append("back, ");
990 if (mask & AUDIO_CHANNEL_IN_LEFT_PROCESSED) s.append("left-processed, ");
991 if (mask & AUDIO_CHANNEL_IN_RIGHT_PROCESSED) s.append("right-processed, ");
992 if (mask & AUDIO_CHANNEL_IN_FRONT_PROCESSED) s.append("front-processed, ");
993 if (mask & AUDIO_CHANNEL_IN_BACK_PROCESSED) s.append("back-processed, ");
994 if (mask & AUDIO_CHANNEL_IN_PRESSURE) s.append("pressure, ");
995 if (mask & AUDIO_CHANNEL_IN_X_AXIS) s.append("X, ");
996 if (mask & AUDIO_CHANNEL_IN_Y_AXIS) s.append("Y, ");
997 if (mask & AUDIO_CHANNEL_IN_Z_AXIS) s.append("Z, ");
Mikhail Naganovc9948492018-05-10 17:25:28 -0700998 if (mask & AUDIO_CHANNEL_IN_BACK_LEFT) s.append("back-left, ");
999 if (mask & AUDIO_CHANNEL_IN_BACK_RIGHT) s.append("back-right, ");
1000 if (mask & AUDIO_CHANNEL_IN_CENTER) s.append("center, ");
Andy Hungfba71252021-05-07 11:58:32 -07001001 if (mask & AUDIO_CHANNEL_IN_LOW_FREQUENCY) s.append("low-frequency, ");
Andy Hungae81b4c2021-05-07 08:54:28 -07001002 if (mask & AUDIO_CHANNEL_IN_TOP_LEFT) s.append("top-left, ");
1003 if (mask & AUDIO_CHANNEL_IN_TOP_RIGHT) s.append("top-right, ");
Andy Hungf98ec8d2015-05-19 12:53:24 -07001004 if (mask & AUDIO_CHANNEL_IN_VOICE_UPLINK) s.append("voice-uplink, ");
1005 if (mask & AUDIO_CHANNEL_IN_VOICE_DNLINK) s.append("voice-dnlink, ");
1006 if (mask & ~AUDIO_CHANNEL_IN_ALL) s.append("unknown, ");
1007 }
1008 const int len = s.length();
1009 if (len > 2) {
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07001010 (void) s.lockBuffer(len); // needed?
Andy Hungf98ec8d2015-05-19 12:53:24 -07001011 s.unlockBuffer(len - 2); // remove trailing ", "
1012 }
1013 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -08001014 }
Andy Hungf98ec8d2015-05-19 12:53:24 -07001015 case AUDIO_CHANNEL_REPRESENTATION_INDEX:
1016 s.appendFormat("index mask, bits:%#x", audio_channel_mask_get_bits(mask));
1017 return s;
1018 default:
1019 s.appendFormat("unknown mask, representation:%d bits:%#x",
1020 representation, audio_channel_mask_get_bits(mask));
1021 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -08001022 }
Marco Nelissenb2208842014-02-07 14:00:50 -08001023}
1024
Andy Hungee58e4a2023-07-07 13:47:37 -07001025void ThreadBase::dump(int fd, const Vector<String16>& args)
Andy Hung920f6572022-10-06 12:09:49 -07001026NO_THREAD_SAFETY_ANALYSIS // conditional try lock
Eric Laurent81784c32012-11-19 14:55:58 -08001027{
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08001028 dprintf(fd, "\n%s thread %p, name %s, tid %d, type %d (%s):\n", isOutput() ? "Output" : "Input",
1029 this, mThreadName, getTid(), type(), threadTypeToString(type()));
1030
Andy Hungc5007f82023-08-29 14:26:09 -07001031 const bool locked = afutils::dumpTryLock(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001032 if (!locked) {
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08001033 dprintf(fd, " Thread may be deadlocked\n");
Eric Laurent81784c32012-11-19 14:55:58 -08001034 }
1035
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001036 dumpBase_l(fd, args);
1037 dumpInternals_l(fd, args);
1038 dumpTracks_l(fd, args);
1039 dumpEffectChains_l(fd, args);
1040
1041 if (locked) {
Andy Hungc5007f82023-08-29 14:26:09 -07001042 mutex().unlock();
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001043 }
1044
1045 dprintf(fd, " Local log:\n");
1046 mLocalLog.dump(fd, " " /* prefix */, 40 /* lines */);
Andy Hungafc51db2022-04-08 17:33:40 -07001047
1048 // --all does the statistics
1049 bool dumpAll = false;
1050 for (const auto &arg : args) {
1051 if (arg == String16("--all")) {
1052 dumpAll = true;
1053 }
1054 }
1055 if (dumpAll || type() == SPATIALIZER) {
Andy Hung44d648b2022-04-08 17:33:40 -07001056 const std::string sched = mThreadSnapshot.toString();
Andy Hungafc51db2022-04-08 17:33:40 -07001057 if (!sched.empty()) {
1058 (void)write(fd, sched.c_str(), sched.size());
1059 }
1060 }
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001061}
1062
Andy Hungee58e4a2023-07-07 13:47:37 -07001063void ThreadBase::dumpBase_l(int fd, const Vector<String16>& /* args */)
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001064{
Elliott Hughes87cebad2014-05-22 10:14:43 -07001065 dprintf(fd, " I/O handle: %d\n", mId);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001066 dprintf(fd, " Standby: %s\n", mStandby ? "yes" : "no");
Glenn Kasten97b7b752014-09-28 13:04:24 -07001067 dprintf(fd, " Sample rate: %u Hz\n", mSampleRate);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001068 dprintf(fd, " HAL frame count: %zu\n", mFrameCount);
Andy Hung25a80ac2023-07-19 12:47:35 -07001069 dprintf(fd, " HAL format: 0x%x (%s)\n", mHALFormat,
1070 IAfThreadBase::formatToString(mHALFormat).c_str());
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001071 dprintf(fd, " HAL buffer size: %zu bytes\n", mBufferSize);
Glenn Kasten97b7b752014-09-28 13:04:24 -07001072 dprintf(fd, " Channel count: %u\n", mChannelCount);
1073 dprintf(fd, " Channel mask: 0x%08x (%s)\n", mChannelMask,
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00001074 channelMaskToString(mChannelMask, mType != RECORD).c_str());
Andy Hung25a80ac2023-07-19 12:47:35 -07001075 dprintf(fd, " Processing format: 0x%x (%s)\n", mFormat,
1076 IAfThreadBase::formatToString(mFormat).c_str());
Glenn Kastenf87c2f52015-08-21 08:03:57 -07001077 dprintf(fd, " Processing frame size: %zu bytes\n", mFrameSize);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001078 dprintf(fd, " Pending config events:");
Marco Nelissenb2208842014-02-07 14:00:50 -08001079 size_t numConfig = mConfigEvents.size();
1080 if (numConfig) {
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001081 const size_t SIZE = 256;
1082 char buffer[SIZE];
Marco Nelissenb2208842014-02-07 14:00:50 -08001083 for (size_t i = 0; i < numConfig; i++) {
1084 mConfigEvents[i]->dump(buffer, SIZE);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001085 dprintf(fd, "\n %s", buffer);
Marco Nelissenb2208842014-02-07 14:00:50 -08001086 }
Elliott Hughes87cebad2014-05-22 10:14:43 -07001087 dprintf(fd, "\n");
Marco Nelissenb2208842014-02-07 14:00:50 -08001088 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07001089 dprintf(fd, " none\n");
Eric Laurent81784c32012-11-19 14:55:58 -08001090 }
Andy Hung293558a2017-03-21 12:19:20 -07001091 // Note: output device may be used by capture threads for effects such as AEC.
jiabinc52b1ff2019-10-31 17:20:42 -07001092 dprintf(fd, " Output devices: %s (%s)\n",
Andy Hungab65b182023-09-06 19:41:47 -07001093 dumpDeviceTypes(outDeviceTypes_l()).c_str(), toString(outDeviceTypes_l()).c_str());
jiabinc52b1ff2019-10-31 17:20:42 -07001094 dprintf(fd, " Input device: %#x (%s)\n",
Andy Hungab65b182023-09-06 19:41:47 -07001095 inDeviceType_l(), toString(inDeviceType_l()).c_str());
Andy Hung9b181952019-02-25 14:53:36 -08001096 dprintf(fd, " Audio source: %d (%s)\n", mAudioSource, toString(mAudioSource).c_str());
Eric Laurent81784c32012-11-19 14:55:58 -08001097
Andy Hung2e2c0bb2018-06-11 19:13:11 -07001098 // Dump timestamp statistics for the Thread types that support it.
1099 if (mType == RECORD
1100 || mType == MIXER
1101 || mType == DUPLICATING
Andy Hungf3234512018-07-03 14:51:47 -07001102 || mType == DIRECT
Andy Hung4b7f54f2022-04-28 17:45:28 -07001103 || mType == OFFLOAD
1104 || mType == SPATIALIZER) {
Andy Hung2e2c0bb2018-06-11 19:13:11 -07001105 dprintf(fd, " Timestamp stats: %s\n", mTimestampVerifier.toString().c_str());
Andy Hungab65b182023-09-06 19:41:47 -07001106 dprintf(fd, " Timestamp corrected: %s\n",
1107 isTimestampCorrectionEnabled_l() ? "yes" : "no");
Andy Hung2e2c0bb2018-06-11 19:13:11 -07001108 }
1109
Andy Hung446f4df2019-02-21 12:26:41 -08001110 if (mLastIoBeginNs > 0) { // MMAP may not set this
1111 dprintf(fd, " Last %s occurred (msecs): %lld\n",
1112 isOutput() ? "write" : "read",
1113 (long long) (systemTime() - mLastIoBeginNs) / NANOS_PER_MILLISECOND);
1114 }
1115
1116 if (mProcessTimeMs.getN() > 0) {
1117 dprintf(fd, " Process time ms stats: %s\n", mProcessTimeMs.toString().c_str());
1118 }
1119
1120 if (mIoJitterMs.getN() > 0) {
1121 dprintf(fd, " Hal %s jitter ms stats: %s\n",
1122 isOutput() ? "write" : "read",
1123 mIoJitterMs.toString().c_str());
1124 }
1125
Andy Hunge6c37112019-02-26 17:38:10 -08001126 if (mLatencyMs.getN() > 0) {
1127 dprintf(fd, " Threadloop %s latency stats: %s\n",
1128 isOutput() ? "write" : "read",
1129 mLatencyMs.toString().c_str());
1130 }
Robert Wu06db0a32021-08-10 19:05:34 +00001131
1132 if (mMonopipePipeDepthStats.getN() > 0) {
1133 dprintf(fd, " Monopipe %s pipe depth stats: %s\n",
1134 isOutput() ? "write" : "read",
1135 mMonopipePipeDepthStats.toString().c_str());
1136 }
Eric Laurent81784c32012-11-19 14:55:58 -08001137}
1138
Andy Hungee58e4a2023-07-07 13:47:37 -07001139void ThreadBase::dumpEffectChains_l(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -08001140{
1141 const size_t SIZE = 256;
1142 char buffer[SIZE];
Eric Laurent81784c32012-11-19 14:55:58 -08001143
Marco Nelissenb2208842014-02-07 14:00:50 -08001144 size_t numEffectChains = mEffectChains.size();
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +00001145 snprintf(buffer, SIZE, " %zu Effect Chains\n", numEffectChains);
Eric Laurent81784c32012-11-19 14:55:58 -08001146 write(fd, buffer, strlen(buffer));
1147
Marco Nelissenb2208842014-02-07 14:00:50 -08001148 for (size_t i = 0; i < numEffectChains; ++i) {
Andy Hung116bc262023-06-20 18:56:17 -07001149 sp<IAfEffectChain> chain = mEffectChains[i];
Eric Laurent81784c32012-11-19 14:55:58 -08001150 if (chain != 0) {
1151 chain->dump(fd, args);
1152 }
1153 }
1154}
1155
Andy Hungee58e4a2023-07-07 13:47:37 -07001156void ThreadBase::acquireWakeLock()
Eric Laurent81784c32012-11-19 14:55:58 -08001157{
Andy Hung972bec12023-08-31 16:13:39 -07001158 audio_utils::lock_guard _l(mutex());
Andy Hungdae27702016-10-31 14:01:16 -07001159 acquireWakeLock_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001160}
1161
Andy Hungee58e4a2023-07-07 13:47:37 -07001162String16 ThreadBase::getWakeLockTag()
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001163{
1164 switch (mType) {
Glenn Kastenbcb14862015-03-05 17:11:21 -08001165 case MIXER:
1166 return String16("AudioMix");
1167 case DIRECT:
1168 return String16("AudioDirectOut");
1169 case DUPLICATING:
1170 return String16("AudioDup");
1171 case RECORD:
1172 return String16("AudioIn");
1173 case OFFLOAD:
1174 return String16("AudioOffload");
Andy Hungea840382020-05-05 21:50:17 -07001175 case MMAP_PLAYBACK:
1176 return String16("MmapPlayback");
1177 case MMAP_CAPTURE:
1178 return String16("MmapCapture");
Eric Laurent1c5e2e32021-08-18 18:50:28 +02001179 case SPATIALIZER:
1180 return String16("AudioSpatial");
Glenn Kastenbcb14862015-03-05 17:11:21 -08001181 default:
1182 ALOG_ASSERT(false);
1183 return String16("AudioUnknown");
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001184 }
1185}
1186
Andy Hungee58e4a2023-07-07 13:47:37 -07001187void ThreadBase::acquireWakeLock_l()
Eric Laurent81784c32012-11-19 14:55:58 -08001188{
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001189 getPowerManager_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001190 if (mPowerManager != 0) {
1191 sp<IBinder> binder = new BBinder();
Andy Hungdae27702016-10-31 14:01:16 -07001192 // Uses AID_AUDIOSERVER for wakelock. updateWakeLockUids_l() updates with client uids.
Chris Ye6597d732020-02-28 22:38:25 -08001193 binder::Status status = mPowerManager->acquireWakeLockAsync(binder,
1194 POWERMANAGER_PARTIAL_WAKE_LOCK,
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001195 getWakeLockTag(),
Marco Nelissendcb346b2015-09-09 10:47:29 -07001196 String16("audioserver"),
Chris Ye6597d732020-02-28 22:38:25 -08001197 {} /* workSource */,
1198 {} /* historyTag */);
1199 if (status.isOk()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001200 mWakeLockToken = binder;
1201 }
Chris Ye6597d732020-02-28 22:38:25 -08001202 ALOGV("acquireWakeLock_l() %s status %d", mThreadName, status.exceptionCode());
Eric Laurent81784c32012-11-19 14:55:58 -08001203 }
Wei Jia3f273d12015-11-24 09:06:49 -08001204
Andy Hung3f0c9022016-01-15 17:49:46 -08001205 gBoottime.acquire(mWakeLockToken);
Andy Hung818e7a32016-02-16 18:08:07 -08001206 mTimestamp.mTimebaseOffset[ExtendedTimestamp::TIMEBASE_BOOTTIME] =
1207 gBoottime.getBoottimeOffset();
Eric Laurent81784c32012-11-19 14:55:58 -08001208}
1209
Andy Hungee58e4a2023-07-07 13:47:37 -07001210void ThreadBase::releaseWakeLock()
Eric Laurent81784c32012-11-19 14:55:58 -08001211{
Andy Hung972bec12023-08-31 16:13:39 -07001212 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001213 releaseWakeLock_l();
1214}
1215
Andy Hungee58e4a2023-07-07 13:47:37 -07001216void ThreadBase::releaseWakeLock_l()
Eric Laurent81784c32012-11-19 14:55:58 -08001217{
Andy Hung3f0c9022016-01-15 17:49:46 -08001218 gBoottime.release(mWakeLockToken);
Eric Laurent81784c32012-11-19 14:55:58 -08001219 if (mWakeLockToken != 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -08001220 ALOGV("releaseWakeLock_l() %s", mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08001221 if (mPowerManager != 0) {
Chris Ye6597d732020-02-28 22:38:25 -08001222 mPowerManager->releaseWakeLockAsync(mWakeLockToken, 0);
Eric Laurent81784c32012-11-19 14:55:58 -08001223 }
1224 mWakeLockToken.clear();
1225 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001226}
1227
Andy Hungee58e4a2023-07-07 13:47:37 -07001228void ThreadBase::getPowerManager_l() {
Eric Laurent72e3f392015-05-20 14:43:50 -07001229 if (mSystemReady && mPowerManager == 0) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001230 // use checkService() to avoid blocking if power service is not up yet
1231 sp<IBinder> binder =
1232 defaultServiceManager()->checkService(String16("power"));
1233 if (binder == 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -08001234 ALOGW("Thread %s cannot connect to the power manager service", mThreadName);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001235 } else {
Chris Ye6597d732020-02-28 22:38:25 -08001236 mPowerManager = interface_cast<os::IPowerManager>(binder);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001237 binder->linkToDeath(mDeathRecipient);
1238 }
1239 }
1240}
1241
Andy Hungee58e4a2023-07-07 13:47:37 -07001242void ThreadBase::updateWakeLockUids_l(const SortedVector<uid_t>& uids) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001243 getPowerManager_l();
Andy Hungdae27702016-10-31 14:01:16 -07001244
1245#if !LOG_NDEBUG
1246 std::stringstream s;
Andy Hungd01b0f12016-11-07 16:10:30 -08001247 for (uid_t uid : uids) {
Andy Hungdae27702016-10-31 14:01:16 -07001248 s << uid << " ";
1249 }
1250 ALOGD("updateWakeLockUids_l %s uids:%s", mThreadName, s.str().c_str());
1251#endif
1252
Andy Hung438e7572015-12-14 15:51:17 -08001253 if (mWakeLockToken == NULL) { // token may be NULL if AudioFlinger::systemReady() not called.
1254 if (mSystemReady) {
1255 ALOGE("no wake lock to update, but system ready!");
1256 } else {
1257 ALOGW("no wake lock to update, system not ready yet");
1258 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001259 return;
1260 }
1261 if (mPowerManager != 0) {
Andy Hung1f12a8a2016-11-07 16:10:30 -08001262 std::vector<int> uidsAsInt(uids.begin(), uids.end()); // powermanager expects uids as ints
Chris Ye6597d732020-02-28 22:38:25 -08001263 binder::Status status = mPowerManager->updateWakeLockUidsAsync(
1264 mWakeLockToken, uidsAsInt);
1265 ALOGV("updateWakeLockUids_l() %s status %d", mThreadName, status.exceptionCode());
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001266 }
1267}
1268
Andy Hungee58e4a2023-07-07 13:47:37 -07001269void ThreadBase::clearPowerManager()
Eric Laurent81784c32012-11-19 14:55:58 -08001270{
Andy Hung972bec12023-08-31 16:13:39 -07001271 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001272 releaseWakeLock_l();
1273 mPowerManager.clear();
1274}
1275
Andy Hungee58e4a2023-07-07 13:47:37 -07001276void ThreadBase::updateOutDevices(
jiabinc52b1ff2019-10-31 17:20:42 -07001277 const DeviceDescriptorBaseVector& outDevices __unused)
1278{
1279 ALOGE("%s should only be called in RecordThread", __func__);
1280}
1281
Andy Hungee58e4a2023-07-07 13:47:37 -07001282void ThreadBase::resizeInputBuffer_l(int32_t /* maxSharedAudioHistoryMs */)
Eric Laurentec376dc2021-04-08 20:41:22 +02001283{
1284 ALOGE("%s should only be called in RecordThread", __func__);
1285}
1286
Andy Hungee58e4a2023-07-07 13:47:37 -07001287void ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& /* who */)
Eric Laurent81784c32012-11-19 14:55:58 -08001288{
1289 sp<ThreadBase> thread = mThread.promote();
1290 if (thread != 0) {
1291 thread->clearPowerManager();
1292 }
1293 ALOGW("power manager service died !!!");
1294}
1295
Andy Hungee58e4a2023-07-07 13:47:37 -07001296void ThreadBase::setEffectSuspended_l(
Glenn Kastend848eb42016-03-08 13:42:11 -08001297 const effect_uuid_t *type, bool suspend, audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001298{
Andy Hung116bc262023-06-20 18:56:17 -07001299 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08001300 if (chain != 0) {
1301 if (type != NULL) {
1302 chain->setEffectSuspended_l(type, suspend);
1303 } else {
1304 chain->setEffectSuspendedAll_l(suspend);
1305 }
1306 }
1307
1308 updateSuspendedSessions_l(type, suspend, sessionId);
1309}
1310
Andy Hungee58e4a2023-07-07 13:47:37 -07001311void ThreadBase::checkSuspendOnAddEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08001312{
1313 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
1314 if (index < 0) {
1315 return;
1316 }
1317
1318 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
1319 mSuspendedSessions.valueAt(index);
1320
1321 for (size_t i = 0; i < sessionEffects.size(); i++) {
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07001322 const sp<SuspendedSessionDesc>& desc = sessionEffects.valueAt(i);
Eric Laurent81784c32012-11-19 14:55:58 -08001323 for (int j = 0; j < desc->mRefCount; j++) {
Andy Hung116bc262023-06-20 18:56:17 -07001324 if (sessionEffects.keyAt(i) == IAfEffectChain::kKeyForSuspendAll) {
Eric Laurent81784c32012-11-19 14:55:58 -08001325 chain->setEffectSuspendedAll_l(true);
1326 } else {
1327 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
1328 desc->mType.timeLow);
1329 chain->setEffectSuspended_l(&desc->mType, true);
1330 }
1331 }
1332 }
1333}
1334
Andy Hungee58e4a2023-07-07 13:47:37 -07001335void ThreadBase::updateSuspendedSessions_l(const effect_uuid_t* type,
Eric Laurent81784c32012-11-19 14:55:58 -08001336 bool suspend,
Glenn Kastend848eb42016-03-08 13:42:11 -08001337 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001338{
1339 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
1340
1341 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1342
1343 if (suspend) {
1344 if (index >= 0) {
1345 sessionEffects = mSuspendedSessions.valueAt(index);
1346 } else {
1347 mSuspendedSessions.add(sessionId, sessionEffects);
1348 }
1349 } else {
1350 if (index < 0) {
1351 return;
1352 }
1353 sessionEffects = mSuspendedSessions.valueAt(index);
1354 }
1355
1356
Andy Hung116bc262023-06-20 18:56:17 -07001357 int key = IAfEffectChain::kKeyForSuspendAll;
Eric Laurent81784c32012-11-19 14:55:58 -08001358 if (type != NULL) {
1359 key = type->timeLow;
1360 }
1361 index = sessionEffects.indexOfKey(key);
1362
1363 sp<SuspendedSessionDesc> desc;
1364 if (suspend) {
1365 if (index >= 0) {
1366 desc = sessionEffects.valueAt(index);
1367 } else {
1368 desc = new SuspendedSessionDesc();
1369 if (type != NULL) {
1370 desc->mType = *type;
1371 }
1372 sessionEffects.add(key, desc);
1373 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
1374 }
1375 desc->mRefCount++;
1376 } else {
1377 if (index < 0) {
1378 return;
1379 }
1380 desc = sessionEffects.valueAt(index);
1381 if (--desc->mRefCount == 0) {
1382 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
1383 sessionEffects.removeItemsAt(index);
1384 if (sessionEffects.isEmpty()) {
1385 ALOGV("updateSuspendedSessions_l() restore removing session %d",
1386 sessionId);
1387 mSuspendedSessions.removeItem(sessionId);
1388 }
1389 }
1390 }
1391 if (!sessionEffects.isEmpty()) {
1392 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1393 }
1394}
1395
Andy Hungee58e4a2023-07-07 13:47:37 -07001396void ThreadBase::checkSuspendOnEffectEnabled(bool enabled,
Eric Laurent6b446ce2019-12-13 10:56:31 -08001397 audio_session_t sessionId,
Andy Hung920f6572022-10-06 12:09:49 -07001398 bool threadLocked)
1399NO_THREAD_SAFETY_ANALYSIS // manual locking
1400{
Eric Laurent6b446ce2019-12-13 10:56:31 -08001401 if (!threadLocked) {
Andy Hungc5007f82023-08-29 14:26:09 -07001402 mutex().lock();
Eric Laurent6b446ce2019-12-13 10:56:31 -08001403 }
Eric Laurent81784c32012-11-19 14:55:58 -08001404
Eric Laurent81784c32012-11-19 14:55:58 -08001405 if (mType != RECORD) {
1406 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1407 // another session. This gives the priority to well behaved effect control panels
1408 // and applications not using global effects.
1409 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
1410 // global effects
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001411 if (!audio_is_global_session(sessionId)) {
Eric Laurent81784c32012-11-19 14:55:58 -08001412 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1413 }
1414 }
1415
Eric Laurent6b446ce2019-12-13 10:56:31 -08001416 if (!threadLocked) {
Andy Hungc5007f82023-08-29 14:26:09 -07001417 mutex().unlock();
Eric Laurent81784c32012-11-19 14:55:58 -08001418 }
1419}
1420
Andy Hungc5007f82023-08-29 14:26:09 -07001421// checkEffectCompatibility_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07001422status_t RecordThread::checkEffectCompatibility_l(
Eric Laurent4c415062016-06-17 16:14:16 -07001423 const effect_descriptor_t *desc, audio_session_t sessionId)
1424{
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001425 // No global output effect sessions on record threads
1426 if (sessionId == AUDIO_SESSION_OUTPUT_MIX
1427 || sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Eric Laurent4c415062016-06-17 16:14:16 -07001428 ALOGW("checkEffectCompatibility_l(): global effect %s on record thread %s",
1429 desc->name, mThreadName);
1430 return BAD_VALUE;
1431 }
1432 // only pre processing effects on record thread
1433 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC) {
1434 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on record thread %s",
1435 desc->name, mThreadName);
1436 return BAD_VALUE;
1437 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001438
1439 // always allow effects without processing load or latency
1440 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1441 return NO_ERROR;
1442 }
1443
Eric Laurent4c415062016-06-17 16:14:16 -07001444 audio_input_flags_t flags = mInput->flags;
1445 if (hasFastCapture() || (flags & AUDIO_INPUT_FLAG_FAST)) {
1446 if (flags & AUDIO_INPUT_FLAG_RAW) {
1447 ALOGW("checkEffectCompatibility_l(): effect %s on record thread %s in raw mode",
1448 desc->name, mThreadName);
1449 return BAD_VALUE;
1450 }
1451 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1452 ALOGW("checkEffectCompatibility_l(): non HW effect %s on record thread %s in fast mode",
1453 desc->name, mThreadName);
1454 return BAD_VALUE;
1455 }
1456 }
jiabineb3bda02020-06-30 14:07:03 -07001457
Andy Hung116bc262023-06-20 18:56:17 -07001458 if (IAfEffectModule::isHapticGenerator(&desc->type)) {
jiabineb3bda02020-06-30 14:07:03 -07001459 ALOGE("%s(): HapticGenerator is not supported in RecordThread", __func__);
1460 return BAD_VALUE;
1461 }
Eric Laurent4c415062016-06-17 16:14:16 -07001462 return NO_ERROR;
1463}
1464
Andy Hungc5007f82023-08-29 14:26:09 -07001465// checkEffectCompatibility_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07001466status_t PlaybackThread::checkEffectCompatibility_l(
Eric Laurent4c415062016-06-17 16:14:16 -07001467 const effect_descriptor_t *desc, audio_session_t sessionId)
1468{
1469 // no preprocessing on playback threads
1470 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001471 ALOGW("%s: pre processing effect %s created on playback"
1472 " thread %s", __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001473 return BAD_VALUE;
1474 }
1475
Eric Laurent3e4de772017-07-16 16:55:08 -07001476 // always allow effects without processing load or latency
1477 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1478 return NO_ERROR;
1479 }
1480
Andy Hung116bc262023-06-20 18:56:17 -07001481 if (IAfEffectModule::isHapticGenerator(&desc->type) && mHapticChannelCount == 0) {
jiabineb3bda02020-06-30 14:07:03 -07001482 ALOGW("%s: thread doesn't support haptic playback while the effect is HapticGenerator",
1483 __func__);
1484 return BAD_VALUE;
1485 }
1486
Eric Laurentf690c462021-09-17 14:47:03 +02001487 if (memcmp(&desc->type, FX_IID_SPATIALIZER, sizeof(effect_uuid_t)) == 0
1488 && mType != SPATIALIZER) {
1489 ALOGW("%s: attempt to create a spatializer effect on a thread of type %d",
1490 __func__, mType);
1491 return BAD_VALUE;
1492 }
1493
Eric Laurent4c415062016-06-17 16:14:16 -07001494 switch (mType) {
1495 case MIXER: {
Eric Laurent4c415062016-06-17 16:14:16 -07001496 audio_output_flags_t flags = mOutput->flags;
1497 if (hasFastMixer() || (flags & AUDIO_OUTPUT_FLAG_FAST)) {
1498 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1499 // global effects are applied only to non fast tracks if they are SW
1500 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1501 break;
1502 }
1503 } else if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1504 // only post processing on output stage session
1505 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001506 ALOGW("%s: non post processing effect %s not allowed on output stage session",
1507 __func__, desc->name);
Eric Laurent4c415062016-06-17 16:14:16 -07001508 return BAD_VALUE;
1509 }
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001510 } else if (sessionId == AUDIO_SESSION_DEVICE) {
1511 // only post processing on output stage session
1512 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001513 ALOGW("%s: non post processing effect %s not allowed on device session",
1514 __func__, desc->name);
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001515 return BAD_VALUE;
1516 }
Eric Laurent4c415062016-06-17 16:14:16 -07001517 } else {
1518 // no restriction on effects applied on non fast tracks
1519 if ((hasAudioSession_l(sessionId) & ThreadBase::FAST_SESSION) == 0) {
1520 break;
1521 }
1522 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001523
Eric Laurent4c415062016-06-17 16:14:16 -07001524 if (flags & AUDIO_OUTPUT_FLAG_RAW) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001525 ALOGW("%s: effect %s on playback thread in raw mode", __func__, desc->name);
Eric Laurent4c415062016-06-17 16:14:16 -07001526 return BAD_VALUE;
1527 }
1528 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001529 ALOGW("%s: non HW effect %s on playback thread in fast mode",
1530 __func__, desc->name);
Eric Laurent4c415062016-06-17 16:14:16 -07001531 return BAD_VALUE;
1532 }
1533 }
1534 } break;
1535 case OFFLOAD:
Jean-Michel Trivi773ee952016-07-11 16:53:18 -07001536 // nothing actionable on offload threads, if the effect:
1537 // - is offloadable: the effect can be created
1538 // - is NOT offloadable: the effect should still be created, but EffectHandle::enable()
1539 // will take care of invalidating the tracks of the thread
Eric Laurent4c415062016-06-17 16:14:16 -07001540 break;
1541 case DIRECT:
1542 // Reject any effect on Direct output threads for now, since the format of
1543 // mSinkBuffer is not guaranteed to be compatible with effect processing (PCM 16 stereo).
Eric Laurentb62d0362021-10-26 17:40:18 +02001544 ALOGW("%s: effect %s on DIRECT output thread %s",
1545 __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001546 return BAD_VALUE;
1547 case DUPLICATING:
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001548 if (audio_is_global_session(sessionId)) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001549 ALOGW("%s: global effect %s on DUPLICATING thread %s",
1550 __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001551 return BAD_VALUE;
1552 }
1553 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001554 ALOGW("%s: post processing effect %s on DUPLICATING thread %s",
1555 __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001556 return BAD_VALUE;
1557 }
1558 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) != 0) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001559 ALOGW("%s: HW tunneled effect %s on DUPLICATING thread %s",
1560 __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001561 return BAD_VALUE;
1562 }
1563 break;
Eric Laurent1c5e2e32021-08-18 18:50:28 +02001564 case SPATIALIZER:
Eric Laurentb62d0362021-10-26 17:40:18 +02001565 // Global effects (AUDIO_SESSION_OUTPUT_MIX) are not supported on spatializer mixer
1566 // as there is no common accumulation buffer for sptialized and non sptialized tracks.
1567 // Post processing effects (AUDIO_SESSION_OUTPUT_STAGE or AUDIO_SESSION_DEVICE)
1568 // are supported and added after the spatializer.
1569 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1570 ALOGW("%s: global effect %s not supported on spatializer thread %s",
1571 __func__, desc->name, mThreadName);
Eric Laurentb3f315a2021-07-13 15:09:05 +02001572 return BAD_VALUE;
Eric Laurentb62d0362021-10-26 17:40:18 +02001573 } else if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1574 // only post processing , downmixer or spatializer effects on output stage session
1575 if (memcmp(&desc->type, FX_IID_SPATIALIZER, sizeof(effect_uuid_t)) == 0
1576 || memcmp(&desc->type, EFFECT_UIID_DOWNMIX, sizeof(effect_uuid_t)) == 0) {
1577 break;
1578 }
1579 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
1580 ALOGW("%s: non post processing effect %s not allowed on output stage session",
1581 __func__, desc->name);
1582 return BAD_VALUE;
1583 }
1584 } else if (sessionId == AUDIO_SESSION_DEVICE) {
1585 // only post processing on output stage session
1586 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
1587 ALOGW("%s: non post processing effect %s not allowed on device session",
1588 __func__, desc->name);
1589 return BAD_VALUE;
1590 }
Eric Laurentb3f315a2021-07-13 15:09:05 +02001591 }
1592 break;
jiabinc658e452022-10-21 20:52:21 +00001593 case BIT_PERFECT:
1594 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) != 0) {
1595 // Allow HW accelerated effects of tunnel type
1596 break;
1597 }
1598 // As bit-perfect tracks will not be allowed to apply audio effect that will touch the audio
1599 // data, effects will not be allowed on 1) global effects (AUDIO_SESSION_OUTPUT_MIX),
1600 // 2) post-processing effects (AUDIO_SESSION_OUTPUT_STAGE or AUDIO_SESSION_DEVICE) and
1601 // 3) there is any bit-perfect track with the given session id.
1602 if (sessionId == AUDIO_SESSION_OUTPUT_MIX || sessionId == AUDIO_SESSION_OUTPUT_STAGE ||
1603 sessionId == AUDIO_SESSION_DEVICE) {
1604 ALOGW("%s: effect %s not supported on bit-perfect thread %s",
1605 __func__, desc->name, mThreadName);
1606 return BAD_VALUE;
1607 } else if ((hasAudioSession_l(sessionId) & ThreadBase::BIT_PERFECT_SESSION) != 0) {
1608 ALOGW("%s: effect %s not supported as there is a bit-perfect track with session as %d",
1609 __func__, desc->name, sessionId);
1610 return BAD_VALUE;
1611 }
1612 break;
Eric Laurent4c415062016-06-17 16:14:16 -07001613 default:
1614 LOG_ALWAYS_FATAL("checkEffectCompatibility_l(): wrong thread type %d", mType);
1615 }
1616
1617 return NO_ERROR;
1618}
1619
Andy Hungc5007f82023-08-29 14:26:09 -07001620// ThreadBase::createEffect_l() must be called with AudioFlinger::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07001621sp<IAfEffectHandle> ThreadBase::createEffect_l(
Andy Hung88035ac2023-06-27 17:05:02 -07001622 const sp<Client>& client,
Eric Laurent81784c32012-11-19 14:55:58 -08001623 const sp<IEffectClient>& effectClient,
1624 int32_t priority,
Glenn Kastend848eb42016-03-08 13:42:11 -08001625 audio_session_t sessionId,
Eric Laurent81784c32012-11-19 14:55:58 -08001626 effect_descriptor_t *desc,
1627 int *enabled,
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001628 status_t *status,
Eric Laurent2fe0acd2020-03-13 14:30:46 -07001629 bool pinned,
Eric Laurentde8caf42021-08-11 17:19:25 +02001630 bool probe,
1631 bool notifyFramesProcessed)
Eric Laurent81784c32012-11-19 14:55:58 -08001632{
Andy Hung116bc262023-06-20 18:56:17 -07001633 sp<IAfEffectModule> effect;
1634 sp<IAfEffectHandle> handle;
Eric Laurent81784c32012-11-19 14:55:58 -08001635 status_t lStatus;
Andy Hung116bc262023-06-20 18:56:17 -07001636 sp<IAfEffectChain> chain;
Eric Laurent81784c32012-11-19 14:55:58 -08001637 bool chainCreated = false;
1638 bool effectCreated = false;
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001639 audio_unique_id_t effectId = AUDIO_UNIQUE_ID_USE_UNSPECIFIED;
Eric Laurent81784c32012-11-19 14:55:58 -08001640
1641 lStatus = initCheck();
1642 if (lStatus != NO_ERROR) {
1643 ALOGW("createEffect_l() Audio driver not initialized.");
1644 goto Exit;
1645 }
1646
Eric Laurent81784c32012-11-19 14:55:58 -08001647 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
1648
Andy Hungc5007f82023-08-29 14:26:09 -07001649 { // scope for mutex()
Andy Hung972bec12023-08-31 16:13:39 -07001650 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001651
Eric Laurent4c415062016-06-17 16:14:16 -07001652 lStatus = checkEffectCompatibility_l(desc, sessionId);
Eric Laurent2fe0acd2020-03-13 14:30:46 -07001653 if (probe || lStatus != NO_ERROR) {
Eric Laurent4c415062016-06-17 16:14:16 -07001654 goto Exit;
1655 }
1656
Eric Laurent81784c32012-11-19 14:55:58 -08001657 // check for existing effect chain with the requested audio session
1658 chain = getEffectChain_l(sessionId);
1659 if (chain == 0) {
1660 // create a new chain for this session
1661 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
Andy Hung116bc262023-06-20 18:56:17 -07001662 chain = IAfEffectChain::create(this, sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08001663 addEffectChain_l(chain);
1664 chain->setStrategy(getStrategyForSession_l(sessionId));
1665 chainCreated = true;
1666 } else {
1667 effect = chain->getEffectFromDesc_l(desc);
1668 }
1669
1670 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
1671
1672 if (effect == 0) {
Andy Hung583043b2023-07-17 17:05:00 -07001673 effectId = mAfThreadCallback->nextUniqueId(AUDIO_UNIQUE_ID_USE_EFFECT);
Eric Laurent81784c32012-11-19 14:55:58 -08001674 // create a new effect module if none present in the chain
Eric Laurent6b446ce2019-12-13 10:56:31 -08001675 lStatus = chain->createEffect_l(effect, desc, effectId, sessionId, pinned);
Eric Laurent81784c32012-11-19 14:55:58 -08001676 if (lStatus != NO_ERROR) {
1677 goto Exit;
1678 }
1679 effectCreated = true;
1680
jiabinc52b1ff2019-10-31 17:20:42 -07001681 // FIXME: use vector of device and address when effect interface is ready.
jiabin8f278ee2019-11-11 12:16:27 -08001682 effect->setDevices(outDeviceTypeAddrs());
1683 effect->setInputDevice(inDeviceTypeAddr());
Andy Hung583043b2023-07-17 17:05:00 -07001684 effect->setMode(mAfThreadCallback->getMode());
Eric Laurent81784c32012-11-19 14:55:58 -08001685 effect->setAudioSource(mAudioSource);
1686 }
jiabin1319f5a2021-03-30 22:21:24 +00001687 if (effect->isHapticGenerator()) {
1688 // TODO(b/184194057): Use the vibrator information from the vibrator that will be used
1689 // for the HapticGenerator.
Lais Andradebc3f37a2021-07-02 00:13:19 +01001690 const std::optional<media::AudioVibratorInfo> defaultVibratorInfo =
Andy Hung583043b2023-07-17 17:05:00 -07001691 std::move(mAfThreadCallback->getDefaultVibratorInfo_l());
Lais Andradebc3f37a2021-07-02 00:13:19 +01001692 if (defaultVibratorInfo) {
jiabin1319f5a2021-03-30 22:21:24 +00001693 // Only set the vibrator info when it is a valid one.
Lais Andradebc3f37a2021-07-02 00:13:19 +01001694 effect->setVibratorInfo(*defaultVibratorInfo);
jiabin1319f5a2021-03-30 22:21:24 +00001695 }
1696 }
Eric Laurent81784c32012-11-19 14:55:58 -08001697 // create effect handle and connect it to effect module
Andy Hung116bc262023-06-20 18:56:17 -07001698 handle = IAfEffectHandle::create(
1699 effect, client, effectClient, priority, notifyFramesProcessed);
Glenn Kastene75da402013-11-20 13:54:52 -08001700 lStatus = handle->initCheck();
1701 if (lStatus == OK) {
1702 lStatus = effect->addHandle(handle.get());
Eric Laurentb3f315a2021-07-13 15:09:05 +02001703 sendCheckOutputStageEffectsEvent_l();
Glenn Kastene75da402013-11-20 13:54:52 -08001704 }
Eric Laurent81784c32012-11-19 14:55:58 -08001705 if (enabled != NULL) {
1706 *enabled = (int)effect->isEnabled();
1707 }
1708 }
1709
1710Exit:
Eric Laurent2fe0acd2020-03-13 14:30:46 -07001711 if (!probe && lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Andy Hung972bec12023-08-31 16:13:39 -07001712 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001713 if (effectCreated) {
1714 chain->removeEffect_l(effect);
1715 }
Eric Laurent81784c32012-11-19 14:55:58 -08001716 if (chainCreated) {
1717 removeEffectChain_l(chain);
1718 }
haobo101735295ff7b0d2017-03-17 17:44:03 +08001719 // handle must be cleared by caller to avoid deadlock.
Eric Laurent81784c32012-11-19 14:55:58 -08001720 }
1721
Glenn Kasten9156ef32013-08-06 15:39:08 -07001722 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001723 return handle;
1724}
1725
Andy Hungee58e4a2023-07-07 13:47:37 -07001726void ThreadBase::disconnectEffectHandle(IAfEffectHandle* handle,
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001727 bool unpinIfLast)
1728{
1729 bool remove = false;
Andy Hung116bc262023-06-20 18:56:17 -07001730 sp<IAfEffectModule> effect;
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001731 {
Andy Hung972bec12023-08-31 16:13:39 -07001732 audio_utils::lock_guard _l(mutex());
Andy Hung116bc262023-06-20 18:56:17 -07001733 sp<IAfEffectBase> effectBase = handle->effect().promote();
Eric Laurent41709552019-12-16 19:34:05 -08001734 if (effectBase == nullptr) {
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001735 return;
1736 }
Eric Laurentb82e6b72019-11-22 17:25:04 -08001737 effect = effectBase->asEffectModule();
1738 if (effect == nullptr) {
1739 return;
1740 }
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001741 // restore suspended effects if the disconnected handle was enabled and the last one.
1742 remove = (effect->removeHandle(handle) == 0) && (!effect->isPinned() || unpinIfLast);
1743 if (remove) {
1744 removeEffect_l(effect, true);
1745 }
Eric Laurentb3f315a2021-07-13 15:09:05 +02001746 sendCheckOutputStageEffectsEvent_l();
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001747 }
1748 if (remove) {
Andy Hung583043b2023-07-17 17:05:00 -07001749 mAfThreadCallback->updateOrphanEffectChains(effect);
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001750 if (handle->enabled()) {
Eric Laurent6b446ce2019-12-13 10:56:31 -08001751 effect->checkSuspendOnEffectEnabled(false, false /*threadLocked*/);
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001752 }
1753 }
1754}
1755
Andy Hungee58e4a2023-07-07 13:47:37 -07001756void ThreadBase::onEffectEnable(const sp<IAfEffectModule>& effect) {
Andy Hungea840382020-05-05 21:50:17 -07001757 if (isOffloadOrMmap()) {
Andy Hung972bec12023-08-31 16:13:39 -07001758 audio_utils::lock_guard _l(mutex());
Eric Laurent6b446ce2019-12-13 10:56:31 -08001759 broadcast_l();
1760 }
1761 if (!effect->isOffloadable()) {
1762 if (mType == ThreadBase::OFFLOAD) {
1763 PlaybackThread *t = (PlaybackThread *)this;
1764 t->invalidateTracks(AUDIO_STREAM_MUSIC);
1765 }
1766 if (effect->sessionId() == AUDIO_SESSION_OUTPUT_MIX) {
Andy Hung583043b2023-07-17 17:05:00 -07001767 mAfThreadCallback->onNonOffloadableGlobalEffectEnable();
Eric Laurent6b446ce2019-12-13 10:56:31 -08001768 }
1769 }
1770}
1771
Andy Hungee58e4a2023-07-07 13:47:37 -07001772void ThreadBase::onEffectDisable() {
Andy Hungea840382020-05-05 21:50:17 -07001773 if (isOffloadOrMmap()) {
Andy Hung972bec12023-08-31 16:13:39 -07001774 audio_utils::lock_guard _l(mutex());
Eric Laurent6b446ce2019-12-13 10:56:31 -08001775 broadcast_l();
1776 }
1777}
1778
Andy Hungee58e4a2023-07-07 13:47:37 -07001779sp<IAfEffectModule> ThreadBase::getEffect(audio_session_t sessionId,
Andy Hung440901d2023-06-29 21:19:25 -07001780 int effectId) const
Eric Laurent81784c32012-11-19 14:55:58 -08001781{
Andy Hung972bec12023-08-31 16:13:39 -07001782 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001783 return getEffect_l(sessionId, effectId);
1784}
1785
Andy Hungee58e4a2023-07-07 13:47:37 -07001786sp<IAfEffectModule> ThreadBase::getEffect_l(audio_session_t sessionId,
Andy Hung440901d2023-06-29 21:19:25 -07001787 int effectId) const
Eric Laurent81784c32012-11-19 14:55:58 -08001788{
Andy Hung116bc262023-06-20 18:56:17 -07001789 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08001790 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
1791}
1792
Andy Hungee58e4a2023-07-07 13:47:37 -07001793std::vector<int> ThreadBase::getEffectIds_l(audio_session_t sessionId) const
Eric Laurent6c796322019-04-09 14:13:17 -07001794{
Andy Hung116bc262023-06-20 18:56:17 -07001795 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent6c796322019-04-09 14:13:17 -07001796 return chain != nullptr ? chain->getEffectIds() : std::vector<int>{};
1797}
1798
Andy Hung972bec12023-08-31 16:13:39 -07001799// PlaybackThread::addEffect_ll() must be called with AudioFlinger::mutex() and
1800// ThreadBase::mutex() held
1801status_t ThreadBase::addEffect_ll(const sp<IAfEffectModule>& effect)
Eric Laurent81784c32012-11-19 14:55:58 -08001802{
1803 // check for existing effect chain with the requested audio session
Glenn Kastend848eb42016-03-08 13:42:11 -08001804 audio_session_t sessionId = effect->sessionId();
Andy Hung116bc262023-06-20 18:56:17 -07001805 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08001806 bool chainCreated = false;
1807
Eric Laurent5baf2af2013-09-12 17:37:00 -07001808 ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(),
Andy Hung972bec12023-08-31 16:13:39 -07001809 "%s: on offloaded thread %p: effect %s does not support offload flags %#x",
1810 __func__, this, effect->desc().name, effect->desc().flags);
Eric Laurent5baf2af2013-09-12 17:37:00 -07001811
Eric Laurent81784c32012-11-19 14:55:58 -08001812 if (chain == 0) {
1813 // create a new chain for this session
Andy Hung972bec12023-08-31 16:13:39 -07001814 ALOGV("%s: new effect chain for session %d", __func__, sessionId);
Andy Hung116bc262023-06-20 18:56:17 -07001815 chain = IAfEffectChain::create(this, sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08001816 addEffectChain_l(chain);
1817 chain->setStrategy(getStrategyForSession_l(sessionId));
1818 chainCreated = true;
1819 }
Andy Hung972bec12023-08-31 16:13:39 -07001820 ALOGV("%s: %p chain %p effect %p", __func__, this, chain.get(), effect.get());
Eric Laurent81784c32012-11-19 14:55:58 -08001821
1822 if (chain->getEffectFromId_l(effect->id()) != 0) {
Andy Hung972bec12023-08-31 16:13:39 -07001823 ALOGW("%s: %p effect %s already present in chain %p",
1824 __func__, this, effect->desc().name, chain.get());
Eric Laurent81784c32012-11-19 14:55:58 -08001825 return BAD_VALUE;
1826 }
1827
Eric Laurent5baf2af2013-09-12 17:37:00 -07001828 effect->setOffloaded(mType == OFFLOAD, mId);
1829
Eric Laurent81784c32012-11-19 14:55:58 -08001830 status_t status = chain->addEffect_l(effect);
1831 if (status != NO_ERROR) {
1832 if (chainCreated) {
1833 removeEffectChain_l(chain);
1834 }
1835 return status;
1836 }
1837
jiabin8f278ee2019-11-11 12:16:27 -08001838 effect->setDevices(outDeviceTypeAddrs());
1839 effect->setInputDevice(inDeviceTypeAddr());
Andy Hung583043b2023-07-17 17:05:00 -07001840 effect->setMode(mAfThreadCallback->getMode());
Eric Laurent81784c32012-11-19 14:55:58 -08001841 effect->setAudioSource(mAudioSource);
Eric Laurentd8365c52017-07-16 15:27:05 -07001842
Eric Laurent81784c32012-11-19 14:55:58 -08001843 return NO_ERROR;
1844}
1845
Andy Hungee58e4a2023-07-07 13:47:37 -07001846void ThreadBase::removeEffect_l(const sp<IAfEffectModule>& effect, bool release) {
Eric Laurent81784c32012-11-19 14:55:58 -08001847
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001848 ALOGV("%s %p effect %p", __FUNCTION__, this, effect.get());
Eric Laurent81784c32012-11-19 14:55:58 -08001849 effect_descriptor_t desc = effect->desc();
1850 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
1851 detachAuxEffect_l(effect->id());
1852 }
1853
Andy Hung116bc262023-06-20 18:56:17 -07001854 sp<IAfEffectChain> chain = effect->getCallback()->chain().promote();
Eric Laurent81784c32012-11-19 14:55:58 -08001855 if (chain != 0) {
1856 // remove effect chain if removing last effect
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001857 if (chain->removeEffect_l(effect, release) == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08001858 removeEffectChain_l(chain);
1859 }
1860 } else {
1861 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
1862 }
1863}
1864
Andy Hungee58e4a2023-07-07 13:47:37 -07001865void ThreadBase::lockEffectChains_l(
Andy Hung116bc262023-06-20 18:56:17 -07001866 Vector<sp<IAfEffectChain>>& effectChains)
Andy Hung920f6572022-10-06 12:09:49 -07001867NO_THREAD_SAFETY_ANALYSIS // calls EffectChain::lock()
Eric Laurent81784c32012-11-19 14:55:58 -08001868{
1869 effectChains = mEffectChains;
1870 for (size_t i = 0; i < mEffectChains.size(); i++) {
Andy Hungf65f5a72023-08-29 12:19:17 -07001871 mEffectChains[i]->mutex().lock();
Eric Laurent81784c32012-11-19 14:55:58 -08001872 }
1873}
1874
Andy Hungee58e4a2023-07-07 13:47:37 -07001875void ThreadBase::unlockEffectChains(
Andy Hung116bc262023-06-20 18:56:17 -07001876 const Vector<sp<IAfEffectChain>>& effectChains)
Andy Hung920f6572022-10-06 12:09:49 -07001877NO_THREAD_SAFETY_ANALYSIS // calls EffectChain::unlock()
Eric Laurent81784c32012-11-19 14:55:58 -08001878{
1879 for (size_t i = 0; i < effectChains.size(); i++) {
Andy Hungf65f5a72023-08-29 12:19:17 -07001880 effectChains[i]->mutex().unlock();
Eric Laurent81784c32012-11-19 14:55:58 -08001881 }
1882}
1883
Andy Hungee58e4a2023-07-07 13:47:37 -07001884sp<IAfEffectChain> ThreadBase::getEffectChain(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08001885{
Andy Hung972bec12023-08-31 16:13:39 -07001886 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001887 return getEffectChain_l(sessionId);
1888}
1889
Andy Hungee58e4a2023-07-07 13:47:37 -07001890sp<IAfEffectChain> ThreadBase::getEffectChain_l(audio_session_t sessionId)
Glenn Kastend848eb42016-03-08 13:42:11 -08001891 const
Eric Laurent81784c32012-11-19 14:55:58 -08001892{
1893 size_t size = mEffectChains.size();
1894 for (size_t i = 0; i < size; i++) {
1895 if (mEffectChains[i]->sessionId() == sessionId) {
1896 return mEffectChains[i];
1897 }
1898 }
1899 return 0;
1900}
1901
Andy Hungee58e4a2023-07-07 13:47:37 -07001902void ThreadBase::setMode(audio_mode_t mode)
Eric Laurent81784c32012-11-19 14:55:58 -08001903{
Andy Hung972bec12023-08-31 16:13:39 -07001904 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001905 size_t size = mEffectChains.size();
1906 for (size_t i = 0; i < size; i++) {
1907 mEffectChains[i]->setMode_l(mode);
1908 }
1909}
1910
Andy Hungee58e4a2023-07-07 13:47:37 -07001911void ThreadBase::toAudioPortConfig(struct audio_port_config* config)
Eric Laurent83b88082014-06-20 18:31:16 -07001912{
1913 config->type = AUDIO_PORT_TYPE_MIX;
1914 config->ext.mix.handle = mId;
1915 config->sample_rate = mSampleRate;
Mikhail Naganov88d54da2023-09-11 11:53:50 -07001916 config->format = mHALFormat;
Eric Laurent83b88082014-06-20 18:31:16 -07001917 config->channel_mask = mChannelMask;
1918 config->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
1919 AUDIO_PORT_CONFIG_FORMAT;
1920}
1921
Andy Hungee58e4a2023-07-07 13:47:37 -07001922void ThreadBase::systemReady()
Eric Laurent72e3f392015-05-20 14:43:50 -07001923{
Andy Hung972bec12023-08-31 16:13:39 -07001924 audio_utils::lock_guard _l(mutex());
Eric Laurent72e3f392015-05-20 14:43:50 -07001925 if (mSystemReady) {
1926 return;
1927 }
1928 mSystemReady = true;
1929
1930 for (size_t i = 0; i < mPendingConfigEvents.size(); i++) {
1931 sendConfigEvent_l(mPendingConfigEvents.editItemAt(i));
1932 }
1933 mPendingConfigEvents.clear();
1934}
1935
Andy Hungdae27702016-10-31 14:01:16 -07001936template <typename T>
Andy Hungee58e4a2023-07-07 13:47:37 -07001937ssize_t ThreadBase::ActiveTracks<T>::add(const sp<T>& track) {
Andy Hungdae27702016-10-31 14:01:16 -07001938 ssize_t index = mActiveTracks.indexOf(track);
1939 if (index >= 0) {
1940 ALOGW("ActiveTracks<T>::add track %p already there", track.get());
1941 return index;
1942 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001943 logTrack("add", track);
Andy Hungdae27702016-10-31 14:01:16 -07001944 mActiveTracksGeneration++;
1945 mLatestActiveTrack = track;
Atneya Nair166663a2023-06-27 19:16:24 -07001946 track->beginBatteryAttribution();
Kevin Rocard069c2712018-03-29 19:09:14 -07001947 mHasChanged = true;
Andy Hungdae27702016-10-31 14:01:16 -07001948 return mActiveTracks.add(track);
1949}
1950
1951template <typename T>
Andy Hungee58e4a2023-07-07 13:47:37 -07001952ssize_t ThreadBase::ActiveTracks<T>::remove(const sp<T>& track) {
Andy Hungdae27702016-10-31 14:01:16 -07001953 ssize_t index = mActiveTracks.remove(track);
1954 if (index < 0) {
1955 ALOGW("ActiveTracks<T>::remove nonexistent track %p", track.get());
1956 return index;
1957 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001958 logTrack("remove", track);
Andy Hungdae27702016-10-31 14:01:16 -07001959 mActiveTracksGeneration++;
Atneya Nair166663a2023-06-27 19:16:24 -07001960 track->endBatteryAttribution();
Andy Hungdae27702016-10-31 14:01:16 -07001961 // mLatestActiveTrack is not cleared even if is the same as track.
Kevin Rocard069c2712018-03-29 19:09:14 -07001962 mHasChanged = true;
Andy Hung8946a282018-04-19 20:04:56 -07001963#ifdef TEE_SINK
1964 track->dumpTee(-1 /* fd */, "_REMOVE");
1965#endif
Andy Hungc2b11cb2020-04-22 09:04:01 -07001966 track->logEndInterval(); // log to MediaMetrics
Andy Hungdae27702016-10-31 14:01:16 -07001967 return index;
1968}
1969
1970template <typename T>
Andy Hungee58e4a2023-07-07 13:47:37 -07001971void ThreadBase::ActiveTracks<T>::clear() {
Andy Hungdae27702016-10-31 14:01:16 -07001972 for (const sp<T> &track : mActiveTracks) {
Atneya Nair166663a2023-06-27 19:16:24 -07001973 track->endBatteryAttribution();
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001974 logTrack("clear", track);
Andy Hungdae27702016-10-31 14:01:16 -07001975 }
1976 mLastActiveTracksGeneration = mActiveTracksGeneration;
Kevin Rocard069c2712018-03-29 19:09:14 -07001977 if (!mActiveTracks.empty()) { mHasChanged = true; }
Andy Hungdae27702016-10-31 14:01:16 -07001978 mActiveTracks.clear();
1979 mLatestActiveTrack.clear();
Andy Hungdae27702016-10-31 14:01:16 -07001980}
1981
1982template <typename T>
Andy Hungab65b182023-09-06 19:41:47 -07001983void ThreadBase::ActiveTracks<T>::updatePowerState_l(
Andy Hung920f6572022-10-06 12:09:49 -07001984 const sp<ThreadBase>& thread, bool force) {
Andy Hungdae27702016-10-31 14:01:16 -07001985 // Updates ActiveTracks client uids to the thread wakelock.
1986 if (mActiveTracksGeneration != mLastActiveTracksGeneration || force) {
1987 thread->updateWakeLockUids_l(getWakeLockUids());
1988 mLastActiveTracksGeneration = mActiveTracksGeneration;
1989 }
Andy Hungdae27702016-10-31 14:01:16 -07001990}
Eric Laurent83b88082014-06-20 18:31:16 -07001991
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001992template <typename T>
Andy Hungee58e4a2023-07-07 13:47:37 -07001993bool ThreadBase::ActiveTracks<T>::readAndClearHasChanged() {
Jasmine Chaeaa10e42021-05-11 10:11:14 +08001994 bool hasChanged = mHasChanged;
Kevin Rocard069c2712018-03-29 19:09:14 -07001995 mHasChanged = false;
Jasmine Chaeaa10e42021-05-11 10:11:14 +08001996
1997 for (const sp<T> &track : mActiveTracks) {
1998 // Do not short-circuit as all hasChanged states must be reset
1999 // as all the metadata are going to be sent
2000 hasChanged |= track->readAndClearHasChanged();
2001 }
Kevin Rocard069c2712018-03-29 19:09:14 -07002002 return hasChanged;
2003}
2004
2005template <typename T>
Andy Hungee58e4a2023-07-07 13:47:37 -07002006void ThreadBase::ActiveTracks<T>::logTrack(
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002007 const char *funcName, const sp<T> &track) const {
2008 if (mLocalLog != nullptr) {
2009 String8 result;
2010 track->appendDump(result, false /* active */);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00002011 mLocalLog->log("AT::%-10s(%p) %s", funcName, track.get(), result.c_str());
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002012 }
2013}
2014
Andy Hungee58e4a2023-07-07 13:47:37 -07002015void ThreadBase::broadcast_l()
Eric Laurent6acd1d42017-01-04 14:23:29 -08002016{
2017 // Thread could be blocked waiting for async
2018 // so signal it to handle state changes immediately
2019 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
2020 // be lost so we also flag to prevent it blocking on mWaitWorkCV
2021 mSignalPending = true;
Andy Hungc5007f82023-08-29 14:26:09 -07002022 mWaitWorkCV.notify_all();
Eric Laurent6acd1d42017-01-04 14:23:29 -08002023}
2024
Andy Hungd0979812019-02-21 15:51:44 -08002025// Call only from threadLoop() or when it is idle.
2026// Do not call from high performance code as this may do binder rpc to the MediaMetrics service.
Andy Hungee58e4a2023-07-07 13:47:37 -07002027void ThreadBase::sendStatistics(bool force)
Andy Hungab65b182023-09-06 19:41:47 -07002028NO_THREAD_SAFETY_ANALYSIS
Andy Hungd0979812019-02-21 15:51:44 -08002029{
2030 // Do not log if we have no stats.
2031 // We choose the timestamp verifier because it is the most likely item to be present.
2032 const int64_t nstats = mTimestampVerifier.getN() - mLastRecordedTimestampVerifierN;
2033 if (nstats == 0) {
2034 return;
2035 }
2036
2037 // Don't log more frequently than once per 12 hours.
2038 // We use BOOTTIME to include suspend time.
2039 const int64_t timeNs = systemTime(SYSTEM_TIME_BOOTTIME);
2040 const int64_t sinceNs = timeNs - mLastRecordedTimeNs; // ok if mLastRecordedTimeNs = 0
2041 if (!force && sinceNs <= 12 * NANOS_PER_HOUR) {
2042 return;
2043 }
2044
2045 mLastRecordedTimestampVerifierN = mTimestampVerifier.getN();
2046 mLastRecordedTimeNs = timeNs;
2047
Ray Essickf27e9872019-12-07 06:28:46 -08002048 std::unique_ptr<mediametrics::Item> item(mediametrics::Item::create("audiothread"));
Andy Hungd0979812019-02-21 15:51:44 -08002049
2050#define MM_PREFIX "android.media.audiothread." // avoid cut-n-paste errors.
2051
2052 // thread configuration
2053 item->setInt32(MM_PREFIX "id", (int32_t)mId); // IO handle
2054 // item->setInt32(MM_PREFIX "portId", (int32_t)mPortId);
2055 item->setCString(MM_PREFIX "type", threadTypeToString(mType));
2056 item->setInt32(MM_PREFIX "sampleRate", (int32_t)mSampleRate);
2057 item->setInt64(MM_PREFIX "channelMask", (int64_t)mChannelMask);
2058 item->setCString(MM_PREFIX "encoding", toString(mFormat).c_str());
2059 item->setInt32(MM_PREFIX "frameCount", (int32_t)mFrameCount);
Andy Hungab65b182023-09-06 19:41:47 -07002060 item->setCString(MM_PREFIX "outDevice", toString(outDeviceTypes_l()).c_str());
2061 item->setCString(MM_PREFIX "inDevice", toString(inDeviceType_l()).c_str());
Andy Hungd0979812019-02-21 15:51:44 -08002062
2063 // thread statistics
2064 if (mIoJitterMs.getN() > 0) {
2065 item->setDouble(MM_PREFIX "ioJitterMs.mean", mIoJitterMs.getMean());
2066 item->setDouble(MM_PREFIX "ioJitterMs.std", mIoJitterMs.getStdDev());
2067 }
2068 if (mProcessTimeMs.getN() > 0) {
2069 item->setDouble(MM_PREFIX "processTimeMs.mean", mProcessTimeMs.getMean());
2070 item->setDouble(MM_PREFIX "processTimeMs.std", mProcessTimeMs.getStdDev());
2071 }
2072 const auto tsjitter = mTimestampVerifier.getJitterMs();
2073 if (tsjitter.getN() > 0) {
2074 item->setDouble(MM_PREFIX "timestampJitterMs.mean", tsjitter.getMean());
2075 item->setDouble(MM_PREFIX "timestampJitterMs.std", tsjitter.getStdDev());
2076 }
2077 if (mLatencyMs.getN() > 0) {
2078 item->setDouble(MM_PREFIX "latencyMs.mean", mLatencyMs.getMean());
2079 item->setDouble(MM_PREFIX "latencyMs.std", mLatencyMs.getStdDev());
2080 }
Robert Wu06db0a32021-08-10 19:05:34 +00002081 if (mMonopipePipeDepthStats.getN() > 0) {
2082 item->setDouble(MM_PREFIX "monopipePipeDepthStats.mean",
2083 mMonopipePipeDepthStats.getMean());
2084 item->setDouble(MM_PREFIX "monopipePipeDepthStats.std",
2085 mMonopipePipeDepthStats.getStdDev());
2086 }
Andy Hungd0979812019-02-21 15:51:44 -08002087
2088 item->selfrecord();
2089}
2090
Andy Hungee58e4a2023-07-07 13:47:37 -07002091product_strategy_t ThreadBase::getStrategyForStream(audio_stream_type_t stream) const
Eric Laurentd66d7a12021-07-13 13:35:32 +02002092{
Andy Hung583043b2023-07-17 17:05:00 -07002093 if (!mAfThreadCallback->isAudioPolicyReady()) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02002094 return PRODUCT_STRATEGY_NONE;
2095 }
2096 return AudioSystem::getStrategyForStream(stream);
2097}
2098
Andy Hungc5007f82023-08-29 14:26:09 -07002099// startMelComputation_l() must be called with AudioFlinger::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07002100void ThreadBase::startMelComputation_l(
Vlad Popa6fbbfbf2023-02-22 15:05:43 +01002101 const sp<audio_utils::MelProcessor>& /*processor*/)
2102{
2103 // Do nothing
2104 ALOGW("%s: ThreadBase does not support CSD", __func__);
2105}
2106
Andy Hungc5007f82023-08-29 14:26:09 -07002107// stopMelComputation_l() must be called with AudioFlinger::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07002108void ThreadBase::stopMelComputation_l()
Vlad Popa6fbbfbf2023-02-22 15:05:43 +01002109{
2110 // Do nothing
2111 ALOGW("%s: ThreadBase does not support CSD", __func__);
2112}
2113
Eric Laurent81784c32012-11-19 14:55:58 -08002114// ----------------------------------------------------------------------------
2115// Playback
2116// ----------------------------------------------------------------------------
2117
Andy Hung583043b2023-07-17 17:05:00 -07002118PlaybackThread::PlaybackThread(const sp<IAfThreadCallback>& afThreadCallback,
Eric Laurent81784c32012-11-19 14:55:58 -08002119 AudioStreamOut* output,
2120 audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -07002121 type_t type,
Eric Laurentf1f22e72021-07-13 14:04:14 +02002122 bool systemReady,
2123 audio_config_base_t *mixerConfig)
Andy Hung583043b2023-07-17 17:05:00 -07002124 : ThreadBase(afThreadCallback, id, type, systemReady, true /* isOut */),
Andy Hung2098f272014-02-27 14:00:06 -08002125 mNormalFrameCount(0), mSinkBuffer(NULL),
Andy Hung81994d62023-07-20 21:44:14 -07002126 mMixerBufferEnabled(kEnableExtendedPrecision || type == SPATIALIZER),
Andy Hung69aed5f2014-02-25 17:24:40 -08002127 mMixerBuffer(NULL),
2128 mMixerBufferSize(0),
2129 mMixerBufferFormat(AUDIO_FORMAT_INVALID),
2130 mMixerBufferValid(false),
Andy Hung81994d62023-07-20 21:44:14 -07002131 mEffectBufferEnabled(kEnableExtendedPrecision || type == SPATIALIZER),
Andy Hung98ef9782014-03-04 14:46:50 -08002132 mEffectBuffer(NULL),
2133 mEffectBufferSize(0),
2134 mEffectBufferFormat(AUDIO_FORMAT_INVALID),
2135 mEffectBufferValid(false),
Glenn Kastenc1fac192013-08-06 07:41:36 -07002136 mSuspended(0), mBytesWritten(0),
Andy Hungc54b1ff2016-02-23 14:07:07 -08002137 mFramesWritten(0),
Andy Hung238fa3d2016-07-28 10:53:22 -07002138 mSuspendedFrames(0),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002139 mActiveTracks(&this->mLocalLog),
Eric Laurent81784c32012-11-19 14:55:58 -08002140 // mStreamTypes[] initialized in constructor body
Andy Hung1bc088a2018-02-09 15:57:31 -08002141 mTracks(type == MIXER),
Eric Laurent81784c32012-11-19 14:55:58 -08002142 mOutput(output),
Andy Hung446f4df2019-02-21 12:26:41 -08002143 mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
Eric Laurent81784c32012-11-19 14:55:58 -08002144 mMixerStatus(MIXER_IDLE),
2145 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
Andy Hung8fe87eb2023-07-20 21:31:38 -07002146 mStandbyDelayNs(getStandbyTimeInNanos()),
Eric Laurentbfb1b832013-01-07 09:53:42 -08002147 mBytesRemaining(0),
2148 mCurrentWriteLength(0),
2149 mUseAsyncWrite(false),
Eric Laurent3b4529e2013-09-05 18:09:19 -07002150 mWriteAckSequence(0),
2151 mDrainSequence(0),
Andy Hung1d2d2aea2023-07-19 16:22:58 -07002152 mScreenState(mAfThreadCallback->getScreenState()),
Eric Laurent81784c32012-11-19 14:55:58 -08002153 // index 0 is reserved for normal mixer's submix
Glenn Kastendc2c50b2016-04-21 08:13:14 -07002154 mFastTrackAvailMask(((1 << FastMixerState::sMaxFastTracks) - 1) & ~1),
Eric Laurent7c29ec92017-09-20 17:54:22 -07002155 mHwSupportsPause(false), mHwPaused(false), mFlushPending(false),
Eric Laurent74c38dc2020-12-23 18:19:44 +01002156 mLeftVolFloat(-1.0), mRightVolFloat(-1.0),
Brian Lindahl65e90012022-07-27 18:01:07 +02002157 mDownStreamPatch{},
Eric Laurentb0463942022-12-20 16:31:10 +01002158 mIsTimestampAdvancing(kMinimumTimeBetweenTimestampChecksNs)
Eric Laurent81784c32012-11-19 14:55:58 -08002159{
Glenn Kastend7dca052015-03-05 16:05:54 -08002160 snprintf(mThreadName, kThreadNameLength, "AudioOut_%X", id);
Andy Hung583043b2023-07-17 17:05:00 -07002161 mNBLogWriter = afThreadCallback->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08002162
Andy Hungc5007f82023-08-29 14:26:09 -07002163 // Assumes constructor is called by AudioFlinger with its mutex() held, but
Eric Laurent81784c32012-11-19 14:55:58 -08002164 // it would be safer to explicitly pass initial masterVolume/masterMute as
2165 // parameter.
2166 //
2167 // If the HAL we are using has support for master volume or master mute,
2168 // then do not attenuate or mute during mixing (just leave the volume at 1.0
2169 // and the mute set to false).
Andy Hung583043b2023-07-17 17:05:00 -07002170 mMasterVolume = afThreadCallback->masterVolume_l();
2171 mMasterMute = afThreadCallback->masterMute_l();
George Burgess IV5e4d86f2020-02-18 12:55:36 -08002172 if (mOutput->audioHwDev) {
Eric Laurent81784c32012-11-19 14:55:58 -08002173 if (mOutput->audioHwDev->canSetMasterVolume()) {
2174 mMasterVolume = 1.0;
2175 }
2176
2177 if (mOutput->audioHwDev->canSetMasterMute()) {
2178 mMasterMute = false;
2179 }
Andy Hungc8fddf32018-08-08 18:32:37 -07002180 mIsMsdDevice = strcmp(
2181 mOutput->audioHwDev->moduleName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002182 }
2183
Eric Laurentf1f22e72021-07-13 14:04:14 +02002184 if (mixerConfig != nullptr && mixerConfig->channel_mask != AUDIO_CHANNEL_NONE) {
2185 mMixerChannelMask = mixerConfig->channel_mask;
2186 }
2187
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002188 readOutputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002189
Eric Laurent1c5e2e32021-08-18 18:50:28 +02002190 if (mType != SPATIALIZER
Eric Laurentb3f315a2021-07-13 15:09:05 +02002191 && mMixerChannelMask != mChannelMask) {
2192 LOG_ALWAYS_FATAL("HAL channel mask %#x does not match mixer channel mask %#x",
2193 mChannelMask, mMixerChannelMask);
2194 }
2195
Andy Hungc8fddf32018-08-08 18:32:37 -07002196 // TODO: We may also match on address as well as device type for
2197 // AUDIO_DEVICE_OUT_BUS, AUDIO_DEVICE_OUT_ALL_A2DP, AUDIO_DEVICE_OUT_REMOTE_SUBMIX
Dean Wheatleyf8726f02019-12-02 14:12:01 +11002198 if (type == MIXER || type == DIRECT || type == OFFLOAD) {
jiabinc52b1ff2019-10-31 17:20:42 -07002199 // TODO: This property should be ensure that only contains one single device type.
2200 mTimestampCorrectedDevice = (audio_devices_t)property_get_int64(
2201 "audio.timestamp.corrected_output_device",
Andy Hungc8fddf32018-08-08 18:32:37 -07002202 (int64_t)(mIsMsdDevice ? AUDIO_DEVICE_OUT_BUS // turn on by default for MSD
2203 : AUDIO_DEVICE_NONE));
2204 }
2205
Mikhail Naganovf33115d2020-09-25 23:03:05 +00002206 for (int i = AUDIO_STREAM_MIN; i < AUDIO_STREAM_FOR_POLICY_CNT; ++i) {
2207 const audio_stream_type_t stream{static_cast<audio_stream_type_t>(i)};
Eric Laurent98e38192018-02-15 18:31:53 -08002208 mStreamTypes[stream].volume = 0.0f;
Andy Hung583043b2023-07-17 17:05:00 -07002209 mStreamTypes[stream].mute = mAfThreadCallback->streamMute_l(stream);
Eric Laurent81784c32012-11-19 14:55:58 -08002210 }
Eric Laurent35f8c7c2020-02-08 11:42:35 -08002211 // Audio patch and call assistant volume are always max
Eric Laurent98e38192018-02-15 18:31:53 -08002212 mStreamTypes[AUDIO_STREAM_PATCH].volume = 1.0f;
2213 mStreamTypes[AUDIO_STREAM_PATCH].mute = false;
Eric Laurent35f8c7c2020-02-08 11:42:35 -08002214 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].volume = 1.0f;
2215 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].mute = false;
Eric Laurent81784c32012-11-19 14:55:58 -08002216}
2217
Andy Hungee58e4a2023-07-07 13:47:37 -07002218PlaybackThread::~PlaybackThread()
Eric Laurent81784c32012-11-19 14:55:58 -08002219{
Andy Hung583043b2023-07-17 17:05:00 -07002220 mAfThreadCallback->unregisterWriter(mNBLogWriter);
Andy Hung010a1a12014-03-13 13:57:33 -07002221 free(mSinkBuffer);
Andy Hung69aed5f2014-02-25 17:24:40 -08002222 free(mMixerBuffer);
Andy Hung98ef9782014-03-04 14:46:50 -08002223 free(mEffectBuffer);
Eric Laurentb62d0362021-10-26 17:40:18 +02002224 free(mPostSpatializerBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08002225}
2226
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002227// Thread virtuals
2228
Andy Hungee58e4a2023-07-07 13:47:37 -07002229void PlaybackThread::onFirstRef()
Eric Laurent81784c32012-11-19 14:55:58 -08002230{
Jasmine Chaeaa10e42021-05-11 10:11:14 +08002231 if (!isStreamInitialized()) {
jiabinf6eb4c32020-02-25 14:06:25 -08002232 ALOGE("The stream is not open yet"); // This should not happen.
2233 } else {
Mikhail Naganovaec565e2023-02-22 16:31:28 -08002234 // Callbacks take strong or weak pointers as a parameter.
2235 // Since PlaybackThread passes itself as a callback handler, it can only
2236 // be done outside of the constructor. Creating weak and especially strong
2237 // pointers to a refcounted object in its own constructor is strongly
2238 // discouraged, see comments in system/core/libutils/include/utils/RefBase.h.
2239 // Even if a function takes a weak pointer, it is possible that it will
2240 // need to convert it to a strong pointer down the line.
2241 if (mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING &&
2242 mOutput->stream->setCallback(this) == OK) {
2243 mUseAsyncWrite = true;
Andy Hungee58e4a2023-07-07 13:47:37 -07002244 mCallbackThread = sp<AsyncCallbackThread>::make(this);
Mikhail Naganovaec565e2023-02-22 16:31:28 -08002245 }
2246
jiabinf6eb4c32020-02-25 14:06:25 -08002247 if (mOutput->stream->setEventCallback(this) != OK) {
jiabinf1a36052020-08-19 14:33:31 -07002248 ALOGD("Failed to add event callback");
jiabinf6eb4c32020-02-25 14:06:25 -08002249 }
2250 }
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002251 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
Andy Hung44d648b2022-04-08 17:33:40 -07002252 mThreadSnapshot.setTid(getTid());
Eric Laurent81784c32012-11-19 14:55:58 -08002253}
2254
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002255// ThreadBase virtuals
Andy Hungee58e4a2023-07-07 13:47:37 -07002256void PlaybackThread::preExit()
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002257{
2258 ALOGV(" preExit()");
Ytai Ben-Tsvi7e0183f2022-02-04 10:49:54 -08002259 status_t result = mOutput->stream->exit();
2260 ALOGE_IF(result != OK, "Error when calling exit(): %d", result);
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002261}
2262
Andy Hungee58e4a2023-07-07 13:47:37 -07002263void PlaybackThread::dumpTracks_l(int fd, const Vector<String16>& /* args */)
Eric Laurent81784c32012-11-19 14:55:58 -08002264{
Eric Laurent81784c32012-11-19 14:55:58 -08002265 String8 result;
2266
Marco Nelissenb2208842014-02-07 14:00:50 -08002267 result.appendFormat(" Stream volumes in dB: ");
Eric Laurent81784c32012-11-19 14:55:58 -08002268 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
2269 const stream_type_t *st = &mStreamTypes[i];
2270 if (i > 0) {
2271 result.appendFormat(", ");
2272 }
2273 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
2274 if (st->mute) {
2275 result.append("M");
2276 }
2277 }
2278 result.append("\n");
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00002279 write(fd, result.c_str(), result.length());
Eric Laurent81784c32012-11-19 14:55:58 -08002280 result.clear();
2281
Eric Laurent81784c32012-11-19 14:55:58 -08002282 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
2283 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
Elliott Hughes87cebad2014-05-22 10:14:43 -07002284 dprintf(fd, " Normal mixer raw underrun counters: partial=%u empty=%u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08002285 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Marco Nelissenb2208842014-02-07 14:00:50 -08002286
2287 size_t numtracks = mTracks.size();
2288 size_t numactive = mActiveTracks.size();
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002289 dprintf(fd, " %zu Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08002290 size_t numactiveseen = 0;
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002291 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08002292 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002293 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002294 result.append(prefix);
Andy Hungf6ab58d2018-05-25 12:50:39 -07002295 mTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08002296 for (size_t i = 0; i < numtracks; ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07002297 sp<IAfTrack> track = mTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08002298 if (track != 0) {
2299 bool active = mActiveTracks.indexOf(track) >= 0;
2300 if (active) {
2301 numactiveseen++;
2302 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002303 result.append(prefix);
2304 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08002305 }
2306 }
2307 } else {
2308 result.append("\n");
2309 }
2310 if (numactiveseen != numactive) {
2311 // some tracks in the active list were not in the tracks list
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002312 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08002313 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002314 result.append(prefix);
Andy Hungf6ab58d2018-05-25 12:50:39 -07002315 mActiveTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08002316 for (size_t i = 0; i < numactive; ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07002317 sp<IAfTrack> track = mActiveTracks[i];
Andy Hungdae27702016-10-31 14:01:16 -07002318 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002319 result.append(prefix);
2320 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08002321 }
2322 }
2323 }
2324
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00002325 write(fd, result.c_str(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08002326}
2327
Andy Hungee58e4a2023-07-07 13:47:37 -07002328void PlaybackThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -08002329{
Andy Hung04cb8f72020-03-20 13:44:33 -07002330 dprintf(fd, " Master volume: %f\n", mMasterVolume);
Mikhail Naganovdfb411f2018-09-11 13:39:56 -07002331 dprintf(fd, " Master mute: %s\n", mMasterMute ? "on" : "off");
Eric Laurentf1f22e72021-07-13 14:04:14 +02002332 dprintf(fd, " Mixer channel Mask: %#x (%s)\n",
2333 mMixerChannelMask, channelMaskToString(mMixerChannelMask, true /* output */).c_str());
jiabin245cdd92018-12-07 17:55:15 -08002334 if (mHapticChannelMask != AUDIO_CHANNEL_NONE) {
2335 dprintf(fd, " Haptic channel mask: %#x (%s)\n", mHapticChannelMask,
2336 channelMaskToString(mHapticChannelMask, true /* output */).c_str());
2337 }
Elliott Hughes87cebad2014-05-22 10:14:43 -07002338 dprintf(fd, " Normal frame count: %zu\n", mNormalFrameCount);
Elliott Hughes87cebad2014-05-22 10:14:43 -07002339 dprintf(fd, " Total writes: %d\n", mNumWrites);
2340 dprintf(fd, " Delayed writes: %d\n", mNumDelayedWrites);
2341 dprintf(fd, " Blocked in write: %s\n", mInWrite ? "yes" : "no");
Andy Hung8d672e02023-09-15 18:19:28 -07002342 dprintf(fd, " Suspend count: %d\n", (int32_t)mSuspended);
Elliott Hughes87cebad2014-05-22 10:14:43 -07002343 dprintf(fd, " Fast track availMask=%#x\n", mFastTrackAvailMask);
Eric Laurent42537be2016-01-08 17:16:42 -08002344 dprintf(fd, " Standby delay ns=%lld\n", (long long)mStandbyDelayNs);
Glenn Kasten97b7b752014-09-28 13:04:24 -07002345 AudioStreamOut *output = mOutput;
2346 audio_output_flags_t flags = output != NULL ? output->flags : AUDIO_OUTPUT_FLAG_NONE;
Mikhail Naganov913d06c2016-11-01 12:49:22 -07002347 dprintf(fd, " AudioStreamOut: %p flags %#x (%s)\n",
Andy Hung9b181952019-02-25 14:53:36 -08002348 output, flags, toString(flags).c_str());
Andy Hungb54c8542016-09-21 12:55:15 -07002349 dprintf(fd, " Frames written: %lld\n", (long long)mFramesWritten);
2350 dprintf(fd, " Suspended frames: %lld\n", (long long)mSuspendedFrames);
2351 if (mPipeSink.get() != nullptr) {
2352 dprintf(fd, " PipeSink frames written: %lld\n", (long long)mPipeSink->framesWritten());
2353 }
2354 if (output != nullptr) {
2355 dprintf(fd, " Hal stream dump:\n");
Andy Hung61589a42021-06-16 09:37:53 -07002356 (void)output->stream->dump(fd, args);
Andy Hungb54c8542016-09-21 12:55:15 -07002357 }
Eric Laurent81784c32012-11-19 14:55:58 -08002358}
2359
Andy Hungc5007f82023-08-29 14:26:09 -07002360// PlaybackThread::createTrack_l() must be called with AudioFlinger::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07002361sp<IAfTrack> PlaybackThread::createTrack_l(
Andy Hung88035ac2023-06-27 17:05:02 -07002362 const sp<Client>& client,
Eric Laurent81784c32012-11-19 14:55:58 -08002363 audio_stream_type_t streamType,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07002364 const audio_attributes_t& attr,
Eric Laurent21da6472017-11-09 16:29:26 -08002365 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08002366 audio_format_t format,
2367 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08002368 size_t *pFrameCount,
Eric Laurent21da6472017-11-09 16:29:26 -08002369 size_t *pNotificationFrameCount,
2370 uint32_t notificationsPerBuffer,
2371 float speed,
Eric Laurent81784c32012-11-19 14:55:58 -08002372 const sp<IMemory>& sharedBuffer,
Glenn Kastend848eb42016-03-08 13:42:11 -08002373 audio_session_t sessionId,
Eric Laurent05067782016-06-01 18:27:28 -07002374 audio_output_flags_t *flags,
Eric Laurent09f1ed22019-04-24 17:45:17 -07002375 pid_t creatorPid,
Svet Ganov33761132021-05-13 22:51:08 +00002376 const AttributionSourceState& attributionSource,
Eric Laurent81784c32012-11-19 14:55:58 -08002377 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002378 status_t *status,
jiabinf6eb4c32020-02-25 14:06:25 -08002379 audio_port_handle_t portId,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02002380 const sp<media::IAudioTrackCallback>& callback,
jiabinc658e452022-10-21 20:52:21 +00002381 bool isSpatialized,
jiabin94ed47c2023-07-27 23:34:20 +00002382 bool isBitPerfect,
2383 audio_output_flags_t *afTrackFlags)
Eric Laurent81784c32012-11-19 14:55:58 -08002384{
Glenn Kasten74935e42013-12-19 08:56:45 -08002385 size_t frameCount = *pFrameCount;
Eric Laurent21da6472017-11-09 16:29:26 -08002386 size_t notificationFrameCount = *pNotificationFrameCount;
Andy Hung8d31fd22023-06-26 19:20:57 -07002387 sp<IAfTrack> track;
Eric Laurent81784c32012-11-19 14:55:58 -08002388 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07002389 audio_output_flags_t outputFlags = mOutput->flags;
Eric Laurent21da6472017-11-09 16:29:26 -08002390 audio_output_flags_t requestedFlags = *flags;
Eric Laurent9b11c022018-06-06 19:19:22 -07002391 uint32_t sampleRate;
2392
2393 if (sharedBuffer != 0 && checkIMemory(sharedBuffer) != NO_ERROR) {
2394 lStatus = BAD_VALUE;
2395 goto Exit;
2396 }
Eric Laurent21da6472017-11-09 16:29:26 -08002397
2398 if (*pSampleRate == 0) {
2399 *pSampleRate = mSampleRate;
2400 }
Eric Laurent9b11c022018-06-06 19:19:22 -07002401 sampleRate = *pSampleRate;
Eric Laurent05067782016-06-01 18:27:28 -07002402
2403 // special case for FAST flag considered OK if fast mixer is present
2404 if (hasFastMixer()) {
2405 outputFlags = (audio_output_flags_t)(outputFlags | AUDIO_OUTPUT_FLAG_FAST);
2406 }
2407
2408 // Check if requested flags are compatible with output stream flags
2409 if ((*flags & outputFlags) != *flags) {
2410 ALOGW("createTrack_l(): mismatch between requested flags (%08x) and output flags (%08x)",
2411 *flags, outputFlags);
2412 *flags = (audio_output_flags_t)(*flags & outputFlags);
2413 }
Eric Laurent81784c32012-11-19 14:55:58 -08002414
jiabinc658e452022-10-21 20:52:21 +00002415 if (isBitPerfect) {
Andy Hung8d672e02023-09-15 18:19:28 -07002416 audio_utils::lock_guard _l(mutex());
Andy Hung116bc262023-06-20 18:56:17 -07002417 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
jiabinc658e452022-10-21 20:52:21 +00002418 if (chain.get() != nullptr) {
2419 // Bit-perfect is required according to the configuration and preferred mixer
2420 // attributes, but it is not in the output flag from the client's request. Explicitly
2421 // adding bit-perfect flag to check the compatibility
2422 audio_output_flags_t flagsToCheck =
2423 (audio_output_flags_t)(*flags & AUDIO_OUTPUT_FLAG_BIT_PERFECT);
2424 chain->checkOutputFlagCompatibility(&flagsToCheck);
2425 if ((flagsToCheck & AUDIO_OUTPUT_FLAG_BIT_PERFECT) == AUDIO_OUTPUT_FLAG_NONE) {
2426 ALOGE("%s cannot create track as there is data-processing effect attached to "
2427 "given session id(%d)", __func__, sessionId);
2428 lStatus = BAD_VALUE;
2429 goto Exit;
2430 }
2431 *flags = flagsToCheck;
2432 }
2433 }
2434
Eric Laurent81784c32012-11-19 14:55:58 -08002435 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07002436 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
Eric Laurent81784c32012-11-19 14:55:58 -08002437 if (
Eric Laurent81784c32012-11-19 14:55:58 -08002438 // PCM data
2439 audio_is_linear_pcm(format) &&
Andy Hung1f439e12015-05-19 12:57:41 -07002440 // TODO: extract as a data library function that checks that a computationally
2441 // expensive downmixer is not required: isFastOutputChannelConversion()
jiabin245cdd92018-12-07 17:55:15 -08002442 (channelMask == (mChannelMask | mHapticChannelMask) ||
Andy Hung1f439e12015-05-19 12:57:41 -07002443 mChannelMask != AUDIO_CHANNEL_OUT_STEREO ||
2444 (channelMask == AUDIO_CHANNEL_OUT_MONO
2445 /* && mChannelMask == AUDIO_CHANNEL_OUT_STEREO */)) &&
Eric Laurent81784c32012-11-19 14:55:58 -08002446 // hardware sample rate
2447 (sampleRate == mSampleRate) &&
Eric Laurent81784c32012-11-19 14:55:58 -08002448 // normal mixer has an associated fast mixer
2449 hasFastMixer() &&
2450 // there are sufficient fast track slots available
2451 (mFastTrackAvailMask != 0)
2452 // FIXME test that MixerThread for this fast track has a capable output HAL
2453 // FIXME add a permission test also?
2454 ) {
Andy Hunge0a269a2016-03-23 15:13:42 -07002455 // static tracks can have any nonzero framecount, streaming tracks check against minimum.
2456 if (sharedBuffer == 0) {
Glenn Kasten03490092014-05-27 12:30:54 -07002457 // read the fast track multiplier property the first time it is needed
2458 int ok = pthread_once(&sFastTrackMultiplierOnce, sFastTrackMultiplierInit);
2459 if (ok != 0) {
2460 ALOGE("%s pthread_once failed: %d", __func__, ok);
2461 }
Andy Hunge0a269a2016-03-23 15:13:42 -07002462 frameCount = max(frameCount, mFrameCount * sFastTrackMultiplier); // incl framecount 0
Eric Laurent81784c32012-11-19 14:55:58 -08002463 }
Eric Laurent4c415062016-06-17 16:14:16 -07002464
2465 // check compatibility with audio effects.
Andy Hungc5007f82023-08-29 14:26:09 -07002466 { // scope for mutex()
Andy Hung972bec12023-08-31 16:13:39 -07002467 audio_utils::lock_guard _l(mutex());
Andy Hungd3bb0ad2016-10-11 17:16:43 -07002468 for (audio_session_t session : {
Eric Laurent3f75a5b2019-11-12 15:55:51 -08002469 AUDIO_SESSION_DEVICE,
Andy Hungd3bb0ad2016-10-11 17:16:43 -07002470 AUDIO_SESSION_OUTPUT_STAGE,
2471 AUDIO_SESSION_OUTPUT_MIX,
2472 sessionId,
2473 }) {
Andy Hung116bc262023-06-20 18:56:17 -07002474 sp<IAfEffectChain> chain = getEffectChain_l(session);
Andy Hungd3bb0ad2016-10-11 17:16:43 -07002475 if (chain.get() != nullptr) {
2476 audio_output_flags_t old = *flags;
2477 chain->checkOutputFlagCompatibility(flags);
2478 if (old != *flags) {
2479 ALOGV("AUDIO_OUTPUT_FLAGS denied by effect, session=%d old=%#x new=%#x",
2480 (int)session, (int)old, (int)*flags);
2481 }
Eric Laurent4c415062016-06-17 16:14:16 -07002482 }
2483 }
2484 }
Eric Laurent122f7e72016-06-29 11:53:29 -07002485 ALOGV_IF((*flags & AUDIO_OUTPUT_FLAG_FAST) != 0,
Eric Laurent4c415062016-06-17 16:14:16 -07002486 "AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
2487 frameCount, mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08002488 } else {
Robert Wu4c7bb7d2021-08-12 18:50:13 +00002489 ALOGD("AUDIO_OUTPUT_FLAG_FAST denied: sharedBuffer=%p frameCount=%zu "
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002490 "mFrameCount=%zu format=%#x mFormat=%#x isLinear=%d channelMask=%#x "
Andy Hung6146c082014-03-18 11:56:15 -07002491 "sampleRate=%u mSampleRate=%u "
Eric Laurent81784c32012-11-19 14:55:58 -08002492 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
Glenn Kastend79072e2016-01-06 08:41:20 -08002493 sharedBuffer.get(), frameCount, mFrameCount, format, mFormat,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07002494 audio_is_linear_pcm(format), channelMask, sampleRate,
2495 mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
Eric Laurent4c415062016-06-17 16:14:16 -07002496 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_FAST);
Andy Hung0e48d252015-01-26 11:43:15 -08002497 }
2498 }
Eric Laurent21da6472017-11-09 16:29:26 -08002499
2500 if (!audio_has_proportional_frames(format)) {
2501 if (sharedBuffer != 0) {
2502 // Same comment as below about ignoring frameCount parameter for set()
2503 frameCount = sharedBuffer->size();
2504 } else if (frameCount == 0) {
2505 frameCount = mNormalFrameCount;
2506 }
2507 if (notificationFrameCount != frameCount) {
2508 notificationFrameCount = frameCount;
2509 }
2510 } else if (sharedBuffer != 0) {
2511 // FIXME: Ensure client side memory buffers need
2512 // not have additional alignment beyond sample
2513 // (e.g. 16 bit stereo accessed as 32 bit frame).
2514 size_t alignment = audio_bytes_per_sample(format);
2515 if (alignment & 1) {
2516 // for AUDIO_FORMAT_PCM_24_BIT_PACKED (not exposed through Java).
2517 alignment = 1;
2518 }
2519 uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
2520 size_t frameSize = channelCount * audio_bytes_per_sample(format);
2521 if (channelCount > 1) {
2522 // More than 2 channels does not require stronger alignment than stereo
2523 alignment <<= 1;
2524 }
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07002525 if (((uintptr_t)sharedBuffer->unsecurePointer() & (alignment - 1)) != 0) {
Eric Laurent21da6472017-11-09 16:29:26 -08002526 ALOGE("Invalid buffer alignment: address %p, channel count %u",
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07002527 sharedBuffer->unsecurePointer(), channelCount);
Eric Laurent21da6472017-11-09 16:29:26 -08002528 lStatus = BAD_VALUE;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002529 goto Exit;
2530 }
Eric Laurent21da6472017-11-09 16:29:26 -08002531
2532 // When initializing a shared buffer AudioTrack via constructors,
2533 // there's no frameCount parameter.
2534 // But when initializing a shared buffer AudioTrack via set(),
2535 // there _is_ a frameCount parameter. We silently ignore it.
2536 frameCount = sharedBuffer->size() / frameSize;
2537 } else {
2538 size_t minFrameCount = 0;
2539 // For fast tracks we try to respect the application's request for notifications per buffer.
2540 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
2541 if (notificationsPerBuffer > 0) {
2542 // Avoid possible arithmetic overflow during multiplication.
2543 if (notificationsPerBuffer > SIZE_MAX / mFrameCount) {
2544 ALOGE("Requested notificationPerBuffer=%u ignored for HAL frameCount=%zu",
2545 notificationsPerBuffer, mFrameCount);
2546 } else {
2547 minFrameCount = mFrameCount * notificationsPerBuffer;
2548 }
2549 }
2550 } else {
2551 // For normal PCM streaming tracks, update minimum frame count.
2552 // Buffer depth is forced to be at least 2 x the normal mixer frame count and
2553 // cover audio hardware latency.
2554 // This is probably too conservative, but legacy application code may depend on it.
2555 // If you change this calculation, also review the start threshold which is related.
2556 uint32_t latencyMs = latency_l();
2557 if (latencyMs == 0) {
2558 ALOGE("Error when retrieving output stream latency");
2559 lStatus = UNKNOWN_ERROR;
2560 goto Exit;
2561 }
2562
2563 minFrameCount = AudioSystem::calculateMinFrameCount(latencyMs, mNormalFrameCount,
2564 mSampleRate, sampleRate, speed /*, 0 mNotificationsPerBufferReq*/);
2565
Eric Laurent81784c32012-11-19 14:55:58 -08002566 }
Eric Laurent21da6472017-11-09 16:29:26 -08002567 if (frameCount < minFrameCount) {
Eric Laurent81784c32012-11-19 14:55:58 -08002568 frameCount = minFrameCount;
2569 }
Eric Laurent81784c32012-11-19 14:55:58 -08002570 }
Eric Laurent21da6472017-11-09 16:29:26 -08002571
2572 // Make sure that application is notified with sufficient margin before underrun.
2573 // The client can divide the AudioTrack buffer into sub-buffers,
2574 // and expresses its desire to server as the notification frame count.
2575 if (sharedBuffer == 0 && audio_is_linear_pcm(format)) {
2576 size_t maxNotificationFrames;
2577 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
2578 // notify every HAL buffer, regardless of the size of the track buffer
2579 maxNotificationFrames = mFrameCount;
2580 } else {
Andy Hungfa117802019-04-12 13:50:39 -07002581 // Triple buffer the notification period for a triple buffered mixer period;
2582 // otherwise, double buffering for the notification period is fine.
2583 //
2584 // TODO: This should be moved to AudioTrack to modify the notification period
2585 // on AudioTrack::setBufferSizeInFrames() changes.
2586 const int nBuffering =
2587 (uint64_t{frameCount} * mSampleRate)
2588 / (uint64_t{mNormalFrameCount} * sampleRate) == 3 ? 3 : 2;
2589
Eric Laurent21da6472017-11-09 16:29:26 -08002590 maxNotificationFrames = frameCount / nBuffering;
2591 // If client requested a fast track but this was denied, then use the smaller maximum.
2592 if (requestedFlags & AUDIO_OUTPUT_FLAG_FAST) {
2593 size_t maxNotificationFramesFastDenied = FMS_20 * sampleRate / 1000;
2594 if (maxNotificationFrames > maxNotificationFramesFastDenied) {
2595 maxNotificationFrames = maxNotificationFramesFastDenied;
2596 }
2597 }
2598 }
2599 if (notificationFrameCount == 0 || notificationFrameCount > maxNotificationFrames) {
2600 if (notificationFrameCount == 0) {
2601 ALOGD("Client defaulted notificationFrames to %zu for frameCount %zu",
2602 maxNotificationFrames, frameCount);
2603 } else {
2604 ALOGW("Client adjusted notificationFrames from %zu to %zu for frameCount %zu",
2605 notificationFrameCount, maxNotificationFrames, frameCount);
2606 }
2607 notificationFrameCount = maxNotificationFrames;
2608 }
2609 }
2610
Glenn Kasten74935e42013-12-19 08:56:45 -08002611 *pFrameCount = frameCount;
Eric Laurent21da6472017-11-09 16:29:26 -08002612 *pNotificationFrameCount = notificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08002613
Glenn Kastenc3df8382014-03-13 15:05:25 -07002614 switch (mType) {
jiabinc658e452022-10-21 20:52:21 +00002615 case BIT_PERFECT:
2616 if (isBitPerfect) {
2617 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
2618 ALOGE("%s, bad parameter when request streaming bit-perfect, sampleRate=%u, "
2619 "format=%#x, channelMask=%#x, mSampleRate=%u, mFormat=%#x, mChannelMask=%#x",
2620 __func__, sampleRate, format, channelMask, mSampleRate, mFormat,
2621 mChannelMask);
2622 lStatus = BAD_VALUE;
2623 goto Exit;
2624 }
2625 }
2626 break;
Glenn Kastenc3df8382014-03-13 15:05:25 -07002627
2628 case DIRECT:
Phil Burkfdb3c072016-02-09 10:47:02 -08002629 if (audio_is_linear_pcm(format)) { // TODO maybe use audio_has_proportional_frames()?
Eric Laurent81784c32012-11-19 14:55:58 -08002630 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002631 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
2632 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08002633 sampleRate, format, channelMask, mOutput, mFormat);
2634 lStatus = BAD_VALUE;
2635 goto Exit;
2636 }
2637 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002638 break;
2639
2640 case OFFLOAD:
Eric Laurentbfb1b832013-01-07 09:53:42 -08002641 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002642 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
2643 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002644 sampleRate, format, channelMask, mOutput, mFormat);
2645 lStatus = BAD_VALUE;
2646 goto Exit;
2647 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002648 break;
2649
2650 default:
Glenn Kasten993fa062014-05-02 11:14:34 -07002651 if (!audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002652 ALOGE("createTrack_l() Bad parameter: format %#x \""
2653 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002654 format, mOutput, mFormat);
2655 lStatus = BAD_VALUE;
2656 goto Exit;
2657 }
Andy Hungcd044842014-08-07 11:04:34 -07002658 if (sampleRate > mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Eric Laurent81784c32012-11-19 14:55:58 -08002659 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
2660 lStatus = BAD_VALUE;
2661 goto Exit;
2662 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002663 break;
2664
Eric Laurent81784c32012-11-19 14:55:58 -08002665 }
2666
2667 lStatus = initCheck();
2668 if (lStatus != NO_ERROR) {
Glenn Kasten15e57982013-09-24 11:52:37 -07002669 ALOGE("createTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08002670 goto Exit;
2671 }
2672
Andy Hungc5007f82023-08-29 14:26:09 -07002673 { // scope for mutex()
Andy Hung972bec12023-08-31 16:13:39 -07002674 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002675
2676 // all tracks in same audio session must share the same routing strategy otherwise
2677 // conflicts will happen when tracks are moved from one output to another by audio policy
2678 // manager
Eric Laurentd66d7a12021-07-13 13:35:32 +02002679 product_strategy_t strategy = getStrategyForStream(streamType);
Eric Laurent81784c32012-11-19 14:55:58 -08002680 for (size_t i = 0; i < mTracks.size(); ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07002681 sp<IAfTrack> t = mTracks[i];
Eric Laurent83b88082014-06-20 18:31:16 -07002682 if (t != 0 && t->isExternalTrack()) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02002683 product_strategy_t actual = getStrategyForStream(t->streamType());
Eric Laurent81784c32012-11-19 14:55:58 -08002684 if (sessionId == t->sessionId() && strategy != actual) {
2685 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
2686 strategy, actual);
2687 lStatus = BAD_VALUE;
2688 goto Exit;
2689 }
2690 }
2691 }
2692
yucliuc9c49cd2020-07-13 16:25:21 -07002693 // Set DIRECT flag if current thread is DirectOutputThread. This can
2694 // happen when the playback is rerouted to direct output thread by
2695 // dynamic audio policy.
2696 // Do NOT report the flag changes back to client, since the client
2697 // doesn't explicitly request a direct flag.
2698 audio_output_flags_t trackFlags = *flags;
2699 if (mType == DIRECT) {
2700 trackFlags = static_cast<audio_output_flags_t>(trackFlags | AUDIO_OUTPUT_FLAG_DIRECT);
2701 }
jiabin94ed47c2023-07-27 23:34:20 +00002702 *afTrackFlags = trackFlags;
yucliuc9c49cd2020-07-13 16:25:21 -07002703
Andy Hung8d31fd22023-06-26 19:20:57 -07002704 track = IAfTrack::create(this, client, streamType, attr, sampleRate, format,
Andy Hung8fe68032017-06-05 16:17:51 -07002705 channelMask, frameCount,
2706 nullptr /* buffer */, (size_t)0 /* bufferSize */, sharedBuffer,
Svet Ganov33761132021-05-13 22:51:08 +00002707 sessionId, creatorPid, attributionSource, trackFlags,
Andy Hung8d31fd22023-06-26 19:20:57 -07002708 IAfTrackBase::TYPE_DEFAULT, portId, SIZE_MAX /*frameCountToBeReady*/,
jiabinc658e452022-10-21 20:52:21 +00002709 speed, isSpatialized, isBitPerfect);
Glenn Kasten03003332013-08-06 15:40:54 -07002710
Glenn Kasten03003332013-08-06 15:40:54 -07002711 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
2712 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08002713 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08002714 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08002715 goto Exit;
2716 }
2717 mTracks.add(track);
jiabinf6eb4c32020-02-25 14:06:25 -08002718 {
Andy Hung972bec12023-08-31 16:13:39 -07002719 audio_utils::lock_guard _atCbL(audioTrackCbMutex());
jiabinf6eb4c32020-02-25 14:06:25 -08002720 if (callback.get() != nullptr) {
jiabin18a4b1c2020-09-17 11:40:42 -07002721 mAudioTrackCallbacks.emplace(track, callback);
jiabinf6eb4c32020-02-25 14:06:25 -08002722 }
2723 }
Eric Laurent81784c32012-11-19 14:55:58 -08002724
Andy Hung116bc262023-06-20 18:56:17 -07002725 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08002726 if (chain != 0) {
2727 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
2728 track->setMainBuffer(chain->inBuffer());
Eric Laurentd66d7a12021-07-13 13:35:32 +02002729 chain->setStrategy(getStrategyForStream(track->streamType()));
Eric Laurent81784c32012-11-19 14:55:58 -08002730 chain->incTrackCnt();
2731 }
2732
Eric Laurent05067782016-06-01 18:27:28 -07002733 if ((*flags & AUDIO_OUTPUT_FLAG_FAST) && (tid != -1)) {
Eric Laurent81784c32012-11-19 14:55:58 -08002734 pid_t callingPid = IPCThreadState::self()->getCallingPid();
2735 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
2736 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07002737 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08002738 }
2739 }
2740
2741 lStatus = NO_ERROR;
2742
2743Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07002744 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08002745 return track;
2746}
2747
Andy Hung1bc088a2018-02-09 15:57:31 -08002748template<typename T>
Andy Hungee58e4a2023-07-07 13:47:37 -07002749ssize_t PlaybackThread::Tracks<T>::remove(const sp<T>& track)
Andy Hung1bc088a2018-02-09 15:57:31 -08002750{
Andy Hungc0691382018-09-12 18:01:57 -07002751 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08002752 const ssize_t index = mTracks.remove(track);
2753 if (index >= 0) {
Andy Hungc0691382018-09-12 18:01:57 -07002754 if (mSaveDeletedTrackIds) {
Andy Hung1bc088a2018-02-09 15:57:31 -08002755 // We can't directly access mAudioMixer since the caller may be outside of threadLoop.
Andy Hungc0691382018-09-12 18:01:57 -07002756 // Instead, we add to mDeletedTrackIds which is solely used for mAudioMixer update,
Andy Hung1bc088a2018-02-09 15:57:31 -08002757 // to be handled when MixerThread::prepareTracks_l() next changes mAudioMixer.
Andy Hungc0691382018-09-12 18:01:57 -07002758 mDeletedTrackIds.emplace(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08002759 }
Andy Hung1bc088a2018-02-09 15:57:31 -08002760 }
2761 return index;
2762}
2763
Andy Hungee58e4a2023-07-07 13:47:37 -07002764uint32_t PlaybackThread::correctLatency_l(uint32_t latency) const
Eric Laurent81784c32012-11-19 14:55:58 -08002765{
2766 return latency;
2767}
2768
Andy Hungee58e4a2023-07-07 13:47:37 -07002769uint32_t PlaybackThread::latency() const
Eric Laurent81784c32012-11-19 14:55:58 -08002770{
Andy Hung972bec12023-08-31 16:13:39 -07002771 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002772 return latency_l();
2773}
Andy Hungee58e4a2023-07-07 13:47:37 -07002774uint32_t PlaybackThread::latency_l() const
Andy Hungab65b182023-09-06 19:41:47 -07002775NO_THREAD_SAFETY_ANALYSIS
2776// Fix later.
Eric Laurent81784c32012-11-19 14:55:58 -08002777{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002778 uint32_t latency;
2779 if (initCheck() == NO_ERROR && mOutput->stream->getLatency(&latency) == OK) {
2780 return correctLatency_l(latency);
Eric Laurent81784c32012-11-19 14:55:58 -08002781 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002782 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002783}
2784
Andy Hungee58e4a2023-07-07 13:47:37 -07002785void PlaybackThread::setMasterVolume(float value)
Eric Laurent81784c32012-11-19 14:55:58 -08002786{
Andy Hung972bec12023-08-31 16:13:39 -07002787 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002788 // Don't apply master volume in SW if our HAL can do it for us.
2789 if (mOutput && mOutput->audioHwDev &&
2790 mOutput->audioHwDev->canSetMasterVolume()) {
2791 mMasterVolume = 1.0;
2792 } else {
2793 mMasterVolume = value;
2794 }
2795}
2796
Andy Hungee58e4a2023-07-07 13:47:37 -07002797void PlaybackThread::setMasterBalance(float balance)
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01002798{
2799 mMasterBalance.store(balance);
2800}
2801
Andy Hungee58e4a2023-07-07 13:47:37 -07002802void PlaybackThread::setMasterMute(bool muted)
Eric Laurent81784c32012-11-19 14:55:58 -08002803{
Eric Laurent6acd1d42017-01-04 14:23:29 -08002804 if (isDuplicating()) {
2805 return;
2806 }
Andy Hung972bec12023-08-31 16:13:39 -07002807 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002808 // Don't apply master mute in SW if our HAL can do it for us.
2809 if (mOutput && mOutput->audioHwDev &&
2810 mOutput->audioHwDev->canSetMasterMute()) {
2811 mMasterMute = false;
2812 } else {
2813 mMasterMute = muted;
2814 }
2815}
2816
Andy Hungee58e4a2023-07-07 13:47:37 -07002817void PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
Eric Laurent81784c32012-11-19 14:55:58 -08002818{
Andy Hung972bec12023-08-31 16:13:39 -07002819 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002820 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002821 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002822}
2823
Andy Hungee58e4a2023-07-07 13:47:37 -07002824void PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
Eric Laurent81784c32012-11-19 14:55:58 -08002825{
Andy Hung972bec12023-08-31 16:13:39 -07002826 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002827 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002828 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002829}
2830
Andy Hungee58e4a2023-07-07 13:47:37 -07002831float PlaybackThread::streamVolume(audio_stream_type_t stream) const
Eric Laurent81784c32012-11-19 14:55:58 -08002832{
Andy Hung972bec12023-08-31 16:13:39 -07002833 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002834 return mStreamTypes[stream].volume;
2835}
2836
Andy Hungee58e4a2023-07-07 13:47:37 -07002837void PlaybackThread::setVolumeForOutput_l(float left, float right) const
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09002838{
2839 mOutput->stream->setVolume(left, right);
2840}
2841
Andy Hungc5007f82023-08-29 14:26:09 -07002842// addTrack_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07002843status_t PlaybackThread::addTrack_l(const sp<IAfTrack>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002844{
2845 status_t status = ALREADY_EXISTS;
2846
Eric Laurent81784c32012-11-19 14:55:58 -08002847 if (mActiveTracks.indexOf(track) < 0) {
2848 // the track is newly added, make sure it fills up all its
2849 // buffers before playing. This is to ensure the client will
2850 // effectively get the latency it requested.
Eric Laurent83b88082014-06-20 18:31:16 -07002851 if (track->isExternalTrack()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07002852 IAfTrackBase::track_state state = track->state();
Andy Hungc5007f82023-08-29 14:26:09 -07002853 mutex().unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002854 status = AudioSystem::startOutput(track->portId());
Andy Hungc5007f82023-08-29 14:26:09 -07002855 mutex().lock();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002856 // abort track was stopped/paused while we released the lock
Andy Hung8d31fd22023-06-26 19:20:57 -07002857 if (state != track->state()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002858 if (status == NO_ERROR) {
Andy Hungc5007f82023-08-29 14:26:09 -07002859 mutex().unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002860 AudioSystem::stopOutput(track->portId());
Andy Hungc5007f82023-08-29 14:26:09 -07002861 mutex().lock();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002862 }
2863 return INVALID_OPERATION;
2864 }
2865 // abort if start is rejected by audio policy manager
2866 if (status != NO_ERROR) {
jiabina84c3d32022-12-02 18:59:55 +00002867 // Do not replace the error if it is DEAD_OBJECT. When this happens, it indicates
2868 // current playback thread is reopened, which may happen when clients set preferred
2869 // mixer configuration. Returning DEAD_OBJECT will make the client restore track
2870 // immediately.
2871 return status == DEAD_OBJECT ? status : PERMISSION_DENIED;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002872 }
2873#ifdef ADD_BATTERY_DATA
2874 // to track the speaker usage
2875 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
2876#endif
Eric Laurent09f1ed22019-04-24 17:45:17 -07002877 sendIoConfigEvent_l(AUDIO_CLIENT_STARTED, track->creatorPid(), track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002878 }
2879
Eric Laurent51716182016-02-29 18:00:56 -08002880 // set retry count for buffer fill
2881 if (track->isOffloaded()) {
Eric Laurente93cc032016-05-05 10:15:10 -07002882 if (track->isStopping_1()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07002883 track->retryCount() = kMaxTrackStopRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07002884 } else {
Andy Hung8d31fd22023-06-26 19:20:57 -07002885 track->retryCount() = kMaxTrackStartupRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07002886 }
Andy Hung8d31fd22023-06-26 19:20:57 -07002887 track->fillingStatus() = mStandby ? IAfTrack::FS_FILLING : IAfTrack::FS_FILLED;
Eric Laurent51716182016-02-29 18:00:56 -08002888 } else {
Andy Hung8d31fd22023-06-26 19:20:57 -07002889 track->retryCount() = kMaxTrackStartupRetries;
2890 track->fillingStatus() =
2891 track->sharedBuffer() != 0 ? IAfTrack::FS_FILLED : IAfTrack::FS_FILLING;
Eric Laurent51716182016-02-29 18:00:56 -08002892 }
2893
Andy Hung116bc262023-06-20 18:56:17 -07002894 sp<IAfEffectChain> chain = getEffectChain_l(track->sessionId());
jiabineb3bda02020-06-30 14:07:03 -07002895 if (mHapticChannelMask != AUDIO_CHANNEL_NONE
2896 && ((track->channelMask() & AUDIO_CHANNEL_HAPTIC_ALL) != AUDIO_CHANNEL_NONE
2897 || (chain != nullptr && chain->containsHapticGeneratingEffect_l()))) {
jiabin57303cc2018-12-18 15:45:57 -08002898 // Unlock due to VibratorService will lock for this call and will
2899 // call Tracks.mute/unmute which also require thread's lock.
Andy Hungc5007f82023-08-29 14:26:09 -07002900 mutex().unlock();
Andy Hung7fb97e12023-07-20 21:23:42 -07002901 const os::HapticScale intensity = afutils::onExternalVibrationStart(
jiabin57303cc2018-12-18 15:45:57 -08002902 track->getExternalVibration());
Lais Andradebc3f37a2021-07-02 00:13:19 +01002903 std::optional<media::AudioVibratorInfo> vibratorInfo;
2904 {
2905 // TODO(b/184194780): Use the vibrator information from the vibrator that will be
2906 // used to play this track.
Andy Hung972bec12023-08-31 16:13:39 -07002907 audio_utils::lock_guard _l(mAfThreadCallback->mutex());
Andy Hung583043b2023-07-17 17:05:00 -07002908 vibratorInfo = std::move(mAfThreadCallback->getDefaultVibratorInfo_l());
Lais Andradebc3f37a2021-07-02 00:13:19 +01002909 }
Andy Hungc5007f82023-08-29 14:26:09 -07002910 mutex().lock();
Simon Bowden62823412022-10-17 14:52:26 +00002911 track->setHapticIntensity(intensity);
Lais Andradebc3f37a2021-07-02 00:13:19 +01002912 if (vibratorInfo) {
2913 track->setHapticMaxAmplitude(vibratorInfo->maxAmplitude);
2914 }
2915
jiabin57303cc2018-12-18 15:45:57 -08002916 // Haptic playback should be enabled by vibrator service.
2917 if (track->getHapticPlaybackEnabled()) {
2918 // Disable haptic playback of all active track to ensure only
2919 // one track playing haptic if current track should play haptic.
2920 for (const auto &t : mActiveTracks) {
2921 t->setHapticPlaybackEnabled(false);
2922 }
jiabin245cdd92018-12-07 17:55:15 -08002923 }
jiabine70bc7f2020-06-30 22:07:55 -07002924
2925 // Set haptic intensity for effect
2926 if (chain != nullptr) {
2927 chain->setHapticIntensity_l(track->id(), intensity);
2928 }
jiabin245cdd92018-12-07 17:55:15 -08002929 }
2930
Andy Hung8d31fd22023-06-26 19:20:57 -07002931 track->setResetDone(false);
Andy Hung59de4262021-06-14 10:53:54 -07002932 track->resetPresentationComplete();
Eric Laurent81784c32012-11-19 14:55:58 -08002933 mActiveTracks.add(track);
Eric Laurentd0107bc2013-06-11 14:38:48 -07002934 if (chain != 0) {
2935 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
2936 track->sessionId());
2937 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08002938 }
2939
Andy Hungc2b11cb2020-04-22 09:04:01 -07002940 track->logBeginInterval(patchSinksToString(&mPatch)); // log to MediaMetrics
Eric Laurent81784c32012-11-19 14:55:58 -08002941 status = NO_ERROR;
2942 }
2943
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08002944 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002945 return status;
2946}
2947
Andy Hungee58e4a2023-07-07 13:47:37 -07002948bool PlaybackThread::destroyTrack_l(const sp<IAfTrack>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002949{
Eric Laurentbfb1b832013-01-07 09:53:42 -08002950 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08002951 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002952 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
Andy Hung8d31fd22023-06-26 19:20:57 -07002953 track->setState(IAfTrackBase::STOPPED);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002954 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08002955 removeTrack_l(track);
Eric Laurentab5cdba2014-06-09 17:22:27 -07002956 } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) {
Andy Hung916987e2023-03-20 19:08:16 -07002957 if (track->isPausePending()) {
2958 track->pauseAck();
2959 }
Andy Hung8d31fd22023-06-26 19:20:57 -07002960 track->setState(IAfTrackBase::STOPPING_1);
Eric Laurent81784c32012-11-19 14:55:58 -08002961 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002962
2963 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08002964}
2965
Andy Hungee58e4a2023-07-07 13:47:37 -07002966void PlaybackThread::removeTrack_l(const sp<IAfTrack>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002967{
2968 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Andy Hung2148bf02016-11-28 19:01:02 -08002969
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002970 String8 result;
2971 track->appendDump(result, false /* active */);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00002972 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.c_str());
Andy Hung2148bf02016-11-28 19:01:02 -08002973
Eric Laurent81784c32012-11-19 14:55:58 -08002974 mTracks.remove(track);
jiabin18a4b1c2020-09-17 11:40:42 -07002975 {
Andy Hung972bec12023-08-31 16:13:39 -07002976 audio_utils::lock_guard _atCbL(audioTrackCbMutex());
jiabin18a4b1c2020-09-17 11:40:42 -07002977 mAudioTrackCallbacks.erase(track);
2978 }
Eric Laurent81784c32012-11-19 14:55:58 -08002979 if (track->isFastTrack()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07002980 int index = track->fastIndex();
Glenn Kastendc2c50b2016-04-21 08:13:14 -07002981 ALOG_ASSERT(0 < index && index < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08002982 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
2983 mFastTrackAvailMask |= 1 << index;
2984 // redundant as track is about to be destroyed, for dumpsys only
Andy Hung8d31fd22023-06-26 19:20:57 -07002985 track->fastIndex() = -1;
Eric Laurent81784c32012-11-19 14:55:58 -08002986 }
Andy Hung116bc262023-06-20 18:56:17 -07002987 sp<IAfEffectChain> chain = getEffectChain_l(track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08002988 if (chain != 0) {
2989 chain->decTrackCnt();
2990 }
2991}
2992
Andy Hungee58e4a2023-07-07 13:47:37 -07002993String8 PlaybackThread::getParameters(const String8& keys)
Eric Laurent81784c32012-11-19 14:55:58 -08002994{
Andy Hung972bec12023-08-31 16:13:39 -07002995 audio_utils::lock_guard _l(mutex());
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002996 String8 out_s8;
2997 if (initCheck() == NO_ERROR && mOutput->stream->getParameters(keys, &out_s8) == OK) {
2998 return out_s8;
Eric Laurent81784c32012-11-19 14:55:58 -08002999 }
Andy Hung920f6572022-10-06 12:09:49 -07003000 return {};
Eric Laurent81784c32012-11-19 14:55:58 -08003001}
3002
Andy Hungee58e4a2023-07-07 13:47:37 -07003003status_t DirectOutputThread::selectPresentation(int presentationId, int programId) {
Andy Hung972bec12023-08-31 16:13:39 -07003004 audio_utils::lock_guard _l(mutex());
Jasmine Chaeaa10e42021-05-11 10:11:14 +08003005 if (!isStreamInitialized()) {
Mikhail Naganovac917ac2018-11-28 14:03:52 -08003006 return NO_INIT;
3007 }
3008 return mOutput->stream->selectPresentation(presentationId, programId);
3009}
3010
Andy Hungab65b182023-09-06 19:41:47 -07003011void PlaybackThread::ioConfigChanged_l(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -07003012 audio_port_handle_t portId) {
Eric Laurent73e26b62015-04-27 16:55:58 -07003013 ALOGV("PlaybackThread::ioConfigChanged, thread %p, event %d", this, event);
Mikhail Naganov88536df2021-07-26 17:30:29 -07003014 sp<AudioIoDescriptor> desc;
3015 const struct audio_patch patch = isMsdDevice() ? mDownStreamPatch : mPatch;
Eric Laurent81784c32012-11-19 14:55:58 -08003016 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07003017 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07003018 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07003019 case AUDIO_OUTPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07003020 desc = sp<AudioIoDescriptor>::make(mId, patch, false /*isInput*/,
3021 mSampleRate, mFormat, mChannelMask,
3022 // FIXME AudioFlinger::frameCount(audio_io_handle_t) instead of mNormalFrameCount?
3023 mNormalFrameCount, mFrameCount, latency_l());
Eric Laurent81784c32012-11-19 14:55:58 -08003024 break;
Eric Laurent09f1ed22019-04-24 17:45:17 -07003025 case AUDIO_CLIENT_STARTED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07003026 desc = sp<AudioIoDescriptor>::make(mId, patch, portId);
Eric Laurent09f1ed22019-04-24 17:45:17 -07003027 break;
Eric Laurent73e26b62015-04-27 16:55:58 -07003028 case AUDIO_OUTPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08003029 default:
Mikhail Naganov88536df2021-07-26 17:30:29 -07003030 desc = sp<AudioIoDescriptor>::make(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08003031 break;
3032 }
Andy Hungab65b182023-09-06 19:41:47 -07003033 mAfThreadCallback->ioConfigChanged_l(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08003034}
3035
Andy Hungee58e4a2023-07-07 13:47:37 -07003036void PlaybackThread::onWriteReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08003037{
Eric Laurent3b4529e2013-09-05 18:09:19 -07003038 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003039}
3040
Andy Hungee58e4a2023-07-07 13:47:37 -07003041void PlaybackThread::onDrainReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08003042{
Eric Laurent3b4529e2013-09-05 18:09:19 -07003043 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003044}
3045
Andy Hungee58e4a2023-07-07 13:47:37 -07003046void PlaybackThread::onError()
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07003047{
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07003048 mCallbackThread->setAsyncError();
3049}
3050
Andy Hungee58e4a2023-07-07 13:47:37 -07003051void PlaybackThread::onCodecFormatChanged(
jiabinf6eb4c32020-02-25 14:06:25 -08003052 const std::basic_string<uint8_t>& metadataBs)
3053{
Andy Hungee58e4a2023-07-07 13:47:37 -07003054 const auto weakPointerThis = wp<PlaybackThread>::fromExisting(this);
Kuowei Li9e2f6162022-11-23 16:25:26 +08003055 std::thread([this, metadataBs, weakPointerThis]() {
Andy Hungee58e4a2023-07-07 13:47:37 -07003056 const sp<PlaybackThread> playbackThread = weakPointerThis.promote();
Kuowei Li9e2f6162022-11-23 16:25:26 +08003057 if (playbackThread == nullptr) {
3058 ALOGW("PlaybackThread was destroyed, skip codec format change event");
3059 return;
3060 }
3061
jiabinf6eb4c32020-02-25 14:06:25 -08003062 audio_utils::metadata::Data metadata =
3063 audio_utils::metadata::dataFromByteString(metadataBs);
3064 if (metadata.empty()) {
3065 ALOGW("Can not transform the buffer to audio metadata, %s, %d",
3066 reinterpret_cast<char*>(const_cast<uint8_t*>(metadataBs.data())),
3067 (int)metadataBs.size());
3068 return;
3069 }
3070
3071 audio_utils::metadata::ByteString metaDataStr =
3072 audio_utils::metadata::byteStringFromData(metadata);
3073 std::vector metadataVec(metaDataStr.begin(), metaDataStr.end());
Andy Hung972bec12023-08-31 16:13:39 -07003074 audio_utils::lock_guard _l(audioTrackCbMutex());
jiabin18a4b1c2020-09-17 11:40:42 -07003075 for (const auto& callbackPair : mAudioTrackCallbacks) {
3076 callbackPair.second->onCodecFormatChanged(metadataVec);
jiabinf6eb4c32020-02-25 14:06:25 -08003077 }
3078 }).detach();
3079}
3080
Andy Hungee58e4a2023-07-07 13:47:37 -07003081void PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08003082{
Andy Hung972bec12023-08-31 16:13:39 -07003083 audio_utils::lock_guard _l(mutex());
Eric Laurent3b4529e2013-09-05 18:09:19 -07003084 // reject out of sequence requests
3085 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
3086 mWriteAckSequence &= ~1;
Andy Hungc5007f82023-08-29 14:26:09 -07003087 mWaitWorkCV.notify_one();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003088 }
3089}
3090
Andy Hungee58e4a2023-07-07 13:47:37 -07003091void PlaybackThread::resetDraining(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 ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
Andy Hungf3234512018-07-03 14:51:47 -07003096 // Register discontinuity when HW drain is completed because that can cause
3097 // the timestamp frame position to reset to 0 for direct and offload threads.
3098 // (Out of sequence requests are ignored, since the discontinuity would be handled
3099 // elsewhere, e.g. in flush).
Dean Wheatley12473e92021-03-18 23:00:55 +11003100 mTimestampVerifier.discontinuity(mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003101 mDrainSequence &= ~1;
Andy Hungc5007f82023-08-29 14:26:09 -07003102 mWaitWorkCV.notify_one();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003103 }
3104}
3105
Andy Hungee58e4a2023-07-07 13:47:37 -07003106void PlaybackThread::readOutputParameters_l()
Andy Hung972bec12023-08-31 16:13:39 -07003107NO_THREAD_SAFETY_ANALYSIS
3108// 'moveEffectChain_ll' requires holding mutex 'AudioFlinger_Mutex' exclusively
Eric Laurent81784c32012-11-19 14:55:58 -08003109{
Glenn Kastenadad3d72014-02-21 14:51:43 -08003110 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Mikhail Naganov560637e2021-03-31 22:40:13 +00003111 const audio_config_base_t audioConfig = mOutput->getAudioProperties();
3112 mSampleRate = audioConfig.sample_rate;
3113 mChannelMask = audioConfig.channel_mask;
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003114 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08003115 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003116 }
Andy Hung81994d62023-07-20 21:44:14 -07003117 if (hasMixer() && !isValidPcmSinkChannelMask(mChannelMask)) {
Andy Hung9a592762014-07-21 21:56:01 -07003118 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output",
3119 mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003120 }
Eric Laurentf1f22e72021-07-13 14:04:14 +02003121
3122 if (mMixerChannelMask == AUDIO_CHANNEL_NONE) {
3123 mMixerChannelMask = mChannelMask;
3124 }
3125
Andy Hunge5412692014-05-16 11:25:07 -07003126 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01003127 mBalance.setChannelMask(mChannelMask);
Phil Burkca5e6142015-07-14 09:42:29 -07003128
Eric Laurentf1f22e72021-07-13 14:04:14 +02003129 uint32_t mixerChannelCount = audio_channel_count_from_out_mask(mMixerChannelMask);
3130
Phil Burkca5e6142015-07-14 09:42:29 -07003131 // Get actual HAL format.
Mikhail Naganov560637e2021-03-31 22:40:13 +00003132 status_t result = mOutput->stream->getAudioProperties(nullptr, nullptr, &mHALFormat);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003133 LOG_ALWAYS_FATAL_IF(result != OK, "Error when retrieving output stream format: %d", result);
Phil Burkca5e6142015-07-14 09:42:29 -07003134 // Get format from the shim, which will be different than the HAL format
3135 // if playing compressed audio over HDMI passthrough.
Mikhail Naganov560637e2021-03-31 22:40:13 +00003136 mFormat = audioConfig.format;
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003137 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08003138 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003139 }
Andy Hung81994d62023-07-20 21:44:14 -07003140 if (hasMixer() && !isValidPcmSinkFormat(mFormat)) {
Andy Hung6146c082014-03-18 11:56:15 -07003141 LOG_FATAL("HAL format %#x not supported for mixed output",
3142 mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003143 }
Phil Burk062e67a2015-02-11 13:40:50 -08003144 mFrameSize = mOutput->getFrameSize();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003145 result = mOutput->stream->getBufferSize(&mBufferSize);
3146 LOG_ALWAYS_FATAL_IF(result != OK,
3147 "Error when retrieving output stream buffer size: %d", result);
Glenn Kasten70949c42013-08-06 07:40:12 -07003148 mFrameCount = mBufferSize / mFrameSize;
Eric Laurentb3f315a2021-07-13 15:09:05 +02003149 if (hasMixer() && (mFrameCount & 15)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003150 ALOGW("HAL output buffer size is %zu frames but AudioMixer requires multiples of 16 frames",
Eric Laurent81784c32012-11-19 14:55:58 -08003151 mFrameCount);
3152 }
3153
Eric Laurentd1f69b02014-12-15 14:33:13 -08003154 mHwSupportsPause = false;
3155 if (mOutput->flags & AUDIO_OUTPUT_FLAG_DIRECT) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003156 bool supportsPause = false, supportsResume = false;
3157 if (mOutput->stream->supportsPauseAndResume(&supportsPause, &supportsResume) == OK) {
3158 if (supportsPause && supportsResume) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08003159 mHwSupportsPause = true;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003160 } else if (supportsPause) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08003161 ALOGW("direct output implements pause but not resume");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003162 } else if (supportsResume) {
3163 ALOGW("direct output implements resume but not pause");
Eric Laurentd1f69b02014-12-15 14:33:13 -08003164 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08003165 }
3166 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07003167 if (!mHwSupportsPause && mOutput->flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) {
3168 LOG_ALWAYS_FATAL("HW_AV_SYNC requested but HAL does not implement pause and resume");
3169 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08003170
Andy Hungfbfc3952015-01-15 13:33:51 -08003171 if (mType == DUPLICATING && mMixerBufferEnabled && mEffectBufferEnabled) {
3172 // For best precision, we use float instead of the associated output
3173 // device format (typically PCM 16 bit).
3174
3175 mFormat = AUDIO_FORMAT_PCM_FLOAT;
3176 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
3177 mBufferSize = mFrameSize * mFrameCount;
3178
3179 // TODO: We currently use the associated output device channel mask and sample rate.
3180 // (1) Perhaps use the ORed channel mask of all downstream MixerThreads
3181 // (if a valid mask) to avoid premature downmix.
3182 // (2) Perhaps use the maximum sample rate of all downstream MixerThreads
3183 // instead of the output device sample rate to avoid loss of high frequency information.
3184 // This may need to be updated as MixerThread/OutputTracks are added and not here.
3185 }
3186
Andy Hung09a50072014-02-27 14:30:47 -08003187 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08003188 double multiplier = 1.0;
Andy Hungd3639922022-04-28 18:00:49 -07003189 // Note: mType == SPATIALIZER does not support FastMixer.
Eric Laurent81784c32012-11-19 14:55:58 -08003190 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
3191 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08003192 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
3193 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Haynes Mathew George227a14b2016-05-09 12:45:48 -07003194
Eric Laurent81784c32012-11-19 14:55:58 -08003195 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
3196 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
3197 maxNormalFrameCount = maxNormalFrameCount & ~15;
3198 if (maxNormalFrameCount < minNormalFrameCount) {
3199 maxNormalFrameCount = minNormalFrameCount;
3200 }
3201 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
3202 if (multiplier <= 1.0) {
3203 multiplier = 1.0;
3204 } else if (multiplier <= 2.0) {
3205 if (2 * mFrameCount <= maxNormalFrameCount) {
3206 multiplier = 2.0;
3207 } else {
3208 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
3209 }
3210 } else {
Haynes Mathew George227a14b2016-05-09 12:45:48 -07003211 multiplier = floor(multiplier);
Eric Laurent81784c32012-11-19 14:55:58 -08003212 }
3213 }
3214 mNormalFrameCount = multiplier * mFrameCount;
3215 // round up to nearest 16 frames to satisfy AudioMixer
Eric Laurentb3f315a2021-07-13 15:09:05 +02003216 if (hasMixer()) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07003217 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
3218 }
Andy Hungab65b182023-09-06 19:41:47 -07003219 ALOGI("HAL output buffer size %zu frames, normal sink buffer size %zu frames",
3220 (size_t)mFrameCount, mNormalFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08003221
Andy Hung08fb1742015-05-31 23:22:10 -07003222 // Check if we want to throttle the processing to no more than 2x normal rate
3223 mThreadThrottle = property_get_bool("af.thread.throttle", true /* default_value */);
Andy Hung40eb1a12015-06-18 13:42:02 -07003224 mThreadThrottleTimeMs = 0;
3225 mThreadThrottleEndMs = 0;
Andy Hung08fb1742015-05-31 23:22:10 -07003226 mHalfBufferMs = mNormalFrameCount * 1000 / (2 * mSampleRate);
3227
Andy Hung010a1a12014-03-13 13:57:33 -07003228 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
3229 // Originally this was int16_t[] array, need to remove legacy implications.
3230 free(mSinkBuffer);
3231 mSinkBuffer = NULL;
Eric Laurent39095982021-08-24 18:29:27 +02003232
Andy Hung5b10a202014-03-13 13:59:29 -07003233 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
3234 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
3235 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07003236 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08003237
Andy Hung69aed5f2014-02-25 17:24:40 -08003238 // We resize the mMixerBuffer according to the requirements of the sink buffer which
3239 // drives the output.
3240 free(mMixerBuffer);
3241 mMixerBuffer = NULL;
3242 if (mMixerBufferEnabled) {
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01003243 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // no longer valid: AUDIO_FORMAT_PCM_16_BIT.
Eric Laurentf1f22e72021-07-13 14:04:14 +02003244 mMixerBufferSize = mNormalFrameCount * mixerChannelCount
Andy Hung69aed5f2014-02-25 17:24:40 -08003245 * audio_bytes_per_sample(mMixerBufferFormat);
3246 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
3247 }
Andy Hung98ef9782014-03-04 14:46:50 -08003248 free(mEffectBuffer);
3249 mEffectBuffer = NULL;
3250 if (mEffectBufferEnabled) {
Andy Hung319587b2023-05-23 14:01:03 -07003251 mEffectBufferFormat = AUDIO_FORMAT_PCM_FLOAT;
Eric Laurentf1f22e72021-07-13 14:04:14 +02003252 mEffectBufferSize = mNormalFrameCount * mixerChannelCount
Andy Hung98ef9782014-03-04 14:46:50 -08003253 * audio_bytes_per_sample(mEffectBufferFormat);
3254 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
3255 }
Andy Hung69aed5f2014-02-25 17:24:40 -08003256
Eric Laurentb62d0362021-10-26 17:40:18 +02003257 if (mType == SPATIALIZER) {
3258 free(mPostSpatializerBuffer);
3259 mPostSpatializerBuffer = nullptr;
3260 mPostSpatializerBufferSize = mNormalFrameCount * mChannelCount
3261 * audio_bytes_per_sample(mEffectBufferFormat);
3262 (void)posix_memalign(&mPostSpatializerBuffer, 32, mPostSpatializerBufferSize);
3263 }
3264
Mikhail Naganov55773032020-10-01 15:08:13 -07003265 mHapticChannelMask = static_cast<audio_channel_mask_t>(mChannelMask & AUDIO_CHANNEL_HAPTIC_ALL);
3266 mChannelMask = static_cast<audio_channel_mask_t>(mChannelMask & ~mHapticChannelMask);
jiabin245cdd92018-12-07 17:55:15 -08003267 mHapticChannelCount = audio_channel_count_from_out_mask(mHapticChannelMask);
3268 mChannelCount -= mHapticChannelCount;
Eric Laurentf1f22e72021-07-13 14:04:14 +02003269 mMixerChannelMask = static_cast<audio_channel_mask_t>(mMixerChannelMask & ~mHapticChannelMask);
jiabin245cdd92018-12-07 17:55:15 -08003270
Eric Laurent81784c32012-11-19 14:55:58 -08003271 // force reconfiguration of effect chains and engines to take new buffer size and audio
3272 // parameters into account
Andy Hungc5007f82023-08-29 14:26:09 -07003273 // Note that mutex() is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08003274 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
3275 // matter.
Andy Hung972bec12023-08-31 16:13:39 -07003276 // create a copy of mEffectChains as calling moveEffectChain_ll()
3277 // can reorder some effect chains
Andy Hung116bc262023-06-20 18:56:17 -07003278 Vector<sp<IAfEffectChain>> effectChains = mEffectChains;
Eric Laurent81784c32012-11-19 14:55:58 -08003279 for (size_t i = 0; i < effectChains.size(); i ++) {
Andy Hung972bec12023-08-31 16:13:39 -07003280 mAfThreadCallback->moveEffectChain_ll(effectChains[i]->sessionId(),
Eric Laurent6c796322019-04-09 14:13:17 -07003281 this/* srcThread */, this/* dstThread */);
Eric Laurent81784c32012-11-19 14:55:58 -08003282 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08003283
George Burgess IV5e4d86f2020-02-18 12:55:36 -08003284 audio_output_flags_t flags = mOutput->flags;
Andy Hungcf10d742020-04-28 15:38:24 -07003285 mediametrics::LogItem item(mThreadMetrics.getMetricsId()); // TODO: method in ThreadMetrics?
Andy Hungb68f5eb2019-12-03 16:49:17 -08003286 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
Andy Hung25a80ac2023-07-19 12:47:35 -07003287 .set(AMEDIAMETRICS_PROP_ENCODING, IAfThreadBase::formatToString(mFormat).c_str())
Andy Hungb68f5eb2019-12-03 16:49:17 -08003288 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
3289 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
3290 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
3291 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mNormalFrameCount)
3292 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
3293 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELMASK,
3294 (int32_t)mHapticChannelMask)
3295 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELCOUNT,
3296 (int32_t)mHapticChannelCount)
3297 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_ENCODING,
Andy Hung25a80ac2023-07-19 12:47:35 -07003298 IAfThreadBase::formatToString(mHALFormat).c_str())
Andy Hungb68f5eb2019-12-03 16:49:17 -08003299 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_FRAMECOUNT,
3300 (int32_t)mFrameCount) // sic - added HAL
3301 ;
3302 uint32_t latencyMs;
3303 if (mOutput->stream->getLatency(&latencyMs) == NO_ERROR) {
3304 item.set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_LATENCYMS, (double)latencyMs);
3305 }
3306 item.record();
Eric Laurent81784c32012-11-19 14:55:58 -08003307}
3308
Andy Hungee58e4a2023-07-07 13:47:37 -07003309ThreadBase::MetadataUpdate PlaybackThread::updateMetadata_l()
Kevin Rocard069c2712018-03-29 19:09:14 -07003310{
Jasmine Chaeaa10e42021-05-11 10:11:14 +08003311 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
Vlad Popa7e81cea2023-01-19 16:34:16 +01003312 return {}; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -07003313 }
3314 StreamOutHalInterface::SourceMetadata metadata;
Kevin Rocard12381092018-04-11 09:19:59 -07003315 auto backInserter = std::back_inserter(metadata.tracks);
Andy Hung8d31fd22023-06-26 19:20:57 -07003316 for (const sp<IAfTrack>& track : mActiveTracks) {
Kevin Rocard069c2712018-03-29 19:09:14 -07003317 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurent49e39282022-06-24 18:42:45 +02003318 track->copyMetadataTo(backInserter);
Kevin Rocard069c2712018-03-29 19:09:14 -07003319 }
Kevin Rocard12381092018-04-11 09:19:59 -07003320 sendMetadataToBackend_l(metadata);
Vlad Popa7e81cea2023-01-19 16:34:16 +01003321 MetadataUpdate change;
3322 change.playbackMetadataUpdate = metadata.tracks;
3323 return change;
Kevin Rocard80ee2722018-04-11 15:53:48 +00003324}
Kevin Rocardc86a7f72018-04-03 09:00:09 -07003325
Andy Hungee58e4a2023-07-07 13:47:37 -07003326void PlaybackThread::sendMetadataToBackend_l(
Kevin Rocard12381092018-04-11 09:19:59 -07003327 const StreamOutHalInterface::SourceMetadata& metadata)
3328{
3329 mOutput->stream->updateSourceMetadata(metadata);
3330};
3331
Andy Hungee58e4a2023-07-07 13:47:37 -07003332status_t PlaybackThread::getRenderPosition(
Andy Hung440901d2023-06-29 21:19:25 -07003333 uint32_t* halFrames, uint32_t* dspFrames) const
Eric Laurent81784c32012-11-19 14:55:58 -08003334{
3335 if (halFrames == NULL || dspFrames == NULL) {
3336 return BAD_VALUE;
3337 }
Andy Hung972bec12023-08-31 16:13:39 -07003338 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08003339 if (initCheck() != NO_ERROR) {
3340 return INVALID_OPERATION;
3341 }
Andy Hung818e7a32016-02-16 18:08:07 -08003342 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08003343 *halFrames = framesWritten;
3344
3345 if (isSuspended()) {
3346 // return an estimation of rendered frames when the output is suspended
3347 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08003348 *dspFrames = (uint32_t)
3349 (framesWritten >= (int64_t)latencyFrames ? framesWritten - latencyFrames : 0);
Eric Laurent81784c32012-11-19 14:55:58 -08003350 return NO_ERROR;
3351 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003352 status_t status;
3353 uint32_t frames;
Phil Burk062e67a2015-02-11 13:40:50 -08003354 status = mOutput->getRenderPosition(&frames);
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003355 *dspFrames = (size_t)frames;
3356 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08003357 }
3358}
3359
Andy Hungee58e4a2023-07-07 13:47:37 -07003360product_strategy_t PlaybackThread::getStrategyForSession_l(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08003361{
3362 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
3363 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
3364 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02003365 return getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurent81784c32012-11-19 14:55:58 -08003366 }
3367 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003368 sp<IAfTrack> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08003369 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02003370 return getStrategyForStream(track->streamType());
Eric Laurent81784c32012-11-19 14:55:58 -08003371 }
3372 }
Eric Laurentd66d7a12021-07-13 13:35:32 +02003373 return getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurent81784c32012-11-19 14:55:58 -08003374}
3375
3376
Andy Hungee58e4a2023-07-07 13:47:37 -07003377AudioStreamOut* PlaybackThread::getOutput() const
Eric Laurent81784c32012-11-19 14:55:58 -08003378{
Andy Hung972bec12023-08-31 16:13:39 -07003379 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08003380 return mOutput;
3381}
3382
Andy Hungee58e4a2023-07-07 13:47:37 -07003383AudioStreamOut* PlaybackThread::clearOutput()
Eric Laurent81784c32012-11-19 14:55:58 -08003384{
Andy Hung972bec12023-08-31 16:13:39 -07003385 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08003386 AudioStreamOut *output = mOutput;
3387 mOutput = NULL;
3388 // FIXME FastMixer might also have a raw ptr to mOutputSink;
3389 // must push a NULL and wait for ack
3390 mOutputSink.clear();
3391 mPipeSink.clear();
3392 mNormalSink.clear();
3393 return output;
3394}
3395
Andy Hungc5007f82023-08-29 14:26:09 -07003396// this method must always be called either with ThreadBase mutex() held or inside the thread loop
Andy Hungee58e4a2023-07-07 13:47:37 -07003397sp<StreamHalInterface> PlaybackThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08003398{
3399 if (mOutput == NULL) {
3400 return NULL;
3401 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003402 return mOutput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08003403}
3404
Andy Hungee58e4a2023-07-07 13:47:37 -07003405uint32_t PlaybackThread::activeSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08003406{
3407 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
3408}
3409
Andy Hungee58e4a2023-07-07 13:47:37 -07003410status_t PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
Eric Laurent81784c32012-11-19 14:55:58 -08003411{
3412 if (!isValidSyncEvent(event)) {
3413 return BAD_VALUE;
3414 }
3415
Andy Hung972bec12023-08-31 16:13:39 -07003416 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08003417
3418 for (size_t i = 0; i < mTracks.size(); ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003419 sp<IAfTrack> track = mTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08003420 if (event->triggerSession() == track->sessionId()) {
3421 (void) track->setSyncEvent(event);
3422 return NO_ERROR;
3423 }
3424 }
3425
3426 return NAME_NOT_FOUND;
3427}
3428
Andy Hungee58e4a2023-07-07 13:47:37 -07003429bool PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
Eric Laurent81784c32012-11-19 14:55:58 -08003430{
3431 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
3432}
3433
Andy Hungee58e4a2023-07-07 13:47:37 -07003434void PlaybackThread::threadLoop_removeTracks(
Andy Hung8d31fd22023-06-26 19:20:57 -07003435 [[maybe_unused]] const Vector<sp<IAfTrack>>& tracksToRemove)
Eric Laurent81784c32012-11-19 14:55:58 -08003436{
Andy Hungfe726a62018-09-27 15:17:25 -07003437 // Miscellaneous track cleanup when removed from the active list,
3438 // called without Thread lock but synchronized with threadLoop processing.
Eric Laurentbfb1b832013-01-07 09:53:42 -08003439#ifdef ADD_BATTERY_DATA
Andy Hungfe726a62018-09-27 15:17:25 -07003440 for (const auto& track : tracksToRemove) {
3441 if (track->isExternalTrack()) {
3442 // to track the speaker usage
3443 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Eric Laurent81784c32012-11-19 14:55:58 -08003444 }
3445 }
Andy Hungfe726a62018-09-27 15:17:25 -07003446#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003447}
3448
Andy Hungee58e4a2023-07-07 13:47:37 -07003449void PlaybackThread::checkSilentMode_l()
Eric Laurent81784c32012-11-19 14:55:58 -08003450{
3451 if (!mMasterMute) {
3452 char value[PROPERTY_VALUE_MAX];
jiabin0a957d32020-04-29 10:56:20 -07003453 if (mOutDeviceTypeAddrs.empty()) {
3454 ALOGD("ro.audio.silent is ignored since no output device is set");
3455 return;
3456 }
Andy Hungab65b182023-09-06 19:41:47 -07003457 if (isSingleDeviceType(outDeviceTypes_l(), AUDIO_DEVICE_OUT_REMOTE_SUBMIX)) {
Jean-Michel Trivi32f37c22016-03-31 16:00:32 -07003458 ALOGD("ro.audio.silent will be ignored for threads on AUDIO_DEVICE_OUT_REMOTE_SUBMIX");
3459 return;
3460 }
Eric Laurent81784c32012-11-19 14:55:58 -08003461 if (property_get("ro.audio.silent", value, "0") > 0) {
3462 char *endptr;
3463 unsigned long ul = strtoul(value, &endptr, 0);
3464 if (*endptr == '\0' && ul != 0) {
3465 ALOGD("Silence is golden");
3466 // The setprop command will not allow a property to be changed after
3467 // the first time it is set, so we don't have to worry about un-muting.
3468 setMasterMute_l(true);
3469 }
3470 }
3471 }
3472}
3473
3474// shared by MIXER and DIRECT, overridden by DUPLICATING
Andy Hungee58e4a2023-07-07 13:47:37 -07003475ssize_t PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08003476{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07003477 LOG_HIST_TS();
Eric Laurent81784c32012-11-19 14:55:58 -08003478 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003479 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07003480 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08003481
3482 // If an NBAIO sink is present, use it to write the normal mixer's submix
3483 if (mNormalSink != 0) {
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003484
Andy Hung010a1a12014-03-13 13:57:33 -07003485 const size_t count = mBytesRemaining / mFrameSize;
3486
Simon Wilson2d590962012-11-29 15:18:50 -08003487 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08003488 // update the setpoint when AudioFlinger::mScreenState changes
Andy Hung1d2d2aea2023-07-19 16:22:58 -07003489 const uint32_t screenState = mAfThreadCallback->getScreenState();
Eric Laurent81784c32012-11-19 14:55:58 -08003490 if (screenState != mScreenState) {
3491 mScreenState = screenState;
3492 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
3493 if (pipe != NULL) {
3494 pipe->setAvgFrames((mScreenState & 1) ?
3495 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
3496 }
3497 }
Andy Hung010a1a12014-03-13 13:57:33 -07003498 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08003499 ATRACE_END();
Vlad Popab042ee62022-10-20 18:05:00 +02003500
Eric Laurent81784c32012-11-19 14:55:58 -08003501 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07003502 bytesWritten = framesWritten * mFrameSize;
Andy Hung58e32872022-11-15 16:12:24 -08003503
Andy Hung8946a282018-04-19 20:04:56 -07003504#ifdef TEE_SINK
3505 mTee.write((char *)mSinkBuffer + offset, framesWritten);
3506#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003507 } else {
3508 bytesWritten = framesWritten;
3509 }
3510 // otherwise use the HAL / AudioStreamOut directly
3511 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003512 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07003513
Eric Laurentbfb1b832013-01-07 09:53:42 -08003514 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003515 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
3516 mWriteAckSequence += 2;
3517 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003518 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003519 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003520 }
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07003521 ATRACE_BEGIN("write");
Glenn Kasten767094d2013-08-23 13:51:43 -07003522 // FIXME We should have an implementation of timestamps for direct output threads.
3523 // They are used e.g for multichannel PCM playback over HDMI.
Phil Burk062e67a2015-02-11 13:40:50 -08003524 bytesWritten = mOutput->write((char *)mSinkBuffer + offset, mBytesRemaining);
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07003525 ATRACE_END();
Eric Laurent51716182016-02-29 18:00:56 -08003526
Eric Laurentbfb1b832013-01-07 09:53:42 -08003527 if (mUseAsyncWrite &&
3528 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
3529 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07003530 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003531 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003532 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003533 }
Eric Laurent81784c32012-11-19 14:55:58 -08003534 }
3535
Eric Laurent81784c32012-11-19 14:55:58 -08003536 mNumWrites++;
3537 mInWrite = false;
Andy Hungcf10d742020-04-28 15:38:24 -07003538 if (mStandby) {
3539 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07003540 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -07003541 mStandby = false;
3542 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003543 return bytesWritten;
3544}
3545
Andy Hungc5007f82023-08-29 14:26:09 -07003546// startMelComputation_l() must be called with AudioFlinger::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07003547void PlaybackThread::startMelComputation_l(
Vlad Popaf09e93f2022-10-31 16:27:12 +01003548 const sp<audio_utils::MelProcessor>& processor)
Vlad Popab042ee62022-10-20 18:05:00 +02003549{
Vlad Popa3c7a2662023-02-14 20:09:47 +01003550 auto outputSink = static_cast<AudioStreamOutSink*>(mOutputSink.get());
Vlad Popa1a0c3ab2023-03-17 01:07:01 +01003551 if (outputSink != nullptr) {
3552 outputSink->startMelComputation(processor);
3553 }
Vlad Popab042ee62022-10-20 18:05:00 +02003554}
3555
Andy Hungc5007f82023-08-29 14:26:09 -07003556// stopMelComputation_l() must be called with AudioFlinger::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07003557void PlaybackThread::stopMelComputation_l()
Vlad Popa3c7a2662023-02-14 20:09:47 +01003558{
3559 auto outputSink = static_cast<AudioStreamOutSink*>(mOutputSink.get());
Vlad Popa1a0c3ab2023-03-17 01:07:01 +01003560 if (outputSink != nullptr) {
3561 outputSink->stopMelComputation();
3562 }
Vlad Popab042ee62022-10-20 18:05:00 +02003563}
3564
Andy Hungee58e4a2023-07-07 13:47:37 -07003565void PlaybackThread::threadLoop_drain()
Eric Laurentbfb1b832013-01-07 09:53:42 -08003566{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003567 bool supportsDrain = false;
3568 if (mOutput->stream->supportsDrain(&supportsDrain) == OK && supportsDrain) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003569 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
3570 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003571 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
3572 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003573 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003574 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003575 }
Mikhail Naganovcbc8f612016-10-11 18:05:13 -07003576 status_t result = mOutput->stream->drain(mMixerStatus == MIXER_DRAIN_TRACK);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003577 ALOGE_IF(result != OK, "Error when draining stream: %d", result);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003578 }
3579}
3580
Andy Hungee58e4a2023-07-07 13:47:37 -07003581void PlaybackThread::threadLoop_exit()
Eric Laurentbfb1b832013-01-07 09:53:42 -08003582{
Eric Laurent275e8e92014-11-30 15:14:47 -08003583 {
Andy Hung972bec12023-08-31 16:13:39 -07003584 audio_utils::lock_guard _l(mutex());
Eric Laurent275e8e92014-11-30 15:14:47 -08003585 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003586 sp<IAfTrack> track = mTracks[i];
Eric Laurent275e8e92014-11-30 15:14:47 -08003587 track->invalidate();
3588 }
Andy Hungdae27702016-10-31 14:01:16 -07003589 // Clear ActiveTracks to update BatteryNotifier in case active tracks remain.
3590 // After we exit there are no more track changes sent to BatteryNotifier
3591 // because that requires an active threadLoop.
3592 // TODO: should we decActiveTrackCnt() of the cleared track effect chain?
3593 mActiveTracks.clear();
Eric Laurent275e8e92014-11-30 15:14:47 -08003594 }
Eric Laurent81784c32012-11-19 14:55:58 -08003595}
3596
3597/*
3598The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08003599 - mSinkBufferSize from frame count * frame size
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003600 - mActiveSleepTimeUs from activeSleepTimeUs()
3601 - mIdleSleepTimeUs from idleSleepTimeUs()
Eric Laurent42537be2016-01-08 17:16:42 -08003602 - mStandbyDelayNs from mActiveSleepTimeUs (DIRECT only) or forced to at least
3603 kDefaultStandbyTimeInNsecs when connected to an A2DP device.
Eric Laurent81784c32012-11-19 14:55:58 -08003604 - maxPeriod from frame count and sample rate (MIXER only)
3605
3606The parameters that affect these derived values are:
3607 - frame count
3608 - frame size
3609 - sample rate
3610 - device type: A2DP or not
3611 - device latency
3612 - format: PCM or not
3613 - active sleep time
3614 - idle sleep time
3615*/
3616
Andy Hungee58e4a2023-07-07 13:47:37 -07003617void PlaybackThread::cacheParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08003618{
Andy Hung25c2dac2014-02-27 14:56:00 -08003619 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003620 mActiveSleepTimeUs = activeSleepTimeUs();
3621 mIdleSleepTimeUs = idleSleepTimeUs();
Eric Laurent42537be2016-01-08 17:16:42 -08003622
Andy Hung8fe87eb2023-07-20 21:31:38 -07003623 mStandbyDelayNs = getStandbyTimeInNanos();
Carter Hsu0ca47c22023-06-02 18:01:45 +08003624
Eric Laurent42537be2016-01-08 17:16:42 -08003625 // make sure standby delay is not too short when connected to an A2DP sink to avoid
3626 // truncating audio when going to standby.
Andy Hungab65b182023-09-06 19:41:47 -07003627 if (!Intersection(outDeviceTypes_l(), getAudioDeviceOutAllA2dpSet()).empty()) {
Eric Laurent42537be2016-01-08 17:16:42 -08003628 if (mStandbyDelayNs < kDefaultStandbyTimeInNsecs) {
3629 mStandbyDelayNs = kDefaultStandbyTimeInNsecs;
3630 }
3631 }
Eric Laurent81784c32012-11-19 14:55:58 -08003632}
3633
Andy Hungee58e4a2023-07-07 13:47:37 -07003634bool PlaybackThread::invalidateTracks_l(audio_stream_type_t streamType)
Eric Laurent81784c32012-11-19 14:55:58 -08003635{
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003636 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %zu",
Eric Laurent81784c32012-11-19 14:55:58 -08003637 this, streamType, mTracks.size());
Eric Laurent13084622016-05-17 10:51:49 -07003638 bool trackMatch = false;
Eric Laurent81784c32012-11-19 14:55:58 -08003639 size_t size = mTracks.size();
3640 for (size_t i = 0; i < size; i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003641 sp<IAfTrack> t = mTracks[i];
Eric Laurentd60560a2015-04-10 11:31:20 -07003642 if (t->streamType() == streamType && t->isExternalTrack()) {
Glenn Kasten5736c352012-12-04 12:12:34 -08003643 t->invalidate();
Eric Laurent13084622016-05-17 10:51:49 -07003644 trackMatch = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003645 }
3646 }
Eric Laurent13084622016-05-17 10:51:49 -07003647 return trackMatch;
Eric Laurent81784c32012-11-19 14:55:58 -08003648}
3649
Andy Hungee58e4a2023-07-07 13:47:37 -07003650void PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
Haynes Mathew George05317d22016-05-03 16:34:26 -07003651{
Andy Hung972bec12023-08-31 16:13:39 -07003652 audio_utils::lock_guard _l(mutex());
Haynes Mathew George05317d22016-05-03 16:34:26 -07003653 invalidateTracks_l(streamType);
3654}
3655
Andy Hungee58e4a2023-07-07 13:47:37 -07003656void PlaybackThread::invalidateTracks(std::set<audio_port_handle_t>& portIds) {
Andy Hung972bec12023-08-31 16:13:39 -07003657 audio_utils::lock_guard _l(mutex());
jiabinc44b3462022-12-08 12:52:31 -08003658 invalidateTracks_l(portIds);
3659}
3660
Andy Hungee58e4a2023-07-07 13:47:37 -07003661bool PlaybackThread::invalidateTracks_l(std::set<audio_port_handle_t>& portIds) {
jiabinc44b3462022-12-08 12:52:31 -08003662 bool trackMatch = false;
3663 const size_t size = mTracks.size();
3664 for (size_t i = 0; i < size; i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003665 sp<IAfTrack> t = mTracks[i];
jiabinc44b3462022-12-08 12:52:31 -08003666 if (t->isExternalTrack() && portIds.find(t->portId()) != portIds.end()) {
3667 t->invalidate();
3668 portIds.erase(t->portId());
3669 trackMatch = true;
3670 }
3671 if (portIds.empty()) {
3672 break;
3673 }
3674 }
3675 return trackMatch;
3676}
3677
jiabinf042b9b2021-05-07 23:46:28 +00003678// getTrackById_l must be called with holding thread lock
Andy Hungee58e4a2023-07-07 13:47:37 -07003679IAfTrack* PlaybackThread::getTrackById_l(
jiabinf042b9b2021-05-07 23:46:28 +00003680 audio_port_handle_t trackPortId) {
3681 for (size_t i = 0; i < mTracks.size(); i++) {
3682 if (mTracks[i]->portId() == trackPortId) {
3683 return mTracks[i].get();
3684 }
3685 }
3686 return nullptr;
3687}
3688
Andy Hungee58e4a2023-07-07 13:47:37 -07003689status_t PlaybackThread::addEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08003690{
Glenn Kastend848eb42016-03-08 13:42:11 -08003691 audio_session_t session = chain->sessionId();
Mikhail Naganov022b9952017-01-04 16:36:51 -08003692 sp<EffectBufferHalInterface> halInBuffer, halOutBuffer;
Andy Hung319587b2023-05-23 14:01:03 -07003693 float *buffer = nullptr; // only used for non global sessions
Eric Laurentb62d0362021-10-26 17:40:18 +02003694
Andy Hungd3639922022-04-28 18:00:49 -07003695 if (mType == SPATIALIZER) {
Eric Laurentb62d0362021-10-26 17:40:18 +02003696 if (!audio_is_global_session(session)) {
3697 // player sessions on a spatializer output will use a dedicated input buffer and
3698 // will either output multi channel to mEffectBuffer if the track is spatilaized
3699 // or stereo to mPostSpatializerBuffer if not spatialized.
3700 uint32_t channelMask;
3701 bool isSessionSpatialized =
3702 (hasAudioSession_l(session) & ThreadBase::SPATIALIZED_SESSION) != 0;
3703 if (isSessionSpatialized) {
3704 channelMask = mMixerChannelMask;
3705 } else {
3706 channelMask = mChannelMask;
3707 }
Eric Laurentf1f22e72021-07-13 14:04:14 +02003708 size_t numSamples = mNormalFrameCount
Eric Laurentb62d0362021-10-26 17:40:18 +02003709 * (audio_channel_count_from_out_mask(channelMask) + mHapticChannelCount);
Andy Hung583043b2023-07-17 17:05:00 -07003710 status_t result = mAfThreadCallback->getEffectsFactoryHal()->allocateBuffer(
Andy Hung319587b2023-05-23 14:01:03 -07003711 numSamples * sizeof(float),
Mikhail Naganov022b9952017-01-04 16:36:51 -08003712 &halInBuffer);
3713 if (result != OK) return result;
Eric Laurentb62d0362021-10-26 17:40:18 +02003714
Andy Hung583043b2023-07-17 17:05:00 -07003715 result = mAfThreadCallback->getEffectsFactoryHal()->mirrorBuffer(
Eric Laurentb62d0362021-10-26 17:40:18 +02003716 isSessionSpatialized ? mEffectBuffer : mPostSpatializerBuffer,
3717 isSessionSpatialized ? mEffectBufferSize : mPostSpatializerBufferSize,
3718 &halOutBuffer);
3719 if (result != OK) return result;
3720
Shunkai Yao44bdbad2023-01-14 05:11:58 +00003721 buffer = halInBuffer ? halInBuffer->audioBuffer()->f32 : buffer;
Andy Hung26836922023-05-22 17:31:57 -07003722
Mikhail Naganov022b9952017-01-04 16:36:51 -08003723 ALOGV("addEffectChain_l() creating new input buffer %p session %d",
3724 buffer, session);
Eric Laurentb62d0362021-10-26 17:40:18 +02003725 } else {
3726 // A global session on a SPATIALIZER thread is either OUTPUT_STAGE or DEVICE
3727 // - OUTPUT_STAGE session uses the mEffectBuffer as input buffer and
3728 // mPostSpatializerBuffer as output buffer
3729 // - DEVICE session uses the mPostSpatializerBuffer as input and output buffer.
Andy Hung583043b2023-07-17 17:05:00 -07003730 status_t result = mAfThreadCallback->getEffectsFactoryHal()->mirrorBuffer(
Eric Laurentb62d0362021-10-26 17:40:18 +02003731 mEffectBuffer, mEffectBufferSize, &halInBuffer);
3732 if (result != OK) return result;
Andy Hung583043b2023-07-17 17:05:00 -07003733 result = mAfThreadCallback->getEffectsFactoryHal()->mirrorBuffer(
Eric Laurentb62d0362021-10-26 17:40:18 +02003734 mPostSpatializerBuffer, mPostSpatializerBufferSize, &halOutBuffer);
3735 if (result != OK) return result;
Eric Laurent81784c32012-11-19 14:55:58 -08003736
Eric Laurentb62d0362021-10-26 17:40:18 +02003737 if (session == AUDIO_SESSION_DEVICE) {
3738 halInBuffer = halOutBuffer;
3739 }
3740 }
3741 } else {
Andy Hung583043b2023-07-17 17:05:00 -07003742 status_t result = mAfThreadCallback->getEffectsFactoryHal()->mirrorBuffer(
Eric Laurentb62d0362021-10-26 17:40:18 +02003743 mEffectBufferEnabled ? mEffectBuffer : mSinkBuffer,
3744 mEffectBufferEnabled ? mEffectBufferSize : mSinkBufferSize,
3745 &halInBuffer);
3746 if (result != OK) return result;
3747 halOutBuffer = halInBuffer;
3748 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
3749 if (!audio_is_global_session(session)) {
Andy Hung319587b2023-05-23 14:01:03 -07003750 buffer = halInBuffer ? reinterpret_cast<float*>(halInBuffer->externalData())
Shunkai Yao44bdbad2023-01-14 05:11:58 +00003751 : buffer;
Eric Laurentb62d0362021-10-26 17:40:18 +02003752 // Only one effect chain can be present in direct output thread and it uses
3753 // the sink buffer as input
3754 if (mType != DIRECT) {
3755 size_t numSamples = mNormalFrameCount
3756 * (audio_channel_count_from_out_mask(mMixerChannelMask)
3757 + mHapticChannelCount);
Andy Hung583043b2023-07-17 17:05:00 -07003758 const status_t allocateStatus =
3759 mAfThreadCallback->getEffectsFactoryHal()->allocateBuffer(
Andy Hung319587b2023-05-23 14:01:03 -07003760 numSamples * sizeof(float),
Eric Laurentb62d0362021-10-26 17:40:18 +02003761 &halInBuffer);
Andy Hung920f6572022-10-06 12:09:49 -07003762 if (allocateStatus != OK) return allocateStatus;
Andy Hung26836922023-05-22 17:31:57 -07003763
Shunkai Yao44bdbad2023-01-14 05:11:58 +00003764 buffer = halInBuffer ? halInBuffer->audioBuffer()->f32 : buffer;
Eric Laurentb62d0362021-10-26 17:40:18 +02003765 ALOGV("addEffectChain_l() creating new input buffer %p session %d",
3766 buffer, session);
3767 }
3768 }
3769 }
3770
3771 if (!audio_is_global_session(session)) {
Eric Laurent81784c32012-11-19 14:55:58 -08003772 // Attach all tracks with same session ID to this chain.
3773 for (size_t i = 0; i < mTracks.size(); ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003774 sp<IAfTrack> track = mTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08003775 if (session == track->sessionId()) {
Eric Laurentb62d0362021-10-26 17:40:18 +02003776 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p",
3777 track.get(), buffer);
Eric Laurent81784c32012-11-19 14:55:58 -08003778 track->setMainBuffer(buffer);
3779 chain->incTrackCnt();
3780 }
3781 }
3782
3783 // indicate all active tracks in the chain
Andy Hung8d31fd22023-06-26 19:20:57 -07003784 for (const sp<IAfTrack>& track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08003785 if (session == track->sessionId()) {
Eric Laurentb62d0362021-10-26 17:40:18 +02003786 ALOGV("addEffectChain_l() activating track %p on session %d",
3787 track.get(), session);
Eric Laurent81784c32012-11-19 14:55:58 -08003788 chain->incActiveTrackCnt();
3789 }
3790 }
3791 }
Eric Laurentb62d0362021-10-26 17:40:18 +02003792
Eric Laurentaaa44472014-09-12 17:41:50 -07003793 chain->setThread(this);
Mikhail Naganov022b9952017-01-04 16:36:51 -08003794 chain->setInBuffer(halInBuffer);
3795 chain->setOutBuffer(halOutBuffer);
Eric Laurent3f75a5b2019-11-12 15:55:51 -08003796 // Effect chain for session AUDIO_SESSION_DEVICE is inserted at end of effect
3797 // chains list in order to be processed last as it contains output device effects.
3798 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted just before to apply post
3799 // processing effects specific to an output stream before effects applied to all streams
3800 // routed to a given device.
Eric Laurent81784c32012-11-19 14:55:58 -08003801 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
3802 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Glenn Kastend848eb42016-03-08 13:42:11 -08003803 // after track specific effects and before output stage.
Eric Laurent81784c32012-11-19 14:55:58 -08003804 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
Glenn Kastend848eb42016-03-08 13:42:11 -08003805 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX.
Eric Laurent81784c32012-11-19 14:55:58 -08003806 // Effect chain for other sessions are inserted at beginning of effect
3807 // chains list to be processed before output mix effects. Relative order between other
Glenn Kastend848eb42016-03-08 13:42:11 -08003808 // sessions is not important.
3809 static_assert(AUDIO_SESSION_OUTPUT_MIX == 0 &&
Eric Laurent3f75a5b2019-11-12 15:55:51 -08003810 AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX &&
3811 AUDIO_SESSION_DEVICE < AUDIO_SESSION_OUTPUT_STAGE,
Glenn Kastend848eb42016-03-08 13:42:11 -08003812 "audio_session_t constants misdefined");
Eric Laurent81784c32012-11-19 14:55:58 -08003813 size_t size = mEffectChains.size();
3814 size_t i = 0;
3815 for (i = 0; i < size; i++) {
3816 if (mEffectChains[i]->sessionId() < session) {
3817 break;
3818 }
3819 }
3820 mEffectChains.insertAt(chain, i);
3821 checkSuspendOnAddEffectChain_l(chain);
3822
3823 return NO_ERROR;
3824}
3825
Andy Hungee58e4a2023-07-07 13:47:37 -07003826size_t PlaybackThread::removeEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08003827{
Glenn Kastend848eb42016-03-08 13:42:11 -08003828 audio_session_t session = chain->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08003829
3830 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
3831
3832 for (size_t i = 0; i < mEffectChains.size(); i++) {
3833 if (chain == mEffectChains[i]) {
3834 mEffectChains.removeAt(i);
3835 // detach all active tracks from the chain
Andy Hung8d31fd22023-06-26 19:20:57 -07003836 for (const sp<IAfTrack>& track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08003837 if (session == track->sessionId()) {
3838 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
3839 chain.get(), session);
3840 chain->decActiveTrackCnt();
3841 }
3842 }
3843
3844 // detach all tracks with same session ID from this chain
Andy Hung920f6572022-10-06 12:09:49 -07003845 for (size_t j = 0; j < mTracks.size(); ++j) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003846 sp<IAfTrack> track = mTracks[j];
Eric Laurent81784c32012-11-19 14:55:58 -08003847 if (session == track->sessionId()) {
Andy Hung319587b2023-05-23 14:01:03 -07003848 track->setMainBuffer(reinterpret_cast<float*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08003849 chain->decTrackCnt();
3850 }
3851 }
3852 break;
3853 }
3854 }
3855 return mEffectChains.size();
3856}
3857
Andy Hungee58e4a2023-07-07 13:47:37 -07003858status_t PlaybackThread::attachAuxEffect(
Andy Hung8d31fd22023-06-26 19:20:57 -07003859 const sp<IAfTrack>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003860{
Andy Hung972bec12023-08-31 16:13:39 -07003861 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08003862 return attachAuxEffect_l(track, EffectId);
3863}
3864
Andy Hungee58e4a2023-07-07 13:47:37 -07003865status_t PlaybackThread::attachAuxEffect_l(
Andy Hung8d31fd22023-06-26 19:20:57 -07003866 const sp<IAfTrack>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003867{
3868 status_t status = NO_ERROR;
3869
3870 if (EffectId == 0) {
3871 track->setAuxBuffer(0, NULL);
3872 } else {
3873 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
Andy Hung116bc262023-06-20 18:56:17 -07003874 sp<IAfEffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Eric Laurent81784c32012-11-19 14:55:58 -08003875 if (effect != 0) {
3876 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
3877 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
3878 } else {
3879 status = INVALID_OPERATION;
3880 }
3881 } else {
3882 status = BAD_VALUE;
3883 }
3884 }
3885 return status;
3886}
3887
Andy Hungee58e4a2023-07-07 13:47:37 -07003888void PlaybackThread::detachAuxEffect_l(int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003889{
3890 for (size_t i = 0; i < mTracks.size(); ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003891 sp<IAfTrack> track = mTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08003892 if (track->auxEffectId() == effectId) {
3893 attachAuxEffect_l(track, 0);
3894 }
3895 }
3896}
3897
Andy Hungee58e4a2023-07-07 13:47:37 -07003898bool PlaybackThread::threadLoop()
Andy Hung920f6572022-10-06 12:09:49 -07003899NO_THREAD_SAFETY_ANALYSIS // manual locking of AudioFlinger
Eric Laurent81784c32012-11-19 14:55:58 -08003900{
Andy Hung78d8d952023-05-30 18:10:23 -07003901 aflog::setThreadWriter(mNBLogWriter.get());
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003902
Andy Hungc00c06b2023-11-07 19:51:12 -08003903 std::future<void> priorityBoostFuture; // joined on dtor; this is a one-shot boost.
Andy Hung077d62e2023-10-03 10:49:34 -07003904 if (mType == SPATIALIZER) {
3905 const pid_t tid = getTid();
3906 if (tid == -1) { // odd: we are here, we must be a running thread.
3907 ALOGW("%s: Cannot update Spatializer mixer thread priority, no tid", __func__);
3908 } else {
Andy Hungc00c06b2023-11-07 19:51:12 -08003909 // We launch the priority boost request in a separate thread because
3910 // the SchedulingPolicyService may not be available during early
3911 // boot time, with a wait causing boot delay.
3912 // There is also a PrioConfigEvent that does this, but it will also
3913 // block other config events. This command should be able
3914 // to run concurrent with other stream commands.
3915 priorityBoostFuture = std::async(std::launch::async,
3916 [tid, output_sp = stream()]() {
3917 const int priorityBoost = requestSpatializerPriority(getpid(), tid);
3918 if (priorityBoost > 0) {
3919 output_sp->setHalThreadPriority(priorityBoost);
3920 }
3921 });
Andy Hung077d62e2023-10-03 10:49:34 -07003922 }
3923 }
3924
Andy Hung8d31fd22023-06-26 19:20:57 -07003925 Vector<sp<IAfTrack>> tracksToRemove;
Eric Laurent81784c32012-11-19 14:55:58 -08003926
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003927 mStandbyTimeNs = systemTime();
Andy Hung446f4df2019-02-21 12:26:41 -08003928 int64_t lastLoopCountWritten = -2; // never matches "previous" loop, when loopCount = 0.
Eric Laurent81784c32012-11-19 14:55:58 -08003929
3930 // MIXER
3931 nsecs_t lastWarning = 0;
3932
3933 // DUPLICATING
3934 // FIXME could this be made local to while loop?
3935 writeFrames = 0;
3936
3937 cacheParameters_l();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003938 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003939
Andy Hungd3639922022-04-28 18:00:49 -07003940 if (mType == MIXER || mType == SPATIALIZER) {
Eric Laurent81784c32012-11-19 14:55:58 -08003941 sleepTimeShift = 0;
3942 }
3943
3944 CpuStats cpuStats;
3945 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
3946
3947 acquireWakeLock();
3948
Glenn Kasteneef598c2017-04-03 14:41:13 -07003949 // mNBLogWriter logging APIs can only be called by a single thread, typically the
3950 // thread associated with this PlaybackThread.
3951 // If you want to share the mNBLogWriter with other threads (for example, binder threads)
3952 // then all such threads must agree to hold a common mutex before logging.
Glenn Kasten9e58b552013-01-18 15:09:48 -08003953 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
3954 // and then that string will be logged at the next convenient opportunity.
Glenn Kasteneef598c2017-04-03 14:41:13 -07003955 // See reference to logString below.
Glenn Kasten9e58b552013-01-18 15:09:48 -08003956 const char *logString = NULL;
3957
rago1bb90822017-05-02 18:31:48 -07003958 // Estimated time for next buffer to be written to hal. This is used only on
3959 // suspended mode (for now) to help schedule the wait time until next iteration.
3960 nsecs_t timeLoopNextNs = 0;
3961
Eric Laurent664539d2013-09-23 18:24:31 -07003962 checkSilentMode_l();
Glenn Kasteneef598c2017-04-03 14:41:13 -07003963
Andy Hung2dbffc22018-08-08 18:50:41 -07003964 audio_patch_handle_t lastDownstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Andy Hungf3234512018-07-03 14:51:47 -07003965
Eric Laurentb3f315a2021-07-13 15:09:05 +02003966 sendCheckOutputStageEffectsEvent();
3967
Andy Hung446f4df2019-02-21 12:26:41 -08003968 // loopCount is used for statistics and diagnostics.
3969 for (int64_t loopCount = 0; !exitPending(); ++loopCount)
Eric Laurent81784c32012-11-19 14:55:58 -08003970 {
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08003971 // Log merge requests are performed during AudioFlinger binder transactions, but
3972 // that does not cover audio playback. It's requested here for that reason.
Andy Hung583043b2023-07-17 17:05:00 -07003973 mAfThreadCallback->requestLogMerge();
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08003974
Eric Laurent81784c32012-11-19 14:55:58 -08003975 cpuStats.sample(myName);
3976
Andy Hung116bc262023-06-20 18:56:17 -07003977 Vector<sp<IAfEffectChain>> effectChains;
Andy Hung6e6a2e62019-04-30 16:38:41 -07003978 audio_session_t activeHapticSessionId = AUDIO_SESSION_NONE;
Eric Laurentb62d0362021-10-26 17:40:18 +02003979 bool isHapticSessionSpatialized = false;
Andy Hung8d31fd22023-06-26 19:20:57 -07003980 std::vector<sp<IAfTrack>> activeTracks;
Eric Laurent81784c32012-11-19 14:55:58 -08003981
Andy Hung2dbffc22018-08-08 18:50:41 -07003982 // If the device is AUDIO_DEVICE_OUT_BUS, check for downstream latency.
3983 //
Andy Hungc5007f82023-08-29 14:26:09 -07003984 // Note: we access outDeviceTypes() outside of mutex().
Andy Hungab65b182023-09-06 19:41:47 -07003985 if (isMsdDevice() && outDeviceTypes_l().count(AUDIO_DEVICE_OUT_BUS) != 0) {
Andy Hung2dbffc22018-08-08 18:50:41 -07003986 // Here, we try for the AF lock, but do not block on it as the latency
3987 // is more informational.
Andy Hung954b9712023-08-28 18:36:53 -07003988 if (mAfThreadCallback->mutex().try_lock()) {
Andy Hungb6692eb2023-07-13 16:52:46 -07003989 std::vector<SoftwarePatch> swPatches;
Andy Hung920f6572022-10-06 12:09:49 -07003990 double latencyMs = 0.; // not required; initialized for clang-tidy
Andy Hung2dbffc22018-08-08 18:50:41 -07003991 status_t status = INVALID_OPERATION;
3992 audio_patch_handle_t downstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Andy Hung583043b2023-07-17 17:05:00 -07003993 if (mAfThreadCallback->getPatchPanel()->getDownstreamSoftwarePatches(
Andy Hungb6692eb2023-07-13 16:52:46 -07003994 id(), &swPatches) == OK
Andy Hung2dbffc22018-08-08 18:50:41 -07003995 && swPatches.size() > 0) {
3996 status = swPatches[0].getLatencyMs_l(&latencyMs);
3997 downstreamPatchHandle = swPatches[0].getPatchHandle();
3998 }
3999 if (downstreamPatchHandle != lastDownstreamPatchHandle) {
Dean Wheatley30d28422018-11-06 10:27:40 +11004000 mDownstreamLatencyStatMs.reset();
Andy Hung2dbffc22018-08-08 18:50:41 -07004001 lastDownstreamPatchHandle = downstreamPatchHandle;
4002 }
4003 if (status == OK) {
4004 // verify downstream latency (we assume a max reasonable
Mikhail Naganov6aa0a312018-11-09 11:00:01 -08004005 // latency of 5 seconds).
4006 const double minLatency = 0., maxLatency = 5000.;
4007 if (latencyMs >= minLatency && latencyMs <= maxLatency) {
Dean Wheatley56a583e2020-05-08 15:12:17 +10004008 ALOGVV("new downstream latency %lf ms", latencyMs);
Andy Hung2dbffc22018-08-08 18:50:41 -07004009 } else {
4010 ALOGD("out of range downstream latency %lf ms", latencyMs);
Andy Hung920f6572022-10-06 12:09:49 -07004011 latencyMs = std::clamp(latencyMs, minLatency, maxLatency);
Andy Hung2dbffc22018-08-08 18:50:41 -07004012 }
Dean Wheatley30d28422018-11-06 10:27:40 +11004013 mDownstreamLatencyStatMs.add(latencyMs);
Andy Hung2dbffc22018-08-08 18:50:41 -07004014 }
Andy Hung583043b2023-07-17 17:05:00 -07004015 mAfThreadCallback->mutex().unlock();
Andy Hung2dbffc22018-08-08 18:50:41 -07004016 }
4017 } else {
4018 if (lastDownstreamPatchHandle != AUDIO_PATCH_HANDLE_NONE) {
4019 // our device is no longer AUDIO_DEVICE_OUT_BUS, reset patch handle and stats.
Dean Wheatley30d28422018-11-06 10:27:40 +11004020 mDownstreamLatencyStatMs.reset();
Andy Hung2dbffc22018-08-08 18:50:41 -07004021 lastDownstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
4022 }
4023 }
4024
Eric Laurentb3f315a2021-07-13 15:09:05 +02004025 if (mCheckOutputStageEffects.exchange(false)) {
4026 checkOutputStageEffects();
4027 }
4028
Vlad Popa7e81cea2023-01-19 16:34:16 +01004029 MetadataUpdate metadataUpdate;
Andy Hungc5007f82023-08-29 14:26:09 -07004030 { // scope for mutex()
Eric Laurent81784c32012-11-19 14:55:58 -08004031
Andy Hungc5007f82023-08-29 14:26:09 -07004032 audio_utils::unique_lock _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08004033
Eric Laurent021cf962014-05-13 10:18:14 -07004034 processConfigEvents_l();
Eric Laurentb3f315a2021-07-13 15:09:05 +02004035 if (mCheckOutputStageEffects.load()) {
4036 continue;
4037 }
Eric Laurent10351942014-05-08 18:49:52 -07004038
Andy Hungc5007f82023-08-29 14:26:09 -07004039 // See comment at declaration of logString for why this is done under mutex()
Glenn Kasten9e58b552013-01-18 15:09:48 -08004040 if (logString != NULL) {
4041 mNBLogWriter->logTimestamp();
4042 mNBLogWriter->log(logString);
4043 logString = NULL;
4044 }
4045
Dean Wheatley12473e92021-03-18 23:00:55 +11004046 collectTimestamps_l();
Andy Hungc8fddf32018-08-08 18:32:37 -07004047
Eric Laurent81784c32012-11-19 14:55:58 -08004048 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004049 if (mSignalPending) {
4050 // A signal was raised while we were unlocked
4051 mSignalPending = false;
4052 } else if (waitingAsyncCallback_l()) {
4053 if (exitPending()) {
4054 break;
4055 }
Marco Nelissen078538c2015-05-12 09:17:57 -07004056 bool released = false;
Eric Laurent64667972016-03-30 18:19:46 -07004057 if (!keepWakeLock()) {
Marco Nelissen078538c2015-05-12 09:17:57 -07004058 releaseWakeLock_l();
4059 released = true;
4060 }
Andy Hung10cbff12017-02-21 17:30:14 -08004061
4062 const int64_t waitNs = computeWaitTimeNs_l();
4063 ALOGV("wait async completion (wait time: %lld)", (long long)waitNs);
Andy Hungc5007f82023-08-29 14:26:09 -07004064 std::cv_status cvstatus =
4065 mWaitWorkCV.wait_for(_l, std::chrono::nanoseconds(waitNs));
4066 if (cvstatus == std::cv_status::timeout) {
Andy Hung10cbff12017-02-21 17:30:14 -08004067 mSignalPending = true; // if timeout recheck everything
4068 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004069 ALOGV("async completion/wake");
Marco Nelissen078538c2015-05-12 09:17:57 -07004070 if (released) {
4071 acquireWakeLock_l();
4072 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004073 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
4074 mSleepTimeUs = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07004075
4076 continue;
4077 }
Eric Tan39ec8d62018-07-24 09:49:29 -07004078 if ((mActiveTracks.isEmpty() && systemTime() > mStandbyTimeNs) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08004079 isSuspended()) {
4080 // put audio hardware into standby after short delay
4081 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004082
4083 threadLoop_standby();
4084
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07004085 // This is where we go into standby
4086 if (!mStandby) {
4087 LOG_AUDIO_STATE();
Andy Hungcf10d742020-04-28 15:38:24 -07004088 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07004089 mThreadSnapshot.onEnd();
Eric Laurent19952e12023-04-20 10:08:29 +02004090 setStandby_l();
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07004091 }
Andy Hungd0979812019-02-21 15:51:44 -08004092 sendStatistics(false /* force */);
Eric Laurent81784c32012-11-19 14:55:58 -08004093 }
4094
Eric Tan39ec8d62018-07-24 09:49:29 -07004095 if (mActiveTracks.isEmpty() && mConfigEvents.isEmpty()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004096 // we're about to wait, flush the binder command buffer
4097 IPCThreadState::self()->flushCommands();
4098
4099 clearOutputTracks();
4100
4101 if (exitPending()) {
4102 break;
4103 }
4104
4105 releaseWakeLock_l();
4106 // wait until we have something to do...
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004107 ALOGV("%s going to sleep", myName.c_str());
Andy Hungc5007f82023-08-29 14:26:09 -07004108 mWaitWorkCV.wait(_l);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004109 ALOGV("%s waking up", myName.c_str());
Eric Laurent81784c32012-11-19 14:55:58 -08004110 acquireWakeLock_l();
4111
4112 mMixerStatus = MIXER_IDLE;
4113 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
4114 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004115 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08004116 checkSilentMode_l();
4117
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004118 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
4119 mSleepTimeUs = mIdleSleepTimeUs;
Andy Hungd3639922022-04-28 18:00:49 -07004120 if (mType == MIXER || mType == SPATIALIZER) {
Eric Laurent81784c32012-11-19 14:55:58 -08004121 sleepTimeShift = 0;
4122 }
4123
4124 continue;
4125 }
4126 }
Eric Laurent81784c32012-11-19 14:55:58 -08004127 // mMixerStatusIgnoringFastTracks is also updated internally
4128 mMixerStatus = prepareTracks_l(&tracksToRemove);
4129
Andy Hungab65b182023-09-06 19:41:47 -07004130 mActiveTracks.updatePowerState_l(this);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08004131
Vlad Popa7e81cea2023-01-19 16:34:16 +01004132 metadataUpdate = updateMetadata_l();
Kevin Rocard069c2712018-03-29 19:09:14 -07004133
Eric Laurent81784c32012-11-19 14:55:58 -08004134 // prevent any changes in effect chain list and in each effect chain
4135 // during mixing and effect process as the audio buffers could be deleted
4136 // or modified if an effect is created or deleted
4137 lockEffectChains_l(effectChains);
Andy Hung6e6a2e62019-04-30 16:38:41 -07004138
4139 // Determine which session to pick up haptic data.
4140 // This must be done under the same lock as prepareTracks_l().
jiabineb3bda02020-06-30 14:07:03 -07004141 // The haptic data from the effect is at a higher priority than the one from track.
Andy Hung6e6a2e62019-04-30 16:38:41 -07004142 // TODO: Write haptic data directly to sink buffer when mixing.
Eric Laurentb62d0362021-10-26 17:40:18 +02004143 if (mHapticChannelCount > 0) {
Andy Hung6e6a2e62019-04-30 16:38:41 -07004144 for (const auto& track : mActiveTracks) {
Andy Hung116bc262023-06-20 18:56:17 -07004145 sp<IAfEffectChain> effectChain = getEffectChain_l(track->sessionId());
Eric Laurentb62d0362021-10-26 17:40:18 +02004146 if (effectChain != nullptr
4147 && effectChain->containsHapticGeneratingEffect_l()) {
jiabineb3bda02020-06-30 14:07:03 -07004148 activeHapticSessionId = track->sessionId();
Eric Laurentb62d0362021-10-26 17:40:18 +02004149 isHapticSessionSpatialized =
Eric Laurentb0a7bc92022-04-05 15:06:08 +02004150 mType == SPATIALIZER && track->isSpatialized();
jiabineb3bda02020-06-30 14:07:03 -07004151 break;
4152 }
Eric Laurentb62d0362021-10-26 17:40:18 +02004153 if (activeHapticSessionId == AUDIO_SESSION_NONE
4154 && track->getHapticPlaybackEnabled()) {
Andy Hung6e6a2e62019-04-30 16:38:41 -07004155 activeHapticSessionId = track->sessionId();
Eric Laurentb62d0362021-10-26 17:40:18 +02004156 isHapticSessionSpatialized =
Eric Laurentb0a7bc92022-04-05 15:06:08 +02004157 mType == SPATIALIZER && track->isSpatialized();
Andy Hung6e6a2e62019-04-30 16:38:41 -07004158 }
4159 }
4160 }
4161
Andy Hungc1646382019-04-30 16:12:10 -07004162 // Acquire a local copy of active tracks with lock (release w/o lock).
4163 //
4164 // Control methods on the track acquire the ThreadBase lock (e.g. start()
4165 // stop(), pause(), etc.), but the threadLoop is entitled to call audio
4166 // data / buffer methods on tracks from activeTracks without the ThreadBase lock.
4167 activeTracks.insert(activeTracks.end(), mActiveTracks.begin(), mActiveTracks.end());
Eric Laurent68a40a82022-05-03 18:15:04 +02004168
4169 setHalLatencyMode_l();
Eric Laurent19952e12023-04-20 10:08:29 +02004170
Jiabin Huangfb476842022-12-06 03:18:10 +00004171 for (const auto &track : mActiveTracks ) {
jiabin7434e812023-06-27 18:22:35 +00004172 track->updateTeePatches_l();
Jiabin Huangfb476842022-12-06 03:18:10 +00004173 }
4174
Eric Laurent19952e12023-04-20 10:08:29 +02004175 // signal actual start of output stream when the render position reported by the kernel
4176 // starts moving.
Eric Laurent4edbd8c2023-05-22 17:00:24 +02004177 if (!mHalStarted && ((isSuspended() && (mBytesWritten != 0)) || (!mStandby
4178 && (mKernelPositionOnStandby
4179 != mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL])))) {
Eric Laurent19952e12023-04-20 10:08:29 +02004180 mHalStarted = true;
Andy Hungc5007f82023-08-29 14:26:09 -07004181 mWaitHalStartCV.notify_all();
Eric Laurent19952e12023-04-20 10:08:29 +02004182 }
Andy Hungc5007f82023-08-29 14:26:09 -07004183 } // mutex() scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08004184
Eric Laurentbfb1b832013-01-07 09:53:42 -08004185 if (mBytesRemaining == 0) {
4186 mCurrentWriteLength = 0;
4187 if (mMixerStatus == MIXER_TRACKS_READY) {
4188 // threadLoop_mix() sets mCurrentWriteLength
4189 threadLoop_mix();
4190 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
4191 && (mMixerStatus != MIXER_DRAIN_ALL)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004192 // threadLoop_sleepTime sets mSleepTimeUs to 0 if data
Eric Laurentbfb1b832013-01-07 09:53:42 -08004193 // must be written to HAL
4194 threadLoop_sleepTime();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004195 if (mSleepTimeUs == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08004196 mCurrentWriteLength = mSinkBufferSize;
Andy Hungc1646382019-04-30 16:12:10 -07004197
4198 // Tally underrun frames as we are inserting 0s here.
4199 for (const auto& track : activeTracks) {
Andy Hung8d31fd22023-06-26 19:20:57 -07004200 if (track->fillingStatus() == IAfTrack::FS_ACTIVE
Andy Hunge2e830f2019-12-03 12:54:46 -08004201 && !track->isStopped()
4202 && !track->isPaused()
4203 && !track->isTerminated()) {
4204 ALOGV("%s: track(%d) %s underrun due to thread sleep of %zu frames",
4205 __func__, track->id(), track->getTrackStateAsString(),
4206 mNormalFrameCount);
Andy Hung8d31fd22023-06-26 19:20:57 -07004207 track->audioTrackServerProxy()->tallyUnderrunFrames(
4208 mNormalFrameCount);
Andy Hungc1646382019-04-30 16:12:10 -07004209 }
4210 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004211 }
4212 }
Andy Hung98ef9782014-03-04 14:46:50 -08004213 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004214 // mMixerBuffer with data if mMixerBufferValid is true and mSleepTimeUs == 0.
Andy Hung98ef9782014-03-04 14:46:50 -08004215 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
jiabinc658e452022-10-21 20:52:21 +00004216 // or mSinkBuffer (if there are no effects and there is no data already copied to
4217 // mSinkBuffer).
Andy Hung98ef9782014-03-04 14:46:50 -08004218 //
4219 // This is done pre-effects computation; if effects change to
4220 // support higher precision, this needs to move.
4221 //
4222 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004223 // TODO use mSleepTimeUs == 0 as an additional condition.
Eric Laurent39095982021-08-24 18:29:27 +02004224 uint32_t mixerChannelCount = mEffectBufferValid ?
4225 audio_channel_count_from_out_mask(mMixerChannelMask) : mChannelCount;
jiabinc658e452022-10-21 20:52:21 +00004226 if (mMixerBufferValid && (mEffectBufferValid || !mHasDataCopiedToSinkBuffer)) {
Andy Hung98ef9782014-03-04 14:46:50 -08004227 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
4228 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
4229
David Li88ee0902022-06-22 10:01:21 +08004230 // Apply mono blending and balancing if the effect buffer is not valid. Otherwise,
4231 // do these processes after effects are applied.
4232 if (!mEffectBufferValid) {
4233 // mono blend occurs for mixer threads only (not direct or offloaded)
4234 // and is handled here if we're going directly to the sink.
4235 if (requireMonoBlend()) {
4236 mono_blend(mMixerBuffer, mMixerBufferFormat, mChannelCount,
4237 mNormalFrameCount, true /*limit*/);
4238 }
Andy Hung2ddee192015-12-18 17:34:44 -08004239
David Li88ee0902022-06-22 10:01:21 +08004240 if (!hasFastMixer()) {
4241 // Balance must take effect after mono conversion.
4242 // We do it here if there is no FastMixer.
4243 // mBalance detects zero balance within the class for speed
4244 // (not needed here).
4245 mBalance.setBalance(mMasterBalance.load());
4246 mBalance.process((float *)mMixerBuffer, mNormalFrameCount);
4247 }
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01004248 }
4249
Andy Hung98ef9782014-03-04 14:46:50 -08004250 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
Eric Laurent39095982021-08-24 18:29:27 +02004251 mNormalFrameCount * (mixerChannelCount + mHapticChannelCount));
jiabin245cdd92018-12-07 17:55:15 -08004252
4253 // If we're going directly to the sink and there are haptic channels,
4254 // we should adjust channels as the sample data is partially interleaved
4255 // in this case.
4256 if (!mEffectBufferValid && mHapticChannelCount > 0) {
4257 adjust_channels_non_destructive(buffer, mChannelCount, buffer,
4258 mChannelCount + mHapticChannelCount,
4259 audio_bytes_per_sample(format),
4260 audio_bytes_per_frame(mChannelCount, format) * mNormalFrameCount);
4261 }
Andy Hung98ef9782014-03-04 14:46:50 -08004262 }
4263
Eric Laurentbfb1b832013-01-07 09:53:42 -08004264 mBytesRemaining = mCurrentWriteLength;
4265 if (isSuspended()) {
Andy Hung238fa3d2016-07-28 10:53:22 -07004266 // Simulate write to HAL when suspended (e.g. BT SCO phone call).
4267 mSleepTimeUs = suspendSleepTimeUs(); // assumes full buffer.
4268 const size_t framesRemaining = mBytesRemaining / mFrameSize;
4269 mBytesWritten += mBytesRemaining;
4270 mFramesWritten += framesRemaining;
4271 mSuspendedFrames += framesRemaining; // to adjust kernel HAL position
Eric Laurentbfb1b832013-01-07 09:53:42 -08004272 mBytesRemaining = 0;
4273 }
Eric Laurent81784c32012-11-19 14:55:58 -08004274
Eric Laurentbfb1b832013-01-07 09:53:42 -08004275 // only process effects if we're going to write
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004276 if (mSleepTimeUs == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004277 for (size_t i = 0; i < effectChains.size(); i ++) {
4278 effectChains[i]->process_l();
jiabin47affe52019-04-04 18:02:07 -07004279 // TODO: Write haptic data directly to sink buffer when mixing.
Andy Hung6e6a2e62019-04-30 16:38:41 -07004280 if (activeHapticSessionId != AUDIO_SESSION_NONE
4281 && activeHapticSessionId == effectChains[i]->sessionId()) {
jiabin47affe52019-04-04 18:02:07 -07004282 // Haptic data is active in this case, copy it directly from
4283 // in buffer to out buffer.
Eric Laurentb62d0362021-10-26 17:40:18 +02004284 uint32_t hapticSessionChannelCount = mEffectBufferValid ?
4285 audio_channel_count_from_out_mask(mMixerChannelMask) :
4286 mChannelCount;
4287 if (mType == SPATIALIZER && !isHapticSessionSpatialized) {
4288 hapticSessionChannelCount = mChannelCount;
4289 }
4290
jiabin47affe52019-04-04 18:02:07 -07004291 const size_t audioBufferSize = mNormalFrameCount
Eric Laurentb62d0362021-10-26 17:40:18 +02004292 * audio_bytes_per_frame(hapticSessionChannelCount,
Andy Hung319587b2023-05-23 14:01:03 -07004293 AUDIO_FORMAT_PCM_FLOAT);
jiabin47affe52019-04-04 18:02:07 -07004294 memcpy_by_audio_format(
4295 (uint8_t*)effectChains[i]->outBuffer() + audioBufferSize,
Andy Hung319587b2023-05-23 14:01:03 -07004296 AUDIO_FORMAT_PCM_FLOAT,
jiabin47affe52019-04-04 18:02:07 -07004297 (const uint8_t*)effectChains[i]->inBuffer() + audioBufferSize,
Andy Hung319587b2023-05-23 14:01:03 -07004298 AUDIO_FORMAT_PCM_FLOAT, mNormalFrameCount * mHapticChannelCount);
jiabin47affe52019-04-04 18:02:07 -07004299 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004300 }
Eric Laurent81784c32012-11-19 14:55:58 -08004301 }
4302 }
Eric Laurent59fe0102013-09-27 18:48:26 -07004303 // Process effect chains for offloaded thread even if no audio
4304 // was read from audio track: process only updates effect state
4305 // and thus does have to be synchronized with audio writes but may have
4306 // to be called while waiting for async write callback
4307 if (mType == OFFLOAD) {
4308 for (size_t i = 0; i < effectChains.size(); i ++) {
4309 effectChains[i]->process_l();
4310 }
4311 }
Eric Laurent81784c32012-11-19 14:55:58 -08004312
Andy Hung98ef9782014-03-04 14:46:50 -08004313 // Only if the Effects buffer is enabled and there is data in the
4314 // Effects buffer (buffer valid), we need to
4315 // copy into the sink buffer.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004316 // TODO use mSleepTimeUs == 0 as an additional condition.
jiabinc658e452022-10-21 20:52:21 +00004317 if (mEffectBufferValid && !mHasDataCopiedToSinkBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08004318 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
Eric Laurentb62d0362021-10-26 17:40:18 +02004319 void *effectBuffer = (mType == SPATIALIZER) ? mPostSpatializerBuffer : mEffectBuffer;
Andy Hung2ddee192015-12-18 17:34:44 -08004320 if (requireMonoBlend()) {
Eric Laurentb62d0362021-10-26 17:40:18 +02004321 mono_blend(effectBuffer, mEffectBufferFormat, mChannelCount, mNormalFrameCount,
Glenn Kasten03c48d52016-01-27 17:25:17 -08004322 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08004323 }
4324
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01004325 if (!hasFastMixer()) {
4326 // Balance must take effect after mono conversion.
4327 // We do it here if there is no FastMixer.
4328 // mBalance detects zero balance within the class for speed (not needed here).
4329 mBalance.setBalance(mMasterBalance.load());
Eric Laurentb62d0362021-10-26 17:40:18 +02004330 mBalance.process((float *)effectBuffer, mNormalFrameCount);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01004331 }
4332
Eric Laurentb62d0362021-10-26 17:40:18 +02004333 // for SPATIALIZER thread, Move haptics channels from mEffectBuffer to
4334 // mPostSpatializerBuffer if the haptics track is spatialized.
4335 // Otherwise, the haptics channels are already in mPostSpatializerBuffer.
4336 // For other thread types, the haptics channels are already in mEffectBuffer.
4337 if (mType == SPATIALIZER && isHapticSessionSpatialized) {
4338 const size_t srcBufferSize = mNormalFrameCount *
4339 audio_bytes_per_frame(audio_channel_count_from_out_mask(mMixerChannelMask),
4340 mEffectBufferFormat);
4341 const size_t dstBufferSize = mNormalFrameCount
4342 * audio_bytes_per_frame(mChannelCount, mEffectBufferFormat);
4343
4344 memcpy_by_audio_format((uint8_t*)mPostSpatializerBuffer + dstBufferSize,
4345 mEffectBufferFormat,
4346 (uint8_t*)mEffectBuffer + srcBufferSize,
4347 mEffectBufferFormat,
4348 mNormalFrameCount * mHapticChannelCount);
Eric Laurent39095982021-08-24 18:29:27 +02004349 }
Atneya Nairba9a1072022-09-19 17:51:37 -07004350 const size_t framesToCopy = mNormalFrameCount * (mChannelCount + mHapticChannelCount);
4351 if (mFormat == AUDIO_FORMAT_PCM_FLOAT &&
4352 mEffectBufferFormat == AUDIO_FORMAT_PCM_FLOAT) {
4353 // Clamp PCM float values more than this distance from 0 to insulate
4354 // a HAL which doesn't handle NaN correctly.
4355 static constexpr float HAL_FLOAT_SAMPLE_LIMIT = 2.0f;
4356 memcpy_to_float_from_float_with_clamping(static_cast<float*>(mSinkBuffer),
4357 static_cast<const float*>(effectBuffer),
4358 framesToCopy, HAL_FLOAT_SAMPLE_LIMIT /* absMax */);
4359 } else {
4360 memcpy_by_audio_format(mSinkBuffer, mFormat,
4361 effectBuffer, mEffectBufferFormat, framesToCopy);
4362 }
jiabin245cdd92018-12-07 17:55:15 -08004363 // The sample data is partially interleaved when haptic channels exist,
4364 // we need to adjust channels here.
4365 if (mHapticChannelCount > 0) {
4366 adjust_channels_non_destructive(mSinkBuffer, mChannelCount, mSinkBuffer,
4367 mChannelCount + mHapticChannelCount,
4368 audio_bytes_per_sample(mFormat),
4369 audio_bytes_per_frame(mChannelCount, mFormat) * mNormalFrameCount);
4370 }
Andy Hung98ef9782014-03-04 14:46:50 -08004371 }
4372
Eric Laurent81784c32012-11-19 14:55:58 -08004373 // enable changes in effect chain
4374 unlockEffectChains(effectChains);
4375
Vlad Popafce10862023-02-03 10:37:07 +01004376 if (!metadataUpdate.playbackMetadataUpdate.empty()) {
Andy Hung583043b2023-07-17 17:05:00 -07004377 mAfThreadCallback->getMelReporter()->updateMetadataForCsd(id(),
Vlad Popafce10862023-02-03 10:37:07 +01004378 metadataUpdate.playbackMetadataUpdate);
4379 }
4380
Eric Laurentbfb1b832013-01-07 09:53:42 -08004381 if (!waitingAsyncCallback()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004382 // mSleepTimeUs == 0 means we must write to audio hardware
4383 if (mSleepTimeUs == 0) {
Andy Hung08fb1742015-05-31 23:22:10 -07004384 ssize_t ret = 0;
Andy Hung446f4df2019-02-21 12:26:41 -08004385 // writePeriodNs is updated >= 0 when ret > 0.
4386 int64_t writePeriodNs = -1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004387 if (mBytesRemaining) {
Andy Hung69488c42016-05-16 18:43:33 -07004388 // FIXME rewrite to reduce number of system calls
Andy Hung446f4df2019-02-21 12:26:41 -08004389 const int64_t lastIoBeginNs = systemTime();
Andy Hung08fb1742015-05-31 23:22:10 -07004390 ret = threadLoop_write();
Andy Hung446f4df2019-02-21 12:26:41 -08004391 const int64_t lastIoEndNs = systemTime();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004392 if (ret < 0) {
4393 mBytesRemaining = 0;
Andy Hung446f4df2019-02-21 12:26:41 -08004394 } else if (ret > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004395 mBytesWritten += ret;
4396 mBytesRemaining -= ret;
Andy Hung446f4df2019-02-21 12:26:41 -08004397 const int64_t frames = ret / mFrameSize;
4398 mFramesWritten += frames;
4399
4400 writePeriodNs = lastIoEndNs - mLastIoEndNs;
4401 // process information relating to write time.
4402 if (audio_has_proportional_frames(mFormat)) {
4403 // we are in a continuous mixing cycle
4404 if (mMixerStatus == MIXER_TRACKS_READY &&
4405 loopCount == lastLoopCountWritten + 1) {
4406
4407 const double jitterMs =
4408 TimestampVerifier<int64_t, int64_t>::computeJitterMs(
4409 {frames, writePeriodNs},
4410 {0, 0} /* lastTimestamp */, mSampleRate);
4411 const double processMs =
4412 (lastIoBeginNs - mLastIoEndNs) * 1e-6;
4413
Andy Hung972bec12023-08-31 16:13:39 -07004414 audio_utils::lock_guard _l(mutex());
Andy Hung446f4df2019-02-21 12:26:41 -08004415 mIoJitterMs.add(jitterMs);
4416 mProcessTimeMs.add(processMs);
Robert Wu06db0a32021-08-10 19:05:34 +00004417
4418 if (mPipeSink.get() != nullptr) {
4419 // Using the Monopipe availableToWrite, we estimate the current
4420 // buffer size.
4421 MonoPipe* monoPipe = static_cast<MonoPipe*>(mPipeSink.get());
4422 const ssize_t
4423 availableToWrite = mPipeSink->availableToWrite();
4424 const size_t pipeFrames = monoPipe->maxFrames();
4425 const size_t
4426 remainingFrames = pipeFrames - max(availableToWrite, 0);
4427 mMonopipePipeDepthStats.add(remainingFrames);
4428 }
Andy Hung446f4df2019-02-21 12:26:41 -08004429 }
4430
4431 // write blocked detection
4432 const int64_t deltaWriteNs = lastIoEndNs - lastIoBeginNs;
Andy Hungd3639922022-04-28 18:00:49 -07004433 if ((mType == MIXER || mType == SPATIALIZER)
4434 && deltaWriteNs > maxPeriod) {
Andy Hung446f4df2019-02-21 12:26:41 -08004435 mNumDelayedWrites++;
4436 if ((lastIoEndNs - lastWarning) > kWarningThrottleNs) {
4437 ATRACE_NAME("underrun");
4438 ALOGW("write blocked for %lld msecs, "
4439 "%d delayed writes, thread %d",
4440 (long long)deltaWriteNs / NANOS_PER_MILLISECOND,
4441 mNumDelayedWrites, mId);
4442 lastWarning = lastIoEndNs;
4443 }
4444 }
4445 }
4446 // update timing info.
4447 mLastIoBeginNs = lastIoBeginNs;
4448 mLastIoEndNs = lastIoEndNs;
4449 lastLoopCountWritten = loopCount;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004450 }
4451 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
4452 (mMixerStatus == MIXER_DRAIN_ALL)) {
4453 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08004454 }
Andy Hungd3639922022-04-28 18:00:49 -07004455 if ((mType == MIXER || mType == SPATIALIZER) && !mStandby) {
Andy Hung08fb1742015-05-31 23:22:10 -07004456
4457 if (mThreadThrottle
4458 && mMixerStatus == MIXER_TRACKS_READY // we are mixing (active tracks)
Andy Hung446f4df2019-02-21 12:26:41 -08004459 && writePeriodNs > 0) { // we have write period info
Andy Hung08fb1742015-05-31 23:22:10 -07004460 // Limit MixerThread data processing to no more than twice the
4461 // expected processing rate.
4462 //
4463 // This helps prevent underruns with NuPlayer and other applications
4464 // which may set up buffers that are close to the minimum size, or use
4465 // deep buffers, and rely on a double-buffering sleep strategy to fill.
4466 //
4467 // The throttle smooths out sudden large data drains from the device,
4468 // e.g. when it comes out of standby, which often causes problems with
4469 // (1) mixer threads without a fast mixer (which has its own warm-up)
4470 // (2) minimum buffer sized tracks (even if the track is full,
4471 // the app won't fill fast enough to handle the sudden draw).
Haynes Mathew Georgef92b2172016-05-09 11:34:15 -07004472 //
4473 // Total time spent in last processing cycle equals time spent in
4474 // 1. threadLoop_write, as well as time spent in
4475 // 2. threadLoop_mix (significant for heavy mixing, especially
4476 // on low tier processors)
Andy Hung08fb1742015-05-31 23:22:10 -07004477
Andy Hung446f4df2019-02-21 12:26:41 -08004478 // it's OK if deltaMs is an overestimate.
4479
4480 const int32_t deltaMs = writePeriodNs / NANOS_PER_MILLISECOND;
Ivan Lozanoe02bc542017-10-26 09:51:54 -07004481
Ivan Lozanoea04d392017-11-07 14:37:07 -08004482 const int32_t throttleMs = (int32_t)mHalfBufferMs - deltaMs;
Andy Hung08fb1742015-05-31 23:22:10 -07004483 if ((signed)mHalfBufferMs >= throttleMs && throttleMs > 0) {
Andy Hungcf10d742020-04-28 15:38:24 -07004484 mThreadMetrics.logThrottleMs((double)throttleMs);
Andy Hungb68f5eb2019-12-03 16:49:17 -08004485
Andy Hung08fb1742015-05-31 23:22:10 -07004486 usleep(throttleMs * 1000);
Andy Hung40eb1a12015-06-18 13:42:02 -07004487 // notify of throttle start on verbose log
4488 ALOGV_IF(mThreadThrottleEndMs == mThreadThrottleTimeMs,
4489 "mixer(%p) throttle begin:"
4490 " ret(%zd) deltaMs(%d) requires sleep %d ms",
Andy Hung08fb1742015-05-31 23:22:10 -07004491 this, ret, deltaMs, throttleMs);
Andy Hung40eb1a12015-06-18 13:42:02 -07004492 mThreadThrottleTimeMs += throttleMs;
Andy Hung0a31ddd2016-07-06 19:10:29 -07004493 // Throttle must be attributed to the previous mixer loop's write time
4494 // to allow back-to-back throttling.
Andy Hung446f4df2019-02-21 12:26:41 -08004495 // This also ensures proper timing statistics.
4496 mLastIoEndNs = systemTime(); // we fetch the write end time again.
Andy Hung40eb1a12015-06-18 13:42:02 -07004497 } else {
4498 uint32_t diff = mThreadThrottleTimeMs - mThreadThrottleEndMs;
4499 if (diff > 0) {
4500 // notify of throttle end on debug log
Andy Hung3ea004d2016-05-05 16:48:37 -07004501 // but prevent spamming for bluetooth
jiabinc52b1ff2019-10-31 17:20:42 -07004502 ALOGD_IF(!isSingleDeviceType(
Andy Hungab65b182023-09-06 19:41:47 -07004503 outDeviceTypes_l(), audio_is_a2dp_out_device) &&
jiabinc52b1ff2019-10-31 17:20:42 -07004504 !isSingleDeviceType(
Andy Hungab65b182023-09-06 19:41:47 -07004505 outDeviceTypes_l(),
4506 audio_is_hearing_aid_out_device),
Andy Hung3ea004d2016-05-05 16:48:37 -07004507 "mixer(%p) throttle end: throttle time(%u)", this, diff);
Andy Hung40eb1a12015-06-18 13:42:02 -07004508 mThreadThrottleEndMs = mThreadThrottleTimeMs;
4509 }
Andy Hung08fb1742015-05-31 23:22:10 -07004510 }
4511 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004512 }
Eric Laurent81784c32012-11-19 14:55:58 -08004513
Eric Laurentbfb1b832013-01-07 09:53:42 -08004514 } else {
Glenn Kastene7754022014-10-31 12:11:26 -07004515 ATRACE_BEGIN("sleep");
Andy Hungc5007f82023-08-29 14:26:09 -07004516 audio_utils::unique_lock _l(mutex());
rago1bb90822017-05-02 18:31:48 -07004517 // suspended requires accurate metering of sleep time.
4518 if (isSuspended()) {
4519 // advance by expected sleepTime
4520 timeLoopNextNs += microseconds((nsecs_t)mSleepTimeUs);
4521 const nsecs_t nowNs = systemTime();
4522
4523 // compute expected next time vs current time.
4524 // (negative deltas are treated as delays).
4525 nsecs_t deltaNs = timeLoopNextNs - nowNs;
4526 if (deltaNs < -kMaxNextBufferDelayNs) {
4527 // Delays longer than the max allowed trigger a reset.
4528 ALOGV("DelayNs: %lld, resetting timeLoopNextNs", (long long) deltaNs);
4529 deltaNs = microseconds((nsecs_t)mSleepTimeUs);
4530 timeLoopNextNs = nowNs + deltaNs;
4531 } else if (deltaNs < 0) {
4532 // Delays within the max delay allowed: zero the delta/sleepTime
4533 // to help the system catch up in the next iteration(s)
4534 ALOGV("DelayNs: %lld, catching-up", (long long) deltaNs);
4535 deltaNs = 0;
4536 }
4537 // update sleep time (which is >= 0)
4538 mSleepTimeUs = deltaNs / 1000;
4539 }
Eric Laurente93cc032016-05-05 10:15:10 -07004540 if (!mSignalPending && mConfigEvents.isEmpty() && !exitPending()) {
Andy Hungc5007f82023-08-29 14:26:09 -07004541 mWaitWorkCV.wait_for(_l, std::chrono::microseconds(mSleepTimeUs));
Eric Laurent51716182016-02-29 18:00:56 -08004542 }
Glenn Kastene7754022014-10-31 12:11:26 -07004543 ATRACE_END();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004544 }
Eric Laurent81784c32012-11-19 14:55:58 -08004545 }
4546
4547 // Finally let go of removed track(s), without the lock held
4548 // since we can't guarantee the destructors won't acquire that
4549 // same lock. This will also mutate and push a new fast mixer state.
4550 threadLoop_removeTracks(tracksToRemove);
4551 tracksToRemove.clear();
4552
4553 // FIXME I don't understand the need for this here;
4554 // it was in the original code but maybe the
4555 // assignment in saveOutputTracks() makes this unnecessary?
4556 clearOutputTracks();
4557
4558 // Effect chains will be actually deleted here if they were removed from
4559 // mEffectChains list during mixing or effects processing
4560 effectChains.clear();
4561
4562 // FIXME Note that the above .clear() is no longer necessary since effectChains
4563 // is now local to this block, but will keep it for now (at least until merge done).
4564 }
4565
Eric Laurentbfb1b832013-01-07 09:53:42 -08004566 threadLoop_exit();
4567
Eric Laurentcf817a22014-08-04 20:36:31 -07004568 if (!mStandby) {
4569 threadLoop_standby();
Eric Laurent19952e12023-04-20 10:08:29 +02004570 setStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08004571 }
4572
4573 releaseWakeLock();
4574
4575 ALOGV("Thread %p type %d exiting", this, mType);
4576 return false;
4577}
4578
Andy Hungee58e4a2023-07-07 13:47:37 -07004579void PlaybackThread::collectTimestamps_l()
Dean Wheatley12473e92021-03-18 23:00:55 +11004580{
Dean Wheatley12473e92021-03-18 23:00:55 +11004581 if (mStandby) {
4582 mTimestampVerifier.discontinuity(discontinuityForStandbyOrFlush());
4583 return;
4584 } else if (mHwPaused) {
4585 mTimestampVerifier.discontinuity(mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS);
4586 return;
4587 }
4588
4589 // Gather the framesReleased counters for all active tracks,
4590 // and associate with the sink frames written out. We need
4591 // this to convert the sink timestamp to the track timestamp.
4592 bool kernelLocationUpdate = false;
4593 ExtendedTimestamp timestamp; // use private copy to fetch
4594
4595 // Always query HAL timestamp and update timestamp verifier. In standby or pause,
4596 // HAL may be draining some small duration buffered data for fade out.
4597 if (threadloop_getHalTimestamp_l(&timestamp) == OK) {
4598 mTimestampVerifier.add(timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL],
4599 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4600 mSampleRate);
4601
Andy Hungab65b182023-09-06 19:41:47 -07004602 if (isTimestampCorrectionEnabled_l()) {
Dean Wheatley12473e92021-03-18 23:00:55 +11004603 ALOGVV("TS_BEFORE: %d %lld %lld", id(),
4604 (long long)timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4605 (long long)timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]);
4606 auto correctedTimestamp = mTimestampVerifier.getLastCorrectedTimestamp();
4607 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4608 = correctedTimestamp.mFrames;
4609 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]
4610 = correctedTimestamp.mTimeNs;
4611 ALOGVV("TS_AFTER: %d %lld %lld", id(),
4612 (long long)timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4613 (long long)timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]);
4614
4615 // Note: Downstream latency only added if timestamp correction enabled.
4616 if (mDownstreamLatencyStatMs.getN() > 0) { // we have latency info.
4617 const int64_t newPosition =
4618 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4619 - int64_t(mDownstreamLatencyStatMs.getMean() * mSampleRate * 1e-3);
4620 // prevent retrograde
4621 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = max(
4622 newPosition,
4623 (mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4624 - mSuspendedFrames));
4625 }
4626 }
4627
4628 // We always fetch the timestamp here because often the downstream
4629 // sink will block while writing.
4630
4631 // We keep track of the last valid kernel position in case we are in underrun
4632 // and the normal mixer period is the same as the fast mixer period, or there
4633 // is some error from the HAL.
4634 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
4635 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
4636 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
4637 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
4638 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4639
4640 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
4641 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER];
4642 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
4643 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER];
4644 }
4645
4646 if (timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
4647 kernelLocationUpdate = true;
4648 } else {
4649 ALOGVV("getTimestamp error - no valid kernel position");
4650 }
4651
4652 // copy over kernel info
4653 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] =
4654 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4655 + mSuspendedFrames; // add frames discarded when suspended
4656 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] =
4657 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4658 } else {
4659 mTimestampVerifier.error();
4660 }
4661
4662 // mFramesWritten for non-offloaded tracks are contiguous
4663 // even after standby() is called. This is useful for the track frame
4664 // to sink frame mapping.
4665 bool serverLocationUpdate = false;
4666 if (mFramesWritten != mLastFramesWritten) {
4667 serverLocationUpdate = true;
4668 mLastFramesWritten = mFramesWritten;
4669 }
4670 // Only update timestamps if there is a meaningful change.
4671 // Either the kernel timestamp must be valid or we have written something.
4672 if (kernelLocationUpdate || serverLocationUpdate) {
4673 if (serverLocationUpdate) {
4674 // use the time before we called the HAL write - it is a bit more accurate
4675 // to when the server last read data than the current time here.
4676 //
4677 // If we haven't written anything, mLastIoBeginNs will be -1
4678 // and we use systemTime().
4679 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] = mFramesWritten;
4680 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = mLastIoBeginNs == -1
Andy Hung8d672e02023-09-15 18:19:28 -07004681 ? systemTime() : (int64_t)mLastIoBeginNs;
Dean Wheatley12473e92021-03-18 23:00:55 +11004682 }
4683
Andy Hung8d31fd22023-06-26 19:20:57 -07004684 for (const sp<IAfTrack>& t : mActiveTracks) {
Dean Wheatley12473e92021-03-18 23:00:55 +11004685 if (!t->isFastTrack()) {
4686 t->updateTrackFrameInfo(
Andy Hung8d31fd22023-06-26 19:20:57 -07004687 t->audioTrackServerProxy()->framesReleased(),
Dean Wheatley12473e92021-03-18 23:00:55 +11004688 mFramesWritten,
4689 mSampleRate,
4690 mTimestamp);
4691 }
4692 }
4693 }
4694
4695 if (audio_has_proportional_frames(mFormat)) {
4696 const double latencyMs = mTimestamp.getOutputServerLatencyMs(mSampleRate);
4697 if (latencyMs != 0.) { // note 0. means timestamp is empty.
4698 mLatencyMs.add(latencyMs);
4699 }
4700 }
4701#if 0
4702 // logFormat example
4703 if (z % 100 == 0) {
4704 timespec ts;
4705 clock_gettime(CLOCK_MONOTONIC, &ts);
4706 LOGT("This is an integer %d, this is a float %f, this is my "
4707 "pid %p %% %s %t", 42, 3.14, "and this is a timestamp", ts);
4708 LOGT("A deceptive null-terminated string %\0");
4709 }
4710 ++z;
4711#endif
4712}
4713
Andy Hungc5007f82023-08-29 14:26:09 -07004714// removeTracks_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07004715void PlaybackThread::removeTracks_l(const Vector<sp<IAfTrack>>& tracksToRemove)
Andy Hungc5007f82023-08-29 14:26:09 -07004716NO_THREAD_SAFETY_ANALYSIS // release and re-acquire mutex()
Eric Laurentbfb1b832013-01-07 09:53:42 -08004717{
Andy Hungfe726a62018-09-27 15:17:25 -07004718 for (const auto& track : tracksToRemove) {
4719 mActiveTracks.remove(track);
4720 ALOGV("%s(%d): removing track on session %d", __func__, track->id(), track->sessionId());
Andy Hung116bc262023-06-20 18:56:17 -07004721 sp<IAfEffectChain> chain = getEffectChain_l(track->sessionId());
Andy Hungfe726a62018-09-27 15:17:25 -07004722 if (chain != 0) {
4723 ALOGV("%s(%d): stopping track on chain %p for session Id: %d",
4724 __func__, track->id(), chain.get(), track->sessionId());
4725 chain->decActiveTrackCnt();
4726 }
4727 // If an external client track, inform APM we're no longer active, and remove if needed.
4728 // We do this under lock so that the state is consistent if the Track is destroyed.
4729 if (track->isExternalTrack()) {
4730 AudioSystem::stopOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08004731 if (track->isTerminated()) {
Andy Hungfe726a62018-09-27 15:17:25 -07004732 AudioSystem::releaseOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08004733 }
4734 }
Andy Hungfe726a62018-09-27 15:17:25 -07004735 if (track->isTerminated()) {
4736 // remove from our tracks vector
4737 removeTrack_l(track);
4738 }
jiabineb3bda02020-06-30 14:07:03 -07004739 if (mHapticChannelCount > 0 &&
4740 ((track->channelMask() & AUDIO_CHANNEL_HAPTIC_ALL) != AUDIO_CHANNEL_NONE
4741 || (chain != nullptr && chain->containsHapticGeneratingEffect_l()))) {
Andy Hungc5007f82023-08-29 14:26:09 -07004742 mutex().unlock();
jiabin57303cc2018-12-18 15:45:57 -08004743 // Unlock due to VibratorService will lock for this call and will
4744 // call Tracks.mute/unmute which also require thread's lock.
Andy Hung7fb97e12023-07-20 21:23:42 -07004745 afutils::onExternalVibrationStop(track->getExternalVibration());
Andy Hungc5007f82023-08-29 14:26:09 -07004746 mutex().lock();
jiabine70bc7f2020-06-30 22:07:55 -07004747
4748 // When the track is stop, set the haptic intensity as MUTE
4749 // for the HapticGenerator effect.
4750 if (chain != nullptr) {
Simon Bowden62823412022-10-17 14:52:26 +00004751 chain->setHapticIntensity_l(track->id(), os::HapticScale::MUTE);
jiabine70bc7f2020-06-30 22:07:55 -07004752 }
jiabin245cdd92018-12-07 17:55:15 -08004753 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004754 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004755}
Eric Laurent81784c32012-11-19 14:55:58 -08004756
Andy Hungee58e4a2023-07-07 13:47:37 -07004757status_t PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
Eric Laurentaccc1472013-09-20 09:36:34 -07004758{
4759 if (mNormalSink != 0) {
Andy Hung818e7a32016-02-16 18:08:07 -08004760 ExtendedTimestamp ets;
4761 status_t status = mNormalSink->getTimestamp(ets);
4762 if (status == NO_ERROR) {
4763 status = ets.getBestTimestamp(&timestamp);
4764 }
4765 return status;
Eric Laurentaccc1472013-09-20 09:36:34 -07004766 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004767 if ((mType == OFFLOAD || mType == DIRECT) && mOutput != NULL) {
Dean Wheatley12473e92021-03-18 23:00:55 +11004768 collectTimestamps_l();
4769 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] <= 0) {
4770 return INVALID_OPERATION;
Eric Laurentaccc1472013-09-20 09:36:34 -07004771 }
Dean Wheatley12473e92021-03-18 23:00:55 +11004772 timestamp.mPosition = mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
4773 const int64_t timeNs = mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4774 timestamp.mTime.tv_sec = timeNs / NANOS_PER_SECOND;
4775 timestamp.mTime.tv_nsec = timeNs - (timestamp.mTime.tv_sec * NANOS_PER_SECOND);
4776 return NO_ERROR;
Eric Laurentaccc1472013-09-20 09:36:34 -07004777 }
4778 return INVALID_OPERATION;
4779}
Eric Laurent1c333e22014-05-20 10:48:17 -07004780
Eric Laurenteab90452019-06-24 15:17:46 -07004781// For dedicated VoIP outputs, let the HAL apply the stream volume. Track volume is
4782// still applied by the mixer.
4783// All tracks attached to a mixer with flag VOIP_RX are tied to the same
4784// stream type STREAM_VOICE_CALL so this will only change the HAL volume once even
4785// if more than one track are active
Andy Hungee58e4a2023-07-07 13:47:37 -07004786status_t PlaybackThread::handleVoipVolume_l(float* volume)
Eric Laurenteab90452019-06-24 15:17:46 -07004787{
4788 status_t result = NO_ERROR;
4789 if ((mOutput->flags & AUDIO_OUTPUT_FLAG_VOIP_RX) != 0) {
4790 if (*volume != mLeftVolFloat) {
4791 result = mOutput->stream->setVolume(*volume, *volume);
Alex Leungc5dedb22023-05-10 08:00:50 -07004792 // HAL can return INVALID_OPERATION if operation is not supported.
4793 ALOGE_IF(result != OK && result != INVALID_OPERATION,
Eric Laurenteab90452019-06-24 15:17:46 -07004794 "Error when setting output stream volume: %d", result);
4795 if (result == NO_ERROR) {
4796 mLeftVolFloat = *volume;
4797 }
4798 }
4799 // if stream volume was successfully sent to the HAL, mLeftVolFloat == v here and we
4800 // remove stream volume contribution from software volume.
4801 if (mLeftVolFloat == *volume) {
4802 *volume = 1.0f;
4803 }
4804 }
4805 return result;
4806}
4807
Andy Hungee58e4a2023-07-07 13:47:37 -07004808status_t MixerThread::createAudioPatch_l(const struct audio_patch* patch,
Eric Laurent054d9d32015-04-24 08:48:48 -07004809 audio_patch_handle_t *handle)
4810{
Andy Hungf60abce2016-08-26 11:37:54 -07004811 status_t status;
4812 if (property_get_bool("af.patch_park", false /* default_value */)) {
4813 // Park FastMixer to avoid potential DOS issues with writing to the HAL
4814 // or if HAL does not properly lock against access.
4815 AutoPark<FastMixer> park(mFastMixer);
4816 status = PlaybackThread::createAudioPatch_l(patch, handle);
4817 } else {
4818 status = PlaybackThread::createAudioPatch_l(patch, handle);
4819 }
Eric Laurentb0463942022-12-20 16:31:10 +01004820
4821 updateHalSupportedLatencyModes_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07004822 return status;
4823}
4824
Andy Hungee58e4a2023-07-07 13:47:37 -07004825status_t PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
Eric Laurent1c333e22014-05-20 10:48:17 -07004826 audio_patch_handle_t *handle)
4827{
4828 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07004829
4830 // store new device and send to effects
4831 audio_devices_t type = AUDIO_DEVICE_NONE;
jiabinc52b1ff2019-10-31 17:20:42 -07004832 AudioDeviceTypeAddrVector deviceTypeAddrs;
Eric Laurent054d9d32015-04-24 08:48:48 -07004833 for (unsigned int i = 0; i < patch->num_sinks; i++) {
jiabinc52b1ff2019-10-31 17:20:42 -07004834 LOG_ALWAYS_FATAL_IF(popcount(patch->sinks[i].ext.device.type) > 1
4835 && !mOutput->audioHwDev->supportsAudioPatches(),
4836 "Enumerated device type(%#x) must not be used "
4837 "as it does not support audio patches",
4838 patch->sinks[i].ext.device.type);
Mikhail Naganov55773032020-10-01 15:08:13 -07004839 type = static_cast<audio_devices_t>(type | patch->sinks[i].ext.device.type);
Andy Hung920f6572022-10-06 12:09:49 -07004840 deviceTypeAddrs.emplace_back(patch->sinks[i].ext.device.type,
4841 patch->sinks[i].ext.device.address);
Eric Laurent054d9d32015-04-24 08:48:48 -07004842 }
4843
François Gaffie0c280aa2018-07-25 10:02:15 +02004844 audio_port_handle_t sinkPortId = patch->sinks[0].id;
Eric Laurent054d9d32015-04-24 08:48:48 -07004845#ifdef ADD_BATTERY_DATA
4846 // when changing the audio output device, call addBatteryData to notify
4847 // the change
jiabinc52b1ff2019-10-31 17:20:42 -07004848 if (outDeviceTypes() != deviceTypes) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004849 uint32_t params = 0;
4850 // check whether speaker is on
jiabinc52b1ff2019-10-31 17:20:42 -07004851 if (deviceTypes.count(AUDIO_DEVICE_OUT_SPEAKER) > 0) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004852 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent1c333e22014-05-20 10:48:17 -07004853 }
4854
Eric Laurent054d9d32015-04-24 08:48:48 -07004855 // check if any other device (except speaker) is on
jiabinc52b1ff2019-10-31 17:20:42 -07004856 if (!isSingleDeviceType(deviceTypes, AUDIO_DEVICE_OUT_SPEAKER)) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004857 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
4858 }
4859
4860 if (params != 0) {
4861 addBatteryData(params);
4862 }
4863 }
4864#endif
4865
4866 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08004867 mEffectChains[i]->setDevices_l(deviceTypeAddrs);
Eric Laurent054d9d32015-04-24 08:48:48 -07004868 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07004869
jiabinc52b1ff2019-10-31 17:20:42 -07004870 // mPatch.num_sinks is not set when the thread is created so that
4871 // the first patch creation triggers an ioConfigChanged callback
4872 bool configChanged = (mPatch.num_sinks == 0) ||
4873 (mPatch.sinks[0].id != sinkPortId);
Eric Laurent296fb132015-05-01 11:38:42 -07004874 mPatch = *patch;
jiabinc52b1ff2019-10-31 17:20:42 -07004875 mOutDeviceTypeAddrs = deviceTypeAddrs;
jiabin0a957d32020-04-29 10:56:20 -07004876 checkSilentMode_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07004877
Mikhail Naganov9ee05402016-10-13 15:58:17 -07004878 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07004879 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
4880 status = hwDevice->createAudioPatch(patch->num_sources,
4881 patch->sources,
4882 patch->num_sinks,
4883 patch->sinks,
4884 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07004885 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08004886 status = mOutput->stream->legacyCreateAudioPatch(patch->sinks[0], std::nullopt, type);
Eric Laurent054d9d32015-04-24 08:48:48 -07004887 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07004888 }
Andy Hungc2b11cb2020-04-22 09:04:01 -07004889 const std::string patchSinksAsString = patchSinksToString(patch);
Andy Hungcf10d742020-04-28 15:38:24 -07004890
4891 mThreadMetrics.logEndInterval();
Andy Hungea840382020-05-05 21:50:17 -07004892 mThreadMetrics.logCreatePatch(/* inDevices */ {}, patchSinksAsString);
Andy Hungcf10d742020-04-28 15:38:24 -07004893 mThreadMetrics.logBeginInterval();
Andy Hungc2b11cb2020-04-22 09:04:01 -07004894 // also dispatch to active AudioTracks for MediaMetrics
4895 for (const auto &track : mActiveTracks) {
4896 track->logEndInterval();
4897 track->logBeginInterval(patchSinksAsString);
4898 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08004899
Eric Laurente8726fe2015-06-26 09:39:24 -07004900 if (configChanged) {
4901 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
4902 }
Vlad Popa7e81cea2023-01-19 16:34:16 +01004903 // Force metadata update after a route change
Eric Laurentdda206a2022-07-08 17:28:35 +02004904 mActiveTracks.setHasChanged();
4905
Eric Laurent1c333e22014-05-20 10:48:17 -07004906 return status;
4907}
4908
Andy Hungee58e4a2023-07-07 13:47:37 -07004909status_t MixerThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
Eric Laurent054d9d32015-04-24 08:48:48 -07004910{
Andy Hungf60abce2016-08-26 11:37:54 -07004911 status_t status;
4912 if (property_get_bool("af.patch_park", false /* default_value */)) {
4913 // Park FastMixer to avoid potential DOS issues with writing to the HAL
4914 // or if HAL does not properly lock against access.
4915 AutoPark<FastMixer> park(mFastMixer);
4916 status = PlaybackThread::releaseAudioPatch_l(handle);
4917 } else {
4918 status = PlaybackThread::releaseAudioPatch_l(handle);
4919 }
Eric Laurent054d9d32015-04-24 08:48:48 -07004920 return status;
4921}
4922
Andy Hungee58e4a2023-07-07 13:47:37 -07004923status_t PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004924{
4925 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07004926
jiabinc52b1ff2019-10-31 17:20:42 -07004927 mPatch = audio_patch{};
4928 mOutDeviceTypeAddrs.clear();
Eric Laurent054d9d32015-04-24 08:48:48 -07004929
Mikhail Naganov9ee05402016-10-13 15:58:17 -07004930 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07004931 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
4932 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07004933 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08004934 status = mOutput->stream->legacyReleaseAudioPatch();
Eric Laurent1c333e22014-05-20 10:48:17 -07004935 }
Eric Laurentdda206a2022-07-08 17:28:35 +02004936 // Force meteadata update after a route change
4937 mActiveTracks.setHasChanged();
4938
Eric Laurent1c333e22014-05-20 10:48:17 -07004939 return status;
4940}
4941
Andy Hungee58e4a2023-07-07 13:47:37 -07004942void PlaybackThread::addPatchTrack(const sp<IAfPatchTrack>& track)
Eric Laurent83b88082014-06-20 18:31:16 -07004943{
Andy Hung972bec12023-08-31 16:13:39 -07004944 audio_utils::lock_guard _l(mutex());
Eric Laurent83b88082014-06-20 18:31:16 -07004945 mTracks.add(track);
4946}
4947
Andy Hungee58e4a2023-07-07 13:47:37 -07004948void PlaybackThread::deletePatchTrack(const sp<IAfPatchTrack>& track)
Eric Laurent83b88082014-06-20 18:31:16 -07004949{
Andy Hung972bec12023-08-31 16:13:39 -07004950 audio_utils::lock_guard _l(mutex());
Eric Laurent83b88082014-06-20 18:31:16 -07004951 destroyTrack_l(track);
4952}
4953
Andy Hungee58e4a2023-07-07 13:47:37 -07004954void PlaybackThread::toAudioPortConfig(struct audio_port_config* config)
Eric Laurent83b88082014-06-20 18:31:16 -07004955{
Mikhail Naganovdc769682018-05-04 15:34:08 -07004956 ThreadBase::toAudioPortConfig(config);
Eric Laurent83b88082014-06-20 18:31:16 -07004957 config->role = AUDIO_PORT_ROLE_SOURCE;
4958 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
4959 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07004960 if (mOutput && mOutput->flags != AUDIO_OUTPUT_FLAG_NONE) {
4961 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
4962 config->flags.output = mOutput->flags;
4963 }
Eric Laurent83b88082014-06-20 18:31:16 -07004964}
4965
Eric Laurent81784c32012-11-19 14:55:58 -08004966// ----------------------------------------------------------------------------
4967
Andy Hungee58e4a2023-07-07 13:47:37 -07004968/* static */
4969sp<IAfPlaybackThread> IAfPlaybackThread::createMixerThread(
Andy Hung583043b2023-07-17 17:05:00 -07004970 const sp<IAfThreadCallback>& afThreadCallback, AudioStreamOut* output,
Andy Hungee58e4a2023-07-07 13:47:37 -07004971 audio_io_handle_t id, bool systemReady, type_t type, audio_config_base_t* mixerConfig) {
Andy Hung583043b2023-07-17 17:05:00 -07004972 return sp<MixerThread>::make(afThreadCallback, output, id, systemReady, type, mixerConfig);
Andy Hungee58e4a2023-07-07 13:47:37 -07004973}
4974
Andy Hung583043b2023-07-17 17:05:00 -07004975MixerThread::MixerThread(const sp<IAfThreadCallback>& afThreadCallback, AudioStreamOut* output,
Eric Laurentf1f22e72021-07-13 14:04:14 +02004976 audio_io_handle_t id, bool systemReady, type_t type, audio_config_base_t *mixerConfig)
Andy Hung583043b2023-07-17 17:05:00 -07004977 : PlaybackThread(afThreadCallback, output, id, type, systemReady, mixerConfig),
Eric Laurent81784c32012-11-19 14:55:58 -08004978 // mAudioMixer below
4979 // mFastMixer below
Eric Laurentb0463942022-12-20 16:31:10 +01004980 mBluetoothLatencyModesEnabled(false),
Andy Hung2ddee192015-12-18 17:34:44 -08004981 mFastMixerFutex(0),
4982 mMasterMono(false)
Eric Laurent81784c32012-11-19 14:55:58 -08004983 // mOutputSink below
4984 // mPipeSink below
4985 // mNormalSink below
4986{
Andy Hung583043b2023-07-17 17:05:00 -07004987 setMasterBalance(afThreadCallback->getMasterBalance_l());
jiabinc52b1ff2019-10-31 17:20:42 -07004988 ALOGV("MixerThread() id=%d type=%d", id, type);
Glenn Kasten49f36ba2017-12-06 13:02:02 -08004989 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%#x, mFrameSize=%zu, "
Glenn Kastenc42e9b42016-03-21 11:35:03 -07004990 "mFrameCount=%zu, mNormalFrameCount=%zu",
Eric Laurent81784c32012-11-19 14:55:58 -08004991 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
4992 mNormalFrameCount);
4993 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
4994
Andy Hungfbfc3952015-01-15 13:33:51 -08004995 if (type == DUPLICATING) {
4996 // The Duplicating thread uses the AudioMixer and delivers data to OutputTracks
4997 // (downstream MixerThreads) in DuplicatingThread::threadLoop_write().
4998 // Do not create or use mFastMixer, mOutputSink, mPipeSink, or mNormalSink.
4999 return;
5000 }
Eric Laurent81784c32012-11-19 14:55:58 -08005001 // create an NBAIO sink for the HAL output stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07005002 mOutputSink = new AudioStreamOutSink(output->stream);
Eric Laurent81784c32012-11-19 14:55:58 -08005003 size_t numCounterOffers = 0;
jiabin245cdd92018-12-07 17:55:15 -08005004 const NBAIO_Format offers[1] = {Format_from_SR_C(
5005 mSampleRate, mChannelCount + mHapticChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005006#if !LOG_NDEBUG
5007 ssize_t index =
5008#else
5009 (void)
5010#endif
5011 mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08005012 ALOG_ASSERT(index == 0);
5013
5014 // initialize fast mixer depending on configuration
5015 bool initFastMixer;
jiabinc658e452022-10-21 20:52:21 +00005016 if (mType == SPATIALIZER || mType == BIT_PERFECT) {
Eric Laurent81784c32012-11-19 14:55:58 -08005017 initFastMixer = false;
Eric Laurentb62d0362021-10-26 17:40:18 +02005018 } else {
5019 switch (kUseFastMixer) {
5020 case FastMixer_Never:
5021 initFastMixer = false;
5022 break;
5023 case FastMixer_Always:
5024 initFastMixer = true;
5025 break;
5026 case FastMixer_Static:
5027 case FastMixer_Dynamic:
5028 initFastMixer = mFrameCount < mNormalFrameCount;
5029 break;
5030 }
5031 ALOGW_IF(initFastMixer == false && mFrameCount < mNormalFrameCount,
5032 "FastMixer is preferred for this sink as frameCount %zu is less than threshold %zu",
5033 mFrameCount, mNormalFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08005034 }
5035 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07005036 audio_format_t fastMixerFormat;
5037 if (mMixerBufferEnabled && mEffectBufferEnabled) {
5038 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
5039 } else {
5040 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
5041 }
5042 if (mFormat != fastMixerFormat) {
5043 // change our Sink format to accept our intermediate precision
5044 mFormat = fastMixerFormat;
5045 free(mSinkBuffer);
jiabin245cdd92018-12-07 17:55:15 -08005046 mFrameSize = audio_bytes_per_frame(mChannelCount + mHapticChannelCount, mFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07005047 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
5048 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
5049 }
Eric Laurent81784c32012-11-19 14:55:58 -08005050
5051 // create a MonoPipe to connect our submix to FastMixer
5052 NBAIO_Format format = mOutputSink->format();
Andy Hung8946a282018-04-19 20:04:56 -07005053
Andy Hung1258c1a2014-05-23 21:22:17 -07005054 // adjust format to match that of the Fast Mixer
Glenn Kasten49f36ba2017-12-06 13:02:02 -08005055 ALOGV("format changed from %#x to %#x", format.mFormat, fastMixerFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07005056 format.mFormat = fastMixerFormat;
5057 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
5058
Eric Laurent81784c32012-11-19 14:55:58 -08005059 // This pipe depth compensates for scheduling latency of the normal mixer thread.
5060 // When it wakes up after a maximum latency, it runs a few cycles quickly before
5061 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
5062 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
Andy Hung920f6572022-10-06 12:09:49 -07005063 const NBAIO_Format offersFast[1] = {format};
5064 size_t numCounterOffersFast = 0;
Andy Hung8946a282018-04-19 20:04:56 -07005065#if !LOG_NDEBUG
Eric Laurent1e28aaa2023-04-16 19:34:23 +02005066 index =
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005067#else
5068 (void)
5069#endif
Andy Hung920f6572022-10-06 12:09:49 -07005070 monoPipe->negotiate(offersFast, std::size(offersFast),
5071 nullptr /* counterOffers */, numCounterOffersFast);
Eric Laurent81784c32012-11-19 14:55:58 -08005072 ALOG_ASSERT(index == 0);
5073 monoPipe->setAvgFrames((mScreenState & 1) ?
5074 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
5075 mPipeSink = monoPipe;
5076
Eric Laurent81784c32012-11-19 14:55:58 -08005077 // create fast mixer and configure it initially with just one fast track for our submix
Andy Hung8946a282018-04-19 20:04:56 -07005078 mFastMixer = new FastMixer(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08005079 FastMixerStateQueue *sq = mFastMixer->sq();
5080#ifdef STATE_QUEUE_DUMP
5081 sq->setObserverDump(&mStateQueueObserverDump);
5082 sq->setMutatorDump(&mStateQueueMutatorDump);
5083#endif
5084 FastMixerState *state = sq->begin();
5085 FastTrack *fastTrack = &state->mFastTracks[0];
5086 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
5087 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
5088 fastTrack->mVolumeProvider = NULL;
Mikhail Naganov55773032020-10-01 15:08:13 -07005089 fastTrack->mChannelMask = static_cast<audio_channel_mask_t>(
5090 mChannelMask | mHapticChannelMask); // mPipeSink channel mask for
5091 // audio to FastMixer
Andy Hunge8a1ced2014-05-09 15:02:21 -07005092 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
jiabin245cdd92018-12-07 17:55:15 -08005093 fastTrack->mHapticPlaybackEnabled = mHapticChannelMask != AUDIO_CHANNEL_NONE;
jiabine70bc7f2020-06-30 22:07:55 -07005094 fastTrack->mHapticIntensity = os::HapticScale::NONE;
Lais Andradebc3f37a2021-07-02 00:13:19 +01005095 fastTrack->mHapticMaxAmplitude = NAN;
Eric Laurent81784c32012-11-19 14:55:58 -08005096 fastTrack->mGeneration++;
5097 state->mFastTracksGen++;
5098 state->mTrackMask = 1;
5099 // fast mixer will use the HAL output sink
5100 state->mOutputSink = mOutputSink.get();
5101 state->mOutputSinkGen++;
5102 state->mFrameCount = mFrameCount;
jiabin245cdd92018-12-07 17:55:15 -08005103 // specify sink channel mask when haptic channel mask present as it can not
5104 // be calculated directly from channel count
5105 state->mSinkChannelMask = mHapticChannelMask == AUDIO_CHANNEL_NONE
Mikhail Naganov55773032020-10-01 15:08:13 -07005106 ? AUDIO_CHANNEL_NONE
5107 : static_cast<audio_channel_mask_t>(mChannelMask | mHapticChannelMask);
Eric Laurent81784c32012-11-19 14:55:58 -08005108 state->mCommand = FastMixerState::COLD_IDLE;
5109 // already done in constructor initialization list
5110 //mFastMixerFutex = 0;
5111 state->mColdFutexAddr = &mFastMixerFutex;
5112 state->mColdGen++;
5113 state->mDumpState = &mFastMixerDumpState;
Andy Hung583043b2023-07-17 17:05:00 -07005114 mFastMixerNBLogWriter = afThreadCallback->newWriter_l(kFastMixerLogSize, "FastMixer");
Glenn Kasten9e58b552013-01-18 15:09:48 -08005115 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08005116 sq->end();
5117 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
5118
Eric Tan0513b5d2018-09-17 10:32:48 -07005119 NBLog::thread_info_t info;
5120 info.id = mId;
5121 info.type = NBLog::FASTMIXER;
5122 mFastMixerNBLogWriter->log<NBLog::EVENT_THREAD_INFO>(info);
5123
Eric Laurent81784c32012-11-19 14:55:58 -08005124 // start the fast mixer
5125 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
5126 pid_t tid = mFastMixer->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07005127 sendPrioConfigEvent(getpid(), tid, kPriorityFastMixer, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08005128 stream()->setHalThreadPriority(kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08005129
5130#ifdef AUDIO_WATCHDOG
5131 // create and start the watchdog
5132 mAudioWatchdog = new AudioWatchdog();
5133 mAudioWatchdog->setDump(&mAudioWatchdogDump);
5134 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
5135 tid = mAudioWatchdog->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07005136 sendPrioConfigEvent(getpid(), tid, kPriorityFastMixer, false /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08005137#endif
Andy Hung8946a282018-04-19 20:04:56 -07005138 } else {
5139#ifdef TEE_SINK
5140 // Only use the MixerThread tee if there is no FastMixer.
5141 mTee.set(mOutputSink->format(), NBAIO_Tee::TEE_FLAG_OUTPUT_THREAD);
5142 mTee.setId(std::string("_") + std::to_string(mId) + "_M");
5143#endif
Eric Laurent81784c32012-11-19 14:55:58 -08005144 }
5145
5146 switch (kUseFastMixer) {
5147 case FastMixer_Never:
5148 case FastMixer_Dynamic:
5149 mNormalSink = mOutputSink;
5150 break;
5151 case FastMixer_Always:
5152 mNormalSink = mPipeSink;
5153 break;
5154 case FastMixer_Static:
5155 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
5156 break;
5157 }
5158}
5159
Andy Hungee58e4a2023-07-07 13:47:37 -07005160MixerThread::~MixerThread()
Eric Laurent81784c32012-11-19 14:55:58 -08005161{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005162 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005163 FastMixerStateQueue *sq = mFastMixer->sq();
5164 FastMixerState *state = sq->begin();
5165 if (state->mCommand == FastMixerState::COLD_IDLE) {
5166 int32_t old = android_atomic_inc(&mFastMixerFutex);
5167 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07005168 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08005169 }
5170 }
5171 state->mCommand = FastMixerState::EXIT;
5172 sq->end();
5173 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
5174 mFastMixer->join();
5175 // Though the fast mixer thread has exited, it's state queue is still valid.
5176 // We'll use that extract the final state which contains one remaining fast track
5177 // corresponding to our sub-mix.
5178 state = sq->begin();
5179 ALOG_ASSERT(state->mTrackMask == 1);
5180 FastTrack *fastTrack = &state->mFastTracks[0];
5181 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
5182 delete fastTrack->mBufferProvider;
5183 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005184 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08005185#ifdef AUDIO_WATCHDOG
5186 if (mAudioWatchdog != 0) {
5187 mAudioWatchdog->requestExit();
5188 mAudioWatchdog->requestExitAndWait();
5189 mAudioWatchdog.clear();
5190 }
5191#endif
5192 }
Andy Hung583043b2023-07-17 17:05:00 -07005193 mAfThreadCallback->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08005194 delete mAudioMixer;
5195}
5196
Andy Hungee58e4a2023-07-07 13:47:37 -07005197void MixerThread::onFirstRef() {
Eric Laurentb0463942022-12-20 16:31:10 +01005198 PlaybackThread::onFirstRef();
5199
Andy Hung972bec12023-08-31 16:13:39 -07005200 audio_utils::lock_guard _l(mutex());
Eric Laurentb0463942022-12-20 16:31:10 +01005201 if (mOutput != nullptr && mOutput->stream != nullptr) {
5202 status_t status = mOutput->stream->setLatencyModeCallback(this);
5203 if (status != INVALID_OPERATION) {
5204 updateHalSupportedLatencyModes_l();
5205 }
5206 // Default to enabled if the HAL supports it. This can be changed by Audioflinger after
5207 // the thread construction according to AudioFlinger::mBluetoothLatencyModesEnabled
5208 mBluetoothLatencyModesEnabled.store(
5209 mOutput->audioHwDev->supportsBluetoothVariableLatency());
5210 }
5211}
Eric Laurent81784c32012-11-19 14:55:58 -08005212
Andy Hungee58e4a2023-07-07 13:47:37 -07005213uint32_t MixerThread::correctLatency_l(uint32_t latency) const
Eric Laurent81784c32012-11-19 14:55:58 -08005214{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005215 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005216 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
5217 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
5218 }
5219 return latency;
5220}
5221
Andy Hungee58e4a2023-07-07 13:47:37 -07005222ssize_t MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08005223{
5224 // FIXME we should only do one push per cycle; confirm this is true
5225 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005226 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005227 FastMixerStateQueue *sq = mFastMixer->sq();
5228 FastMixerState *state = sq->begin();
5229 if (state->mCommand != FastMixerState::MIX_WRITE &&
5230 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
5231 if (state->mCommand == FastMixerState::COLD_IDLE) {
Eric Laurenta2ab4502015-09-09 12:25:51 -07005232
5233 // FIXME workaround for first HAL write being CPU bound on some devices
5234 ATRACE_BEGIN("write");
5235 mOutput->write((char *)mSinkBuffer, 0);
5236 ATRACE_END();
5237
Eric Laurent81784c32012-11-19 14:55:58 -08005238 int32_t old = android_atomic_inc(&mFastMixerFutex);
5239 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07005240 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08005241 }
5242#ifdef AUDIO_WATCHDOG
5243 if (mAudioWatchdog != 0) {
5244 mAudioWatchdog->resume();
5245 }
5246#endif
5247 }
5248 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kastend797a9d2015-03-02 14:19:25 -08005249#ifdef FAST_THREAD_STATISTICS
Andy Hung583043b2023-07-17 17:05:00 -07005250 mFastMixerDumpState.increaseSamplingN(mAfThreadCallback->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08005251 FastThreadDumpState::kSamplingNforLowRamDevice : FastThreadDumpState::kSamplingN);
Glenn Kastend797a9d2015-03-02 14:19:25 -08005252#endif
Eric Laurent81784c32012-11-19 14:55:58 -08005253 sq->end();
5254 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
5255 if (kUseFastMixer == FastMixer_Dynamic) {
5256 mNormalSink = mPipeSink;
5257 }
5258 } else {
5259 sq->end(false /*didModify*/);
5260 }
5261 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005262 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08005263}
5264
Andy Hungee58e4a2023-07-07 13:47:37 -07005265void MixerThread::threadLoop_standby()
Eric Laurent81784c32012-11-19 14:55:58 -08005266{
5267 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005268 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005269 FastMixerStateQueue *sq = mFastMixer->sq();
5270 FastMixerState *state = sq->begin();
5271 if (!(state->mCommand & FastMixerState::IDLE)) {
Andy Hung2148bf02016-11-28 19:01:02 -08005272 // Report any frames trapped in the Monopipe
5273 MonoPipe *monoPipe = (MonoPipe *)mPipeSink.get();
5274 const long long pipeFrames = monoPipe->maxFrames() - monoPipe->availableToWrite();
5275 mLocalLog.log("threadLoop_standby: framesWritten:%lld suspendedFrames:%lld "
5276 "monoPipeWritten:%lld monoPipeLeft:%lld",
5277 (long long)mFramesWritten, (long long)mSuspendedFrames,
5278 (long long)mPipeSink->framesWritten(), pipeFrames);
5279 mLocalLog.log("threadLoop_standby: %s", mTimestamp.toString().c_str());
5280
Eric Laurent81784c32012-11-19 14:55:58 -08005281 state->mCommand = FastMixerState::COLD_IDLE;
5282 state->mColdFutexAddr = &mFastMixerFutex;
5283 state->mColdGen++;
5284 mFastMixerFutex = 0;
5285 sq->end();
5286 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
5287 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
5288 if (kUseFastMixer == FastMixer_Dynamic) {
5289 mNormalSink = mOutputSink;
5290 }
5291#ifdef AUDIO_WATCHDOG
5292 if (mAudioWatchdog != 0) {
5293 mAudioWatchdog->pause();
5294 }
5295#endif
5296 } else {
5297 sq->end(false /*didModify*/);
5298 }
5299 }
5300 PlaybackThread::threadLoop_standby();
5301}
5302
Andy Hungee58e4a2023-07-07 13:47:37 -07005303bool PlaybackThread::waitingAsyncCallback_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08005304{
5305 return false;
5306}
5307
Andy Hungee58e4a2023-07-07 13:47:37 -07005308bool PlaybackThread::shouldStandby_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08005309{
5310 return !mStandby;
5311}
5312
Andy Hungee58e4a2023-07-07 13:47:37 -07005313bool PlaybackThread::waitingAsyncCallback()
Eric Laurentbfb1b832013-01-07 09:53:42 -08005314{
Andy Hung972bec12023-08-31 16:13:39 -07005315 audio_utils::lock_guard _l(mutex());
Eric Laurentbfb1b832013-01-07 09:53:42 -08005316 return waitingAsyncCallback_l();
5317}
5318
Eric Laurent81784c32012-11-19 14:55:58 -08005319// shared by MIXER and DIRECT, overridden by DUPLICATING
Andy Hungee58e4a2023-07-07 13:47:37 -07005320void PlaybackThread::threadLoop_standby()
Eric Laurent81784c32012-11-19 14:55:58 -08005321{
Andy Hung8d672e02023-09-15 18:19:28 -07005322 ALOGV("%s: audio hardware entering standby, mixer %p, suspend count %d",
5323 __func__, this, (int32_t)mSuspended);
Phil Burk062e67a2015-02-11 13:40:50 -08005324 mOutput->standby();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005325 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005326 // discard any pending drain or write ack by incrementing sequence
5327 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
5328 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005329 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005330 mCallbackThread->setWriteBlocked(mWriteAckSequence);
5331 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005332 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08005333 mHwPaused = false;
Eric Laurent68a40a82022-05-03 18:15:04 +02005334 setHalLatencyMode_l();
Eric Laurent81784c32012-11-19 14:55:58 -08005335}
5336
Andy Hungee58e4a2023-07-07 13:47:37 -07005337void PlaybackThread::onAddNewTrack_l()
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08005338{
5339 ALOGV("signal playback thread");
5340 broadcast_l();
5341}
5342
Andy Hungee58e4a2023-07-07 13:47:37 -07005343void PlaybackThread::onAsyncError()
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005344{
5345 for (int i = AUDIO_STREAM_SYSTEM; i < (int)AUDIO_STREAM_CNT; i++) {
5346 invalidateTracks((audio_stream_type_t)i);
5347 }
5348}
5349
Andy Hungee58e4a2023-07-07 13:47:37 -07005350void MixerThread::threadLoop_mix()
Eric Laurent81784c32012-11-19 14:55:58 -08005351{
Eric Laurent81784c32012-11-19 14:55:58 -08005352 // mix buffers...
Glenn Kastend79072e2016-01-06 08:41:20 -08005353 mAudioMixer->process();
Andy Hung25c2dac2014-02-27 14:56:00 -08005354 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005355 // increase sleep time progressively when application underrun condition clears.
5356 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
5357 // that a steady state of alternating ready/not ready conditions keeps the sleep time
5358 // such that we would underrun the audio HAL.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005359 if ((mSleepTimeUs == 0) && (sleepTimeShift > 0)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005360 sleepTimeShift--;
5361 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005362 mSleepTimeUs = 0;
5363 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08005364 //TODO: delay standby when effects have a tail
Glenn Kasten4c053ea2014-09-28 14:41:07 -07005365
Eric Laurent81784c32012-11-19 14:55:58 -08005366}
5367
Andy Hungee58e4a2023-07-07 13:47:37 -07005368void MixerThread::threadLoop_sleepTime()
Eric Laurent81784c32012-11-19 14:55:58 -08005369{
5370 // If no tracks are ready, sleep once for the duration of an output
5371 // buffer size, then write 0s to the output
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005372 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005373 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Andy Hung06d13222018-05-03 20:13:31 -07005374 if (mPipeSink.get() != nullptr && mPipeSink == mNormalSink) {
5375 // Using the Monopipe availableToWrite, we estimate the
5376 // sleep time to retry for more data (before we underrun).
5377 MonoPipe *monoPipe = static_cast<MonoPipe *>(mPipeSink.get());
5378 const ssize_t availableToWrite = mPipeSink->availableToWrite();
5379 const size_t pipeFrames = monoPipe->maxFrames();
5380 const size_t framesLeft = pipeFrames - max(availableToWrite, 0);
5381 // HAL_framecount <= framesDelay ~ framesLeft / 2 <= Normal_Mixer_framecount
5382 const size_t framesDelay = std::min(
5383 mNormalFrameCount, max(framesLeft / 2, mFrameCount));
5384 ALOGV("pipeFrames:%zu framesLeft:%zu framesDelay:%zu",
5385 pipeFrames, framesLeft, framesDelay);
5386 mSleepTimeUs = framesDelay * MICROS_PER_SECOND / mSampleRate;
5387 } else {
5388 mSleepTimeUs = mActiveSleepTimeUs >> sleepTimeShift;
5389 if (mSleepTimeUs < kMinThreadSleepTimeUs) {
5390 mSleepTimeUs = kMinThreadSleepTimeUs;
5391 }
5392 // reduce sleep time in case of consecutive application underruns to avoid
5393 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
5394 // duration we would end up writing less data than needed by the audio HAL if
5395 // the condition persists.
5396 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
5397 sleepTimeShift++;
5398 }
Eric Laurent81784c32012-11-19 14:55:58 -08005399 }
5400 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005401 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005402 }
5403 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08005404 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
5405 // before effects processing or output.
5406 if (mMixerBufferValid) {
5407 memset(mMixerBuffer, 0, mMixerBufferSize);
Eric Laurent39095982021-08-24 18:29:27 +02005408 if (mType == SPATIALIZER) {
5409 memset(mSinkBuffer, 0, mSinkBufferSize);
5410 }
Andy Hung98ef9782014-03-04 14:46:50 -08005411 } else {
5412 memset(mSinkBuffer, 0, mSinkBufferSize);
5413 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005414 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005415 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
5416 "anticipated start");
5417 }
5418 // TODO add standby time extension fct of effect tail
5419}
5420
Andy Hungc5007f82023-08-29 14:26:09 -07005421// prepareTracks_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07005422PlaybackThread::mixer_state MixerThread::prepareTracks_l(
Andy Hung8d31fd22023-06-26 19:20:57 -07005423 Vector<sp<IAfTrack>>* tracksToRemove)
Eric Laurent81784c32012-11-19 14:55:58 -08005424{
Andy Hungc0691382018-09-12 18:01:57 -07005425 // clean up deleted track ids in AudioMixer before allocating new tracks
5426 (void)mTracks.processDeletedTrackIds([this](int trackId) {
5427 // for each trackId, destroy it in the AudioMixer
5428 if (mAudioMixer->exists(trackId)) {
5429 mAudioMixer->destroy(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08005430 }
5431 });
Andy Hungc0691382018-09-12 18:01:57 -07005432 mTracks.clearDeletedTrackIds();
Eric Laurent81784c32012-11-19 14:55:58 -08005433
5434 mixer_state mixerStatus = MIXER_IDLE;
5435 // find out which tracks need to be processed
5436 size_t count = mActiveTracks.size();
5437 size_t mixedTracks = 0;
5438 size_t tracksWithEffect = 0;
5439 // counts only _active_ fast tracks
5440 size_t fastTracks = 0;
5441 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
5442
5443 float masterVolume = mMasterVolume;
5444 bool masterMute = mMasterMute;
5445
5446 if (masterMute) {
5447 masterVolume = 0;
5448 }
5449 // Delegate master volume control to effect in output mix effect chain if needed
Andy Hung116bc262023-06-20 18:56:17 -07005450 sp<IAfEffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Eric Laurent81784c32012-11-19 14:55:58 -08005451 if (chain != 0) {
5452 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
5453 chain->setVolume_l(&v, &v);
5454 masterVolume = (float)((v + (1 << 23)) >> 24);
5455 chain.clear();
5456 }
5457
5458 // prepare a new state to push
5459 FastMixerStateQueue *sq = NULL;
5460 FastMixerState *state = NULL;
5461 bool didModify = false;
5462 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Andy Hungf2285312017-02-14 18:31:59 -08005463 bool coldIdle = false;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005464 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005465 sq = mFastMixer->sq();
5466 state = sq->begin();
Andy Hungf2285312017-02-14 18:31:59 -08005467 coldIdle = state->mCommand == FastMixerState::COLD_IDLE;
Eric Laurent81784c32012-11-19 14:55:58 -08005468 }
5469
Andy Hung69aed5f2014-02-25 17:24:40 -08005470 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08005471 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08005472
Andy Hungbd3b2b02018-05-21 10:53:11 -07005473 // DeferredOperations handles statistics after setting mixerStatus.
5474 class DeferredOperations {
5475 public:
Andy Hungea840382020-05-05 21:50:17 -07005476 DeferredOperations(mixer_state *mixerStatus, ThreadMetrics *threadMetrics)
5477 : mMixerStatus(mixerStatus)
5478 , mThreadMetrics(threadMetrics) {}
Andy Hungbd3b2b02018-05-21 10:53:11 -07005479
5480 // when leaving scope, tally frames properly.
5481 ~DeferredOperations() {
5482 // Tally underrun frames only if we are actually mixing (MIXER_TRACKS_READY)
5483 // because that is when the underrun occurs.
5484 // We do not distinguish between FastTracks and NormalTracks here.
Andy Hungea840382020-05-05 21:50:17 -07005485 size_t maxUnderrunFrames = 0;
Andy Hungb68f5eb2019-12-03 16:49:17 -08005486 if (*mMixerStatus == MIXER_TRACKS_READY && mUnderrunFrames.size() > 0) {
Andy Hungbd3b2b02018-05-21 10:53:11 -07005487 for (const auto &underrun : mUnderrunFrames) {
Andy Hungc2b11cb2020-04-22 09:04:01 -07005488 underrun.first->tallyUnderrunFrames(underrun.second);
Andy Hungea840382020-05-05 21:50:17 -07005489 maxUnderrunFrames = max(underrun.second, maxUnderrunFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07005490 }
5491 }
Andy Hungea840382020-05-05 21:50:17 -07005492 // send the max underrun frames for this mixer period
5493 mThreadMetrics->logUnderrunFrames(maxUnderrunFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07005494 }
5495
5496 // tallyUnderrunFrames() is called to update the track counters
5497 // with the number of underrun frames for a particular mixer period.
5498 // We defer tallying until we know the final mixer status.
Andy Hung8d31fd22023-06-26 19:20:57 -07005499 void tallyUnderrunFrames(const sp<IAfTrack>& track, size_t underrunFrames) {
Andy Hungbd3b2b02018-05-21 10:53:11 -07005500 mUnderrunFrames.emplace_back(track, underrunFrames);
5501 }
5502
5503 private:
5504 const mixer_state * const mMixerStatus;
Andy Hungea840382020-05-05 21:50:17 -07005505 ThreadMetrics * const mThreadMetrics;
Andy Hung8d31fd22023-06-26 19:20:57 -07005506 std::vector<std::pair<sp<IAfTrack>, size_t>> mUnderrunFrames;
Andy Hungea840382020-05-05 21:50:17 -07005507 } deferredOperations(&mixerStatus, &mThreadMetrics);
Andy Hungb68f5eb2019-12-03 16:49:17 -08005508 // implicit nested scope for variable capture
Andy Hungbd3b2b02018-05-21 10:53:11 -07005509
jiabin245cdd92018-12-07 17:55:15 -08005510 bool noFastHapticTrack = true;
Eric Laurent81784c32012-11-19 14:55:58 -08005511 for (size_t i=0 ; i<count ; i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07005512 const sp<IAfTrack> t = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08005513
5514 // this const just means the local variable doesn't change
Andy Hung8d31fd22023-06-26 19:20:57 -07005515 IAfTrack* const track = t.get();
Eric Laurent81784c32012-11-19 14:55:58 -08005516
5517 // process fast tracks
5518 if (track->isFastTrack()) {
Andy Hungae22b482019-05-09 15:38:55 -07005519 LOG_ALWAYS_FATAL_IF(mFastMixer.get() == nullptr,
5520 "%s(%d): FastTrack(%d) present without FastMixer",
5521 __func__, id(), track->id());
5522
jiabin245cdd92018-12-07 17:55:15 -08005523 if (track->getHapticPlaybackEnabled()) {
5524 noFastHapticTrack = false;
5525 }
Eric Laurent81784c32012-11-19 14:55:58 -08005526
5527 // It's theoretically possible (though unlikely) for a fast track to be created
5528 // and then removed within the same normal mix cycle. This is not a problem, as
5529 // the track never becomes active so it's fast mixer slot is never touched.
5530 // The converse, of removing an (active) track and then creating a new track
5531 // at the identical fast mixer slot within the same normal mix cycle,
5532 // is impossible because the slot isn't marked available until the end of each cycle.
Andy Hung8d31fd22023-06-26 19:20:57 -07005533 int j = track->fastIndex();
Glenn Kastendc2c50b2016-04-21 08:13:14 -07005534 ALOG_ASSERT(0 < j && j < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08005535 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
5536 FastTrack *fastTrack = &state->mFastTracks[j];
5537
5538 // Determine whether the track is currently in underrun condition,
5539 // and whether it had a recent underrun.
5540 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
5541 FastTrackUnderruns underruns = ftDump->mUnderruns;
5542 uint32_t recentFull = (underruns.mBitFields.mFull -
Andy Hung8d31fd22023-06-26 19:20:57 -07005543 track->fastTrackUnderruns().mBitFields.mFull) & UNDERRUN_MASK;
Eric Laurent81784c32012-11-19 14:55:58 -08005544 uint32_t recentPartial = (underruns.mBitFields.mPartial -
Andy Hung8d31fd22023-06-26 19:20:57 -07005545 track->fastTrackUnderruns().mBitFields.mPartial) & UNDERRUN_MASK;
Eric Laurent81784c32012-11-19 14:55:58 -08005546 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
Andy Hung8d31fd22023-06-26 19:20:57 -07005547 track->fastTrackUnderruns().mBitFields.mEmpty) & UNDERRUN_MASK;
Eric Laurent81784c32012-11-19 14:55:58 -08005548 uint32_t recentUnderruns = recentPartial + recentEmpty;
Andy Hung8d31fd22023-06-26 19:20:57 -07005549 track->fastTrackUnderruns() = underruns;
Eric Laurent81784c32012-11-19 14:55:58 -08005550 // don't count underruns that occur while stopping or pausing
5551 // or stopped which can occur when flush() is called while active
Andy Hungbd3b2b02018-05-21 10:53:11 -07005552 size_t underrunFrames = 0;
Glenn Kasten82aaf942013-07-17 16:05:07 -07005553 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
5554 recentUnderruns > 0) {
5555 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
Andy Hungbd3b2b02018-05-21 10:53:11 -07005556 underrunFrames = recentUnderruns * mFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08005557 }
Andy Hungbd3b2b02018-05-21 10:53:11 -07005558 // Immediately account for FastTrack underruns.
Andy Hung8d31fd22023-06-26 19:20:57 -07005559 track->audioTrackServerProxy()->tallyUnderrunFrames(underrunFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08005560
5561 // This is similar to the state machine for normal tracks,
5562 // with a few modifications for fast tracks.
5563 bool isActive = true;
Andy Hung8d31fd22023-06-26 19:20:57 -07005564 switch (track->state()) {
5565 case IAfTrackBase::STOPPING_1:
Eric Laurent81784c32012-11-19 14:55:58 -08005566 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08005567 if (recentUnderruns > 0 || track->isTerminated()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07005568 track->setState(IAfTrackBase::STOPPING_2);
Eric Laurent81784c32012-11-19 14:55:58 -08005569 }
5570 break;
Andy Hung8d31fd22023-06-26 19:20:57 -07005571 case IAfTrackBase::PAUSING:
Eric Laurent81784c32012-11-19 14:55:58 -08005572 // ramp down is not yet implemented
5573 track->setPaused();
5574 break;
Andy Hung8d31fd22023-06-26 19:20:57 -07005575 case IAfTrackBase::RESUMING:
Eric Laurent81784c32012-11-19 14:55:58 -08005576 // ramp up is not yet implemented
Andy Hung8d31fd22023-06-26 19:20:57 -07005577 track->setState(IAfTrackBase::ACTIVE);
Eric Laurent81784c32012-11-19 14:55:58 -08005578 break;
Andy Hung8d31fd22023-06-26 19:20:57 -07005579 case IAfTrackBase::ACTIVE:
Eric Laurent81784c32012-11-19 14:55:58 -08005580 if (recentFull > 0 || recentPartial > 0) {
5581 // track has provided at least some frames recently: reset retry count
Andy Hung8d31fd22023-06-26 19:20:57 -07005582 track->retryCount() = kMaxTrackRetries;
Eric Laurent81784c32012-11-19 14:55:58 -08005583 }
5584 if (recentUnderruns == 0) {
5585 // no recent underruns: stay active
5586 break;
5587 }
5588 // there has recently been an underrun of some kind
5589 if (track->sharedBuffer() == 0) {
5590 // were any of the recent underruns "empty" (no frames available)?
5591 if (recentEmpty == 0) {
5592 // no, then ignore the partial underruns as they are allowed indefinitely
5593 break;
5594 }
5595 // there has recently been an "empty" underrun: decrement the retry counter
Andy Hung8d31fd22023-06-26 19:20:57 -07005596 if (--(track->retryCount()) > 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005597 break;
5598 }
5599 // indicate to client process that the track was disabled because of underrun;
5600 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08005601 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08005602 // remove from active list, but state remains ACTIVE [confusing but true]
5603 isActive = false;
5604 break;
5605 }
Chih-Hung Hsieh2b487032018-09-13 14:16:02 -07005606 FALLTHROUGH_INTENDED;
Andy Hung8d31fd22023-06-26 19:20:57 -07005607 case IAfTrackBase::STOPPING_2:
5608 case IAfTrackBase::PAUSED:
5609 case IAfTrackBase::STOPPED:
5610 case IAfTrackBase::FLUSHED: // flush() while active
Eric Laurent81784c32012-11-19 14:55:58 -08005611 // Check for presentation complete if track is inactive
5612 // We have consumed all the buffers of this track.
5613 // This would be incomplete if we auto-paused on underrun
5614 {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005615 uint32_t latency = 0;
5616 status_t result = mOutput->stream->getLatency(&latency);
5617 ALOGE_IF(result != OK,
5618 "Error when retrieving output stream latency: %d", result);
5619 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08005620 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005621 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
5622 // track stays in active list until presentation is complete
5623 break;
5624 }
5625 }
5626 if (track->isStopping_2()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07005627 track->setState(IAfTrackBase::STOPPED);
Eric Laurent81784c32012-11-19 14:55:58 -08005628 }
5629 if (track->isStopped()) {
5630 // Can't reset directly, as fast mixer is still polling this track
5631 // track->reset();
5632 // So instead mark this track as needing to be reset after push with ack
5633 resetMask |= 1 << i;
5634 }
5635 isActive = false;
5636 break;
Andy Hung8d31fd22023-06-26 19:20:57 -07005637 case IAfTrackBase::IDLE:
Eric Laurent81784c32012-11-19 14:55:58 -08005638 default:
Andy Hung8d31fd22023-06-26 19:20:57 -07005639 LOG_ALWAYS_FATAL("unexpected track state %d", (int)track->state());
Eric Laurent81784c32012-11-19 14:55:58 -08005640 }
5641
5642 if (isActive) {
5643 // was it previously inactive?
5644 if (!(state->mTrackMask & (1 << j))) {
Andy Hung8d31fd22023-06-26 19:20:57 -07005645 ExtendedAudioBufferProvider *eabp = track->asExtendedAudioBufferProvider();
5646 VolumeProvider *vp = track->asVolumeProvider();
Eric Laurent81784c32012-11-19 14:55:58 -08005647 fastTrack->mBufferProvider = eabp;
5648 fastTrack->mVolumeProvider = vp;
Andy Hung8d31fd22023-06-26 19:20:57 -07005649 fastTrack->mChannelMask = track->channelMask();
5650 fastTrack->mFormat = track->format();
jiabin245cdd92018-12-07 17:55:15 -08005651 fastTrack->mHapticPlaybackEnabled = track->getHapticPlaybackEnabled();
jiabin77270b82018-12-18 15:41:29 -08005652 fastTrack->mHapticIntensity = track->getHapticIntensity();
Lais Andradebc3f37a2021-07-02 00:13:19 +01005653 fastTrack->mHapticMaxAmplitude = track->getHapticMaxAmplitude();
Eric Laurent81784c32012-11-19 14:55:58 -08005654 fastTrack->mGeneration++;
5655 state->mTrackMask |= 1 << j;
5656 didModify = true;
5657 // no acknowledgement required for newly active tracks
5658 }
Andy Hung8d31fd22023-06-26 19:20:57 -07005659 sp<AudioTrackServerProxy> proxy = track->audioTrackServerProxy();
Eric Laurenteab90452019-06-24 15:17:46 -07005660 float volume;
5661 if (track->isPlaybackRestricted() || mStreamTypes[track->streamType()].mute) {
5662 volume = 0.f;
5663 } else {
5664 volume = masterVolume * mStreamTypes[track->streamType()].volume;
5665 }
5666
5667 handleVoipVolume_l(&volume);
5668
Eric Laurent81784c32012-11-19 14:55:58 -08005669 // cache the combined master volume and stream type volume for fast mixer; this
5670 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005671 const float vh = track->getVolumeHandler()->getVolume(
Eric Laurenteab90452019-06-24 15:17:46 -07005672 proxy->framesReleased()).first;
5673 volume *= vh;
Andy Hung8d31fd22023-06-26 19:20:57 -07005674 track->setCachedVolume(volume);
Kevin Rocard12381092018-04-11 09:19:59 -07005675 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Vlad Popae2f5aef2022-07-25 16:00:20 +02005676 float vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
5677 float vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
5678
Andy Hung583043b2023-07-17 17:05:00 -07005679 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
Vlad Popae2f5aef2022-07-25 16:00:20 +02005680 /*muteState=*/{masterVolume == 0.f,
5681 mStreamTypes[track->streamType()].volume == 0.f,
5682 mStreamTypes[track->streamType()].mute,
5683 track->isPlaybackRestricted(),
Vlad Popa436c9172022-08-02 15:25:08 +02005684 vlf == 0.f && vrf == 0.f,
5685 vh == 0.f});
Vlad Popae2f5aef2022-07-25 16:00:20 +02005686
5687 vlf *= volume;
5688 vrf *= volume;
Eric Laurenteab90452019-06-24 15:17:46 -07005689
jiabin76d94692022-12-15 21:51:21 +00005690 track->setFinalVolume(vlf, vrf);
Eric Laurent81784c32012-11-19 14:55:58 -08005691 ++fastTracks;
5692 } else {
5693 // was it previously active?
5694 if (state->mTrackMask & (1 << j)) {
5695 fastTrack->mBufferProvider = NULL;
5696 fastTrack->mGeneration++;
5697 state->mTrackMask &= ~(1 << j);
5698 didModify = true;
5699 // If any fast tracks were removed, we must wait for acknowledgement
5700 // because we're about to decrement the last sp<> on those tracks.
5701 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
5702 } else {
Glenn Kastenbf848af2017-12-22 11:55:01 -08005703 // ALOGW rather than LOG_ALWAYS_FATAL because it seems there are cases where an
5704 // AudioTrack may start (which may not be with a start() but with a write()
5705 // after underrun) and immediately paused or released. In that case the
5706 // FastTrack state hasn't had time to update.
5707 // TODO Remove the ALOGW when this theory is confirmed.
5708 ALOGW("fast track %d should have been active; "
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08005709 "mState=%d, mTrackMask=%#x, recentUnderruns=%u, isShared=%d",
Andy Hung8d31fd22023-06-26 19:20:57 -07005710 j, (int)track->state(), state->mTrackMask, recentUnderruns,
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08005711 track->sharedBuffer() != 0);
Glenn Kastenbf848af2017-12-22 11:55:01 -08005712 // Since the FastMixer state already has the track inactive, do nothing here.
Eric Laurent81784c32012-11-19 14:55:58 -08005713 }
5714 tracksToRemove->add(track);
5715 // Avoids a misleading display in dumpsys
Andy Hung8d31fd22023-06-26 19:20:57 -07005716 track->fastTrackUnderruns().mBitFields.mMostRecent = UNDERRUN_FULL;
Eric Laurent81784c32012-11-19 14:55:58 -08005717 }
jiabin245cdd92018-12-07 17:55:15 -08005718 if (fastTrack->mHapticPlaybackEnabled != track->getHapticPlaybackEnabled()) {
5719 fastTrack->mHapticPlaybackEnabled = track->getHapticPlaybackEnabled();
5720 didModify = true;
5721 }
Eric Laurent81784c32012-11-19 14:55:58 -08005722 continue;
5723 }
5724
5725 { // local variable scope to avoid goto warning
5726
5727 audio_track_cblk_t* cblk = track->cblk();
5728
5729 // The first time a track is added we wait
5730 // for all its buffers to be filled before processing it
Andy Hungc0691382018-09-12 18:01:57 -07005731 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08005732
5733 // if an active track doesn't exist in the AudioMixer, create it.
Andy Hungc0691382018-09-12 18:01:57 -07005734 // use the trackId as the AudioMixer name.
5735 if (!mAudioMixer->exists(trackId)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08005736 status_t status = mAudioMixer->create(
Andy Hungc0691382018-09-12 18:01:57 -07005737 trackId,
Andy Hung8d31fd22023-06-26 19:20:57 -07005738 track->channelMask(),
5739 track->format(),
5740 track->sessionId());
Andy Hung1bc088a2018-02-09 15:57:31 -08005741 if (status != OK) {
Andy Hungc0691382018-09-12 18:01:57 -07005742 ALOGW("%s(): AudioMixer cannot create track(%d)"
5743 " mask %#x, format %#x, sessionId %d",
5744 __func__, trackId,
Andy Hung8d31fd22023-06-26 19:20:57 -07005745 track->channelMask(), track->format(), track->sessionId());
Andy Hung1bc088a2018-02-09 15:57:31 -08005746 tracksToRemove->add(track);
5747 track->invalidate(); // consider it dead.
5748 continue;
5749 }
5750 }
5751
Eric Laurent81784c32012-11-19 14:55:58 -08005752 // make sure that we have enough frames to mix one full buffer.
5753 // enforce this condition only once to enable draining the buffer in case the client
5754 // app does not call stop() and relies on underrun to stop:
5755 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
5756 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005757 size_t desiredFrames;
Andy Hung8d31fd22023-06-26 19:20:57 -07005758 const uint32_t sampleRate = track->audioTrackServerProxy()->getSampleRate();
5759 const AudioPlaybackRate playbackRate = track->audioTrackServerProxy()->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07005760
5761 desiredFrames = sourceFramesNeededWithTimestretch(
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07005762 sampleRate, mNormalFrameCount, mSampleRate, playbackRate.mSpeed);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005763 // TODO: ONLY USED FOR LEGACY RESAMPLERS, remove when they are removed.
5764 // add frames already consumed but not yet released by the resampler
5765 // because mAudioTrackServerProxy->framesReady() will include these frames
Andy Hungc0691382018-09-12 18:01:57 -07005766 desiredFrames += mAudioMixer->getUnreleasedFrames(trackId);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005767
Eric Laurent81784c32012-11-19 14:55:58 -08005768 uint32_t minFrames = 1;
5769 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
5770 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005771 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08005772 }
Eric Laurent13e4c962013-12-20 17:36:01 -08005773
5774 size_t framesReady = track->framesReady();
Glenn Kastene7754022014-10-31 12:11:26 -07005775 if (ATRACE_ENABLED()) {
5776 // I wish we had formatted trace names
Andy Hung1bc088a2018-02-09 15:57:31 -08005777 std::string traceName("nRdy");
Andy Hungc0691382018-09-12 18:01:57 -07005778 traceName += std::to_string(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08005779 ATRACE_INT(traceName.c_str(), framesReady);
Glenn Kastene7754022014-10-31 12:11:26 -07005780 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005781 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08005782 !track->isPaused() && !track->isTerminated())
5783 {
Andy Hungc0691382018-09-12 18:01:57 -07005784 ALOGVV("track(%d) s=%08x [OK] on thread %p", trackId, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08005785
5786 mixedTracks++;
5787
Andy Hung69aed5f2014-02-25 17:24:40 -08005788 // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
5789 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08005790 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08005791 if (track->mainBuffer() != mSinkBuffer &&
5792 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08005793 if (mEffectBufferEnabled) {
5794 mEffectBufferValid = true; // Later can set directly.
5795 }
Eric Laurent81784c32012-11-19 14:55:58 -08005796 chain = getEffectChain_l(track->sessionId());
5797 // Delegate volume control to effect in track effect chain if needed
5798 if (chain != 0) {
5799 tracksWithEffect++;
5800 } else {
Andy Hungc0691382018-09-12 18:01:57 -07005801 ALOGW("prepareTracks_l(): track(%d) attached to effect but no chain found on "
Eric Laurent81784c32012-11-19 14:55:58 -08005802 "session %d",
Andy Hungc0691382018-09-12 18:01:57 -07005803 trackId, track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08005804 }
5805 }
5806
5807
5808 int param = AudioMixer::VOLUME;
Andy Hung8d31fd22023-06-26 19:20:57 -07005809 if (track->fillingStatus() == IAfTrack::FS_FILLED) {
Eric Laurent81784c32012-11-19 14:55:58 -08005810 // no ramp for the first volume setting
Andy Hung8d31fd22023-06-26 19:20:57 -07005811 track->fillingStatus() = IAfTrack::FS_ACTIVE;
5812 if (track->state() == IAfTrackBase::RESUMING) {
5813 track->setState(IAfTrackBase::ACTIVE);
Revathi Uddaraju453bcb52017-08-14 14:19:40 +08005814 // If a new track is paused immediately after start, do not ramp on resume.
5815 if (cblk->mServer != 0) {
5816 param = AudioMixer::RAMP_VOLUME;
5817 }
Eric Laurent81784c32012-11-19 14:55:58 -08005818 }
Andy Hungc0691382018-09-12 18:01:57 -07005819 mAudioMixer->setParameter(trackId, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Eric Laurent7c29ec92017-09-20 17:54:22 -07005820 mLeftVolFloat = -1.0;
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005821 // FIXME should not make a decision based on mServer
5822 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005823 // If the track is stopped before the first frame was mixed,
5824 // do not apply ramp
5825 param = AudioMixer::RAMP_VOLUME;
5826 }
5827
5828 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07005829 uint32_t vl, vr; // in U8.24 integer format
5830 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Eric Laurent7c29ec92017-09-20 17:54:22 -07005831 // read original volumes with volume control
Eric Laurenteab90452019-06-24 15:17:46 -07005832 float v = masterVolume * mStreamTypes[track->streamType()].volume;
Andy Hung333ab962019-05-28 20:23:35 -07005833 // Always fetch volumeshaper volume to ensure state is updated.
Andy Hung8d31fd22023-06-26 19:20:57 -07005834 const sp<AudioTrackServerProxy> proxy = track->audioTrackServerProxy();
Andy Hung333ab962019-05-28 20:23:35 -07005835 const float vh = track->getVolumeHandler()->getVolume(
Andy Hung8d31fd22023-06-26 19:20:57 -07005836 track->audioTrackServerProxy()->framesReleased()).first;
Eric Laurent7c29ec92017-09-20 17:54:22 -07005837
Eric Laurenteab90452019-06-24 15:17:46 -07005838 if (mStreamTypes[track->streamType()].mute || track->isPlaybackRestricted()) {
5839 v = 0;
5840 }
5841
5842 handleVoipVolume_l(&v);
5843
5844 if (track->isPausing()) {
Andy Hung6be49402014-05-30 10:42:03 -07005845 vl = vr = 0;
5846 vlf = vrf = vaf = 0.;
Eric Laurenteab90452019-06-24 15:17:46 -07005847 track->setPaused();
Eric Laurent81784c32012-11-19 14:55:58 -08005848 } else {
Glenn Kastenc56f3422014-03-21 17:53:17 -07005849 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07005850 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
5851 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08005852 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07005853 if (vlf > GAIN_FLOAT_UNITY) {
5854 ALOGV("Track left volume out of range: %.3g", vlf);
5855 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08005856 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07005857 if (vrf > GAIN_FLOAT_UNITY) {
5858 ALOGV("Track right volume out of range: %.3g", vrf);
5859 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08005860 }
Vlad Popae2f5aef2022-07-25 16:00:20 +02005861
Andy Hung583043b2023-07-17 17:05:00 -07005862 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
Vlad Popae2f5aef2022-07-25 16:00:20 +02005863 /*muteState=*/{masterVolume == 0.f,
5864 mStreamTypes[track->streamType()].volume == 0.f,
5865 mStreamTypes[track->streamType()].mute,
5866 track->isPlaybackRestricted(),
Vlad Popa436c9172022-08-02 15:25:08 +02005867 vlf == 0.f && vrf == 0.f,
5868 vh == 0.f});
Vlad Popae2f5aef2022-07-25 16:00:20 +02005869
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005870 // now apply the master volume and stream type volume and shaper volume
5871 vlf *= v * vh;
5872 vrf *= v * vh;
Eric Laurent81784c32012-11-19 14:55:58 -08005873 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07005874 // then derive vl and vr as U8.24 versions for the effect chain
5875 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
5876 vl = (uint32_t) (scaleto8_24 * vlf);
5877 vr = (uint32_t) (scaleto8_24 * vrf);
5878 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08005879 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08005880 // send level comes from shared memory and so may be corrupt
5881 if (sendLevel > MAX_GAIN_INT) {
5882 ALOGV("Track send level out of range: %04X", sendLevel);
5883 sendLevel = MAX_GAIN_INT;
5884 }
Andy Hung6be49402014-05-30 10:42:03 -07005885 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
5886 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08005887 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005888
jiabin76d94692022-12-15 21:51:21 +00005889 track->setFinalVolume(vrf, vlf);
Kevin Rocard12381092018-04-11 09:19:59 -07005890
Eric Laurent81784c32012-11-19 14:55:58 -08005891 // Delegate volume control to effect in track effect chain if needed
5892 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
5893 // Do not ramp volume if volume is controlled by effect
5894 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08005895 // Update remaining floating point volume levels
5896 vlf = (float)vl / (1 << 24);
5897 vrf = (float)vr / (1 << 24);
Andy Hung8d31fd22023-06-26 19:20:57 -07005898 track->setHasVolumeController(true);
Eric Laurent81784c32012-11-19 14:55:58 -08005899 } else {
5900 // force no volume ramp when volume controller was just disabled or removed
5901 // from effect chain to avoid volume spike
Andy Hung8d31fd22023-06-26 19:20:57 -07005902 if (track->hasVolumeController()) {
Eric Laurent81784c32012-11-19 14:55:58 -08005903 param = AudioMixer::VOLUME;
5904 }
Andy Hung8d31fd22023-06-26 19:20:57 -07005905 track->setHasVolumeController(false);
Eric Laurent81784c32012-11-19 14:55:58 -08005906 }
5907
Eric Laurent81784c32012-11-19 14:55:58 -08005908 // XXX: these things DON'T need to be done each time
Andy Hung8d31fd22023-06-26 19:20:57 -07005909 mAudioMixer->setBufferProvider(trackId, track->asExtendedAudioBufferProvider());
Andy Hungc0691382018-09-12 18:01:57 -07005910 mAudioMixer->enable(trackId);
Eric Laurent81784c32012-11-19 14:55:58 -08005911
Andy Hungc0691382018-09-12 18:01:57 -07005912 mAudioMixer->setParameter(trackId, param, AudioMixer::VOLUME0, &vlf);
5913 mAudioMixer->setParameter(trackId, param, AudioMixer::VOLUME1, &vrf);
5914 mAudioMixer->setParameter(trackId, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08005915 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005916 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005917 AudioMixer::TRACK,
5918 AudioMixer::FORMAT, (void *)track->format());
5919 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005920 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005921 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00005922 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Eric Laurent39095982021-08-24 18:29:27 +02005923
Eric Laurentb0a7bc92022-04-05 15:06:08 +02005924 if (mType == SPATIALIZER && !track->isSpatialized()) {
Eric Laurent39095982021-08-24 18:29:27 +02005925 mAudioMixer->setParameter(
5926 trackId,
5927 AudioMixer::TRACK,
5928 AudioMixer::MIXER_CHANNEL_MASK,
5929 (void *)(uintptr_t)(mChannelMask | mHapticChannelMask));
5930 } else {
5931 mAudioMixer->setParameter(
5932 trackId,
5933 AudioMixer::TRACK,
5934 AudioMixer::MIXER_CHANNEL_MASK,
5935 (void *)(uintptr_t)(mMixerChannelMask | mHapticChannelMask));
5936 }
5937
Glenn Kastene3aa6592012-12-04 12:22:46 -08005938 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07005939 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Andy Hung333ab962019-05-28 20:23:35 -07005940 uint32_t reqSampleRate = proxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08005941 if (reqSampleRate == 0) {
5942 reqSampleRate = mSampleRate;
5943 } else if (reqSampleRate > maxSampleRate) {
5944 reqSampleRate = maxSampleRate;
5945 }
Eric Laurent81784c32012-11-19 14:55:58 -08005946 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005947 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005948 AudioMixer::RESAMPLE,
5949 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00005950 (void *)(uintptr_t)reqSampleRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005951
Andy Hung8edb8dc2015-03-26 19:13:55 -07005952 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005953 trackId,
Andy Hung8edb8dc2015-03-26 19:13:55 -07005954 AudioMixer::TIMESTRETCH,
5955 AudioMixer::PLAYBACK_RATE,
Andy Hung920f6572022-10-06 12:09:49 -07005956 // cast away constness for this generic API.
5957 const_cast<void *>(reinterpret_cast<const void *>(&playbackRate)));
Andy Hung8edb8dc2015-03-26 19:13:55 -07005958
Andy Hung69aed5f2014-02-25 17:24:40 -08005959 /*
5960 * Select the appropriate output buffer for the track.
5961 *
Andy Hung98ef9782014-03-04 14:46:50 -08005962 * Tracks with effects go into their own effects chain buffer
5963 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08005964 *
5965 * Other tracks can use mMixerBuffer for higher precision
5966 * channel accumulation. If this buffer is enabled
5967 * (mMixerBufferEnabled true), then selected tracks will accumulate
5968 * into it.
5969 *
5970 */
5971 if (mMixerBufferEnabled
5972 && (track->mainBuffer() == mSinkBuffer
5973 || track->mainBuffer() == mMixerBuffer)) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02005974 if (mType == SPATIALIZER && !track->isSpatialized()) {
Eric Laurent39095982021-08-24 18:29:27 +02005975 mAudioMixer->setParameter(
5976 trackId,
5977 AudioMixer::TRACK,
Eric Laurentb62d0362021-10-26 17:40:18 +02005978 AudioMixer::MIXER_FORMAT, (void *)mEffectBufferFormat);
Eric Laurent39095982021-08-24 18:29:27 +02005979 mAudioMixer->setParameter(
5980 trackId,
5981 AudioMixer::TRACK,
Eric Laurentb62d0362021-10-26 17:40:18 +02005982 AudioMixer::MAIN_BUFFER, (void *)mPostSpatializerBuffer);
Eric Laurent39095982021-08-24 18:29:27 +02005983 } else {
5984 mAudioMixer->setParameter(
5985 trackId,
5986 AudioMixer::TRACK,
5987 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
5988 mAudioMixer->setParameter(
5989 trackId,
5990 AudioMixer::TRACK,
5991 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
5992 // TODO: override track->mainBuffer()?
5993 mMixerBufferValid = true;
5994 }
Andy Hung69aed5f2014-02-25 17:24:40 -08005995 } else {
5996 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005997 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08005998 AudioMixer::TRACK,
Andy Hung319587b2023-05-23 14:01:03 -07005999 AudioMixer::MIXER_FORMAT, (void *)AUDIO_FORMAT_PCM_FLOAT);
Andy Hung69aed5f2014-02-25 17:24:40 -08006000 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07006001 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08006002 AudioMixer::TRACK,
6003 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
6004 }
Eric Laurent81784c32012-11-19 14:55:58 -08006005 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07006006 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08006007 AudioMixer::TRACK,
6008 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
jiabin245cdd92018-12-07 17:55:15 -08006009 mAudioMixer->setParameter(
6010 trackId,
6011 AudioMixer::TRACK,
6012 AudioMixer::HAPTIC_ENABLED, (void *)(uintptr_t)track->getHapticPlaybackEnabled());
jiabin77270b82018-12-18 15:41:29 -08006013 mAudioMixer->setParameter(
6014 trackId,
6015 AudioMixer::TRACK,
6016 AudioMixer::HAPTIC_INTENSITY, (void *)(uintptr_t)track->getHapticIntensity());
Andy Hung8d31fd22023-06-26 19:20:57 -07006017 const float hapticMaxAmplitude = track->getHapticMaxAmplitude();
Lais Andradebc3f37a2021-07-02 00:13:19 +01006018 mAudioMixer->setParameter(
6019 trackId,
6020 AudioMixer::TRACK,
Andy Hung8d31fd22023-06-26 19:20:57 -07006021 AudioMixer::HAPTIC_MAX_AMPLITUDE, (void *)&hapticMaxAmplitude);
Eric Laurent81784c32012-11-19 14:55:58 -08006022
6023 // reset retry count
Andy Hung8d31fd22023-06-26 19:20:57 -07006024 track->retryCount() = kMaxTrackRetries;
Eric Laurent81784c32012-11-19 14:55:58 -08006025
6026 // If one track is ready, set the mixer ready if:
6027 // - the mixer was not ready during previous round OR
6028 // - no other track is not ready
6029 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
6030 mixerStatus != MIXER_TRACKS_ENABLED) {
6031 mixerStatus = MIXER_TRACKS_READY;
6032 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08006033
6034 // Enable the next few lines to instrument a test for underrun log handling.
6035 // TODO: Remove when we have a better way of testing the underrun log.
6036#if 0
6037 static int i;
6038 if ((++i & 0xf) == 0) {
6039 deferredOperations.tallyUnderrunFrames(track, 10 /* underrunFrames */);
6040 }
6041#endif
Eric Laurent81784c32012-11-19 14:55:58 -08006042 } else {
Andy Hungbd3b2b02018-05-21 10:53:11 -07006043 size_t underrunFrames = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08006044 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Andy Hungb68f5eb2019-12-03 16:49:17 -08006045 ALOGV("track(%d) underrun, track state %s framesReady(%zu) < framesDesired(%zd)",
6046 trackId, track->getTrackStateAsString(), framesReady, desiredFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07006047 underrunFrames = desiredFrames;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08006048 }
Andy Hungbd3b2b02018-05-21 10:53:11 -07006049 deferredOperations.tallyUnderrunFrames(track, underrunFrames);
Phil Burk2812d9e2016-01-04 10:34:30 -08006050
Eric Laurent81784c32012-11-19 14:55:58 -08006051 // clear effect chain input buffer if an active track underruns to avoid sending
6052 // previous audio buffer again to effects
6053 chain = getEffectChain_l(track->sessionId());
6054 if (chain != 0) {
6055 chain->clearInputBuffer();
6056 }
6057
Andy Hungc0691382018-09-12 18:01:57 -07006058 ALOGVV("track(%d) s=%08x [NOT READY] on thread %p", trackId, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08006059 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
6060 track->isStopped() || track->isPaused()) {
6061 // We have consumed all the buffers of this track.
6062 // Remove it from the list of active tracks.
6063 // TODO: use actual buffer filling status instead of latency when available from
6064 // audio HAL
6065 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08006066 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08006067 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
6068 if (track->isStopped()) {
6069 track->reset();
6070 }
6071 tracksToRemove->add(track);
6072 }
6073 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08006074 // No buffers for this track. Give it a few chances to
6075 // fill a buffer, then remove it from active list.
Andy Hung8d31fd22023-06-26 19:20:57 -07006076 if (--(track->retryCount()) <= 0) {
Andy Hungc0691382018-09-12 18:01:57 -07006077 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p",
6078 trackId, this);
Eric Laurent81784c32012-11-19 14:55:58 -08006079 tracksToRemove->add(track);
6080 // indicate to client process that the track was disabled because of underrun;
6081 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08006082 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08006083 // If one track is not ready, mark the mixer also not ready if:
6084 // - the mixer was ready during previous round OR
6085 // - no other track is ready
6086 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
6087 mixerStatus != MIXER_TRACKS_READY) {
6088 mixerStatus = MIXER_TRACKS_ENABLED;
6089 }
6090 }
Andy Hungc0691382018-09-12 18:01:57 -07006091 mAudioMixer->disable(trackId);
Eric Laurent81784c32012-11-19 14:55:58 -08006092 }
6093
6094 } // local variable scope to avoid goto warning
Eric Laurent81784c32012-11-19 14:55:58 -08006095
6096 }
6097
jiabin245cdd92018-12-07 17:55:15 -08006098 if (mHapticChannelMask != AUDIO_CHANNEL_NONE && sq != NULL) {
6099 // When there is no fast track playing haptic and FastMixer exists,
6100 // enabling the first FastTrack, which provides mixed data from normal
6101 // tracks, to play haptic data.
6102 FastTrack *fastTrack = &state->mFastTracks[0];
6103 if (fastTrack->mHapticPlaybackEnabled != noFastHapticTrack) {
6104 fastTrack->mHapticPlaybackEnabled = noFastHapticTrack;
6105 didModify = true;
6106 }
6107 }
6108
Eric Laurent81784c32012-11-19 14:55:58 -08006109 // Push the new FastMixer state if necessary
Jing Mike537412f2023-03-12 11:01:47 +08006110 [[maybe_unused]] bool pauseAudioWatchdog = false;
Eric Laurent81784c32012-11-19 14:55:58 -08006111 if (didModify) {
6112 state->mFastTracksGen++;
6113 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
6114 if (kUseFastMixer == FastMixer_Dynamic &&
6115 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
6116 state->mCommand = FastMixerState::COLD_IDLE;
6117 state->mColdFutexAddr = &mFastMixerFutex;
6118 state->mColdGen++;
6119 mFastMixerFutex = 0;
6120 if (kUseFastMixer == FastMixer_Dynamic) {
6121 mNormalSink = mOutputSink;
6122 }
6123 // If we go into cold idle, need to wait for acknowledgement
6124 // so that fast mixer stops doing I/O.
6125 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
6126 pauseAudioWatchdog = true;
6127 }
Eric Laurent81784c32012-11-19 14:55:58 -08006128 }
6129 if (sq != NULL) {
6130 sq->end(didModify);
Andy Hungf2285312017-02-14 18:31:59 -08006131 // No need to block if the FastMixer is in COLD_IDLE as the FastThread
6132 // is not active. (We BLOCK_UNTIL_ACKED when entering COLD_IDLE
6133 // when bringing the output sink into standby.)
6134 //
6135 // We will get the latest FastMixer state when we come out of COLD_IDLE.
6136 //
6137 // This occurs with BT suspend when we idle the FastMixer with
6138 // active tracks, which may be added or removed.
6139 sq->push(coldIdle ? FastMixerStateQueue::BLOCK_NEVER : block);
Eric Laurent81784c32012-11-19 14:55:58 -08006140 }
6141#ifdef AUDIO_WATCHDOG
6142 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
6143 mAudioWatchdog->pause();
6144 }
6145#endif
6146
6147 // Now perform the deferred reset on fast tracks that have stopped
6148 while (resetMask != 0) {
6149 size_t i = __builtin_ctz(resetMask);
6150 ALOG_ASSERT(i < count);
6151 resetMask &= ~(1 << i);
Andy Hung8d31fd22023-06-26 19:20:57 -07006152 sp<IAfTrack> track = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08006153 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
6154 track->reset();
6155 }
6156
Andy Hung80d03d22018-04-10 10:32:11 -07006157 // Track destruction may occur outside of threadLoop once it is removed from active tracks.
6158 // Ensure the AudioMixer doesn't have a raw "buffer provider" pointer to the track if
6159 // it ceases to be active, to allow safe removal from the AudioMixer at the start
6160 // of prepareTracks_l(); this releases any outstanding buffer back to the track.
6161 // See also the implementation of destroyTrack_l().
6162 for (const auto &track : *tracksToRemove) {
Andy Hungc0691382018-09-12 18:01:57 -07006163 const int trackId = track->id();
6164 if (mAudioMixer->exists(trackId)) { // Normal tracks here, fast tracks in FastMixer.
6165 mAudioMixer->setBufferProvider(trackId, nullptr /* bufferProvider */);
Andy Hung80d03d22018-04-10 10:32:11 -07006166 }
6167 }
6168
Eric Laurent81784c32012-11-19 14:55:58 -08006169 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08006170 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08006171
Eric Laurentb3f315a2021-07-13 15:09:05 +02006172 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0 ||
6173 getEffectChain_l(AUDIO_SESSION_OUTPUT_STAGE) != 0) {
Eric Laurent97d547d2014-09-02 14:45:53 -07006174 mEffectBufferValid = true;
Marco Nelissenac302142014-10-20 13:15:38 -07006175 }
6176
6177 if (mEffectBufferValid) {
Marco Nelissen57088b52014-10-17 16:39:39 -07006178 // as long as there are effects we should clear the effects buffer, to avoid
6179 // passing a non-clean buffer to the effect chain
6180 memset(mEffectBuffer, 0, mEffectBufferSize);
Eric Laurentb62d0362021-10-26 17:40:18 +02006181 if (mType == SPATIALIZER) {
6182 memset(mPostSpatializerBuffer, 0, mPostSpatializerBufferSize);
6183 }
Eric Laurent97d547d2014-09-02 14:45:53 -07006184 }
Andy Hung69aed5f2014-02-25 17:24:40 -08006185 // sink or mix buffer must be cleared if all tracks are connected to an
6186 // effect chain as in this case the mixer will not write to the sink or mix buffer
6187 // and track effects will accumulate into it
Eric Laurent39095982021-08-24 18:29:27 +02006188 // always clear sink buffer for spatializer output as the output of the spatializer
6189 // effect will be accumulated into it
6190 if ((mBytesRemaining == 0) && (((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
6191 (mixedTracks == 0 && fastTracks > 0)) || (mType == SPATIALIZER))) {
Eric Laurent81784c32012-11-19 14:55:58 -08006192 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08006193 if (mMixerBufferValid) {
6194 memset(mMixerBuffer, 0, mMixerBufferSize);
6195 // TODO: In testing, mSinkBuffer below need not be cleared because
6196 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
6197 // after mixing.
6198 //
6199 // To enforce this guarantee:
6200 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
6201 // (mixedTracks == 0 && fastTracks > 0))
6202 // must imply MIXER_TRACKS_READY.
6203 // Later, we may clear buffers regardless, and skip much of this logic.
6204 }
Andy Hung98ef9782014-03-04 14:46:50 -08006205 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07006206 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08006207 }
6208
6209 // if any fast tracks, then status is ready
6210 mMixerStatusIgnoringFastTracks = mixerStatus;
6211 if (fastTracks > 0) {
6212 mixerStatus = MIXER_TRACKS_READY;
6213 }
6214 return mixerStatus;
6215}
6216
Andy Hungc5007f82023-08-29 14:26:09 -07006217// trackCountForUid_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07006218uint32_t PlaybackThread::trackCountForUid_l(uid_t uid) const
Eric Laurentad7dd962016-09-22 12:38:37 -07006219{
6220 uint32_t trackCount = 0;
6221 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hung1f12a8a2016-11-07 16:10:30 -08006222 if (mTracks[i]->uid() == uid) {
Eric Laurentad7dd962016-09-22 12:38:37 -07006223 trackCount++;
6224 }
6225 }
6226 return trackCount;
6227}
6228
Andy Hungee58e4a2023-07-07 13:47:37 -07006229bool PlaybackThread::IsTimestampAdvancing::check(AudioStreamOut* output)
ziyangch8f194f12021-12-01 13:48:04 -08006230{
Brian Lindahl65e90012022-07-27 18:01:07 +02006231 // Check the timestamp to see if it's advancing once every 150ms. If we check too frequently, we
6232 // could falsely detect that the frame position has stalled due to underrun because we haven't
6233 // given the Audio HAL enough time to update.
6234 const nsecs_t nowNs = systemTime();
6235 if (nowNs - mPreviousNs < mMinimumTimeBetweenChecksNs) {
6236 return mLatchedValue;
6237 }
6238 mPreviousNs = nowNs;
6239 mLatchedValue = false;
6240 // Determine if the presentation position is still advancing.
ziyangch8f194f12021-12-01 13:48:04 -08006241 uint64_t position = 0;
6242 struct timespec unused;
Brian Lindahl65e90012022-07-27 18:01:07 +02006243 const status_t ret = output->getPresentationPosition(&position, &unused);
ziyangch8f194f12021-12-01 13:48:04 -08006244 if (ret == NO_ERROR) {
Brian Lindahl65e90012022-07-27 18:01:07 +02006245 if (position != mPreviousPosition) {
6246 mPreviousPosition = position;
6247 mLatchedValue = true;
ziyangch8f194f12021-12-01 13:48:04 -08006248 }
6249 }
Brian Lindahl65e90012022-07-27 18:01:07 +02006250 return mLatchedValue;
6251}
6252
Andy Hungee58e4a2023-07-07 13:47:37 -07006253void PlaybackThread::IsTimestampAdvancing::clear()
Brian Lindahl65e90012022-07-27 18:01:07 +02006254{
6255 mLatchedValue = true;
6256 mPreviousPosition = 0;
6257 mPreviousNs = 0;
ziyangch8f194f12021-12-01 13:48:04 -08006258}
6259
Andy Hungc5007f82023-08-29 14:26:09 -07006260// isTrackAllowed_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07006261bool MixerThread::isTrackAllowed_l(
Andy Hung1bc088a2018-02-09 15:57:31 -08006262 audio_channel_mask_t channelMask, audio_format_t format,
6263 audio_session_t sessionId, uid_t uid) const
Eric Laurent81784c32012-11-19 14:55:58 -08006264{
Andy Hung1bc088a2018-02-09 15:57:31 -08006265 if (!PlaybackThread::isTrackAllowed_l(channelMask, format, sessionId, uid)) {
6266 return false;
Eric Laurentad7dd962016-09-22 12:38:37 -07006267 }
Andy Hung1bc088a2018-02-09 15:57:31 -08006268 // Check validity as we don't call AudioMixer::create() here.
Mikhail Naganov7ad7a252019-07-30 14:42:32 -07006269 if (!mAudioMixer->isValidFormat(format)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08006270 ALOGW("%s: invalid format: %#x", __func__, format);
6271 return false;
6272 }
Mikhail Naganov7ad7a252019-07-30 14:42:32 -07006273 if (!mAudioMixer->isValidChannelMask(channelMask)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08006274 ALOGW("%s: invalid channelMask: %#x", __func__, channelMask);
6275 return false;
6276 }
6277 return true;
Eric Laurent81784c32012-11-19 14:55:58 -08006278}
6279
Andy Hungc5007f82023-08-29 14:26:09 -07006280// checkForNewParameter_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07006281bool MixerThread::checkForNewParameter_l(const String8& keyValuePair,
Eric Laurent10351942014-05-08 18:49:52 -07006282 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08006283{
Eric Laurent81784c32012-11-19 14:55:58 -08006284 bool reconfig = false;
Eric Laurent10351942014-05-08 18:49:52 -07006285 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006286
Glenn Kastenc05b8d72016-03-24 09:48:17 -07006287 AutoPark<FastMixer> park(mFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08006288
Eric Laurent10351942014-05-08 18:49:52 -07006289 AudioParameter param = AudioParameter(keyValuePair);
6290 int value;
6291 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
6292 reconfig = true;
6293 }
6294 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung81994d62023-07-20 21:44:14 -07006295 if (!isValidPcmSinkFormat(static_cast<audio_format_t>(value))) {
Eric Laurent10351942014-05-08 18:49:52 -07006296 status = BAD_VALUE;
6297 } else {
6298 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08006299 reconfig = true;
6300 }
Eric Laurent10351942014-05-08 18:49:52 -07006301 }
6302 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hung81994d62023-07-20 21:44:14 -07006303 if (!isValidPcmSinkChannelMask(static_cast<audio_channel_mask_t>(value))) {
Eric Laurent10351942014-05-08 18:49:52 -07006304 status = BAD_VALUE;
6305 } else {
6306 // no need to save value, since it's constant
6307 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006308 }
Eric Laurent10351942014-05-08 18:49:52 -07006309 }
6310 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6311 // do not accept frame count changes if tracks are open as the track buffer
6312 // size depends on frame count and correct behavior would not be guaranteed
6313 // if frame count is changed after track creation
6314 if (!mTracks.isEmpty()) {
6315 status = INVALID_OPERATION;
6316 } else {
6317 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006318 }
Eric Laurent10351942014-05-08 18:49:52 -07006319 }
6320 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07006321 LOG_FATAL("Should not set routing device in MixerThread");
Eric Laurent10351942014-05-08 18:49:52 -07006322 }
Eric Laurent81784c32012-11-19 14:55:58 -08006323
Eric Laurent10351942014-05-08 18:49:52 -07006324 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006325 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07006326 if (!mStandby && status == INVALID_OPERATION) {
Andy Hungdda7aed2023-03-27 15:53:06 -07006327 ALOGW("%s: setParameters failed with keyValuePair %s, entering standby",
6328 __func__, keyValuePair.c_str());
Phil Burk062e67a2015-02-11 13:40:50 -08006329 mOutput->standby();
Andy Hungdda7aed2023-03-27 15:53:06 -07006330 mThreadMetrics.logEndInterval();
6331 mThreadSnapshot.onEnd();
6332 setStandby_l();
Eric Laurent10351942014-05-08 18:49:52 -07006333 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006334 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent81784c32012-11-19 14:55:58 -08006335 }
Eric Laurent10351942014-05-08 18:49:52 -07006336 if (status == NO_ERROR && reconfig) {
6337 readOutputParameters_l();
6338 delete mAudioMixer;
6339 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
Andy Hung1bc088a2018-02-09 15:57:31 -08006340 for (const auto &track : mTracks) {
Andy Hungc0691382018-09-12 18:01:57 -07006341 const int trackId = track->id();
Andy Hung920f6572022-10-06 12:09:49 -07006342 const status_t createStatus = mAudioMixer->create(
Andy Hungc0691382018-09-12 18:01:57 -07006343 trackId,
Andy Hung8d31fd22023-06-26 19:20:57 -07006344 track->channelMask(),
6345 track->format(),
6346 track->sessionId());
Andy Hung920f6572022-10-06 12:09:49 -07006347 ALOGW_IF(createStatus != NO_ERROR,
Andy Hungc0691382018-09-12 18:01:57 -07006348 "%s(): AudioMixer cannot create track(%d)"
6349 " mask %#x, format %#x, sessionId %d",
Andy Hung1bc088a2018-02-09 15:57:31 -08006350 __func__,
Andy Hung8d31fd22023-06-26 19:20:57 -07006351 trackId, track->channelMask(), track->format(), track->sessionId());
Eric Laurent10351942014-05-08 18:49:52 -07006352 }
Eric Laurent73e26b62015-04-27 16:55:58 -07006353 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07006354 }
Eric Laurent81784c32012-11-19 14:55:58 -08006355 }
6356
Dean Wheatley68918102021-03-19 22:09:19 +11006357 return reconfig;
Eric Laurent81784c32012-11-19 14:55:58 -08006358}
6359
6360
Andy Hungee58e4a2023-07-07 13:47:37 -07006361void MixerThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -08006362{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07006363 PlaybackThread::dumpInternals_l(fd, args);
Andy Hung8d672e02023-09-15 18:19:28 -07006364 dprintf(fd, " Thread throttle time (msecs): %u\n", (uint32_t)mThreadThrottleTimeMs);
Andy Hung8ed196a2018-01-05 13:21:11 -08006365 dprintf(fd, " AudioMixer tracks: %s\n", mAudioMixer->trackNames().c_str());
Andy Hung2ddee192015-12-18 17:34:44 -08006366 dprintf(fd, " Master mono: %s\n", mMasterMono ? "on" : "off");
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006367 dprintf(fd, " Master balance: %f (%s)\n", mMasterBalance.load(),
6368 (hasFastMixer() ? std::to_string(mFastMixer->getMasterBalance())
6369 : mBalance.toString()).c_str());
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006370 if (hasFastMixer()) {
6371 dprintf(fd, " FastMixer thread %p tid=%d", mFastMixer.get(), mFastMixer->getTid());
6372
6373 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
6374 // while we are dumping it. It may be inconsistent, but it won't mutate!
6375 // This is a large object so we place it on the heap.
6376 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
Eric Tan2942a4e2018-09-12 17:41:27 -07006377 const std::unique_ptr<FastMixerDumpState> copy =
6378 std::make_unique<FastMixerDumpState>(mFastMixerDumpState);
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006379 copy->dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08006380
6381#ifdef STATE_QUEUE_DUMP
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006382 // Similar for state queue
6383 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
6384 observerCopy.dump(fd);
6385 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
6386 mutatorCopy.dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08006387#endif
6388
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006389#ifdef AUDIO_WATCHDOG
6390 if (mAudioWatchdog != 0) {
6391 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
6392 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
6393 wdCopy.dump(fd);
6394 }
6395#endif
6396
6397 } else {
6398 dprintf(fd, " No FastMixer\n");
6399 }
Eric Laurent90cea102023-05-15 15:08:27 +02006400
6401 dprintf(fd, "Bluetooth latency modes are %senabled\n",
6402 mBluetoothLatencyModesEnabled ? "" : "not ");
6403 dprintf(fd, "HAL does %ssupport Bluetooth latency modes\n", mOutput != nullptr &&
6404 mOutput->audioHwDev->supportsBluetoothVariableLatency() ? "" : "not ");
6405 dprintf(fd, "Supported latency modes: %s\n", toString(mSupportedLatencyModes).c_str());
Eric Laurent81784c32012-11-19 14:55:58 -08006406}
6407
Andy Hungee58e4a2023-07-07 13:47:37 -07006408uint32_t MixerThread::idleSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08006409{
6410 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
6411}
6412
Andy Hungee58e4a2023-07-07 13:47:37 -07006413uint32_t MixerThread::suspendSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08006414{
6415 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
6416}
6417
Andy Hungee58e4a2023-07-07 13:47:37 -07006418void MixerThread::cacheParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08006419{
6420 PlaybackThread::cacheParameters_l();
6421
6422 // FIXME: Relaxed timing because of a certain device that can't meet latency
6423 // Should be reduced to 2x after the vendor fixes the driver issue
6424 // increase threshold again due to low power audio mode. The way this warning
6425 // threshold is calculated and its usefulness should be reconsidered anyway.
6426 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
6427}
6428
Andy Hungee58e4a2023-07-07 13:47:37 -07006429void MixerThread::onHalLatencyModesChanged_l() {
Andy Hung583043b2023-07-17 17:05:00 -07006430 mAfThreadCallback->onSupportedLatencyModesChanged(mId, mSupportedLatencyModes);
Eric Laurentb0463942022-12-20 16:31:10 +01006431}
6432
Andy Hungee58e4a2023-07-07 13:47:37 -07006433void MixerThread::setHalLatencyMode_l() {
Eric Laurentb0463942022-12-20 16:31:10 +01006434 // Only handle latency mode if:
6435 // - mBluetoothLatencyModesEnabled is true
6436 // - the HAL supports latency modes
6437 // - the selected device is Bluetooth LE or A2DP
6438 if (!mBluetoothLatencyModesEnabled.load() || mSupportedLatencyModes.empty()) {
6439 return;
6440 }
6441 if (mOutDeviceTypeAddrs.size() != 1
6442 || !(audio_is_a2dp_out_device(mOutDeviceTypeAddrs[0].mType)
6443 || audio_is_ble_out_device(mOutDeviceTypeAddrs[0].mType))) {
6444 return;
6445 }
6446
6447 audio_latency_mode_t latencyMode = AUDIO_LATENCY_MODE_FREE;
6448 if (mSupportedLatencyModes.size() == 1) {
6449 // If the HAL only support one latency mode currently, confirm the choice
6450 latencyMode = mSupportedLatencyModes[0];
6451 } else if (mSupportedLatencyModes.size() > 1) {
6452 // Request low latency if:
6453 // - At least one active track is either:
6454 // - a fast track with gaming usage or
6455 // - a track with acessibility usage
6456 for (const auto& track : mActiveTracks) {
6457 if ((track->isFastTrack() && track->attributes().usage == AUDIO_USAGE_GAME)
6458 || track->attributes().usage == AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY) {
6459 latencyMode = AUDIO_LATENCY_MODE_LOW;
6460 break;
6461 }
6462 }
6463 }
6464
6465 if (latencyMode != mSetLatencyMode) {
6466 status_t status = mOutput->stream->setLatencyMode(latencyMode);
6467 ALOGD("%s: thread(%d) setLatencyMode(%s) returned %d",
6468 __func__, mId, toString(latencyMode).c_str(), status);
6469 if (status == NO_ERROR) {
6470 mSetLatencyMode = latencyMode;
6471 }
6472 }
6473}
6474
Andy Hungee58e4a2023-07-07 13:47:37 -07006475void MixerThread::updateHalSupportedLatencyModes_l() {
Eric Laurentb0463942022-12-20 16:31:10 +01006476
6477 if (mOutput == nullptr || mOutput->stream == nullptr) {
6478 return;
6479 }
6480 std::vector<audio_latency_mode_t> latencyModes;
6481 const status_t status = mOutput->stream->getRecommendedLatencyModes(&latencyModes);
6482 if (status != NO_ERROR) {
6483 latencyModes.clear();
6484 }
6485 if (latencyModes != mSupportedLatencyModes) {
6486 ALOGD("%s: thread(%d) status %d supported latency modes: %s",
6487 __func__, mId, status, toString(latencyModes).c_str());
6488 mSupportedLatencyModes.swap(latencyModes);
6489 sendHalLatencyModesChangedEvent_l();
6490 }
6491}
6492
Andy Hungee58e4a2023-07-07 13:47:37 -07006493status_t MixerThread::getSupportedLatencyModes(
Eric Laurentb0463942022-12-20 16:31:10 +01006494 std::vector<audio_latency_mode_t>* modes) {
6495 if (modes == nullptr) {
6496 return BAD_VALUE;
6497 }
Andy Hung972bec12023-08-31 16:13:39 -07006498 audio_utils::lock_guard _l(mutex());
Eric Laurentb0463942022-12-20 16:31:10 +01006499 *modes = mSupportedLatencyModes;
6500 return NO_ERROR;
6501}
6502
Andy Hungee58e4a2023-07-07 13:47:37 -07006503void MixerThread::onRecommendedLatencyModeChanged(
Eric Laurentb0463942022-12-20 16:31:10 +01006504 std::vector<audio_latency_mode_t> modes) {
Andy Hung972bec12023-08-31 16:13:39 -07006505 audio_utils::lock_guard _l(mutex());
Eric Laurentb0463942022-12-20 16:31:10 +01006506 if (modes != mSupportedLatencyModes) {
6507 ALOGD("%s: thread(%d) supported latency modes: %s",
6508 __func__, mId, toString(modes).c_str());
6509 mSupportedLatencyModes.swap(modes);
6510 sendHalLatencyModesChangedEvent_l();
6511 }
6512}
6513
Andy Hungee58e4a2023-07-07 13:47:37 -07006514status_t MixerThread::setBluetoothVariableLatencyEnabled(bool enabled) {
Eric Laurentb0463942022-12-20 16:31:10 +01006515 if (mOutput == nullptr || mOutput->audioHwDev == nullptr
6516 || !mOutput->audioHwDev->supportsBluetoothVariableLatency()) {
6517 return INVALID_OPERATION;
6518 }
6519 mBluetoothLatencyModesEnabled.store(enabled);
6520 return NO_ERROR;
6521}
6522
Eric Laurent81784c32012-11-19 14:55:58 -08006523// ----------------------------------------------------------------------------
6524
Andy Hungee58e4a2023-07-07 13:47:37 -07006525/* static */
6526sp<IAfPlaybackThread> IAfPlaybackThread::createDirectOutputThread(
Andy Hung583043b2023-07-17 17:05:00 -07006527 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hungee58e4a2023-07-07 13:47:37 -07006528 AudioStreamOut* output, audio_io_handle_t id, bool systemReady,
6529 const audio_offload_info_t& offloadInfo) {
6530 return sp<DirectOutputThread>::make(
Andy Hung583043b2023-07-17 17:05:00 -07006531 afThreadCallback, output, id, systemReady, offloadInfo);
Andy Hungee58e4a2023-07-07 13:47:37 -07006532}
6533
Andy Hung583043b2023-07-17 17:05:00 -07006534DirectOutputThread::DirectOutputThread(const sp<IAfThreadCallback>& afThreadCallback,
Gareth Fennb18c1a32022-10-05 13:42:36 -07006535 AudioStreamOut* output, audio_io_handle_t id, ThreadBase::type_t type, bool systemReady,
6536 const audio_offload_info_t& offloadInfo)
Andy Hung583043b2023-07-17 17:05:00 -07006537 : PlaybackThread(afThreadCallback, output, id, type, systemReady)
Gareth Fennb18c1a32022-10-05 13:42:36 -07006538 , mOffloadInfo(offloadInfo)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006539{
Andy Hung583043b2023-07-17 17:05:00 -07006540 setMasterBalance(afThreadCallback->getMasterBalance_l());
Eric Laurentbfb1b832013-01-07 09:53:42 -08006541}
6542
Andy Hungee58e4a2023-07-07 13:47:37 -07006543DirectOutputThread::~DirectOutputThread()
Eric Laurent81784c32012-11-19 14:55:58 -08006544{
6545}
6546
Andy Hungee58e4a2023-07-07 13:47:37 -07006547void DirectOutputThread::dumpInternals_l(int fd, const Vector<String16>& args)
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006548{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07006549 PlaybackThread::dumpInternals_l(fd, args);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006550 dprintf(fd, " Master balance: %f Left: %f Right: %f\n",
6551 mMasterBalance.load(), mMasterBalanceLeft, mMasterBalanceRight);
6552}
6553
Andy Hungee58e4a2023-07-07 13:47:37 -07006554void DirectOutputThread::setMasterBalance(float balance)
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006555{
Andy Hung972bec12023-08-31 16:13:39 -07006556 audio_utils::lock_guard _l(mutex());
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006557 if (mMasterBalance != balance) {
6558 mMasterBalance.store(balance);
6559 mBalance.computeStereoBalance(balance, &mMasterBalanceLeft, &mMasterBalanceRight);
6560 broadcast_l();
6561 }
6562}
6563
Andy Hungee58e4a2023-07-07 13:47:37 -07006564void DirectOutputThread::processVolume_l(IAfTrack* track, bool lastTrack)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006565{
Eric Laurentbfb1b832013-01-07 09:53:42 -08006566 float left, right;
6567
Andy Hung333ab962019-05-28 20:23:35 -07006568 // Ensure volumeshaper state always advances even when muted.
Andy Hung8d31fd22023-06-26 19:20:57 -07006569 const sp<AudioTrackServerProxy> proxy = track->audioTrackServerProxy();
Andy Hung398ffa22022-12-13 19:19:53 -08006570
Andy Hung398ffa22022-12-13 19:19:53 -08006571 const int64_t frames = mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
6572 const int64_t time = mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
6573
Dean Wheatleyb11b0022023-09-12 04:07:35 +10006574 ALOGVV("%s: Direct/Offload bufferConsumed:%zu timestamp frames:%lld time:%lld",
6575 __func__, proxy->framesReleased(), (long long)frames, (long long)time);
Andy Hung398ffa22022-12-13 19:19:53 -08006576
6577 const int64_t volumeShaperFrames =
6578 mMonotonicFrameCounter.updateAndGetMonotonicFrameCount(frames, time);
6579 const auto [shaperVolume, shaperActive] =
6580 track->getVolumeHandler()->getVolume(volumeShaperFrames);
Andy Hung333ab962019-05-28 20:23:35 -07006581 mVolumeShaperActive = shaperActive;
6582
Vlad Popae2f5aef2022-07-25 16:00:20 +02006583 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
6584 left = float_from_gain(gain_minifloat_unpack_left(vlr));
6585 right = float_from_gain(gain_minifloat_unpack_right(vlr));
6586
6587 const bool clientVolumeMute = (left == 0.f && right == 0.f);
6588
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08006589 if (mMasterMute || mStreamTypes[track->streamType()].mute || track->isPlaybackRestricted()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08006590 left = right = 0;
6591 } else {
6592 float typeVolume = mStreamTypes[track->streamType()].volume;
Andy Hung333ab962019-05-28 20:23:35 -07006593 const float v = mMasterVolume * typeVolume * shaperVolume;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08006594
Glenn Kastenc56f3422014-03-21 17:53:17 -07006595 if (left > GAIN_FLOAT_UNITY) {
6596 left = GAIN_FLOAT_UNITY;
6597 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07006598 if (right > GAIN_FLOAT_UNITY) {
6599 right = GAIN_FLOAT_UNITY;
6600 }
zhangjincheng86cb3bc2023-01-16 17:17:38 +08006601 left *= v;
6602 right *= v;
Andy Hung583043b2023-07-17 17:05:00 -07006603 if (mAfThreadCallback->getMode() != AUDIO_MODE_IN_COMMUNICATION
zhangjincheng86cb3bc2023-01-16 17:17:38 +08006604 || audio_channel_count_from_out_mask(mChannelMask) > 1) {
6605 left *= mMasterBalanceLeft; // DirectOutputThread balance applied as track volume
6606 right *= mMasterBalanceRight;
6607 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006608 }
6609
Andy Hung583043b2023-07-17 17:05:00 -07006610 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
Vlad Popae8d99472022-06-30 16:02:48 +02006611 /*muteState=*/{mMasterMute,
6612 mStreamTypes[track->streamType()].volume == 0.f,
6613 mStreamTypes[track->streamType()].mute,
Vlad Popae2f5aef2022-07-25 16:00:20 +02006614 track->isPlaybackRestricted(),
Vlad Popa436c9172022-08-02 15:25:08 +02006615 clientVolumeMute,
6616 shaperVolume == 0.f});
Vlad Popae8d99472022-06-30 16:02:48 +02006617
Eric Laurentbfb1b832013-01-07 09:53:42 -08006618 if (lastTrack) {
jiabin76d94692022-12-15 21:51:21 +00006619 track->setFinalVolume(left, right);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006620 if (left != mLeftVolFloat || right != mRightVolFloat) {
6621 mLeftVolFloat = left;
6622 mRightVolFloat = right;
6623
Eric Laurentbfb1b832013-01-07 09:53:42 -08006624 // Delegate volume control to effect in track effect chain if needed
6625 // only one effect chain can be present on DirectOutputThread, so if
6626 // there is one, the track is connected to it
6627 if (!mEffectChains.isEmpty()) {
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09006628 // if effect chain exists, volume is handled by it.
6629 // Convert volumes from float to 8.24
6630 uint32_t vl = (uint32_t)(left * (1 << 24));
6631 uint32_t vr = (uint32_t)(right * (1 << 24));
6632 // Direct/Offload effect chains set output volume in setVolume_l().
6633 (void)mEffectChains[0]->setVolume_l(&vl, &vr);
6634 } else {
6635 // otherwise we directly set the volume.
6636 setVolumeForOutput_l(left, right);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006637 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006638 }
6639 }
6640}
6641
Andy Hungee58e4a2023-07-07 13:47:37 -07006642void DirectOutputThread::onAddNewTrack_l()
Phil Burk43b4dcc2015-06-09 16:53:44 -07006643{
Andy Hung8d31fd22023-06-26 19:20:57 -07006644 sp<IAfTrack> previousTrack = mPreviousTrack.promote();
6645 sp<IAfTrack> latestTrack = mActiveTracks.getLatest();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006646
Eric Laurent0f0631e2015-07-06 18:01:25 -07006647 if (previousTrack != 0 && latestTrack != 0) {
6648 if (mType == DIRECT) {
6649 if (previousTrack.get() != latestTrack.get()) {
6650 mFlushPending = true;
6651 }
6652 } else /* mType == OFFLOAD */ {
Dean Wheatley0f51fd02022-08-31 16:41:40 +10006653 if (previousTrack->sessionId() != latestTrack->sessionId() ||
6654 previousTrack->isFlushPending()) {
Eric Laurent0f0631e2015-07-06 18:01:25 -07006655 mFlushPending = true;
6656 }
6657 }
Revathi Uddaraju20413a92016-10-13 17:16:14 +08006658 } else if (previousTrack == 0) {
6659 // there could be an old track added back during track transition for direct
6660 // output, so always issues flush to flush data of the previous track if it
6661 // was already destroyed with HAL paused, then flush can resume the playback
6662 mFlushPending = true;
Phil Burk43b4dcc2015-06-09 16:53:44 -07006663 }
6664 PlaybackThread::onAddNewTrack_l();
6665}
Eric Laurentbfb1b832013-01-07 09:53:42 -08006666
Andy Hungee58e4a2023-07-07 13:47:37 -07006667PlaybackThread::mixer_state DirectOutputThread::prepareTracks_l(
Andy Hung8d31fd22023-06-26 19:20:57 -07006668 Vector<sp<IAfTrack>>* tracksToRemove
Eric Laurent81784c32012-11-19 14:55:58 -08006669)
6670{
Eric Laurentd595b7c2013-04-03 17:27:56 -07006671 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08006672 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006673 bool doHwPause = false;
6674 bool doHwResume = false;
Eric Laurent81784c32012-11-19 14:55:58 -08006675
6676 // find out which tracks need to be processed
Andy Hung8d31fd22023-06-26 19:20:57 -07006677 for (const sp<IAfTrack>& t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08006678 if (t->isInvalid()) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07006679 ALOGW("An invalidated track shouldn't be in active list");
Eric Laurent5850c4c2016-11-10 13:04:31 -08006680 tracksToRemove->add(t);
Phil Burk43b4dcc2015-06-09 16:53:44 -07006681 continue;
6682 }
6683
Andy Hung8d31fd22023-06-26 19:20:57 -07006684 IAfTrack* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006685#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurent81784c32012-11-19 14:55:58 -08006686 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006687#endif
Eric Laurentfd477972013-10-25 18:10:40 -07006688 // Only consider last track started for volume and mixer state control.
6689 // In theory an older track could underrun and restart after the new one starts
6690 // but as we only care about the transition phase between two tracks on a
6691 // direct output, it is not a problem to ignore the underrun case.
Andy Hung8d31fd22023-06-26 19:20:57 -07006692 sp<IAfTrack> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08006693 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08006694
Kuowei Li23666472021-01-20 10:23:25 +08006695 if (track->isPausePending()) {
6696 track->pauseAck();
6697 // It is possible a track might have been flushed or stopped.
6698 // Other operations such as flush pending might occur on the next prepare.
6699 if (track->isPausing()) {
6700 track->setPaused();
6701 }
6702 // Always perform pause, as an immediate flush will change
6703 // the pause state to be no longer isPausing().
Phil Burk6fc2a7c2015-04-30 16:08:10 -07006704 if (mHwSupportsPause && last && !mHwPaused) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006705 doHwPause = true;
6706 mHwPaused = true;
6707 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08006708 } else if (track->isFlushPending()) {
6709 track->flushAck();
6710 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07006711 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006712 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07006713 } else if (track->isResumePending()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006714 track->resumeAck();
Eric Laurent3df841a2016-07-15 15:15:40 -07006715 if (last) {
6716 mLeftVolFloat = mRightVolFloat = -1.0;
6717 if (mHwPaused) {
6718 doHwResume = true;
6719 mHwPaused = false;
6720 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08006721 }
6722 }
6723
Eric Laurent81784c32012-11-19 14:55:58 -08006724 // The first time a track is added we wait
Phil Burk99adee32014-12-10 16:46:30 -08006725 // for all its buffers to be filled before processing it.
6726 // Allow draining the buffer in case the client
6727 // app does not call stop() and relies on underrun to stop:
Andy Hung8d31fd22023-06-26 19:20:57 -07006728 // hence the test on (track->retryCount() > 1).
6729 // If track->retryCount() <= 1 then track is about to be disabled, paused, removed,
Andy Hung455982f2021-04-27 17:46:12 -07006730 // so we accept any nonzero amount of data delivered by the AudioTrack (which will
6731 // reset the retry counter).
Phil Burkca5e6142015-07-14 09:42:29 -07006732 // Do not use a high threshold for compressed audio.
Andy Hung455982f2021-04-27 17:46:12 -07006733
6734 // target retry count that we will use is based on the time we wait for retries.
6735 const int32_t targetRetryCount = kMaxTrackRetriesDirectMs * 1000 / mActiveSleepTimeUs;
6736 // the retry threshold is when we accept any size for PCM data. This is slightly
6737 // smaller than the retry count so we can push small bits of data without a glitch.
6738 const int32_t retryThreshold = targetRetryCount > 2 ? targetRetryCount - 1 : 1;
Eric Laurent81784c32012-11-19 14:55:58 -08006739 uint32_t minFrames;
Phil Burk99adee32014-12-10 16:46:30 -08006740 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
Andy Hung8d31fd22023-06-26 19:20:57 -07006741 && (track->retryCount() > retryThreshold) && audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006742 minFrames = mNormalFrameCount;
6743 } else {
6744 minFrames = 1;
6745 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006746
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07006747 const size_t framesReady = track->framesReady();
6748 const int trackId = track->id();
6749 if (ATRACE_ENABLED()) {
6750 std::string traceName("nRdy");
6751 traceName += std::to_string(trackId);
6752 ATRACE_INT(traceName.c_str(), framesReady);
6753 }
6754 if ((framesReady >= minFrames) && track->isReady() && !track->isPaused() &&
Eric Laurentab5cdba2014-06-09 17:22:27 -07006755 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08006756 {
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07006757 ALOGVV("track(%d) s=%08x [OK]", trackId, cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08006758
Andy Hung8d31fd22023-06-26 19:20:57 -07006759 if (track->fillingStatus() == IAfTrack::FS_FILLED) {
6760 track->fillingStatus() = IAfTrack::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07006761 if (last) {
6762 // make sure processVolume_l() will apply new volume even if 0
6763 mLeftVolFloat = mRightVolFloat = -1.0;
6764 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08006765 if (!mHwSupportsPause) {
6766 track->resumeAck();
Eric Laurent81784c32012-11-19 14:55:58 -08006767 }
6768 }
6769
6770 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08006771 processVolume_l(track, last);
6772 if (last) {
Andy Hung8d31fd22023-06-26 19:20:57 -07006773 sp<IAfTrack> previousTrack = mPreviousTrack.promote();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006774 if (previousTrack != 0) {
6775 if (track != previousTrack.get()) {
6776 // Flush any data still being written from last track
6777 mBytesRemaining = 0;
Eric Laurent0f0631e2015-07-06 18:01:25 -07006778 // Invalidate previous track to force a seek when resuming.
6779 previousTrack->invalidate();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006780 }
6781 }
6782 mPreviousTrack = track;
6783
Eric Laurentd595b7c2013-04-03 17:27:56 -07006784 // reset retry count
Andy Hung8d31fd22023-06-26 19:20:57 -07006785 track->retryCount() = targetRetryCount;
Eric Laurent5850c4c2016-11-10 13:04:31 -08006786 mActiveTrack = t;
Eric Laurentd595b7c2013-04-03 17:27:56 -07006787 mixerStatus = MIXER_TRACKS_READY;
Eric Laurent5cff4032015-05-26 13:49:58 -07006788 if (mHwPaused) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08006789 doHwResume = true;
6790 mHwPaused = false;
6791 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07006792 }
Eric Laurent81784c32012-11-19 14:55:58 -08006793 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07006794 // clear effect chain input buffer if the last active track started underruns
6795 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07006796 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08006797 mEffectChains[0]->clearInputBuffer();
6798 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07006799 if (track->isStopping_1()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07006800 track->setState(IAfTrackBase::STOPPING_2);
Eric Laurentb369caf2015-03-30 20:51:47 -07006801 if (last && mHwPaused) {
6802 doHwResume = true;
6803 mHwPaused = false;
6804 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07006805 }
6806 if ((track->sharedBuffer() != 0) || track->isStopped() ||
6807 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08006808 // We have consumed all the buffers of this track.
6809 // Remove it from the list of active tracks.
Atneya Nair0cae0432022-05-10 18:12:12 -04006810 bool presComplete = false;
Eric Laurentfd477972013-10-25 18:10:40 -07006811 if (mStandby || !last ||
Atneya Nair0cae0432022-05-10 18:12:12 -04006812 (presComplete = track->presentationComplete(latency_l())) ||
Jindong32dc26e2019-11-11 18:10:01 +08006813 track->isPaused() || mHwPaused) {
Atneya Nair0cae0432022-05-10 18:12:12 -04006814 if (presComplete) {
6815 mOutput->presentationComplete();
6816 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07006817 if (track->isStopping_2()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07006818 track->setState(IAfTrackBase::STOPPED);
Eric Laurentab5cdba2014-06-09 17:22:27 -07006819 }
Eric Laurent81784c32012-11-19 14:55:58 -08006820 if (track->isStopped()) {
6821 track->reset();
6822 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07006823 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08006824 }
6825 } else {
6826 // No buffers for this track. Give it a few chances to
6827 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07006828 // Only consider last track started for mixer state control
Brian Lindahl65e90012022-07-27 18:01:07 +02006829 bool isTimestampAdvancing = mIsTimestampAdvancing.check(mOutput);
Gareth Fennb18c1a32022-10-05 13:42:36 -07006830 if (!isTunerStream() // tuner streams remain active in underrun
Andy Hung8d31fd22023-06-26 19:20:57 -07006831 && --(track->retryCount()) <= 0) {
Brian Lindahl65e90012022-07-27 18:01:07 +02006832 if (isTimestampAdvancing) { // HAL is still playing audio, give us more time.
Andy Hung8d31fd22023-06-26 19:20:57 -07006833 track->retryCount() = kMaxTrackRetriesOffload;
ziyangch8f194f12021-12-01 13:48:04 -08006834 } else {
6835 ALOGV("BUFFER TIMEOUT: remove track(%d) from active list", trackId);
6836 tracksToRemove->add(track);
6837 // indicate to client process that the track was disabled because of
6838 // underrun; it will then automatically call start() when data is available
6839 track->disable();
6840 // only do hw pause when track is going to be removed due to BUFFER TIMEOUT.
6841 // unlike mixerthread, HAL can be paused for direct output
6842 ALOGW("pause because of UNDERRUN, framesReady = %zu,"
6843 "minFrames = %u, mFormat = %#x",
6844 framesReady, minFrames, mFormat);
6845 if (last && mHwSupportsPause && !mHwPaused && !mStandby) {
6846 doHwPause = true;
6847 mHwPaused = true;
6848 }
Eric Laurent0f7b5f22014-12-19 10:43:21 -08006849 }
Haynes Mathew George5c6daae2017-01-24 20:06:05 -08006850 } else if (last) {
6851 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurent81784c32012-11-19 14:55:58 -08006852 }
6853 }
6854 }
6855 }
6856
Eric Laurentd1f69b02014-12-15 14:33:13 -08006857 // if an active track did not command a flush, check for pending flush on stopped tracks
Phil Burk43b4dcc2015-06-09 16:53:44 -07006858 if (!mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006859 for (size_t i = 0; i < mTracks.size(); i++) {
6860 if (mTracks[i]->isFlushPending()) {
6861 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006862 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006863 }
6864 }
6865 }
6866
6867 // make sure the pause/flush/resume sequence is executed in the right order.
6868 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
6869 // before flush and then resume HW. This can happen in case of pause/flush/resume
6870 // if resume is received before pause is executed.
6871 if (mHwSupportsPause && !mStandby &&
Phil Burk43b4dcc2015-06-09 16:53:44 -07006872 (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006873 status_t result = mOutput->stream->pause();
6874 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Gareth Fenncd1e1622022-10-05 11:45:45 -07006875 doHwResume = !doHwPause; // resume if pause is due to flush.
Eric Laurentd1f69b02014-12-15 14:33:13 -08006876 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07006877 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006878 flushHw_l();
6879 }
6880 if (mHwSupportsPause && !mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006881 status_t result = mOutput->stream->resume();
6882 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08006883 }
Eric Laurent81784c32012-11-19 14:55:58 -08006884 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08006885 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08006886
6887 return mixerStatus;
6888}
6889
Andy Hungee58e4a2023-07-07 13:47:37 -07006890void DirectOutputThread::threadLoop_mix()
Eric Laurent81784c32012-11-19 14:55:58 -08006891{
Eric Laurent81784c32012-11-19 14:55:58 -08006892 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08006893 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08006894 // output audio to hardware
6895 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07006896 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08006897 buffer.frameCount = frameCount;
Phil Burk062e67a2015-02-11 13:40:50 -08006898 status_t status = mActiveTrack->getNextBuffer(&buffer);
6899 if (status != NO_ERROR || buffer.raw == NULL) {
Eric Laurent51716182016-02-29 18:00:56 -08006900 // no need to pad with 0 for compressed audio
6901 if (audio_has_proportional_frames(mFormat)) {
6902 memset(curBuf, 0, frameCount * mFrameSize);
6903 }
Eric Laurent81784c32012-11-19 14:55:58 -08006904 break;
6905 }
6906 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
6907 frameCount -= buffer.frameCount;
6908 curBuf += buffer.frameCount * mFrameSize;
6909 mActiveTrack->releaseBuffer(&buffer);
6910 }
Andy Hung2098f272014-02-27 14:00:06 -08006911 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006912 mSleepTimeUs = 0;
6913 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08006914 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08006915}
6916
Andy Hungee58e4a2023-07-07 13:47:37 -07006917void DirectOutputThread::threadLoop_sleepTime()
Eric Laurent81784c32012-11-19 14:55:58 -08006918{
Eric Laurentd1f69b02014-12-15 14:33:13 -08006919 // do not write to HAL when paused
Eric Laurent0f7b5f22014-12-19 10:43:21 -08006920 if (mHwPaused || (usesHwAvSync() && mStandby)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006921 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006922 return;
6923 }
Andy Hung85ba3332021-04-27 17:40:26 -07006924 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
6925 mSleepTimeUs = mActiveSleepTimeUs;
6926 } else {
6927 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006928 }
Andy Hung85ba3332021-04-27 17:40:26 -07006929 // Note: In S or later, we do not write zeroes for
6930 // linear or proportional PCM direct tracks in underrun.
Eric Laurent81784c32012-11-19 14:55:58 -08006931}
6932
Andy Hungee58e4a2023-07-07 13:47:37 -07006933void DirectOutputThread::threadLoop_exit()
Eric Laurentd1f69b02014-12-15 14:33:13 -08006934{
6935 {
Andy Hung972bec12023-08-31 16:13:39 -07006936 audio_utils::lock_guard _l(mutex());
Eric Laurentd1f69b02014-12-15 14:33:13 -08006937 for (size_t i = 0; i < mTracks.size(); i++) {
6938 if (mTracks[i]->isFlushPending()) {
6939 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006940 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006941 }
6942 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07006943 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006944 flushHw_l();
6945 }
6946 }
6947 PlaybackThread::threadLoop_exit();
6948}
6949
6950// must be called with thread mutex locked
Andy Hungee58e4a2023-07-07 13:47:37 -07006951bool DirectOutputThread::shouldStandby_l()
Eric Laurentd1f69b02014-12-15 14:33:13 -08006952{
6953 bool trackPaused = false;
Eric Laurentb369caf2015-03-30 20:51:47 -07006954 bool trackStopped = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006955
6956 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
6957 // after a timeout and we will enter standby then.
6958 if (mTracks.size() > 0) {
6959 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
Eric Laurentb369caf2015-03-30 20:51:47 -07006960 trackStopped = mTracks[mTracks.size() - 1]->isStopped() ||
Andy Hung8d31fd22023-06-26 19:20:57 -07006961 mTracks[mTracks.size() - 1]->state() == IAfTrackBase::IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006962 }
6963
Eric Laurent5cff4032015-05-26 13:49:58 -07006964 return !mStandby && !(trackPaused || (mHwPaused && !trackStopped));
Eric Laurentd1f69b02014-12-15 14:33:13 -08006965}
6966
Andy Hungc5007f82023-08-29 14:26:09 -07006967// checkForNewParameter_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07006968bool DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
Eric Laurent10351942014-05-08 18:49:52 -07006969 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08006970{
6971 bool reconfig = false;
Eric Laurent10351942014-05-08 18:49:52 -07006972 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006973
Eric Laurent10351942014-05-08 18:49:52 -07006974 AudioParameter param = AudioParameter(keyValuePair);
6975 int value;
6976 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07006977 LOG_FATAL("Should not set routing device in DirectOutputThread");
Eric Laurent81784c32012-11-19 14:55:58 -08006978 }
Eric Laurent10351942014-05-08 18:49:52 -07006979 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6980 // do not accept frame count changes if tracks are open as the track buffer
6981 // size depends on frame count and correct behavior would not be garantied
6982 // if frame count is changed after track creation
6983 if (!mTracks.isEmpty()) {
6984 status = INVALID_OPERATION;
6985 } else {
6986 reconfig = true;
6987 }
6988 }
6989 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006990 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07006991 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08006992 mOutput->standby();
Andy Hungcf10d742020-04-28 15:38:24 -07006993 if (!mStandby) {
6994 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07006995 mThreadSnapshot.onEnd();
Eric Laurent19952e12023-04-20 10:08:29 +02006996 setStandby_l();
Andy Hungcf10d742020-04-28 15:38:24 -07006997 }
Eric Laurent10351942014-05-08 18:49:52 -07006998 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006999 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07007000 }
7001 if (status == NO_ERROR && reconfig) {
7002 readOutputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07007003 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07007004 }
7005 }
7006
Dean Wheatley68918102021-03-19 22:09:19 +11007007 return reconfig;
Eric Laurent81784c32012-11-19 14:55:58 -08007008}
7009
Andy Hungee58e4a2023-07-07 13:47:37 -07007010uint32_t DirectOutputThread::activeSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08007011{
7012 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08007013 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08007014 time = PlaybackThread::activeSleepTimeUs();
7015 } else {
Eric Laurent51716182016-02-29 18:00:56 -08007016 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007017 }
7018 return time;
7019}
7020
Andy Hungee58e4a2023-07-07 13:47:37 -07007021uint32_t DirectOutputThread::idleSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08007022{
7023 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08007024 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08007025 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
7026 } else {
Eric Laurent51716182016-02-29 18:00:56 -08007027 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007028 }
7029 return time;
7030}
7031
Andy Hungee58e4a2023-07-07 13:47:37 -07007032uint32_t DirectOutputThread::suspendSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08007033{
7034 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08007035 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08007036 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
7037 } else {
Eric Laurent51716182016-02-29 18:00:56 -08007038 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007039 }
7040 return time;
7041}
7042
Andy Hungee58e4a2023-07-07 13:47:37 -07007043void DirectOutputThread::cacheParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08007044{
7045 PlaybackThread::cacheParameters_l();
7046
7047 // use shorter standby delay as on normal output to release
7048 // hardware resources as soon as possible
Eric Laurentb369caf2015-03-30 20:51:47 -07007049 // no delay on outputs with HW A/V sync
7050 if (usesHwAvSync()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007051 mStandbyDelayNs = 0;
Phil Burkfdb3c072016-02-09 10:47:02 -08007052 } else if ((mType == OFFLOAD) && !audio_has_proportional_frames(mFormat)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007053 mStandbyDelayNs = kOffloadStandbyDelayNs;
Eric Laurent5cff4032015-05-26 13:49:58 -07007054 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007055 mStandbyDelayNs = microseconds(mActiveSleepTimeUs*2);
Eric Laurent972a1732013-09-04 09:42:59 -07007056 }
Eric Laurent81784c32012-11-19 14:55:58 -08007057}
7058
Andy Hungee58e4a2023-07-07 13:47:37 -07007059void DirectOutputThread::flushHw_l()
Eric Laurente659ef42014-09-29 13:06:46 -07007060{
ziyangch8f194f12021-12-01 13:48:04 -08007061 PlaybackThread::flushHw_l();
Phil Burk062e67a2015-02-11 13:40:50 -08007062 mOutput->flush();
Eric Laurentd1f69b02014-12-15 14:33:13 -08007063 mHwPaused = false;
Phil Burk43b4dcc2015-06-09 16:53:44 -07007064 mFlushPending = false;
Dean Wheatley12473e92021-03-18 23:00:55 +11007065 mTimestampVerifier.discontinuity(discontinuityForStandbyOrFlush());
Sampath Shetty999f0e82020-01-15 10:19:06 +11007066 mTimestamp.clear();
Andy Hung398ffa22022-12-13 19:19:53 -08007067 mMonotonicFrameCounter.onFlush();
Eric Laurente659ef42014-09-29 13:06:46 -07007068}
7069
Andy Hungee58e4a2023-07-07 13:47:37 -07007070int64_t DirectOutputThread::computeWaitTimeNs_l() const {
Andy Hung10cbff12017-02-21 17:30:14 -08007071 // If a VolumeShaper is active, we must wake up periodically to update volume.
7072 const int64_t NS_PER_MS = 1000000;
7073 return mVolumeShaperActive ?
7074 kMinNormalSinkBufferSizeMs * NS_PER_MS : PlaybackThread::computeWaitTimeNs_l();
7075}
7076
Eric Laurent81784c32012-11-19 14:55:58 -08007077// ----------------------------------------------------------------------------
7078
Andy Hungee58e4a2023-07-07 13:47:37 -07007079AsyncCallbackThread::AsyncCallbackThread(
7080 const wp<PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08007081 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07007082 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07007083 mWriteAckSequence(0),
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007084 mDrainSequence(0),
7085 mAsyncError(false)
Eric Laurentbfb1b832013-01-07 09:53:42 -08007086{
7087}
7088
Andy Hungee58e4a2023-07-07 13:47:37 -07007089void AsyncCallbackThread::onFirstRef()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007090{
7091 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
7092}
7093
Andy Hungee58e4a2023-07-07 13:47:37 -07007094bool AsyncCallbackThread::threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007095{
7096 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07007097 uint32_t writeAckSequence;
7098 uint32_t drainSequence;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007099 bool asyncError;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007100
7101 {
Andy Hungc5007f82023-08-29 14:26:09 -07007102 audio_utils::unique_lock _l(mutex());
Haynes Mathew George24a325d2013-12-03 21:26:02 -08007103 while (!((mWriteAckSequence & 1) ||
7104 (mDrainSequence & 1) ||
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007105 mAsyncError ||
Haynes Mathew George24a325d2013-12-03 21:26:02 -08007106 exitPending())) {
Andy Hungc5007f82023-08-29 14:26:09 -07007107 mWaitWorkCV.wait(_l);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08007108 }
7109
Eric Laurentbfb1b832013-01-07 09:53:42 -08007110 if (exitPending()) {
7111 break;
7112 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07007113 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
7114 mWriteAckSequence, mDrainSequence);
7115 writeAckSequence = mWriteAckSequence;
7116 mWriteAckSequence &= ~1;
7117 drainSequence = mDrainSequence;
7118 mDrainSequence &= ~1;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007119 asyncError = mAsyncError;
7120 mAsyncError = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007121 }
7122 {
Andy Hungee58e4a2023-07-07 13:47:37 -07007123 const sp<PlaybackThread> playbackThread = mPlaybackThread.promote();
Eric Laurent4de95592013-09-26 15:28:21 -07007124 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07007125 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07007126 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007127 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07007128 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07007129 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007130 }
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007131 if (asyncError) {
7132 playbackThread->onAsyncError();
7133 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007134 }
7135 }
7136 }
7137 return false;
7138}
7139
Andy Hungee58e4a2023-07-07 13:47:37 -07007140void AsyncCallbackThread::exit()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007141{
7142 ALOGV("AsyncCallbackThread::exit");
Andy Hung972bec12023-08-31 16:13:39 -07007143 audio_utils::lock_guard _l(mutex());
Eric Laurentbfb1b832013-01-07 09:53:42 -08007144 requestExit();
Andy Hungc5007f82023-08-29 14:26:09 -07007145 mWaitWorkCV.notify_all();
Eric Laurentbfb1b832013-01-07 09:53:42 -08007146}
7147
Andy Hungee58e4a2023-07-07 13:47:37 -07007148void AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08007149{
Andy Hung972bec12023-08-31 16:13:39 -07007150 audio_utils::lock_guard _l(mutex());
Eric Laurent3b4529e2013-09-05 18:09:19 -07007151 // bit 0 is cleared
7152 mWriteAckSequence = sequence << 1;
7153}
7154
Andy Hungee58e4a2023-07-07 13:47:37 -07007155void AsyncCallbackThread::resetWriteBlocked()
Eric Laurent3b4529e2013-09-05 18:09:19 -07007156{
Andy Hung972bec12023-08-31 16:13:39 -07007157 audio_utils::lock_guard _l(mutex());
Eric Laurent3b4529e2013-09-05 18:09:19 -07007158 // ignore unexpected callbacks
7159 if (mWriteAckSequence & 2) {
7160 mWriteAckSequence |= 1;
Andy Hungc5007f82023-08-29 14:26:09 -07007161 mWaitWorkCV.notify_one();
Eric Laurentbfb1b832013-01-07 09:53:42 -08007162 }
7163}
7164
Andy Hungee58e4a2023-07-07 13:47:37 -07007165void AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08007166{
Andy Hung972bec12023-08-31 16:13:39 -07007167 audio_utils::lock_guard _l(mutex());
Eric Laurent3b4529e2013-09-05 18:09:19 -07007168 // bit 0 is cleared
7169 mDrainSequence = sequence << 1;
7170}
7171
Andy Hungee58e4a2023-07-07 13:47:37 -07007172void AsyncCallbackThread::resetDraining()
Eric Laurent3b4529e2013-09-05 18:09:19 -07007173{
Andy Hung972bec12023-08-31 16:13:39 -07007174 audio_utils::lock_guard _l(mutex());
Eric Laurent3b4529e2013-09-05 18:09:19 -07007175 // ignore unexpected callbacks
7176 if (mDrainSequence & 2) {
7177 mDrainSequence |= 1;
Andy Hungc5007f82023-08-29 14:26:09 -07007178 mWaitWorkCV.notify_one();
Eric Laurentbfb1b832013-01-07 09:53:42 -08007179 }
7180}
7181
Andy Hungee58e4a2023-07-07 13:47:37 -07007182void AsyncCallbackThread::setAsyncError()
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007183{
Andy Hung972bec12023-08-31 16:13:39 -07007184 audio_utils::lock_guard _l(mutex());
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007185 mAsyncError = true;
Andy Hungc5007f82023-08-29 14:26:09 -07007186 mWaitWorkCV.notify_one();
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007187}
7188
Eric Laurentbfb1b832013-01-07 09:53:42 -08007189
7190// ----------------------------------------------------------------------------
Andy Hungee58e4a2023-07-07 13:47:37 -07007191
7192/* static */
7193sp<IAfPlaybackThread> IAfPlaybackThread::createOffloadThread(
Andy Hung583043b2023-07-17 17:05:00 -07007194 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hungee58e4a2023-07-07 13:47:37 -07007195 AudioStreamOut* output, audio_io_handle_t id, bool systemReady,
7196 const audio_offload_info_t& offloadInfo) {
Andy Hung583043b2023-07-17 17:05:00 -07007197 return sp<OffloadThread>::make(afThreadCallback, output, id, systemReady, offloadInfo);
Andy Hungee58e4a2023-07-07 13:47:37 -07007198}
7199
Andy Hung583043b2023-07-17 17:05:00 -07007200OffloadThread::OffloadThread(const sp<IAfThreadCallback>& afThreadCallback,
Gareth Fennb18c1a32022-10-05 13:42:36 -07007201 AudioStreamOut* output, audio_io_handle_t id, bool systemReady,
7202 const audio_offload_info_t& offloadInfo)
Andy Hung583043b2023-07-17 17:05:00 -07007203 : DirectOutputThread(afThreadCallback, output, id, OFFLOAD, systemReady, offloadInfo),
ziyangch8f194f12021-12-01 13:48:04 -08007204 mPausedWriteLength(0), mPausedBytesRemaining(0), mKeepWakeLock(true)
Eric Laurentbfb1b832013-01-07 09:53:42 -08007205{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07007206 //FIXME: mStandby should be set to true by ThreadBase constructo
Eric Laurentfd477972013-10-25 18:10:40 -07007207 mStandby = true;
Eric Laurent64667972016-03-30 18:19:46 -07007208 mKeepWakeLock = property_get_bool("ro.audio.offload_wakelock", true /* default_value */);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007209}
7210
Andy Hungee58e4a2023-07-07 13:47:37 -07007211void OffloadThread::threadLoop_exit()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007212{
7213 if (mFlushPending || mHwPaused) {
7214 // If a flush is pending or track was paused, just discard buffered data
Andy Hungab65b182023-09-06 19:41:47 -07007215 audio_utils::lock_guard l(mutex());
Eric Laurentbfb1b832013-01-07 09:53:42 -08007216 flushHw_l();
7217 } else {
7218 mMixerStatus = MIXER_DRAIN_ALL;
7219 threadLoop_drain();
7220 }
Uday Gupta56604aa2014-05-13 11:19:17 -07007221 if (mUseAsyncWrite) {
7222 ALOG_ASSERT(mCallbackThread != 0);
7223 mCallbackThread->exit();
7224 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007225 PlaybackThread::threadLoop_exit();
7226}
7227
Andy Hungee58e4a2023-07-07 13:47:37 -07007228PlaybackThread::mixer_state OffloadThread::prepareTracks_l(
Andy Hung8d31fd22023-06-26 19:20:57 -07007229 Vector<sp<IAfTrack>>* tracksToRemove
Eric Laurentbfb1b832013-01-07 09:53:42 -08007230)
7231{
Eric Laurentbfb1b832013-01-07 09:53:42 -08007232 size_t count = mActiveTracks.size();
7233
7234 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07007235 bool doHwPause = false;
7236 bool doHwResume = false;
7237
Glenn Kastenc42e9b42016-03-21 11:35:03 -07007238 ALOGV("OffloadThread::prepareTracks_l active tracks %zu", count);
Eric Laurentede6c3b2013-09-19 14:37:46 -07007239
Eric Laurentbfb1b832013-01-07 09:53:42 -08007240 // find out which tracks need to be processed
Andy Hung8d31fd22023-06-26 19:20:57 -07007241 for (const sp<IAfTrack>& t : mActiveTracks) {
7242 IAfTrack* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07007243#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurentbfb1b832013-01-07 09:53:42 -08007244 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07007245#endif
Eric Laurentfd477972013-10-25 18:10:40 -07007246 // Only consider last track started for volume and mixer state control.
7247 // In theory an older track could underrun and restart after the new one starts
7248 // but as we only care about the transition phase between two tracks on a
7249 // direct output, it is not a problem to ignore the underrun case.
Andy Hung8d31fd22023-06-26 19:20:57 -07007250 sp<IAfTrack> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08007251 bool last = l.get() == track;
Eric Laurentfd477972013-10-25 18:10:40 -07007252
Haynes Mathew George7844f672014-01-15 12:32:55 -08007253 if (track->isInvalid()) {
7254 ALOGW("An invalidated track shouldn't be in active list");
7255 tracksToRemove->add(track);
7256 continue;
7257 }
7258
Andy Hung8d31fd22023-06-26 19:20:57 -07007259 if (track->state() == IAfTrackBase::IDLE) {
Haynes Mathew George7844f672014-01-15 12:32:55 -08007260 ALOGW("An idle track shouldn't be in active list");
7261 continue;
7262 }
7263
Kuowei Li23666472021-01-20 10:23:25 +08007264 if (track->isPausePending()) {
7265 track->pauseAck();
7266 // It is possible a track might have been flushed or stopped.
7267 // Other operations such as flush pending might occur on the next prepare.
7268 if (track->isPausing()) {
7269 track->setPaused();
7270 }
7271 // Always perform pause if last, as an immediate flush will change
7272 // the pause state to be no longer isPausing().
Eric Laurentbfb1b832013-01-07 09:53:42 -08007273 if (last) {
Eric Laurent5cff4032015-05-26 13:49:58 -07007274 if (mHwSupportsPause && !mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07007275 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007276 mHwPaused = true;
7277 }
7278 // If we were part way through writing the mixbuffer to
7279 // the HAL we must save this until we resume
7280 // BUG - this will be wrong if a different track is made active,
7281 // in that case we want to discard the pending data in the
7282 // mixbuffer and tell the client to present it again when the
7283 // track is resumed
7284 mPausedWriteLength = mCurrentWriteLength;
7285 mPausedBytesRemaining = mBytesRemaining;
7286 mBytesRemaining = 0; // stop writing
7287 }
7288 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08007289 } else if (track->isFlushPending()) {
Eric Laurente93cc032016-05-05 10:15:10 -07007290 if (track->isStopping_1()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07007291 track->retryCount() = kMaxTrackStopRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07007292 } else {
Andy Hung8d31fd22023-06-26 19:20:57 -07007293 track->retryCount() = kMaxTrackRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07007294 }
Haynes Mathew George7844f672014-01-15 12:32:55 -08007295 track->flushAck();
7296 if (last) {
7297 mFlushPending = true;
7298 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08007299 } else if (track->isResumePending()){
7300 track->resumeAck();
7301 if (last) {
7302 if (mPausedBytesRemaining) {
7303 // Need to continue write that was interrupted
7304 mCurrentWriteLength = mPausedWriteLength;
7305 mBytesRemaining = mPausedBytesRemaining;
7306 mPausedBytesRemaining = 0;
7307 }
7308 if (mHwPaused) {
7309 doHwResume = true;
7310 mHwPaused = false;
7311 // threadLoop_mix() will handle the case that we need to
7312 // resume an interrupted write
7313 }
7314 // enable write to audio HAL
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007315 mSleepTimeUs = 0;
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08007316
Eric Laurent3df841a2016-07-15 15:15:40 -07007317 mLeftVolFloat = mRightVolFloat = -1.0;
7318
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08007319 // Do not handle new data in this iteration even if track->framesReady()
7320 mixerStatus = MIXER_TRACKS_ENABLED;
7321 }
7322 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07007323 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Andy Hungc0691382018-09-12 18:01:57 -07007324 ALOGVV("OffloadThread: track(%d) s=%08x [OK]", track->id(), cblk->mServer);
Andy Hung8d31fd22023-06-26 19:20:57 -07007325 if (track->fillingStatus() == IAfTrack::FS_FILLED) {
7326 track->fillingStatus() = IAfTrack::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07007327 if (last) {
7328 // make sure processVolume_l() will apply new volume even if 0
7329 mLeftVolFloat = mRightVolFloat = -1.0;
7330 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007331 }
7332
7333 if (last) {
Andy Hung8d31fd22023-06-26 19:20:57 -07007334 sp<IAfTrack> previousTrack = mPreviousTrack.promote();
Eric Laurentd7e59222013-11-15 12:02:28 -08007335 if (previousTrack != 0) {
7336 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08007337 // Flush any data still being written from last track
7338 mBytesRemaining = 0;
7339 if (mPausedBytesRemaining) {
7340 // Last track was paused so we also need to flush saved
7341 // mixbuffer state and invalidate track so that it will
7342 // re-submit that unwritten data when it is next resumed
7343 mPausedBytesRemaining = 0;
7344 // Invalidate is a bit drastic - would be more efficient
7345 // to have a flag to tell client that some of the
7346 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08007347 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08007348 }
7349 // flush data already sent to the DSP if changing audio session as audio
7350 // comes from a different source. Also invalidate previous track to force a
7351 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08007352 if (previousTrack->sessionId() != track->sessionId()) {
7353 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08007354 }
7355 }
7356 }
7357 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007358 // reset retry count
Eric Laurente93cc032016-05-05 10:15:10 -07007359 if (track->isStopping_1()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07007360 track->retryCount() = kMaxTrackStopRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07007361 } else {
Andy Hung8d31fd22023-06-26 19:20:57 -07007362 track->retryCount() = kMaxTrackRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07007363 }
Eric Laurent5850c4c2016-11-10 13:04:31 -08007364 mActiveTrack = t;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007365 mixerStatus = MIXER_TRACKS_READY;
7366 }
7367 } else {
Andy Hungc0691382018-09-12 18:01:57 -07007368 ALOGVV("OffloadThread: track(%d) s=%08x [NOT READY]", track->id(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007369 if (track->isStopping_1()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07007370 if (--(track->retryCount()) <= 0) {
Eric Laurente93cc032016-05-05 10:15:10 -07007371 // Hardware buffer can hold a large amount of audio so we must
7372 // wait for all current track's data to drain before we say
7373 // that the track is stopped.
7374 if (mBytesRemaining == 0) {
7375 // Only start draining when all data in mixbuffer
7376 // has been written
7377 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
Andy Hung8d31fd22023-06-26 19:20:57 -07007378 track->setState(IAfTrackBase::STOPPING_2);
7379 // so presentation completes after
Eric Laurente93cc032016-05-05 10:15:10 -07007380 // drain do not drain if no data was ever sent to HAL (mStandby == true)
7381 if (last && !mStandby) {
7382 // do not modify drain sequence if we are already draining. This happens
7383 // when resuming from pause after drain.
7384 if ((mDrainSequence & 1) == 0) {
7385 mSleepTimeUs = 0;
7386 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
7387 mixerStatus = MIXER_DRAIN_TRACK;
7388 mDrainSequence += 2;
7389 }
7390 if (mHwPaused) {
7391 // It is possible to move from PAUSED to STOPPING_1 without
7392 // a resume so we must ensure hardware is running
7393 doHwResume = true;
7394 mHwPaused = false;
7395 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007396 }
7397 }
Eric Laurente93cc032016-05-05 10:15:10 -07007398 } else if (last) {
Andy Hung8d31fd22023-06-26 19:20:57 -07007399 ALOGV("stopping1 underrun retries left %d", track->retryCount());
Eric Laurente93cc032016-05-05 10:15:10 -07007400 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007401 }
7402 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07007403 // Drain has completed or we are in standby, signal presentation complete
7404 if (!(mDrainSequence & 1) || !last || mStandby) {
Andy Hung8d31fd22023-06-26 19:20:57 -07007405 track->setState(IAfTrackBase::STOPPED);
Atneya Nair0cae0432022-05-10 18:12:12 -04007406 mOutput->presentationComplete();
7407 track->presentationComplete(latency_l()); // always returns true
Eric Laurentbfb1b832013-01-07 09:53:42 -08007408 track->reset();
7409 tracksToRemove->add(track);
Dean Wheatley12473e92021-03-18 23:00:55 +11007410 // OFFLOADED stop resets frame counts.
Andy Hungf3234512018-07-03 14:51:47 -07007411 if (!mUseAsyncWrite) {
7412 // If we don't get explicit drain notification we must
7413 // register discontinuity regardless of whether this is
7414 // the previous (!last) or the upcoming (last) track
7415 // to avoid skipping the discontinuity.
Dean Wheatley12473e92021-03-18 23:00:55 +11007416 mTimestampVerifier.discontinuity(
7417 mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Andy Hungf3234512018-07-03 14:51:47 -07007418 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007419 }
7420 } else {
7421 // No buffers for this track. Give it a few chances to
7422 // fill a buffer, then remove it from active list.
Brian Lindahl65e90012022-07-27 18:01:07 +02007423 bool isTimestampAdvancing = mIsTimestampAdvancing.check(mOutput);
Gareth Fennb18c1a32022-10-05 13:42:36 -07007424 if (!isTunerStream() // tuner streams remain active in underrun
Andy Hung8d31fd22023-06-26 19:20:57 -07007425 && --(track->retryCount()) <= 0) {
Brian Lindahl65e90012022-07-27 18:01:07 +02007426 if (isTimestampAdvancing) { // HAL is still playing audio, give us more time.
Andy Hung8d31fd22023-06-26 19:20:57 -07007427 track->retryCount() = kMaxTrackRetriesOffload;
Andy Hungf8044752016-07-27 14:58:11 -07007428 } else {
Andy Hungc0691382018-09-12 18:01:57 -07007429 ALOGV("OffloadThread: BUFFER TIMEOUT: remove track(%d) from active list",
7430 track->id());
Andy Hungf8044752016-07-27 14:58:11 -07007431 tracksToRemove->add(track);
Glenn Kastend3bb6452016-12-05 18:14:37 -08007432 // tell client process that the track was disabled because of underrun;
Andy Hungf8044752016-07-27 14:58:11 -07007433 // it will then automatically call start() when data is available
7434 track->disable();
7435 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007436 } else if (last){
7437 mixerStatus = MIXER_TRACKS_ENABLED;
7438 }
7439 }
7440 }
7441 // compute volume for this track
Wenfeng Sun79458332019-05-29 20:12:43 +08007442 if (track->isReady()) { // check ready to prevent premature start.
7443 processVolume_l(track, last);
7444 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007445 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007446
Eric Laurentea0fade2013-10-04 16:23:48 -07007447 // make sure the pause/flush/resume sequence is executed in the right order.
7448 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
7449 // before flush and then resume HW. This can happen in case of pause/flush/resume
7450 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07007451 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007452 status_t result = mOutput->stream->pause();
7453 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Gareth Fenncd1e1622022-10-05 11:45:45 -07007454 doHwResume = !doHwPause; // resume if pause is due to flush.
Eric Laurent972a1732013-09-04 09:42:59 -07007455 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007456 if (mFlushPending) {
7457 flushHw_l();
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007458 }
Eric Laurentfd477972013-10-25 18:10:40 -07007459 if (!mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007460 status_t result = mOutput->stream->resume();
7461 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07007462 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007463
Eric Laurentbfb1b832013-01-07 09:53:42 -08007464 // remove all the tracks that need to be...
7465 removeTracks_l(*tracksToRemove);
7466
7467 return mixerStatus;
7468}
7469
Eric Laurentbfb1b832013-01-07 09:53:42 -08007470// must be called with thread mutex locked
Andy Hungee58e4a2023-07-07 13:47:37 -07007471bool OffloadThread::waitingAsyncCallback_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007472{
Eric Laurent3b4529e2013-09-05 18:09:19 -07007473 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
7474 mWriteAckSequence, mDrainSequence);
7475 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08007476 return true;
7477 }
7478 return false;
7479}
7480
Andy Hungee58e4a2023-07-07 13:47:37 -07007481bool OffloadThread::waitingAsyncCallback()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007482{
Andy Hung972bec12023-08-31 16:13:39 -07007483 audio_utils::lock_guard _l(mutex());
Eric Laurentbfb1b832013-01-07 09:53:42 -08007484 return waitingAsyncCallback_l();
7485}
7486
Andy Hungee58e4a2023-07-07 13:47:37 -07007487void OffloadThread::flushHw_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007488{
Eric Laurente659ef42014-09-29 13:06:46 -07007489 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08007490 // Flush anything still waiting in the mixbuffer
7491 mCurrentWriteLength = 0;
7492 mBytesRemaining = 0;
7493 mPausedWriteLength = 0;
7494 mPausedBytesRemaining = 0;
Eric Laurent3eaf66b2016-04-01 14:44:17 -07007495 // reset bytes written count to reflect that DSP buffers are empty after flush.
7496 mBytesWritten = 0;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08007497
Eric Laurentbfb1b832013-01-07 09:53:42 -08007498 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07007499 // discard any pending drain or write ack by incrementing sequence
7500 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
7501 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007502 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07007503 mCallbackThread->setWriteBlocked(mWriteAckSequence);
7504 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007505 }
7506}
7507
Andy Hungee58e4a2023-07-07 13:47:37 -07007508void OffloadThread::invalidateTracks(audio_stream_type_t streamType)
Haynes Mathew George05317d22016-05-03 16:34:26 -07007509{
Andy Hung972bec12023-08-31 16:13:39 -07007510 audio_utils::lock_guard _l(mutex());
Eric Laurent13084622016-05-17 10:51:49 -07007511 if (PlaybackThread::invalidateTracks_l(streamType)) {
7512 mFlushPending = true;
7513 }
Haynes Mathew George05317d22016-05-03 16:34:26 -07007514}
7515
Andy Hungee58e4a2023-07-07 13:47:37 -07007516void OffloadThread::invalidateTracks(std::set<audio_port_handle_t>& portIds) {
Andy Hung972bec12023-08-31 16:13:39 -07007517 audio_utils::lock_guard _l(mutex());
jiabinc44b3462022-12-08 12:52:31 -08007518 if (PlaybackThread::invalidateTracks_l(portIds)) {
7519 mFlushPending = true;
7520 }
7521}
7522
Eric Laurentbfb1b832013-01-07 09:53:42 -08007523// ----------------------------------------------------------------------------
7524
Andy Hungee58e4a2023-07-07 13:47:37 -07007525/* static */
7526sp<IAfDuplicatingThread> IAfDuplicatingThread::create(
Andy Hung583043b2023-07-17 17:05:00 -07007527 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hungee58e4a2023-07-07 13:47:37 -07007528 IAfPlaybackThread* mainThread, audio_io_handle_t id, bool systemReady) {
Andy Hung583043b2023-07-17 17:05:00 -07007529 return sp<DuplicatingThread>::make(afThreadCallback, mainThread, id, systemReady);
Andy Hungee58e4a2023-07-07 13:47:37 -07007530}
7531
Andy Hung583043b2023-07-17 17:05:00 -07007532DuplicatingThread::DuplicatingThread(const sp<IAfThreadCallback>& afThreadCallback,
Andy Hung87c693c2023-07-06 20:56:16 -07007533 IAfPlaybackThread* mainThread, audio_io_handle_t id, bool systemReady)
Andy Hung583043b2023-07-17 17:05:00 -07007534 : MixerThread(afThreadCallback, mainThread->getOutput(), id,
Eric Laurent72e3f392015-05-20 14:43:50 -07007535 systemReady, DUPLICATING),
Eric Laurent81784c32012-11-19 14:55:58 -08007536 mWaitTimeMs(UINT_MAX)
7537{
7538 addOutputTrack(mainThread);
7539}
7540
Andy Hungee58e4a2023-07-07 13:47:37 -07007541DuplicatingThread::~DuplicatingThread()
Eric Laurent81784c32012-11-19 14:55:58 -08007542{
7543 for (size_t i = 0; i < mOutputTracks.size(); i++) {
7544 mOutputTracks[i]->destroy();
7545 }
7546}
7547
Andy Hungee58e4a2023-07-07 13:47:37 -07007548void DuplicatingThread::threadLoop_mix()
Eric Laurent81784c32012-11-19 14:55:58 -08007549{
7550 // mix buffers...
Andy Hung920f6572022-10-06 12:09:49 -07007551 if (outputsReady()) {
Glenn Kastend79072e2016-01-06 08:41:20 -08007552 mAudioMixer->process();
Eric Laurent81784c32012-11-19 14:55:58 -08007553 } else {
Eric Laurent02b57082014-11-07 17:28:28 -08007554 if (mMixerBufferValid) {
7555 memset(mMixerBuffer, 0, mMixerBufferSize);
7556 } else {
7557 memset(mSinkBuffer, 0, mSinkBufferSize);
7558 }
Eric Laurent81784c32012-11-19 14:55:58 -08007559 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007560 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007561 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08007562 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007563 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08007564}
7565
Andy Hungee58e4a2023-07-07 13:47:37 -07007566void DuplicatingThread::threadLoop_sleepTime()
Eric Laurent81784c32012-11-19 14:55:58 -08007567{
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007568 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08007569 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007570 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007571 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007572 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007573 }
7574 } else if (mBytesWritten != 0) {
7575 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
7576 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08007577 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08007578 } else {
7579 // flush remaining overflow buffers in output tracks
7580 writeFrames = 0;
7581 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007582 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007583 }
7584}
7585
Andy Hungee58e4a2023-07-07 13:47:37 -07007586ssize_t DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08007587{
7588 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hung1c86ebe2018-05-29 20:29:08 -07007589 const ssize_t actualWritten = outputTracks[i]->write(mSinkBuffer, writeFrames);
7590
7591 // Consider the first OutputTrack for timestamp and frame counting.
7592
7593 // The threadLoop() generally assumes writing a full sink buffer size at a time.
7594 // Here, we correct for writeFrames of 0 (a stop) or underruns because
7595 // we always claim success.
7596 if (i == 0) {
7597 const ssize_t correction = mSinkBufferSize / mFrameSize - actualWritten;
7598 ALOGD_IF(correction != 0 && writeFrames != 0,
7599 "%s: writeFrames:%u actualWritten:%zd correction:%zd mFramesWritten:%lld",
7600 __func__, writeFrames, actualWritten, correction, (long long)mFramesWritten);
7601 mFramesWritten -= correction;
7602 }
7603
7604 // TODO: Report correction for the other output tracks and show in the dump.
Eric Laurent81784c32012-11-19 14:55:58 -08007605 }
Andy Hungcf10d742020-04-28 15:38:24 -07007606 if (mStandby) {
7607 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07007608 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -07007609 mStandby = false;
7610 }
Andy Hung25c2dac2014-02-27 14:56:00 -08007611 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08007612}
7613
Andy Hungee58e4a2023-07-07 13:47:37 -07007614void DuplicatingThread::threadLoop_standby()
Eric Laurent81784c32012-11-19 14:55:58 -08007615{
7616 // DuplicatingThread implements standby by stopping all tracks
7617 for (size_t i = 0; i < outputTracks.size(); i++) {
7618 outputTracks[i]->stop();
7619 }
7620}
7621
Andy Hungee58e4a2023-07-07 13:47:37 -07007622void DuplicatingThread::dumpInternals_l(int fd, const Vector<String16>& args)
Andy Hung1bc088a2018-02-09 15:57:31 -08007623{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07007624 MixerThread::dumpInternals_l(fd, args);
Andy Hung1bc088a2018-02-09 15:57:31 -08007625
7626 std::stringstream ss;
7627 const size_t numTracks = mOutputTracks.size();
7628 ss << " " << numTracks << " OutputTracks";
7629 if (numTracks > 0) {
7630 ss << ":";
7631 for (const auto &track : mOutputTracks) {
Andy Hung87c693c2023-07-06 20:56:16 -07007632 const auto thread = track->thread().promote();
Andy Hungc0691382018-09-12 18:01:57 -07007633 ss << " (" << track->id() << " : ";
Andy Hung1bc088a2018-02-09 15:57:31 -08007634 if (thread.get() != nullptr) {
7635 ss << thread.get() << ", " << thread->id();
7636 } else {
7637 ss << "null";
7638 }
7639 ss << ")";
7640 }
7641 }
7642 ss << "\n";
7643 std::string result = ss.str();
7644 write(fd, result.c_str(), result.size());
7645}
7646
Andy Hungee58e4a2023-07-07 13:47:37 -07007647void DuplicatingThread::saveOutputTracks()
Eric Laurent81784c32012-11-19 14:55:58 -08007648{
7649 outputTracks = mOutputTracks;
7650}
7651
Andy Hungee58e4a2023-07-07 13:47:37 -07007652void DuplicatingThread::clearOutputTracks()
Eric Laurent81784c32012-11-19 14:55:58 -08007653{
7654 outputTracks.clear();
7655}
7656
Andy Hungee58e4a2023-07-07 13:47:37 -07007657void DuplicatingThread::addOutputTrack(IAfPlaybackThread* thread)
Eric Laurent81784c32012-11-19 14:55:58 -08007658{
Andy Hung972bec12023-08-31 16:13:39 -07007659 audio_utils::lock_guard _l(mutex());
Andy Hungc25b84a2015-01-14 19:04:10 -08007660 // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
7661 // Adjust for thread->sampleRate() to determine minimum buffer frame count.
7662 // Then triple buffer because Threads do not run synchronously and may not be clock locked.
7663 const size_t frameCount =
7664 3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
7665 // TODO: Consider asynchronous sample rate conversion to handle clock disparity
7666 // from different OutputTracks and their associated MixerThreads (e.g. one may
7667 // nearly empty and the other may be dropping data).
7668
Svet Ganov33761132021-05-13 22:51:08 +00007669 // TODO b/182392769: use attribution source util, move to server edge
7670 AttributionSourceState attributionSource = AttributionSourceState();
7671 attributionSource.uid = VALUE_OR_FATAL(legacy2aidl_uid_t_int32_t(
Philip P. Moltmannbda45752020-07-17 16:41:18 -07007672 IPCThreadState::self()->getCallingUid()));
Svet Ganov33761132021-05-13 22:51:08 +00007673 attributionSource.pid = VALUE_OR_FATAL(legacy2aidl_pid_t_int32_t(
Philip P. Moltmannbda45752020-07-17 16:41:18 -07007674 IPCThreadState::self()->getCallingPid()));
Svet Ganov33761132021-05-13 22:51:08 +00007675 attributionSource.token = sp<BBinder>::make();
Andy Hung8d31fd22023-06-26 19:20:57 -07007676 sp<IAfOutputTrack> outputTrack = IAfOutputTrack::create(thread,
Eric Laurent81784c32012-11-19 14:55:58 -08007677 this,
7678 mSampleRate,
Andy Hungc25b84a2015-01-14 19:04:10 -08007679 mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08007680 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08007681 frameCount,
Svet Ganov33761132021-05-13 22:51:08 +00007682 attributionSource);
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07007683 status_t status = outputTrack != 0 ? outputTrack->initCheck() : (status_t) NO_MEMORY;
7684 if (status != NO_ERROR) {
7685 ALOGE("addOutputTrack() initCheck failed %d", status);
7686 return;
Eric Laurent81784c32012-11-19 14:55:58 -08007687 }
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07007688 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
7689 mOutputTracks.add(outputTrack);
7690 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
7691 updateWaitTime_l();
Eric Laurent81784c32012-11-19 14:55:58 -08007692}
7693
Andy Hungee58e4a2023-07-07 13:47:37 -07007694void DuplicatingThread::removeOutputTrack(IAfPlaybackThread* thread)
Eric Laurent81784c32012-11-19 14:55:58 -08007695{
Andy Hung972bec12023-08-31 16:13:39 -07007696 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08007697 for (size_t i = 0; i < mOutputTracks.size(); i++) {
7698 if (mOutputTracks[i]->thread() == thread) {
7699 mOutputTracks[i]->destroy();
7700 mOutputTracks.removeAt(i);
7701 updateWaitTime_l();
Andy Hung8d672e02023-09-15 18:19:28 -07007702 // NO_THREAD_SAFETY_ANALYSIS
7703 // Lambda workaround: as thread != this
7704 // we can safely call the remote thread getOutput.
7705 const bool equalOutput =
7706 [&](){ return thread->getOutput() == mOutput; }();
7707 if (equalOutput) {
7708 mOutput = nullptr;
Eric Laurentf6870ae2015-05-08 10:50:03 -07007709 }
Eric Laurent81784c32012-11-19 14:55:58 -08007710 return;
7711 }
7712 }
Eric Laurentf6870ae2015-05-08 10:50:03 -07007713 ALOGV("removeOutputTrack(): unknown thread: %p", thread);
Eric Laurent81784c32012-11-19 14:55:58 -08007714}
7715
Andy Hungc5007f82023-08-29 14:26:09 -07007716// caller must hold mutex()
Andy Hungee58e4a2023-07-07 13:47:37 -07007717void DuplicatingThread::updateWaitTime_l()
Eric Laurent81784c32012-11-19 14:55:58 -08007718{
7719 mWaitTimeMs = UINT_MAX;
7720 for (size_t i = 0; i < mOutputTracks.size(); i++) {
Andy Hung87c693c2023-07-06 20:56:16 -07007721 const auto strong = mOutputTracks[i]->thread().promote();
Eric Laurent81784c32012-11-19 14:55:58 -08007722 if (strong != 0) {
7723 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
7724 if (waitTimeMs < mWaitTimeMs) {
7725 mWaitTimeMs = waitTimeMs;
7726 }
7727 }
7728 }
7729}
7730
Andy Hungee58e4a2023-07-07 13:47:37 -07007731bool DuplicatingThread::outputsReady()
Eric Laurent81784c32012-11-19 14:55:58 -08007732{
7733 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hung87c693c2023-07-06 20:56:16 -07007734 const auto thread = outputTracks[i]->thread().promote();
Eric Laurent81784c32012-11-19 14:55:58 -08007735 if (thread == 0) {
7736 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
7737 outputTracks[i].get());
7738 return false;
7739 }
Andy Hung87c693c2023-07-06 20:56:16 -07007740 IAfPlaybackThread* const playbackThread = thread->asIAfPlaybackThread().get();
Eric Laurent81784c32012-11-19 14:55:58 -08007741 // see note at standby() declaration
Andy Hung440901d2023-06-29 21:19:25 -07007742 if (playbackThread->inStandby() && !playbackThread->isSuspended()) {
Eric Laurent81784c32012-11-19 14:55:58 -08007743 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
7744 thread.get());
7745 return false;
7746 }
7747 }
7748 return true;
7749}
7750
Andy Hungee58e4a2023-07-07 13:47:37 -07007751void DuplicatingThread::sendMetadataToBackend_l(
Kevin Rocard12381092018-04-11 09:19:59 -07007752 const StreamOutHalInterface::SourceMetadata& metadata)
Kevin Rocard069c2712018-03-29 19:09:14 -07007753{
Kevin Rocard12381092018-04-11 09:19:59 -07007754 for (auto& outputTrack : outputTracks) { // not mOutputTracks
7755 outputTrack->setMetadatas(metadata.tracks);
7756 }
Kevin Rocard069c2712018-03-29 19:09:14 -07007757}
7758
Andy Hungee58e4a2023-07-07 13:47:37 -07007759uint32_t DuplicatingThread::activeSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08007760{
Andy Hung7a6a0f02023-11-29 13:42:08 -08007761 // return half the wait time in microseconds.
7762 return std::min(mWaitTimeMs * 500ULL, (unsigned long long)UINT32_MAX); // prevent overflow.
Eric Laurent81784c32012-11-19 14:55:58 -08007763}
7764
Andy Hungee58e4a2023-07-07 13:47:37 -07007765void DuplicatingThread::cacheParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08007766{
7767 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
7768 updateWaitTime_l();
7769
7770 MixerThread::cacheParameters_l();
7771}
7772
Eric Laurentb3f315a2021-07-13 15:09:05 +02007773// ----------------------------------------------------------------------------
7774
Andy Hungee58e4a2023-07-07 13:47:37 -07007775/* static */
7776sp<IAfPlaybackThread> IAfPlaybackThread::createSpatializerThread(
Andy Hung583043b2023-07-17 17:05:00 -07007777 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hungee58e4a2023-07-07 13:47:37 -07007778 AudioStreamOut* output,
7779 audio_io_handle_t id,
7780 bool systemReady,
7781 audio_config_base_t* mixerConfig) {
Andy Hung583043b2023-07-17 17:05:00 -07007782 return sp<SpatializerThread>::make(afThreadCallback, output, id, systemReady, mixerConfig);
Andy Hungee58e4a2023-07-07 13:47:37 -07007783}
7784
Andy Hung583043b2023-07-17 17:05:00 -07007785SpatializerThread::SpatializerThread(const sp<IAfThreadCallback>& afThreadCallback,
Eric Laurentb3f315a2021-07-13 15:09:05 +02007786 AudioStreamOut* output,
7787 audio_io_handle_t id,
7788 bool systemReady,
7789 audio_config_base_t *mixerConfig)
Andy Hung583043b2023-07-17 17:05:00 -07007790 : MixerThread(afThreadCallback, output, id, systemReady, SPATIALIZER, mixerConfig)
Eric Laurentb3f315a2021-07-13 15:09:05 +02007791{
7792}
7793
Andy Hungee58e4a2023-07-07 13:47:37 -07007794void SpatializerThread::setHalLatencyMode_l() {
Eric Laurent68a40a82022-05-03 18:15:04 +02007795 // if mSupportedLatencyModes is empty, the HAL stream does not support
7796 // latency mode control and we can exit.
7797 if (mSupportedLatencyModes.empty()) {
7798 return;
7799 }
7800 audio_latency_mode_t latencyMode = AUDIO_LATENCY_MODE_FREE;
7801 if (mSupportedLatencyModes.size() == 1) {
7802 // If the HAL only support one latency mode currently, confirm the choice
7803 latencyMode = mSupportedLatencyModes[0];
7804 } else if (mSupportedLatencyModes.size() > 1) {
7805 // Request low latency if:
7806 // - The low latency mode is requested by the spatializer controller
7807 // (mRequestedLatencyMode = AUDIO_LATENCY_MODE_LOW)
7808 // AND
7809 // - At least one active track is spatialized
7810 bool hasSpatializedActiveTrack = false;
7811 for (const auto& track : mActiveTracks) {
7812 if (track->isSpatialized()) {
7813 hasSpatializedActiveTrack = true;
7814 break;
7815 }
7816 }
7817 if (hasSpatializedActiveTrack && mRequestedLatencyMode == AUDIO_LATENCY_MODE_LOW) {
7818 latencyMode = AUDIO_LATENCY_MODE_LOW;
7819 }
7820 }
7821
7822 if (latencyMode != mSetLatencyMode) {
7823 status_t status = mOutput->stream->setLatencyMode(latencyMode);
Andy Hung4bd53e72022-11-17 17:21:45 -08007824 ALOGD("%s: thread(%d) setLatencyMode(%s) returned %d",
7825 __func__, mId, toString(latencyMode).c_str(), status);
Eric Laurent68a40a82022-05-03 18:15:04 +02007826 if (status == NO_ERROR) {
7827 mSetLatencyMode = latencyMode;
7828 }
7829 }
7830}
7831
Andy Hungee58e4a2023-07-07 13:47:37 -07007832status_t SpatializerThread::setRequestedLatencyMode(audio_latency_mode_t mode) {
Eric Laurent68a40a82022-05-03 18:15:04 +02007833 if (mode != AUDIO_LATENCY_MODE_LOW && mode != AUDIO_LATENCY_MODE_FREE) {
7834 return BAD_VALUE;
7835 }
Andy Hung972bec12023-08-31 16:13:39 -07007836 audio_utils::lock_guard _l(mutex());
Eric Laurent68a40a82022-05-03 18:15:04 +02007837 mRequestedLatencyMode = mode;
7838 return NO_ERROR;
7839}
7840
Andy Hungee58e4a2023-07-07 13:47:37 -07007841void SpatializerThread::checkOutputStageEffects()
Andy Hung972bec12023-08-31 16:13:39 -07007842NO_THREAD_SAFETY_ANALYSIS
7843// 'createEffect_l' requires holding mutex 'AudioFlinger_Mutex' exclusively
Eric Laurentb3f315a2021-07-13 15:09:05 +02007844{
7845 bool hasVirtualizer = false;
7846 bool hasDownMixer = false;
Andy Hung116bc262023-06-20 18:56:17 -07007847 sp<IAfEffectHandle> finalDownMixer;
Eric Laurentb3f315a2021-07-13 15:09:05 +02007848 {
Andy Hung972bec12023-08-31 16:13:39 -07007849 audio_utils::lock_guard _l(mutex());
Andy Hung116bc262023-06-20 18:56:17 -07007850 sp<IAfEffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_STAGE);
Eric Laurentb3f315a2021-07-13 15:09:05 +02007851 if (chain != 0) {
Eric Laurent1c5e2e32021-08-18 18:50:28 +02007852 hasVirtualizer = chain->getEffectFromType_l(FX_IID_SPATIALIZER) != nullptr;
Eric Laurentb3f315a2021-07-13 15:09:05 +02007853 hasDownMixer = chain->getEffectFromType_l(EFFECT_UIID_DOWNMIX) != nullptr;
7854 }
7855
7856 finalDownMixer = mFinalDownMixer;
7857 mFinalDownMixer.clear();
7858 }
7859
7860 if (hasVirtualizer) {
7861 if (finalDownMixer != nullptr) {
7862 int32_t ret;
Andy Hung116bc262023-06-20 18:56:17 -07007863 finalDownMixer->asIEffect()->disable(&ret);
Eric Laurentb3f315a2021-07-13 15:09:05 +02007864 }
7865 finalDownMixer.clear();
7866 } else if (!hasDownMixer) {
7867 std::vector<effect_descriptor_t> descriptors;
Andy Hung583043b2023-07-17 17:05:00 -07007868 status_t status = mAfThreadCallback->getEffectsFactoryHal()->getDescriptors(
Eric Laurentb3f315a2021-07-13 15:09:05 +02007869 EFFECT_UIID_DOWNMIX, &descriptors);
7870 if (status != NO_ERROR) {
7871 return;
7872 }
7873 ALOG_ASSERT(!descriptors.empty(),
7874 "%s getDescriptors() returned no error but empty list", __func__);
7875
7876 finalDownMixer = createEffect_l(nullptr /*client*/, nullptr /*effectClient*/,
7877 0 /*priority*/, AUDIO_SESSION_OUTPUT_STAGE, &descriptors[0], nullptr /*enabled*/,
Eric Laurentde8caf42021-08-11 17:19:25 +02007878 &status, false /*pinned*/, false /*probe*/, false /*notifyFramesProcessed*/);
Eric Laurentb3f315a2021-07-13 15:09:05 +02007879
7880 if (finalDownMixer == nullptr || (status != NO_ERROR && status != ALREADY_EXISTS)) {
7881 ALOGW("%s error creating downmixer %d", __func__, status);
7882 finalDownMixer.clear();
7883 } else {
7884 int32_t ret;
Andy Hung116bc262023-06-20 18:56:17 -07007885 finalDownMixer->asIEffect()->enable(&ret);
Eric Laurentb3f315a2021-07-13 15:09:05 +02007886 }
7887 }
7888
7889 {
Andy Hung972bec12023-08-31 16:13:39 -07007890 audio_utils::lock_guard _l(mutex());
Eric Laurentb3f315a2021-07-13 15:09:05 +02007891 mFinalDownMixer = finalDownMixer;
7892 }
7893}
7894
Eric Laurent81784c32012-11-19 14:55:58 -08007895// ----------------------------------------------------------------------------
7896// Record
7897// ----------------------------------------------------------------------------
7898
Andy Hung583043b2023-07-17 17:05:00 -07007899sp<IAfRecordThread> IAfRecordThread::create(const sp<IAfThreadCallback>& afThreadCallback,
Andy Hung87c693c2023-07-06 20:56:16 -07007900 AudioStreamIn* input,
7901 audio_io_handle_t id,
7902 bool systemReady) {
Andy Hung583043b2023-07-17 17:05:00 -07007903 return sp<RecordThread>::make(afThreadCallback, input, id, systemReady);
Andy Hung87c693c2023-07-06 20:56:16 -07007904}
7905
Andy Hung583043b2023-07-17 17:05:00 -07007906RecordThread::RecordThread(const sp<IAfThreadCallback>& afThreadCallback,
Eric Laurent81784c32012-11-19 14:55:58 -08007907 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08007908 audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -07007909 bool systemReady
Glenn Kasten46909e72013-02-26 09:20:22 -08007910 ) :
Andy Hung583043b2023-07-17 17:05:00 -07007911 ThreadBase(afThreadCallback, id, RECORD, systemReady, false /* isOut */),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007912 mInput(input),
Mikhail Naganov2534b382019-09-25 13:05:02 -07007913 mSource(mInput),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007914 mActiveTracks(&this->mLocalLog),
7915 mRsmpInBuffer(NULL),
Glenn Kasten1b291842016-07-18 14:55:21 -07007916 // mRsmpInFrames, mRsmpInFramesP2, and mRsmpInFramesOA are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007917 mRsmpInRear(0)
Glenn Kastenb880f5e2014-05-07 08:43:45 -07007918 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
7919 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007920 // mFastCapture below
7921 , mFastCaptureFutex(0)
7922 // mInputSource
7923 // mPipeSink
7924 // mPipeSource
7925 , mPipeFramesP2(0)
7926 // mPipeMemory
7927 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07007928 , mFastTrackAvail(false)
Eric Laurentd8365c52017-07-16 15:27:05 -07007929 , mBtNrecSuspended(false)
Eric Laurent81784c32012-11-19 14:55:58 -08007930{
Glenn Kastend7dca052015-03-05 16:05:54 -08007931 snprintf(mThreadName, kThreadNameLength, "AudioIn_%X", id);
Andy Hung583043b2023-07-17 17:05:00 -07007932 mNBLogWriter = afThreadCallback->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08007933
George Burgess IVa8f90c12020-05-14 11:27:19 -07007934 if (mInput->audioHwDev != nullptr) {
Andy Hungc8fddf32018-08-08 18:32:37 -07007935 mIsMsdDevice = strcmp(
7936 mInput->audioHwDev->moduleName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0;
7937 }
7938
Glenn Kastendeca2ae2014-02-07 10:25:56 -08007939 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007940
Andy Hungc8fddf32018-08-08 18:32:37 -07007941 // TODO: We may also match on address as well as device type for
7942 // AUDIO_DEVICE_IN_BUS, AUDIO_DEVICE_IN_BLUETOOTH_A2DP, AUDIO_DEVICE_IN_REMOTE_SUBMIX
jiabinc52b1ff2019-10-31 17:20:42 -07007943 // TODO: This property should be ensure that only contains one single device type.
7944 mTimestampCorrectedDevice = (audio_devices_t)property_get_int64(
7945 "audio.timestamp.corrected_input_device",
Andy Hungc8fddf32018-08-08 18:32:37 -07007946 (int64_t)(mIsMsdDevice ? AUDIO_DEVICE_IN_BUS // turn on by default for MSD
7947 : AUDIO_DEVICE_NONE));
7948
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007949 // create an NBAIO source for the HAL input stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07007950 mInputSource = new AudioStreamInSource(input->stream);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007951 size_t numCounterOffers = 0;
7952 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07007953#if !LOG_NDEBUG
Jing Mike537412f2023-03-12 11:01:47 +08007954 [[maybe_unused]] ssize_t index =
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07007955#else
7956 (void)
7957#endif
7958 mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007959 ALOG_ASSERT(index == 0);
7960
7961 // initialize fast capture depending on configuration
7962 bool initFastCapture;
7963 switch (kUseFastCapture) {
7964 case FastCapture_Never:
7965 initFastCapture = false;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007966 ALOGV("%p kUseFastCapture = Never, initFastCapture = false", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007967 break;
7968 case FastCapture_Always:
7969 initFastCapture = true;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007970 ALOGV("%p kUseFastCapture = Always, initFastCapture = true", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007971 break;
7972 case FastCapture_Static:
Sampath6fac2332022-12-16 17:34:37 +11007973 initFastCapture = !mIsMsdDevice // Disable fast capture for MSD BUS devices.
Dean Wheatley8e5d9e42023-11-03 12:37:27 +11007974 && audio_is_linear_pcm(mFormat)
Sampath6fac2332022-12-16 17:34:37 +11007975 && (mFrameCount * 1000) / mSampleRate < kMinNormalCaptureBufferSizeMs;
Dean Wheatley8e5d9e42023-11-03 12:37:27 +11007976 ALOGV("%p kUseFastCapture = Static, format = 0x%x, (%lld * 1000) / %u vs %u, "
7977 "initFastCapture = %d, mIsMsdDevice = %d", this, mFormat, (long long)mFrameCount,
7978 mSampleRate, kMinNormalCaptureBufferSizeMs, initFastCapture, mIsMsdDevice);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007979 break;
7980 // case FastCapture_Dynamic:
7981 }
7982
7983 if (initFastCapture) {
Glenn Kastend198b852015-03-16 14:55:53 -07007984 // create a Pipe for FastCapture to write to, and for us and fast tracks to read from
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007985 NBAIO_Format format = mInputSource->format();
Glenn Kasten1b291842016-07-18 14:55:21 -07007986 // quadruple-buffering of 20 ms each; this ensures we can sleep for 20ms in RecordThread
7987 size_t pipeFramesP2 = roundup(4 * FMS_20 * mSampleRate / 1000);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007988 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007989 void *pipeBuffer = nullptr;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007990 const sp<MemoryDealer> roHeap(readOnlyHeap());
7991 sp<IMemory> pipeMemory;
7992 if ((roHeap == 0) ||
7993 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07007994 (pipeBuffer = pipeMemory->unsecurePointer()) == nullptr) {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007995 ALOGE("not enough memory for pipe buffer size=%zu; "
7996 "roHeap=%p, pipeMemory=%p, pipeBuffer=%p; roHeapSize: %lld",
7997 pipeSize, roHeap.get(), pipeMemory.get(), pipeBuffer,
7998 (long long)kRecordThreadReadOnlyHeapSize);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007999 goto failed;
8000 }
8001 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
8002 memset(pipeBuffer, 0, pipeSize);
8003 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
Andy Hung920f6572022-10-06 12:09:49 -07008004 const NBAIO_Format offersFast[1] = {format};
8005 size_t numCounterOffersFast = 0;
Eric Laurent1e28aaa2023-04-16 19:34:23 +02008006 [[maybe_unused]] ssize_t index2 = pipe->negotiate(offersFast, std::size(offersFast),
Andy Hung920f6572022-10-06 12:09:49 -07008007 nullptr /* counterOffers */, numCounterOffersFast);
Eric Laurent1e28aaa2023-04-16 19:34:23 +02008008 ALOG_ASSERT(index2 == 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008009 mPipeSink = pipe;
8010 PipeReader *pipeReader = new PipeReader(*pipe);
Andy Hung920f6572022-10-06 12:09:49 -07008011 numCounterOffersFast = 0;
Eric Laurent1e28aaa2023-04-16 19:34:23 +02008012 index2 = pipeReader->negotiate(offersFast, std::size(offersFast),
Andy Hung920f6572022-10-06 12:09:49 -07008013 nullptr /* counterOffers */, numCounterOffersFast);
Eric Laurent1e28aaa2023-04-16 19:34:23 +02008014 ALOG_ASSERT(index2 == 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008015 mPipeSource = pipeReader;
8016 mPipeFramesP2 = pipeFramesP2;
8017 mPipeMemory = pipeMemory;
8018
8019 // create fast capture
8020 mFastCapture = new FastCapture();
8021 FastCaptureStateQueue *sq = mFastCapture->sq();
8022#ifdef STATE_QUEUE_DUMP
8023 // FIXME
8024#endif
8025 FastCaptureState *state = sq->begin();
8026 state->mCblk = NULL;
8027 state->mInputSource = mInputSource.get();
8028 state->mInputSourceGen++;
8029 state->mPipeSink = pipe;
8030 state->mPipeSinkGen++;
8031 state->mFrameCount = mFrameCount;
8032 state->mCommand = FastCaptureState::COLD_IDLE;
8033 // already done in constructor initialization list
8034 //mFastCaptureFutex = 0;
8035 state->mColdFutexAddr = &mFastCaptureFutex;
8036 state->mColdGen++;
8037 state->mDumpState = &mFastCaptureDumpState;
8038#ifdef TEE_SINK
8039 // FIXME
8040#endif
Andy Hung583043b2023-07-17 17:05:00 -07008041 mFastCaptureNBLogWriter =
8042 afThreadCallback->newWriter_l(kFastCaptureLogSize, "FastCapture");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008043 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
8044 sq->end();
8045 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
8046
8047 // start the fast capture
8048 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
8049 pid_t tid = mFastCapture->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07008050 sendPrioConfigEvent(getpid(), tid, kPriorityFastCapture, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08008051 stream()->setHalThreadPriority(kPriorityFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008052#ifdef AUDIO_WATCHDOG
8053 // FIXME
8054#endif
8055
Glenn Kasten6e6704c2014-07-03 10:20:00 -07008056 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008057 }
Andy Hung8946a282018-04-19 20:04:56 -07008058#ifdef TEE_SINK
8059 mTee.set(mInputSource->format(), NBAIO_Tee::TEE_FLAG_INPUT_THREAD);
8060 mTee.setId(std::string("_") + std::to_string(mId) + "_C");
8061#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008062failed: ;
8063
8064 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08008065}
8066
Andy Hungee58e4a2023-07-07 13:47:37 -07008067RecordThread::~RecordThread()
Eric Laurent81784c32012-11-19 14:55:58 -08008068{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008069 if (mFastCapture != 0) {
8070 FastCaptureStateQueue *sq = mFastCapture->sq();
8071 FastCaptureState *state = sq->begin();
8072 if (state->mCommand == FastCaptureState::COLD_IDLE) {
8073 int32_t old = android_atomic_inc(&mFastCaptureFutex);
8074 if (old == -1) {
8075 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
8076 }
8077 }
8078 state->mCommand = FastCaptureState::EXIT;
8079 sq->end();
8080 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
8081 mFastCapture->join();
8082 mFastCapture.clear();
8083 }
Andy Hung583043b2023-07-17 17:05:00 -07008084 mAfThreadCallback->unregisterWriter(mFastCaptureNBLogWriter);
8085 mAfThreadCallback->unregisterWriter(mNBLogWriter);
Andy Hung57446612015-04-19 23:56:46 -07008086 free(mRsmpInBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08008087}
8088
Andy Hungee58e4a2023-07-07 13:47:37 -07008089void RecordThread::onFirstRef()
Eric Laurent81784c32012-11-19 14:55:58 -08008090{
Glenn Kastend7dca052015-03-05 16:05:54 -08008091 run(mThreadName, PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08008092}
8093
Andy Hungee58e4a2023-07-07 13:47:37 -07008094void RecordThread::preExit()
Eric Laurent555530a2017-02-07 18:17:24 -08008095{
8096 ALOGV(" preExit()");
Andy Hung972bec12023-08-31 16:13:39 -07008097 audio_utils::lock_guard _l(mutex());
Eric Laurent555530a2017-02-07 18:17:24 -08008098 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07008099 sp<IAfRecordTrack> track = mTracks[i];
Eric Laurent555530a2017-02-07 18:17:24 -08008100 track->invalidate();
8101 }
8102 mActiveTracks.clear();
Andy Hungc5007f82023-08-29 14:26:09 -07008103 mStartStopCV.notify_all();
Eric Laurent555530a2017-02-07 18:17:24 -08008104}
8105
Andy Hungee58e4a2023-07-07 13:47:37 -07008106bool RecordThread::threadLoop()
Eric Laurent81784c32012-11-19 14:55:58 -08008107{
Eric Laurent81784c32012-11-19 14:55:58 -08008108 nsecs_t lastWarning = 0;
8109
8110 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08008111
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008112reacquire_wakelock:
Andy Hung8d31fd22023-06-26 19:20:57 -07008113 sp<IAfRecordTrack> activeTrack;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008114 {
Andy Hung972bec12023-08-31 16:13:39 -07008115 audio_utils::lock_guard _l(mutex());
Andy Hungdae27702016-10-31 14:01:16 -07008116 acquireWakeLock_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008117 }
8118
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008119 // used to request a deferred sleep, to be executed later while mutex is unlocked
8120 uint32_t sleepUs = 0;
8121
Andy Hung95c94a22023-10-20 16:41:18 -07008122 // timestamp correction enable is determined under lock, used in processing step.
8123 bool timestampCorrectionEnabled = false;
8124
Andy Hung446f4df2019-02-21 12:26:41 -08008125 int64_t lastLoopCountRead = -2; // never matches "previous" loop, when loopCount = 0.
8126
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008127 // loop while there is work to do
Andy Hung446f4df2019-02-21 12:26:41 -08008128 for (int64_t loopCount = 0;; ++loopCount) { // loopCount used for statistics tracking
Andy Hung116bc262023-06-20 18:56:17 -07008129 Vector<sp<IAfEffectChain>> effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07008130
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008131 // activeTracks accumulates a copy of a subset of mActiveTracks
Andy Hung8d31fd22023-06-26 19:20:57 -07008132 Vector<sp<IAfRecordTrack>> activeTracks;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008133
Glenn Kasten735f45f2014-08-18 15:51:59 -07008134 // reference to the (first and only) active fast track
Andy Hung8d31fd22023-06-26 19:20:57 -07008135 sp<IAfRecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07008136
Glenn Kasten735f45f2014-08-18 15:51:59 -07008137 // reference to a fast track which is about to be removed
Andy Hung8d31fd22023-06-26 19:20:57 -07008138 sp<IAfRecordTrack> fastTrackToRemove;
Glenn Kasten735f45f2014-08-18 15:51:59 -07008139
Eric Laurent33403f02020-05-29 18:35:06 -07008140 bool silenceFastCapture = false;
8141
Andy Hungc5007f82023-08-29 14:26:09 -07008142 { // scope for mutex()
8143 audio_utils::unique_lock _l(mutex());
Eric Laurent000a4192014-01-29 15:17:32 -08008144
Eric Laurent021cf962014-05-13 10:18:14 -07008145 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008146
Eric Laurent000a4192014-01-29 15:17:32 -08008147 // check exitPending here because checkForNewParameters_l() and
Andy Hungc5007f82023-08-29 14:26:09 -07008148 // checkForNewParameters_l() can temporarily release mutex()
Eric Laurent000a4192014-01-29 15:17:32 -08008149 if (exitPending()) {
8150 break;
8151 }
8152
Eric Laurent5c25d562016-07-13 17:17:45 -07008153 // sleep with mutex unlocked
8154 if (sleepUs > 0) {
Glenn Kastenf9715e42016-07-13 14:02:03 -07008155 ATRACE_BEGIN("sleepC");
Andy Hungc5007f82023-08-29 14:26:09 -07008156 (void)mWaitWorkCV.wait_for(_l, std::chrono::microseconds(sleepUs));
Eric Laurent5c25d562016-07-13 17:17:45 -07008157 ATRACE_END();
8158 sleepUs = 0;
8159 continue;
8160 }
8161
Glenn Kasten2b806402013-11-20 16:37:38 -08008162 // if no active track(s), then standby and release wakelock
8163 size_t size = mActiveTracks.size();
8164 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07008165 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07008166 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08008167 releaseWakeLock_l();
8168 ALOGV("RecordThread: loop stopping");
8169 // go to sleep
Andy Hungc5007f82023-08-29 14:26:09 -07008170 mWaitWorkCV.wait(_l);
Eric Laurent81784c32012-11-19 14:55:58 -08008171 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008172 goto reacquire_wakelock;
8173 }
8174
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008175 bool doBroadcast = false;
Eric Laurent5c25d562016-07-13 17:17:45 -07008176 bool allStopped = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008177 for (size_t i = 0; i < size; ) {
Glenn Kasten9e982352013-08-14 14:39:50 -07008178
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008179 activeTrack = mActiveTracks[i];
8180 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07008181 if (activeTrack->isFastTrack()) {
8182 ALOG_ASSERT(fastTrackToRemove == 0);
8183 fastTrackToRemove = activeTrack;
8184 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008185 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08008186 mActiveTracks.remove(activeTrack);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008187 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07008188 continue;
8189 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008190
Andy Hung8d31fd22023-06-26 19:20:57 -07008191 IAfTrackBase::track_state activeTrackState = activeTrack->state();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008192 switch (activeTrackState) {
8193
Andy Hung8d31fd22023-06-26 19:20:57 -07008194 case IAfTrackBase::PAUSING:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008195 mActiveTracks.remove(activeTrack);
Andy Hung8d31fd22023-06-26 19:20:57 -07008196 activeTrack->setState(IAfTrackBase::PAUSED);
François Gaffie39634e42023-10-17 12:13:32 +02008197 if (activeTrack->isFastTrack()) {
8198 ALOGV("%s fast track is paused, thus removed from active list", __func__);
8199 // Keep a ref on fast track to wait for FastCapture thread to get updated
8200 // state before potential track removal
8201 fastTrackToRemove = activeTrack;
8202 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008203 doBroadcast = true;
8204 size--;
8205 continue;
8206
Andy Hung8d31fd22023-06-26 19:20:57 -07008207 case IAfTrackBase::STARTING_1:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008208 sleepUs = 10000;
8209 i++;
Eric Laurent5c25d562016-07-13 17:17:45 -07008210 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008211 continue;
8212
Andy Hung8d31fd22023-06-26 19:20:57 -07008213 case IAfTrackBase::STARTING_2:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008214 doBroadcast = true;
Andy Hungcf10d742020-04-28 15:38:24 -07008215 if (mStandby) {
8216 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07008217 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -07008218 mStandby = false;
8219 }
Andy Hung8d31fd22023-06-26 19:20:57 -07008220 activeTrack->setState(IAfTrackBase::ACTIVE);
Eric Laurent5c25d562016-07-13 17:17:45 -07008221 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008222 break;
8223
Andy Hung8d31fd22023-06-26 19:20:57 -07008224 case IAfTrackBase::ACTIVE:
Eric Laurent5c25d562016-07-13 17:17:45 -07008225 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008226 break;
8227
Andy Hung8d31fd22023-06-26 19:20:57 -07008228 case IAfTrackBase::IDLE: // cannot be on ActiveTracks if idle
8229 case IAfTrackBase::PAUSED: // cannot be on ActiveTracks if paused
8230 case IAfTrackBase::STOPPED: // cannot be on ActiveTracks if destroyed/terminated
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008231 default:
Andy Hungce685402018-10-05 17:23:27 -07008232 LOG_ALWAYS_FATAL("%s: Unexpected active track state:%d, id:%d, tracks:%zu",
8233 __func__, activeTrackState, activeTrack->id(), size);
Glenn Kasten9e982352013-08-14 14:39:50 -07008234 }
Glenn Kasten9e982352013-08-14 14:39:50 -07008235
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008236 if (activeTrack->isFastTrack()) {
8237 ALOG_ASSERT(!mFastTrackAvail);
8238 ALOG_ASSERT(fastTrack == 0);
Eric Laurent33403f02020-05-29 18:35:06 -07008239 // if the active fast track is silenced either:
8240 // 1) silence the whole capture from fast capture buffer if this is
8241 // the only active track
8242 // 2) invalidate this track: this will cause the client to reconnect and possibly
8243 // be invalidated again until unsilenced
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008244 bool invalidate = false;
Eric Laurent33403f02020-05-29 18:35:06 -07008245 if (activeTrack->isSilenced()) {
8246 if (size > 1) {
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008247 invalidate = true;
Eric Laurent33403f02020-05-29 18:35:06 -07008248 } else {
8249 silenceFastCapture = true;
8250 }
8251 }
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008252 // Invalidate fast tracks if access to audio history is required as this is not
8253 // possible with fast tracks. Once the fast track has been invalidated, no new
8254 // fast track will be created until mMaxSharedAudioHistoryMs is cleared.
8255 if (mMaxSharedAudioHistoryMs != 0) {
8256 invalidate = true;
8257 }
8258 if (invalidate) {
8259 activeTrack->invalidate();
8260 ALOG_ASSERT(fastTrackToRemove == 0);
8261 fastTrackToRemove = activeTrack;
8262 removeTrack_l(activeTrack);
8263 mActiveTracks.remove(activeTrack);
8264 size--;
8265 continue;
8266 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008267 fastTrack = activeTrack;
8268 }
Eric Laurent33403f02020-05-29 18:35:06 -07008269
8270 activeTracks.add(activeTrack);
8271 i++;
8272
Glenn Kasten9e982352013-08-14 14:39:50 -07008273 }
Eric Laurent5c25d562016-07-13 17:17:45 -07008274
Andy Hungab65b182023-09-06 19:41:47 -07008275 mActiveTracks.updatePowerState_l(this);
Andy Hungdae27702016-10-31 14:01:16 -07008276
Kevin Rocard069c2712018-03-29 19:09:14 -07008277 updateMetadata_l();
8278
Eric Laurent5c25d562016-07-13 17:17:45 -07008279 if (allStopped) {
8280 standbyIfNotAlreadyInStandby();
8281 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008282 if (doBroadcast) {
Andy Hungc5007f82023-08-29 14:26:09 -07008283 mStartStopCV.notify_all();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008284 }
8285
8286 // sleep if there are no active tracks to process
Eric Tan39ec8d62018-07-24 09:49:29 -07008287 if (activeTracks.isEmpty()) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008288 if (sleepUs == 0) {
8289 sleepUs = kRecordThreadSleepUs;
8290 }
8291 continue;
8292 }
8293 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07008294
Andy Hung95c94a22023-10-20 16:41:18 -07008295 timestampCorrectionEnabled = isTimestampCorrectionEnabled_l();
Eric Laurent81784c32012-11-19 14:55:58 -08008296 lockEffectChains_l(effectChains);
8297 }
8298
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008299 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07008300
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008301 size_t size = effectChains.size();
8302 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008303 // thread mutex is not locked, but effect chain is locked
8304 effectChains[i]->process_l();
8305 }
8306
Glenn Kasten735f45f2014-08-18 15:51:59 -07008307 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008308 if (mFastCapture != 0) {
8309 FastCaptureStateQueue *sq = mFastCapture->sq();
8310 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07008311 bool didModify = false;
8312 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008313 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
8314 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
8315 if (state->mCommand == FastCaptureState::COLD_IDLE) {
8316 int32_t old = android_atomic_inc(&mFastCaptureFutex);
8317 if (old == -1) {
8318 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
8319 }
8320 }
8321 state->mCommand = FastCaptureState::READ_WRITE;
8322#if 0 // FIXME
Andy Hung583043b2023-07-17 17:05:00 -07008323 mFastCaptureDumpState.increaseSamplingN(mAfThreadCallback->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08008324 FastThreadDumpState::kSamplingNforLowRamDevice :
8325 FastThreadDumpState::kSamplingN);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008326#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07008327 didModify = true;
8328 }
8329 audio_track_cblk_t *cblkOld = state->mCblk;
8330 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
8331 if (cblkNew != cblkOld) {
8332 state->mCblk = cblkNew;
8333 // block until acked if removing a fast track
8334 if (cblkOld != NULL) {
8335 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
8336 }
8337 didModify = true;
8338 }
jiabin01c8f562018-07-19 17:47:28 -07008339 AudioBufferProvider* abp = (fastTrack != 0 && fastTrack->isPatchTrack()) ?
8340 reinterpret_cast<AudioBufferProvider*>(fastTrack.get()) : nullptr;
8341 if (state->mFastPatchRecordBufferProvider != abp) {
8342 state->mFastPatchRecordBufferProvider = abp;
8343 state->mFastPatchRecordFormat = fastTrack == 0 ?
8344 AUDIO_FORMAT_INVALID : fastTrack->format();
8345 didModify = true;
8346 }
Eric Laurent33403f02020-05-29 18:35:06 -07008347 if (state->mSilenceCapture != silenceFastCapture) {
8348 state->mSilenceCapture = silenceFastCapture;
8349 didModify = true;
8350 }
Glenn Kasten735f45f2014-08-18 15:51:59 -07008351 sq->end(didModify);
8352 if (didModify) {
8353 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008354#if 0
8355 if (kUseFastCapture == FastCapture_Dynamic) {
8356 mNormalSource = mPipeSource;
8357 }
8358#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008359 }
8360 }
8361
Glenn Kasten735f45f2014-08-18 15:51:59 -07008362 // now run the fast track destructor with thread mutex unlocked
8363 fastTrackToRemove.clear();
8364
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008365 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
8366 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
8367 // slow, then this RecordThread will overrun by not calling HAL read often enough.
8368 // If destination is non-contiguous, first read past the nominal end of buffer, then
8369 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008370
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008371 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Andy Hung920f6572022-10-06 12:09:49 -07008372 ssize_t framesRead = 0; // not needed, remove clang-tidy warning.
Andy Hung446f4df2019-02-21 12:26:41 -08008373 const int64_t lastIoBeginNs = systemTime(); // start IO timing
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008374
8375 // If an NBAIO source is present, use it to read the normal capture's data
8376 if (mPipeSource != 0) {
Andy Hung156317a2018-08-02 11:49:29 -07008377 size_t framesToRead = min(mRsmpInFramesOA - rear, mRsmpInFramesP2 / 2);
Andy Hungd5b638f2018-04-30 13:56:10 -07008378
8379 // The audio fifo read() returns OVERRUN on overflow, and advances the read pointer
8380 // to the full buffer point (clearing the overflow condition). Upon OVERRUN error,
8381 // we immediately retry the read() to get data and prevent another overflow.
8382 for (int retries = 0; retries <= 2; ++retries) {
8383 ALOGW_IF(retries > 0, "overrun on read from pipe, retry #%d", retries);
8384 framesRead = mPipeSource->read((uint8_t*)mRsmpInBuffer + rear * mFrameSize,
8385 framesToRead);
8386 if (framesRead != OVERRUN) break;
8387 }
8388
Andy Hung7a3dc6b2018-05-01 16:39:51 -07008389 const ssize_t availableToRead = mPipeSource->availableToRead();
8390 if (availableToRead >= 0) {
Robert Wu06db0a32021-08-10 19:05:34 +00008391 mMonopipePipeDepthStats.add(availableToRead);
Glenn Kastena2f59b32020-08-03 16:37:24 -07008392 // PipeSource is the primary clock. It is up to the AudioRecord client to keep up.
Andy Hung7a3dc6b2018-05-01 16:39:51 -07008393 LOG_ALWAYS_FATAL_IF((size_t)availableToRead > mPipeFramesP2,
8394 "more frames to read than fifo size, %zd > %zu",
8395 availableToRead, mPipeFramesP2);
8396 const size_t pipeFramesFree = mPipeFramesP2 - availableToRead;
8397 const size_t sleepFrames = min(pipeFramesFree, mRsmpInFramesP2) / 2;
8398 ALOGVV("mPipeFramesP2:%zu mRsmpInFramesP2:%zu sleepFrames:%zu availableToRead:%zd",
8399 mPipeFramesP2, mRsmpInFramesP2, sleepFrames, availableToRead);
Glenn Kasten1b291842016-07-18 14:55:21 -07008400 sleepUs = (sleepFrames * 1000000LL) / mSampleRate;
8401 }
8402 if (framesRead < 0) {
8403 status_t status = (status_t) framesRead;
8404 switch (status) {
8405 case OVERRUN:
8406 ALOGW("overrun on read from pipe");
8407 framesRead = 0;
8408 break;
8409 case NEGOTIATE:
8410 ALOGE("re-negotiation is needed");
8411 framesRead = -1; // Will cause an attempt to recover.
8412 break;
8413 default:
8414 ALOGE("unknown error %d on read from pipe", status);
8415 break;
8416 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008417 }
8418 // otherwise use the HAL / AudioStreamIn directly
8419 } else {
Glenn Kastenec6a7032016-03-14 07:40:23 -07008420 ATRACE_BEGIN("read");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008421 size_t bytesRead;
Mikhail Naganov2534b382019-09-25 13:05:02 -07008422 status_t result = mSource->read(
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008423 (uint8_t*)mRsmpInBuffer + rear * mFrameSize, mBufferSize, &bytesRead);
Glenn Kastenec6a7032016-03-14 07:40:23 -07008424 ATRACE_END();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008425 if (result < 0) {
8426 framesRead = result;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008427 } else {
8428 framesRead = bytesRead / mFrameSize;
8429 }
8430 }
8431
Andy Hung446f4df2019-02-21 12:26:41 -08008432 const int64_t lastIoEndNs = systemTime(); // end IO timing
8433
Andy Hung3f0c9022016-01-15 17:49:46 -08008434 // Update server timestamp with server stats
8435 // systemTime() is optional if the hardware supports timestamps.
Andy Hung743f6402020-06-03 13:17:04 -07008436 if (framesRead >= 0) {
8437 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += framesRead;
8438 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = lastIoEndNs;
8439 }
Andy Hung3f0c9022016-01-15 17:49:46 -08008440
8441 // Update server timestamp with kernel stats
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008442 if (mPipeSource.get() == nullptr /* don't obtain for FastCapture, could block */) {
Andy Hung3f0c9022016-01-15 17:49:46 -08008443 int64_t position, time;
Andy Hung2e2c0bb2018-06-11 19:13:11 -07008444 if (mStandby) {
Dean Wheatley12473e92021-03-18 23:00:55 +11008445 mTimestampVerifier.discontinuity(audio_is_linear_pcm(mFormat) ?
8446 mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS :
8447 mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Mikhail Naganov2534b382019-09-25 13:05:02 -07008448 } else if (mSource->getCapturePosition(&position, &time) == NO_ERROR
Andy Hungc8fddf32018-08-08 18:32:37 -07008449 && time > mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]) {
8450
8451 mTimestampVerifier.add(position, time, mSampleRate);
Andy Hungab65b182023-09-06 19:41:47 -07008452 if (timestampCorrectionEnabled) {
Dean Wheatley56a583e2020-05-08 15:12:17 +10008453 ALOGVV("TS_BEFORE: %d %lld %lld",
Andy Hungc8fddf32018-08-08 18:32:37 -07008454 id(), (long long)time, (long long)position);
8455 auto correctedTimestamp = mTimestampVerifier.getLastCorrectedTimestamp();
8456 position = correctedTimestamp.mFrames;
8457 time = correctedTimestamp.mTimeNs;
Dean Wheatley56a583e2020-05-08 15:12:17 +10008458 ALOGVV("TS_AFTER: %d %lld %lld",
Andy Hungc8fddf32018-08-08 18:32:37 -07008459 id(), (long long)time, (long long)position);
8460 }
8461
Andy Hung3f0c9022016-01-15 17:49:46 -08008462 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = position;
8463 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] = time;
8464 // Note: In general record buffers should tend to be empty in
8465 // a properly running pipeline.
8466 //
8467 // Also, it is not advantageous to call get_presentation_position during the read
8468 // as the read obtains a lock, preventing the timestamp call from executing.
Andy Hung2e2c0bb2018-06-11 19:13:11 -07008469 } else {
8470 mTimestampVerifier.error();
Andy Hung3f0c9022016-01-15 17:49:46 -08008471 }
8472 }
Andy Hunge6c37112019-02-26 17:38:10 -08008473
8474 // From the timestamp, input read latency is negative output write latency.
8475 const audio_input_flags_t flags = mInput != NULL ? mInput->flags : AUDIO_INPUT_FLAG_NONE;
Andy Hung8d31fd22023-06-26 19:20:57 -07008476 const double latencyMs = IAfRecordTrack::checkServerLatencySupported(mFormat, flags)
Andy Hunge6c37112019-02-26 17:38:10 -08008477 ? - mTimestamp.getOutputServerLatencyMs(mSampleRate) : 0.;
8478 if (latencyMs != 0.) { // note 0. means timestamp is empty.
8479 mLatencyMs.add(latencyMs);
8480 }
8481
Andy Hung3f0c9022016-01-15 17:49:46 -08008482 // Use this to track timestamp information
8483 // ALOGD("%s", mTimestamp.toString().c_str());
8484
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008485 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07008486 ALOGE("read failed: framesRead=%zd", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008487 // Force input into standby so that it tries to recover at next read attempt
8488 inputStandBy();
8489 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008490 }
8491 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008492 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008493 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008494 ALOG_ASSERT(framesRead > 0);
Andy Hung6427e442018-08-09 12:51:02 -07008495 mFramesRead += framesRead;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008496
Andy Hung8946a282018-04-19 20:04:56 -07008497#ifdef TEE_SINK
8498 (void)mTee.write((uint8_t*)mRsmpInBuffer + rear * mFrameSize, framesRead);
8499#endif
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008500 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008501 {
8502 size_t part1 = mRsmpInFramesP2 - rear;
8503 if ((size_t) framesRead > part1) {
Andy Hung57446612015-04-19 23:56:46 -07008504 memcpy(mRsmpInBuffer, (uint8_t*)mRsmpInBuffer + mRsmpInFramesP2 * mFrameSize,
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008505 (framesRead - part1) * mFrameSize);
8506 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008507 }
Dean Wheatleyfd56e812020-11-06 22:32:21 +11008508 mRsmpInRear = audio_utils::safe_add_overflow(mRsmpInRear, (int32_t)framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008509
8510 size = activeTracks.size();
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008511
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008512 // loop over each active track
8513 for (size_t i = 0; i < size; i++) {
8514 activeTrack = activeTracks[i];
8515
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008516 // skip fast tracks, as those are handled directly by FastCapture
8517 if (activeTrack->isFastTrack()) {
8518 continue;
8519 }
8520
Andy Hung73c02e42015-03-29 01:13:58 -07008521 // TODO: This code probably should be moved to RecordTrack.
Andy Hung97a893e2015-03-29 01:03:07 -07008522 // TODO: Update the activeTrack buffer converter in case of reconfigure.
8523
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008524 enum {
8525 OVERRUN_UNKNOWN,
8526 OVERRUN_TRUE,
8527 OVERRUN_FALSE
8528 } overrun = OVERRUN_UNKNOWN;
8529
8530 // loop over getNextBuffer to handle circular sink
8531 for (;;) {
8532
Andy Hung8d31fd22023-06-26 19:20:57 -07008533 activeTrack->sinkBuffer().frameCount = ~0;
8534 status_t status = activeTrack->getNextBuffer(&activeTrack->sinkBuffer());
8535 size_t framesOut = activeTrack->sinkBuffer().frameCount;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008536 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
8537
Andy Hung73c02e42015-03-29 01:13:58 -07008538 // check available frames and handle overrun conditions
8539 // if the record track isn't draining fast enough.
8540 bool hasOverrun;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008541 size_t framesIn;
Andy Hung8d31fd22023-06-26 19:20:57 -07008542 activeTrack->resamplerBufferProvider()->sync(&framesIn, &hasOverrun);
Andy Hung73c02e42015-03-29 01:13:58 -07008543 if (hasOverrun) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008544 overrun = OVERRUN_TRUE;
8545 }
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08008546 if (framesOut == 0 || framesIn == 0) {
8547 break;
8548 }
8549
Andy Hung6770c6f2015-04-07 13:43:36 -07008550 // Don't allow framesOut to be larger than what is possible with resampling
8551 // from framesIn.
8552 // This isn't strictly necessary but helps limit buffer resizing in
8553 // RecordBufferConverter. TODO: remove when no longer needed.
Dean Wheatleydea650c2023-11-01 22:49:01 +11008554 if (audio_is_linear_pcm(activeTrack->format())) {
8555 framesOut = min(framesOut,
8556 destinationFramesPossible(
8557 framesIn, mSampleRate, activeTrack->sampleRate()));
8558 }
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008559
8560 if (activeTrack->isDirect()) {
Daniel Van Veen9e2376e2018-09-27 14:37:58 +10008561 // No RecordBufferConverter used for direct streams. Pass
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008562 // straight from RecordThread buffer to RecordTrack buffer.
8563 AudioBufferProvider::Buffer buffer;
8564 buffer.frameCount = framesOut;
Andy Hung920f6572022-10-06 12:09:49 -07008565 const status_t getNextBufferStatus =
Andy Hung8d31fd22023-06-26 19:20:57 -07008566 activeTrack->resamplerBufferProvider()->getNextBuffer(&buffer);
Andy Hung920f6572022-10-06 12:09:49 -07008567 if (getNextBufferStatus == OK && buffer.frameCount != 0) {
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008568 ALOGV_IF(buffer.frameCount != framesOut,
8569 "%s() read less than expected (%zu vs %zu)",
8570 __func__, buffer.frameCount, framesOut);
8571 framesOut = buffer.frameCount;
Andy Hung8d31fd22023-06-26 19:20:57 -07008572 memcpy(activeTrack->sinkBuffer().raw,
8573 buffer.raw, buffer.frameCount * mFrameSize);
8574 activeTrack->resamplerBufferProvider()->releaseBuffer(&buffer);
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008575 } else {
8576 framesOut = 0;
8577 ALOGE("%s() cannot fill request, status: %d, frameCount: %zu",
Andy Hung920f6572022-10-06 12:09:49 -07008578 __func__, getNextBufferStatus, buffer.frameCount);
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008579 }
8580 } else {
8581 // process frames from the RecordThread buffer provider to the RecordTrack
8582 // buffer
Andy Hung8d31fd22023-06-26 19:20:57 -07008583 framesOut = activeTrack->recordBufferConverter()->convert(
8584 activeTrack->sinkBuffer().raw,
8585 activeTrack->resamplerBufferProvider(),
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008586 framesOut);
8587 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008588
8589 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
8590 overrun = OVERRUN_FALSE;
8591 }
8592
Andy Hung93bb5732023-05-04 21:16:34 -07008593 // MediaSyncEvent handling: Synchronize AudioRecord to AudioTrack completion.
8594 const ssize_t framesToDrop =
Andy Hung8d31fd22023-06-26 19:20:57 -07008595 activeTrack->synchronizedRecordState().updateRecordFrames(framesOut);
Andy Hung93bb5732023-05-04 21:16:34 -07008596 if (framesToDrop == 0) {
8597 // no sync event, process normally, otherwise ignore.
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008598 if (framesOut > 0) {
Andy Hung8d31fd22023-06-26 19:20:57 -07008599 activeTrack->sinkBuffer().frameCount = framesOut;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008600 // Sanitize before releasing if the track has no access to the source data
8601 // An idle UID receives silence from non virtual devices until active
8602 if (activeTrack->isSilenced()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07008603 memset(activeTrack->sinkBuffer().raw,
8604 0, framesOut * activeTrack->frameSize());
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008605 }
Andy Hung8d31fd22023-06-26 19:20:57 -07008606 activeTrack->releaseBuffer(&activeTrack->sinkBuffer());
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008607 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008608 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008609 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008610 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008611 }
8612 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008613
8614 switch (overrun) {
8615 case OVERRUN_TRUE:
8616 // client isn't retrieving buffers fast enough
8617 if (!activeTrack->setOverflow()) {
8618 nsecs_t now = systemTime();
8619 // FIXME should lastWarning per track?
8620 if ((now - lastWarning) > kWarningThrottleNs) {
8621 ALOGW("RecordThread: buffer overflow");
8622 lastWarning = now;
8623 }
8624 }
8625 break;
8626 case OVERRUN_FALSE:
8627 activeTrack->clearOverflow();
8628 break;
8629 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008630 break;
8631 }
8632
Andy Hung3f0c9022016-01-15 17:49:46 -08008633 // update frame information and push timestamp out
8634 activeTrack->updateTrackFrameInfo(
Andy Hung8d31fd22023-06-26 19:20:57 -07008635 activeTrack->serverProxy()->framesReleased(),
Andy Hung3f0c9022016-01-15 17:49:46 -08008636 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER],
8637 mSampleRate, mTimestamp);
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008638 }
8639
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008640unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08008641 // enable changes in effect chain
8642 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07008643 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurentcccbc762019-04-05 14:20:05 -07008644 if (audio_has_proportional_frames(mFormat)
8645 && loopCount == lastLoopCountRead + 1) {
8646 const int64_t readPeriodNs = lastIoEndNs - mLastIoEndNs;
8647 const double jitterMs =
8648 TimestampVerifier<int64_t, int64_t>::computeJitterMs(
8649 {framesRead, readPeriodNs},
8650 {0, 0} /* lastTimestamp */, mSampleRate);
8651 const double processMs = (lastIoBeginNs - mLastIoEndNs) * 1e-6;
8652
Andy Hung972bec12023-08-31 16:13:39 -07008653 audio_utils::lock_guard _l(mutex());
Eric Laurentcccbc762019-04-05 14:20:05 -07008654 mIoJitterMs.add(jitterMs);
8655 mProcessTimeMs.add(processMs);
8656 }
8657 // update timing info.
8658 mLastIoBeginNs = lastIoBeginNs;
8659 mLastIoEndNs = lastIoEndNs;
8660 lastLoopCountRead = loopCount;
Eric Laurent81784c32012-11-19 14:55:58 -08008661 }
8662
Glenn Kasten93e471f2013-08-19 08:40:07 -07008663 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08008664
8665 {
Andy Hung972bec12023-08-31 16:13:39 -07008666 audio_utils::lock_guard _l(mutex());
Eric Laurent9a54bc22013-09-09 09:08:44 -07008667 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07008668 sp<IAfRecordTrack> track = mTracks[i];
Eric Laurent9a54bc22013-09-09 09:08:44 -07008669 track->invalidate();
8670 }
Glenn Kasten2b806402013-11-20 16:37:38 -08008671 mActiveTracks.clear();
Andy Hungc5007f82023-08-29 14:26:09 -07008672 mStartStopCV.notify_all();
Eric Laurent81784c32012-11-19 14:55:58 -08008673 }
8674
8675 releaseWakeLock();
8676
8677 ALOGV("RecordThread %p exiting", this);
8678 return false;
8679}
8680
Andy Hungee58e4a2023-07-07 13:47:37 -07008681void RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08008682{
8683 if (!mStandby) {
8684 inputStandBy();
Andy Hungcf10d742020-04-28 15:38:24 -07008685 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07008686 mThreadSnapshot.onEnd();
Eric Laurent81784c32012-11-19 14:55:58 -08008687 mStandby = true;
8688 }
8689}
8690
Andy Hungee58e4a2023-07-07 13:47:37 -07008691void RecordThread::inputStandBy()
Eric Laurent81784c32012-11-19 14:55:58 -08008692{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008693 // Idle the fast capture if it's currently running
8694 if (mFastCapture != 0) {
8695 FastCaptureStateQueue *sq = mFastCapture->sq();
8696 FastCaptureState *state = sq->begin();
8697 if (!(state->mCommand & FastCaptureState::IDLE)) {
8698 state->mCommand = FastCaptureState::COLD_IDLE;
8699 state->mColdFutexAddr = &mFastCaptureFutex;
8700 state->mColdGen++;
8701 mFastCaptureFutex = 0;
8702 sq->end();
8703 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
8704 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
8705#if 0
8706 if (kUseFastCapture == FastCapture_Dynamic) {
8707 // FIXME
8708 }
8709#endif
8710#ifdef AUDIO_WATCHDOG
8711 // FIXME
8712#endif
8713 } else {
8714 sq->end(false /*didModify*/);
8715 }
8716 }
Mikhail Naganov2534b382019-09-25 13:05:02 -07008717 status_t result = mSource->standby();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008718 ALOGE_IF(result != OK, "Error when putting input stream into standby: %d", result);
Andy Hungad6d52d2016-07-18 13:42:03 -07008719
8720 // If going into standby, flush the pipe source.
8721 if (mPipeSource.get() != nullptr) {
8722 const ssize_t flushed = mPipeSource->flush();
8723 if (flushed > 0) {
8724 ALOGV("Input standby flushed PipeSource %zd frames", flushed);
8725 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += flushed;
8726 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
8727 }
8728 }
Eric Laurent81784c32012-11-19 14:55:58 -08008729}
8730
Andy Hungc5007f82023-08-29 14:26:09 -07008731// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07008732sp<IAfRecordTrack> RecordThread::createRecordTrack_l(
Andy Hung88035ac2023-06-27 17:05:02 -07008733 const sp<Client>& client,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07008734 const audio_attributes_t& attr,
Eric Laurentf14db3c2017-12-08 14:20:36 -08008735 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08008736 audio_format_t format,
8737 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08008738 size_t *pFrameCount,
Glenn Kastend848eb42016-03-08 13:42:11 -08008739 audio_session_t sessionId,
Eric Laurentf14db3c2017-12-08 14:20:36 -08008740 size_t *pNotificationFrameCount,
Eric Laurent09f1ed22019-04-24 17:45:17 -07008741 pid_t creatorPid,
Svet Ganov33761132021-05-13 22:51:08 +00008742 const AttributionSourceState& attributionSource,
Eric Laurent05067782016-06-01 18:27:28 -07008743 audio_input_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08008744 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08008745 status_t *status,
Eric Laurentec376dc2021-04-08 20:41:22 +02008746 audio_port_handle_t portId,
8747 int32_t maxSharedAudioHistoryMs)
Eric Laurent81784c32012-11-19 14:55:58 -08008748{
Glenn Kasten74935e42013-12-19 08:56:45 -08008749 size_t frameCount = *pFrameCount;
Eric Laurentf14db3c2017-12-08 14:20:36 -08008750 size_t notificationFrameCount = *pNotificationFrameCount;
Andy Hung8d31fd22023-06-26 19:20:57 -07008751 sp<IAfRecordTrack> track;
Eric Laurent81784c32012-11-19 14:55:58 -08008752 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07008753 audio_input_flags_t inputFlags = mInput->flags;
Eric Laurentf14db3c2017-12-08 14:20:36 -08008754 audio_input_flags_t requestedFlags = *flags;
8755 uint32_t sampleRate;
8756
8757 lStatus = initCheck();
8758 if (lStatus != NO_ERROR) {
8759 ALOGE("createRecordTrack_l() audio driver not initialized");
8760 goto Exit;
8761 }
8762
Mikhail Naganovce9f2652018-07-16 11:09:24 -07008763 if (!audio_is_linear_pcm(mFormat) && (*flags & AUDIO_INPUT_FLAG_DIRECT) == 0) {
8764 ALOGE("createRecordTrack_l() on an encoded stream requires AUDIO_INPUT_FLAG_DIRECT");
8765 lStatus = BAD_VALUE;
8766 goto Exit;
8767 }
8768
Eric Laurentec376dc2021-04-08 20:41:22 +02008769 if (maxSharedAudioHistoryMs != 0) {
Eric Laurent9ff3e532022-11-10 16:04:44 +01008770 if (!captureHotwordAllowed(attributionSource)) {
Eric Laurentec376dc2021-04-08 20:41:22 +02008771 lStatus = PERMISSION_DENIED;
8772 goto Exit;
8773 }
Eric Laurentec376dc2021-04-08 20:41:22 +02008774 if (maxSharedAudioHistoryMs < 0
Andy Hung25a80ac2023-07-19 12:47:35 -07008775 || maxSharedAudioHistoryMs > kMaxSharedAudioHistoryMs) {
Eric Laurentec376dc2021-04-08 20:41:22 +02008776 lStatus = BAD_VALUE;
8777 goto Exit;
8778 }
8779 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08008780 if (*pSampleRate == 0) {
8781 *pSampleRate = mSampleRate;
8782 }
8783 sampleRate = *pSampleRate;
Eric Laurent05067782016-06-01 18:27:28 -07008784
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008785 // special case for FAST flag considered OK if fast capture is present and access to
8786 // audio history is not required
8787 if (hasFastCapture() && mMaxSharedAudioHistoryMs == 0) {
Eric Laurent05067782016-06-01 18:27:28 -07008788 inputFlags = (audio_input_flags_t)(inputFlags | AUDIO_INPUT_FLAG_FAST);
8789 }
8790
Eric Laurentf14db3c2017-12-08 14:20:36 -08008791 // Check if requested flags are compatible with input stream flags
Eric Laurent05067782016-06-01 18:27:28 -07008792 if ((*flags & inputFlags) != *flags) {
8793 ALOGW("createRecordTrack_l(): mismatch between requested flags (%08x) and"
8794 " input flags (%08x)",
8795 *flags, inputFlags);
8796 *flags = (audio_input_flags_t)(*flags & inputFlags);
8797 }
Eric Laurent81784c32012-11-19 14:55:58 -08008798
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008799 // client expresses a preference for FAST and no access to audio history,
8800 // but we get the final say
8801 if (*flags & AUDIO_INPUT_FLAG_FAST && maxSharedAudioHistoryMs == 0) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07008802 if (
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07008803 // we formerly checked for a callback handler (non-0 tid),
8804 // but that is no longer required for TRANSFER_OBTAIN mode
jiabinb00edc32021-08-16 16:27:54 +00008805 // No need to match hardware format, format conversion will be done in client side.
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07008806 //
Phil Burk7ed66a12019-04-18 13:20:30 -07008807 // Frame count is not specified (0), or is less than or equal the pipe depth.
8808 // It is OK to provide a higher capacity than requested.
8809 // We will force it to mPipeFramesP2 below.
8810 (frameCount <= mPipeFramesP2) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07008811 // PCM data
8812 audio_is_linear_pcm(format) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08008813 // hardware channel mask
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008814 (channelMask == mChannelMask) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08008815 // hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07008816 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07008817 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008818 hasFastCapture() &&
8819 // there are sufficient fast track slots available
8820 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07008821 ) {
Eric Laurent4c415062016-06-17 16:14:16 -07008822 // check compatibility with audio effects.
Andy Hung972bec12023-08-31 16:13:39 -07008823 audio_utils::lock_guard _l(mutex());
Eric Laurent4c415062016-06-17 16:14:16 -07008824 // Do not accept FAST flag if the session has software effects
Andy Hung116bc262023-06-20 18:56:17 -07008825 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent4c415062016-06-17 16:14:16 -07008826 if (chain != 0) {
Andy Hungd3bb0ad2016-10-11 17:16:43 -07008827 audio_input_flags_t old = *flags;
8828 chain->checkInputFlagCompatibility(flags);
8829 if (old != *flags) {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008830 ALOGV("%p AUDIO_INPUT_FLAGS denied by effect old=%#x new=%#x",
8831 this, (int)old, (int)*flags);
Eric Laurent4c415062016-06-17 16:14:16 -07008832 }
8833 }
Eric Laurent122f7e72016-06-29 11:53:29 -07008834 ALOGV_IF((*flags & AUDIO_INPUT_FLAG_FAST) != 0,
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008835 "%p AUDIO_INPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
8836 this, frameCount, mFrameCount);
Glenn Kasten90e58b12013-07-31 16:16:02 -07008837 } else {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008838 ALOGV("%p AUDIO_INPUT_FLAG_FAST denied: frameCount=%zu mFrameCount=%zu mPipeFramesP2=%zu "
8839 "format=%#x isLinear=%d mFormat=%#x channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008840 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008841 this, frameCount, mFrameCount, mPipeFramesP2,
8842 format, audio_is_linear_pcm(format), mFormat, channelMask, sampleRate, mSampleRate,
Glenn Kasten74105912014-07-03 12:28:53 -07008843 hasFastCapture(), tid, mFastTrackAvail);
Eric Laurent05067782016-06-01 18:27:28 -07008844 *flags = (audio_input_flags_t)(*flags & ~AUDIO_INPUT_FLAG_FAST);
Glenn Kasten74105912014-07-03 12:28:53 -07008845 }
8846 }
8847
Eric Laurentf14db3c2017-12-08 14:20:36 -08008848 // If FAST or RAW flags were corrected, ask caller to request new input from audio policy
8849 if ((*flags & AUDIO_INPUT_FLAG_FAST) !=
8850 (requestedFlags & AUDIO_INPUT_FLAG_FAST)) {
8851 *flags = (audio_input_flags_t) (*flags & ~(AUDIO_INPUT_FLAG_FAST | AUDIO_INPUT_FLAG_RAW));
8852 lStatus = BAD_TYPE;
8853 goto Exit;
8854 }
8855
Glenn Kasten74105912014-07-03 12:28:53 -07008856 // compute track buffer size in frames, and suggest the notification frame count
Eric Laurent05067782016-06-01 18:27:28 -07008857 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten74105912014-07-03 12:28:53 -07008858 // fast track: frame count is exactly the pipe depth
8859 frameCount = mPipeFramesP2;
8860 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
Eric Laurentf14db3c2017-12-08 14:20:36 -08008861 notificationFrameCount = mFrameCount;
Glenn Kasten74105912014-07-03 12:28:53 -07008862 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07008863 // not fast track: max notification period is resampled equivalent of one HAL buffer time
8864 // or 20 ms if there is a fast capture
8865 // TODO This could be a roundupRatio inline, and const
8866 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
8867 * sampleRate + mSampleRate - 1) / mSampleRate;
8868 // minimum number of notification periods is at least kMinNotifications,
8869 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
8870 static const size_t kMinNotifications = 3;
8871 static const uint32_t kMinMs = 30;
8872 // TODO This could be a roundupRatio inline
8873 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
8874 // TODO This could be a roundupRatio inline
8875 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
8876 maxNotificationFrames;
8877 const size_t minFrameCount = maxNotificationFrames *
8878 max(kMinNotifications, minNotificationsByMs);
8879 frameCount = max(frameCount, minFrameCount);
Eric Laurentf14db3c2017-12-08 14:20:36 -08008880 if (notificationFrameCount == 0 || notificationFrameCount > maxNotificationFrames) {
8881 notificationFrameCount = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07008882 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07008883 }
Glenn Kasten74935e42013-12-19 08:56:45 -08008884 *pFrameCount = frameCount;
Eric Laurentf14db3c2017-12-08 14:20:36 -08008885 *pNotificationFrameCount = notificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08008886
Andy Hungc5007f82023-08-29 14:26:09 -07008887 { // scope for mutex()
Andy Hung972bec12023-08-31 16:13:39 -07008888 audio_utils::lock_guard _l(mutex());
Eric Laurent2407ce32021-04-26 14:56:03 +02008889 int32_t startFrames = -1;
Eric Laurentec376dc2021-04-08 20:41:22 +02008890 if (!mSharedAudioPackageName.empty()
Eric Laurent9ff3e532022-11-10 16:04:44 +01008891 && mSharedAudioPackageName == attributionSource.packageName
Eric Laurentec376dc2021-04-08 20:41:22 +02008892 && mSharedAudioSessionId == sessionId
Eric Laurent9ff3e532022-11-10 16:04:44 +01008893 && captureHotwordAllowed(attributionSource)) {
Eric Laurent2407ce32021-04-26 14:56:03 +02008894 startFrames = mSharedAudioStartFrames;
Eric Laurentec376dc2021-04-08 20:41:22 +02008895 }
Eric Laurent81784c32012-11-19 14:55:58 -08008896
Andy Hung8d31fd22023-06-26 19:20:57 -07008897 track = IAfRecordTrack::create(this, client, attr, sampleRate,
Andy Hung8fe68032017-06-05 16:17:51 -07008898 format, channelMask, frameCount,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07008899 nullptr /* buffer */, (size_t)0 /* bufferSize */, sessionId, creatorPid,
Andy Hung8d31fd22023-06-26 19:20:57 -07008900 attributionSource, *flags, IAfTrackBase::TYPE_DEFAULT, portId,
Svet Ganov33761132021-05-13 22:51:08 +00008901 startFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08008902
Glenn Kasten03003332013-08-06 15:40:54 -07008903 lStatus = track->initCheck();
8904 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07008905 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08008906 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08008907 goto Exit;
8908 }
8909 mTracks.add(track);
8910
Eric Laurent05067782016-06-01 18:27:28 -07008911 if ((*flags & AUDIO_INPUT_FLAG_FAST) && (tid != -1)) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07008912 pid_t callingPid = IPCThreadState::self()->getCallingPid();
8913 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
8914 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07008915 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Glenn Kasten90e58b12013-07-31 16:16:02 -07008916 }
Eric Laurentec376dc2021-04-08 20:41:22 +02008917
8918 if (maxSharedAudioHistoryMs != 0) {
8919 sendResizeBufferConfigEvent_l(maxSharedAudioHistoryMs);
8920 }
Eric Laurent81784c32012-11-19 14:55:58 -08008921 }
Glenn Kasten05997e22014-03-13 15:08:33 -07008922
Eric Laurent81784c32012-11-19 14:55:58 -08008923 lStatus = NO_ERROR;
8924
8925Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07008926 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08008927 return track;
8928}
8929
Andy Hungee58e4a2023-07-07 13:47:37 -07008930status_t RecordThread::start(IAfRecordTrack* recordTrack,
Eric Laurent81784c32012-11-19 14:55:58 -08008931 AudioSystem::sync_event_t event,
Glenn Kastend848eb42016-03-08 13:42:11 -08008932 audio_session_t triggerSession)
Eric Laurent81784c32012-11-19 14:55:58 -08008933{
8934 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
8935 sp<ThreadBase> strongMe = this;
8936 status_t status = NO_ERROR;
8937
8938 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08008939 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08008940 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Andy Hung8d31fd22023-06-26 19:20:57 -07008941 recordTrack->synchronizedRecordState().startRecording(
Andy Hung583043b2023-07-17 17:05:00 -07008942 mAfThreadCallback->createSyncEvent(
Andy Hung93bb5732023-05-04 21:16:34 -07008943 event, triggerSession,
8944 recordTrack->sessionId(), syncStartEventCallback, recordTrack));
Eric Laurent81784c32012-11-19 14:55:58 -08008945 }
8946
8947 {
Glenn Kasten47c20702013-08-13 15:37:35 -07008948 // This section is a rendezvous between binder thread executing start() and RecordThread
Andy Hung972bec12023-08-31 16:13:39 -07008949 audio_utils::lock_guard lock(mutex());
Andy Hungce685402018-10-05 17:23:27 -07008950 if (recordTrack->isInvalid()) {
8951 recordTrack->clearSyncStartEvent();
Eric Laurentd52a28c2020-08-21 17:10:39 -07008952 ALOGW("%s track %d: invalidated before startInput", __func__, recordTrack->portId());
8953 return DEAD_OBJECT;
Andy Hungce685402018-10-05 17:23:27 -07008954 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008955 if (mActiveTracks.indexOf(recordTrack) >= 0) {
Andy Hung8d31fd22023-06-26 19:20:57 -07008956 if (recordTrack->state() == IAfTrackBase::PAUSING) {
Andy Hungce685402018-10-05 17:23:27 -07008957 // We haven't stopped yet (moved to PAUSED and not in mActiveTracks)
8958 // so no need to startInput().
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008959 ALOGV("active record track PAUSING -> ACTIVE");
Andy Hung8d31fd22023-06-26 19:20:57 -07008960 recordTrack->setState(IAfTrackBase::ACTIVE);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008961 } else {
Andy Hung8d31fd22023-06-26 19:20:57 -07008962 ALOGV("active record track state %d", (int)recordTrack->state());
Eric Laurent81784c32012-11-19 14:55:58 -08008963 }
8964 return status;
8965 }
8966
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08008967 // TODO consider other ways of handling this, such as changing the state to :STARTING and
8968 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
8969 // or using a separate command thread
Andy Hung8d31fd22023-06-26 19:20:57 -07008970 recordTrack->setState(IAfTrackBase::STARTING_1);
Glenn Kasten2b806402013-11-20 16:37:38 -08008971 mActiveTracks.add(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07008972 if (recordTrack->isExternalTrack()) {
Andy Hungc5007f82023-08-29 14:26:09 -07008973 mutex().unlock();
Eric Laurent4eb58f12018-12-07 16:41:02 -08008974 status = AudioSystem::startInput(recordTrack->portId());
Andy Hungc5007f82023-08-29 14:26:09 -07008975 mutex().lock();
Andy Hungce685402018-10-05 17:23:27 -07008976 if (recordTrack->isInvalid()) {
8977 recordTrack->clearSyncStartEvent();
Andy Hung8d31fd22023-06-26 19:20:57 -07008978 if (status == NO_ERROR && recordTrack->state() == IAfTrackBase::STARTING_1) {
8979 recordTrack->setState(IAfTrackBase::STARTING_2);
Andy Hungce685402018-10-05 17:23:27 -07008980 // STARTING_2 forces destroy to call stopInput.
8981 }
Eric Laurentd52a28c2020-08-21 17:10:39 -07008982 ALOGW("%s track %d: invalidated after startInput", __func__, recordTrack->portId());
8983 return DEAD_OBJECT;
Andy Hungce685402018-10-05 17:23:27 -07008984 }
Andy Hung8d31fd22023-06-26 19:20:57 -07008985 if (recordTrack->state() != IAfTrackBase::STARTING_1) {
Andy Hungce685402018-10-05 17:23:27 -07008986 ALOGW("%s(%d): unsynchronized mState:%d change",
Andy Hung8d31fd22023-06-26 19:20:57 -07008987 __func__, recordTrack->id(), (int)recordTrack->state());
Andy Hungce685402018-10-05 17:23:27 -07008988 // Someone else has changed state, let them take over,
8989 // leave mState in the new state.
8990 recordTrack->clearSyncStartEvent();
8991 return INVALID_OPERATION;
8992 }
8993 // we're ok, but perhaps startInput has failed
Eric Laurent83b88082014-06-20 18:31:16 -07008994 if (status != NO_ERROR) {
Andy Hungce685402018-10-05 17:23:27 -07008995 ALOGW("%s(%d): startInput failed, status %d",
8996 __func__, recordTrack->id(), status);
8997 // We are in ActiveTracks if STARTING_1 and valid, so remove from ActiveTracks,
8998 // leave in STARTING_1, so destroy() will not call stopInput.
Eric Laurent83b88082014-06-20 18:31:16 -07008999 mActiveTracks.remove(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07009000 recordTrack->clearSyncStartEvent();
Eric Laurent83b88082014-06-20 18:31:16 -07009001 return status;
9002 }
Eric Laurent09f1ed22019-04-24 17:45:17 -07009003 sendIoConfigEvent_l(
9004 AUDIO_CLIENT_STARTED, recordTrack->creatorPid(), recordTrack->portId());
Eric Laurent81784c32012-11-19 14:55:58 -08009005 }
Andy Hungc2b11cb2020-04-22 09:04:01 -07009006
9007 recordTrack->logBeginInterval(patchSourcesToString(&mPatch)); // log to MediaMetrics
9008
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009009 // Catch up with current buffer indices if thread is already running.
9010 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
9011 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
9012 // see previously buffered data before it called start(), but with greater risk of overrun.
9013
Andy Hung8d31fd22023-06-26 19:20:57 -07009014 recordTrack->resamplerBufferProvider()->reset();
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07009015 if (!recordTrack->isDirect()) {
9016 // clear any converter state as new data will be discontinuous
Andy Hung8d31fd22023-06-26 19:20:57 -07009017 recordTrack->recordBufferConverter()->reset();
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07009018 }
Andy Hung8d31fd22023-06-26 19:20:57 -07009019 recordTrack->setState(IAfTrackBase::STARTING_2);
Eric Laurent81784c32012-11-19 14:55:58 -08009020 // signal thread to start
Andy Hungc5007f82023-08-29 14:26:09 -07009021 mWaitWorkCV.notify_all();
Eric Laurent81784c32012-11-19 14:55:58 -08009022 return status;
9023 }
Eric Laurent81784c32012-11-19 14:55:58 -08009024}
9025
Andy Hungee58e4a2023-07-07 13:47:37 -07009026void RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
Eric Laurent81784c32012-11-19 14:55:58 -08009027{
Andy Hungee58e4a2023-07-07 13:47:37 -07009028 const sp<SyncEvent> strongEvent = event.promote();
Eric Laurent81784c32012-11-19 14:55:58 -08009029
9030 if (strongEvent != 0) {
Andy Hungd29af632023-06-23 19:27:19 -07009031 sp<IAfTrackBase> ptr =
9032 std::any_cast<const wp<IAfTrackBase>>(strongEvent->cookie()).promote();
9033 if (ptr != nullptr) {
Andy Hung99b1ba62023-07-14 11:00:08 -07009034 // TODO(b/291317898) handleSyncStartEvent is in IAfTrackBase not IAfRecordTrack.
Andy Hungd29af632023-06-23 19:27:19 -07009035 ptr->handleSyncStartEvent(strongEvent);
Eric Laurent8ea16e42014-02-20 16:26:11 -08009036 }
Eric Laurent81784c32012-11-19 14:55:58 -08009037 }
9038}
9039
Andy Hungee58e4a2023-07-07 13:47:37 -07009040bool RecordThread::stop(IAfRecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08009041 ALOGV("RecordThread::stop");
Andy Hungc5007f82023-08-29 14:26:09 -07009042 audio_utils::unique_lock _l(mutex());
Andy Hungce685402018-10-05 17:23:27 -07009043 // if we're invalid, we can't be on the ActiveTracks.
Andy Hung8d31fd22023-06-26 19:20:57 -07009044 if (mActiveTracks.indexOf(recordTrack) < 0 || recordTrack->state() == IAfTrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08009045 return false;
9046 }
Glenn Kasten47c20702013-08-13 15:37:35 -07009047 // note that threadLoop may still be processing the track at this point [without lock]
Andy Hung8d31fd22023-06-26 19:20:57 -07009048 recordTrack->setState(IAfTrackBase::PAUSING);
Andy Hungce685402018-10-05 17:23:27 -07009049
Andy Hungabfab202019-03-07 19:45:54 -08009050 // NOTE: Waiting here is important to keep stop synchronous.
9051 // This is needed for proper patchRecord peer release.
Andy Hung8d31fd22023-06-26 19:20:57 -07009052 while (recordTrack->state() == IAfTrackBase::PAUSING && !recordTrack->isInvalid()) {
Andy Hungc5007f82023-08-29 14:26:09 -07009053 mWaitWorkCV.notify_all(); // signal thread to stop
9054 mStartStopCV.wait(_l);
Eric Laurent81784c32012-11-19 14:55:58 -08009055 }
Andy Hungce685402018-10-05 17:23:27 -07009056
Andy Hung8d31fd22023-06-26 19:20:57 -07009057 if (recordTrack->state() == IAfTrackBase::PAUSED) { // successful stop
Eric Laurent81784c32012-11-19 14:55:58 -08009058 ALOGV("Record stopped OK");
9059 return true;
9060 }
Andy Hungce685402018-10-05 17:23:27 -07009061
9062 // don't handle anything - we've been invalidated or restarted and in a different state
9063 ALOGW_IF("%s(%d): unsynchronized stop, state: %d",
Andy Hung8d31fd22023-06-26 19:20:57 -07009064 __func__, recordTrack->id(), recordTrack->state());
Eric Laurent81784c32012-11-19 14:55:58 -08009065 return false;
9066}
9067
Andy Hungee58e4a2023-07-07 13:47:37 -07009068bool RecordThread::isValidSyncEvent(const sp<SyncEvent>& /* event */) const
Eric Laurent81784c32012-11-19 14:55:58 -08009069{
9070 return false;
9071}
9072
Andy Hungee58e4a2023-07-07 13:47:37 -07009073status_t RecordThread::setSyncEvent(const sp<SyncEvent>& /* event */)
Eric Laurent81784c32012-11-19 14:55:58 -08009074{
9075#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
9076 if (!isValidSyncEvent(event)) {
9077 return BAD_VALUE;
9078 }
9079
Glenn Kastend848eb42016-03-08 13:42:11 -08009080 audio_session_t eventSession = event->triggerSession();
Eric Laurent81784c32012-11-19 14:55:58 -08009081 status_t ret = NAME_NOT_FOUND;
9082
Andy Hung972bec12023-08-31 16:13:39 -07009083 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08009084
9085 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07009086 sp<IAfRecordTrack> track = mTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08009087 if (eventSession == track->sessionId()) {
9088 (void) track->setSyncEvent(event);
9089 ret = NO_ERROR;
9090 }
9091 }
9092 return ret;
9093#else
9094 return BAD_VALUE;
9095#endif
9096}
9097
Andy Hungee58e4a2023-07-07 13:47:37 -07009098status_t RecordThread::getActiveMicrophones(
Andy Hung87c693c2023-07-06 20:56:16 -07009099 std::vector<media::MicrophoneInfoFw>* activeMicrophones) const
jiabin653cc0a2018-01-17 17:54:10 -08009100{
9101 ALOGV("RecordThread::getActiveMicrophones");
Andy Hung972bec12023-08-31 16:13:39 -07009102 audio_utils::lock_guard _l(mutex());
Jasmine Chaeaa10e42021-05-11 10:11:14 +08009103 if (!isStreamInitialized()) {
Paul McLean8a661a32021-04-12 10:21:42 -06009104 return NO_INIT;
9105 }
jiabin9ff780e2018-03-19 18:19:52 -07009106 status_t status = mInput->stream->getActiveMicrophones(activeMicrophones);
9107 return status;
jiabin653cc0a2018-01-17 17:54:10 -08009108}
9109
Andy Hungee58e4a2023-07-07 13:47:37 -07009110status_t RecordThread::setPreferredMicrophoneDirection(
Paul McLean12340082019-03-19 09:35:05 -06009111 audio_microphone_direction_t direction)
Paul McLean03a6e6a2018-12-04 10:54:13 -07009112{
Paul McLean12340082019-03-19 09:35:05 -06009113 ALOGV("setPreferredMicrophoneDirection(%d)", direction);
Andy Hung972bec12023-08-31 16:13:39 -07009114 audio_utils::lock_guard _l(mutex());
Jasmine Chaeaa10e42021-05-11 10:11:14 +08009115 if (!isStreamInitialized()) {
Paul McLean8a661a32021-04-12 10:21:42 -06009116 return NO_INIT;
9117 }
Paul McLean12340082019-03-19 09:35:05 -06009118 return mInput->stream->setPreferredMicrophoneDirection(direction);
Paul McLean03a6e6a2018-12-04 10:54:13 -07009119}
9120
Andy Hungee58e4a2023-07-07 13:47:37 -07009121status_t RecordThread::setPreferredMicrophoneFieldDimension(float zoom)
Paul McLean03a6e6a2018-12-04 10:54:13 -07009122{
Paul McLean12340082019-03-19 09:35:05 -06009123 ALOGV("setPreferredMicrophoneFieldDimension(%f)", zoom);
Andy Hung972bec12023-08-31 16:13:39 -07009124 audio_utils::lock_guard _l(mutex());
Jasmine Chaeaa10e42021-05-11 10:11:14 +08009125 if (!isStreamInitialized()) {
Paul McLean8a661a32021-04-12 10:21:42 -06009126 return NO_INIT;
9127 }
Paul McLean12340082019-03-19 09:35:05 -06009128 return mInput->stream->setPreferredMicrophoneFieldDimension(zoom);
Paul McLean03a6e6a2018-12-04 10:54:13 -07009129}
9130
Andy Hungee58e4a2023-07-07 13:47:37 -07009131status_t RecordThread::shareAudioHistory(
Eric Laurentec376dc2021-04-08 20:41:22 +02009132 const std::string& sharedAudioPackageName, audio_session_t sharedSessionId,
9133 int64_t sharedAudioStartMs) {
Andy Hung972bec12023-08-31 16:13:39 -07009134 audio_utils::lock_guard _l(mutex());
Eric Laurentec376dc2021-04-08 20:41:22 +02009135 return shareAudioHistory_l(sharedAudioPackageName, sharedSessionId, sharedAudioStartMs);
9136}
9137
Andy Hungee58e4a2023-07-07 13:47:37 -07009138status_t RecordThread::shareAudioHistory_l(
Eric Laurentec376dc2021-04-08 20:41:22 +02009139 const std::string& sharedAudioPackageName, audio_session_t sharedSessionId,
9140 int64_t sharedAudioStartMs) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009141
Eric Laurentec376dc2021-04-08 20:41:22 +02009142 if ((hasAudioSession_l(sharedSessionId) & ThreadBase::TRACK_SESSION) == 0) {
9143 return BAD_VALUE;
9144 }
Eric Laurent2407ce32021-04-26 14:56:03 +02009145
9146 if (sharedAudioStartMs < 0
9147 || sharedAudioStartMs > INT64_MAX / mSampleRate) {
Eric Laurentec376dc2021-04-08 20:41:22 +02009148 return BAD_VALUE;
9149 }
9150
Eric Laurent2407ce32021-04-26 14:56:03 +02009151 // Current implementation of the input resampling buffer wraps around indexes at 32 bit.
9152 // As we cannot detect more than one wraparound, only accept values up current write position
9153 // after one wraparound
9154 // We assume recent wraparounds on mRsmpInRear only given it is unlikely that the requesting
9155 // app waits several hours after the start time was computed.
Eric Laurent92d0a322021-07-16 15:32:33 +02009156 int64_t sharedAudioStartFrames = sharedAudioStartMs * mSampleRate / 1000;
Eric Laurent2407ce32021-04-26 14:56:03 +02009157 const int32_t sharedOffset = audio_utils::safe_sub_overflow(mRsmpInRear,
9158 (int32_t)sharedAudioStartFrames);
Eric Laurent92d0a322021-07-16 15:32:33 +02009159 // Bring the start frame position within the input buffer to match the documented
9160 // "best effort" behavior of the API.
9161 if (sharedOffset < 0) {
9162 sharedAudioStartFrames = mRsmpInRear;
Andy Hung920f6572022-10-06 12:09:49 -07009163 } else if (sharedOffset > static_cast<signed>(mRsmpInFrames)) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009164 sharedAudioStartFrames =
9165 audio_utils::safe_sub_overflow(mRsmpInRear, (int32_t)mRsmpInFrames);
Eric Laurent2407ce32021-04-26 14:56:03 +02009166 }
9167
Eric Laurentec376dc2021-04-08 20:41:22 +02009168 mSharedAudioPackageName = sharedAudioPackageName;
9169 if (mSharedAudioPackageName.empty()) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009170 resetAudioHistory_l();
Eric Laurentec376dc2021-04-08 20:41:22 +02009171 } else {
9172 mSharedAudioSessionId = sharedSessionId;
Eric Laurent2407ce32021-04-26 14:56:03 +02009173 mSharedAudioStartFrames = (int32_t)sharedAudioStartFrames;
Eric Laurentec376dc2021-04-08 20:41:22 +02009174 }
9175 return NO_ERROR;
9176}
9177
Andy Hungee58e4a2023-07-07 13:47:37 -07009178void RecordThread::resetAudioHistory_l() {
Eric Laurent92d0a322021-07-16 15:32:33 +02009179 mSharedAudioSessionId = AUDIO_SESSION_NONE;
9180 mSharedAudioStartFrames = -1;
9181 mSharedAudioPackageName = "";
9182}
9183
Andy Hungee58e4a2023-07-07 13:47:37 -07009184ThreadBase::MetadataUpdate RecordThread::updateMetadata_l()
Kevin Rocard069c2712018-03-29 19:09:14 -07009185{
Jasmine Chaeaa10e42021-05-11 10:11:14 +08009186 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
Vlad Popa7e81cea2023-01-19 16:34:16 +01009187 return {}; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -07009188 }
9189 StreamInHalInterface::SinkMetadata metadata;
Eric Laurent78b07302022-10-07 16:20:34 +02009190 auto backInserter = std::back_inserter(metadata.tracks);
Andy Hung8d31fd22023-06-26 19:20:57 -07009191 for (const sp<IAfRecordTrack>& track : mActiveTracks) {
Eric Laurent78b07302022-10-07 16:20:34 +02009192 track->copyMetadataTo(backInserter);
Kevin Rocard069c2712018-03-29 19:09:14 -07009193 }
9194 mInput->stream->updateSinkMetadata(metadata);
Vlad Popa7e81cea2023-01-19 16:34:16 +01009195 MetadataUpdate change;
9196 change.recordMetadataUpdate = metadata.tracks;
9197 return change;
Kevin Rocard069c2712018-03-29 19:09:14 -07009198}
9199
Andy Hungc5007f82023-08-29 14:26:09 -07009200// destroyTrack_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07009201void RecordThread::destroyTrack_l(const sp<IAfRecordTrack>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08009202{
Eric Laurentbfb1b832013-01-07 09:53:42 -08009203 track->terminate();
Andy Hung8d31fd22023-06-26 19:20:57 -07009204 track->setState(IAfTrackBase::STOPPED);
Eric Laurentec376dc2021-04-08 20:41:22 +02009205
Eric Laurent81784c32012-11-19 14:55:58 -08009206 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08009207 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08009208 removeTrack_l(track);
9209 }
9210}
9211
Andy Hungee58e4a2023-07-07 13:47:37 -07009212void RecordThread::removeTrack_l(const sp<IAfRecordTrack>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08009213{
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009214 String8 result;
9215 track->appendDump(result, false /* active */);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00009216 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.c_str());
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009217
Eric Laurent81784c32012-11-19 14:55:58 -08009218 mTracks.remove(track);
9219 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07009220 if (track->isFastTrack()) {
9221 ALOG_ASSERT(!mFastTrackAvail);
9222 mFastTrackAvail = true;
9223 }
Eric Laurent81784c32012-11-19 14:55:58 -08009224}
9225
Andy Hungee58e4a2023-07-07 13:47:37 -07009226void RecordThread::dumpInternals_l(int fd, const Vector<String16>& /* args */)
Eric Laurent81784c32012-11-19 14:55:58 -08009227{
Mikhail Naganov913d06c2016-11-01 12:49:22 -07009228 AudioStreamIn *input = mInput;
9229 audio_input_flags_t flags = input != NULL ? input->flags : AUDIO_INPUT_FLAG_NONE;
9230 dprintf(fd, " AudioStreamIn: %p flags %#x (%s)\n",
Andy Hung9b181952019-02-25 14:53:36 -08009231 input, flags, toString(flags).c_str());
Andy Hung6427e442018-08-09 12:51:02 -07009232 dprintf(fd, " Frames read: %lld\n", (long long)mFramesRead);
Eric Tan39ec8d62018-07-24 09:49:29 -07009233 if (mActiveTracks.isEmpty()) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07009234 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08009235 }
Andy Hungbfa64962017-06-12 14:43:19 -07009236
9237 if (input != nullptr) {
9238 dprintf(fd, " Hal stream dump:\n");
9239 (void)input->stream->dump(fd);
9240 }
9241
Glenn Kasten6e6704c2014-07-03 10:20:00 -07009242 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07009243 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Glenn Kasten17c9c992015-03-02 15:53:01 -08009244
Glenn Kasten2f90c512015-12-02 11:40:09 -08009245 // Make a non-atomic copy of fast capture dump state so it won't change underneath us
9246 // while we are dumping it. It may be inconsistent, but it won't mutate!
9247 // This is a large object so we place it on the heap.
9248 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
Eric Tan2942a4e2018-09-12 17:41:27 -07009249 const std::unique_ptr<FastCaptureDumpState> copy =
9250 std::make_unique<FastCaptureDumpState>(mFastCaptureDumpState);
Glenn Kasten2f90c512015-12-02 11:40:09 -08009251 copy->dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08009252}
9253
Andy Hungee58e4a2023-07-07 13:47:37 -07009254void RecordThread::dumpTracks_l(int fd, const Vector<String16>& /* args */)
Eric Laurent81784c32012-11-19 14:55:58 -08009255{
Eric Laurent81784c32012-11-19 14:55:58 -08009256 String8 result;
Marco Nelissenb2208842014-02-07 14:00:50 -08009257 size_t numtracks = mTracks.size();
9258 size_t numactive = mActiveTracks.size();
9259 size_t numactiveseen = 0;
Glenn Kastenc42e9b42016-03-21 11:35:03 -07009260 dprintf(fd, " %zu Tracks", numtracks);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009261 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08009262 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07009263 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009264 result.append(prefix);
Andy Hung000adb52018-06-01 15:43:26 -07009265 mTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08009266 for (size_t i = 0; i < numtracks ; ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07009267 sp<IAfRecordTrack> track = mTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08009268 if (track != 0) {
9269 bool active = mActiveTracks.indexOf(track) >= 0;
9270 if (active) {
9271 numactiveseen++;
9272 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009273 result.append(prefix);
9274 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08009275 }
Eric Laurent81784c32012-11-19 14:55:58 -08009276 }
Marco Nelissenb2208842014-02-07 14:00:50 -08009277 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07009278 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08009279 }
9280
Marco Nelissenb2208842014-02-07 14:00:50 -08009281 if (numactiveseen != numactive) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009282 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08009283 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009284 result.append(prefix);
Andy Hung000adb52018-06-01 15:43:26 -07009285 mActiveTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08009286 for (size_t i = 0; i < numactive; ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07009287 sp<IAfRecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08009288 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009289 result.append(prefix);
9290 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08009291 }
Glenn Kasten2b806402013-11-20 16:37:38 -08009292 }
Eric Laurent81784c32012-11-19 14:55:58 -08009293
9294 }
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00009295 write(fd, result.c_str(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08009296}
9297
Andy Hungee58e4a2023-07-07 13:47:37 -07009298void RecordThread::setRecordSilenced(audio_port_handle_t portId, bool silenced)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08009299{
Andy Hung972bec12023-08-31 16:13:39 -07009300 audio_utils::lock_guard _l(mutex());
Svet Ganovf4ddfef2018-01-16 07:37:58 -08009301 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07009302 sp<IAfRecordTrack> track = mTracks[i];
Eric Laurent5ada82e2019-08-29 17:53:54 -07009303 if (track != 0 && track->portId() == portId) {
Svet Ganovf4ddfef2018-01-16 07:37:58 -08009304 track->setSilenced(silenced);
9305 }
9306 }
9307}
Andy Hung73c02e42015-03-29 01:13:58 -07009308
Andy Hung8d31fd22023-06-26 19:20:57 -07009309void ResamplerBufferProvider::reset()
Andy Hung73c02e42015-03-29 01:13:58 -07009310{
Andy Hung87c693c2023-07-06 20:56:16 -07009311 const auto threadBase = mRecordTrack->thread().promote();
Andy Hungee58e4a2023-07-07 13:47:37 -07009312 auto* const recordThread = static_cast<RecordThread *>(threadBase->asIAfRecordThread().get());
Andy Hung73c02e42015-03-29 01:13:58 -07009313 mRsmpInUnrel = 0;
Eric Laurentec376dc2021-04-08 20:41:22 +02009314 const int32_t rear = recordThread->mRsmpInRear;
9315 ssize_t deltaFrames = 0;
Eric Laurent2407ce32021-04-26 14:56:03 +02009316 if (mRecordTrack->startFrames() >= 0) {
9317 int32_t startFrames = mRecordTrack->startFrames();
9318 // Accept a recent wraparound of mRsmpInRear
9319 if (startFrames <= rear) {
9320 deltaFrames = rear - startFrames;
9321 } else {
9322 deltaFrames = (int32_t)((int64_t)rear + UINT32_MAX + 1 - startFrames);
Eric Laurentec376dc2021-04-08 20:41:22 +02009323 }
Eric Laurentec376dc2021-04-08 20:41:22 +02009324 // start frame cannot be further in the past than start of resampling buffer
9325 if ((size_t) deltaFrames > recordThread->mRsmpInFrames) {
9326 deltaFrames = recordThread->mRsmpInFrames;
9327 }
9328 }
9329 mRsmpInFront = audio_utils::safe_sub_overflow(rear, static_cast<int32_t>(deltaFrames));
Andy Hung73c02e42015-03-29 01:13:58 -07009330}
9331
Andy Hung8d31fd22023-06-26 19:20:57 -07009332void ResamplerBufferProvider::sync(
Andy Hung73c02e42015-03-29 01:13:58 -07009333 size_t *framesAvailable, bool *hasOverrun)
9334{
Andy Hung87c693c2023-07-06 20:56:16 -07009335 const auto threadBase = mRecordTrack->thread().promote();
Andy Hungee58e4a2023-07-07 13:47:37 -07009336 auto* const recordThread = static_cast<RecordThread *>(threadBase->asIAfRecordThread().get());
Andy Hung73c02e42015-03-29 01:13:58 -07009337 const int32_t rear = recordThread->mRsmpInRear;
9338 const int32_t front = mRsmpInFront;
Hongwei Wang95e37682019-04-12 11:13:36 -07009339 const ssize_t filled = audio_utils::safe_sub_overflow(rear, front);
Andy Hung73c02e42015-03-29 01:13:58 -07009340
9341 size_t framesIn;
9342 bool overrun = false;
9343 if (filled < 0) {
9344 // should not happen, but treat like a massive overrun and re-sync
9345 framesIn = 0;
9346 mRsmpInFront = rear;
9347 overrun = true;
9348 } else if ((size_t) filled <= recordThread->mRsmpInFrames) {
9349 framesIn = (size_t) filled;
9350 } else {
9351 // client is not keeping up with server, but give it latest data
9352 framesIn = recordThread->mRsmpInFrames;
Hongwei Wang95e37682019-04-12 11:13:36 -07009353 mRsmpInFront = /* front = */ audio_utils::safe_sub_overflow(
9354 rear, static_cast<int32_t>(framesIn));
Andy Hung73c02e42015-03-29 01:13:58 -07009355 overrun = true;
9356 }
9357 if (framesAvailable != NULL) {
9358 *framesAvailable = framesIn;
9359 }
9360 if (hasOverrun != NULL) {
9361 *hasOverrun = overrun;
9362 }
9363}
9364
Eric Laurent81784c32012-11-19 14:55:58 -08009365// AudioBufferProvider interface
Andy Hung8d31fd22023-06-26 19:20:57 -07009366status_t ResamplerBufferProvider::getNextBuffer(
Glenn Kastend79072e2016-01-06 08:41:20 -08009367 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08009368{
Andy Hung87c693c2023-07-06 20:56:16 -07009369 const auto threadBase = mRecordTrack->thread().promote();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009370 if (threadBase == 0) {
9371 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08009372 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009373 return NOT_ENOUGH_DATA;
9374 }
Andy Hungee58e4a2023-07-07 13:47:37 -07009375 auto* const recordThread = static_cast<RecordThread *>(threadBase->asIAfRecordThread().get());
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009376 int32_t rear = recordThread->mRsmpInRear;
Andy Hung73c02e42015-03-29 01:13:58 -07009377 int32_t front = mRsmpInFront;
Hongwei Wang95e37682019-04-12 11:13:36 -07009378 ssize_t filled = audio_utils::safe_sub_overflow(rear, front);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009379 // FIXME should not be P2 (don't want to increase latency)
9380 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08009381 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07009382 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009383
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009384 front &= recordThread->mRsmpInFramesP2 - 1;
9385 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07009386 if (part1 > (size_t) filled) {
9387 part1 = filled;
9388 }
9389 size_t ask = buffer->frameCount;
9390 ALOG_ASSERT(ask > 0);
9391 if (part1 > ask) {
9392 part1 = ask;
9393 }
9394 if (part1 == 0) {
Andy Hung73c02e42015-03-29 01:13:58 -07009395 // out of data is fine since the resampler will return a short-count.
Glenn Kasten85948432013-08-19 12:09:05 -07009396 buffer->raw = NULL;
9397 buffer->frameCount = 0;
Andy Hung73c02e42015-03-29 01:13:58 -07009398 mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07009399 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08009400 }
9401
Andy Hung57446612015-04-19 23:56:46 -07009402 buffer->raw = (uint8_t*)recordThread->mRsmpInBuffer + front * recordThread->mFrameSize;
Glenn Kasten85948432013-08-19 12:09:05 -07009403 buffer->frameCount = part1;
Andy Hung73c02e42015-03-29 01:13:58 -07009404 mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08009405 return NO_ERROR;
9406}
9407
9408// AudioBufferProvider interface
Andy Hung8d31fd22023-06-26 19:20:57 -07009409void ResamplerBufferProvider::releaseBuffer(
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009410 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08009411{
Hongwei Wang95e37682019-04-12 11:13:36 -07009412 int32_t stepCount = static_cast<int32_t>(buffer->frameCount);
Glenn Kasten85948432013-08-19 12:09:05 -07009413 if (stepCount == 0) {
9414 return;
9415 }
Eric Laurent1e28aaa2023-04-16 19:34:23 +02009416 ALOG_ASSERT(stepCount <= (int32_t)mRsmpInUnrel);
Andy Hung73c02e42015-03-29 01:13:58 -07009417 mRsmpInUnrel -= stepCount;
Hongwei Wang95e37682019-04-12 11:13:36 -07009418 mRsmpInFront = audio_utils::safe_add_overflow(mRsmpInFront, stepCount);
Glenn Kasten85948432013-08-19 12:09:05 -07009419 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08009420 buffer->frameCount = 0;
9421}
9422
Andy Hungee58e4a2023-07-07 13:47:37 -07009423void RecordThread::checkBtNrec()
Eric Laurentd8365c52017-07-16 15:27:05 -07009424{
Andy Hung972bec12023-08-31 16:13:39 -07009425 audio_utils::lock_guard _l(mutex());
Eric Laurentd8365c52017-07-16 15:27:05 -07009426 checkBtNrec_l();
9427}
9428
Andy Hungee58e4a2023-07-07 13:47:37 -07009429void RecordThread::checkBtNrec_l()
Eric Laurentd8365c52017-07-16 15:27:05 -07009430{
9431 // disable AEC and NS if the device is a BT SCO headset supporting those
9432 // pre processings
Andy Hungab65b182023-09-06 19:41:47 -07009433 bool suspend = audio_is_bluetooth_sco_device(inDeviceType_l()) &&
Andy Hung583043b2023-07-17 17:05:00 -07009434 mAfThreadCallback->btNrecIsOff();
Eric Laurentd8365c52017-07-16 15:27:05 -07009435 if (mBtNrecSuspended.exchange(suspend) != suspend) {
9436 for (size_t i = 0; i < mEffectChains.size(); i++) {
9437 setEffectSuspended_l(FX_IID_AEC, suspend, mEffectChains[i]->sessionId());
9438 setEffectSuspended_l(FX_IID_NS, suspend, mEffectChains[i]->sessionId());
9439 }
9440 }
9441}
9442
Andy Hung97a893e2015-03-29 01:03:07 -07009443
Andy Hungee58e4a2023-07-07 13:47:37 -07009444bool RecordThread::checkForNewParameter_l(const String8& keyValuePair,
Eric Laurent10351942014-05-08 18:49:52 -07009445 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08009446{
9447 bool reconfig = false;
9448
Eric Laurent10351942014-05-08 18:49:52 -07009449 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08009450
Eric Laurent10351942014-05-08 18:49:52 -07009451 audio_format_t reqFormat = mFormat;
9452 uint32_t samplingRate = mSampleRate;
Glenn Kastene1635ec2015-06-08 15:46:49 -07009453 // 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 +08009454 [[maybe_unused]] audio_channel_mask_t channelMask =
9455 audio_channel_in_mask_from_count(mChannelCount);
Eric Laurent10351942014-05-08 18:49:52 -07009456
9457 AudioParameter param = AudioParameter(keyValuePair);
9458 int value;
Haynes Mathew George9ce67b52015-09-30 11:40:47 -07009459
9460 // scope for AutoPark extends to end of method
9461 AutoPark<FastCapture> park(mFastCapture);
9462
Eric Laurent10351942014-05-08 18:49:52 -07009463 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
9464 // channel count change can be requested. Do we mandate the first client defines the
9465 // HAL sampling rate and channel count or do we allow changes on the fly?
9466 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
9467 samplingRate = value;
9468 reconfig = true;
9469 }
9470 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung97a893e2015-03-29 01:03:07 -07009471 if (!audio_is_linear_pcm((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07009472 status = BAD_VALUE;
9473 } else {
9474 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08009475 reconfig = true;
9476 }
Eric Laurent10351942014-05-08 18:49:52 -07009477 }
9478 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
9479 audio_channel_mask_t mask = (audio_channel_mask_t) value;
Andy Hungd330ee42015-04-20 13:23:41 -07009480 if (!audio_is_input_channel(mask) ||
Andy Hung936845a2021-06-08 00:09:06 -07009481 audio_channel_count_from_in_mask(mask) > FCC_LIMIT) {
Eric Laurent10351942014-05-08 18:49:52 -07009482 status = BAD_VALUE;
9483 } else {
9484 channelMask = mask;
9485 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08009486 }
Eric Laurent10351942014-05-08 18:49:52 -07009487 }
9488 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
9489 // do not accept frame count changes if tracks are open as the track buffer
9490 // size depends on frame count and correct behavior would not be guaranteed
9491 // if frame count is changed after track creation
9492 if (mActiveTracks.size() > 0) {
9493 status = INVALID_OPERATION;
9494 } else {
9495 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08009496 }
Eric Laurent10351942014-05-08 18:49:52 -07009497 }
9498 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07009499 LOG_FATAL("Should not set routing device in RecordThread");
Eric Laurent10351942014-05-08 18:49:52 -07009500 }
9501 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
9502 mAudioSource != (audio_source_t)value) {
jiabinc52b1ff2019-10-31 17:20:42 -07009503 LOG_FATAL("Should not set audio source in RecordThread");
Eric Laurent10351942014-05-08 18:49:52 -07009504 }
Glenn Kastene198c362013-08-13 09:13:36 -07009505
Eric Laurent10351942014-05-08 18:49:52 -07009506 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009507 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07009508 if (status == INVALID_OPERATION) {
9509 inputStandBy();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009510 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07009511 }
9512 if (reconfig) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009513 if (status == BAD_VALUE) {
Mikhail Naganov560637e2021-03-31 22:40:13 +00009514 audio_config_base_t config = AUDIO_CONFIG_BASE_INITIALIZER;
9515 if (mInput->stream->getAudioProperties(&config) == OK &&
9516 audio_is_linear_pcm(config.format) && audio_is_linear_pcm(reqFormat) &&
9517 config.sample_rate <= (AUDIO_RESAMPLER_DOWN_RATIO_MAX * samplingRate) &&
Andy Hung936845a2021-06-08 00:09:06 -07009518 audio_channel_count_from_in_mask(config.channel_mask) <= FCC_LIMIT) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009519 status = NO_ERROR;
9520 }
Eric Laurent81784c32012-11-19 14:55:58 -08009521 }
Eric Laurent10351942014-05-08 18:49:52 -07009522 if (status == NO_ERROR) {
9523 readInputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07009524 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08009525 }
9526 }
Eric Laurent81784c32012-11-19 14:55:58 -08009527 }
Eric Laurent10351942014-05-08 18:49:52 -07009528
Eric Laurent81784c32012-11-19 14:55:58 -08009529 return reconfig;
9530}
9531
Andy Hungee58e4a2023-07-07 13:47:37 -07009532String8 RecordThread::getParameters(const String8& keys)
Eric Laurent81784c32012-11-19 14:55:58 -08009533{
Andy Hung972bec12023-08-31 16:13:39 -07009534 audio_utils::lock_guard _l(mutex());
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009535 if (initCheck() == NO_ERROR) {
9536 String8 out_s8;
9537 if (mInput->stream->getParameters(keys, &out_s8) == OK) {
9538 return out_s8;
9539 }
Eric Laurent81784c32012-11-19 14:55:58 -08009540 }
Andy Hung920f6572022-10-06 12:09:49 -07009541 return {};
Eric Laurent81784c32012-11-19 14:55:58 -08009542}
9543
Andy Hungab65b182023-09-06 19:41:47 -07009544void RecordThread::ioConfigChanged_l(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -07009545 audio_port_handle_t portId) {
Mikhail Naganov88536df2021-07-26 17:30:29 -07009546 sp<AudioIoDescriptor> desc;
Eric Laurent81784c32012-11-19 14:55:58 -08009547 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07009548 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07009549 case AUDIO_INPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07009550 case AUDIO_INPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07009551 desc = sp<AudioIoDescriptor>::make(mId, mPatch, true /*isInput*/,
9552 mSampleRate, mFormat, mChannelMask, mFrameCount, mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08009553 break;
Eric Laurent09f1ed22019-04-24 17:45:17 -07009554 case AUDIO_CLIENT_STARTED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07009555 desc = sp<AudioIoDescriptor>::make(mId, mPatch, portId);
Eric Laurent09f1ed22019-04-24 17:45:17 -07009556 break;
Eric Laurent73e26b62015-04-27 16:55:58 -07009557 case AUDIO_INPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08009558 default:
Mikhail Naganov88536df2021-07-26 17:30:29 -07009559 desc = sp<AudioIoDescriptor>::make(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08009560 break;
9561 }
Andy Hungab65b182023-09-06 19:41:47 -07009562 mAfThreadCallback->ioConfigChanged_l(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08009563}
9564
Andy Hungee58e4a2023-07-07 13:47:37 -07009565void RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08009566{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009567 status_t result = mInput->stream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
9568 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
Andy Hung463be252014-07-10 16:56:07 -07009569 mFormat = mHALFormat;
Mikhail Naganovce9f2652018-07-16 11:09:24 -07009570 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
9571 if (audio_is_linear_pcm(mFormat)) {
Andy Hung936845a2021-06-08 00:09:06 -07009572 LOG_ALWAYS_FATAL_IF(mChannelCount > FCC_LIMIT, "HAL channel count %d > %d",
9573 mChannelCount, FCC_LIMIT);
Mikhail Naganovce9f2652018-07-16 11:09:24 -07009574 } else {
Andy Hung936845a2021-06-08 00:09:06 -07009575 // Can have more that FCC_LIMIT channels in encoded streams.
Mikhail Naganovce9f2652018-07-16 11:09:24 -07009576 ALOGI("HAL format %#x is not linear pcm", mFormat);
9577 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009578 result = mInput->stream->getFrameSize(&mFrameSize);
9579 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
Hayden Gomes1a89ab32020-06-12 11:05:47 -07009580 LOG_ALWAYS_FATAL_IF(mFrameSize <= 0, "Error frame size was %zu but must be greater than zero",
9581 mFrameSize);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009582 result = mInput->stream->getBufferSize(&mBufferSize);
9583 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
Glenn Kasten548efc92012-11-29 08:48:51 -08009584 mFrameCount = mBufferSize / mFrameSize;
Hayden Gomes1a89ab32020-06-12 11:05:47 -07009585 ALOGV("%p RecordThread params: mChannelCount=%u, mFormat=%#x, mFrameSize=%zu, "
9586 "mBufferSize=%zu, mFrameCount=%zu",
9587 this, mChannelCount, mFormat, mFrameSize, mBufferSize, mFrameCount);
Glenn Kasten49d00ad2014-07-21 11:22:03 -07009588
Eric Laurentec376dc2021-04-08 20:41:22 +02009589 // mRsmpInFrames must be 0 before calling resizeInputBuffer_l for the first time
9590 mRsmpInFrames = 0;
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009591 resizeInputBuffer_l(0 /*maxSharedAudioHistoryMs*/);
Eric Laurent81784c32012-11-19 14:55:58 -08009592
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08009593 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
9594 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Andy Hungea840382020-05-05 21:50:17 -07009595
9596 audio_input_flags_t flags = mInput->flags;
9597 mediametrics::LogItem item(mThreadMetrics.getMetricsId());
9598 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
Andy Hung25a80ac2023-07-19 12:47:35 -07009599 .set(AMEDIAMETRICS_PROP_ENCODING, IAfThreadBase::formatToString(mFormat).c_str())
Andy Hungea840382020-05-05 21:50:17 -07009600 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
9601 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
9602 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
9603 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
9604 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mFrameCount)
9605 .record();
Eric Laurent81784c32012-11-19 14:55:58 -08009606}
9607
Andy Hungee58e4a2023-07-07 13:47:37 -07009608uint32_t RecordThread::getInputFramesLost() const
Eric Laurent81784c32012-11-19 14:55:58 -08009609{
Andy Hung972bec12023-08-31 16:13:39 -07009610 audio_utils::lock_guard _l(mutex());
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009611 uint32_t result;
9612 if (initCheck() == NO_ERROR && mInput->stream->getInputFramesLost(&result) == OK) {
9613 return result;
Eric Laurent81784c32012-11-19 14:55:58 -08009614 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009615 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08009616}
9617
Andy Hungee58e4a2023-07-07 13:47:37 -07009618KeyedVector<audio_session_t, bool> RecordThread::sessionIds() const
Eric Laurent81784c32012-11-19 14:55:58 -08009619{
Glenn Kastend848eb42016-03-08 13:42:11 -08009620 KeyedVector<audio_session_t, bool> ids;
Andy Hung972bec12023-08-31 16:13:39 -07009621 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08009622 for (size_t j = 0; j < mTracks.size(); ++j) {
Andy Hung8d31fd22023-06-26 19:20:57 -07009623 sp<IAfRecordTrack> track = mTracks[j];
Glenn Kastend848eb42016-03-08 13:42:11 -08009624 audio_session_t sessionId = track->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08009625 if (ids.indexOfKey(sessionId) < 0) {
9626 ids.add(sessionId, true);
9627 }
9628 }
9629 return ids;
9630}
9631
Andy Hungee58e4a2023-07-07 13:47:37 -07009632AudioStreamIn* RecordThread::clearInput()
Eric Laurent81784c32012-11-19 14:55:58 -08009633{
Andy Hung972bec12023-08-31 16:13:39 -07009634 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08009635 AudioStreamIn *input = mInput;
9636 mInput = NULL;
Mikhail Naganov49aecf02023-09-08 15:14:34 -07009637 mInputSource.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08009638 return input;
9639}
9640
Andy Hungc5007f82023-08-29 14:26:09 -07009641// this method must always be called either with ThreadBase mutex() held or inside the thread loop
Andy Hungee58e4a2023-07-07 13:47:37 -07009642sp<StreamHalInterface> RecordThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08009643{
9644 if (mInput == NULL) {
9645 return NULL;
9646 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009647 return mInput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08009648}
9649
Andy Hungee58e4a2023-07-07 13:47:37 -07009650status_t RecordThread::addEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08009651{
Eric Laurent81784c32012-11-19 14:55:58 -08009652 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurentaaa44472014-09-12 17:41:50 -07009653 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08009654 chain->setInBuffer(NULL);
9655 chain->setOutBuffer(NULL);
9656
9657 checkSuspendOnAddEffectChain_l(chain);
9658
Eric Laurent1b928682014-10-02 19:41:47 -07009659 // make sure enabled pre processing effects state is communicated to the HAL as we
9660 // just moved them to a new input stream.
9661 chain->syncHalEffectsState();
9662
Eric Laurent81784c32012-11-19 14:55:58 -08009663 mEffectChains.add(chain);
9664
9665 return NO_ERROR;
9666}
9667
Andy Hungee58e4a2023-07-07 13:47:37 -07009668size_t RecordThread::removeEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08009669{
9670 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
Eric Laurentb20cf7d2019-04-05 19:37:34 -07009671
9672 for (size_t i = 0; i < mEffectChains.size(); i++) {
9673 if (chain == mEffectChains[i]) {
9674 mEffectChains.removeAt(i);
9675 break;
9676 }
Eric Laurent81784c32012-11-19 14:55:58 -08009677 }
Eric Laurentb20cf7d2019-04-05 19:37:34 -07009678 return mEffectChains.size();
Eric Laurent81784c32012-11-19 14:55:58 -08009679}
9680
Andy Hungee58e4a2023-07-07 13:47:37 -07009681status_t RecordThread::createAudioPatch_l(const struct audio_patch* patch,
Eric Laurent1c333e22014-05-20 10:48:17 -07009682 audio_patch_handle_t *handle)
9683{
9684 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07009685
9686 // store new device and send to effects
jiabinc52b1ff2019-10-31 17:20:42 -07009687 mInDeviceTypeAddr.mType = patch->sources[0].ext.device.type;
jiabin0a488932020-08-07 17:32:40 -07009688 mInDeviceTypeAddr.setAddress(patch->sources[0].ext.device.address);
François Gaffie0c280aa2018-07-25 10:02:15 +02009689 audio_port_handle_t deviceId = patch->sources[0].id;
Eric Laurent054d9d32015-04-24 08:48:48 -07009690 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08009691 mEffectChains[i]->setInputDevice_l(inDeviceTypeAddr());
Eric Laurent054d9d32015-04-24 08:48:48 -07009692 }
9693
Eric Laurentd8365c52017-07-16 15:27:05 -07009694 checkBtNrec_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07009695
9696 // store new source and send to effects
9697 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
9698 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent1c333e22014-05-20 10:48:17 -07009699 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent054d9d32015-04-24 08:48:48 -07009700 mEffectChains[i]->setAudioSource_l(mAudioSource);
Eric Laurent1c333e22014-05-20 10:48:17 -07009701 }
Eric Laurent054d9d32015-04-24 08:48:48 -07009702 }
Eric Laurent1c333e22014-05-20 10:48:17 -07009703
Mikhail Naganov9ee05402016-10-13 15:58:17 -07009704 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07009705 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
9706 status = hwDevice->createAudioPatch(patch->num_sources,
9707 patch->sources,
9708 patch->num_sinks,
9709 patch->sinks,
9710 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07009711 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08009712 status = mInput->stream->legacyCreateAudioPatch(patch->sources[0],
9713 patch->sinks[0].ext.mix.usecase.source,
9714 patch->sources[0].ext.device.type);
Eric Laurent054d9d32015-04-24 08:48:48 -07009715 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07009716 }
Eric Laurent054d9d32015-04-24 08:48:48 -07009717
jiabinc52b1ff2019-10-31 17:20:42 -07009718 if ((mPatch.num_sources == 0) || (mPatch.sources[0].id != deviceId)) {
Eric Laurente8726fe2015-06-26 09:39:24 -07009719 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
jiabinc52b1ff2019-10-31 17:20:42 -07009720 mPatch = *patch;
Eric Laurente8726fe2015-06-26 09:39:24 -07009721 }
Eric Laurent296fb132015-05-01 11:38:42 -07009722
Andy Hungc2b11cb2020-04-22 09:04:01 -07009723 const std::string pathSourcesAsString = patchSourcesToString(patch);
Andy Hungcf10d742020-04-28 15:38:24 -07009724 mThreadMetrics.logEndInterval();
Andy Hungea840382020-05-05 21:50:17 -07009725 mThreadMetrics.logCreatePatch(pathSourcesAsString, /* outDevices */ {});
Andy Hungcf10d742020-04-28 15:38:24 -07009726 mThreadMetrics.logBeginInterval();
Andy Hungc2b11cb2020-04-22 09:04:01 -07009727 // also dispatch to active AudioRecords
9728 for (const auto &track : mActiveTracks) {
9729 track->logEndInterval();
9730 track->logBeginInterval(pathSourcesAsString);
9731 }
Eric Laurentdda206a2022-07-08 17:28:35 +02009732 // Force meteadata update after a route change
9733 mActiveTracks.setHasChanged();
9734
Eric Laurent1c333e22014-05-20 10:48:17 -07009735 return status;
9736}
9737
Andy Hungee58e4a2023-07-07 13:47:37 -07009738status_t RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
Eric Laurent1c333e22014-05-20 10:48:17 -07009739{
9740 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07009741
jiabinc52b1ff2019-10-31 17:20:42 -07009742 mPatch = audio_patch{};
9743 mInDeviceTypeAddr.reset();
Eric Laurent054d9d32015-04-24 08:48:48 -07009744
Mikhail Naganov9ee05402016-10-13 15:58:17 -07009745 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07009746 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
9747 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07009748 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08009749 status = mInput->stream->legacyReleaseAudioPatch();
Eric Laurent1c333e22014-05-20 10:48:17 -07009750 }
Eric Laurentdda206a2022-07-08 17:28:35 +02009751 // Force meteadata update after a route change
9752 mActiveTracks.setHasChanged();
9753
Eric Laurent1c333e22014-05-20 10:48:17 -07009754 return status;
9755}
9756
Andy Hungee58e4a2023-07-07 13:47:37 -07009757void RecordThread::updateOutDevices(const DeviceDescriptorBaseVector& outDevices)
jiabinc52b1ff2019-10-31 17:20:42 -07009758{
Andy Hung972bec12023-08-31 16:13:39 -07009759 audio_utils::lock_guard _l(mutex());
jiabinc52b1ff2019-10-31 17:20:42 -07009760 mOutDevices = outDevices;
9761 mOutDeviceTypeAddrs = deviceTypeAddrsFromDescriptors(mOutDevices);
9762 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08009763 mEffectChains[i]->setDevices_l(outDeviceTypeAddrs());
jiabinc52b1ff2019-10-31 17:20:42 -07009764 }
9765}
9766
Andy Hungee58e4a2023-07-07 13:47:37 -07009767int32_t RecordThread::getOldestFront_l()
Eric Laurentec376dc2021-04-08 20:41:22 +02009768{
9769 if (mTracks.size() == 0) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009770 return mRsmpInRear;
Eric Laurentec376dc2021-04-08 20:41:22 +02009771 }
Eric Laurent2407ce32021-04-26 14:56:03 +02009772 int32_t oldestFront = mRsmpInRear;
9773 int32_t maxFilled = 0;
Eric Laurentec376dc2021-04-08 20:41:22 +02009774 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07009775 int32_t front = mTracks[i]->resamplerBufferProvider()->getFront();
Eric Laurent2407ce32021-04-26 14:56:03 +02009776 int32_t filled;
Eric Laurent92d0a322021-07-16 15:32:33 +02009777 (void)__builtin_sub_overflow(mRsmpInRear, front, &filled);
Eric Laurent2407ce32021-04-26 14:56:03 +02009778 if (filled > maxFilled) {
9779 oldestFront = front;
9780 maxFilled = filled;
9781 }
Eric Laurentec376dc2021-04-08 20:41:22 +02009782 }
Andy Hung920f6572022-10-06 12:09:49 -07009783 if (maxFilled > static_cast<signed>(mRsmpInFrames)) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009784 (void)__builtin_sub_overflow(mRsmpInRear, mRsmpInFrames, &oldestFront);
9785 }
Eric Laurent2407ce32021-04-26 14:56:03 +02009786 return oldestFront;
Eric Laurentec376dc2021-04-08 20:41:22 +02009787}
9788
Andy Hungee58e4a2023-07-07 13:47:37 -07009789void RecordThread::updateFronts_l(int32_t offset)
Eric Laurentec376dc2021-04-08 20:41:22 +02009790{
9791 if (offset == 0) {
9792 return;
9793 }
9794 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07009795 int32_t front = mTracks[i]->resamplerBufferProvider()->getFront();
Eric Laurentec376dc2021-04-08 20:41:22 +02009796 front = audio_utils::safe_sub_overflow(front, offset);
Andy Hung8d31fd22023-06-26 19:20:57 -07009797 mTracks[i]->resamplerBufferProvider()->setFront(front);
Eric Laurentec376dc2021-04-08 20:41:22 +02009798 }
9799}
9800
Andy Hungee58e4a2023-07-07 13:47:37 -07009801void RecordThread::resizeInputBuffer_l(int32_t maxSharedAudioHistoryMs)
Eric Laurentec376dc2021-04-08 20:41:22 +02009802{
9803 // This is the formula for calculating the temporary buffer size.
9804 // With 7 HAL buffers, we can guarantee ability to down-sample the input by ratio of 6:1 to
9805 // 1 full output buffer, regardless of the alignment of the available input.
9806 // The value is somewhat arbitrary, and could probably be even larger.
9807 // A larger value should allow more old data to be read after a track calls start(),
9808 // without increasing latency.
9809 //
9810 // Note this is independent of the maximum downsampling ratio permitted for capture.
9811 size_t minRsmpInFrames = mFrameCount * 7;
9812
9813 // maxSharedAudioHistoryMs != 0 indicates a request to possibly make some part of the audio
9814 // capture history available to another client using the same session ID:
9815 // dimension the resampler input buffer accordingly.
9816
9817 // Get oldest client read position: getOldestFront_l() must be called before altering
9818 // mRsmpInRear, or mRsmpInFrames
9819 int32_t previousFront = getOldestFront_l();
9820 size_t previousRsmpInFramesP2 = mRsmpInFramesP2;
9821 int32_t previousRear = mRsmpInRear;
9822 mRsmpInRear = 0;
9823
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009824 ALOG_ASSERT(maxSharedAudioHistoryMs >= 0
Andy Hungee58e4a2023-07-07 13:47:37 -07009825 && maxSharedAudioHistoryMs <= kMaxSharedAudioHistoryMs,
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009826 "resizeInputBuffer_l() called with invalid max shared history %d",
9827 maxSharedAudioHistoryMs);
Eric Laurentec376dc2021-04-08 20:41:22 +02009828 if (maxSharedAudioHistoryMs != 0) {
9829 // resizeInputBuffer_l should never be called with a non zero shared history if the
9830 // buffer was not already allocated
9831 ALOG_ASSERT(mRsmpInBuffer != nullptr && mRsmpInFrames != 0,
9832 "resizeInputBuffer_l() called with shared history and unallocated buffer");
9833 size_t rsmpInFrames = (size_t)maxSharedAudioHistoryMs * mSampleRate / 1000;
9834 // never reduce resampler input buffer size
Eric Laurent92d0a322021-07-16 15:32:33 +02009835 if (rsmpInFrames <= mRsmpInFrames) {
Eric Laurentec376dc2021-04-08 20:41:22 +02009836 return;
9837 }
9838 mRsmpInFrames = rsmpInFrames;
9839 }
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009840 mMaxSharedAudioHistoryMs = maxSharedAudioHistoryMs;
Eric Laurentec376dc2021-04-08 20:41:22 +02009841 // Note: mRsmpInFrames is 0 when called with maxSharedAudioHistoryMs equals to 0 so it is always
9842 // initialized
9843 if (mRsmpInFrames < minRsmpInFrames) {
9844 mRsmpInFrames = minRsmpInFrames;
9845 }
9846 mRsmpInFramesP2 = roundup(mRsmpInFrames);
9847
9848 // TODO optimize audio capture buffer sizes ...
9849 // Here we calculate the size of the sliding buffer used as a source
9850 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
9851 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
9852 // be better to have it derived from the pipe depth in the long term.
9853 // The current value is higher than necessary. However it should not add to latency.
9854
9855 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
9856 mRsmpInFramesOA = mRsmpInFramesP2 + mFrameCount - 1;
9857
9858 void *rsmpInBuffer;
9859 (void)posix_memalign(&rsmpInBuffer, 32, mRsmpInFramesOA * mFrameSize);
9860 // if posix_memalign fails, will segv here.
9861 memset(rsmpInBuffer, 0, mRsmpInFramesOA * mFrameSize);
9862
9863 // Copy audio history if any from old buffer before freeing it
9864 if (previousRear != 0) {
9865 ALOG_ASSERT(mRsmpInBuffer != nullptr,
9866 "resizeInputBuffer_l() called with null buffer but frames already read from HAL");
9867
9868 ssize_t unread = audio_utils::safe_sub_overflow(previousRear, previousFront);
9869 previousFront &= previousRsmpInFramesP2 - 1;
9870 size_t part1 = previousRsmpInFramesP2 - previousFront;
9871 if (part1 > (size_t) unread) {
9872 part1 = unread;
9873 }
9874 if (part1 != 0) {
9875 memcpy(rsmpInBuffer, (const uint8_t*)mRsmpInBuffer + previousFront * mFrameSize,
9876 part1 * mFrameSize);
9877 mRsmpInRear = part1;
9878 part1 = unread - part1;
9879 if (part1 != 0) {
9880 memcpy((uint8_t*)rsmpInBuffer + mRsmpInRear * mFrameSize,
9881 (const uint8_t*)mRsmpInBuffer, part1 * mFrameSize);
9882 mRsmpInRear += part1;
9883 }
9884 }
9885 // Update front for all clients according to new rear
9886 updateFronts_l(audio_utils::safe_sub_overflow(previousRear, mRsmpInRear));
9887 } else {
9888 mRsmpInRear = 0;
9889 }
9890 free(mRsmpInBuffer);
9891 mRsmpInBuffer = rsmpInBuffer;
9892}
9893
Andy Hungee58e4a2023-07-07 13:47:37 -07009894void RecordThread::addPatchTrack(const sp<IAfPatchRecord>& record)
Eric Laurent83b88082014-06-20 18:31:16 -07009895{
Andy Hung972bec12023-08-31 16:13:39 -07009896 audio_utils::lock_guard _l(mutex());
Eric Laurent83b88082014-06-20 18:31:16 -07009897 mTracks.add(record);
Mikhail Naganov2534b382019-09-25 13:05:02 -07009898 if (record->getSource()) {
9899 mSource = record->getSource();
9900 }
Eric Laurent83b88082014-06-20 18:31:16 -07009901}
9902
Andy Hungee58e4a2023-07-07 13:47:37 -07009903void RecordThread::deletePatchTrack(const sp<IAfPatchRecord>& record)
Eric Laurent83b88082014-06-20 18:31:16 -07009904{
Andy Hung972bec12023-08-31 16:13:39 -07009905 audio_utils::lock_guard _l(mutex());
Mikhail Naganov2534b382019-09-25 13:05:02 -07009906 if (mSource == record->getSource()) {
9907 mSource = mInput;
9908 }
Eric Laurent83b88082014-06-20 18:31:16 -07009909 destroyTrack_l(record);
9910}
9911
Andy Hungee58e4a2023-07-07 13:47:37 -07009912void RecordThread::toAudioPortConfig(struct audio_port_config* config)
Eric Laurent83b88082014-06-20 18:31:16 -07009913{
Mikhail Naganovdc769682018-05-04 15:34:08 -07009914 ThreadBase::toAudioPortConfig(config);
Eric Laurent83b88082014-06-20 18:31:16 -07009915 config->role = AUDIO_PORT_ROLE_SINK;
9916 config->ext.mix.hw_module = mInput->audioHwDev->handle();
9917 config->ext.mix.usecase.source = mAudioSource;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07009918 if (mInput && mInput->flags != AUDIO_INPUT_FLAG_NONE) {
9919 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
9920 config->flags.input = mInput->flags;
9921 }
Eric Laurent83b88082014-06-20 18:31:16 -07009922}
Eric Laurent1c333e22014-05-20 10:48:17 -07009923
Eric Laurent6acd1d42017-01-04 14:23:29 -08009924// ----------------------------------------------------------------------------
9925// Mmap
9926// ----------------------------------------------------------------------------
9927
Andy Hung7aa7d102023-07-07 15:58:48 -07009928// Mmap stream control interface implementation. Each MmapThreadHandle controls one
9929// MmapPlaybackThread or MmapCaptureThread instance.
9930class MmapThreadHandle : public MmapStreamInterface {
9931public:
9932 explicit MmapThreadHandle(const sp<IAfMmapThread>& thread);
9933 ~MmapThreadHandle() override;
9934
9935 // MmapStreamInterface virtuals
9936 status_t createMmapBuffer(int32_t minSizeFrames,
9937 struct audio_mmap_buffer_info* info) final;
9938 status_t getMmapPosition(struct audio_mmap_position* position) final;
9939 status_t getExternalPosition(uint64_t* position, int64_t* timeNanos) final;
9940 status_t start(const AudioClient& client,
9941 const audio_attributes_t* attr, audio_port_handle_t* handle) final;
9942 status_t stop(audio_port_handle_t handle) final;
9943 status_t standby() final;
9944 status_t reportData(const void* buffer, size_t frameCount) final;
9945private:
9946 const sp<IAfMmapThread> mThread;
9947};
9948
9949/* static */
9950sp<MmapStreamInterface> IAfMmapThread::createMmapStreamInterfaceAdapter(
9951 const sp<IAfMmapThread>& mmapThread) {
9952 return sp<MmapThreadHandle>::make(mmapThread);
9953}
9954
9955MmapThreadHandle::MmapThreadHandle(const sp<IAfMmapThread>& thread)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009956 : mThread(thread)
9957{
Phil Burk9fabbf82017-08-03 12:02:00 -07009958 assert(thread != 0); // thread must start non-null and stay non-null
Eric Laurent6acd1d42017-01-04 14:23:29 -08009959}
9960
Andy Hung7aa7d102023-07-07 15:58:48 -07009961// MmapStreamInterface could be directly implemented by MmapThread excepting this
9962// special handling on adapter dtor.
9963MmapThreadHandle::~MmapThreadHandle()
Eric Laurent6acd1d42017-01-04 14:23:29 -08009964{
Phil Burk9fabbf82017-08-03 12:02:00 -07009965 mThread->disconnect();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009966}
9967
Andy Hung7aa7d102023-07-07 15:58:48 -07009968status_t MmapThreadHandle::createMmapBuffer(int32_t minSizeFrames,
Eric Laurent6acd1d42017-01-04 14:23:29 -08009969 struct audio_mmap_buffer_info *info)
9970{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009971 return mThread->createMmapBuffer(minSizeFrames, info);
9972}
9973
Andy Hung7aa7d102023-07-07 15:58:48 -07009974status_t MmapThreadHandle::getMmapPosition(struct audio_mmap_position* position)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009975{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009976 return mThread->getMmapPosition(position);
9977}
9978
Andy Hung7aa7d102023-07-07 15:58:48 -07009979status_t MmapThreadHandle::getExternalPosition(uint64_t* position,
jiabinb7d8c5a2020-08-26 17:24:52 -07009980 int64_t *timeNanos) {
9981 return mThread->getExternalPosition(position, timeNanos);
9982}
9983
Andy Hung7aa7d102023-07-07 15:58:48 -07009984status_t MmapThreadHandle::start(const AudioClient& client,
jiabind1f1cb62020-03-24 11:57:57 -07009985 const audio_attributes_t *attr, audio_port_handle_t *handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009986{
jiabind1f1cb62020-03-24 11:57:57 -07009987 return mThread->start(client, attr, handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009988}
9989
Andy Hung7aa7d102023-07-07 15:58:48 -07009990status_t MmapThreadHandle::stop(audio_port_handle_t handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009991{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009992 return mThread->stop(handle);
9993}
9994
Andy Hung7aa7d102023-07-07 15:58:48 -07009995status_t MmapThreadHandle::standby()
Eric Laurent18b57012017-02-13 16:23:52 -08009996{
Eric Laurent18b57012017-02-13 16:23:52 -08009997 return mThread->standby();
9998}
9999
Andy Hung7aa7d102023-07-07 15:58:48 -070010000status_t MmapThreadHandle::reportData(const void* buffer, size_t frameCount)
10001{
jiabinfc791ee2023-02-15 19:43:40 +000010002 return mThread->reportData(buffer, frameCount);
10003}
10004
Eric Laurent6acd1d42017-01-04 14:23:29 -080010005
Andy Hungee58e4a2023-07-07 13:47:37 -070010006MmapThread::MmapThread(
Andy Hung583043b2023-07-17 17:05:00 -070010007 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
Andy Hung920f6572022-10-06 12:09:49 -070010008 AudioHwDevice *hwDev, const sp<StreamHalInterface>& stream, bool systemReady, bool isOut)
Andy Hung583043b2023-07-17 17:05:00 -070010009 : ThreadBase(afThreadCallback, id, (isOut ? MMAP_PLAYBACK : MMAP_CAPTURE), systemReady, isOut),
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010010 mSessionId(AUDIO_SESSION_NONE),
François Gaffie0c280aa2018-07-25 10:02:15 +020010011 mPortId(AUDIO_PORT_HANDLE_NONE),
Andy Hung2c6c3bb2017-06-16 14:01:45 -070010012 mHalStream(stream), mHalDevice(hwDev->hwDevice()), mAudioHwDev(hwDev),
Eric Laurent67f97292018-04-20 18:05:41 -070010013 mActiveTracks(&this->mLocalLog),
10014 mHalVolFloat(-1.0f), // Initialize to illegal value so it always gets set properly later.
10015 mNoCallbackWarningCount(0)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010016{
Eric Laurent18b57012017-02-13 16:23:52 -080010017 mStandby = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010018 readHalParameters_l();
10019}
10020
Andy Hungee58e4a2023-07-07 13:47:37 -070010021void MmapThread::onFirstRef()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010022{
10023 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
10024}
10025
Andy Hungee58e4a2023-07-07 13:47:37 -070010026void MmapThread::disconnect()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010027{
Andy Hung8d31fd22023-06-26 19:20:57 -070010028 ActiveTracks<IAfMmapTrack> activeTracks;
Andy Hung3f49ebb2023-09-19 14:48:41 -070010029 audio_port_handle_t localPortId;
Eric Laurent331679c2018-04-16 17:03:16 -070010030 {
Andy Hung972bec12023-08-31 16:13:39 -070010031 audio_utils::lock_guard _l(mutex());
Andy Hung8d31fd22023-06-26 19:20:57 -070010032 for (const sp<IAfMmapTrack>& t : mActiveTracks) {
Eric Laurent331679c2018-04-16 17:03:16 -070010033 activeTracks.add(t);
10034 }
Andy Hung3f49ebb2023-09-19 14:48:41 -070010035 localPortId = mPortId;
Eric Laurent331679c2018-04-16 17:03:16 -070010036 }
Andy Hung8d31fd22023-06-26 19:20:57 -070010037 for (const sp<IAfMmapTrack>& t : activeTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010038 stop(t->portId());
10039 }
Phil Burk9fabbf82017-08-03 12:02:00 -070010040 // This will decrement references and may cause the destruction of this thread.
Eric Laurent6acd1d42017-01-04 14:23:29 -080010041 if (isOutput()) {
Andy Hung3f49ebb2023-09-19 14:48:41 -070010042 AudioSystem::releaseOutput(localPortId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010043 } else {
Andy Hung3f49ebb2023-09-19 14:48:41 -070010044 AudioSystem::releaseInput(localPortId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010045 }
10046}
10047
10048
Andy Hung8d672e02023-09-15 18:19:28 -070010049void MmapThread::configure_l(const audio_attributes_t* attr,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010050 audio_stream_type_t streamType __unused,
10051 audio_session_t sessionId,
10052 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010053 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010054 audio_port_handle_t portId)
10055{
10056 mAttr = *attr;
10057 mSessionId = sessionId;
10058 mCallback = callback;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010059 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010060 mPortId = portId;
10061}
10062
Andy Hungee58e4a2023-07-07 13:47:37 -070010063status_t MmapThread::createMmapBuffer(int32_t minSizeFrames,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010064 struct audio_mmap_buffer_info *info)
10065{
Andy Hung3f49ebb2023-09-19 14:48:41 -070010066 audio_utils::lock_guard l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010067 if (mHalStream == 0) {
10068 return NO_INIT;
10069 }
Eric Laurent18b57012017-02-13 16:23:52 -080010070 mStandby = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010071 return mHalStream->createMmapBuffer(minSizeFrames, info);
10072}
10073
Andy Hungee58e4a2023-07-07 13:47:37 -070010074status_t MmapThread::getMmapPosition(struct audio_mmap_position* position) const
Eric Laurent6acd1d42017-01-04 14:23:29 -080010075{
Andy Hung3f49ebb2023-09-19 14:48:41 -070010076 audio_utils::lock_guard l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010077 if (mHalStream == 0) {
10078 return NO_INIT;
10079 }
10080 return mHalStream->getMmapPosition(position);
10081}
10082
Andy Hungee58e4a2023-07-07 13:47:37 -070010083status_t MmapThread::exitStandby_l()
Eric Laurent331679c2018-04-16 17:03:16 -070010084{
Eric Laurentdda206a2022-07-08 17:28:35 +020010085 // The HAL must receive track metadata before starting the stream
10086 updateMetadata_l();
Eric Laurent331679c2018-04-16 17:03:16 -070010087 status_t ret = mHalStream->start();
10088 if (ret != NO_ERROR) {
10089 ALOGE("%s: error mHalStream->start() = %d for first track", __FUNCTION__, ret);
10090 return ret;
10091 }
Andy Hungcf10d742020-04-28 15:38:24 -070010092 if (mStandby) {
10093 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -070010094 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -070010095 mStandby = false;
10096 }
Eric Laurent331679c2018-04-16 17:03:16 -070010097 return NO_ERROR;
10098}
10099
Andy Hungee58e4a2023-07-07 13:47:37 -070010100status_t MmapThread::start(const AudioClient& client,
jiabind1f1cb62020-03-24 11:57:57 -070010101 const audio_attributes_t *attr,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010102 audio_port_handle_t *handle)
10103{
Andy Hung3f49ebb2023-09-19 14:48:41 -070010104 audio_utils::lock_guard l(mutex());
Eric Laurenta54f1282017-07-01 19:39:32 -070010105 ALOGV("%s clientUid %d mStandby %d mPortId %d *handle %d", __FUNCTION__,
Svet Ganov33761132021-05-13 22:51:08 +000010106 client.attributionSource.uid, mStandby, mPortId, *handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010107 if (mHalStream == 0) {
10108 return NO_INIT;
10109 }
10110
10111 status_t ret;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010112
Eric Laurentdda206a2022-07-08 17:28:35 +020010113 // For the first track, reuse portId and session allocated when the stream was opened.
Eric Laurenta54f1282017-07-01 19:39:32 -070010114 if (*handle == mPortId) {
Andy Hung3f49ebb2023-09-19 14:48:41 -070010115 acquireWakeLock_l();
Eric Laurentdda206a2022-07-08 17:28:35 +020010116 return NO_ERROR;
Eric Laurenta54f1282017-07-01 19:39:32 -070010117 }
10118
10119 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
10120
10121 audio_io_handle_t io = mId;
Andy Hung6cd79802023-07-19 16:56:19 -070010122 const AttributionSourceState adjAttributionSource = afutils::checkAttributionSourcePackage(
Atneya Nairf59db5c2023-05-10 21:37:41 -070010123 client.attributionSource);
10124
Andy Hung3f49ebb2023-09-19 14:48:41 -070010125 const auto localSessionId = mSessionId;
10126 auto localAttr = mAttr;
Eric Laurenta54f1282017-07-01 19:39:32 -070010127 if (isOutput()) {
10128 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
10129 config.sample_rate = mSampleRate;
10130 config.channel_mask = mChannelMask;
10131 config.format = mFormat;
Andy Hung3f49ebb2023-09-19 14:48:41 -070010132 audio_stream_type_t stream = streamType_l();
Eric Laurenta54f1282017-07-01 19:39:32 -070010133 audio_output_flags_t flags =
10134 (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010135 audio_port_handle_t deviceId = mDeviceId;
Kevin Rocard153f92d2018-12-18 18:33:28 -080010136 std::vector<audio_io_handle_t> secondaryOutputs;
Eric Laurentb0a7bc92022-04-05 15:06:08 +020010137 bool isSpatialized;
jiabinc658e452022-10-21 20:52:21 +000010138 bool isBitPerfect;
Andy Hung3f49ebb2023-09-19 14:48:41 -070010139 mutex().unlock();
10140 ret = AudioSystem::getOutputForAttr(&localAttr, &io,
10141 localSessionId,
Eric Laurenta54f1282017-07-01 19:39:32 -070010142 &stream,
Atneya Nairf59db5c2023-05-10 21:37:41 -070010143 adjAttributionSource,
Eric Laurenta54f1282017-07-01 19:39:32 -070010144 &config,
10145 flags,
10146 &deviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -080010147 &portId,
Eric Laurentb0a7bc92022-04-05 15:06:08 +020010148 &secondaryOutputs,
jiabinc658e452022-10-21 20:52:21 +000010149 &isSpatialized,
10150 &isBitPerfect);
Andy Hung3f49ebb2023-09-19 14:48:41 -070010151 mutex().lock();
10152 mAttr = localAttr;
Kevin Rocard153f92d2018-12-18 18:33:28 -080010153 ALOGD_IF(!secondaryOutputs.empty(),
10154 "MmapThread::start does not support secondary outputs, ignoring them");
Eric Laurent6acd1d42017-01-04 14:23:29 -080010155 } else {
Eric Laurenta54f1282017-07-01 19:39:32 -070010156 audio_config_base_t config;
10157 config.sample_rate = mSampleRate;
10158 config.channel_mask = mChannelMask;
10159 config.format = mFormat;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010160 audio_port_handle_t deviceId = mDeviceId;
Andy Hung3f49ebb2023-09-19 14:48:41 -070010161 mutex().unlock();
10162 ret = AudioSystem::getInputForAttr(&localAttr, &io,
Mikhail Naganov2996f672019-04-18 12:29:59 -070010163 RECORD_RIID_INVALID,
Andy Hung3f49ebb2023-09-19 14:48:41 -070010164 localSessionId,
Atneya Nairf59db5c2023-05-10 21:37:41 -070010165 adjAttributionSource,
Eric Laurenta54f1282017-07-01 19:39:32 -070010166 &config,
10167 AUDIO_INPUT_FLAG_MMAP_NOIRQ,
10168 &deviceId,
10169 &portId);
Andy Hung3f49ebb2023-09-19 14:48:41 -070010170 mutex().lock();
10171 // localAttr is const for getInputForAttr.
Eric Laurenta54f1282017-07-01 19:39:32 -070010172 }
10173 // APM should not chose a different input or output stream for the same set of attributes
10174 // and audo configuration
10175 if (ret != NO_ERROR || io != mId) {
10176 ALOGE("%s: error getting output or input from APM (error %d, io %d expected io %d)",
10177 __FUNCTION__, ret, io, mId);
10178 return BAD_VALUE;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010179 }
10180
10181 if (isOutput()) {
Andy Hung3f49ebb2023-09-19 14:48:41 -070010182 mutex().unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -070010183 ret = AudioSystem::startOutput(portId);
Andy Hung3f49ebb2023-09-19 14:48:41 -070010184 mutex().lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010185 } else {
jiabin09609032022-06-15 19:26:01 +000010186 {
10187 // Add the track record before starting input so that the silent status for the
10188 // client can be cached.
jiabin09609032022-06-15 19:26:01 +000010189 setClientSilencedState_l(portId, false /*silenced*/);
10190 }
Andy Hung3f49ebb2023-09-19 14:48:41 -070010191 mutex().unlock();
Eric Laurent4eb58f12018-12-07 16:41:02 -080010192 ret = AudioSystem::startInput(portId);
Andy Hung3f49ebb2023-09-19 14:48:41 -070010193 mutex().lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010194 }
10195
10196 // abort if start is rejected by audio policy manager
10197 if (ret != NO_ERROR) {
Phil Burk7f6b40d2017-02-09 13:18:38 -080010198 ALOGE("%s: error start rejected by AudioPolicyManager = %d", __FUNCTION__, ret);
Eric Tan39ec8d62018-07-24 09:49:29 -070010199 if (!mActiveTracks.isEmpty()) {
Andy Hungc5007f82023-08-29 14:26:09 -070010200 mutex().unlock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010201 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -070010202 AudioSystem::releaseOutput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010203 } else {
Eric Laurentfee19762018-01-29 18:44:13 -080010204 AudioSystem::releaseInput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010205 }
Andy Hungc5007f82023-08-29 14:26:09 -070010206 mutex().lock();
Eric Laurent18b57012017-02-13 16:23:52 -080010207 } else {
10208 mHalStream->stop();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010209 }
jiabin09609032022-06-15 19:26:01 +000010210 eraseClientSilencedState_l(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010211 return PERMISSION_DENIED;
10212 }
10213
Kevin Rocard1f564ac2018-03-29 13:53:10 -070010214 // Given that MmapThread::mAttr is mutable, should a MmapTrack have attributes ?
Andy Hung8d31fd22023-06-26 19:20:57 -070010215 sp<IAfMmapTrack> track = IAfMmapTrack::create(
10216 this, attr == nullptr ? mAttr : *attr, mSampleRate, mFormat,
Svet Ganov33761132021-05-13 22:51:08 +000010217 mChannelMask, mSessionId, isOutput(),
10218 client.attributionSource,
Philip P. Moltmannbda45752020-07-17 16:41:18 -070010219 IPCThreadState::self()->getCallingPid(), portId);
jiabin09609032022-06-15 19:26:01 +000010220 if (!isOutput()) {
10221 track->setSilenced_l(isClientSilenced_l(portId));
10222 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010223
Eric Laurent4eb58f12018-12-07 16:41:02 -080010224 if (isOutput()) {
10225 // force volume update when a new track is added
10226 mHalVolFloat = -1.0f;
10227 } else if (!track->isSilenced_l()) {
Andy Hung8d31fd22023-06-26 19:20:57 -070010228 for (const sp<IAfMmapTrack>& t : mActiveTracks) {
Andy Hung920f6572022-10-06 12:09:49 -070010229 if (t->isSilenced_l()
10230 && t->uid() != static_cast<uid_t>(client.attributionSource.uid)) {
Eric Laurent4eb58f12018-12-07 16:41:02 -080010231 t->invalidate();
Andy Hung920f6572022-10-06 12:09:49 -070010232 }
Eric Laurent4eb58f12018-12-07 16:41:02 -080010233 }
10234 }
10235
Eric Laurent6acd1d42017-01-04 14:23:29 -080010236 mActiveTracks.add(track);
Andy Hung116bc262023-06-20 18:56:17 -070010237 sp<IAfEffectChain> chain = getEffectChain_l(mSessionId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010238 if (chain != 0) {
Andy Hung3f49ebb2023-09-19 14:48:41 -070010239 chain->setStrategy(getStrategyForStream(streamType_l()));
Eric Laurent6acd1d42017-01-04 14:23:29 -080010240 chain->incTrackCnt();
10241 chain->incActiveTrackCnt();
10242 }
10243
Andy Hungc2b11cb2020-04-22 09:04:01 -070010244 track->logBeginInterval(patchSinksToString(&mPatch)); // log to MediaMetrics
Eric Laurent6acd1d42017-01-04 14:23:29 -080010245 *handle = portId;
Eric Laurentdda206a2022-07-08 17:28:35 +020010246
10247 if (mActiveTracks.size() == 1) {
10248 ret = exitStandby_l();
10249 }
10250
Eric Laurent6acd1d42017-01-04 14:23:29 -080010251 broadcast_l();
10252
Eric Laurentdda206a2022-07-08 17:28:35 +020010253 ALOGV("%s DONE status %d handle %d stream %p", __FUNCTION__, ret, *handle, mHalStream.get());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010254
Eric Laurentdda206a2022-07-08 17:28:35 +020010255 return ret;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010256}
10257
Andy Hungee58e4a2023-07-07 13:47:37 -070010258status_t MmapThread::stop(audio_port_handle_t handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010259{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010260 ALOGV("%s handle %d", __FUNCTION__, handle);
Andy Hung3f49ebb2023-09-19 14:48:41 -070010261 audio_utils::lock_guard l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010262
10263 if (mHalStream == 0) {
10264 return NO_INIT;
10265 }
10266
Eric Laurenta54f1282017-07-01 19:39:32 -070010267 if (handle == mPortId) {
Andy Hung3f49ebb2023-09-19 14:48:41 -070010268 releaseWakeLock_l();
Eric Laurenta54f1282017-07-01 19:39:32 -070010269 return NO_ERROR;
10270 }
10271
Andy Hung8d31fd22023-06-26 19:20:57 -070010272 sp<IAfMmapTrack> track;
10273 for (const sp<IAfMmapTrack>& t : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010274 if (handle == t->portId()) {
10275 track = t;
10276 break;
10277 }
10278 }
10279 if (track == 0) {
10280 return BAD_VALUE;
10281 }
10282
10283 mActiveTracks.remove(track);
jiabin09609032022-06-15 19:26:01 +000010284 eraseClientSilencedState_l(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010285
Andy Hungc5007f82023-08-29 14:26:09 -070010286 mutex().unlock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010287 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -070010288 AudioSystem::stopOutput(track->portId());
10289 AudioSystem::releaseOutput(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010290 } else {
Eric Laurentfee19762018-01-29 18:44:13 -080010291 AudioSystem::stopInput(track->portId());
10292 AudioSystem::releaseInput(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010293 }
Andy Hungc5007f82023-08-29 14:26:09 -070010294 mutex().lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010295
Andy Hung116bc262023-06-20 18:56:17 -070010296 sp<IAfEffectChain> chain = getEffectChain_l(track->sessionId());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010297 if (chain != 0) {
10298 chain->decActiveTrackCnt();
10299 chain->decTrackCnt();
10300 }
10301
Eric Laurentdda206a2022-07-08 17:28:35 +020010302 if (mActiveTracks.isEmpty()) {
10303 mHalStream->stop();
10304 }
10305
Eric Laurent6acd1d42017-01-04 14:23:29 -080010306 broadcast_l();
10307
Eric Laurent6acd1d42017-01-04 14:23:29 -080010308 return NO_ERROR;
10309}
10310
Andy Hungee58e4a2023-07-07 13:47:37 -070010311status_t MmapThread::standby()
Andy Hung3f49ebb2023-09-19 14:48:41 -070010312NO_THREAD_SAFETY_ANALYSIS // clang bug
Eric Laurent18b57012017-02-13 16:23:52 -080010313{
10314 ALOGV("%s", __FUNCTION__);
Atneya Nair97a73882023-10-30 20:26:21 -070010315 audio_utils::lock_guard l_{mutex()};
Eric Laurent18b57012017-02-13 16:23:52 -080010316
10317 if (mHalStream == 0) {
10318 return NO_INIT;
10319 }
Eric Tan39ec8d62018-07-24 09:49:29 -070010320 if (!mActiveTracks.isEmpty()) {
Eric Laurent18b57012017-02-13 16:23:52 -080010321 return INVALID_OPERATION;
10322 }
10323 mHalStream->standby();
Andy Hungcf10d742020-04-28 15:38:24 -070010324 if (!mStandby) {
10325 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -070010326 mThreadSnapshot.onEnd();
Andy Hungcf10d742020-04-28 15:38:24 -070010327 mStandby = true;
10328 }
Andy Hung3f49ebb2023-09-19 14:48:41 -070010329 releaseWakeLock_l();
Eric Laurent18b57012017-02-13 16:23:52 -080010330 return NO_ERROR;
10331}
10332
Andy Hungee58e4a2023-07-07 13:47:37 -070010333status_t MmapThread::reportData(const void* /*buffer*/, size_t /*frameCount*/) {
jiabinfc791ee2023-02-15 19:43:40 +000010334 // This is a stub implementation. The MmapPlaybackThread overrides this function.
10335 return INVALID_OPERATION;
10336}
10337
Andy Hungee58e4a2023-07-07 13:47:37 -070010338void MmapThread::readHalParameters_l()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010339{
10340 status_t result = mHalStream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
10341 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
10342 mFormat = mHALFormat;
10343 LOG_ALWAYS_FATAL_IF(!audio_is_linear_pcm(mFormat), "HAL format %#x is not linear pcm", mFormat);
10344 result = mHalStream->getFrameSize(&mFrameSize);
10345 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
Hayden Gomes1a89ab32020-06-12 11:05:47 -070010346 LOG_ALWAYS_FATAL_IF(mFrameSize <= 0, "Error frame size was %zu but must be greater than zero",
10347 mFrameSize);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010348 result = mHalStream->getBufferSize(&mBufferSize);
10349 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
10350 mFrameCount = mBufferSize / mFrameSize;
Andy Hungc2b11cb2020-04-22 09:04:01 -070010351
Andy Hungcf10d742020-04-28 15:38:24 -070010352 // TODO: make a readHalParameters call?
10353 mediametrics::LogItem item(mThreadMetrics.getMetricsId());
Andy Hungc2b11cb2020-04-22 09:04:01 -070010354 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
Andy Hung25a80ac2023-07-19 12:47:35 -070010355 .set(AMEDIAMETRICS_PROP_ENCODING, IAfThreadBase::formatToString(mFormat).c_str())
Andy Hungc2b11cb2020-04-22 09:04:01 -070010356 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
10357 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
10358 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
10359 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mFrameCount)
10360 /*
10361 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
10362 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELMASK,
10363 (int32_t)mHapticChannelMask)
10364 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELCOUNT,
10365 (int32_t)mHapticChannelCount)
10366 */
10367 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_ENCODING,
Andy Hung25a80ac2023-07-19 12:47:35 -070010368 IAfThreadBase::formatToString(mHALFormat).c_str())
Andy Hungc2b11cb2020-04-22 09:04:01 -070010369 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_FRAMECOUNT,
10370 (int32_t)mFrameCount) // sic - added HAL
10371 .record();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010372}
10373
Andy Hungee58e4a2023-07-07 13:47:37 -070010374bool MmapThread::threadLoop()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010375{
Andy Hungab65b182023-09-06 19:41:47 -070010376 {
10377 audio_utils::unique_lock _l(mutex());
10378 checkSilentMode_l();
10379 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010380
10381 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
10382
10383 while (!exitPending())
10384 {
Andy Hung116bc262023-06-20 18:56:17 -070010385 Vector<sp<IAfEffectChain>> effectChains;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010386
Andy Hung13850be2019-03-14 11:33:09 -070010387 { // under Thread lock
Andy Hungc5007f82023-08-29 14:26:09 -070010388 audio_utils::unique_lock _l(mutex());
Andy Hung13850be2019-03-14 11:33:09 -070010389
Eric Laurent6acd1d42017-01-04 14:23:29 -080010390 if (mSignalPending) {
10391 // A signal was raised while we were unlocked
10392 mSignalPending = false;
10393 } else {
10394 if (mConfigEvents.isEmpty()) {
10395 // we're about to wait, flush the binder command buffer
10396 IPCThreadState::self()->flushCommands();
10397
10398 if (exitPending()) {
10399 break;
10400 }
10401
Eric Laurent6acd1d42017-01-04 14:23:29 -080010402 // wait until we have something to do...
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +000010403 ALOGV("%s going to sleep", myName.c_str());
Andy Hungc5007f82023-08-29 14:26:09 -070010404 mWaitWorkCV.wait(_l);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +000010405 ALOGV("%s waking up", myName.c_str());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010406
10407 checkSilentMode_l();
10408
10409 continue;
10410 }
10411 }
10412
10413 processConfigEvents_l();
10414
10415 processVolume_l();
10416
10417 checkInvalidTracks_l();
10418
Andy Hungab65b182023-09-06 19:41:47 -070010419 mActiveTracks.updatePowerState_l(this);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010420
Kevin Rocard069c2712018-03-29 19:09:14 -070010421 updateMetadata_l();
10422
Eric Laurent6acd1d42017-01-04 14:23:29 -080010423 lockEffectChains_l(effectChains);
Andy Hung13850be2019-03-14 11:33:09 -070010424 } // release Thread lock
10425
Eric Laurent6acd1d42017-01-04 14:23:29 -080010426 for (size_t i = 0; i < effectChains.size(); i ++) {
Andy Hung13850be2019-03-14 11:33:09 -070010427 effectChains[i]->process_l(); // Thread is not locked, but effect chain is locked
Eric Laurent6acd1d42017-01-04 14:23:29 -080010428 }
Andy Hung13850be2019-03-14 11:33:09 -070010429
10430 // enable changes in effect chain, including moving to another thread.
Eric Laurent6acd1d42017-01-04 14:23:29 -080010431 unlockEffectChains(effectChains);
10432 // Effect chains will be actually deleted here if they were removed from
10433 // mEffectChains list during mixing or effects processing
10434 }
10435
10436 threadLoop_exit();
10437
10438 if (!mStandby) {
10439 threadLoop_standby();
10440 mStandby = true;
10441 }
10442
Eric Laurent6acd1d42017-01-04 14:23:29 -080010443 ALOGV("Thread %p type %d exiting", this, mType);
10444 return false;
10445}
10446
Andy Hungc5007f82023-08-29 14:26:09 -070010447// checkForNewParameter_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -070010448bool MmapThread::checkForNewParameter_l(const String8& keyValuePair,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010449 status_t& status)
10450{
10451 AudioParameter param = AudioParameter(keyValuePair);
10452 int value;
Eric Laurente6e9a482017-07-25 19:26:02 -070010453 bool sendToHal = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010454 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -070010455 LOG_FATAL("Should not happen set routing device in MmapThread");
Eric Laurent6acd1d42017-01-04 14:23:29 -080010456 }
Eric Laurente6e9a482017-07-25 19:26:02 -070010457 if (sendToHal) {
10458 status = mHalStream->setParameters(keyValuePair);
10459 } else {
10460 status = NO_ERROR;
10461 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010462
10463 return false;
10464}
10465
Andy Hungee58e4a2023-07-07 13:47:37 -070010466String8 MmapThread::getParameters(const String8& keys)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010467{
Andy Hung972bec12023-08-31 16:13:39 -070010468 audio_utils::lock_guard _l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010469 String8 out_s8;
10470 if (initCheck() == NO_ERROR && mHalStream->getParameters(keys, &out_s8) == OK) {
10471 return out_s8;
10472 }
Andy Hung920f6572022-10-06 12:09:49 -070010473 return {};
Eric Laurent6acd1d42017-01-04 14:23:29 -080010474}
10475
Andy Hungab65b182023-09-06 19:41:47 -070010476void MmapThread::ioConfigChanged_l(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -070010477 audio_port_handle_t portId __unused) {
Mikhail Naganov88536df2021-07-26 17:30:29 -070010478 sp<AudioIoDescriptor> desc;
10479 bool isInput = false;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010480 switch (event) {
10481 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -070010482 case AUDIO_INPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -080010483 case AUDIO_INPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -070010484 isInput = true;
10485 FALLTHROUGH_INTENDED;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010486 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -070010487 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -080010488 case AUDIO_OUTPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -070010489 desc = sp<AudioIoDescriptor>::make(mId, mPatch, isInput,
10490 mSampleRate, mFormat, mChannelMask, mFrameCount, mFrameCount);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010491 break;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010492 case AUDIO_INPUT_CLOSED:
10493 case AUDIO_OUTPUT_CLOSED:
10494 default:
Mikhail Naganov88536df2021-07-26 17:30:29 -070010495 desc = sp<AudioIoDescriptor>::make(mId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010496 break;
10497 }
Andy Hungab65b182023-09-06 19:41:47 -070010498 mAfThreadCallback->ioConfigChanged_l(event, desc, pid);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010499}
10500
Andy Hungee58e4a2023-07-07 13:47:37 -070010501status_t MmapThread::createAudioPatch_l(const struct audio_patch* patch,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010502 audio_patch_handle_t *handle)
Andy Hungc5007f82023-08-29 14:26:09 -070010503NO_THREAD_SAFETY_ANALYSIS // elease and re-acquire mutex()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010504{
10505 status_t status = NO_ERROR;
10506
10507 // store new device and send to effects
10508 audio_devices_t type = AUDIO_DEVICE_NONE;
10509 audio_port_handle_t deviceId;
jiabinc52b1ff2019-10-31 17:20:42 -070010510 AudioDeviceTypeAddrVector sinkDeviceTypeAddrs;
10511 AudioDeviceTypeAddr sourceDeviceTypeAddr;
10512 uint32_t numDevices = 0;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010513 if (isOutput()) {
10514 for (unsigned int i = 0; i < patch->num_sinks; i++) {
jiabinc52b1ff2019-10-31 17:20:42 -070010515 LOG_ALWAYS_FATAL_IF(popcount(patch->sinks[i].ext.device.type) > 1
10516 && !mAudioHwDev->supportsAudioPatches(),
10517 "Enumerated device type(%#x) must not be used "
10518 "as it does not support audio patches",
10519 patch->sinks[i].ext.device.type);
Mikhail Naganov55773032020-10-01 15:08:13 -070010520 type = static_cast<audio_devices_t>(type | patch->sinks[i].ext.device.type);
Andy Hung920f6572022-10-06 12:09:49 -070010521 sinkDeviceTypeAddrs.emplace_back(patch->sinks[i].ext.device.type,
10522 patch->sinks[i].ext.device.address);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010523 }
10524 deviceId = patch->sinks[0].id;
jiabinc52b1ff2019-10-31 17:20:42 -070010525 numDevices = mPatch.num_sinks;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010526 } else {
10527 type = patch->sources[0].ext.device.type;
10528 deviceId = patch->sources[0].id;
jiabinc52b1ff2019-10-31 17:20:42 -070010529 numDevices = mPatch.num_sources;
10530 sourceDeviceTypeAddr.mType = patch->sources[0].ext.device.type;
jiabin0a488932020-08-07 17:32:40 -070010531 sourceDeviceTypeAddr.setAddress(patch->sources[0].ext.device.address);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010532 }
10533
10534 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -080010535 if (isOutput()) {
10536 mEffectChains[i]->setDevices_l(sinkDeviceTypeAddrs);
10537 } else {
10538 mEffectChains[i]->setInputDevice_l(sourceDeviceTypeAddr);
10539 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010540 }
10541
jiabinc52b1ff2019-10-31 17:20:42 -070010542 if (!isOutput()) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010543 // store new source and send to effects
10544 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
10545 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
10546 for (size_t i = 0; i < mEffectChains.size(); i++) {
10547 mEffectChains[i]->setAudioSource_l(mAudioSource);
10548 }
10549 }
10550 }
10551
10552 if (mAudioHwDev->supportsAudioPatches()) {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010553 status = mHalDevice->createAudioPatch(patch->num_sources, patch->sources, patch->num_sinks,
10554 patch->sinks, handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010555 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010556 audio_port_config port;
10557 std::optional<audio_source_t> source;
10558 if (isOutput()) {
10559 port = patch->sinks[0];
Eric Laurent6acd1d42017-01-04 14:23:29 -080010560 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010561 port = patch->sources[0];
10562 source = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010563 }
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010564 status = mHalStream->legacyCreateAudioPatch(port, source, type);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010565 *handle = AUDIO_PATCH_HANDLE_NONE;
10566 }
10567
jiabinc52b1ff2019-10-31 17:20:42 -070010568 if (numDevices == 0 || mDeviceId != deviceId) {
10569 if (isOutput()) {
10570 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
10571 mOutDeviceTypeAddrs = sinkDeviceTypeAddrs;
jiabin0a957d32020-04-29 10:56:20 -070010572 checkSilentMode_l();
jiabinc52b1ff2019-10-31 17:20:42 -070010573 } else {
10574 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
10575 mInDeviceTypeAddr = sourceDeviceTypeAddr;
10576 }
Phil Burk7f6b40d2017-02-09 13:18:38 -080010577 sp<MmapStreamCallback> callback = mCallback.promote();
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010578 if (mDeviceId != deviceId && callback != 0) {
Andy Hungc5007f82023-08-29 14:26:09 -070010579 mutex().unlock();
Phil Burk7f6b40d2017-02-09 13:18:38 -080010580 callback->onRoutingChanged(deviceId);
Andy Hungc5007f82023-08-29 14:26:09 -070010581 mutex().lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010582 }
jiabinc52b1ff2019-10-31 17:20:42 -070010583 mPatch = *patch;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010584 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010585 }
Eric Laurentdda206a2022-07-08 17:28:35 +020010586 // Force meteadata update after a route change
10587 mActiveTracks.setHasChanged();
10588
Eric Laurent6acd1d42017-01-04 14:23:29 -080010589 return status;
10590}
10591
Andy Hungee58e4a2023-07-07 13:47:37 -070010592status_t MmapThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010593{
10594 status_t status = NO_ERROR;
10595
jiabinc52b1ff2019-10-31 17:20:42 -070010596 mPatch = audio_patch{};
10597 mOutDeviceTypeAddrs.clear();
10598 mInDeviceTypeAddr.reset();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010599
10600 bool supportsAudioPatches = mHalDevice->supportsAudioPatches(&supportsAudioPatches) == OK ?
10601 supportsAudioPatches : false;
10602
10603 if (supportsAudioPatches) {
10604 status = mHalDevice->releaseAudioPatch(handle);
10605 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010606 status = mHalStream->legacyReleaseAudioPatch();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010607 }
Eric Laurentdda206a2022-07-08 17:28:35 +020010608 // Force meteadata update after a route change
10609 mActiveTracks.setHasChanged();
10610
Eric Laurent6acd1d42017-01-04 14:23:29 -080010611 return status;
10612}
10613
Andy Hungee58e4a2023-07-07 13:47:37 -070010614void MmapThread::toAudioPortConfig(struct audio_port_config* config)
Andy Hung3f49ebb2023-09-19 14:48:41 -070010615NO_THREAD_SAFETY_ANALYSIS // mAudioHwDev handle access
Eric Laurent6acd1d42017-01-04 14:23:29 -080010616{
Mikhail Naganovdc769682018-05-04 15:34:08 -070010617 ThreadBase::toAudioPortConfig(config);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010618 if (isOutput()) {
10619 config->role = AUDIO_PORT_ROLE_SOURCE;
10620 config->ext.mix.hw_module = mAudioHwDev->handle();
10621 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
10622 } else {
10623 config->role = AUDIO_PORT_ROLE_SINK;
10624 config->ext.mix.hw_module = mAudioHwDev->handle();
10625 config->ext.mix.usecase.source = mAudioSource;
10626 }
10627}
10628
Andy Hungee58e4a2023-07-07 13:47:37 -070010629status_t MmapThread::addEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010630{
10631 audio_session_t session = chain->sessionId();
10632
10633 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
10634 // Attach all tracks with same session ID to this chain.
10635 // indicate all active tracks in the chain
Andy Hung8d31fd22023-06-26 19:20:57 -070010636 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010637 if (session == track->sessionId()) {
10638 chain->incTrackCnt();
10639 chain->incActiveTrackCnt();
10640 }
10641 }
10642
10643 chain->setThread(this);
10644 chain->setInBuffer(nullptr);
10645 chain->setOutBuffer(nullptr);
10646 chain->syncHalEffectsState();
10647
10648 mEffectChains.add(chain);
10649 checkSuspendOnAddEffectChain_l(chain);
10650 return NO_ERROR;
10651}
10652
Andy Hungee58e4a2023-07-07 13:47:37 -070010653size_t MmapThread::removeEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010654{
10655 audio_session_t session = chain->sessionId();
10656
10657 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
10658
10659 for (size_t i = 0; i < mEffectChains.size(); i++) {
10660 if (chain == mEffectChains[i]) {
10661 mEffectChains.removeAt(i);
10662 // detach all active tracks from the chain
10663 // detach all tracks with same session ID from this chain
Andy Hung8d31fd22023-06-26 19:20:57 -070010664 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010665 if (session == track->sessionId()) {
10666 chain->decActiveTrackCnt();
10667 chain->decTrackCnt();
10668 }
10669 }
10670 break;
10671 }
10672 }
10673 return mEffectChains.size();
10674}
10675
Andy Hungee58e4a2023-07-07 13:47:37 -070010676void MmapThread::threadLoop_standby()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010677{
10678 mHalStream->standby();
10679}
10680
Andy Hungee58e4a2023-07-07 13:47:37 -070010681void MmapThread::threadLoop_exit()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010682{
Phil Burk7dce7282017-09-27 13:51:41 -070010683 // Do not call callback->onTearDown() because it is redundant for thread exit
10684 // and because it can cause a recursive mutex lock on stop().
Eric Laurent6acd1d42017-01-04 14:23:29 -080010685}
10686
Andy Hungee58e4a2023-07-07 13:47:37 -070010687status_t MmapThread::setSyncEvent(const sp<SyncEvent>& /* event */)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010688{
10689 return BAD_VALUE;
10690}
10691
Andy Hungee58e4a2023-07-07 13:47:37 -070010692bool MmapThread::isValidSyncEvent(
10693 const sp<SyncEvent>& /* event */) const
Eric Laurent6acd1d42017-01-04 14:23:29 -080010694{
10695 return false;
10696}
10697
Andy Hungee58e4a2023-07-07 13:47:37 -070010698status_t MmapThread::checkEffectCompatibility_l(
Eric Laurent6acd1d42017-01-04 14:23:29 -080010699 const effect_descriptor_t *desc, audio_session_t sessionId)
10700{
10701 // No global effect sessions on mmap threads
Eric Laurent3f75a5b2019-11-12 15:55:51 -080010702 if (audio_is_global_session(sessionId)) {
10703 ALOGW("checkEffectCompatibility_l(): global effect %s on MMAP thread %s",
Eric Laurent6acd1d42017-01-04 14:23:29 -080010704 desc->name, mThreadName);
10705 return BAD_VALUE;
10706 }
10707
10708 if (!isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC)) {
10709 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on capture mmap thread",
10710 desc->name);
10711 return BAD_VALUE;
10712 }
10713 if (isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Glenn Kastend3bb6452016-12-05 18:14:37 -080010714 ALOGW("checkEffectCompatibility_l(): pre processing effect %s created on playback mmap "
10715 "thread", desc->name);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010716 return BAD_VALUE;
10717 }
10718
10719 // Only allow effects without processing load or latency
10720 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) != EFFECT_FLAG_NO_PROCESS) {
10721 return BAD_VALUE;
10722 }
10723
Andy Hung116bc262023-06-20 18:56:17 -070010724 if (IAfEffectModule::isHapticGenerator(&desc->type)) {
jiabineb3bda02020-06-30 14:07:03 -070010725 ALOGE("%s(): HapticGenerator is not supported for MmapThread", __func__);
10726 return BAD_VALUE;
10727 }
10728
Eric Laurent6acd1d42017-01-04 14:23:29 -080010729 return NO_ERROR;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010730}
10731
Andy Hungee58e4a2023-07-07 13:47:37 -070010732void MmapThread::checkInvalidTracks_l()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010733{
Eric Laurent039c24a2022-10-07 14:01:59 +020010734 sp<MmapStreamCallback> callback;
Andy Hung8d31fd22023-06-26 19:20:57 -070010735 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010736 if (track->isInvalid()) {
Eric Laurent039c24a2022-10-07 14:01:59 +020010737 callback = mCallback.promote();
10738 if (callback == nullptr && mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
10739 ALOGW("Could not notify MMAP stream tear down: no onRoutingChanged callback!");
10740 mNoCallbackWarningCount++;
10741 }
10742 break;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010743 }
10744 }
Eric Laurent039c24a2022-10-07 14:01:59 +020010745 if (callback != 0) {
Andy Hungc5007f82023-08-29 14:26:09 -070010746 mutex().unlock();
Eric Laurent039c24a2022-10-07 14:01:59 +020010747 callback->onRoutingChanged(AUDIO_PORT_HANDLE_NONE);
Andy Hungc5007f82023-08-29 14:26:09 -070010748 mutex().lock();
jiabindfa32482022-10-06 19:45:50 +000010749 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010750}
10751
Andy Hungee58e4a2023-07-07 13:47:37 -070010752void MmapThread::dumpInternals_l(int fd, const Vector<String16>& /* args */)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010753{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010754 dprintf(fd, " Attributes: content type %d usage %d source %d\n",
10755 mAttr.content_type, mAttr.usage, mAttr.source);
10756 dprintf(fd, " Session: %d port Id: %d\n", mSessionId, mPortId);
Eric Tan39ec8d62018-07-24 09:49:29 -070010757 if (mActiveTracks.isEmpty()) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010758 dprintf(fd, " No active clients\n");
10759 }
10760}
10761
Andy Hungee58e4a2023-07-07 13:47:37 -070010762void MmapThread::dumpTracks_l(int fd, const Vector<String16>& /* args */)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010763{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010764 String8 result;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010765 size_t numtracks = mActiveTracks.size();
Andy Hung2c6c3bb2017-06-16 14:01:45 -070010766 dprintf(fd, " %zu Tracks\n", numtracks);
10767 const char *prefix = " ";
Eric Laurent6acd1d42017-01-04 14:23:29 -080010768 if (numtracks) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -070010769 result.append(prefix);
Kevin Rocard5f2136e2018-05-11 22:03:00 -070010770 mActiveTracks[0]->appendDumpHeader(result);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010771 for (size_t i = 0; i < numtracks ; ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -070010772 sp<IAfMmapTrack> track = mActiveTracks[i];
Andy Hung2c6c3bb2017-06-16 14:01:45 -070010773 result.append(prefix);
10774 track->appendDump(result, true /* active */);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010775 }
10776 } else {
10777 dprintf(fd, "\n");
10778 }
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +000010779 write(fd, result.c_str(), result.size());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010780}
10781
Andy Hungee58e4a2023-07-07 13:47:37 -070010782/* static */
10783sp<IAfMmapPlaybackThread> IAfMmapPlaybackThread::create(
Andy Hung583043b2023-07-17 17:05:00 -070010784 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
Andy Hungee58e4a2023-07-07 13:47:37 -070010785 AudioHwDevice* hwDev, AudioStreamOut* output, bool systemReady) {
Andy Hung583043b2023-07-17 17:05:00 -070010786 return sp<MmapPlaybackThread>::make(afThreadCallback, id, hwDev, output, systemReady);
Andy Hungee58e4a2023-07-07 13:47:37 -070010787}
10788
10789MmapPlaybackThread::MmapPlaybackThread(
Andy Hung583043b2023-07-17 17:05:00 -070010790 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
jiabinc52b1ff2019-10-31 17:20:42 -070010791 AudioHwDevice *hwDev, AudioStreamOut *output, bool systemReady)
Andy Hung583043b2023-07-17 17:05:00 -070010792 : MmapThread(afThreadCallback, id, hwDev, output->stream, systemReady, true /* isOut */),
Eric Laurent6acd1d42017-01-04 14:23:29 -080010793 mStreamType(AUDIO_STREAM_MUSIC),
Phil Burk56ecf3e2018-03-12 15:38:17 -070010794 mOutput(output)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010795{
10796 snprintf(mThreadName, kThreadNameLength, "AudioMmapOut_%X", id);
10797 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Andy Hung583043b2023-07-17 17:05:00 -070010798 mMasterVolume = afThreadCallback->masterVolume_l();
10799 mMasterMute = afThreadCallback->masterMute_l();
Eric Laurent1f9b5e62023-07-03 18:14:07 +020010800
10801 for (int i = AUDIO_STREAM_MIN; i < AUDIO_STREAM_FOR_POLICY_CNT; ++i) {
10802 const audio_stream_type_t stream{static_cast<audio_stream_type_t>(i)};
10803 mStreamTypes[stream].volume = 0.0f;
Andy Hung583043b2023-07-17 17:05:00 -070010804 mStreamTypes[stream].mute = mAfThreadCallback->streamMute_l(stream);
Eric Laurent1f9b5e62023-07-03 18:14:07 +020010805 }
10806 // Audio patch and call assistant volume are always max
10807 mStreamTypes[AUDIO_STREAM_PATCH].volume = 1.0f;
10808 mStreamTypes[AUDIO_STREAM_PATCH].mute = false;
10809 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].volume = 1.0f;
10810 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].mute = false;
10811
Eric Laurent6acd1d42017-01-04 14:23:29 -080010812 if (mAudioHwDev) {
10813 if (mAudioHwDev->canSetMasterVolume()) {
10814 mMasterVolume = 1.0;
10815 }
10816
10817 if (mAudioHwDev->canSetMasterMute()) {
10818 mMasterMute = false;
10819 }
10820 }
10821}
10822
Andy Hungee58e4a2023-07-07 13:47:37 -070010823void MmapPlaybackThread::configure(const audio_attributes_t* attr,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010824 audio_stream_type_t streamType,
10825 audio_session_t sessionId,
10826 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010827 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010828 audio_port_handle_t portId)
10829{
Andy Hung8d672e02023-09-15 18:19:28 -070010830 audio_utils::lock_guard l(mutex());
10831 MmapThread::configure_l(attr, streamType, sessionId, callback, deviceId, portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010832 mStreamType = streamType;
10833}
10834
Andy Hungee58e4a2023-07-07 13:47:37 -070010835AudioStreamOut* MmapPlaybackThread::clearOutput()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010836{
Andy Hung972bec12023-08-31 16:13:39 -070010837 audio_utils::lock_guard _l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010838 AudioStreamOut *output = mOutput;
10839 mOutput = NULL;
10840 return output;
10841}
10842
Andy Hungee58e4a2023-07-07 13:47:37 -070010843void MmapPlaybackThread::setMasterVolume(float value)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010844{
Andy Hung972bec12023-08-31 16:13:39 -070010845 audio_utils::lock_guard _l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010846 // Don't apply master volume in SW if our HAL can do it for us.
10847 if (mAudioHwDev &&
10848 mAudioHwDev->canSetMasterVolume()) {
10849 mMasterVolume = 1.0;
10850 } else {
10851 mMasterVolume = value;
10852 }
10853}
10854
Andy Hungee58e4a2023-07-07 13:47:37 -070010855void MmapPlaybackThread::setMasterMute(bool muted)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010856{
Andy Hung972bec12023-08-31 16:13:39 -070010857 audio_utils::lock_guard _l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010858 // Don't apply master mute in SW if our HAL can do it for us.
10859 if (mAudioHwDev && mAudioHwDev->canSetMasterMute()) {
10860 mMasterMute = false;
10861 } else {
10862 mMasterMute = muted;
10863 }
10864}
10865
Andy Hungee58e4a2023-07-07 13:47:37 -070010866void MmapPlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010867{
Andy Hung972bec12023-08-31 16:13:39 -070010868 audio_utils::lock_guard _l(mutex());
Eric Laurent1f9b5e62023-07-03 18:14:07 +020010869 mStreamTypes[stream].volume = value;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010870 if (stream == mStreamType) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010871 broadcast_l();
10872 }
10873}
10874
Andy Hungee58e4a2023-07-07 13:47:37 -070010875float MmapPlaybackThread::streamVolume(audio_stream_type_t stream) const
Eric Laurent6acd1d42017-01-04 14:23:29 -080010876{
Andy Hung972bec12023-08-31 16:13:39 -070010877 audio_utils::lock_guard _l(mutex());
Eric Laurent1f9b5e62023-07-03 18:14:07 +020010878 return mStreamTypes[stream].volume;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010879}
10880
Andy Hungee58e4a2023-07-07 13:47:37 -070010881void MmapPlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010882{
Andy Hung972bec12023-08-31 16:13:39 -070010883 audio_utils::lock_guard _l(mutex());
Eric Laurent1f9b5e62023-07-03 18:14:07 +020010884 mStreamTypes[stream].mute = muted;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010885 if (stream == mStreamType) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010886 broadcast_l();
10887 }
10888}
10889
Andy Hungee58e4a2023-07-07 13:47:37 -070010890void MmapPlaybackThread::invalidateTracks(audio_stream_type_t streamType)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010891{
Andy Hung972bec12023-08-31 16:13:39 -070010892 audio_utils::lock_guard _l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010893 if (streamType == mStreamType) {
Andy Hung8d31fd22023-06-26 19:20:57 -070010894 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010895 track->invalidate();
10896 }
10897 broadcast_l();
10898 }
10899}
10900
Andy Hungee58e4a2023-07-07 13:47:37 -070010901void MmapPlaybackThread::invalidateTracks(std::set<audio_port_handle_t>& portIds)
jiabinc44b3462022-12-08 12:52:31 -080010902{
Andy Hung972bec12023-08-31 16:13:39 -070010903 audio_utils::lock_guard _l(mutex());
jiabinc44b3462022-12-08 12:52:31 -080010904 bool trackMatch = false;
Andy Hung8d31fd22023-06-26 19:20:57 -070010905 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
jiabinc44b3462022-12-08 12:52:31 -080010906 if (portIds.find(track->portId()) != portIds.end()) {
10907 track->invalidate();
10908 trackMatch = true;
10909 portIds.erase(track->portId());
10910 }
10911 if (portIds.empty()) {
10912 break;
10913 }
10914 }
10915 if (trackMatch) {
10916 broadcast_l();
10917 }
10918}
10919
Andy Hungee58e4a2023-07-07 13:47:37 -070010920void MmapPlaybackThread::processVolume_l()
Andy Hung920f6572022-10-06 12:09:49 -070010921NO_THREAD_SAFETY_ANALYSIS // access of track->processMuteEvent_l
Eric Laurent6acd1d42017-01-04 14:23:29 -080010922{
10923 float volume;
10924
Eric Laurent1f9b5e62023-07-03 18:14:07 +020010925 if (mMasterMute || streamMuted_l()) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010926 volume = 0;
10927 } else {
Eric Laurent1f9b5e62023-07-03 18:14:07 +020010928 volume = mMasterVolume * streamVolume_l();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010929 }
10930
10931 if (volume != mHalVolFloat) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010932 // Convert volumes from float to 8.24
10933 uint32_t vol = (uint32_t)(volume * (1 << 24));
10934
10935 // Delegate volume control to effect in track effect chain if needed
10936 // only one effect chain can be present on DirectOutputThread, so if
10937 // there is one, the track is connected to it
10938 if (!mEffectChains.isEmpty()) {
10939 mEffectChains[0]->setVolume_l(&vol, &vol);
10940 volume = (float)vol / (1 << 24);
10941 }
Eric Laurentdff774a2017-04-21 15:29:38 -070010942 // Try to use HW volume control and fall back to SW control if not implemented
Phil Burk56ecf3e2018-03-12 15:38:17 -070010943 if (mOutput->stream->setVolume(volume, volume) == NO_ERROR) {
10944 mHalVolFloat = volume; // HW volume control worked, so update value.
10945 mNoCallbackWarningCount = 0;
10946 } else {
Eric Laurentdff774a2017-04-21 15:29:38 -070010947 sp<MmapStreamCallback> callback = mCallback.promote();
10948 if (callback != 0) {
Phil Burk56ecf3e2018-03-12 15:38:17 -070010949 mHalVolFloat = volume; // SW volume control worked, so update value.
10950 mNoCallbackWarningCount = 0;
Andy Hungc5007f82023-08-29 14:26:09 -070010951 mutex().unlock();
Robert Wu4389ae62022-02-17 18:39:41 +000010952 callback->onVolumeChanged(volume);
Andy Hungc5007f82023-08-29 14:26:09 -070010953 mutex().lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010954 } else {
Phil Burk56ecf3e2018-03-12 15:38:17 -070010955 if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
10956 ALOGW("Could not set MMAP stream volume: no volume callback!");
10957 mNoCallbackWarningCount++;
10958 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010959 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010960 }
Andy Hung8d31fd22023-06-26 19:20:57 -070010961 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Jasmine Chaeaa10e42021-05-11 10:11:14 +080010962 track->setMetadataHasChanged();
Andy Hung583043b2023-07-17 17:05:00 -070010963 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
Vlad Popaec1788e2022-08-04 11:23:30 +020010964 /*muteState=*/{mMasterMute,
Eric Laurent1f9b5e62023-07-03 18:14:07 +020010965 streamVolume_l() == 0.f,
10966 streamMuted_l(),
Vlad Popaec1788e2022-08-04 11:23:30 +020010967 // TODO(b/241533526): adjust logic to include mute from AppOps
10968 false /*muteFromPlaybackRestricted*/,
10969 false /*muteFromClientVolume*/,
10970 false /*muteFromVolumeShaper*/});
Jasmine Chaeaa10e42021-05-11 10:11:14 +080010971 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010972 }
10973}
10974
Andy Hungee58e4a2023-07-07 13:47:37 -070010975ThreadBase::MetadataUpdate MmapPlaybackThread::updateMetadata_l()
Kevin Rocard069c2712018-03-29 19:09:14 -070010976{
Jasmine Chaeaa10e42021-05-11 10:11:14 +080010977 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
Vlad Popa7e81cea2023-01-19 16:34:16 +010010978 return {}; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -070010979 }
10980 StreamOutHalInterface::SourceMetadata metadata;
Andy Hung8d31fd22023-06-26 19:20:57 -070010981 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Kevin Rocard069c2712018-03-29 19:09:14 -070010982 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurent94579172020-11-20 18:41:04 +010010983 playback_track_metadata_v7_t trackMetadata;
10984 trackMetadata.base = {
Kevin Rocard069c2712018-03-29 19:09:14 -070010985 .usage = track->attributes().usage,
10986 .content_type = track->attributes().content_type,
10987 .gain = mHalVolFloat, // TODO: propagate from aaudio pre-mix volume
Eric Laurent94579172020-11-20 18:41:04 +010010988 };
10989 trackMetadata.channel_mask = track->channelMask(),
10990 strncpy(trackMetadata.tags, track->attributes().tags, AUDIO_ATTRIBUTES_TAGS_MAX_SIZE);
10991 metadata.tracks.push_back(trackMetadata);
Kevin Rocard069c2712018-03-29 19:09:14 -070010992 }
10993 mOutput->stream->updateSourceMetadata(metadata);
Vlad Popa7e81cea2023-01-19 16:34:16 +010010994
10995 MetadataUpdate change;
10996 change.playbackMetadataUpdate = metadata.tracks;
10997 return change;
10998};
Kevin Rocard069c2712018-03-29 19:09:14 -070010999
Andy Hungee58e4a2023-07-07 13:47:37 -070011000void MmapPlaybackThread::checkSilentMode_l()
Eric Laurent6acd1d42017-01-04 14:23:29 -080011001{
11002 if (!mMasterMute) {
11003 char value[PROPERTY_VALUE_MAX];
11004 if (property_get("ro.audio.silent", value, "0") > 0) {
11005 char *endptr;
11006 unsigned long ul = strtoul(value, &endptr, 0);
11007 if (*endptr == '\0' && ul != 0) {
11008 ALOGD("Silence is golden");
11009 // The setprop command will not allow a property to be changed after
11010 // the first time it is set, so we don't have to worry about un-muting.
11011 setMasterMute_l(true);
11012 }
11013 }
11014 }
11015}
11016
Andy Hungee58e4a2023-07-07 13:47:37 -070011017void MmapPlaybackThread::toAudioPortConfig(struct audio_port_config* config)
Mikhail Naganov32abc2b2018-05-24 12:57:11 -070011018{
11019 MmapThread::toAudioPortConfig(config);
11020 if (mOutput && mOutput->flags != AUDIO_OUTPUT_FLAG_NONE) {
11021 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
11022 config->flags.output = mOutput->flags;
11023 }
11024}
11025
Andy Hungee58e4a2023-07-07 13:47:37 -070011026status_t MmapPlaybackThread::getExternalPosition(uint64_t* position,
Andy Hung440901d2023-06-29 21:19:25 -070011027 int64_t* timeNanos) const
jiabinb7d8c5a2020-08-26 17:24:52 -070011028{
11029 if (mOutput == nullptr) {
11030 return NO_INIT;
11031 }
11032 struct timespec timestamp;
11033 status_t status = mOutput->getPresentationPosition(position, &timestamp);
11034 if (status == NO_ERROR) {
11035 *timeNanos = timestamp.tv_sec * NANOS_PER_SECOND + timestamp.tv_nsec;
11036 }
11037 return status;
11038}
11039
Andy Hungee58e4a2023-07-07 13:47:37 -070011040status_t MmapPlaybackThread::reportData(const void* buffer, size_t frameCount) {
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010011041 // Send to MelProcessor for sound dose measurement.
11042 auto processor = mMelProcessor.load();
11043 if (processor) {
11044 processor->process(buffer, frameCount * mFrameSize);
11045 }
11046
jiabinfc791ee2023-02-15 19:43:40 +000011047 return NO_ERROR;
11048}
11049
Andy Hungc5007f82023-08-29 14:26:09 -070011050// startMelComputation_l() must be called with AudioFlinger::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -070011051void MmapPlaybackThread::startMelComputation_l(
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010011052 const sp<audio_utils::MelProcessor>& processor)
11053{
11054 ALOGV("%s: starting mel processor for thread %d", __func__, id());
Vlad Popa1c2f7e12023-03-28 02:08:56 +020011055 mMelProcessor.store(processor);
11056 if (processor) {
11057 processor->resume();
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010011058 }
Vlad Popa1c2f7e12023-03-28 02:08:56 +020011059
11060 // no need to update output format for MMapPlaybackThread since it is
11061 // assigned constant for each thread
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010011062}
11063
Andy Hungc5007f82023-08-29 14:26:09 -070011064// stopMelComputation_l() must be called with AudioFlinger::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -070011065void MmapPlaybackThread::stopMelComputation_l()
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010011066{
Vlad Popa1c2f7e12023-03-28 02:08:56 +020011067 ALOGV("%s: pausing mel processor for thread %d", __func__, id());
11068 auto melProcessor = mMelProcessor.load();
11069 if (melProcessor != nullptr) {
11070 melProcessor->pause();
11071 }
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010011072}
11073
Andy Hungee58e4a2023-07-07 13:47:37 -070011074void MmapPlaybackThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent6acd1d42017-01-04 14:23:29 -080011075{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -070011076 MmapThread::dumpInternals_l(fd, args);
Eric Laurent6acd1d42017-01-04 14:23:29 -080011077
Glenn Kastend3bb6452016-12-05 18:14:37 -080011078 dprintf(fd, " Stream type: %d Stream volume: %f HAL volume: %f Stream mute %d\n",
Eric Laurent1f9b5e62023-07-03 18:14:07 +020011079 mStreamType, streamVolume_l(), mHalVolFloat, streamMuted_l());
Eric Laurent6acd1d42017-01-04 14:23:29 -080011080 dprintf(fd, " Master volume: %f Master mute %d\n", mMasterVolume, mMasterMute);
11081}
11082
Andy Hungee58e4a2023-07-07 13:47:37 -070011083/* static */
11084sp<IAfMmapCaptureThread> IAfMmapCaptureThread::create(
Andy Hung583043b2023-07-17 17:05:00 -070011085 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
Andy Hungee58e4a2023-07-07 13:47:37 -070011086 AudioHwDevice* hwDev, AudioStreamIn* input, bool systemReady) {
Andy Hung583043b2023-07-17 17:05:00 -070011087 return sp<MmapCaptureThread>::make(afThreadCallback, id, hwDev, input, systemReady);
Andy Hungee58e4a2023-07-07 13:47:37 -070011088}
11089
11090MmapCaptureThread::MmapCaptureThread(
Andy Hung583043b2023-07-17 17:05:00 -070011091 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
jiabinc52b1ff2019-10-31 17:20:42 -070011092 AudioHwDevice *hwDev, AudioStreamIn *input, bool systemReady)
Andy Hung583043b2023-07-17 17:05:00 -070011093 : MmapThread(afThreadCallback, id, hwDev, input->stream, systemReady, false /* isOut */),
Eric Laurent6acd1d42017-01-04 14:23:29 -080011094 mInput(input)
11095{
11096 snprintf(mThreadName, kThreadNameLength, "AudioMmapIn_%X", id);
11097 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
11098}
11099
Andy Hungee58e4a2023-07-07 13:47:37 -070011100status_t MmapCaptureThread::exitStandby_l()
Eric Laurent331679c2018-04-16 17:03:16 -070011101{
Phil Burkf054fc32018-12-06 09:45:59 -080011102 {
11103 // mInput might have been cleared by clearInput()
Phil Burkf054fc32018-12-06 09:45:59 -080011104 if (mInput != nullptr && mInput->stream != nullptr) {
11105 mInput->stream->setGain(1.0f);
11106 }
11107 }
Eric Laurentdda206a2022-07-08 17:28:35 +020011108 return MmapThread::exitStandby_l();
Eric Laurent331679c2018-04-16 17:03:16 -070011109}
11110
Andy Hungee58e4a2023-07-07 13:47:37 -070011111AudioStreamIn* MmapCaptureThread::clearInput()
Eric Laurent6acd1d42017-01-04 14:23:29 -080011112{
Andy Hung972bec12023-08-31 16:13:39 -070011113 audio_utils::lock_guard _l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080011114 AudioStreamIn *input = mInput;
11115 mInput = NULL;
11116 return input;
11117}
Kevin Rocard069c2712018-03-29 19:09:14 -070011118
Andy Hungee58e4a2023-07-07 13:47:37 -070011119void MmapCaptureThread::processVolume_l()
Eric Laurent331679c2018-04-16 17:03:16 -070011120{
11121 bool changed = false;
11122 bool silenced = false;
11123
11124 sp<MmapStreamCallback> callback = mCallback.promote();
11125 if (callback == 0) {
11126 if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
11127 ALOGW("Could not set MMAP stream silenced: no onStreamSilenced callback!");
11128 mNoCallbackWarningCount++;
11129 }
11130 }
11131
11132 // After a change occurred in track silenced state, mute capture in audio DSP if at least one
11133 // track is silenced and unmute otherwise
11134 for (size_t i = 0; i < mActiveTracks.size() && !silenced; i++) {
11135 if (!mActiveTracks[i]->getAndSetSilencedNotified_l()) {
11136 changed = true;
11137 silenced = mActiveTracks[i]->isSilenced_l();
11138 }
11139 }
11140
11141 if (changed) {
11142 mInput->stream->setGain(silenced ? 0.0f: 1.0f);
11143 }
11144}
11145
Andy Hungee58e4a2023-07-07 13:47:37 -070011146ThreadBase::MetadataUpdate MmapCaptureThread::updateMetadata_l()
Kevin Rocard069c2712018-03-29 19:09:14 -070011147{
Jasmine Chaeaa10e42021-05-11 10:11:14 +080011148 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
Vlad Popa7e81cea2023-01-19 16:34:16 +010011149 return {}; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -070011150 }
11151 StreamInHalInterface::SinkMetadata metadata;
Andy Hung8d31fd22023-06-26 19:20:57 -070011152 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Kevin Rocard069c2712018-03-29 19:09:14 -070011153 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurent94579172020-11-20 18:41:04 +010011154 record_track_metadata_v7_t trackMetadata;
11155 trackMetadata.base = {
Kevin Rocard069c2712018-03-29 19:09:14 -070011156 .source = track->attributes().source,
11157 .gain = 1, // capture tracks do not have volumes
Eric Laurent94579172020-11-20 18:41:04 +010011158 };
11159 trackMetadata.channel_mask = track->channelMask(),
11160 strncpy(trackMetadata.tags, track->attributes().tags, AUDIO_ATTRIBUTES_TAGS_MAX_SIZE);
11161 metadata.tracks.push_back(trackMetadata);
Kevin Rocard069c2712018-03-29 19:09:14 -070011162 }
11163 mInput->stream->updateSinkMetadata(metadata);
Vlad Popa7e81cea2023-01-19 16:34:16 +010011164 MetadataUpdate change;
11165 change.recordMetadataUpdate = metadata.tracks;
11166 return change;
Kevin Rocard069c2712018-03-29 19:09:14 -070011167}
11168
Andy Hungee58e4a2023-07-07 13:47:37 -070011169void MmapCaptureThread::setRecordSilenced(audio_port_handle_t portId, bool silenced)
Eric Laurent331679c2018-04-16 17:03:16 -070011170{
Andy Hung972bec12023-08-31 16:13:39 -070011171 audio_utils::lock_guard _l(mutex());
Eric Laurent331679c2018-04-16 17:03:16 -070011172 for (size_t i = 0; i < mActiveTracks.size() ; i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -070011173 if (mActiveTracks[i]->portId() == portId) {
Eric Laurent331679c2018-04-16 17:03:16 -070011174 mActiveTracks[i]->setSilenced_l(silenced);
11175 broadcast_l();
11176 }
11177 }
jiabin09609032022-06-15 19:26:01 +000011178 setClientSilencedIfExists_l(portId, silenced);
Eric Laurent331679c2018-04-16 17:03:16 -070011179}
11180
Andy Hungee58e4a2023-07-07 13:47:37 -070011181void MmapCaptureThread::toAudioPortConfig(struct audio_port_config* config)
Mikhail Naganov32abc2b2018-05-24 12:57:11 -070011182{
11183 MmapThread::toAudioPortConfig(config);
11184 if (mInput && mInput->flags != AUDIO_INPUT_FLAG_NONE) {
11185 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
11186 config->flags.input = mInput->flags;
11187 }
11188}
11189
Andy Hungee58e4a2023-07-07 13:47:37 -070011190status_t MmapCaptureThread::getExternalPosition(
Andy Hung440901d2023-06-29 21:19:25 -070011191 uint64_t* position, int64_t* timeNanos) const
jiabinb7d8c5a2020-08-26 17:24:52 -070011192{
11193 if (mInput == nullptr) {
11194 return NO_INIT;
11195 }
11196 return mInput->getCapturePosition((int64_t*)position, timeNanos);
11197}
11198
jiabinc658e452022-10-21 20:52:21 +000011199// ----------------------------------------------------------------------------
11200
Andy Hungee58e4a2023-07-07 13:47:37 -070011201/* static */
11202sp<IAfPlaybackThread> IAfPlaybackThread::createBitPerfectThread(
Andy Hung583043b2023-07-17 17:05:00 -070011203 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hungee58e4a2023-07-07 13:47:37 -070011204 AudioStreamOut* output, audio_io_handle_t id, bool systemReady) {
Andy Hung583043b2023-07-17 17:05:00 -070011205 return sp<BitPerfectThread>::make(afThreadCallback, output, id, systemReady);
Andy Hungee58e4a2023-07-07 13:47:37 -070011206}
11207
Andy Hung583043b2023-07-17 17:05:00 -070011208BitPerfectThread::BitPerfectThread(const sp<IAfThreadCallback> &afThreadCallback,
jiabinc658e452022-10-21 20:52:21 +000011209 AudioStreamOut *output, audio_io_handle_t id, bool systemReady)
Andy Hung583043b2023-07-17 17:05:00 -070011210 : MixerThread(afThreadCallback, output, id, systemReady, BIT_PERFECT) {}
jiabinc658e452022-10-21 20:52:21 +000011211
Andy Hungee58e4a2023-07-07 13:47:37 -070011212PlaybackThread::mixer_state BitPerfectThread::prepareTracks_l(
Andy Hung8d31fd22023-06-26 19:20:57 -070011213 Vector<sp<IAfTrack>>* tracksToRemove) {
jiabinc658e452022-10-21 20:52:21 +000011214 mixer_state result = MixerThread::prepareTracks_l(tracksToRemove);
11215 // If there is only one active track and it is bit-perfect, enable tee buffer.
jiabin76d94692022-12-15 21:51:21 +000011216 float volumeLeft = 1.0f;
11217 float volumeRight = 1.0f;
jiabinc658e452022-10-21 20:52:21 +000011218 if (mActiveTracks.size() == 1 && mActiveTracks[0]->isBitPerfect()) {
11219 const int trackId = mActiveTracks[0]->id();
11220 mAudioMixer->setParameter(
11221 trackId, AudioMixer::TRACK, AudioMixer::TEE_BUFFER, (void *)mSinkBuffer);
11222 mAudioMixer->setParameter(
11223 trackId, AudioMixer::TRACK, AudioMixer::TEE_BUFFER_FRAME_COUNT,
11224 (void *)(uintptr_t)mNormalFrameCount);
jiabin76d94692022-12-15 21:51:21 +000011225 mActiveTracks[0]->getFinalVolume(&volumeLeft, &volumeRight);
jiabinc658e452022-10-21 20:52:21 +000011226 mIsBitPerfect = true;
11227 } else {
11228 mIsBitPerfect = false;
11229 // No need to copy bit-perfect data directly to sink buffer given there are multiple tracks
11230 // active.
11231 for (const auto& track : mActiveTracks) {
11232 const int trackId = track->id();
11233 mAudioMixer->setParameter(
11234 trackId, AudioMixer::TRACK, AudioMixer::TEE_BUFFER, nullptr);
11235 }
11236 }
jiabin76d94692022-12-15 21:51:21 +000011237 if (mVolumeLeft != volumeLeft || mVolumeRight != volumeRight) {
11238 mVolumeLeft = volumeLeft;
11239 mVolumeRight = volumeRight;
11240 setVolumeForOutput_l(volumeLeft, volumeRight);
11241 }
jiabinc658e452022-10-21 20:52:21 +000011242 return result;
11243}
11244
Andy Hungee58e4a2023-07-07 13:47:37 -070011245void BitPerfectThread::threadLoop_mix() {
jiabinc658e452022-10-21 20:52:21 +000011246 MixerThread::threadLoop_mix();
11247 mHasDataCopiedToSinkBuffer = mIsBitPerfect;
11248}
11249
Glenn Kasten63238ef2015-03-02 15:50:29 -080011250} // namespace android