blob: 1e897397b45d51993413f1d8a1294aa60347018e [file] [log] [blame]
Eric Laurent81784c32012-11-19 14:55:58 -08001/*
2**
3** Copyright 2012, The Android Open Source Project
4**
5** Licensed under the Apache License, Version 2.0 (the "License");
6** you may not use this file except in compliance with the License.
7** You may obtain a copy of the License at
8**
9** http://www.apache.org/licenses/LICENSE-2.0
10**
11** Unless required by applicable law or agreed to in writing, software
12** distributed under the License is distributed on an "AS IS" BASIS,
13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14** See the License for the specific language governing permissions and
15** limitations under the License.
16*/
17
18
19#define LOG_TAG "AudioFlinger"
Vlad Popab042ee62022-10-20 18:05:00 +020020// #define LOG_NDEBUG 0
Alex Ray371eb972012-11-30 11:11:54 -080021#define ATRACE_TAG ATRACE_TAG_AUDIO
Eric Laurent81784c32012-11-19 14:55:58 -080022
Andy Hung25a80ac2023-07-19 12:47:35 -070023#include "Threads.h"
24
25#include "Client.h"
26#include "IAfEffect.h"
27#include "MelReporter.h"
28#include "ResamplerBufferProvider.h"
29
30#include <afutils/DumpTryLock.h>
31#include <afutils/Permission.h>
32#include <afutils/TypedLogger.h>
33#include <afutils/Vibrator.h>
34#include <audio_utils/MelProcessor.h>
35#include <audio_utils/Metadata.h>
36#ifdef DEBUG_CPU_USAGE
37#include <audio_utils/Statistics.h>
38#include <cpustats/ThreadCpuUsage.h>
39#endif
40#include <audio_utils/channels.h>
41#include <audio_utils/format.h>
42#include <audio_utils/minifloat.h>
43#include <audio_utils/mono_blend.h>
44#include <audio_utils/primitives.h>
45#include <audio_utils/safe_math.h>
46#include <audiomanager/AudioManager.h>
47#include <binder/IPCThreadState.h>
48#include <binder/IServiceManager.h>
49#include <binder/PersistableBundle.h>
Eric Laurent4eb45d02023-12-20 12:07:17 +010050#include <com_android_media_audio.h>
Glenn Kastenc9a23672020-06-30 12:12:42 -070051#include <cutils/bitops.h>
Eric Laurent81784c32012-11-19 14:55:58 -080052#include <cutils/properties.h>
Andy Hung25a80ac2023-07-19 12:47:35 -070053#include <fastpath/AutoPark.h>
jiabinc52b1ff2019-10-31 17:20:42 -070054#include <media/AudioContainers.h>
55#include <media/AudioDeviceTypeAddr.h>
Glenn Kasten1ab85ec2013-05-31 09:18:43 -070056#include <media/AudioParameter.h>
Andy Hungcd044842014-08-07 11:04:34 -070057#include <media/AudioResamplerPublic.h>
Andy Hung25a80ac2023-07-19 12:47:35 -070058#ifdef ADD_BATTERY_DATA
59#include <media/IMediaPlayerService.h>
60#include <media/IMediaDeathNotifier.h>
61#endif
62#include <media/MmapStreamCallback.h>
Andy Hung89816052017-01-11 17:08:23 -080063#include <media/RecordBufferConverter.h>
Mikhail Naganov913d06c2016-11-01 12:49:22 -070064#include <media/TypeConverter.h>
Andy Hung25a80ac2023-07-19 12:47:35 -070065#include <media/audiohal/EffectsFactoryHalInterface.h>
66#include <media/audiohal/StreamHalInterface.h>
Glenn Kasten6dbb5e32014-05-13 10:38:42 -070067#include <media/nbaio/AudioStreamInSource.h>
Eric Laurent81784c32012-11-19 14:55:58 -080068#include <media/nbaio/AudioStreamOutSink.h>
69#include <media/nbaio/MonoPipe.h>
70#include <media/nbaio/MonoPipeReader.h>
71#include <media/nbaio/Pipe.h>
72#include <media/nbaio/PipeReader.h>
73#include <media/nbaio/SourceAudioBufferProvider.h>
Wei Jia3f273d12015-11-24 09:06:49 -080074#include <mediautils/BatteryNotifier.h>
Andy Hungafc51db2022-04-08 17:33:40 -070075#include <mediautils/Process.h>
Andy Hungab7ef302018-05-15 19:35:29 -070076#include <mediautils/SchedulingPolicyService.h>
77#include <mediautils/ServiceUtilities.h>
Andy Hung25a80ac2023-07-19 12:47:35 -070078#include <powermanager/PowerManager.h>
79#include <private/android_filesystem_config.h>
80#include <private/media/AudioTrackShared.h>
81#include <system/audio_effects/effect_aec.h>
82#include <system/audio_effects/effect_downmix.h>
83#include <system/audio_effects/effect_ns.h>
84#include <system/audio_effects/effect_spatializer.h>
85#include <utils/Log.h>
86#include <utils/Trace.h>
Eric Laurent81784c32012-11-19 14:55:58 -080087
Andy Hung25a80ac2023-07-19 12:47:35 -070088#include <fcntl.h>
89#include <linux/futex.h>
90#include <math.h>
91#include <memory>
Nicolas Rouletfe1e1442017-01-30 12:02:03 -080092#include <pthread.h>
Andy Hung25a80ac2023-07-19 12:47:35 -070093#include <sstream>
94#include <string>
95#include <sys/stat.h>
96#include <sys/syscall.h>
Nicolas Rouletfe1e1442017-01-30 12:02:03 -080097
Eric Laurent81784c32012-11-19 14:55:58 -080098// ----------------------------------------------------------------------------
99
100// Note: the following macro is used for extremely verbose logging message. In
101// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
102// 0; but one side effect of this is to turn all LOGV's as well. Some messages
103// are so verbose that we want to suppress them even when we have ALOG_ASSERT
104// turned on. Do not uncomment the #def below unless you really know what you
105// are doing and want to see all of the extremely verbose messages.
106//#define VERY_VERY_VERBOSE_LOGGING
107#ifdef VERY_VERY_VERBOSE_LOGGING
108#define ALOGVV ALOGV
109#else
110#define ALOGVV(a...) do { } while(0)
111#endif
112
Andy Hung6770c6f2015-04-07 13:43:36 -0700113// TODO: Move these macro/inlines to a header file.
Glenn Kasten49d00ad2014-07-21 11:22:03 -0700114#define max(a, b) ((a) > (b) ? (a) : (b))
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700115
Andy Hung6770c6f2015-04-07 13:43:36 -0700116template <typename T>
117static inline T min(const T& a, const T& b)
118{
119 return a < b ? a : b;
120}
Glenn Kasten49d00ad2014-07-21 11:22:03 -0700121
Eric Laurent81784c32012-11-19 14:55:58 -0800122namespace android {
123
Andy Hungee58e4a2023-07-07 13:47:37 -0700124using audioflinger::SyncEvent;
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -0700125using media::IEffectClient;
Svet Ganov33761132021-05-13 22:51:08 +0000126using content::AttributionSourceState;
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -0700127
Andy Hung25a80ac2023-07-19 12:47:35 -0700128// Keep in sync with java definition in media/java/android/media/AudioRecord.java
129static constexpr int32_t kMaxSharedAudioHistoryMs = 5000;
130
Eric Laurent81784c32012-11-19 14:55:58 -0800131// retry counts for buffer fill timeout
132// 50 * ~20msecs = 1 second
133static const int8_t kMaxTrackRetries = 50;
134static const int8_t kMaxTrackStartupRetries = 50;
Andy Hung455982f2021-04-27 17:46:12 -0700135
Eric Laurent81784c32012-11-19 14:55:58 -0800136// allow less retry attempts on direct output thread.
137// direct outputs can be a scarce resource in audio hardware and should
138// be released as quickly as possible.
Andy Hung455982f2021-04-27 17:46:12 -0700139// Notes:
140// 1) The retry duration kMaxTrackRetriesDirectMs may be increased
141// in case the data write is bursty for the AudioTrack. The application
142// should endeavor to write at least once every kMaxTrackRetriesDirectMs
143// to prevent an underrun situation. If the data is bursty, then
144// the application can also throttle the data sent to be even.
145// 2) For compressed audio data, any data present in the AudioTrack buffer
146// will be sent and reset the retry count. This delivers data as
147// it arrives, with approximately kDirectMinSleepTimeUs = 10ms checking interval.
148// 3) For linear PCM or proportional PCM, we wait one period for a period's worth
149// of data to be available, then any remaining data is delivered.
150// This is required to ensure the last bit of data is delivered before underrun.
151//
152// Sleep time per cycle is kDirectMinSleepTimeUs for compressed tracks
153// or the size of the HAL period for proportional / linear PCM tracks.
154static const int32_t kMaxTrackRetriesDirectMs = 200;
Eric Laurent81784c32012-11-19 14:55:58 -0800155
156// don't warn about blocked writes or record buffer overflows more often than this
157static const nsecs_t kWarningThrottleNs = seconds(5);
158
159// RecordThread loop sleep time upon application overrun or audio HAL read error
160static const int kRecordThreadSleepUs = 5000;
161
Eric Laurent10351942014-05-08 18:49:52 -0700162// maximum time to wait in sendConfigEvent_l() for a status to be received
163static const nsecs_t kConfigEventTimeoutNs = seconds(2);
Eric Laurent81784c32012-11-19 14:55:58 -0800164
165// minimum sleep time for the mixer thread loop when tracks are active but in underrun
166static const uint32_t kMinThreadSleepTimeUs = 5000;
167// maximum divider applied to the active sleep time in the mixer thread loop
168static const uint32_t kMaxThreadSleepTimeShift = 2;
169
Andy Hung09a50072014-02-27 14:30:47 -0800170// minimum normal sink buffer size, expressed in milliseconds rather than frames
Glenn Kasteneb9487e2015-07-22 09:15:17 -0700171// FIXME This should be based on experimentally observed scheduling jitter
Andy Hung09a50072014-02-27 14:30:47 -0800172static const uint32_t kMinNormalSinkBufferSizeMs = 20;
173// maximum normal sink buffer size
174static const uint32_t kMaxNormalSinkBufferSizeMs = 24;
Eric Laurent81784c32012-11-19 14:55:58 -0800175
Glenn Kasteneb9487e2015-07-22 09:15:17 -0700176// minimum capture buffer size in milliseconds to _not_ need a fast capture thread
177// FIXME This should be based on experimentally observed scheduling jitter
178static const uint32_t kMinNormalCaptureBufferSizeMs = 12;
179
Eric Laurent972a1732013-09-04 09:42:59 -0700180// Offloaded output thread standby delay: allows track transition without going to standby
181static const nsecs_t kOffloadStandbyDelayNs = seconds(1);
182
Eric Laurent51716182016-02-29 18:00:56 -0800183// Direct output thread minimum sleep time in idle or active(underrun) state
184static const nsecs_t kDirectMinSleepTimeUs = 10000;
185
Brian Lindahl65e90012022-07-27 18:01:07 +0200186// Minimum amount of time between checking to see if the timestamp is advancing
187// for underrun detection. If we check too frequently, we may not detect a
188// timestamp update and will falsely detect underrun.
Andy Hung0ff14292023-12-20 15:55:16 -0800189static constexpr nsecs_t kMinimumTimeBetweenTimestampChecksNs = 150 /* ms */ * 1'000'000;
Brian Lindahl65e90012022-07-27 18:01:07 +0200190
Glenn Kasten1b291842016-07-18 14:55:21 -0700191// The universal constant for ubiquitous 20ms value. The value of 20ms seems to provide a good
192// balance between power consumption and latency, and allows threads to be scheduled reliably
193// by the CFS scheduler.
194// FIXME Express other hardcoded references to 20ms with references to this constant and move
195// it appropriately.
196#define FMS_20 20
Eric Laurent51716182016-02-29 18:00:56 -0800197
Eric Laurent81784c32012-11-19 14:55:58 -0800198// Whether to use fast mixer
199static const enum {
200 FastMixer_Never, // never initialize or use: for debugging only
201 FastMixer_Always, // always initialize and use, even if not needed: for debugging only
202 // normal mixer multiplier is 1
203 FastMixer_Static, // initialize if needed, then use all the time if initialized,
204 // multiplier is calculated based on min & max normal mixer buffer size
205 FastMixer_Dynamic, // initialize if needed, then use dynamically depending on track load,
206 // multiplier is calculated based on min & max normal mixer buffer size
207 // FIXME for FastMixer_Dynamic:
208 // Supporting this option will require fixing HALs that can't handle large writes.
209 // For example, one HAL implementation returns an error from a large write,
210 // and another HAL implementation corrupts memory, possibly in the sample rate converter.
211 // We could either fix the HAL implementations, or provide a wrapper that breaks
212 // up large writes into smaller ones, and the wrapper would need to deal with scheduler.
213} kUseFastMixer = FastMixer_Static;
214
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700215// Whether to use fast capture
216static const enum {
217 FastCapture_Never, // never initialize or use: for debugging only
218 FastCapture_Always, // always initialize and use, even if not needed: for debugging only
219 FastCapture_Static, // initialize if needed, then use all the time if initialized
220} kUseFastCapture = FastCapture_Static;
221
Eric Laurent81784c32012-11-19 14:55:58 -0800222// Priorities for requestPriority
223static const int kPriorityAudioApp = 2;
224static const int kPriorityFastMixer = 3;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700225static const int kPriorityFastCapture = 3;
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 Hung02ea2a02024-01-25 17:02:30 -0800725 if (event->mCondition.wait_for(
726 _l, std::chrono::nanoseconds(kConfigEventTimeoutNs), getTid())
727 == std::cv_status::timeout) {
Eric Laurent10351942014-05-08 18:49:52 -0700728 event->mStatus = TIMED_OUT;
729 event->mWaitStatus = false;
730 }
731 }
732 status = event->mStatus;
Eric Laurent81784c32012-11-19 14:55:58 -0800733 }
Andy Hungc5007f82023-08-29 14:26:09 -0700734 mutex().lock();
Eric Laurent81784c32012-11-19 14:55:58 -0800735 return status;
736}
737
Andy Hungee58e4a2023-07-07 13:47:37 -0700738void ThreadBase::sendIoConfigEvent(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -0700739 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -0800740{
Andy Hung972bec12023-08-31 16:13:39 -0700741 audio_utils::lock_guard _l(mutex());
Eric Laurent09f1ed22019-04-24 17:45:17 -0700742 sendIoConfigEvent_l(event, pid, portId);
Eric Laurent81784c32012-11-19 14:55:58 -0800743}
744
Andy Hungc5007f82023-08-29 14:26:09 -0700745// sendIoConfigEvent_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -0700746void ThreadBase::sendIoConfigEvent_l(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -0700747 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -0800748{
Andy Hungd0979812019-02-21 15:51:44 -0800749 // The audio statistics history is exponentially weighted to forget events
750 // about five or more seconds in the past. In order to have
751 // crisper statistics for mediametrics, we reset the statistics on
752 // an IoConfigEvent, to reflect different properties for a new device.
753 mIoJitterMs.reset();
754 mLatencyMs.reset();
755 mProcessTimeMs.reset();
Robert Wu06db0a32021-08-10 19:05:34 +0000756 mMonopipePipeDepthStats.reset();
Dean Wheatley12473e92021-03-18 23:00:55 +1100757 mTimestampVerifier.discontinuity(mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS);
Andy Hungd0979812019-02-21 15:51:44 -0800758
Eric Laurent09f1ed22019-04-24 17:45:17 -0700759 sp<ConfigEvent> configEvent = (ConfigEvent *)new IoConfigEvent(event, pid, portId);
Eric Laurent10351942014-05-08 18:49:52 -0700760 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800761}
762
Andy Hungee58e4a2023-07-07 13:47:37 -0700763void ThreadBase::sendPrioConfigEvent(pid_t pid, pid_t tid, int32_t prio, bool forApp)
Eric Laurent72e3f392015-05-20 14:43:50 -0700764{
Andy Hung972bec12023-08-31 16:13:39 -0700765 audio_utils::lock_guard _l(mutex());
Mikhail Naganov83f04272017-02-07 10:45:09 -0800766 sendPrioConfigEvent_l(pid, tid, prio, forApp);
Eric Laurent72e3f392015-05-20 14:43:50 -0700767}
768
Andy Hungc5007f82023-08-29 14:26:09 -0700769// sendPrioConfigEvent_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -0700770void ThreadBase::sendPrioConfigEvent_l(
Mikhail Naganov83f04272017-02-07 10:45:09 -0800771 pid_t pid, pid_t tid, int32_t prio, bool forApp)
Eric Laurent81784c32012-11-19 14:55:58 -0800772{
Mikhail Naganov83f04272017-02-07 10:45:09 -0800773 sp<ConfigEvent> configEvent = (ConfigEvent *)new PrioConfigEvent(pid, tid, prio, forApp);
Eric Laurent10351942014-05-08 18:49:52 -0700774 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800775}
776
Andy Hungc5007f82023-08-29 14:26:09 -0700777// sendSetParameterConfigEvent_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -0700778status_t ThreadBase::sendSetParameterConfigEvent_l(const String8& keyValuePair)
Eric Laurent81784c32012-11-19 14:55:58 -0800779{
Andy Hung2ddee192015-12-18 17:34:44 -0800780 sp<ConfigEvent> configEvent;
781 AudioParameter param(keyValuePair);
782 int value;
Mikhail Naganov00260b52016-10-13 12:54:24 -0700783 if (param.getInt(String8(AudioParameter::keyMonoOutput), value) == NO_ERROR) {
Andy Hung2ddee192015-12-18 17:34:44 -0800784 setMasterMono_l(value != 0);
785 if (param.size() == 1) {
786 return NO_ERROR; // should be a solo parameter - we don't pass down
787 }
Mikhail Naganov00260b52016-10-13 12:54:24 -0700788 param.remove(String8(AudioParameter::keyMonoOutput));
Andy Hung2ddee192015-12-18 17:34:44 -0800789 configEvent = new SetParameterConfigEvent(param.toString());
790 } else {
791 configEvent = new SetParameterConfigEvent(keyValuePair);
792 }
Eric Laurent10351942014-05-08 18:49:52 -0700793 return sendConfigEvent_l(configEvent);
Glenn Kastenf7773312013-08-13 16:00:42 -0700794}
795
Andy Hungee58e4a2023-07-07 13:47:37 -0700796status_t ThreadBase::sendCreateAudioPatchConfigEvent(
Eric Laurent1c333e22014-05-20 10:48:17 -0700797 const struct audio_patch *patch,
798 audio_patch_handle_t *handle)
799{
Andy Hung972bec12023-08-31 16:13:39 -0700800 audio_utils::lock_guard _l(mutex());
Eric Laurent1c333e22014-05-20 10:48:17 -0700801 sp<ConfigEvent> configEvent = (ConfigEvent *)new CreateAudioPatchConfigEvent(*patch, *handle);
802 status_t status = sendConfigEvent_l(configEvent);
803 if (status == NO_ERROR) {
804 CreateAudioPatchConfigEventData *data =
805 (CreateAudioPatchConfigEventData *)configEvent->mData.get();
806 *handle = data->mHandle;
807 }
808 return status;
809}
810
Andy Hungee58e4a2023-07-07 13:47:37 -0700811status_t ThreadBase::sendReleaseAudioPatchConfigEvent(
Eric Laurent1c333e22014-05-20 10:48:17 -0700812 const audio_patch_handle_t handle)
813{
Andy Hung972bec12023-08-31 16:13:39 -0700814 audio_utils::lock_guard _l(mutex());
Eric Laurent1c333e22014-05-20 10:48:17 -0700815 sp<ConfigEvent> configEvent = (ConfigEvent *)new ReleaseAudioPatchConfigEvent(handle);
816 return sendConfigEvent_l(configEvent);
817}
818
Andy Hungee58e4a2023-07-07 13:47:37 -0700819status_t ThreadBase::sendUpdateOutDeviceConfigEvent(
jiabinc52b1ff2019-10-31 17:20:42 -0700820 const DeviceDescriptorBaseVector& outDevices)
821{
822 if (type() != RECORD) {
823 // The update out device operation is only for record thread.
824 return INVALID_OPERATION;
825 }
Andy Hung972bec12023-08-31 16:13:39 -0700826 audio_utils::lock_guard _l(mutex());
jiabinc52b1ff2019-10-31 17:20:42 -0700827 sp<ConfigEvent> configEvent = (ConfigEvent *)new UpdateOutDevicesConfigEvent(outDevices);
828 return sendConfigEvent_l(configEvent);
829}
830
Andy Hungee58e4a2023-07-07 13:47:37 -0700831void ThreadBase::sendResizeBufferConfigEvent_l(int32_t maxSharedAudioHistoryMs)
Eric Laurentec376dc2021-04-08 20:41:22 +0200832{
833 ALOG_ASSERT(type() == RECORD, "sendResizeBufferConfigEvent_l() called on non record thread");
834 sp<ConfigEvent> configEvent =
835 (ConfigEvent *)new ResizeBufferConfigEvent(maxSharedAudioHistoryMs);
836 sendConfigEvent_l(configEvent);
837}
Eric Laurent1c333e22014-05-20 10:48:17 -0700838
Andy Hungee58e4a2023-07-07 13:47:37 -0700839void ThreadBase::sendCheckOutputStageEffectsEvent()
Eric Laurentb3f315a2021-07-13 15:09:05 +0200840{
Andy Hung972bec12023-08-31 16:13:39 -0700841 audio_utils::lock_guard _l(mutex());
Eric Laurentb3f315a2021-07-13 15:09:05 +0200842 sendCheckOutputStageEffectsEvent_l();
843}
844
Andy Hungee58e4a2023-07-07 13:47:37 -0700845void ThreadBase::sendCheckOutputStageEffectsEvent_l()
Eric Laurentb3f315a2021-07-13 15:09:05 +0200846{
847 sp<ConfigEvent> configEvent =
848 (ConfigEvent *)new CheckOutputStageEffectsEvent();
849 sendConfigEvent_l(configEvent);
850}
851
Andy Hungee58e4a2023-07-07 13:47:37 -0700852void ThreadBase::sendHalLatencyModesChangedEvent_l()
Eric Laurent68a40a82022-05-03 18:15:04 +0200853{
854 sp<ConfigEvent> configEvent = sp<HalLatencyModesChangedEvent>::make();
855 sendConfigEvent_l(configEvent);
856}
857
Glenn Kasten2cfbf882013-08-14 13:12:11 -0700858// post condition: mConfigEvents.isEmpty()
Andy Hungee58e4a2023-07-07 13:47:37 -0700859void ThreadBase::processConfigEvents_l()
Glenn Kastenf7773312013-08-13 16:00:42 -0700860{
Eric Laurent10351942014-05-08 18:49:52 -0700861 bool configChanged = false;
862
Eric Laurent81784c32012-11-19 14:55:58 -0800863 while (!mConfigEvents.isEmpty()) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700864 ALOGV("processConfigEvents_l() remaining events %zu", mConfigEvents.size());
Eric Laurent10351942014-05-08 18:49:52 -0700865 sp<ConfigEvent> event = mConfigEvents[0];
Eric Laurent81784c32012-11-19 14:55:58 -0800866 mConfigEvents.removeAt(0);
Eric Laurent10351942014-05-08 18:49:52 -0700867 switch (event->mType) {
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700868 case CFG_EVENT_PRIO: {
Eric Laurent10351942014-05-08 18:49:52 -0700869 PrioConfigEventData *data = (PrioConfigEventData *)event->mData.get();
870 // FIXME Need to understand why this has to be done asynchronously
Mikhail Naganov83f04272017-02-07 10:45:09 -0800871 int err = requestPriority(data->mPid, data->mTid, data->mPrio, data->mForApp,
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700872 true /*asynchronous*/);
873 if (err != 0) {
874 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Eric Laurent10351942014-05-08 18:49:52 -0700875 data->mPrio, data->mPid, data->mTid, err);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700876 }
877 } break;
878 case CFG_EVENT_IO: {
Eric Laurent10351942014-05-08 18:49:52 -0700879 IoConfigEventData *data = (IoConfigEventData *)event->mData.get();
Andy Hungab65b182023-09-06 19:41:47 -0700880 ioConfigChanged_l(data->mEvent, data->mPid, data->mPortId);
Eric Laurent10351942014-05-08 18:49:52 -0700881 } break;
882 case CFG_EVENT_SET_PARAMETER: {
883 SetParameterConfigEventData *data = (SetParameterConfigEventData *)event->mData.get();
884 if (checkForNewParameter_l(data->mKeyValuePairs, event->mStatus)) {
885 configChanged = true;
Andy Hung293558a2017-03-21 12:19:20 -0700886 mLocalLog.log("CFG_EVENT_SET_PARAMETER: (%s) configuration changed",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +0000887 data->mKeyValuePairs.c_str());
Glenn Kastend5418eb2013-08-14 13:11:06 -0700888 }
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700889 } break;
Eric Laurent1c333e22014-05-20 10:48:17 -0700890 case CFG_EVENT_CREATE_AUDIO_PATCH: {
Andy Hungab65b182023-09-06 19:41:47 -0700891 const DeviceTypeSet oldDevices = getDeviceTypes_l();
Eric Laurent1c333e22014-05-20 10:48:17 -0700892 CreateAudioPatchConfigEventData *data =
893 (CreateAudioPatchConfigEventData *)event->mData.get();
894 event->mStatus = createAudioPatch_l(&data->mPatch, &data->mHandle);
Andy Hungab65b182023-09-06 19:41:47 -0700895 const DeviceTypeSet newDevices = getDeviceTypes_l();
Eric Laurent52568142022-10-28 11:23:28 +0200896 configChanged = oldDevices != newDevices;
jiabinc52b1ff2019-10-31 17:20:42 -0700897 mLocalLog.log("CFG_EVENT_CREATE_AUDIO_PATCH: old device %s (%s) new device %s (%s)",
898 dumpDeviceTypes(oldDevices).c_str(), toString(oldDevices).c_str(),
899 dumpDeviceTypes(newDevices).c_str(), toString(newDevices).c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -0700900 } break;
901 case CFG_EVENT_RELEASE_AUDIO_PATCH: {
Andy Hungab65b182023-09-06 19:41:47 -0700902 const DeviceTypeSet oldDevices = getDeviceTypes_l();
Eric Laurent1c333e22014-05-20 10:48:17 -0700903 ReleaseAudioPatchConfigEventData *data =
904 (ReleaseAudioPatchConfigEventData *)event->mData.get();
905 event->mStatus = releaseAudioPatch_l(data->mHandle);
Andy Hungab65b182023-09-06 19:41:47 -0700906 const DeviceTypeSet newDevices = getDeviceTypes_l();
Eric Laurent52568142022-10-28 11:23:28 +0200907 configChanged = oldDevices != newDevices;
jiabinc52b1ff2019-10-31 17:20:42 -0700908 mLocalLog.log("CFG_EVENT_RELEASE_AUDIO_PATCH: old device %s (%s) new device %s (%s)",
909 dumpDeviceTypes(oldDevices).c_str(), toString(oldDevices).c_str(),
910 dumpDeviceTypes(newDevices).c_str(), toString(newDevices).c_str());
911 } break;
912 case CFG_EVENT_UPDATE_OUT_DEVICE: {
913 UpdateOutDevicesConfigEventData *data =
914 (UpdateOutDevicesConfigEventData *)event->mData.get();
915 updateOutDevices(data->mOutDevices);
Eric Laurent1c333e22014-05-20 10:48:17 -0700916 } break;
Eric Laurentec376dc2021-04-08 20:41:22 +0200917 case CFG_EVENT_RESIZE_BUFFER: {
918 ResizeBufferConfigEventData *data =
919 (ResizeBufferConfigEventData *)event->mData.get();
920 resizeInputBuffer_l(data->mMaxSharedAudioHistoryMs);
921 } break;
Eric Laurentb3f315a2021-07-13 15:09:05 +0200922
923 case CFG_EVENT_CHECK_OUTPUT_STAGE_EFFECTS: {
924 setCheckOutputStageEffects();
925 } break;
926
Eric Laurent68a40a82022-05-03 18:15:04 +0200927 case CFG_EVENT_HAL_LATENCY_MODES_CHANGED: {
928 onHalLatencyModesChanged_l();
929 } break;
930
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700931 default:
Eric Laurent10351942014-05-08 18:49:52 -0700932 ALOG_ASSERT(false, "processConfigEvents_l() unknown event type %d", event->mType);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700933 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800934 }
Eric Laurent10351942014-05-08 18:49:52 -0700935 {
Andy Hung972bec12023-08-31 16:13:39 -0700936 audio_utils::lock_guard _l(event->mutex());
Eric Laurent10351942014-05-08 18:49:52 -0700937 if (event->mWaitStatus) {
938 event->mWaitStatus = false;
Andy Hungc5007f82023-08-29 14:26:09 -0700939 event->mCondition.notify_one();
Eric Laurent10351942014-05-08 18:49:52 -0700940 }
941 }
942 ALOGV_IF(mConfigEvents.isEmpty(), "processConfigEvents_l() DONE thread %p", this);
943 }
944
945 if (configChanged) {
946 cacheParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800947 }
Eric Laurent81784c32012-11-19 14:55:58 -0800948}
949
Marco Nelissenb2208842014-02-07 14:00:50 -0800950String8 channelMaskToString(audio_channel_mask_t mask, bool output) {
951 String8 s;
Glenn Kastene1635ec2015-06-08 15:46:49 -0700952 const audio_channel_representation_t representation =
953 audio_channel_mask_get_representation(mask);
Andy Hungf98ec8d2015-05-19 12:53:24 -0700954
955 switch (representation) {
jiabin245cdd92018-12-07 17:55:15 -0800956 // Travel all single bit channel mask to convert channel mask to string.
Andy Hungf98ec8d2015-05-19 12:53:24 -0700957 case AUDIO_CHANNEL_REPRESENTATION_POSITION: {
958 if (output) {
959 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT) s.append("front-left, ");
960 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT) s.append("front-right, ");
961 if (mask & AUDIO_CHANNEL_OUT_FRONT_CENTER) s.append("front-center, ");
Andy Hungfba71252021-05-07 11:58:32 -0700962 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY) s.append("low-frequency, ");
Andy Hungf98ec8d2015-05-19 12:53:24 -0700963 if (mask & AUDIO_CHANNEL_OUT_BACK_LEFT) s.append("back-left, ");
964 if (mask & AUDIO_CHANNEL_OUT_BACK_RIGHT) s.append("back-right, ");
965 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT_OF_CENTER) s.append("front-left-of-center, ");
966 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT_OF_CENTER) s.append("front-right-of-center, ");
967 if (mask & AUDIO_CHANNEL_OUT_BACK_CENTER) s.append("back-center, ");
968 if (mask & AUDIO_CHANNEL_OUT_SIDE_LEFT) s.append("side-left, ");
969 if (mask & AUDIO_CHANNEL_OUT_SIDE_RIGHT) s.append("side-right, ");
970 if (mask & AUDIO_CHANNEL_OUT_TOP_CENTER) s.append("top-center ,");
971 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_LEFT) s.append("top-front-left, ");
972 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_CENTER) s.append("top-front-center, ");
973 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_RIGHT) s.append("top-front-right, ");
974 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_LEFT) s.append("top-back-left, ");
Andy Hungae81b4c2021-05-07 08:54:28 -0700975 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_CENTER) s.append("top-back-center, ");
976 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_RIGHT) s.append("top-back-right, ");
977 if (mask & AUDIO_CHANNEL_OUT_TOP_SIDE_LEFT) s.append("top-side-left, ");
978 if (mask & AUDIO_CHANNEL_OUT_TOP_SIDE_RIGHT) s.append("top-side-right, ");
979 if (mask & AUDIO_CHANNEL_OUT_BOTTOM_FRONT_LEFT) s.append("bottom-front-left, ");
980 if (mask & AUDIO_CHANNEL_OUT_BOTTOM_FRONT_CENTER) s.append("bottom-front-center, ");
981 if (mask & AUDIO_CHANNEL_OUT_BOTTOM_FRONT_RIGHT) s.append("bottom-front-right, ");
Andy Hungfba71252021-05-07 11:58:32 -0700982 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY_2) s.append("low-frequency-2, ");
Andy Hungae81b4c2021-05-07 08:54:28 -0700983 if (mask & AUDIO_CHANNEL_OUT_HAPTIC_B) s.append("haptic-B, ");
984 if (mask & AUDIO_CHANNEL_OUT_HAPTIC_A) s.append("haptic-A, ");
Andy Hungf98ec8d2015-05-19 12:53:24 -0700985 if (mask & ~AUDIO_CHANNEL_OUT_ALL) s.append("unknown, ");
986 } else {
987 if (mask & AUDIO_CHANNEL_IN_LEFT) s.append("left, ");
988 if (mask & AUDIO_CHANNEL_IN_RIGHT) s.append("right, ");
989 if (mask & AUDIO_CHANNEL_IN_FRONT) s.append("front, ");
990 if (mask & AUDIO_CHANNEL_IN_BACK) s.append("back, ");
991 if (mask & AUDIO_CHANNEL_IN_LEFT_PROCESSED) s.append("left-processed, ");
992 if (mask & AUDIO_CHANNEL_IN_RIGHT_PROCESSED) s.append("right-processed, ");
993 if (mask & AUDIO_CHANNEL_IN_FRONT_PROCESSED) s.append("front-processed, ");
994 if (mask & AUDIO_CHANNEL_IN_BACK_PROCESSED) s.append("back-processed, ");
995 if (mask & AUDIO_CHANNEL_IN_PRESSURE) s.append("pressure, ");
996 if (mask & AUDIO_CHANNEL_IN_X_AXIS) s.append("X, ");
997 if (mask & AUDIO_CHANNEL_IN_Y_AXIS) s.append("Y, ");
998 if (mask & AUDIO_CHANNEL_IN_Z_AXIS) s.append("Z, ");
Mikhail Naganovc9948492018-05-10 17:25:28 -0700999 if (mask & AUDIO_CHANNEL_IN_BACK_LEFT) s.append("back-left, ");
1000 if (mask & AUDIO_CHANNEL_IN_BACK_RIGHT) s.append("back-right, ");
1001 if (mask & AUDIO_CHANNEL_IN_CENTER) s.append("center, ");
Andy Hungfba71252021-05-07 11:58:32 -07001002 if (mask & AUDIO_CHANNEL_IN_LOW_FREQUENCY) s.append("low-frequency, ");
Andy Hungae81b4c2021-05-07 08:54:28 -07001003 if (mask & AUDIO_CHANNEL_IN_TOP_LEFT) s.append("top-left, ");
1004 if (mask & AUDIO_CHANNEL_IN_TOP_RIGHT) s.append("top-right, ");
Andy Hungf98ec8d2015-05-19 12:53:24 -07001005 if (mask & AUDIO_CHANNEL_IN_VOICE_UPLINK) s.append("voice-uplink, ");
1006 if (mask & AUDIO_CHANNEL_IN_VOICE_DNLINK) s.append("voice-dnlink, ");
1007 if (mask & ~AUDIO_CHANNEL_IN_ALL) s.append("unknown, ");
1008 }
1009 const int len = s.length();
1010 if (len > 2) {
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07001011 (void) s.lockBuffer(len); // needed?
Andy Hungf98ec8d2015-05-19 12:53:24 -07001012 s.unlockBuffer(len - 2); // remove trailing ", "
1013 }
1014 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -08001015 }
Andy Hungf98ec8d2015-05-19 12:53:24 -07001016 case AUDIO_CHANNEL_REPRESENTATION_INDEX:
1017 s.appendFormat("index mask, bits:%#x", audio_channel_mask_get_bits(mask));
1018 return s;
1019 default:
1020 s.appendFormat("unknown mask, representation:%d bits:%#x",
1021 representation, audio_channel_mask_get_bits(mask));
1022 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -08001023 }
Marco Nelissenb2208842014-02-07 14:00:50 -08001024}
1025
Andy Hungee58e4a2023-07-07 13:47:37 -07001026void ThreadBase::dump(int fd, const Vector<String16>& args)
Andy Hung920f6572022-10-06 12:09:49 -07001027NO_THREAD_SAFETY_ANALYSIS // conditional try lock
Eric Laurent81784c32012-11-19 14:55:58 -08001028{
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08001029 dprintf(fd, "\n%s thread %p, name %s, tid %d, type %d (%s):\n", isOutput() ? "Output" : "Input",
1030 this, mThreadName, getTid(), type(), threadTypeToString(type()));
1031
Andy Hungc5007f82023-08-29 14:26:09 -07001032 const bool locked = afutils::dumpTryLock(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001033 if (!locked) {
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08001034 dprintf(fd, " Thread may be deadlocked\n");
Eric Laurent81784c32012-11-19 14:55:58 -08001035 }
1036
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001037 dumpBase_l(fd, args);
1038 dumpInternals_l(fd, args);
1039 dumpTracks_l(fd, args);
1040 dumpEffectChains_l(fd, args);
1041
1042 if (locked) {
Andy Hungc5007f82023-08-29 14:26:09 -07001043 mutex().unlock();
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001044 }
1045
1046 dprintf(fd, " Local log:\n");
1047 mLocalLog.dump(fd, " " /* prefix */, 40 /* lines */);
Andy Hungafc51db2022-04-08 17:33:40 -07001048
1049 // --all does the statistics
1050 bool dumpAll = false;
1051 for (const auto &arg : args) {
1052 if (arg == String16("--all")) {
1053 dumpAll = true;
1054 }
1055 }
1056 if (dumpAll || type() == SPATIALIZER) {
Andy Hung44d648b2022-04-08 17:33:40 -07001057 const std::string sched = mThreadSnapshot.toString();
Andy Hungafc51db2022-04-08 17:33:40 -07001058 if (!sched.empty()) {
1059 (void)write(fd, sched.c_str(), sched.size());
1060 }
1061 }
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001062}
1063
Andy Hungee58e4a2023-07-07 13:47:37 -07001064void ThreadBase::dumpBase_l(int fd, const Vector<String16>& /* args */)
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001065{
Elliott Hughes87cebad2014-05-22 10:14:43 -07001066 dprintf(fd, " I/O handle: %d\n", mId);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001067 dprintf(fd, " Standby: %s\n", mStandby ? "yes" : "no");
Glenn Kasten97b7b752014-09-28 13:04:24 -07001068 dprintf(fd, " Sample rate: %u Hz\n", mSampleRate);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001069 dprintf(fd, " HAL frame count: %zu\n", mFrameCount);
Andy Hung25a80ac2023-07-19 12:47:35 -07001070 dprintf(fd, " HAL format: 0x%x (%s)\n", mHALFormat,
1071 IAfThreadBase::formatToString(mHALFormat).c_str());
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001072 dprintf(fd, " HAL buffer size: %zu bytes\n", mBufferSize);
Glenn Kasten97b7b752014-09-28 13:04:24 -07001073 dprintf(fd, " Channel count: %u\n", mChannelCount);
1074 dprintf(fd, " Channel mask: 0x%08x (%s)\n", mChannelMask,
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00001075 channelMaskToString(mChannelMask, mType != RECORD).c_str());
Andy Hung25a80ac2023-07-19 12:47:35 -07001076 dprintf(fd, " Processing format: 0x%x (%s)\n", mFormat,
1077 IAfThreadBase::formatToString(mFormat).c_str());
Glenn Kastenf87c2f52015-08-21 08:03:57 -07001078 dprintf(fd, " Processing frame size: %zu bytes\n", mFrameSize);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001079 dprintf(fd, " Pending config events:");
Marco Nelissenb2208842014-02-07 14:00:50 -08001080 size_t numConfig = mConfigEvents.size();
1081 if (numConfig) {
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001082 const size_t SIZE = 256;
1083 char buffer[SIZE];
Marco Nelissenb2208842014-02-07 14:00:50 -08001084 for (size_t i = 0; i < numConfig; i++) {
1085 mConfigEvents[i]->dump(buffer, SIZE);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001086 dprintf(fd, "\n %s", buffer);
Marco Nelissenb2208842014-02-07 14:00:50 -08001087 }
Elliott Hughes87cebad2014-05-22 10:14:43 -07001088 dprintf(fd, "\n");
Marco Nelissenb2208842014-02-07 14:00:50 -08001089 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07001090 dprintf(fd, " none\n");
Eric Laurent81784c32012-11-19 14:55:58 -08001091 }
Andy Hung293558a2017-03-21 12:19:20 -07001092 // Note: output device may be used by capture threads for effects such as AEC.
jiabinc52b1ff2019-10-31 17:20:42 -07001093 dprintf(fd, " Output devices: %s (%s)\n",
Andy Hungab65b182023-09-06 19:41:47 -07001094 dumpDeviceTypes(outDeviceTypes_l()).c_str(), toString(outDeviceTypes_l()).c_str());
jiabinc52b1ff2019-10-31 17:20:42 -07001095 dprintf(fd, " Input device: %#x (%s)\n",
Andy Hungab65b182023-09-06 19:41:47 -07001096 inDeviceType_l(), toString(inDeviceType_l()).c_str());
Andy Hung9b181952019-02-25 14:53:36 -08001097 dprintf(fd, " Audio source: %d (%s)\n", mAudioSource, toString(mAudioSource).c_str());
Eric Laurent81784c32012-11-19 14:55:58 -08001098
Andy Hung2e2c0bb2018-06-11 19:13:11 -07001099 // Dump timestamp statistics for the Thread types that support it.
1100 if (mType == RECORD
1101 || mType == MIXER
1102 || mType == DUPLICATING
Andy Hungf3234512018-07-03 14:51:47 -07001103 || mType == DIRECT
Andy Hung4b7f54f2022-04-28 17:45:28 -07001104 || mType == OFFLOAD
1105 || mType == SPATIALIZER) {
Andy Hung2e2c0bb2018-06-11 19:13:11 -07001106 dprintf(fd, " Timestamp stats: %s\n", mTimestampVerifier.toString().c_str());
Andy Hungab65b182023-09-06 19:41:47 -07001107 dprintf(fd, " Timestamp corrected: %s\n",
1108 isTimestampCorrectionEnabled_l() ? "yes" : "no");
Andy Hung2e2c0bb2018-06-11 19:13:11 -07001109 }
1110
Andy Hung446f4df2019-02-21 12:26:41 -08001111 if (mLastIoBeginNs > 0) { // MMAP may not set this
1112 dprintf(fd, " Last %s occurred (msecs): %lld\n",
1113 isOutput() ? "write" : "read",
1114 (long long) (systemTime() - mLastIoBeginNs) / NANOS_PER_MILLISECOND);
1115 }
1116
1117 if (mProcessTimeMs.getN() > 0) {
1118 dprintf(fd, " Process time ms stats: %s\n", mProcessTimeMs.toString().c_str());
1119 }
1120
1121 if (mIoJitterMs.getN() > 0) {
1122 dprintf(fd, " Hal %s jitter ms stats: %s\n",
1123 isOutput() ? "write" : "read",
1124 mIoJitterMs.toString().c_str());
1125 }
1126
Andy Hunge6c37112019-02-26 17:38:10 -08001127 if (mLatencyMs.getN() > 0) {
1128 dprintf(fd, " Threadloop %s latency stats: %s\n",
1129 isOutput() ? "write" : "read",
1130 mLatencyMs.toString().c_str());
1131 }
Robert Wu06db0a32021-08-10 19:05:34 +00001132
1133 if (mMonopipePipeDepthStats.getN() > 0) {
1134 dprintf(fd, " Monopipe %s pipe depth stats: %s\n",
1135 isOutput() ? "write" : "read",
1136 mMonopipePipeDepthStats.toString().c_str());
1137 }
Eric Laurent81784c32012-11-19 14:55:58 -08001138}
1139
Andy Hungee58e4a2023-07-07 13:47:37 -07001140void ThreadBase::dumpEffectChains_l(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -08001141{
1142 const size_t SIZE = 256;
1143 char buffer[SIZE];
Eric Laurent81784c32012-11-19 14:55:58 -08001144
Marco Nelissenb2208842014-02-07 14:00:50 -08001145 size_t numEffectChains = mEffectChains.size();
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +00001146 snprintf(buffer, SIZE, " %zu Effect Chains\n", numEffectChains);
Eric Laurent81784c32012-11-19 14:55:58 -08001147 write(fd, buffer, strlen(buffer));
1148
Marco Nelissenb2208842014-02-07 14:00:50 -08001149 for (size_t i = 0; i < numEffectChains; ++i) {
Andy Hung116bc262023-06-20 18:56:17 -07001150 sp<IAfEffectChain> chain = mEffectChains[i];
Eric Laurent81784c32012-11-19 14:55:58 -08001151 if (chain != 0) {
1152 chain->dump(fd, args);
1153 }
1154 }
1155}
1156
Andy Hungee58e4a2023-07-07 13:47:37 -07001157void ThreadBase::acquireWakeLock()
Eric Laurent81784c32012-11-19 14:55:58 -08001158{
Andy Hung972bec12023-08-31 16:13:39 -07001159 audio_utils::lock_guard _l(mutex());
Andy Hungdae27702016-10-31 14:01:16 -07001160 acquireWakeLock_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001161}
1162
Andy Hungee58e4a2023-07-07 13:47:37 -07001163String16 ThreadBase::getWakeLockTag()
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001164{
1165 switch (mType) {
Glenn Kastenbcb14862015-03-05 17:11:21 -08001166 case MIXER:
1167 return String16("AudioMix");
1168 case DIRECT:
1169 return String16("AudioDirectOut");
1170 case DUPLICATING:
1171 return String16("AudioDup");
1172 case RECORD:
1173 return String16("AudioIn");
1174 case OFFLOAD:
1175 return String16("AudioOffload");
Andy Hungea840382020-05-05 21:50:17 -07001176 case MMAP_PLAYBACK:
1177 return String16("MmapPlayback");
1178 case MMAP_CAPTURE:
1179 return String16("MmapCapture");
Eric Laurent1c5e2e32021-08-18 18:50:28 +02001180 case SPATIALIZER:
1181 return String16("AudioSpatial");
Glenn Kastenbcb14862015-03-05 17:11:21 -08001182 default:
1183 ALOG_ASSERT(false);
1184 return String16("AudioUnknown");
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001185 }
1186}
1187
Andy Hungee58e4a2023-07-07 13:47:37 -07001188void ThreadBase::acquireWakeLock_l()
Eric Laurent81784c32012-11-19 14:55:58 -08001189{
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001190 getPowerManager_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001191 if (mPowerManager != 0) {
1192 sp<IBinder> binder = new BBinder();
Andy Hungdae27702016-10-31 14:01:16 -07001193 // Uses AID_AUDIOSERVER for wakelock. updateWakeLockUids_l() updates with client uids.
Chris Ye6597d732020-02-28 22:38:25 -08001194 binder::Status status = mPowerManager->acquireWakeLockAsync(binder,
1195 POWERMANAGER_PARTIAL_WAKE_LOCK,
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001196 getWakeLockTag(),
Marco Nelissendcb346b2015-09-09 10:47:29 -07001197 String16("audioserver"),
Chris Ye6597d732020-02-28 22:38:25 -08001198 {} /* workSource */,
1199 {} /* historyTag */);
1200 if (status.isOk()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001201 mWakeLockToken = binder;
1202 }
Chris Ye6597d732020-02-28 22:38:25 -08001203 ALOGV("acquireWakeLock_l() %s status %d", mThreadName, status.exceptionCode());
Eric Laurent81784c32012-11-19 14:55:58 -08001204 }
Wei Jia3f273d12015-11-24 09:06:49 -08001205
Andy Hung3f0c9022016-01-15 17:49:46 -08001206 gBoottime.acquire(mWakeLockToken);
Andy Hung818e7a32016-02-16 18:08:07 -08001207 mTimestamp.mTimebaseOffset[ExtendedTimestamp::TIMEBASE_BOOTTIME] =
1208 gBoottime.getBoottimeOffset();
Eric Laurent81784c32012-11-19 14:55:58 -08001209}
1210
Andy Hungee58e4a2023-07-07 13:47:37 -07001211void ThreadBase::releaseWakeLock()
Eric Laurent81784c32012-11-19 14:55:58 -08001212{
Andy Hung972bec12023-08-31 16:13:39 -07001213 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001214 releaseWakeLock_l();
1215}
1216
Andy Hungee58e4a2023-07-07 13:47:37 -07001217void ThreadBase::releaseWakeLock_l()
Eric Laurent81784c32012-11-19 14:55:58 -08001218{
Andy Hung3f0c9022016-01-15 17:49:46 -08001219 gBoottime.release(mWakeLockToken);
Eric Laurent81784c32012-11-19 14:55:58 -08001220 if (mWakeLockToken != 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -08001221 ALOGV("releaseWakeLock_l() %s", mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08001222 if (mPowerManager != 0) {
Chris Ye6597d732020-02-28 22:38:25 -08001223 mPowerManager->releaseWakeLockAsync(mWakeLockToken, 0);
Eric Laurent81784c32012-11-19 14:55:58 -08001224 }
1225 mWakeLockToken.clear();
1226 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001227}
1228
Andy Hungee58e4a2023-07-07 13:47:37 -07001229void ThreadBase::getPowerManager_l() {
Eric Laurent72e3f392015-05-20 14:43:50 -07001230 if (mSystemReady && mPowerManager == 0) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001231 // use checkService() to avoid blocking if power service is not up yet
1232 sp<IBinder> binder =
1233 defaultServiceManager()->checkService(String16("power"));
1234 if (binder == 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -08001235 ALOGW("Thread %s cannot connect to the power manager service", mThreadName);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001236 } else {
Chris Ye6597d732020-02-28 22:38:25 -08001237 mPowerManager = interface_cast<os::IPowerManager>(binder);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001238 binder->linkToDeath(mDeathRecipient);
1239 }
1240 }
1241}
1242
Andy Hungee58e4a2023-07-07 13:47:37 -07001243void ThreadBase::updateWakeLockUids_l(const SortedVector<uid_t>& uids) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001244 getPowerManager_l();
Andy Hungdae27702016-10-31 14:01:16 -07001245
1246#if !LOG_NDEBUG
1247 std::stringstream s;
Andy Hungd01b0f12016-11-07 16:10:30 -08001248 for (uid_t uid : uids) {
Andy Hungdae27702016-10-31 14:01:16 -07001249 s << uid << " ";
1250 }
1251 ALOGD("updateWakeLockUids_l %s uids:%s", mThreadName, s.str().c_str());
1252#endif
1253
Andy Hung438e7572015-12-14 15:51:17 -08001254 if (mWakeLockToken == NULL) { // token may be NULL if AudioFlinger::systemReady() not called.
1255 if (mSystemReady) {
1256 ALOGE("no wake lock to update, but system ready!");
1257 } else {
1258 ALOGW("no wake lock to update, system not ready yet");
1259 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001260 return;
1261 }
1262 if (mPowerManager != 0) {
Andy Hung1f12a8a2016-11-07 16:10:30 -08001263 std::vector<int> uidsAsInt(uids.begin(), uids.end()); // powermanager expects uids as ints
Chris Ye6597d732020-02-28 22:38:25 -08001264 binder::Status status = mPowerManager->updateWakeLockUidsAsync(
1265 mWakeLockToken, uidsAsInt);
1266 ALOGV("updateWakeLockUids_l() %s status %d", mThreadName, status.exceptionCode());
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001267 }
1268}
1269
Andy Hungee58e4a2023-07-07 13:47:37 -07001270void ThreadBase::clearPowerManager()
Eric Laurent81784c32012-11-19 14:55:58 -08001271{
Andy Hung972bec12023-08-31 16:13:39 -07001272 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001273 releaseWakeLock_l();
1274 mPowerManager.clear();
1275}
1276
Andy Hungee58e4a2023-07-07 13:47:37 -07001277void ThreadBase::updateOutDevices(
jiabinc52b1ff2019-10-31 17:20:42 -07001278 const DeviceDescriptorBaseVector& outDevices __unused)
1279{
1280 ALOGE("%s should only be called in RecordThread", __func__);
1281}
1282
Andy Hungee58e4a2023-07-07 13:47:37 -07001283void ThreadBase::resizeInputBuffer_l(int32_t /* maxSharedAudioHistoryMs */)
Eric Laurentec376dc2021-04-08 20:41:22 +02001284{
1285 ALOGE("%s should only be called in RecordThread", __func__);
1286}
1287
Andy Hungee58e4a2023-07-07 13:47:37 -07001288void ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& /* who */)
Eric Laurent81784c32012-11-19 14:55:58 -08001289{
1290 sp<ThreadBase> thread = mThread.promote();
1291 if (thread != 0) {
1292 thread->clearPowerManager();
1293 }
1294 ALOGW("power manager service died !!!");
1295}
1296
Andy Hungee58e4a2023-07-07 13:47:37 -07001297void ThreadBase::setEffectSuspended_l(
Glenn Kastend848eb42016-03-08 13:42:11 -08001298 const effect_uuid_t *type, bool suspend, audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001299{
Andy Hung116bc262023-06-20 18:56:17 -07001300 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08001301 if (chain != 0) {
1302 if (type != NULL) {
1303 chain->setEffectSuspended_l(type, suspend);
1304 } else {
1305 chain->setEffectSuspendedAll_l(suspend);
1306 }
1307 }
1308
1309 updateSuspendedSessions_l(type, suspend, sessionId);
1310}
1311
Andy Hungee58e4a2023-07-07 13:47:37 -07001312void ThreadBase::checkSuspendOnAddEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08001313{
1314 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
1315 if (index < 0) {
1316 return;
1317 }
1318
1319 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
1320 mSuspendedSessions.valueAt(index);
1321
1322 for (size_t i = 0; i < sessionEffects.size(); i++) {
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07001323 const sp<SuspendedSessionDesc>& desc = sessionEffects.valueAt(i);
Eric Laurent81784c32012-11-19 14:55:58 -08001324 for (int j = 0; j < desc->mRefCount; j++) {
Andy Hung116bc262023-06-20 18:56:17 -07001325 if (sessionEffects.keyAt(i) == IAfEffectChain::kKeyForSuspendAll) {
Eric Laurent81784c32012-11-19 14:55:58 -08001326 chain->setEffectSuspendedAll_l(true);
1327 } else {
1328 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
1329 desc->mType.timeLow);
1330 chain->setEffectSuspended_l(&desc->mType, true);
1331 }
1332 }
1333 }
1334}
1335
Andy Hungee58e4a2023-07-07 13:47:37 -07001336void ThreadBase::updateSuspendedSessions_l(const effect_uuid_t* type,
Eric Laurent81784c32012-11-19 14:55:58 -08001337 bool suspend,
Glenn Kastend848eb42016-03-08 13:42:11 -08001338 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001339{
1340 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
1341
1342 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1343
1344 if (suspend) {
1345 if (index >= 0) {
1346 sessionEffects = mSuspendedSessions.valueAt(index);
1347 } else {
1348 mSuspendedSessions.add(sessionId, sessionEffects);
1349 }
1350 } else {
1351 if (index < 0) {
1352 return;
1353 }
1354 sessionEffects = mSuspendedSessions.valueAt(index);
1355 }
1356
1357
Andy Hung116bc262023-06-20 18:56:17 -07001358 int key = IAfEffectChain::kKeyForSuspendAll;
Eric Laurent81784c32012-11-19 14:55:58 -08001359 if (type != NULL) {
1360 key = type->timeLow;
1361 }
1362 index = sessionEffects.indexOfKey(key);
1363
1364 sp<SuspendedSessionDesc> desc;
1365 if (suspend) {
1366 if (index >= 0) {
1367 desc = sessionEffects.valueAt(index);
1368 } else {
1369 desc = new SuspendedSessionDesc();
1370 if (type != NULL) {
1371 desc->mType = *type;
1372 }
1373 sessionEffects.add(key, desc);
1374 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
1375 }
1376 desc->mRefCount++;
1377 } else {
1378 if (index < 0) {
1379 return;
1380 }
1381 desc = sessionEffects.valueAt(index);
1382 if (--desc->mRefCount == 0) {
1383 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
1384 sessionEffects.removeItemsAt(index);
1385 if (sessionEffects.isEmpty()) {
1386 ALOGV("updateSuspendedSessions_l() restore removing session %d",
1387 sessionId);
1388 mSuspendedSessions.removeItem(sessionId);
1389 }
1390 }
1391 }
1392 if (!sessionEffects.isEmpty()) {
1393 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1394 }
1395}
1396
Andy Hungee58e4a2023-07-07 13:47:37 -07001397void ThreadBase::checkSuspendOnEffectEnabled(bool enabled,
Eric Laurent6b446ce2019-12-13 10:56:31 -08001398 audio_session_t sessionId,
Andy Hung920f6572022-10-06 12:09:49 -07001399 bool threadLocked)
1400NO_THREAD_SAFETY_ANALYSIS // manual locking
1401{
Eric Laurent6b446ce2019-12-13 10:56:31 -08001402 if (!threadLocked) {
Andy Hungc5007f82023-08-29 14:26:09 -07001403 mutex().lock();
Eric Laurent6b446ce2019-12-13 10:56:31 -08001404 }
Eric Laurent81784c32012-11-19 14:55:58 -08001405
Eric Laurent81784c32012-11-19 14:55:58 -08001406 if (mType != RECORD) {
1407 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1408 // another session. This gives the priority to well behaved effect control panels
1409 // and applications not using global effects.
1410 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
1411 // global effects
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001412 if (!audio_is_global_session(sessionId)) {
Eric Laurent81784c32012-11-19 14:55:58 -08001413 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1414 }
1415 }
1416
Eric Laurent6b446ce2019-12-13 10:56:31 -08001417 if (!threadLocked) {
Andy Hungc5007f82023-08-29 14:26:09 -07001418 mutex().unlock();
Eric Laurent81784c32012-11-19 14:55:58 -08001419 }
1420}
1421
Andy Hungc5007f82023-08-29 14:26:09 -07001422// checkEffectCompatibility_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07001423status_t RecordThread::checkEffectCompatibility_l(
Eric Laurent4c415062016-06-17 16:14:16 -07001424 const effect_descriptor_t *desc, audio_session_t sessionId)
1425{
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001426 // No global output effect sessions on record threads
1427 if (sessionId == AUDIO_SESSION_OUTPUT_MIX
1428 || sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Eric Laurent4c415062016-06-17 16:14:16 -07001429 ALOGW("checkEffectCompatibility_l(): global effect %s on record thread %s",
1430 desc->name, mThreadName);
1431 return BAD_VALUE;
1432 }
1433 // only pre processing effects on record thread
1434 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC) {
1435 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on record thread %s",
1436 desc->name, mThreadName);
1437 return BAD_VALUE;
1438 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001439
1440 // always allow effects without processing load or latency
1441 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1442 return NO_ERROR;
1443 }
1444
Eric Laurent4c415062016-06-17 16:14:16 -07001445 audio_input_flags_t flags = mInput->flags;
1446 if (hasFastCapture() || (flags & AUDIO_INPUT_FLAG_FAST)) {
1447 if (flags & AUDIO_INPUT_FLAG_RAW) {
1448 ALOGW("checkEffectCompatibility_l(): effect %s on record thread %s in raw mode",
1449 desc->name, mThreadName);
1450 return BAD_VALUE;
1451 }
1452 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1453 ALOGW("checkEffectCompatibility_l(): non HW effect %s on record thread %s in fast mode",
1454 desc->name, mThreadName);
1455 return BAD_VALUE;
1456 }
1457 }
jiabineb3bda02020-06-30 14:07:03 -07001458
Andy Hung116bc262023-06-20 18:56:17 -07001459 if (IAfEffectModule::isHapticGenerator(&desc->type)) {
jiabineb3bda02020-06-30 14:07:03 -07001460 ALOGE("%s(): HapticGenerator is not supported in RecordThread", __func__);
1461 return BAD_VALUE;
1462 }
Eric Laurent4c415062016-06-17 16:14:16 -07001463 return NO_ERROR;
1464}
1465
Andy Hungc5007f82023-08-29 14:26:09 -07001466// checkEffectCompatibility_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07001467status_t PlaybackThread::checkEffectCompatibility_l(
Eric Laurent4c415062016-06-17 16:14:16 -07001468 const effect_descriptor_t *desc, audio_session_t sessionId)
1469{
1470 // no preprocessing on playback threads
1471 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001472 ALOGW("%s: pre processing effect %s created on playback"
1473 " thread %s", __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001474 return BAD_VALUE;
1475 }
1476
Eric Laurent3e4de772017-07-16 16:55:08 -07001477 // always allow effects without processing load or latency
1478 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1479 return NO_ERROR;
1480 }
1481
Andy Hung116bc262023-06-20 18:56:17 -07001482 if (IAfEffectModule::isHapticGenerator(&desc->type) && mHapticChannelCount == 0) {
jiabineb3bda02020-06-30 14:07:03 -07001483 ALOGW("%s: thread doesn't support haptic playback while the effect is HapticGenerator",
1484 __func__);
1485 return BAD_VALUE;
1486 }
1487
Eric Laurent4eb45d02023-12-20 12:07:17 +01001488 if (IAfEffectModule::isSpatializer(&desc->type)
Eric Laurentf690c462021-09-17 14:47:03 +02001489 && mType != SPATIALIZER) {
1490 ALOGW("%s: attempt to create a spatializer effect on a thread of type %d",
1491 __func__, mType);
1492 return BAD_VALUE;
1493 }
1494
Eric Laurent4c415062016-06-17 16:14:16 -07001495 switch (mType) {
1496 case MIXER: {
Eric Laurent4c415062016-06-17 16:14:16 -07001497 audio_output_flags_t flags = mOutput->flags;
1498 if (hasFastMixer() || (flags & AUDIO_OUTPUT_FLAG_FAST)) {
1499 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1500 // global effects are applied only to non fast tracks if they are SW
1501 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1502 break;
1503 }
1504 } else if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1505 // only post processing on output stage session
1506 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001507 ALOGW("%s: non post processing effect %s not allowed on output stage session",
1508 __func__, desc->name);
Eric Laurent4c415062016-06-17 16:14:16 -07001509 return BAD_VALUE;
1510 }
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001511 } else if (sessionId == AUDIO_SESSION_DEVICE) {
1512 // only post processing on output stage session
1513 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001514 ALOGW("%s: non post processing effect %s not allowed on device session",
1515 __func__, desc->name);
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001516 return BAD_VALUE;
1517 }
Eric Laurent4c415062016-06-17 16:14:16 -07001518 } else {
1519 // no restriction on effects applied on non fast tracks
1520 if ((hasAudioSession_l(sessionId) & ThreadBase::FAST_SESSION) == 0) {
1521 break;
1522 }
1523 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001524
Eric Laurent4c415062016-06-17 16:14:16 -07001525 if (flags & AUDIO_OUTPUT_FLAG_RAW) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001526 ALOGW("%s: effect %s on playback thread in raw mode", __func__, desc->name);
Eric Laurent4c415062016-06-17 16:14:16 -07001527 return BAD_VALUE;
1528 }
1529 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001530 ALOGW("%s: non HW effect %s on playback thread in fast mode",
1531 __func__, desc->name);
Eric Laurent4c415062016-06-17 16:14:16 -07001532 return BAD_VALUE;
1533 }
1534 }
1535 } break;
1536 case OFFLOAD:
Jean-Michel Trivi773ee952016-07-11 16:53:18 -07001537 // nothing actionable on offload threads, if the effect:
1538 // - is offloadable: the effect can be created
1539 // - is NOT offloadable: the effect should still be created, but EffectHandle::enable()
1540 // will take care of invalidating the tracks of the thread
Eric Laurent4c415062016-06-17 16:14:16 -07001541 break;
1542 case DIRECT:
1543 // Reject any effect on Direct output threads for now, since the format of
1544 // mSinkBuffer is not guaranteed to be compatible with effect processing (PCM 16 stereo).
Eric Laurentb62d0362021-10-26 17:40:18 +02001545 ALOGW("%s: effect %s on DIRECT output thread %s",
1546 __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001547 return BAD_VALUE;
1548 case DUPLICATING:
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001549 if (audio_is_global_session(sessionId)) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001550 ALOGW("%s: global effect %s on DUPLICATING thread %s",
1551 __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001552 return BAD_VALUE;
1553 }
1554 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001555 ALOGW("%s: post processing effect %s on DUPLICATING thread %s",
1556 __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001557 return BAD_VALUE;
1558 }
1559 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) != 0) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001560 ALOGW("%s: HW tunneled effect %s on DUPLICATING thread %s",
1561 __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001562 return BAD_VALUE;
1563 }
1564 break;
Eric Laurent1c5e2e32021-08-18 18:50:28 +02001565 case SPATIALIZER:
Eric Laurentb62d0362021-10-26 17:40:18 +02001566 // Global effects (AUDIO_SESSION_OUTPUT_MIX) are not supported on spatializer mixer
1567 // as there is no common accumulation buffer for sptialized and non sptialized tracks.
1568 // Post processing effects (AUDIO_SESSION_OUTPUT_STAGE or AUDIO_SESSION_DEVICE)
1569 // are supported and added after the spatializer.
1570 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1571 ALOGW("%s: global effect %s not supported on spatializer thread %s",
1572 __func__, desc->name, mThreadName);
Eric Laurentb3f315a2021-07-13 15:09:05 +02001573 return BAD_VALUE;
Eric Laurentb62d0362021-10-26 17:40:18 +02001574 } else if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1575 // only post processing , downmixer or spatializer effects on output stage session
Eric Laurent4eb45d02023-12-20 12:07:17 +01001576 if (IAfEffectModule::isSpatializer(&desc->type)
Eric Laurentb62d0362021-10-26 17:40:18 +02001577 || memcmp(&desc->type, EFFECT_UIID_DOWNMIX, sizeof(effect_uuid_t)) == 0) {
1578 break;
1579 }
1580 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
1581 ALOGW("%s: non post processing effect %s not allowed on output stage session",
1582 __func__, desc->name);
1583 return BAD_VALUE;
1584 }
1585 } else if (sessionId == AUDIO_SESSION_DEVICE) {
1586 // only post processing on output stage session
1587 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
1588 ALOGW("%s: non post processing effect %s not allowed on device session",
1589 __func__, desc->name);
1590 return BAD_VALUE;
1591 }
Eric Laurentb3f315a2021-07-13 15:09:05 +02001592 }
1593 break;
jiabinc658e452022-10-21 20:52:21 +00001594 case BIT_PERFECT:
1595 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) != 0) {
1596 // Allow HW accelerated effects of tunnel type
1597 break;
1598 }
1599 // As bit-perfect tracks will not be allowed to apply audio effect that will touch the audio
1600 // data, effects will not be allowed on 1) global effects (AUDIO_SESSION_OUTPUT_MIX),
1601 // 2) post-processing effects (AUDIO_SESSION_OUTPUT_STAGE or AUDIO_SESSION_DEVICE) and
1602 // 3) there is any bit-perfect track with the given session id.
1603 if (sessionId == AUDIO_SESSION_OUTPUT_MIX || sessionId == AUDIO_SESSION_OUTPUT_STAGE ||
1604 sessionId == AUDIO_SESSION_DEVICE) {
1605 ALOGW("%s: effect %s not supported on bit-perfect thread %s",
1606 __func__, desc->name, mThreadName);
1607 return BAD_VALUE;
1608 } else if ((hasAudioSession_l(sessionId) & ThreadBase::BIT_PERFECT_SESSION) != 0) {
1609 ALOGW("%s: effect %s not supported as there is a bit-perfect track with session as %d",
1610 __func__, desc->name, sessionId);
1611 return BAD_VALUE;
1612 }
1613 break;
Eric Laurent4c415062016-06-17 16:14:16 -07001614 default:
1615 LOG_ALWAYS_FATAL("checkEffectCompatibility_l(): wrong thread type %d", mType);
1616 }
1617
1618 return NO_ERROR;
1619}
1620
Andy Hungc5007f82023-08-29 14:26:09 -07001621// ThreadBase::createEffect_l() must be called with AudioFlinger::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07001622sp<IAfEffectHandle> ThreadBase::createEffect_l(
Andy Hung88035ac2023-06-27 17:05:02 -07001623 const sp<Client>& client,
Eric Laurent81784c32012-11-19 14:55:58 -08001624 const sp<IEffectClient>& effectClient,
1625 int32_t priority,
Glenn Kastend848eb42016-03-08 13:42:11 -08001626 audio_session_t sessionId,
Eric Laurent81784c32012-11-19 14:55:58 -08001627 effect_descriptor_t *desc,
1628 int *enabled,
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001629 status_t *status,
Eric Laurent2fe0acd2020-03-13 14:30:46 -07001630 bool pinned,
Eric Laurentde8caf42021-08-11 17:19:25 +02001631 bool probe,
1632 bool notifyFramesProcessed)
Eric Laurent81784c32012-11-19 14:55:58 -08001633{
Andy Hung116bc262023-06-20 18:56:17 -07001634 sp<IAfEffectModule> effect;
1635 sp<IAfEffectHandle> handle;
Eric Laurent81784c32012-11-19 14:55:58 -08001636 status_t lStatus;
Andy Hung116bc262023-06-20 18:56:17 -07001637 sp<IAfEffectChain> chain;
Eric Laurent81784c32012-11-19 14:55:58 -08001638 bool chainCreated = false;
1639 bool effectCreated = false;
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001640 audio_unique_id_t effectId = AUDIO_UNIQUE_ID_USE_UNSPECIFIED;
Eric Laurent81784c32012-11-19 14:55:58 -08001641
1642 lStatus = initCheck();
1643 if (lStatus != NO_ERROR) {
1644 ALOGW("createEffect_l() Audio driver not initialized.");
1645 goto Exit;
1646 }
1647
Eric Laurent81784c32012-11-19 14:55:58 -08001648 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
1649
Andy Hungc5007f82023-08-29 14:26:09 -07001650 { // scope for mutex()
Andy Hung972bec12023-08-31 16:13:39 -07001651 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001652
Eric Laurent4c415062016-06-17 16:14:16 -07001653 lStatus = checkEffectCompatibility_l(desc, sessionId);
Eric Laurent2fe0acd2020-03-13 14:30:46 -07001654 if (probe || lStatus != NO_ERROR) {
Eric Laurent4c415062016-06-17 16:14:16 -07001655 goto Exit;
1656 }
1657
Eric Laurent81784c32012-11-19 14:55:58 -08001658 // check for existing effect chain with the requested audio session
1659 chain = getEffectChain_l(sessionId);
1660 if (chain == 0) {
1661 // create a new chain for this session
1662 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
Andy Hung116bc262023-06-20 18:56:17 -07001663 chain = IAfEffectChain::create(this, sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08001664 addEffectChain_l(chain);
1665 chain->setStrategy(getStrategyForSession_l(sessionId));
1666 chainCreated = true;
1667 } else {
1668 effect = chain->getEffectFromDesc_l(desc);
1669 }
1670
1671 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
1672
1673 if (effect == 0) {
Andy Hung583043b2023-07-17 17:05:00 -07001674 effectId = mAfThreadCallback->nextUniqueId(AUDIO_UNIQUE_ID_USE_EFFECT);
Eric Laurent81784c32012-11-19 14:55:58 -08001675 // create a new effect module if none present in the chain
Eric Laurent6b446ce2019-12-13 10:56:31 -08001676 lStatus = chain->createEffect_l(effect, desc, effectId, sessionId, pinned);
Eric Laurent81784c32012-11-19 14:55:58 -08001677 if (lStatus != NO_ERROR) {
1678 goto Exit;
1679 }
1680 effectCreated = true;
1681
jiabinc52b1ff2019-10-31 17:20:42 -07001682 // FIXME: use vector of device and address when effect interface is ready.
jiabin8f278ee2019-11-11 12:16:27 -08001683 effect->setDevices(outDeviceTypeAddrs());
1684 effect->setInputDevice(inDeviceTypeAddr());
Andy Hung583043b2023-07-17 17:05:00 -07001685 effect->setMode(mAfThreadCallback->getMode());
Eric Laurent81784c32012-11-19 14:55:58 -08001686 effect->setAudioSource(mAudioSource);
1687 }
jiabin1319f5a2021-03-30 22:21:24 +00001688 if (effect->isHapticGenerator()) {
1689 // TODO(b/184194057): Use the vibrator information from the vibrator that will be used
1690 // for the HapticGenerator.
Lais Andradebc3f37a2021-07-02 00:13:19 +01001691 const std::optional<media::AudioVibratorInfo> defaultVibratorInfo =
Andy Hung583043b2023-07-17 17:05:00 -07001692 std::move(mAfThreadCallback->getDefaultVibratorInfo_l());
Lais Andradebc3f37a2021-07-02 00:13:19 +01001693 if (defaultVibratorInfo) {
jiabin1319f5a2021-03-30 22:21:24 +00001694 // Only set the vibrator info when it is a valid one.
Shunkai Yaod125e402024-01-20 03:19:06 +00001695 effect->setVibratorInfo_l(*defaultVibratorInfo);
jiabin1319f5a2021-03-30 22:21:24 +00001696 }
1697 }
Eric Laurent81784c32012-11-19 14:55:58 -08001698 // create effect handle and connect it to effect module
Andy Hung116bc262023-06-20 18:56:17 -07001699 handle = IAfEffectHandle::create(
1700 effect, client, effectClient, priority, notifyFramesProcessed);
Glenn Kastene75da402013-11-20 13:54:52 -08001701 lStatus = handle->initCheck();
1702 if (lStatus == OK) {
1703 lStatus = effect->addHandle(handle.get());
Eric Laurentb3f315a2021-07-13 15:09:05 +02001704 sendCheckOutputStageEffectsEvent_l();
Glenn Kastene75da402013-11-20 13:54:52 -08001705 }
Eric Laurent81784c32012-11-19 14:55:58 -08001706 if (enabled != NULL) {
1707 *enabled = (int)effect->isEnabled();
1708 }
1709 }
1710
1711Exit:
Eric Laurent2fe0acd2020-03-13 14:30:46 -07001712 if (!probe && lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Andy Hung972bec12023-08-31 16:13:39 -07001713 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001714 if (effectCreated) {
1715 chain->removeEffect_l(effect);
1716 }
Eric Laurent81784c32012-11-19 14:55:58 -08001717 if (chainCreated) {
1718 removeEffectChain_l(chain);
1719 }
haobo101735295ff7b0d2017-03-17 17:44:03 +08001720 // handle must be cleared by caller to avoid deadlock.
Eric Laurent81784c32012-11-19 14:55:58 -08001721 }
1722
Glenn Kasten9156ef32013-08-06 15:39:08 -07001723 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001724 return handle;
1725}
1726
Andy Hungee58e4a2023-07-07 13:47:37 -07001727void ThreadBase::disconnectEffectHandle(IAfEffectHandle* handle,
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001728 bool unpinIfLast)
1729{
1730 bool remove = false;
Andy Hung116bc262023-06-20 18:56:17 -07001731 sp<IAfEffectModule> effect;
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001732 {
Andy Hung972bec12023-08-31 16:13:39 -07001733 audio_utils::lock_guard _l(mutex());
Andy Hung116bc262023-06-20 18:56:17 -07001734 sp<IAfEffectBase> effectBase = handle->effect().promote();
Eric Laurent41709552019-12-16 19:34:05 -08001735 if (effectBase == nullptr) {
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001736 return;
1737 }
Eric Laurentb82e6b72019-11-22 17:25:04 -08001738 effect = effectBase->asEffectModule();
1739 if (effect == nullptr) {
1740 return;
1741 }
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001742 // restore suspended effects if the disconnected handle was enabled and the last one.
1743 remove = (effect->removeHandle(handle) == 0) && (!effect->isPinned() || unpinIfLast);
1744 if (remove) {
1745 removeEffect_l(effect, true);
1746 }
Eric Laurentb3f315a2021-07-13 15:09:05 +02001747 sendCheckOutputStageEffectsEvent_l();
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001748 }
1749 if (remove) {
Andy Hung583043b2023-07-17 17:05:00 -07001750 mAfThreadCallback->updateOrphanEffectChains(effect);
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001751 if (handle->enabled()) {
Eric Laurent6b446ce2019-12-13 10:56:31 -08001752 effect->checkSuspendOnEffectEnabled(false, false /*threadLocked*/);
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001753 }
1754 }
1755}
1756
Andy Hungee58e4a2023-07-07 13:47:37 -07001757void ThreadBase::onEffectEnable(const sp<IAfEffectModule>& effect) {
Andy Hungea840382020-05-05 21:50:17 -07001758 if (isOffloadOrMmap()) {
Andy Hung972bec12023-08-31 16:13:39 -07001759 audio_utils::lock_guard _l(mutex());
Eric Laurent6b446ce2019-12-13 10:56:31 -08001760 broadcast_l();
1761 }
1762 if (!effect->isOffloadable()) {
1763 if (mType == ThreadBase::OFFLOAD) {
1764 PlaybackThread *t = (PlaybackThread *)this;
1765 t->invalidateTracks(AUDIO_STREAM_MUSIC);
1766 }
1767 if (effect->sessionId() == AUDIO_SESSION_OUTPUT_MIX) {
Andy Hung583043b2023-07-17 17:05:00 -07001768 mAfThreadCallback->onNonOffloadableGlobalEffectEnable();
Eric Laurent6b446ce2019-12-13 10:56:31 -08001769 }
1770 }
1771}
1772
Andy Hungee58e4a2023-07-07 13:47:37 -07001773void ThreadBase::onEffectDisable() {
Andy Hungea840382020-05-05 21:50:17 -07001774 if (isOffloadOrMmap()) {
Andy Hung972bec12023-08-31 16:13:39 -07001775 audio_utils::lock_guard _l(mutex());
Eric Laurent6b446ce2019-12-13 10:56:31 -08001776 broadcast_l();
1777 }
1778}
1779
Andy Hungee58e4a2023-07-07 13:47:37 -07001780sp<IAfEffectModule> ThreadBase::getEffect(audio_session_t sessionId,
Andy Hung440901d2023-06-29 21:19:25 -07001781 int effectId) const
Eric Laurent81784c32012-11-19 14:55:58 -08001782{
Andy Hung972bec12023-08-31 16:13:39 -07001783 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001784 return getEffect_l(sessionId, effectId);
1785}
1786
Andy Hungee58e4a2023-07-07 13:47:37 -07001787sp<IAfEffectModule> ThreadBase::getEffect_l(audio_session_t sessionId,
Andy Hung440901d2023-06-29 21:19:25 -07001788 int effectId) const
Eric Laurent81784c32012-11-19 14:55:58 -08001789{
Andy Hung116bc262023-06-20 18:56:17 -07001790 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08001791 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
1792}
1793
Andy Hungee58e4a2023-07-07 13:47:37 -07001794std::vector<int> ThreadBase::getEffectIds_l(audio_session_t sessionId) const
Eric Laurent6c796322019-04-09 14:13:17 -07001795{
Andy Hung116bc262023-06-20 18:56:17 -07001796 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Shunkai Yaod125e402024-01-20 03:19:06 +00001797 return chain != nullptr ? chain->getEffectIds_l() : std::vector<int>{};
Eric Laurent6c796322019-04-09 14:13:17 -07001798}
1799
Andy Hung972bec12023-08-31 16:13:39 -07001800// PlaybackThread::addEffect_ll() must be called with AudioFlinger::mutex() and
1801// ThreadBase::mutex() held
1802status_t ThreadBase::addEffect_ll(const sp<IAfEffectModule>& effect)
Eric Laurent81784c32012-11-19 14:55:58 -08001803{
1804 // check for existing effect chain with the requested audio session
Glenn Kastend848eb42016-03-08 13:42:11 -08001805 audio_session_t sessionId = effect->sessionId();
Andy Hung116bc262023-06-20 18:56:17 -07001806 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08001807 bool chainCreated = false;
1808
Eric Laurent5baf2af2013-09-12 17:37:00 -07001809 ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(),
Andy Hung972bec12023-08-31 16:13:39 -07001810 "%s: on offloaded thread %p: effect %s does not support offload flags %#x",
1811 __func__, this, effect->desc().name, effect->desc().flags);
Eric Laurent5baf2af2013-09-12 17:37:00 -07001812
Eric Laurent81784c32012-11-19 14:55:58 -08001813 if (chain == 0) {
1814 // create a new chain for this session
Andy Hung972bec12023-08-31 16:13:39 -07001815 ALOGV("%s: new effect chain for session %d", __func__, sessionId);
Andy Hung116bc262023-06-20 18:56:17 -07001816 chain = IAfEffectChain::create(this, sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08001817 addEffectChain_l(chain);
1818 chain->setStrategy(getStrategyForSession_l(sessionId));
1819 chainCreated = true;
1820 }
Andy Hung972bec12023-08-31 16:13:39 -07001821 ALOGV("%s: %p chain %p effect %p", __func__, this, chain.get(), effect.get());
Eric Laurent81784c32012-11-19 14:55:58 -08001822
1823 if (chain->getEffectFromId_l(effect->id()) != 0) {
Andy Hung972bec12023-08-31 16:13:39 -07001824 ALOGW("%s: %p effect %s already present in chain %p",
1825 __func__, this, effect->desc().name, chain.get());
Eric Laurent81784c32012-11-19 14:55:58 -08001826 return BAD_VALUE;
1827 }
1828
Shunkai Yaod125e402024-01-20 03:19:06 +00001829 effect->setOffloaded_l(mType == OFFLOAD, mId);
Eric Laurent5baf2af2013-09-12 17:37:00 -07001830
Eric Laurent81784c32012-11-19 14:55:58 -08001831 status_t status = chain->addEffect_l(effect);
1832 if (status != NO_ERROR) {
1833 if (chainCreated) {
1834 removeEffectChain_l(chain);
1835 }
1836 return status;
1837 }
1838
jiabin8f278ee2019-11-11 12:16:27 -08001839 effect->setDevices(outDeviceTypeAddrs());
1840 effect->setInputDevice(inDeviceTypeAddr());
Andy Hung583043b2023-07-17 17:05:00 -07001841 effect->setMode(mAfThreadCallback->getMode());
Eric Laurent81784c32012-11-19 14:55:58 -08001842 effect->setAudioSource(mAudioSource);
Eric Laurentd8365c52017-07-16 15:27:05 -07001843
Eric Laurent81784c32012-11-19 14:55:58 -08001844 return NO_ERROR;
1845}
1846
Andy Hungee58e4a2023-07-07 13:47:37 -07001847void ThreadBase::removeEffect_l(const sp<IAfEffectModule>& effect, bool release) {
Eric Laurent81784c32012-11-19 14:55:58 -08001848
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001849 ALOGV("%s %p effect %p", __FUNCTION__, this, effect.get());
Eric Laurent81784c32012-11-19 14:55:58 -08001850 effect_descriptor_t desc = effect->desc();
1851 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
1852 detachAuxEffect_l(effect->id());
1853 }
1854
Andy Hung116bc262023-06-20 18:56:17 -07001855 sp<IAfEffectChain> chain = effect->getCallback()->chain().promote();
Eric Laurent81784c32012-11-19 14:55:58 -08001856 if (chain != 0) {
1857 // remove effect chain if removing last effect
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001858 if (chain->removeEffect_l(effect, release) == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08001859 removeEffectChain_l(chain);
1860 }
1861 } else {
1862 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
1863 }
1864}
1865
Shunkai Yaof4847652024-01-12 00:25:20 +00001866void ThreadBase::lockEffectChains_l(Vector<sp<IAfEffectChain>>& effectChains)
1867 NO_THREAD_SAFETY_ANALYSIS // calls EffectChain::lock()
Eric Laurent81784c32012-11-19 14:55:58 -08001868{
1869 effectChains = mEffectChains;
Shunkai Yaof4847652024-01-12 00:25:20 +00001870 for (const auto& effectChain : effectChains) {
1871 effectChain->mutex().lock();
Eric Laurent81784c32012-11-19 14:55:58 -08001872 }
1873}
1874
Shunkai Yaof4847652024-01-12 00:25:20 +00001875void ThreadBase::unlockEffectChains(const Vector<sp<IAfEffectChain>>& effectChains)
1876 NO_THREAD_SAFETY_ANALYSIS // calls EffectChain::unlock()
Eric Laurent81784c32012-11-19 14:55:58 -08001877{
Shunkai Yaof4847652024-01-12 00:25:20 +00001878 for (const auto& effectChain : effectChains) {
1879 effectChain->mutex().unlock();
Eric Laurent81784c32012-11-19 14:55:58 -08001880 }
1881}
1882
Andy Hungee58e4a2023-07-07 13:47:37 -07001883sp<IAfEffectChain> ThreadBase::getEffectChain(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08001884{
Andy Hung972bec12023-08-31 16:13:39 -07001885 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001886 return getEffectChain_l(sessionId);
1887}
1888
Andy Hungee58e4a2023-07-07 13:47:37 -07001889sp<IAfEffectChain> ThreadBase::getEffectChain_l(audio_session_t sessionId)
Glenn Kastend848eb42016-03-08 13:42:11 -08001890 const
Eric Laurent81784c32012-11-19 14:55:58 -08001891{
1892 size_t size = mEffectChains.size();
1893 for (size_t i = 0; i < size; i++) {
1894 if (mEffectChains[i]->sessionId() == sessionId) {
1895 return mEffectChains[i];
1896 }
1897 }
1898 return 0;
1899}
1900
Andy Hungee58e4a2023-07-07 13:47:37 -07001901void ThreadBase::setMode(audio_mode_t mode)
Eric Laurent81784c32012-11-19 14:55:58 -08001902{
Andy Hung972bec12023-08-31 16:13:39 -07001903 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001904 size_t size = mEffectChains.size();
1905 for (size_t i = 0; i < size; i++) {
1906 mEffectChains[i]->setMode_l(mode);
1907 }
1908}
1909
Andy Hungee58e4a2023-07-07 13:47:37 -07001910void ThreadBase::toAudioPortConfig(struct audio_port_config* config)
Eric Laurent83b88082014-06-20 18:31:16 -07001911{
1912 config->type = AUDIO_PORT_TYPE_MIX;
1913 config->ext.mix.handle = mId;
1914 config->sample_rate = mSampleRate;
Mikhail Naganov88d54da2023-09-11 11:53:50 -07001915 config->format = mHALFormat;
Eric Laurent83b88082014-06-20 18:31:16 -07001916 config->channel_mask = mChannelMask;
1917 config->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
1918 AUDIO_PORT_CONFIG_FORMAT;
1919}
1920
Andy Hungee58e4a2023-07-07 13:47:37 -07001921void ThreadBase::systemReady()
Eric Laurent72e3f392015-05-20 14:43:50 -07001922{
Andy Hung972bec12023-08-31 16:13:39 -07001923 audio_utils::lock_guard _l(mutex());
Eric Laurent72e3f392015-05-20 14:43:50 -07001924 if (mSystemReady) {
1925 return;
1926 }
1927 mSystemReady = true;
1928
1929 for (size_t i = 0; i < mPendingConfigEvents.size(); i++) {
1930 sendConfigEvent_l(mPendingConfigEvents.editItemAt(i));
1931 }
1932 mPendingConfigEvents.clear();
1933}
1934
Andy Hungdae27702016-10-31 14:01:16 -07001935template <typename T>
Andy Hungee58e4a2023-07-07 13:47:37 -07001936ssize_t ThreadBase::ActiveTracks<T>::add(const sp<T>& track) {
Andy Hungdae27702016-10-31 14:01:16 -07001937 ssize_t index = mActiveTracks.indexOf(track);
1938 if (index >= 0) {
1939 ALOGW("ActiveTracks<T>::add track %p already there", track.get());
1940 return index;
1941 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001942 logTrack("add", track);
Andy Hungdae27702016-10-31 14:01:16 -07001943 mActiveTracksGeneration++;
1944 mLatestActiveTrack = track;
Atneya Nair166663a2023-06-27 19:16:24 -07001945 track->beginBatteryAttribution();
Kevin Rocard069c2712018-03-29 19:09:14 -07001946 mHasChanged = true;
Andy Hungdae27702016-10-31 14:01:16 -07001947 return mActiveTracks.add(track);
1948}
1949
1950template <typename T>
Andy Hungee58e4a2023-07-07 13:47:37 -07001951ssize_t ThreadBase::ActiveTracks<T>::remove(const sp<T>& track) {
Andy Hungdae27702016-10-31 14:01:16 -07001952 ssize_t index = mActiveTracks.remove(track);
1953 if (index < 0) {
1954 ALOGW("ActiveTracks<T>::remove nonexistent track %p", track.get());
1955 return index;
1956 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001957 logTrack("remove", track);
Andy Hungdae27702016-10-31 14:01:16 -07001958 mActiveTracksGeneration++;
Atneya Nair166663a2023-06-27 19:16:24 -07001959 track->endBatteryAttribution();
Andy Hungdae27702016-10-31 14:01:16 -07001960 // mLatestActiveTrack is not cleared even if is the same as track.
Kevin Rocard069c2712018-03-29 19:09:14 -07001961 mHasChanged = true;
Andy Hung8946a282018-04-19 20:04:56 -07001962#ifdef TEE_SINK
1963 track->dumpTee(-1 /* fd */, "_REMOVE");
1964#endif
Andy Hungc2b11cb2020-04-22 09:04:01 -07001965 track->logEndInterval(); // log to MediaMetrics
Andy Hungdae27702016-10-31 14:01:16 -07001966 return index;
1967}
1968
1969template <typename T>
Andy Hungee58e4a2023-07-07 13:47:37 -07001970void ThreadBase::ActiveTracks<T>::clear() {
Andy Hungdae27702016-10-31 14:01:16 -07001971 for (const sp<T> &track : mActiveTracks) {
Atneya Nair166663a2023-06-27 19:16:24 -07001972 track->endBatteryAttribution();
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001973 logTrack("clear", track);
Andy Hungdae27702016-10-31 14:01:16 -07001974 }
1975 mLastActiveTracksGeneration = mActiveTracksGeneration;
Kevin Rocard069c2712018-03-29 19:09:14 -07001976 if (!mActiveTracks.empty()) { mHasChanged = true; }
Andy Hungdae27702016-10-31 14:01:16 -07001977 mActiveTracks.clear();
1978 mLatestActiveTrack.clear();
Andy Hungdae27702016-10-31 14:01:16 -07001979}
1980
1981template <typename T>
Andy Hungab65b182023-09-06 19:41:47 -07001982void ThreadBase::ActiveTracks<T>::updatePowerState_l(
Andy Hung920f6572022-10-06 12:09:49 -07001983 const sp<ThreadBase>& thread, bool force) {
Andy Hungdae27702016-10-31 14:01:16 -07001984 // Updates ActiveTracks client uids to the thread wakelock.
1985 if (mActiveTracksGeneration != mLastActiveTracksGeneration || force) {
1986 thread->updateWakeLockUids_l(getWakeLockUids());
1987 mLastActiveTracksGeneration = mActiveTracksGeneration;
1988 }
Andy Hungdae27702016-10-31 14:01:16 -07001989}
Eric Laurent83b88082014-06-20 18:31:16 -07001990
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001991template <typename T>
Andy Hungee58e4a2023-07-07 13:47:37 -07001992bool ThreadBase::ActiveTracks<T>::readAndClearHasChanged() {
Jasmine Chaeaa10e42021-05-11 10:11:14 +08001993 bool hasChanged = mHasChanged;
Kevin Rocard069c2712018-03-29 19:09:14 -07001994 mHasChanged = false;
Jasmine Chaeaa10e42021-05-11 10:11:14 +08001995
1996 for (const sp<T> &track : mActiveTracks) {
1997 // Do not short-circuit as all hasChanged states must be reset
1998 // as all the metadata are going to be sent
1999 hasChanged |= track->readAndClearHasChanged();
2000 }
Kevin Rocard069c2712018-03-29 19:09:14 -07002001 return hasChanged;
2002}
2003
2004template <typename T>
Andy Hungee58e4a2023-07-07 13:47:37 -07002005void ThreadBase::ActiveTracks<T>::logTrack(
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002006 const char *funcName, const sp<T> &track) const {
2007 if (mLocalLog != nullptr) {
2008 String8 result;
2009 track->appendDump(result, false /* active */);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00002010 mLocalLog->log("AT::%-10s(%p) %s", funcName, track.get(), result.c_str());
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002011 }
2012}
2013
Andy Hungee58e4a2023-07-07 13:47:37 -07002014void ThreadBase::broadcast_l()
Eric Laurent6acd1d42017-01-04 14:23:29 -08002015{
2016 // Thread could be blocked waiting for async
2017 // so signal it to handle state changes immediately
2018 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
2019 // be lost so we also flag to prevent it blocking on mWaitWorkCV
2020 mSignalPending = true;
Andy Hungc5007f82023-08-29 14:26:09 -07002021 mWaitWorkCV.notify_all();
Eric Laurent6acd1d42017-01-04 14:23:29 -08002022}
2023
Andy Hungd0979812019-02-21 15:51:44 -08002024// Call only from threadLoop() or when it is idle.
2025// Do not call from high performance code as this may do binder rpc to the MediaMetrics service.
Andy Hungee58e4a2023-07-07 13:47:37 -07002026void ThreadBase::sendStatistics(bool force)
Andy Hungab65b182023-09-06 19:41:47 -07002027NO_THREAD_SAFETY_ANALYSIS
Andy Hungd0979812019-02-21 15:51:44 -08002028{
2029 // Do not log if we have no stats.
2030 // We choose the timestamp verifier because it is the most likely item to be present.
2031 const int64_t nstats = mTimestampVerifier.getN() - mLastRecordedTimestampVerifierN;
2032 if (nstats == 0) {
2033 return;
2034 }
2035
2036 // Don't log more frequently than once per 12 hours.
2037 // We use BOOTTIME to include suspend time.
2038 const int64_t timeNs = systemTime(SYSTEM_TIME_BOOTTIME);
2039 const int64_t sinceNs = timeNs - mLastRecordedTimeNs; // ok if mLastRecordedTimeNs = 0
2040 if (!force && sinceNs <= 12 * NANOS_PER_HOUR) {
2041 return;
2042 }
2043
2044 mLastRecordedTimestampVerifierN = mTimestampVerifier.getN();
2045 mLastRecordedTimeNs = timeNs;
2046
Ray Essickf27e9872019-12-07 06:28:46 -08002047 std::unique_ptr<mediametrics::Item> item(mediametrics::Item::create("audiothread"));
Andy Hungd0979812019-02-21 15:51:44 -08002048
2049#define MM_PREFIX "android.media.audiothread." // avoid cut-n-paste errors.
2050
2051 // thread configuration
2052 item->setInt32(MM_PREFIX "id", (int32_t)mId); // IO handle
2053 // item->setInt32(MM_PREFIX "portId", (int32_t)mPortId);
2054 item->setCString(MM_PREFIX "type", threadTypeToString(mType));
2055 item->setInt32(MM_PREFIX "sampleRate", (int32_t)mSampleRate);
2056 item->setInt64(MM_PREFIX "channelMask", (int64_t)mChannelMask);
2057 item->setCString(MM_PREFIX "encoding", toString(mFormat).c_str());
2058 item->setInt32(MM_PREFIX "frameCount", (int32_t)mFrameCount);
Andy Hungab65b182023-09-06 19:41:47 -07002059 item->setCString(MM_PREFIX "outDevice", toString(outDeviceTypes_l()).c_str());
2060 item->setCString(MM_PREFIX "inDevice", toString(inDeviceType_l()).c_str());
Andy Hungd0979812019-02-21 15:51:44 -08002061
2062 // thread statistics
2063 if (mIoJitterMs.getN() > 0) {
2064 item->setDouble(MM_PREFIX "ioJitterMs.mean", mIoJitterMs.getMean());
2065 item->setDouble(MM_PREFIX "ioJitterMs.std", mIoJitterMs.getStdDev());
2066 }
2067 if (mProcessTimeMs.getN() > 0) {
2068 item->setDouble(MM_PREFIX "processTimeMs.mean", mProcessTimeMs.getMean());
2069 item->setDouble(MM_PREFIX "processTimeMs.std", mProcessTimeMs.getStdDev());
2070 }
2071 const auto tsjitter = mTimestampVerifier.getJitterMs();
2072 if (tsjitter.getN() > 0) {
2073 item->setDouble(MM_PREFIX "timestampJitterMs.mean", tsjitter.getMean());
2074 item->setDouble(MM_PREFIX "timestampJitterMs.std", tsjitter.getStdDev());
2075 }
2076 if (mLatencyMs.getN() > 0) {
2077 item->setDouble(MM_PREFIX "latencyMs.mean", mLatencyMs.getMean());
2078 item->setDouble(MM_PREFIX "latencyMs.std", mLatencyMs.getStdDev());
2079 }
Robert Wu06db0a32021-08-10 19:05:34 +00002080 if (mMonopipePipeDepthStats.getN() > 0) {
2081 item->setDouble(MM_PREFIX "monopipePipeDepthStats.mean",
2082 mMonopipePipeDepthStats.getMean());
2083 item->setDouble(MM_PREFIX "monopipePipeDepthStats.std",
2084 mMonopipePipeDepthStats.getStdDev());
2085 }
Andy Hungd0979812019-02-21 15:51:44 -08002086
2087 item->selfrecord();
2088}
2089
Andy Hungee58e4a2023-07-07 13:47:37 -07002090product_strategy_t ThreadBase::getStrategyForStream(audio_stream_type_t stream) const
Eric Laurentd66d7a12021-07-13 13:35:32 +02002091{
Andy Hung583043b2023-07-17 17:05:00 -07002092 if (!mAfThreadCallback->isAudioPolicyReady()) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02002093 return PRODUCT_STRATEGY_NONE;
2094 }
2095 return AudioSystem::getStrategyForStream(stream);
2096}
2097
Andy Hungc5007f82023-08-29 14:26:09 -07002098// startMelComputation_l() must be called with AudioFlinger::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07002099void ThreadBase::startMelComputation_l(
Vlad Popa6fbbfbf2023-02-22 15:05:43 +01002100 const sp<audio_utils::MelProcessor>& /*processor*/)
2101{
2102 // Do nothing
2103 ALOGW("%s: ThreadBase does not support CSD", __func__);
2104}
2105
Andy Hungc5007f82023-08-29 14:26:09 -07002106// stopMelComputation_l() must be called with AudioFlinger::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07002107void ThreadBase::stopMelComputation_l()
Vlad Popa6fbbfbf2023-02-22 15:05:43 +01002108{
2109 // Do nothing
2110 ALOGW("%s: ThreadBase does not support CSD", __func__);
2111}
2112
Eric Laurent81784c32012-11-19 14:55:58 -08002113// ----------------------------------------------------------------------------
2114// Playback
2115// ----------------------------------------------------------------------------
2116
Andy Hung583043b2023-07-17 17:05:00 -07002117PlaybackThread::PlaybackThread(const sp<IAfThreadCallback>& afThreadCallback,
Eric Laurent81784c32012-11-19 14:55:58 -08002118 AudioStreamOut* output,
2119 audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -07002120 type_t type,
Eric Laurentf1f22e72021-07-13 14:04:14 +02002121 bool systemReady,
2122 audio_config_base_t *mixerConfig)
Andy Hung583043b2023-07-17 17:05:00 -07002123 : ThreadBase(afThreadCallback, id, type, systemReady, true /* isOut */),
Andy Hung2098f272014-02-27 14:00:06 -08002124 mNormalFrameCount(0), mSinkBuffer(NULL),
Andy Hung81994d62023-07-20 21:44:14 -07002125 mMixerBufferEnabled(kEnableExtendedPrecision || type == SPATIALIZER),
Andy Hung69aed5f2014-02-25 17:24:40 -08002126 mMixerBuffer(NULL),
2127 mMixerBufferSize(0),
2128 mMixerBufferFormat(AUDIO_FORMAT_INVALID),
2129 mMixerBufferValid(false),
Andy Hung81994d62023-07-20 21:44:14 -07002130 mEffectBufferEnabled(kEnableExtendedPrecision || type == SPATIALIZER),
Andy Hung98ef9782014-03-04 14:46:50 -08002131 mEffectBuffer(NULL),
2132 mEffectBufferSize(0),
2133 mEffectBufferFormat(AUDIO_FORMAT_INVALID),
2134 mEffectBufferValid(false),
Glenn Kastenc1fac192013-08-06 07:41:36 -07002135 mSuspended(0), mBytesWritten(0),
Andy Hungc54b1ff2016-02-23 14:07:07 -08002136 mFramesWritten(0),
Andy Hung238fa3d2016-07-28 10:53:22 -07002137 mSuspendedFrames(0),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002138 mActiveTracks(&this->mLocalLog),
Eric Laurent81784c32012-11-19 14:55:58 -08002139 // mStreamTypes[] initialized in constructor body
Andy Hung1bc088a2018-02-09 15:57:31 -08002140 mTracks(type == MIXER),
Eric Laurent81784c32012-11-19 14:55:58 -08002141 mOutput(output),
Andy Hung446f4df2019-02-21 12:26:41 -08002142 mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
Eric Laurent81784c32012-11-19 14:55:58 -08002143 mMixerStatus(MIXER_IDLE),
2144 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
Andy Hung8fe87eb2023-07-20 21:31:38 -07002145 mStandbyDelayNs(getStandbyTimeInNanos()),
Eric Laurentbfb1b832013-01-07 09:53:42 -08002146 mBytesRemaining(0),
2147 mCurrentWriteLength(0),
2148 mUseAsyncWrite(false),
Eric Laurent3b4529e2013-09-05 18:09:19 -07002149 mWriteAckSequence(0),
2150 mDrainSequence(0),
Andy Hung1d2d2aea2023-07-19 16:22:58 -07002151 mScreenState(mAfThreadCallback->getScreenState()),
Eric Laurent81784c32012-11-19 14:55:58 -08002152 // index 0 is reserved for normal mixer's submix
Glenn Kastendc2c50b2016-04-21 08:13:14 -07002153 mFastTrackAvailMask(((1 << FastMixerState::sMaxFastTracks) - 1) & ~1),
Eric Laurent7c29ec92017-09-20 17:54:22 -07002154 mHwSupportsPause(false), mHwPaused(false), mFlushPending(false),
Eric Laurent74c38dc2020-12-23 18:19:44 +01002155 mLeftVolFloat(-1.0), mRightVolFloat(-1.0),
Brian Lindahl65e90012022-07-27 18:01:07 +02002156 mDownStreamPatch{},
Eric Laurentb0463942022-12-20 16:31:10 +01002157 mIsTimestampAdvancing(kMinimumTimeBetweenTimestampChecksNs)
Eric Laurent81784c32012-11-19 14:55:58 -08002158{
Glenn Kastend7dca052015-03-05 16:05:54 -08002159 snprintf(mThreadName, kThreadNameLength, "AudioOut_%X", id);
Andy Hung583043b2023-07-17 17:05:00 -07002160 mNBLogWriter = afThreadCallback->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08002161
Andy Hungc5007f82023-08-29 14:26:09 -07002162 // Assumes constructor is called by AudioFlinger with its mutex() held, but
Eric Laurent81784c32012-11-19 14:55:58 -08002163 // it would be safer to explicitly pass initial masterVolume/masterMute as
2164 // parameter.
2165 //
2166 // If the HAL we are using has support for master volume or master mute,
2167 // then do not attenuate or mute during mixing (just leave the volume at 1.0
2168 // and the mute set to false).
Andy Hung583043b2023-07-17 17:05:00 -07002169 mMasterVolume = afThreadCallback->masterVolume_l();
2170 mMasterMute = afThreadCallback->masterMute_l();
George Burgess IV5e4d86f2020-02-18 12:55:36 -08002171 if (mOutput->audioHwDev) {
Eric Laurent81784c32012-11-19 14:55:58 -08002172 if (mOutput->audioHwDev->canSetMasterVolume()) {
2173 mMasterVolume = 1.0;
2174 }
2175
2176 if (mOutput->audioHwDev->canSetMasterMute()) {
2177 mMasterMute = false;
2178 }
Andy Hungc8fddf32018-08-08 18:32:37 -07002179 mIsMsdDevice = strcmp(
2180 mOutput->audioHwDev->moduleName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002181 }
2182
Eric Laurentf1f22e72021-07-13 14:04:14 +02002183 if (mixerConfig != nullptr && mixerConfig->channel_mask != AUDIO_CHANNEL_NONE) {
2184 mMixerChannelMask = mixerConfig->channel_mask;
2185 }
2186
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002187 readOutputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002188
Eric Laurent1c5e2e32021-08-18 18:50:28 +02002189 if (mType != SPATIALIZER
Eric Laurentb3f315a2021-07-13 15:09:05 +02002190 && mMixerChannelMask != mChannelMask) {
2191 LOG_ALWAYS_FATAL("HAL channel mask %#x does not match mixer channel mask %#x",
2192 mChannelMask, mMixerChannelMask);
2193 }
2194
Andy Hungc8fddf32018-08-08 18:32:37 -07002195 // TODO: We may also match on address as well as device type for
2196 // AUDIO_DEVICE_OUT_BUS, AUDIO_DEVICE_OUT_ALL_A2DP, AUDIO_DEVICE_OUT_REMOTE_SUBMIX
Dean Wheatleyf8726f02019-12-02 14:12:01 +11002197 if (type == MIXER || type == DIRECT || type == OFFLOAD) {
jiabinc52b1ff2019-10-31 17:20:42 -07002198 // TODO: This property should be ensure that only contains one single device type.
2199 mTimestampCorrectedDevice = (audio_devices_t)property_get_int64(
2200 "audio.timestamp.corrected_output_device",
Andy Hungc8fddf32018-08-08 18:32:37 -07002201 (int64_t)(mIsMsdDevice ? AUDIO_DEVICE_OUT_BUS // turn on by default for MSD
2202 : AUDIO_DEVICE_NONE));
2203 }
2204
Mikhail Naganovf33115d2020-09-25 23:03:05 +00002205 for (int i = AUDIO_STREAM_MIN; i < AUDIO_STREAM_FOR_POLICY_CNT; ++i) {
2206 const audio_stream_type_t stream{static_cast<audio_stream_type_t>(i)};
Eric Laurent98e38192018-02-15 18:31:53 -08002207 mStreamTypes[stream].volume = 0.0f;
Andy Hung583043b2023-07-17 17:05:00 -07002208 mStreamTypes[stream].mute = mAfThreadCallback->streamMute_l(stream);
Eric Laurent81784c32012-11-19 14:55:58 -08002209 }
Eric Laurent35f8c7c2020-02-08 11:42:35 -08002210 // Audio patch and call assistant volume are always max
Eric Laurent98e38192018-02-15 18:31:53 -08002211 mStreamTypes[AUDIO_STREAM_PATCH].volume = 1.0f;
2212 mStreamTypes[AUDIO_STREAM_PATCH].mute = false;
Eric Laurent35f8c7c2020-02-08 11:42:35 -08002213 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].volume = 1.0f;
2214 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].mute = false;
Eric Laurent81784c32012-11-19 14:55:58 -08002215}
2216
Andy Hungee58e4a2023-07-07 13:47:37 -07002217PlaybackThread::~PlaybackThread()
Eric Laurent81784c32012-11-19 14:55:58 -08002218{
Andy Hung583043b2023-07-17 17:05:00 -07002219 mAfThreadCallback->unregisterWriter(mNBLogWriter);
Andy Hung010a1a12014-03-13 13:57:33 -07002220 free(mSinkBuffer);
Andy Hung69aed5f2014-02-25 17:24:40 -08002221 free(mMixerBuffer);
Andy Hung98ef9782014-03-04 14:46:50 -08002222 free(mEffectBuffer);
Eric Laurentb62d0362021-10-26 17:40:18 +02002223 free(mPostSpatializerBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08002224}
2225
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002226// Thread virtuals
2227
Andy Hungee58e4a2023-07-07 13:47:37 -07002228void PlaybackThread::onFirstRef()
Eric Laurent81784c32012-11-19 14:55:58 -08002229{
Jasmine Chaeaa10e42021-05-11 10:11:14 +08002230 if (!isStreamInitialized()) {
jiabinf6eb4c32020-02-25 14:06:25 -08002231 ALOGE("The stream is not open yet"); // This should not happen.
2232 } else {
Mikhail Naganovaec565e2023-02-22 16:31:28 -08002233 // Callbacks take strong or weak pointers as a parameter.
2234 // Since PlaybackThread passes itself as a callback handler, it can only
2235 // be done outside of the constructor. Creating weak and especially strong
2236 // pointers to a refcounted object in its own constructor is strongly
2237 // discouraged, see comments in system/core/libutils/include/utils/RefBase.h.
2238 // Even if a function takes a weak pointer, it is possible that it will
2239 // need to convert it to a strong pointer down the line.
2240 if (mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING &&
2241 mOutput->stream->setCallback(this) == OK) {
2242 mUseAsyncWrite = true;
Andy Hungee58e4a2023-07-07 13:47:37 -07002243 mCallbackThread = sp<AsyncCallbackThread>::make(this);
Mikhail Naganovaec565e2023-02-22 16:31:28 -08002244 }
2245
jiabinf6eb4c32020-02-25 14:06:25 -08002246 if (mOutput->stream->setEventCallback(this) != OK) {
jiabinf1a36052020-08-19 14:33:31 -07002247 ALOGD("Failed to add event callback");
jiabinf6eb4c32020-02-25 14:06:25 -08002248 }
2249 }
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002250 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
Andy Hung44d648b2022-04-08 17:33:40 -07002251 mThreadSnapshot.setTid(getTid());
Eric Laurent81784c32012-11-19 14:55:58 -08002252}
2253
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002254// ThreadBase virtuals
Andy Hungee58e4a2023-07-07 13:47:37 -07002255void PlaybackThread::preExit()
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002256{
2257 ALOGV(" preExit()");
Ytai Ben-Tsvi7e0183f2022-02-04 10:49:54 -08002258 status_t result = mOutput->stream->exit();
2259 ALOGE_IF(result != OK, "Error when calling exit(): %d", result);
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002260}
2261
Andy Hungee58e4a2023-07-07 13:47:37 -07002262void PlaybackThread::dumpTracks_l(int fd, const Vector<String16>& /* args */)
Eric Laurent81784c32012-11-19 14:55:58 -08002263{
Eric Laurent81784c32012-11-19 14:55:58 -08002264 String8 result;
2265
Marco Nelissenb2208842014-02-07 14:00:50 -08002266 result.appendFormat(" Stream volumes in dB: ");
Eric Laurent81784c32012-11-19 14:55:58 -08002267 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
2268 const stream_type_t *st = &mStreamTypes[i];
2269 if (i > 0) {
2270 result.appendFormat(", ");
2271 }
2272 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
2273 if (st->mute) {
2274 result.append("M");
2275 }
2276 }
2277 result.append("\n");
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00002278 write(fd, result.c_str(), result.length());
Eric Laurent81784c32012-11-19 14:55:58 -08002279 result.clear();
2280
Eric Laurent81784c32012-11-19 14:55:58 -08002281 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
2282 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
Elliott Hughes87cebad2014-05-22 10:14:43 -07002283 dprintf(fd, " Normal mixer raw underrun counters: partial=%u empty=%u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08002284 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Marco Nelissenb2208842014-02-07 14:00:50 -08002285
2286 size_t numtracks = mTracks.size();
2287 size_t numactive = mActiveTracks.size();
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002288 dprintf(fd, " %zu Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08002289 size_t numactiveseen = 0;
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002290 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08002291 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002292 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002293 result.append(prefix);
Andy Hungf6ab58d2018-05-25 12:50:39 -07002294 mTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08002295 for (size_t i = 0; i < numtracks; ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07002296 sp<IAfTrack> track = mTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08002297 if (track != 0) {
2298 bool active = mActiveTracks.indexOf(track) >= 0;
2299 if (active) {
2300 numactiveseen++;
2301 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002302 result.append(prefix);
2303 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08002304 }
2305 }
2306 } else {
2307 result.append("\n");
2308 }
2309 if (numactiveseen != numactive) {
2310 // some tracks in the active list were not in the tracks list
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002311 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08002312 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002313 result.append(prefix);
Andy Hungf6ab58d2018-05-25 12:50:39 -07002314 mActiveTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08002315 for (size_t i = 0; i < numactive; ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07002316 sp<IAfTrack> track = mActiveTracks[i];
Andy Hungdae27702016-10-31 14:01:16 -07002317 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002318 result.append(prefix);
2319 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08002320 }
2321 }
2322 }
2323
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00002324 write(fd, result.c_str(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08002325}
2326
Andy Hungee58e4a2023-07-07 13:47:37 -07002327void PlaybackThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -08002328{
Andy Hung04cb8f72020-03-20 13:44:33 -07002329 dprintf(fd, " Master volume: %f\n", mMasterVolume);
Mikhail Naganovdfb411f2018-09-11 13:39:56 -07002330 dprintf(fd, " Master mute: %s\n", mMasterMute ? "on" : "off");
Eric Laurentf1f22e72021-07-13 14:04:14 +02002331 dprintf(fd, " Mixer channel Mask: %#x (%s)\n",
2332 mMixerChannelMask, channelMaskToString(mMixerChannelMask, true /* output */).c_str());
jiabin245cdd92018-12-07 17:55:15 -08002333 if (mHapticChannelMask != AUDIO_CHANNEL_NONE) {
2334 dprintf(fd, " Haptic channel mask: %#x (%s)\n", mHapticChannelMask,
2335 channelMaskToString(mHapticChannelMask, true /* output */).c_str());
2336 }
Elliott Hughes87cebad2014-05-22 10:14:43 -07002337 dprintf(fd, " Normal frame count: %zu\n", mNormalFrameCount);
Elliott Hughes87cebad2014-05-22 10:14:43 -07002338 dprintf(fd, " Total writes: %d\n", mNumWrites);
2339 dprintf(fd, " Delayed writes: %d\n", mNumDelayedWrites);
2340 dprintf(fd, " Blocked in write: %s\n", mInWrite ? "yes" : "no");
Andy Hung8d672e02023-09-15 18:19:28 -07002341 dprintf(fd, " Suspend count: %d\n", (int32_t)mSuspended);
Elliott Hughes87cebad2014-05-22 10:14:43 -07002342 dprintf(fd, " Fast track availMask=%#x\n", mFastTrackAvailMask);
Eric Laurent42537be2016-01-08 17:16:42 -08002343 dprintf(fd, " Standby delay ns=%lld\n", (long long)mStandbyDelayNs);
Glenn Kasten97b7b752014-09-28 13:04:24 -07002344 AudioStreamOut *output = mOutput;
2345 audio_output_flags_t flags = output != NULL ? output->flags : AUDIO_OUTPUT_FLAG_NONE;
Mikhail Naganov913d06c2016-11-01 12:49:22 -07002346 dprintf(fd, " AudioStreamOut: %p flags %#x (%s)\n",
Andy Hung9b181952019-02-25 14:53:36 -08002347 output, flags, toString(flags).c_str());
Andy Hungb54c8542016-09-21 12:55:15 -07002348 dprintf(fd, " Frames written: %lld\n", (long long)mFramesWritten);
2349 dprintf(fd, " Suspended frames: %lld\n", (long long)mSuspendedFrames);
2350 if (mPipeSink.get() != nullptr) {
2351 dprintf(fd, " PipeSink frames written: %lld\n", (long long)mPipeSink->framesWritten());
2352 }
2353 if (output != nullptr) {
2354 dprintf(fd, " Hal stream dump:\n");
Andy Hung61589a42021-06-16 09:37:53 -07002355 (void)output->stream->dump(fd, args);
Andy Hungb54c8542016-09-21 12:55:15 -07002356 }
Eric Laurent81784c32012-11-19 14:55:58 -08002357}
2358
Andy Hungc5007f82023-08-29 14:26:09 -07002359// PlaybackThread::createTrack_l() must be called with AudioFlinger::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07002360sp<IAfTrack> PlaybackThread::createTrack_l(
Andy Hung88035ac2023-06-27 17:05:02 -07002361 const sp<Client>& client,
Eric Laurent81784c32012-11-19 14:55:58 -08002362 audio_stream_type_t streamType,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07002363 const audio_attributes_t& attr,
Eric Laurent21da6472017-11-09 16:29:26 -08002364 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08002365 audio_format_t format,
2366 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08002367 size_t *pFrameCount,
Eric Laurent21da6472017-11-09 16:29:26 -08002368 size_t *pNotificationFrameCount,
2369 uint32_t notificationsPerBuffer,
2370 float speed,
Eric Laurent81784c32012-11-19 14:55:58 -08002371 const sp<IMemory>& sharedBuffer,
Glenn Kastend848eb42016-03-08 13:42:11 -08002372 audio_session_t sessionId,
Eric Laurent05067782016-06-01 18:27:28 -07002373 audio_output_flags_t *flags,
Eric Laurent09f1ed22019-04-24 17:45:17 -07002374 pid_t creatorPid,
Svet Ganov33761132021-05-13 22:51:08 +00002375 const AttributionSourceState& attributionSource,
Eric Laurent81784c32012-11-19 14:55:58 -08002376 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002377 status_t *status,
jiabinf6eb4c32020-02-25 14:06:25 -08002378 audio_port_handle_t portId,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02002379 const sp<media::IAudioTrackCallback>& callback,
jiabinc658e452022-10-21 20:52:21 +00002380 bool isSpatialized,
jiabin94ed47c2023-07-27 23:34:20 +00002381 bool isBitPerfect,
2382 audio_output_flags_t *afTrackFlags)
Eric Laurent81784c32012-11-19 14:55:58 -08002383{
Glenn Kasten74935e42013-12-19 08:56:45 -08002384 size_t frameCount = *pFrameCount;
Eric Laurent21da6472017-11-09 16:29:26 -08002385 size_t notificationFrameCount = *pNotificationFrameCount;
Andy Hung8d31fd22023-06-26 19:20:57 -07002386 sp<IAfTrack> track;
Eric Laurent81784c32012-11-19 14:55:58 -08002387 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07002388 audio_output_flags_t outputFlags = mOutput->flags;
Eric Laurent21da6472017-11-09 16:29:26 -08002389 audio_output_flags_t requestedFlags = *flags;
Eric Laurent9b11c022018-06-06 19:19:22 -07002390 uint32_t sampleRate;
2391
2392 if (sharedBuffer != 0 && checkIMemory(sharedBuffer) != NO_ERROR) {
2393 lStatus = BAD_VALUE;
2394 goto Exit;
2395 }
Eric Laurent21da6472017-11-09 16:29:26 -08002396
2397 if (*pSampleRate == 0) {
2398 *pSampleRate = mSampleRate;
2399 }
Eric Laurent9b11c022018-06-06 19:19:22 -07002400 sampleRate = *pSampleRate;
Eric Laurent05067782016-06-01 18:27:28 -07002401
2402 // special case for FAST flag considered OK if fast mixer is present
2403 if (hasFastMixer()) {
2404 outputFlags = (audio_output_flags_t)(outputFlags | AUDIO_OUTPUT_FLAG_FAST);
2405 }
2406
2407 // Check if requested flags are compatible with output stream flags
2408 if ((*flags & outputFlags) != *flags) {
2409 ALOGW("createTrack_l(): mismatch between requested flags (%08x) and output flags (%08x)",
2410 *flags, outputFlags);
2411 *flags = (audio_output_flags_t)(*flags & outputFlags);
2412 }
Eric Laurent81784c32012-11-19 14:55:58 -08002413
jiabinc658e452022-10-21 20:52:21 +00002414 if (isBitPerfect) {
Andy Hung8d672e02023-09-15 18:19:28 -07002415 audio_utils::lock_guard _l(mutex());
Andy Hung116bc262023-06-20 18:56:17 -07002416 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
jiabinc658e452022-10-21 20:52:21 +00002417 if (chain.get() != nullptr) {
2418 // Bit-perfect is required according to the configuration and preferred mixer
2419 // attributes, but it is not in the output flag from the client's request. Explicitly
2420 // adding bit-perfect flag to check the compatibility
2421 audio_output_flags_t flagsToCheck =
2422 (audio_output_flags_t)(*flags & AUDIO_OUTPUT_FLAG_BIT_PERFECT);
2423 chain->checkOutputFlagCompatibility(&flagsToCheck);
2424 if ((flagsToCheck & AUDIO_OUTPUT_FLAG_BIT_PERFECT) == AUDIO_OUTPUT_FLAG_NONE) {
2425 ALOGE("%s cannot create track as there is data-processing effect attached to "
2426 "given session id(%d)", __func__, sessionId);
2427 lStatus = BAD_VALUE;
2428 goto Exit;
2429 }
2430 *flags = flagsToCheck;
2431 }
2432 }
2433
Eric Laurent81784c32012-11-19 14:55:58 -08002434 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07002435 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
Eric Laurent81784c32012-11-19 14:55:58 -08002436 if (
Eric Laurent81784c32012-11-19 14:55:58 -08002437 // PCM data
2438 audio_is_linear_pcm(format) &&
Andy Hung1f439e12015-05-19 12:57:41 -07002439 // TODO: extract as a data library function that checks that a computationally
2440 // expensive downmixer is not required: isFastOutputChannelConversion()
jiabin245cdd92018-12-07 17:55:15 -08002441 (channelMask == (mChannelMask | mHapticChannelMask) ||
Andy Hung1f439e12015-05-19 12:57:41 -07002442 mChannelMask != AUDIO_CHANNEL_OUT_STEREO ||
2443 (channelMask == AUDIO_CHANNEL_OUT_MONO
2444 /* && mChannelMask == AUDIO_CHANNEL_OUT_STEREO */)) &&
Eric Laurent81784c32012-11-19 14:55:58 -08002445 // hardware sample rate
2446 (sampleRate == mSampleRate) &&
Eric Laurent81784c32012-11-19 14:55:58 -08002447 // normal mixer has an associated fast mixer
2448 hasFastMixer() &&
2449 // there are sufficient fast track slots available
2450 (mFastTrackAvailMask != 0)
2451 // FIXME test that MixerThread for this fast track has a capable output HAL
2452 // FIXME add a permission test also?
2453 ) {
Andy Hunge0a269a2016-03-23 15:13:42 -07002454 // static tracks can have any nonzero framecount, streaming tracks check against minimum.
2455 if (sharedBuffer == 0) {
Glenn Kasten03490092014-05-27 12:30:54 -07002456 // read the fast track multiplier property the first time it is needed
2457 int ok = pthread_once(&sFastTrackMultiplierOnce, sFastTrackMultiplierInit);
2458 if (ok != 0) {
2459 ALOGE("%s pthread_once failed: %d", __func__, ok);
2460 }
Andy Hunge0a269a2016-03-23 15:13:42 -07002461 frameCount = max(frameCount, mFrameCount * sFastTrackMultiplier); // incl framecount 0
Eric Laurent81784c32012-11-19 14:55:58 -08002462 }
Eric Laurent4c415062016-06-17 16:14:16 -07002463
2464 // check compatibility with audio effects.
Andy Hungc5007f82023-08-29 14:26:09 -07002465 { // scope for mutex()
Andy Hung972bec12023-08-31 16:13:39 -07002466 audio_utils::lock_guard _l(mutex());
Andy Hungd3bb0ad2016-10-11 17:16:43 -07002467 for (audio_session_t session : {
Eric Laurent3f75a5b2019-11-12 15:55:51 -08002468 AUDIO_SESSION_DEVICE,
Andy Hungd3bb0ad2016-10-11 17:16:43 -07002469 AUDIO_SESSION_OUTPUT_STAGE,
2470 AUDIO_SESSION_OUTPUT_MIX,
2471 sessionId,
2472 }) {
Andy Hung116bc262023-06-20 18:56:17 -07002473 sp<IAfEffectChain> chain = getEffectChain_l(session);
Andy Hungd3bb0ad2016-10-11 17:16:43 -07002474 if (chain.get() != nullptr) {
2475 audio_output_flags_t old = *flags;
2476 chain->checkOutputFlagCompatibility(flags);
2477 if (old != *flags) {
2478 ALOGV("AUDIO_OUTPUT_FLAGS denied by effect, session=%d old=%#x new=%#x",
2479 (int)session, (int)old, (int)*flags);
2480 }
Eric Laurent4c415062016-06-17 16:14:16 -07002481 }
2482 }
2483 }
Eric Laurent122f7e72016-06-29 11:53:29 -07002484 ALOGV_IF((*flags & AUDIO_OUTPUT_FLAG_FAST) != 0,
Eric Laurent4c415062016-06-17 16:14:16 -07002485 "AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
2486 frameCount, mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08002487 } else {
Robert Wu4c7bb7d2021-08-12 18:50:13 +00002488 ALOGD("AUDIO_OUTPUT_FLAG_FAST denied: sharedBuffer=%p frameCount=%zu "
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002489 "mFrameCount=%zu format=%#x mFormat=%#x isLinear=%d channelMask=%#x "
Andy Hung6146c082014-03-18 11:56:15 -07002490 "sampleRate=%u mSampleRate=%u "
Eric Laurent81784c32012-11-19 14:55:58 -08002491 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
Glenn Kastend79072e2016-01-06 08:41:20 -08002492 sharedBuffer.get(), frameCount, mFrameCount, format, mFormat,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07002493 audio_is_linear_pcm(format), channelMask, sampleRate,
2494 mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
Eric Laurent4c415062016-06-17 16:14:16 -07002495 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_FAST);
Andy Hung0e48d252015-01-26 11:43:15 -08002496 }
2497 }
Eric Laurent21da6472017-11-09 16:29:26 -08002498
2499 if (!audio_has_proportional_frames(format)) {
2500 if (sharedBuffer != 0) {
2501 // Same comment as below about ignoring frameCount parameter for set()
2502 frameCount = sharedBuffer->size();
2503 } else if (frameCount == 0) {
2504 frameCount = mNormalFrameCount;
2505 }
2506 if (notificationFrameCount != frameCount) {
2507 notificationFrameCount = frameCount;
2508 }
2509 } else if (sharedBuffer != 0) {
2510 // FIXME: Ensure client side memory buffers need
2511 // not have additional alignment beyond sample
2512 // (e.g. 16 bit stereo accessed as 32 bit frame).
2513 size_t alignment = audio_bytes_per_sample(format);
2514 if (alignment & 1) {
2515 // for AUDIO_FORMAT_PCM_24_BIT_PACKED (not exposed through Java).
2516 alignment = 1;
2517 }
2518 uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
2519 size_t frameSize = channelCount * audio_bytes_per_sample(format);
2520 if (channelCount > 1) {
2521 // More than 2 channels does not require stronger alignment than stereo
2522 alignment <<= 1;
2523 }
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07002524 if (((uintptr_t)sharedBuffer->unsecurePointer() & (alignment - 1)) != 0) {
Eric Laurent21da6472017-11-09 16:29:26 -08002525 ALOGE("Invalid buffer alignment: address %p, channel count %u",
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07002526 sharedBuffer->unsecurePointer(), channelCount);
Eric Laurent21da6472017-11-09 16:29:26 -08002527 lStatus = BAD_VALUE;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002528 goto Exit;
2529 }
Eric Laurent21da6472017-11-09 16:29:26 -08002530
2531 // When initializing a shared buffer AudioTrack via constructors,
2532 // there's no frameCount parameter.
2533 // But when initializing a shared buffer AudioTrack via set(),
2534 // there _is_ a frameCount parameter. We silently ignore it.
2535 frameCount = sharedBuffer->size() / frameSize;
2536 } else {
2537 size_t minFrameCount = 0;
2538 // For fast tracks we try to respect the application's request for notifications per buffer.
2539 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
2540 if (notificationsPerBuffer > 0) {
2541 // Avoid possible arithmetic overflow during multiplication.
2542 if (notificationsPerBuffer > SIZE_MAX / mFrameCount) {
2543 ALOGE("Requested notificationPerBuffer=%u ignored for HAL frameCount=%zu",
2544 notificationsPerBuffer, mFrameCount);
2545 } else {
2546 minFrameCount = mFrameCount * notificationsPerBuffer;
2547 }
2548 }
2549 } else {
2550 // For normal PCM streaming tracks, update minimum frame count.
2551 // Buffer depth is forced to be at least 2 x the normal mixer frame count and
2552 // cover audio hardware latency.
2553 // This is probably too conservative, but legacy application code may depend on it.
2554 // If you change this calculation, also review the start threshold which is related.
2555 uint32_t latencyMs = latency_l();
2556 if (latencyMs == 0) {
2557 ALOGE("Error when retrieving output stream latency");
2558 lStatus = UNKNOWN_ERROR;
2559 goto Exit;
2560 }
2561
2562 minFrameCount = AudioSystem::calculateMinFrameCount(latencyMs, mNormalFrameCount,
2563 mSampleRate, sampleRate, speed /*, 0 mNotificationsPerBufferReq*/);
2564
Eric Laurent81784c32012-11-19 14:55:58 -08002565 }
Eric Laurent21da6472017-11-09 16:29:26 -08002566 if (frameCount < minFrameCount) {
Eric Laurent81784c32012-11-19 14:55:58 -08002567 frameCount = minFrameCount;
2568 }
Eric Laurent81784c32012-11-19 14:55:58 -08002569 }
Eric Laurent21da6472017-11-09 16:29:26 -08002570
2571 // Make sure that application is notified with sufficient margin before underrun.
2572 // The client can divide the AudioTrack buffer into sub-buffers,
2573 // and expresses its desire to server as the notification frame count.
2574 if (sharedBuffer == 0 && audio_is_linear_pcm(format)) {
2575 size_t maxNotificationFrames;
2576 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
2577 // notify every HAL buffer, regardless of the size of the track buffer
2578 maxNotificationFrames = mFrameCount;
2579 } else {
Andy Hungfa117802019-04-12 13:50:39 -07002580 // Triple buffer the notification period for a triple buffered mixer period;
2581 // otherwise, double buffering for the notification period is fine.
2582 //
2583 // TODO: This should be moved to AudioTrack to modify the notification period
2584 // on AudioTrack::setBufferSizeInFrames() changes.
2585 const int nBuffering =
2586 (uint64_t{frameCount} * mSampleRate)
2587 / (uint64_t{mNormalFrameCount} * sampleRate) == 3 ? 3 : 2;
2588
Eric Laurent21da6472017-11-09 16:29:26 -08002589 maxNotificationFrames = frameCount / nBuffering;
2590 // If client requested a fast track but this was denied, then use the smaller maximum.
2591 if (requestedFlags & AUDIO_OUTPUT_FLAG_FAST) {
2592 size_t maxNotificationFramesFastDenied = FMS_20 * sampleRate / 1000;
2593 if (maxNotificationFrames > maxNotificationFramesFastDenied) {
2594 maxNotificationFrames = maxNotificationFramesFastDenied;
2595 }
2596 }
2597 }
2598 if (notificationFrameCount == 0 || notificationFrameCount > maxNotificationFrames) {
2599 if (notificationFrameCount == 0) {
2600 ALOGD("Client defaulted notificationFrames to %zu for frameCount %zu",
2601 maxNotificationFrames, frameCount);
2602 } else {
2603 ALOGW("Client adjusted notificationFrames from %zu to %zu for frameCount %zu",
2604 notificationFrameCount, maxNotificationFrames, frameCount);
2605 }
2606 notificationFrameCount = maxNotificationFrames;
2607 }
2608 }
2609
Glenn Kasten74935e42013-12-19 08:56:45 -08002610 *pFrameCount = frameCount;
Eric Laurent21da6472017-11-09 16:29:26 -08002611 *pNotificationFrameCount = notificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08002612
Glenn Kastenc3df8382014-03-13 15:05:25 -07002613 switch (mType) {
jiabinc658e452022-10-21 20:52:21 +00002614 case BIT_PERFECT:
2615 if (isBitPerfect) {
2616 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
2617 ALOGE("%s, bad parameter when request streaming bit-perfect, sampleRate=%u, "
2618 "format=%#x, channelMask=%#x, mSampleRate=%u, mFormat=%#x, mChannelMask=%#x",
2619 __func__, sampleRate, format, channelMask, mSampleRate, mFormat,
2620 mChannelMask);
2621 lStatus = BAD_VALUE;
2622 goto Exit;
2623 }
2624 }
2625 break;
Glenn Kastenc3df8382014-03-13 15:05:25 -07002626
2627 case DIRECT:
Phil Burkfdb3c072016-02-09 10:47:02 -08002628 if (audio_is_linear_pcm(format)) { // TODO maybe use audio_has_proportional_frames()?
Eric Laurent81784c32012-11-19 14:55:58 -08002629 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002630 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
2631 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08002632 sampleRate, format, channelMask, mOutput, mFormat);
2633 lStatus = BAD_VALUE;
2634 goto Exit;
2635 }
2636 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002637 break;
2638
2639 case OFFLOAD:
Eric Laurentbfb1b832013-01-07 09:53:42 -08002640 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002641 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
2642 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002643 sampleRate, format, channelMask, mOutput, mFormat);
2644 lStatus = BAD_VALUE;
2645 goto Exit;
2646 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002647 break;
2648
2649 default:
Glenn Kasten993fa062014-05-02 11:14:34 -07002650 if (!audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002651 ALOGE("createTrack_l() Bad parameter: format %#x \""
2652 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002653 format, mOutput, mFormat);
2654 lStatus = BAD_VALUE;
2655 goto Exit;
2656 }
Andy Hungcd044842014-08-07 11:04:34 -07002657 if (sampleRate > mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Eric Laurent81784c32012-11-19 14:55:58 -08002658 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
2659 lStatus = BAD_VALUE;
2660 goto Exit;
2661 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002662 break;
2663
Eric Laurent81784c32012-11-19 14:55:58 -08002664 }
2665
2666 lStatus = initCheck();
2667 if (lStatus != NO_ERROR) {
Glenn Kasten15e57982013-09-24 11:52:37 -07002668 ALOGE("createTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08002669 goto Exit;
2670 }
2671
Andy Hungc5007f82023-08-29 14:26:09 -07002672 { // scope for mutex()
Andy Hung972bec12023-08-31 16:13:39 -07002673 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002674
2675 // all tracks in same audio session must share the same routing strategy otherwise
2676 // conflicts will happen when tracks are moved from one output to another by audio policy
2677 // manager
Eric Laurentd66d7a12021-07-13 13:35:32 +02002678 product_strategy_t strategy = getStrategyForStream(streamType);
Eric Laurent81784c32012-11-19 14:55:58 -08002679 for (size_t i = 0; i < mTracks.size(); ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07002680 sp<IAfTrack> t = mTracks[i];
Eric Laurent83b88082014-06-20 18:31:16 -07002681 if (t != 0 && t->isExternalTrack()) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02002682 product_strategy_t actual = getStrategyForStream(t->streamType());
Eric Laurent81784c32012-11-19 14:55:58 -08002683 if (sessionId == t->sessionId() && strategy != actual) {
2684 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
2685 strategy, actual);
2686 lStatus = BAD_VALUE;
2687 goto Exit;
2688 }
2689 }
2690 }
2691
yucliuc9c49cd2020-07-13 16:25:21 -07002692 // Set DIRECT flag if current thread is DirectOutputThread. This can
2693 // happen when the playback is rerouted to direct output thread by
2694 // dynamic audio policy.
2695 // Do NOT report the flag changes back to client, since the client
2696 // doesn't explicitly request a direct flag.
2697 audio_output_flags_t trackFlags = *flags;
2698 if (mType == DIRECT) {
2699 trackFlags = static_cast<audio_output_flags_t>(trackFlags | AUDIO_OUTPUT_FLAG_DIRECT);
2700 }
jiabin94ed47c2023-07-27 23:34:20 +00002701 *afTrackFlags = trackFlags;
yucliuc9c49cd2020-07-13 16:25:21 -07002702
Andy Hung8d31fd22023-06-26 19:20:57 -07002703 track = IAfTrack::create(this, client, streamType, attr, sampleRate, format,
Andy Hung8fe68032017-06-05 16:17:51 -07002704 channelMask, frameCount,
2705 nullptr /* buffer */, (size_t)0 /* bufferSize */, sharedBuffer,
Svet Ganov33761132021-05-13 22:51:08 +00002706 sessionId, creatorPid, attributionSource, trackFlags,
Andy Hung8d31fd22023-06-26 19:20:57 -07002707 IAfTrackBase::TYPE_DEFAULT, portId, SIZE_MAX /*frameCountToBeReady*/,
jiabinc658e452022-10-21 20:52:21 +00002708 speed, isSpatialized, isBitPerfect);
Glenn Kasten03003332013-08-06 15:40:54 -07002709
Glenn Kasten03003332013-08-06 15:40:54 -07002710 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
2711 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08002712 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08002713 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08002714 goto Exit;
2715 }
2716 mTracks.add(track);
jiabinf6eb4c32020-02-25 14:06:25 -08002717 {
Andy Hung972bec12023-08-31 16:13:39 -07002718 audio_utils::lock_guard _atCbL(audioTrackCbMutex());
jiabinf6eb4c32020-02-25 14:06:25 -08002719 if (callback.get() != nullptr) {
jiabin18a4b1c2020-09-17 11:40:42 -07002720 mAudioTrackCallbacks.emplace(track, callback);
jiabinf6eb4c32020-02-25 14:06:25 -08002721 }
2722 }
Eric Laurent81784c32012-11-19 14:55:58 -08002723
Andy Hung116bc262023-06-20 18:56:17 -07002724 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08002725 if (chain != 0) {
2726 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
2727 track->setMainBuffer(chain->inBuffer());
Eric Laurentd66d7a12021-07-13 13:35:32 +02002728 chain->setStrategy(getStrategyForStream(track->streamType()));
Eric Laurent81784c32012-11-19 14:55:58 -08002729 chain->incTrackCnt();
2730 }
2731
Eric Laurent05067782016-06-01 18:27:28 -07002732 if ((*flags & AUDIO_OUTPUT_FLAG_FAST) && (tid != -1)) {
Eric Laurent81784c32012-11-19 14:55:58 -08002733 pid_t callingPid = IPCThreadState::self()->getCallingPid();
2734 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
2735 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07002736 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08002737 }
2738 }
2739
2740 lStatus = NO_ERROR;
2741
2742Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07002743 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08002744 return track;
2745}
2746
Andy Hung1bc088a2018-02-09 15:57:31 -08002747template<typename T>
Andy Hungee58e4a2023-07-07 13:47:37 -07002748ssize_t PlaybackThread::Tracks<T>::remove(const sp<T>& track)
Andy Hung1bc088a2018-02-09 15:57:31 -08002749{
Andy Hungc0691382018-09-12 18:01:57 -07002750 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08002751 const ssize_t index = mTracks.remove(track);
2752 if (index >= 0) {
Andy Hungc0691382018-09-12 18:01:57 -07002753 if (mSaveDeletedTrackIds) {
Andy Hung1bc088a2018-02-09 15:57:31 -08002754 // We can't directly access mAudioMixer since the caller may be outside of threadLoop.
Andy Hungc0691382018-09-12 18:01:57 -07002755 // Instead, we add to mDeletedTrackIds which is solely used for mAudioMixer update,
Andy Hung1bc088a2018-02-09 15:57:31 -08002756 // to be handled when MixerThread::prepareTracks_l() next changes mAudioMixer.
Andy Hungc0691382018-09-12 18:01:57 -07002757 mDeletedTrackIds.emplace(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08002758 }
Andy Hung1bc088a2018-02-09 15:57:31 -08002759 }
2760 return index;
2761}
2762
Andy Hungee58e4a2023-07-07 13:47:37 -07002763uint32_t PlaybackThread::correctLatency_l(uint32_t latency) const
Eric Laurent81784c32012-11-19 14:55:58 -08002764{
2765 return latency;
2766}
2767
Andy Hungee58e4a2023-07-07 13:47:37 -07002768uint32_t PlaybackThread::latency() const
Eric Laurent81784c32012-11-19 14:55:58 -08002769{
Andy Hung972bec12023-08-31 16:13:39 -07002770 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002771 return latency_l();
2772}
Andy Hungee58e4a2023-07-07 13:47:37 -07002773uint32_t PlaybackThread::latency_l() const
Andy Hungab65b182023-09-06 19:41:47 -07002774NO_THREAD_SAFETY_ANALYSIS
2775// Fix later.
Eric Laurent81784c32012-11-19 14:55:58 -08002776{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002777 uint32_t latency;
2778 if (initCheck() == NO_ERROR && mOutput->stream->getLatency(&latency) == OK) {
2779 return correctLatency_l(latency);
Eric Laurent81784c32012-11-19 14:55:58 -08002780 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002781 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002782}
2783
Andy Hungee58e4a2023-07-07 13:47:37 -07002784void PlaybackThread::setMasterVolume(float value)
Eric Laurent81784c32012-11-19 14:55:58 -08002785{
Andy Hung972bec12023-08-31 16:13:39 -07002786 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002787 // Don't apply master volume in SW if our HAL can do it for us.
2788 if (mOutput && mOutput->audioHwDev &&
2789 mOutput->audioHwDev->canSetMasterVolume()) {
2790 mMasterVolume = 1.0;
2791 } else {
2792 mMasterVolume = value;
2793 }
2794}
2795
Andy Hungee58e4a2023-07-07 13:47:37 -07002796void PlaybackThread::setMasterBalance(float balance)
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01002797{
2798 mMasterBalance.store(balance);
2799}
2800
Andy Hungee58e4a2023-07-07 13:47:37 -07002801void PlaybackThread::setMasterMute(bool muted)
Eric Laurent81784c32012-11-19 14:55:58 -08002802{
Eric Laurent6acd1d42017-01-04 14:23:29 -08002803 if (isDuplicating()) {
2804 return;
2805 }
Andy Hung972bec12023-08-31 16:13:39 -07002806 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002807 // Don't apply master mute in SW if our HAL can do it for us.
2808 if (mOutput && mOutput->audioHwDev &&
2809 mOutput->audioHwDev->canSetMasterMute()) {
2810 mMasterMute = false;
2811 } else {
2812 mMasterMute = muted;
2813 }
2814}
2815
Andy Hungee58e4a2023-07-07 13:47:37 -07002816void PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
Eric Laurent81784c32012-11-19 14:55:58 -08002817{
Andy Hung972bec12023-08-31 16:13:39 -07002818 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002819 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002820 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002821}
2822
Andy Hungee58e4a2023-07-07 13:47:37 -07002823void PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
Eric Laurent81784c32012-11-19 14:55:58 -08002824{
Andy Hung972bec12023-08-31 16:13:39 -07002825 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002826 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002827 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002828}
2829
Andy Hungee58e4a2023-07-07 13:47:37 -07002830float PlaybackThread::streamVolume(audio_stream_type_t stream) const
Eric Laurent81784c32012-11-19 14:55:58 -08002831{
Andy Hung972bec12023-08-31 16:13:39 -07002832 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002833 return mStreamTypes[stream].volume;
2834}
2835
Andy Hungee58e4a2023-07-07 13:47:37 -07002836void PlaybackThread::setVolumeForOutput_l(float left, float right) const
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09002837{
2838 mOutput->stream->setVolume(left, right);
2839}
2840
Andy Hungc5007f82023-08-29 14:26:09 -07002841// addTrack_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07002842status_t PlaybackThread::addTrack_l(const sp<IAfTrack>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002843{
2844 status_t status = ALREADY_EXISTS;
2845
Eric Laurent81784c32012-11-19 14:55:58 -08002846 if (mActiveTracks.indexOf(track) < 0) {
2847 // the track is newly added, make sure it fills up all its
2848 // buffers before playing. This is to ensure the client will
2849 // effectively get the latency it requested.
Eric Laurent83b88082014-06-20 18:31:16 -07002850 if (track->isExternalTrack()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07002851 IAfTrackBase::track_state state = track->state();
Andy Hung6c498e92023-12-05 17:28:17 -08002852 // Because the track is not on the ActiveTracks,
2853 // at this point, only the TrackHandle will be adding the track.
Andy Hungc5007f82023-08-29 14:26:09 -07002854 mutex().unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002855 status = AudioSystem::startOutput(track->portId());
Andy Hungc5007f82023-08-29 14:26:09 -07002856 mutex().lock();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002857 // abort track was stopped/paused while we released the lock
Andy Hung8d31fd22023-06-26 19:20:57 -07002858 if (state != track->state()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002859 if (status == NO_ERROR) {
Andy Hungc5007f82023-08-29 14:26:09 -07002860 mutex().unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002861 AudioSystem::stopOutput(track->portId());
Andy Hungc5007f82023-08-29 14:26:09 -07002862 mutex().lock();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002863 }
2864 return INVALID_OPERATION;
2865 }
2866 // abort if start is rejected by audio policy manager
2867 if (status != NO_ERROR) {
jiabina84c3d32022-12-02 18:59:55 +00002868 // Do not replace the error if it is DEAD_OBJECT. When this happens, it indicates
2869 // current playback thread is reopened, which may happen when clients set preferred
2870 // mixer configuration. Returning DEAD_OBJECT will make the client restore track
2871 // immediately.
2872 return status == DEAD_OBJECT ? status : PERMISSION_DENIED;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002873 }
2874#ifdef ADD_BATTERY_DATA
2875 // to track the speaker usage
2876 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
2877#endif
Eric Laurent09f1ed22019-04-24 17:45:17 -07002878 sendIoConfigEvent_l(AUDIO_CLIENT_STARTED, track->creatorPid(), track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002879 }
2880
Eric Laurent51716182016-02-29 18:00:56 -08002881 // set retry count for buffer fill
2882 if (track->isOffloaded()) {
Eric Laurente93cc032016-05-05 10:15:10 -07002883 if (track->isStopping_1()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07002884 track->retryCount() = kMaxTrackStopRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07002885 } else {
Andy Hung8d31fd22023-06-26 19:20:57 -07002886 track->retryCount() = kMaxTrackStartupRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07002887 }
Andy Hung8d31fd22023-06-26 19:20:57 -07002888 track->fillingStatus() = mStandby ? IAfTrack::FS_FILLING : IAfTrack::FS_FILLED;
Eric Laurent51716182016-02-29 18:00:56 -08002889 } else {
Andy Hung8d31fd22023-06-26 19:20:57 -07002890 track->retryCount() = kMaxTrackStartupRetries;
2891 track->fillingStatus() =
2892 track->sharedBuffer() != 0 ? IAfTrack::FS_FILLED : IAfTrack::FS_FILLING;
Eric Laurent51716182016-02-29 18:00:56 -08002893 }
2894
Andy Hung116bc262023-06-20 18:56:17 -07002895 sp<IAfEffectChain> chain = getEffectChain_l(track->sessionId());
jiabineb3bda02020-06-30 14:07:03 -07002896 if (mHapticChannelMask != AUDIO_CHANNEL_NONE
2897 && ((track->channelMask() & AUDIO_CHANNEL_HAPTIC_ALL) != AUDIO_CHANNEL_NONE
2898 || (chain != nullptr && chain->containsHapticGeneratingEffect_l()))) {
jiabin57303cc2018-12-18 15:45:57 -08002899 // Unlock due to VibratorService will lock for this call and will
2900 // call Tracks.mute/unmute which also require thread's lock.
Andy Hungc5007f82023-08-29 14:26:09 -07002901 mutex().unlock();
Andy Hung7fb97e12023-07-20 21:23:42 -07002902 const os::HapticScale intensity = afutils::onExternalVibrationStart(
jiabin57303cc2018-12-18 15:45:57 -08002903 track->getExternalVibration());
Lais Andradebc3f37a2021-07-02 00:13:19 +01002904 std::optional<media::AudioVibratorInfo> vibratorInfo;
2905 {
2906 // TODO(b/184194780): Use the vibrator information from the vibrator that will be
2907 // used to play this track.
Andy Hung972bec12023-08-31 16:13:39 -07002908 audio_utils::lock_guard _l(mAfThreadCallback->mutex());
Andy Hung583043b2023-07-17 17:05:00 -07002909 vibratorInfo = std::move(mAfThreadCallback->getDefaultVibratorInfo_l());
Lais Andradebc3f37a2021-07-02 00:13:19 +01002910 }
Andy Hungc5007f82023-08-29 14:26:09 -07002911 mutex().lock();
Simon Bowden62823412022-10-17 14:52:26 +00002912 track->setHapticIntensity(intensity);
Lais Andradebc3f37a2021-07-02 00:13:19 +01002913 if (vibratorInfo) {
2914 track->setHapticMaxAmplitude(vibratorInfo->maxAmplitude);
2915 }
2916
jiabin57303cc2018-12-18 15:45:57 -08002917 // Haptic playback should be enabled by vibrator service.
2918 if (track->getHapticPlaybackEnabled()) {
2919 // Disable haptic playback of all active track to ensure only
2920 // one track playing haptic if current track should play haptic.
2921 for (const auto &t : mActiveTracks) {
2922 t->setHapticPlaybackEnabled(false);
2923 }
jiabin245cdd92018-12-07 17:55:15 -08002924 }
jiabine70bc7f2020-06-30 22:07:55 -07002925
2926 // Set haptic intensity for effect
2927 if (chain != nullptr) {
2928 chain->setHapticIntensity_l(track->id(), intensity);
2929 }
jiabin245cdd92018-12-07 17:55:15 -08002930 }
2931
Andy Hung8d31fd22023-06-26 19:20:57 -07002932 track->setResetDone(false);
Andy Hung59de4262021-06-14 10:53:54 -07002933 track->resetPresentationComplete();
Andy Hung6c498e92023-12-05 17:28:17 -08002934
2935 // Do not release the ThreadBase mutex after the track is added to mActiveTracks unless
2936 // all key changes are complete. It is possible that the threadLoop will begin
2937 // processing the added track immediately after the ThreadBase mutex is released.
Eric Laurent81784c32012-11-19 14:55:58 -08002938 mActiveTracks.add(track);
Andy Hung6c498e92023-12-05 17:28:17 -08002939
Eric Laurentd0107bc2013-06-11 14:38:48 -07002940 if (chain != 0) {
2941 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
2942 track->sessionId());
2943 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08002944 }
2945
Andy Hungc2b11cb2020-04-22 09:04:01 -07002946 track->logBeginInterval(patchSinksToString(&mPatch)); // log to MediaMetrics
Eric Laurent81784c32012-11-19 14:55:58 -08002947 status = NO_ERROR;
2948 }
2949
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08002950 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002951 return status;
2952}
2953
Andy Hungee58e4a2023-07-07 13:47:37 -07002954bool PlaybackThread::destroyTrack_l(const sp<IAfTrack>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002955{
Eric Laurentbfb1b832013-01-07 09:53:42 -08002956 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08002957 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002958 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
Andy Hung8d31fd22023-06-26 19:20:57 -07002959 track->setState(IAfTrackBase::STOPPED);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002960 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08002961 removeTrack_l(track);
Eric Laurentab5cdba2014-06-09 17:22:27 -07002962 } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) {
Andy Hung916987e2023-03-20 19:08:16 -07002963 if (track->isPausePending()) {
2964 track->pauseAck();
2965 }
Andy Hung8d31fd22023-06-26 19:20:57 -07002966 track->setState(IAfTrackBase::STOPPING_1);
Eric Laurent81784c32012-11-19 14:55:58 -08002967 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002968
2969 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08002970}
2971
Andy Hungee58e4a2023-07-07 13:47:37 -07002972void PlaybackThread::removeTrack_l(const sp<IAfTrack>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002973{
2974 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Andy Hung2148bf02016-11-28 19:01:02 -08002975
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002976 String8 result;
2977 track->appendDump(result, false /* active */);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00002978 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.c_str());
Andy Hung2148bf02016-11-28 19:01:02 -08002979
Eric Laurent81784c32012-11-19 14:55:58 -08002980 mTracks.remove(track);
jiabin18a4b1c2020-09-17 11:40:42 -07002981 {
Andy Hung972bec12023-08-31 16:13:39 -07002982 audio_utils::lock_guard _atCbL(audioTrackCbMutex());
jiabin18a4b1c2020-09-17 11:40:42 -07002983 mAudioTrackCallbacks.erase(track);
2984 }
Eric Laurent81784c32012-11-19 14:55:58 -08002985 if (track->isFastTrack()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07002986 int index = track->fastIndex();
Glenn Kastendc2c50b2016-04-21 08:13:14 -07002987 ALOG_ASSERT(0 < index && index < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08002988 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
2989 mFastTrackAvailMask |= 1 << index;
2990 // redundant as track is about to be destroyed, for dumpsys only
Andy Hung8d31fd22023-06-26 19:20:57 -07002991 track->fastIndex() = -1;
Eric Laurent81784c32012-11-19 14:55:58 -08002992 }
Andy Hung116bc262023-06-20 18:56:17 -07002993 sp<IAfEffectChain> chain = getEffectChain_l(track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08002994 if (chain != 0) {
2995 chain->decTrackCnt();
2996 }
2997}
2998
Andy Hungee58e4a2023-07-07 13:47:37 -07002999String8 PlaybackThread::getParameters(const String8& keys)
Eric Laurent81784c32012-11-19 14:55:58 -08003000{
Andy Hung972bec12023-08-31 16:13:39 -07003001 audio_utils::lock_guard _l(mutex());
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003002 String8 out_s8;
3003 if (initCheck() == NO_ERROR && mOutput->stream->getParameters(keys, &out_s8) == OK) {
3004 return out_s8;
Eric Laurent81784c32012-11-19 14:55:58 -08003005 }
Andy Hung920f6572022-10-06 12:09:49 -07003006 return {};
Eric Laurent81784c32012-11-19 14:55:58 -08003007}
3008
Andy Hungee58e4a2023-07-07 13:47:37 -07003009status_t DirectOutputThread::selectPresentation(int presentationId, int programId) {
Andy Hung972bec12023-08-31 16:13:39 -07003010 audio_utils::lock_guard _l(mutex());
Jasmine Chaeaa10e42021-05-11 10:11:14 +08003011 if (!isStreamInitialized()) {
Mikhail Naganovac917ac2018-11-28 14:03:52 -08003012 return NO_INIT;
3013 }
3014 return mOutput->stream->selectPresentation(presentationId, programId);
3015}
3016
Andy Hungab65b182023-09-06 19:41:47 -07003017void PlaybackThread::ioConfigChanged_l(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -07003018 audio_port_handle_t portId) {
Eric Laurent73e26b62015-04-27 16:55:58 -07003019 ALOGV("PlaybackThread::ioConfigChanged, thread %p, event %d", this, event);
Mikhail Naganov88536df2021-07-26 17:30:29 -07003020 sp<AudioIoDescriptor> desc;
3021 const struct audio_patch patch = isMsdDevice() ? mDownStreamPatch : mPatch;
Eric Laurent81784c32012-11-19 14:55:58 -08003022 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07003023 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07003024 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07003025 case AUDIO_OUTPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07003026 desc = sp<AudioIoDescriptor>::make(mId, patch, false /*isInput*/,
3027 mSampleRate, mFormat, mChannelMask,
3028 // FIXME AudioFlinger::frameCount(audio_io_handle_t) instead of mNormalFrameCount?
3029 mNormalFrameCount, mFrameCount, latency_l());
Eric Laurent81784c32012-11-19 14:55:58 -08003030 break;
Eric Laurent09f1ed22019-04-24 17:45:17 -07003031 case AUDIO_CLIENT_STARTED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07003032 desc = sp<AudioIoDescriptor>::make(mId, patch, portId);
Eric Laurent09f1ed22019-04-24 17:45:17 -07003033 break;
Eric Laurent73e26b62015-04-27 16:55:58 -07003034 case AUDIO_OUTPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08003035 default:
Mikhail Naganov88536df2021-07-26 17:30:29 -07003036 desc = sp<AudioIoDescriptor>::make(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08003037 break;
3038 }
Andy Hungab65b182023-09-06 19:41:47 -07003039 mAfThreadCallback->ioConfigChanged_l(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08003040}
3041
Andy Hungee58e4a2023-07-07 13:47:37 -07003042void PlaybackThread::onWriteReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08003043{
Eric Laurent3b4529e2013-09-05 18:09:19 -07003044 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003045}
3046
Andy Hungee58e4a2023-07-07 13:47:37 -07003047void PlaybackThread::onDrainReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08003048{
Eric Laurent3b4529e2013-09-05 18:09:19 -07003049 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003050}
3051
Andy Hungee58e4a2023-07-07 13:47:37 -07003052void PlaybackThread::onError()
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07003053{
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07003054 mCallbackThread->setAsyncError();
3055}
3056
Andy Hungee58e4a2023-07-07 13:47:37 -07003057void PlaybackThread::onCodecFormatChanged(
jiabinf6eb4c32020-02-25 14:06:25 -08003058 const std::basic_string<uint8_t>& metadataBs)
3059{
Andy Hungee58e4a2023-07-07 13:47:37 -07003060 const auto weakPointerThis = wp<PlaybackThread>::fromExisting(this);
Kuowei Li9e2f6162022-11-23 16:25:26 +08003061 std::thread([this, metadataBs, weakPointerThis]() {
Andy Hungee58e4a2023-07-07 13:47:37 -07003062 const sp<PlaybackThread> playbackThread = weakPointerThis.promote();
Kuowei Li9e2f6162022-11-23 16:25:26 +08003063 if (playbackThread == nullptr) {
3064 ALOGW("PlaybackThread was destroyed, skip codec format change event");
3065 return;
3066 }
3067
jiabinf6eb4c32020-02-25 14:06:25 -08003068 audio_utils::metadata::Data metadata =
3069 audio_utils::metadata::dataFromByteString(metadataBs);
3070 if (metadata.empty()) {
3071 ALOGW("Can not transform the buffer to audio metadata, %s, %d",
3072 reinterpret_cast<char*>(const_cast<uint8_t*>(metadataBs.data())),
3073 (int)metadataBs.size());
3074 return;
3075 }
3076
3077 audio_utils::metadata::ByteString metaDataStr =
3078 audio_utils::metadata::byteStringFromData(metadata);
3079 std::vector metadataVec(metaDataStr.begin(), metaDataStr.end());
Andy Hung972bec12023-08-31 16:13:39 -07003080 audio_utils::lock_guard _l(audioTrackCbMutex());
jiabin18a4b1c2020-09-17 11:40:42 -07003081 for (const auto& callbackPair : mAudioTrackCallbacks) {
3082 callbackPair.second->onCodecFormatChanged(metadataVec);
jiabinf6eb4c32020-02-25 14:06:25 -08003083 }
3084 }).detach();
3085}
3086
Andy Hungee58e4a2023-07-07 13:47:37 -07003087void PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08003088{
Andy Hung972bec12023-08-31 16:13:39 -07003089 audio_utils::lock_guard _l(mutex());
Eric Laurent3b4529e2013-09-05 18:09:19 -07003090 // reject out of sequence requests
3091 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
3092 mWriteAckSequence &= ~1;
Andy Hungc5007f82023-08-29 14:26:09 -07003093 mWaitWorkCV.notify_one();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003094 }
3095}
3096
Andy Hungee58e4a2023-07-07 13:47:37 -07003097void PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08003098{
Andy Hung972bec12023-08-31 16:13:39 -07003099 audio_utils::lock_guard _l(mutex());
Eric Laurent3b4529e2013-09-05 18:09:19 -07003100 // reject out of sequence requests
3101 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
Andy Hungf3234512018-07-03 14:51:47 -07003102 // Register discontinuity when HW drain is completed because that can cause
3103 // the timestamp frame position to reset to 0 for direct and offload threads.
3104 // (Out of sequence requests are ignored, since the discontinuity would be handled
3105 // elsewhere, e.g. in flush).
Dean Wheatley12473e92021-03-18 23:00:55 +11003106 mTimestampVerifier.discontinuity(mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003107 mDrainSequence &= ~1;
Andy Hungc5007f82023-08-29 14:26:09 -07003108 mWaitWorkCV.notify_one();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003109 }
3110}
3111
Andy Hungee58e4a2023-07-07 13:47:37 -07003112void PlaybackThread::readOutputParameters_l()
Andy Hung972bec12023-08-31 16:13:39 -07003113NO_THREAD_SAFETY_ANALYSIS
3114// 'moveEffectChain_ll' requires holding mutex 'AudioFlinger_Mutex' exclusively
Eric Laurent81784c32012-11-19 14:55:58 -08003115{
Glenn Kastenadad3d72014-02-21 14:51:43 -08003116 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Mikhail Naganov560637e2021-03-31 22:40:13 +00003117 const audio_config_base_t audioConfig = mOutput->getAudioProperties();
3118 mSampleRate = audioConfig.sample_rate;
3119 mChannelMask = audioConfig.channel_mask;
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003120 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08003121 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003122 }
Andy Hung81994d62023-07-20 21:44:14 -07003123 if (hasMixer() && !isValidPcmSinkChannelMask(mChannelMask)) {
Andy Hung9a592762014-07-21 21:56:01 -07003124 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output",
3125 mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003126 }
Eric Laurentf1f22e72021-07-13 14:04:14 +02003127
3128 if (mMixerChannelMask == AUDIO_CHANNEL_NONE) {
3129 mMixerChannelMask = mChannelMask;
3130 }
3131
Andy Hunge5412692014-05-16 11:25:07 -07003132 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01003133 mBalance.setChannelMask(mChannelMask);
Phil Burkca5e6142015-07-14 09:42:29 -07003134
Eric Laurentf1f22e72021-07-13 14:04:14 +02003135 uint32_t mixerChannelCount = audio_channel_count_from_out_mask(mMixerChannelMask);
3136
Phil Burkca5e6142015-07-14 09:42:29 -07003137 // Get actual HAL format.
Mikhail Naganov560637e2021-03-31 22:40:13 +00003138 status_t result = mOutput->stream->getAudioProperties(nullptr, nullptr, &mHALFormat);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003139 LOG_ALWAYS_FATAL_IF(result != OK, "Error when retrieving output stream format: %d", result);
Phil Burkca5e6142015-07-14 09:42:29 -07003140 // Get format from the shim, which will be different than the HAL format
3141 // if playing compressed audio over HDMI passthrough.
Mikhail Naganov560637e2021-03-31 22:40:13 +00003142 mFormat = audioConfig.format;
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003143 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08003144 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003145 }
Andy Hung81994d62023-07-20 21:44:14 -07003146 if (hasMixer() && !isValidPcmSinkFormat(mFormat)) {
Andy Hung6146c082014-03-18 11:56:15 -07003147 LOG_FATAL("HAL format %#x not supported for mixed output",
3148 mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003149 }
Phil Burk062e67a2015-02-11 13:40:50 -08003150 mFrameSize = mOutput->getFrameSize();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003151 result = mOutput->stream->getBufferSize(&mBufferSize);
3152 LOG_ALWAYS_FATAL_IF(result != OK,
3153 "Error when retrieving output stream buffer size: %d", result);
Glenn Kasten70949c42013-08-06 07:40:12 -07003154 mFrameCount = mBufferSize / mFrameSize;
Eric Laurentb3f315a2021-07-13 15:09:05 +02003155 if (hasMixer() && (mFrameCount & 15)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003156 ALOGW("HAL output buffer size is %zu frames but AudioMixer requires multiples of 16 frames",
Eric Laurent81784c32012-11-19 14:55:58 -08003157 mFrameCount);
3158 }
3159
Eric Laurentd1f69b02014-12-15 14:33:13 -08003160 mHwSupportsPause = false;
3161 if (mOutput->flags & AUDIO_OUTPUT_FLAG_DIRECT) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003162 bool supportsPause = false, supportsResume = false;
3163 if (mOutput->stream->supportsPauseAndResume(&supportsPause, &supportsResume) == OK) {
3164 if (supportsPause && supportsResume) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08003165 mHwSupportsPause = true;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003166 } else if (supportsPause) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08003167 ALOGW("direct output implements pause but not resume");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003168 } else if (supportsResume) {
3169 ALOGW("direct output implements resume but not pause");
Eric Laurentd1f69b02014-12-15 14:33:13 -08003170 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08003171 }
3172 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07003173 if (!mHwSupportsPause && mOutput->flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) {
3174 LOG_ALWAYS_FATAL("HW_AV_SYNC requested but HAL does not implement pause and resume");
3175 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08003176
Andy Hungfbfc3952015-01-15 13:33:51 -08003177 if (mType == DUPLICATING && mMixerBufferEnabled && mEffectBufferEnabled) {
3178 // For best precision, we use float instead of the associated output
3179 // device format (typically PCM 16 bit).
3180
3181 mFormat = AUDIO_FORMAT_PCM_FLOAT;
3182 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
3183 mBufferSize = mFrameSize * mFrameCount;
3184
3185 // TODO: We currently use the associated output device channel mask and sample rate.
3186 // (1) Perhaps use the ORed channel mask of all downstream MixerThreads
3187 // (if a valid mask) to avoid premature downmix.
3188 // (2) Perhaps use the maximum sample rate of all downstream MixerThreads
3189 // instead of the output device sample rate to avoid loss of high frequency information.
3190 // This may need to be updated as MixerThread/OutputTracks are added and not here.
3191 }
3192
Andy Hung09a50072014-02-27 14:30:47 -08003193 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08003194 double multiplier = 1.0;
Andy Hungd3639922022-04-28 18:00:49 -07003195 // Note: mType == SPATIALIZER does not support FastMixer.
Eric Laurent81784c32012-11-19 14:55:58 -08003196 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
3197 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08003198 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
3199 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Haynes Mathew George227a14b2016-05-09 12:45:48 -07003200
Eric Laurent81784c32012-11-19 14:55:58 -08003201 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
3202 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
3203 maxNormalFrameCount = maxNormalFrameCount & ~15;
3204 if (maxNormalFrameCount < minNormalFrameCount) {
3205 maxNormalFrameCount = minNormalFrameCount;
3206 }
3207 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
3208 if (multiplier <= 1.0) {
3209 multiplier = 1.0;
3210 } else if (multiplier <= 2.0) {
3211 if (2 * mFrameCount <= maxNormalFrameCount) {
3212 multiplier = 2.0;
3213 } else {
3214 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
3215 }
3216 } else {
Haynes Mathew George227a14b2016-05-09 12:45:48 -07003217 multiplier = floor(multiplier);
Eric Laurent81784c32012-11-19 14:55:58 -08003218 }
3219 }
3220 mNormalFrameCount = multiplier * mFrameCount;
3221 // round up to nearest 16 frames to satisfy AudioMixer
Eric Laurentb3f315a2021-07-13 15:09:05 +02003222 if (hasMixer()) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07003223 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
3224 }
Andy Hungab65b182023-09-06 19:41:47 -07003225 ALOGI("HAL output buffer size %zu frames, normal sink buffer size %zu frames",
3226 (size_t)mFrameCount, mNormalFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08003227
Andy Hung08fb1742015-05-31 23:22:10 -07003228 // Check if we want to throttle the processing to no more than 2x normal rate
3229 mThreadThrottle = property_get_bool("af.thread.throttle", true /* default_value */);
Andy Hung40eb1a12015-06-18 13:42:02 -07003230 mThreadThrottleTimeMs = 0;
3231 mThreadThrottleEndMs = 0;
Andy Hung08fb1742015-05-31 23:22:10 -07003232 mHalfBufferMs = mNormalFrameCount * 1000 / (2 * mSampleRate);
3233
Andy Hung010a1a12014-03-13 13:57:33 -07003234 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
3235 // Originally this was int16_t[] array, need to remove legacy implications.
3236 free(mSinkBuffer);
3237 mSinkBuffer = NULL;
Eric Laurent39095982021-08-24 18:29:27 +02003238
Andy Hung5b10a202014-03-13 13:59:29 -07003239 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
3240 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
3241 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07003242 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08003243
Andy Hung69aed5f2014-02-25 17:24:40 -08003244 // We resize the mMixerBuffer according to the requirements of the sink buffer which
3245 // drives the output.
3246 free(mMixerBuffer);
3247 mMixerBuffer = NULL;
3248 if (mMixerBufferEnabled) {
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01003249 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // no longer valid: AUDIO_FORMAT_PCM_16_BIT.
Eric Laurentf1f22e72021-07-13 14:04:14 +02003250 mMixerBufferSize = mNormalFrameCount * mixerChannelCount
Andy Hung69aed5f2014-02-25 17:24:40 -08003251 * audio_bytes_per_sample(mMixerBufferFormat);
3252 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
3253 }
Andy Hung98ef9782014-03-04 14:46:50 -08003254 free(mEffectBuffer);
3255 mEffectBuffer = NULL;
3256 if (mEffectBufferEnabled) {
Andy Hung319587b2023-05-23 14:01:03 -07003257 mEffectBufferFormat = AUDIO_FORMAT_PCM_FLOAT;
Eric Laurentf1f22e72021-07-13 14:04:14 +02003258 mEffectBufferSize = mNormalFrameCount * mixerChannelCount
Andy Hung98ef9782014-03-04 14:46:50 -08003259 * audio_bytes_per_sample(mEffectBufferFormat);
3260 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
3261 }
Andy Hung69aed5f2014-02-25 17:24:40 -08003262
Eric Laurentb62d0362021-10-26 17:40:18 +02003263 if (mType == SPATIALIZER) {
3264 free(mPostSpatializerBuffer);
3265 mPostSpatializerBuffer = nullptr;
3266 mPostSpatializerBufferSize = mNormalFrameCount * mChannelCount
3267 * audio_bytes_per_sample(mEffectBufferFormat);
3268 (void)posix_memalign(&mPostSpatializerBuffer, 32, mPostSpatializerBufferSize);
3269 }
3270
Mikhail Naganov55773032020-10-01 15:08:13 -07003271 mHapticChannelMask = static_cast<audio_channel_mask_t>(mChannelMask & AUDIO_CHANNEL_HAPTIC_ALL);
3272 mChannelMask = static_cast<audio_channel_mask_t>(mChannelMask & ~mHapticChannelMask);
jiabin245cdd92018-12-07 17:55:15 -08003273 mHapticChannelCount = audio_channel_count_from_out_mask(mHapticChannelMask);
3274 mChannelCount -= mHapticChannelCount;
Eric Laurentf1f22e72021-07-13 14:04:14 +02003275 mMixerChannelMask = static_cast<audio_channel_mask_t>(mMixerChannelMask & ~mHapticChannelMask);
jiabin245cdd92018-12-07 17:55:15 -08003276
Eric Laurent81784c32012-11-19 14:55:58 -08003277 // force reconfiguration of effect chains and engines to take new buffer size and audio
3278 // parameters into account
Andy Hungc5007f82023-08-29 14:26:09 -07003279 // Note that mutex() is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08003280 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
3281 // matter.
Andy Hung972bec12023-08-31 16:13:39 -07003282 // create a copy of mEffectChains as calling moveEffectChain_ll()
3283 // can reorder some effect chains
Andy Hung116bc262023-06-20 18:56:17 -07003284 Vector<sp<IAfEffectChain>> effectChains = mEffectChains;
Eric Laurent81784c32012-11-19 14:55:58 -08003285 for (size_t i = 0; i < effectChains.size(); i ++) {
Andy Hung972bec12023-08-31 16:13:39 -07003286 mAfThreadCallback->moveEffectChain_ll(effectChains[i]->sessionId(),
Eric Laurent6c796322019-04-09 14:13:17 -07003287 this/* srcThread */, this/* dstThread */);
Eric Laurent81784c32012-11-19 14:55:58 -08003288 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08003289
George Burgess IV5e4d86f2020-02-18 12:55:36 -08003290 audio_output_flags_t flags = mOutput->flags;
Andy Hungcf10d742020-04-28 15:38:24 -07003291 mediametrics::LogItem item(mThreadMetrics.getMetricsId()); // TODO: method in ThreadMetrics?
Andy Hungb68f5eb2019-12-03 16:49:17 -08003292 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
Andy Hung25a80ac2023-07-19 12:47:35 -07003293 .set(AMEDIAMETRICS_PROP_ENCODING, IAfThreadBase::formatToString(mFormat).c_str())
Andy Hungb68f5eb2019-12-03 16:49:17 -08003294 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
3295 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
3296 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
3297 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mNormalFrameCount)
3298 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
3299 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELMASK,
3300 (int32_t)mHapticChannelMask)
3301 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELCOUNT,
3302 (int32_t)mHapticChannelCount)
3303 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_ENCODING,
Andy Hung25a80ac2023-07-19 12:47:35 -07003304 IAfThreadBase::formatToString(mHALFormat).c_str())
Andy Hungb68f5eb2019-12-03 16:49:17 -08003305 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_FRAMECOUNT,
3306 (int32_t)mFrameCount) // sic - added HAL
3307 ;
3308 uint32_t latencyMs;
3309 if (mOutput->stream->getLatency(&latencyMs) == NO_ERROR) {
3310 item.set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_LATENCYMS, (double)latencyMs);
3311 }
3312 item.record();
Eric Laurent81784c32012-11-19 14:55:58 -08003313}
3314
Andy Hungee58e4a2023-07-07 13:47:37 -07003315ThreadBase::MetadataUpdate PlaybackThread::updateMetadata_l()
Kevin Rocard069c2712018-03-29 19:09:14 -07003316{
Jasmine Chaeaa10e42021-05-11 10:11:14 +08003317 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
Vlad Popa7e81cea2023-01-19 16:34:16 +01003318 return {}; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -07003319 }
3320 StreamOutHalInterface::SourceMetadata metadata;
Eric Laurent4eb45d02023-12-20 12:07:17 +01003321 if (com_android_media_audio_stereo_spatialization()) {
3322 std::map<audio_session_t, std::vector<playback_track_metadata_v7_t> >allSessionsMetadata;
3323 for (const sp<IAfTrack>& track : mActiveTracks) {
3324 std::vector<playback_track_metadata_v7_t>& sessionMetadata =
3325 allSessionsMetadata[track->sessionId()];
3326 auto backInserter = std::back_inserter(sessionMetadata);
3327 // No track is invalid as this is called after prepareTrack_l in the same
3328 // critical section
3329 track->copyMetadataTo(backInserter);
3330 }
3331 std::vector<playback_track_metadata_v7_t> spatializedTracksMetaData;
3332 for (const auto& [session, sessionTrackMetadata] : allSessionsMetadata) {
3333 metadata.tracks.insert(metadata.tracks.end(),
3334 sessionTrackMetadata.begin(), sessionTrackMetadata.end());
3335 if (auto chain = getEffectChain_l(session) ; chain != nullptr) {
3336 chain->sendMetadata_l(sessionTrackMetadata, {});
3337 }
3338 if ((hasAudioSession_l(session) & IAfThreadBase::SPATIALIZED_SESSION) != 0) {
3339 spatializedTracksMetaData.insert(spatializedTracksMetaData.end(),
3340 sessionTrackMetadata.begin(), sessionTrackMetadata.end());
3341 }
3342 }
3343 if (auto chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX); chain != nullptr) {
3344 chain->sendMetadata_l(metadata.tracks, {});
3345 }
3346 if (auto chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_STAGE); chain != nullptr) {
3347 chain->sendMetadata_l(metadata.tracks, spatializedTracksMetaData);
3348 }
3349 if (auto chain = getEffectChain_l(AUDIO_SESSION_DEVICE); chain != nullptr) {
3350 chain->sendMetadata_l(metadata.tracks, {});
3351 }
3352 } else {
3353 auto backInserter = std::back_inserter(metadata.tracks);
3354 for (const sp<IAfTrack>& track : mActiveTracks) {
3355 // No track is invalid as this is called after prepareTrack_l in the same
3356 // critical section
3357 track->copyMetadataTo(backInserter);
3358 }
Kevin Rocard069c2712018-03-29 19:09:14 -07003359 }
Kevin Rocard12381092018-04-11 09:19:59 -07003360 sendMetadataToBackend_l(metadata);
Vlad Popa7e81cea2023-01-19 16:34:16 +01003361 MetadataUpdate change;
3362 change.playbackMetadataUpdate = metadata.tracks;
3363 return change;
Kevin Rocard80ee2722018-04-11 15:53:48 +00003364}
Kevin Rocardc86a7f72018-04-03 09:00:09 -07003365
Andy Hungee58e4a2023-07-07 13:47:37 -07003366void PlaybackThread::sendMetadataToBackend_l(
Kevin Rocard12381092018-04-11 09:19:59 -07003367 const StreamOutHalInterface::SourceMetadata& metadata)
3368{
3369 mOutput->stream->updateSourceMetadata(metadata);
3370};
3371
Andy Hungee58e4a2023-07-07 13:47:37 -07003372status_t PlaybackThread::getRenderPosition(
Andy Hung440901d2023-06-29 21:19:25 -07003373 uint32_t* halFrames, uint32_t* dspFrames) const
Eric Laurent81784c32012-11-19 14:55:58 -08003374{
3375 if (halFrames == NULL || dspFrames == NULL) {
3376 return BAD_VALUE;
3377 }
Andy Hung972bec12023-08-31 16:13:39 -07003378 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08003379 if (initCheck() != NO_ERROR) {
3380 return INVALID_OPERATION;
3381 }
Andy Hung818e7a32016-02-16 18:08:07 -08003382 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08003383 *halFrames = framesWritten;
3384
3385 if (isSuspended()) {
3386 // return an estimation of rendered frames when the output is suspended
3387 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08003388 *dspFrames = (uint32_t)
3389 (framesWritten >= (int64_t)latencyFrames ? framesWritten - latencyFrames : 0);
Eric Laurent81784c32012-11-19 14:55:58 -08003390 return NO_ERROR;
3391 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003392 status_t status;
3393 uint32_t frames;
Phil Burk062e67a2015-02-11 13:40:50 -08003394 status = mOutput->getRenderPosition(&frames);
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003395 *dspFrames = (size_t)frames;
3396 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08003397 }
3398}
3399
Andy Hungee58e4a2023-07-07 13:47:37 -07003400product_strategy_t PlaybackThread::getStrategyForSession_l(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08003401{
3402 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
3403 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
3404 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02003405 return getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurent81784c32012-11-19 14:55:58 -08003406 }
3407 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003408 sp<IAfTrack> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08003409 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02003410 return getStrategyForStream(track->streamType());
Eric Laurent81784c32012-11-19 14:55:58 -08003411 }
3412 }
Eric Laurentd66d7a12021-07-13 13:35:32 +02003413 return getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurent81784c32012-11-19 14:55:58 -08003414}
3415
3416
Andy Hungee58e4a2023-07-07 13:47:37 -07003417AudioStreamOut* PlaybackThread::getOutput() const
Eric Laurent81784c32012-11-19 14:55:58 -08003418{
Andy Hung972bec12023-08-31 16:13:39 -07003419 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08003420 return mOutput;
3421}
3422
Andy Hungee58e4a2023-07-07 13:47:37 -07003423AudioStreamOut* PlaybackThread::clearOutput()
Eric Laurent81784c32012-11-19 14:55:58 -08003424{
Andy Hung972bec12023-08-31 16:13:39 -07003425 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08003426 AudioStreamOut *output = mOutput;
3427 mOutput = NULL;
3428 // FIXME FastMixer might also have a raw ptr to mOutputSink;
3429 // must push a NULL and wait for ack
3430 mOutputSink.clear();
3431 mPipeSink.clear();
3432 mNormalSink.clear();
3433 return output;
3434}
3435
Andy Hungc5007f82023-08-29 14:26:09 -07003436// this method must always be called either with ThreadBase mutex() held or inside the thread loop
Andy Hungee58e4a2023-07-07 13:47:37 -07003437sp<StreamHalInterface> PlaybackThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08003438{
3439 if (mOutput == NULL) {
3440 return NULL;
3441 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003442 return mOutput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08003443}
3444
Andy Hungee58e4a2023-07-07 13:47:37 -07003445uint32_t PlaybackThread::activeSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08003446{
3447 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
3448}
3449
Andy Hungee58e4a2023-07-07 13:47:37 -07003450status_t PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
Eric Laurent81784c32012-11-19 14:55:58 -08003451{
3452 if (!isValidSyncEvent(event)) {
3453 return BAD_VALUE;
3454 }
3455
Andy Hung972bec12023-08-31 16:13:39 -07003456 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08003457
3458 for (size_t i = 0; i < mTracks.size(); ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003459 sp<IAfTrack> track = mTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08003460 if (event->triggerSession() == track->sessionId()) {
3461 (void) track->setSyncEvent(event);
3462 return NO_ERROR;
3463 }
3464 }
3465
3466 return NAME_NOT_FOUND;
3467}
3468
Andy Hungee58e4a2023-07-07 13:47:37 -07003469bool PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
Eric Laurent81784c32012-11-19 14:55:58 -08003470{
3471 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
3472}
3473
Andy Hungee58e4a2023-07-07 13:47:37 -07003474void PlaybackThread::threadLoop_removeTracks(
Andy Hung8d31fd22023-06-26 19:20:57 -07003475 [[maybe_unused]] const Vector<sp<IAfTrack>>& tracksToRemove)
Eric Laurent81784c32012-11-19 14:55:58 -08003476{
Andy Hungfe726a62018-09-27 15:17:25 -07003477 // Miscellaneous track cleanup when removed from the active list,
3478 // called without Thread lock but synchronized with threadLoop processing.
Eric Laurentbfb1b832013-01-07 09:53:42 -08003479#ifdef ADD_BATTERY_DATA
Andy Hungfe726a62018-09-27 15:17:25 -07003480 for (const auto& track : tracksToRemove) {
3481 if (track->isExternalTrack()) {
3482 // to track the speaker usage
3483 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Eric Laurent81784c32012-11-19 14:55:58 -08003484 }
3485 }
Andy Hungfe726a62018-09-27 15:17:25 -07003486#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003487}
3488
Andy Hungee58e4a2023-07-07 13:47:37 -07003489void PlaybackThread::checkSilentMode_l()
Eric Laurent81784c32012-11-19 14:55:58 -08003490{
3491 if (!mMasterMute) {
3492 char value[PROPERTY_VALUE_MAX];
jiabin0a957d32020-04-29 10:56:20 -07003493 if (mOutDeviceTypeAddrs.empty()) {
3494 ALOGD("ro.audio.silent is ignored since no output device is set");
3495 return;
3496 }
Andy Hungab65b182023-09-06 19:41:47 -07003497 if (isSingleDeviceType(outDeviceTypes_l(), AUDIO_DEVICE_OUT_REMOTE_SUBMIX)) {
Jean-Michel Trivi32f37c22016-03-31 16:00:32 -07003498 ALOGD("ro.audio.silent will be ignored for threads on AUDIO_DEVICE_OUT_REMOTE_SUBMIX");
3499 return;
3500 }
Eric Laurent81784c32012-11-19 14:55:58 -08003501 if (property_get("ro.audio.silent", value, "0") > 0) {
3502 char *endptr;
3503 unsigned long ul = strtoul(value, &endptr, 0);
3504 if (*endptr == '\0' && ul != 0) {
3505 ALOGD("Silence is golden");
3506 // The setprop command will not allow a property to be changed after
3507 // the first time it is set, so we don't have to worry about un-muting.
3508 setMasterMute_l(true);
3509 }
3510 }
3511 }
3512}
3513
3514// shared by MIXER and DIRECT, overridden by DUPLICATING
Andy Hungee58e4a2023-07-07 13:47:37 -07003515ssize_t PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08003516{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07003517 LOG_HIST_TS();
Eric Laurent81784c32012-11-19 14:55:58 -08003518 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003519 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07003520 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08003521
3522 // If an NBAIO sink is present, use it to write the normal mixer's submix
3523 if (mNormalSink != 0) {
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003524
Andy Hung010a1a12014-03-13 13:57:33 -07003525 const size_t count = mBytesRemaining / mFrameSize;
3526
Simon Wilson2d590962012-11-29 15:18:50 -08003527 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08003528 // update the setpoint when AudioFlinger::mScreenState changes
Andy Hung1d2d2aea2023-07-19 16:22:58 -07003529 const uint32_t screenState = mAfThreadCallback->getScreenState();
Eric Laurent81784c32012-11-19 14:55:58 -08003530 if (screenState != mScreenState) {
3531 mScreenState = screenState;
3532 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
3533 if (pipe != NULL) {
3534 pipe->setAvgFrames((mScreenState & 1) ?
3535 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
3536 }
3537 }
Andy Hung010a1a12014-03-13 13:57:33 -07003538 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08003539 ATRACE_END();
Vlad Popab042ee62022-10-20 18:05:00 +02003540
Eric Laurent81784c32012-11-19 14:55:58 -08003541 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07003542 bytesWritten = framesWritten * mFrameSize;
Andy Hung58e32872022-11-15 16:12:24 -08003543
Andy Hung8946a282018-04-19 20:04:56 -07003544#ifdef TEE_SINK
3545 mTee.write((char *)mSinkBuffer + offset, framesWritten);
3546#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003547 } else {
3548 bytesWritten = framesWritten;
3549 }
3550 // otherwise use the HAL / AudioStreamOut directly
3551 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003552 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07003553
Eric Laurentbfb1b832013-01-07 09:53:42 -08003554 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003555 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
3556 mWriteAckSequence += 2;
3557 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003558 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003559 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003560 }
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07003561 ATRACE_BEGIN("write");
Glenn Kasten767094d2013-08-23 13:51:43 -07003562 // FIXME We should have an implementation of timestamps for direct output threads.
3563 // They are used e.g for multichannel PCM playback over HDMI.
Phil Burk062e67a2015-02-11 13:40:50 -08003564 bytesWritten = mOutput->write((char *)mSinkBuffer + offset, mBytesRemaining);
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07003565 ATRACE_END();
Eric Laurent51716182016-02-29 18:00:56 -08003566
Eric Laurentbfb1b832013-01-07 09:53:42 -08003567 if (mUseAsyncWrite &&
3568 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
3569 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07003570 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003571 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003572 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003573 }
Eric Laurent81784c32012-11-19 14:55:58 -08003574 }
3575
Eric Laurent81784c32012-11-19 14:55:58 -08003576 mNumWrites++;
3577 mInWrite = false;
Andy Hungcf10d742020-04-28 15:38:24 -07003578 if (mStandby) {
3579 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07003580 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -07003581 mStandby = false;
3582 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003583 return bytesWritten;
3584}
3585
Andy Hungc5007f82023-08-29 14:26:09 -07003586// startMelComputation_l() must be called with AudioFlinger::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07003587void PlaybackThread::startMelComputation_l(
Vlad Popaf09e93f2022-10-31 16:27:12 +01003588 const sp<audio_utils::MelProcessor>& processor)
Vlad Popab042ee62022-10-20 18:05:00 +02003589{
Vlad Popa3c7a2662023-02-14 20:09:47 +01003590 auto outputSink = static_cast<AudioStreamOutSink*>(mOutputSink.get());
Vlad Popa1a0c3ab2023-03-17 01:07:01 +01003591 if (outputSink != nullptr) {
3592 outputSink->startMelComputation(processor);
3593 }
Vlad Popab042ee62022-10-20 18:05:00 +02003594}
3595
Andy Hungc5007f82023-08-29 14:26:09 -07003596// stopMelComputation_l() must be called with AudioFlinger::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07003597void PlaybackThread::stopMelComputation_l()
Vlad Popa3c7a2662023-02-14 20:09:47 +01003598{
3599 auto outputSink = static_cast<AudioStreamOutSink*>(mOutputSink.get());
Vlad Popa1a0c3ab2023-03-17 01:07:01 +01003600 if (outputSink != nullptr) {
3601 outputSink->stopMelComputation();
3602 }
Vlad Popab042ee62022-10-20 18:05:00 +02003603}
3604
Andy Hungee58e4a2023-07-07 13:47:37 -07003605void PlaybackThread::threadLoop_drain()
Eric Laurentbfb1b832013-01-07 09:53:42 -08003606{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003607 bool supportsDrain = false;
3608 if (mOutput->stream->supportsDrain(&supportsDrain) == OK && supportsDrain) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003609 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
3610 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003611 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
3612 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003613 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003614 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003615 }
Mikhail Naganovcbc8f612016-10-11 18:05:13 -07003616 status_t result = mOutput->stream->drain(mMixerStatus == MIXER_DRAIN_TRACK);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003617 ALOGE_IF(result != OK, "Error when draining stream: %d", result);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003618 }
3619}
3620
Andy Hungee58e4a2023-07-07 13:47:37 -07003621void PlaybackThread::threadLoop_exit()
Eric Laurentbfb1b832013-01-07 09:53:42 -08003622{
Eric Laurent275e8e92014-11-30 15:14:47 -08003623 {
Andy Hung972bec12023-08-31 16:13:39 -07003624 audio_utils::lock_guard _l(mutex());
Eric Laurent275e8e92014-11-30 15:14:47 -08003625 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003626 sp<IAfTrack> track = mTracks[i];
Eric Laurent275e8e92014-11-30 15:14:47 -08003627 track->invalidate();
3628 }
Andy Hungdae27702016-10-31 14:01:16 -07003629 // Clear ActiveTracks to update BatteryNotifier in case active tracks remain.
3630 // After we exit there are no more track changes sent to BatteryNotifier
3631 // because that requires an active threadLoop.
3632 // TODO: should we decActiveTrackCnt() of the cleared track effect chain?
3633 mActiveTracks.clear();
Eric Laurent275e8e92014-11-30 15:14:47 -08003634 }
Eric Laurent81784c32012-11-19 14:55:58 -08003635}
3636
3637/*
3638The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08003639 - mSinkBufferSize from frame count * frame size
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003640 - mActiveSleepTimeUs from activeSleepTimeUs()
3641 - mIdleSleepTimeUs from idleSleepTimeUs()
Eric Laurent42537be2016-01-08 17:16:42 -08003642 - mStandbyDelayNs from mActiveSleepTimeUs (DIRECT only) or forced to at least
3643 kDefaultStandbyTimeInNsecs when connected to an A2DP device.
Eric Laurent81784c32012-11-19 14:55:58 -08003644 - maxPeriod from frame count and sample rate (MIXER only)
3645
3646The parameters that affect these derived values are:
3647 - frame count
3648 - frame size
3649 - sample rate
3650 - device type: A2DP or not
3651 - device latency
3652 - format: PCM or not
3653 - active sleep time
3654 - idle sleep time
3655*/
3656
Andy Hungee58e4a2023-07-07 13:47:37 -07003657void PlaybackThread::cacheParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08003658{
Andy Hung25c2dac2014-02-27 14:56:00 -08003659 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003660 mActiveSleepTimeUs = activeSleepTimeUs();
3661 mIdleSleepTimeUs = idleSleepTimeUs();
Eric Laurent42537be2016-01-08 17:16:42 -08003662
Andy Hung8fe87eb2023-07-20 21:31:38 -07003663 mStandbyDelayNs = getStandbyTimeInNanos();
Carter Hsu0ca47c22023-06-02 18:01:45 +08003664
Eric Laurent42537be2016-01-08 17:16:42 -08003665 // make sure standby delay is not too short when connected to an A2DP sink to avoid
3666 // truncating audio when going to standby.
Andy Hungab65b182023-09-06 19:41:47 -07003667 if (!Intersection(outDeviceTypes_l(), getAudioDeviceOutAllA2dpSet()).empty()) {
Eric Laurent42537be2016-01-08 17:16:42 -08003668 if (mStandbyDelayNs < kDefaultStandbyTimeInNsecs) {
3669 mStandbyDelayNs = kDefaultStandbyTimeInNsecs;
3670 }
3671 }
Eric Laurent81784c32012-11-19 14:55:58 -08003672}
3673
Andy Hungee58e4a2023-07-07 13:47:37 -07003674bool PlaybackThread::invalidateTracks_l(audio_stream_type_t streamType)
Eric Laurent81784c32012-11-19 14:55:58 -08003675{
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003676 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %zu",
Eric Laurent81784c32012-11-19 14:55:58 -08003677 this, streamType, mTracks.size());
Eric Laurent13084622016-05-17 10:51:49 -07003678 bool trackMatch = false;
Eric Laurent81784c32012-11-19 14:55:58 -08003679 size_t size = mTracks.size();
3680 for (size_t i = 0; i < size; i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003681 sp<IAfTrack> t = mTracks[i];
Eric Laurentd60560a2015-04-10 11:31:20 -07003682 if (t->streamType() == streamType && t->isExternalTrack()) {
Glenn Kasten5736c352012-12-04 12:12:34 -08003683 t->invalidate();
Eric Laurent13084622016-05-17 10:51:49 -07003684 trackMatch = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003685 }
3686 }
Eric Laurent13084622016-05-17 10:51:49 -07003687 return trackMatch;
Eric Laurent81784c32012-11-19 14:55:58 -08003688}
3689
Andy Hungee58e4a2023-07-07 13:47:37 -07003690void PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
Haynes Mathew George05317d22016-05-03 16:34:26 -07003691{
Andy Hung972bec12023-08-31 16:13:39 -07003692 audio_utils::lock_guard _l(mutex());
Haynes Mathew George05317d22016-05-03 16:34:26 -07003693 invalidateTracks_l(streamType);
3694}
3695
Andy Hungee58e4a2023-07-07 13:47:37 -07003696void PlaybackThread::invalidateTracks(std::set<audio_port_handle_t>& portIds) {
Andy Hung972bec12023-08-31 16:13:39 -07003697 audio_utils::lock_guard _l(mutex());
jiabinc44b3462022-12-08 12:52:31 -08003698 invalidateTracks_l(portIds);
3699}
3700
Andy Hungee58e4a2023-07-07 13:47:37 -07003701bool PlaybackThread::invalidateTracks_l(std::set<audio_port_handle_t>& portIds) {
jiabinc44b3462022-12-08 12:52:31 -08003702 bool trackMatch = false;
3703 const size_t size = mTracks.size();
3704 for (size_t i = 0; i < size; i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003705 sp<IAfTrack> t = mTracks[i];
jiabinc44b3462022-12-08 12:52:31 -08003706 if (t->isExternalTrack() && portIds.find(t->portId()) != portIds.end()) {
3707 t->invalidate();
3708 portIds.erase(t->portId());
3709 trackMatch = true;
3710 }
3711 if (portIds.empty()) {
3712 break;
3713 }
3714 }
3715 return trackMatch;
3716}
3717
jiabinf042b9b2021-05-07 23:46:28 +00003718// getTrackById_l must be called with holding thread lock
Andy Hungee58e4a2023-07-07 13:47:37 -07003719IAfTrack* PlaybackThread::getTrackById_l(
jiabinf042b9b2021-05-07 23:46:28 +00003720 audio_port_handle_t trackPortId) {
3721 for (size_t i = 0; i < mTracks.size(); i++) {
3722 if (mTracks[i]->portId() == trackPortId) {
3723 return mTracks[i].get();
3724 }
3725 }
3726 return nullptr;
3727}
3728
Andy Hungee58e4a2023-07-07 13:47:37 -07003729status_t PlaybackThread::addEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08003730{
Glenn Kastend848eb42016-03-08 13:42:11 -08003731 audio_session_t session = chain->sessionId();
Mikhail Naganov022b9952017-01-04 16:36:51 -08003732 sp<EffectBufferHalInterface> halInBuffer, halOutBuffer;
Andy Hung319587b2023-05-23 14:01:03 -07003733 float *buffer = nullptr; // only used for non global sessions
Eric Laurentb62d0362021-10-26 17:40:18 +02003734
Andy Hungd3639922022-04-28 18:00:49 -07003735 if (mType == SPATIALIZER) {
Eric Laurentb62d0362021-10-26 17:40:18 +02003736 if (!audio_is_global_session(session)) {
3737 // player sessions on a spatializer output will use a dedicated input buffer and
3738 // will either output multi channel to mEffectBuffer if the track is spatilaized
3739 // or stereo to mPostSpatializerBuffer if not spatialized.
3740 uint32_t channelMask;
3741 bool isSessionSpatialized =
3742 (hasAudioSession_l(session) & ThreadBase::SPATIALIZED_SESSION) != 0;
3743 if (isSessionSpatialized) {
3744 channelMask = mMixerChannelMask;
3745 } else {
3746 channelMask = mChannelMask;
3747 }
Eric Laurentf1f22e72021-07-13 14:04:14 +02003748 size_t numSamples = mNormalFrameCount
Eric Laurentb62d0362021-10-26 17:40:18 +02003749 * (audio_channel_count_from_out_mask(channelMask) + mHapticChannelCount);
Andy Hung583043b2023-07-17 17:05:00 -07003750 status_t result = mAfThreadCallback->getEffectsFactoryHal()->allocateBuffer(
Andy Hung319587b2023-05-23 14:01:03 -07003751 numSamples * sizeof(float),
Mikhail Naganov022b9952017-01-04 16:36:51 -08003752 &halInBuffer);
3753 if (result != OK) return result;
Eric Laurentb62d0362021-10-26 17:40:18 +02003754
Andy Hung583043b2023-07-17 17:05:00 -07003755 result = mAfThreadCallback->getEffectsFactoryHal()->mirrorBuffer(
Eric Laurentb62d0362021-10-26 17:40:18 +02003756 isSessionSpatialized ? mEffectBuffer : mPostSpatializerBuffer,
3757 isSessionSpatialized ? mEffectBufferSize : mPostSpatializerBufferSize,
3758 &halOutBuffer);
3759 if (result != OK) return result;
3760
Shunkai Yao44bdbad2023-01-14 05:11:58 +00003761 buffer = halInBuffer ? halInBuffer->audioBuffer()->f32 : buffer;
Andy Hung26836922023-05-22 17:31:57 -07003762
Mikhail Naganov022b9952017-01-04 16:36:51 -08003763 ALOGV("addEffectChain_l() creating new input buffer %p session %d",
3764 buffer, session);
Eric Laurentb62d0362021-10-26 17:40:18 +02003765 } else {
3766 // A global session on a SPATIALIZER thread is either OUTPUT_STAGE or DEVICE
3767 // - OUTPUT_STAGE session uses the mEffectBuffer as input buffer and
3768 // mPostSpatializerBuffer as output buffer
3769 // - DEVICE session uses the mPostSpatializerBuffer as input and output buffer.
Andy Hung583043b2023-07-17 17:05:00 -07003770 status_t result = mAfThreadCallback->getEffectsFactoryHal()->mirrorBuffer(
Eric Laurentb62d0362021-10-26 17:40:18 +02003771 mEffectBuffer, mEffectBufferSize, &halInBuffer);
3772 if (result != OK) return result;
Andy Hung583043b2023-07-17 17:05:00 -07003773 result = mAfThreadCallback->getEffectsFactoryHal()->mirrorBuffer(
Eric Laurentb62d0362021-10-26 17:40:18 +02003774 mPostSpatializerBuffer, mPostSpatializerBufferSize, &halOutBuffer);
3775 if (result != OK) return result;
Eric Laurent81784c32012-11-19 14:55:58 -08003776
Eric Laurentb62d0362021-10-26 17:40:18 +02003777 if (session == AUDIO_SESSION_DEVICE) {
3778 halInBuffer = halOutBuffer;
3779 }
3780 }
3781 } else {
Andy Hung583043b2023-07-17 17:05:00 -07003782 status_t result = mAfThreadCallback->getEffectsFactoryHal()->mirrorBuffer(
Eric Laurentb62d0362021-10-26 17:40:18 +02003783 mEffectBufferEnabled ? mEffectBuffer : mSinkBuffer,
3784 mEffectBufferEnabled ? mEffectBufferSize : mSinkBufferSize,
3785 &halInBuffer);
3786 if (result != OK) return result;
3787 halOutBuffer = halInBuffer;
3788 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
3789 if (!audio_is_global_session(session)) {
Andy Hung319587b2023-05-23 14:01:03 -07003790 buffer = halInBuffer ? reinterpret_cast<float*>(halInBuffer->externalData())
Shunkai Yao44bdbad2023-01-14 05:11:58 +00003791 : buffer;
Eric Laurentb62d0362021-10-26 17:40:18 +02003792 // Only one effect chain can be present in direct output thread and it uses
3793 // the sink buffer as input
3794 if (mType != DIRECT) {
3795 size_t numSamples = mNormalFrameCount
3796 * (audio_channel_count_from_out_mask(mMixerChannelMask)
3797 + mHapticChannelCount);
Andy Hung583043b2023-07-17 17:05:00 -07003798 const status_t allocateStatus =
3799 mAfThreadCallback->getEffectsFactoryHal()->allocateBuffer(
Andy Hung319587b2023-05-23 14:01:03 -07003800 numSamples * sizeof(float),
Eric Laurentb62d0362021-10-26 17:40:18 +02003801 &halInBuffer);
Andy Hung920f6572022-10-06 12:09:49 -07003802 if (allocateStatus != OK) return allocateStatus;
Andy Hung26836922023-05-22 17:31:57 -07003803
Shunkai Yao44bdbad2023-01-14 05:11:58 +00003804 buffer = halInBuffer ? halInBuffer->audioBuffer()->f32 : buffer;
Eric Laurentb62d0362021-10-26 17:40:18 +02003805 ALOGV("addEffectChain_l() creating new input buffer %p session %d",
3806 buffer, session);
3807 }
3808 }
3809 }
3810
3811 if (!audio_is_global_session(session)) {
Eric Laurent81784c32012-11-19 14:55:58 -08003812 // Attach all tracks with same session ID to this chain.
3813 for (size_t i = 0; i < mTracks.size(); ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003814 sp<IAfTrack> track = mTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08003815 if (session == track->sessionId()) {
Eric Laurentb62d0362021-10-26 17:40:18 +02003816 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p",
3817 track.get(), buffer);
Eric Laurent81784c32012-11-19 14:55:58 -08003818 track->setMainBuffer(buffer);
3819 chain->incTrackCnt();
3820 }
3821 }
3822
3823 // indicate all active tracks in the chain
Andy Hung8d31fd22023-06-26 19:20:57 -07003824 for (const sp<IAfTrack>& track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08003825 if (session == track->sessionId()) {
Eric Laurentb62d0362021-10-26 17:40:18 +02003826 ALOGV("addEffectChain_l() activating track %p on session %d",
3827 track.get(), session);
Eric Laurent81784c32012-11-19 14:55:58 -08003828 chain->incActiveTrackCnt();
3829 }
3830 }
3831 }
Eric Laurentb62d0362021-10-26 17:40:18 +02003832
Eric Laurentaaa44472014-09-12 17:41:50 -07003833 chain->setThread(this);
Mikhail Naganov022b9952017-01-04 16:36:51 -08003834 chain->setInBuffer(halInBuffer);
3835 chain->setOutBuffer(halOutBuffer);
Eric Laurent3f75a5b2019-11-12 15:55:51 -08003836 // Effect chain for session AUDIO_SESSION_DEVICE is inserted at end of effect
3837 // chains list in order to be processed last as it contains output device effects.
3838 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted just before to apply post
3839 // processing effects specific to an output stream before effects applied to all streams
3840 // routed to a given device.
Eric Laurent81784c32012-11-19 14:55:58 -08003841 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
3842 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Glenn Kastend848eb42016-03-08 13:42:11 -08003843 // after track specific effects and before output stage.
Eric Laurent81784c32012-11-19 14:55:58 -08003844 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
Glenn Kastend848eb42016-03-08 13:42:11 -08003845 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX.
Eric Laurent81784c32012-11-19 14:55:58 -08003846 // Effect chain for other sessions are inserted at beginning of effect
3847 // chains list to be processed before output mix effects. Relative order between other
Glenn Kastend848eb42016-03-08 13:42:11 -08003848 // sessions is not important.
3849 static_assert(AUDIO_SESSION_OUTPUT_MIX == 0 &&
Eric Laurent3f75a5b2019-11-12 15:55:51 -08003850 AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX &&
3851 AUDIO_SESSION_DEVICE < AUDIO_SESSION_OUTPUT_STAGE,
Glenn Kastend848eb42016-03-08 13:42:11 -08003852 "audio_session_t constants misdefined");
Eric Laurent81784c32012-11-19 14:55:58 -08003853 size_t size = mEffectChains.size();
3854 size_t i = 0;
3855 for (i = 0; i < size; i++) {
3856 if (mEffectChains[i]->sessionId() < session) {
3857 break;
3858 }
3859 }
3860 mEffectChains.insertAt(chain, i);
3861 checkSuspendOnAddEffectChain_l(chain);
3862
3863 return NO_ERROR;
3864}
3865
Andy Hungee58e4a2023-07-07 13:47:37 -07003866size_t PlaybackThread::removeEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08003867{
Glenn Kastend848eb42016-03-08 13:42:11 -08003868 audio_session_t session = chain->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08003869
3870 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
3871
3872 for (size_t i = 0; i < mEffectChains.size(); i++) {
3873 if (chain == mEffectChains[i]) {
3874 mEffectChains.removeAt(i);
3875 // detach all active tracks from the chain
Andy Hung8d31fd22023-06-26 19:20:57 -07003876 for (const sp<IAfTrack>& track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08003877 if (session == track->sessionId()) {
3878 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
3879 chain.get(), session);
3880 chain->decActiveTrackCnt();
3881 }
3882 }
3883
3884 // detach all tracks with same session ID from this chain
Andy Hung920f6572022-10-06 12:09:49 -07003885 for (size_t j = 0; j < mTracks.size(); ++j) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003886 sp<IAfTrack> track = mTracks[j];
Eric Laurent81784c32012-11-19 14:55:58 -08003887 if (session == track->sessionId()) {
Andy Hung319587b2023-05-23 14:01:03 -07003888 track->setMainBuffer(reinterpret_cast<float*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08003889 chain->decTrackCnt();
3890 }
3891 }
3892 break;
3893 }
3894 }
3895 return mEffectChains.size();
3896}
3897
Andy Hungee58e4a2023-07-07 13:47:37 -07003898status_t PlaybackThread::attachAuxEffect(
Andy Hung8d31fd22023-06-26 19:20:57 -07003899 const sp<IAfTrack>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003900{
Andy Hung972bec12023-08-31 16:13:39 -07003901 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08003902 return attachAuxEffect_l(track, EffectId);
3903}
3904
Andy Hungee58e4a2023-07-07 13:47:37 -07003905status_t PlaybackThread::attachAuxEffect_l(
Andy Hung8d31fd22023-06-26 19:20:57 -07003906 const sp<IAfTrack>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003907{
3908 status_t status = NO_ERROR;
3909
3910 if (EffectId == 0) {
3911 track->setAuxBuffer(0, NULL);
3912 } else {
3913 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
Andy Hung116bc262023-06-20 18:56:17 -07003914 sp<IAfEffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Eric Laurent81784c32012-11-19 14:55:58 -08003915 if (effect != 0) {
3916 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
3917 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
3918 } else {
3919 status = INVALID_OPERATION;
3920 }
3921 } else {
3922 status = BAD_VALUE;
3923 }
3924 }
3925 return status;
3926}
3927
Andy Hungee58e4a2023-07-07 13:47:37 -07003928void PlaybackThread::detachAuxEffect_l(int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003929{
3930 for (size_t i = 0; i < mTracks.size(); ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003931 sp<IAfTrack> track = mTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08003932 if (track->auxEffectId() == effectId) {
3933 attachAuxEffect_l(track, 0);
3934 }
3935 }
3936}
3937
Andy Hungee58e4a2023-07-07 13:47:37 -07003938bool PlaybackThread::threadLoop()
Andy Hung920f6572022-10-06 12:09:49 -07003939NO_THREAD_SAFETY_ANALYSIS // manual locking of AudioFlinger
Eric Laurent81784c32012-11-19 14:55:58 -08003940{
Andy Hung78d8d952023-05-30 18:10:23 -07003941 aflog::setThreadWriter(mNBLogWriter.get());
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003942
Andy Hung077d62e2023-10-03 10:49:34 -07003943 if (mType == SPATIALIZER) {
3944 const pid_t tid = getTid();
3945 if (tid == -1) { // odd: we are here, we must be a running thread.
3946 ALOGW("%s: Cannot update Spatializer mixer thread priority, no tid", __func__);
3947 } else {
Andy Hung639dbc92023-11-28 18:21:55 +00003948 const int priorityBoost = requestSpatializerPriority(getpid(), tid);
3949 if (priorityBoost > 0) {
3950 stream()->setHalThreadPriority(priorityBoost);
3951 }
Andy Hung077d62e2023-10-03 10:49:34 -07003952 }
3953 }
3954
Andy Hung8d31fd22023-06-26 19:20:57 -07003955 Vector<sp<IAfTrack>> tracksToRemove;
Eric Laurent81784c32012-11-19 14:55:58 -08003956
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003957 mStandbyTimeNs = systemTime();
Andy Hung446f4df2019-02-21 12:26:41 -08003958 int64_t lastLoopCountWritten = -2; // never matches "previous" loop, when loopCount = 0.
Eric Laurent81784c32012-11-19 14:55:58 -08003959
3960 // MIXER
3961 nsecs_t lastWarning = 0;
3962
3963 // DUPLICATING
3964 // FIXME could this be made local to while loop?
3965 writeFrames = 0;
3966
3967 cacheParameters_l();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003968 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003969
Andy Hungd3639922022-04-28 18:00:49 -07003970 if (mType == MIXER || mType == SPATIALIZER) {
Eric Laurent81784c32012-11-19 14:55:58 -08003971 sleepTimeShift = 0;
3972 }
3973
3974 CpuStats cpuStats;
3975 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
3976
3977 acquireWakeLock();
3978
Glenn Kasteneef598c2017-04-03 14:41:13 -07003979 // mNBLogWriter logging APIs can only be called by a single thread, typically the
3980 // thread associated with this PlaybackThread.
3981 // If you want to share the mNBLogWriter with other threads (for example, binder threads)
3982 // then all such threads must agree to hold a common mutex before logging.
Glenn Kasten9e58b552013-01-18 15:09:48 -08003983 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
3984 // and then that string will be logged at the next convenient opportunity.
Glenn Kasteneef598c2017-04-03 14:41:13 -07003985 // See reference to logString below.
Glenn Kasten9e58b552013-01-18 15:09:48 -08003986 const char *logString = NULL;
3987
rago1bb90822017-05-02 18:31:48 -07003988 // Estimated time for next buffer to be written to hal. This is used only on
3989 // suspended mode (for now) to help schedule the wait time until next iteration.
3990 nsecs_t timeLoopNextNs = 0;
3991
Eric Laurent664539d2013-09-23 18:24:31 -07003992 checkSilentMode_l();
Glenn Kasteneef598c2017-04-03 14:41:13 -07003993
Andy Hung2dbffc22018-08-08 18:50:41 -07003994 audio_patch_handle_t lastDownstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Andy Hungf3234512018-07-03 14:51:47 -07003995
Eric Laurentb3f315a2021-07-13 15:09:05 +02003996 sendCheckOutputStageEffectsEvent();
3997
Andy Hung446f4df2019-02-21 12:26:41 -08003998 // loopCount is used for statistics and diagnostics.
3999 for (int64_t loopCount = 0; !exitPending(); ++loopCount)
Eric Laurent81784c32012-11-19 14:55:58 -08004000 {
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08004001 // Log merge requests are performed during AudioFlinger binder transactions, but
4002 // that does not cover audio playback. It's requested here for that reason.
Andy Hung583043b2023-07-17 17:05:00 -07004003 mAfThreadCallback->requestLogMerge();
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08004004
Eric Laurent81784c32012-11-19 14:55:58 -08004005 cpuStats.sample(myName);
4006
Andy Hung116bc262023-06-20 18:56:17 -07004007 Vector<sp<IAfEffectChain>> effectChains;
Andy Hung6e6a2e62019-04-30 16:38:41 -07004008 audio_session_t activeHapticSessionId = AUDIO_SESSION_NONE;
Eric Laurentb62d0362021-10-26 17:40:18 +02004009 bool isHapticSessionSpatialized = false;
Andy Hung8d31fd22023-06-26 19:20:57 -07004010 std::vector<sp<IAfTrack>> activeTracks;
Eric Laurent81784c32012-11-19 14:55:58 -08004011
Andy Hung2dbffc22018-08-08 18:50:41 -07004012 // If the device is AUDIO_DEVICE_OUT_BUS, check for downstream latency.
4013 //
Andy Hungc5007f82023-08-29 14:26:09 -07004014 // Note: we access outDeviceTypes() outside of mutex().
Andy Hungab65b182023-09-06 19:41:47 -07004015 if (isMsdDevice() && outDeviceTypes_l().count(AUDIO_DEVICE_OUT_BUS) != 0) {
Andy Hung2dbffc22018-08-08 18:50:41 -07004016 // Here, we try for the AF lock, but do not block on it as the latency
4017 // is more informational.
Andy Hung954b9712023-08-28 18:36:53 -07004018 if (mAfThreadCallback->mutex().try_lock()) {
Andy Hungb6692eb2023-07-13 16:52:46 -07004019 std::vector<SoftwarePatch> swPatches;
Andy Hung920f6572022-10-06 12:09:49 -07004020 double latencyMs = 0.; // not required; initialized for clang-tidy
Andy Hung2dbffc22018-08-08 18:50:41 -07004021 status_t status = INVALID_OPERATION;
4022 audio_patch_handle_t downstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Andy Hung583043b2023-07-17 17:05:00 -07004023 if (mAfThreadCallback->getPatchPanel()->getDownstreamSoftwarePatches(
Andy Hungb6692eb2023-07-13 16:52:46 -07004024 id(), &swPatches) == OK
Andy Hung2dbffc22018-08-08 18:50:41 -07004025 && swPatches.size() > 0) {
4026 status = swPatches[0].getLatencyMs_l(&latencyMs);
4027 downstreamPatchHandle = swPatches[0].getPatchHandle();
4028 }
4029 if (downstreamPatchHandle != lastDownstreamPatchHandle) {
Dean Wheatley30d28422018-11-06 10:27:40 +11004030 mDownstreamLatencyStatMs.reset();
Andy Hung2dbffc22018-08-08 18:50:41 -07004031 lastDownstreamPatchHandle = downstreamPatchHandle;
4032 }
4033 if (status == OK) {
4034 // verify downstream latency (we assume a max reasonable
Mikhail Naganov6aa0a312018-11-09 11:00:01 -08004035 // latency of 5 seconds).
4036 const double minLatency = 0., maxLatency = 5000.;
4037 if (latencyMs >= minLatency && latencyMs <= maxLatency) {
Dean Wheatley56a583e2020-05-08 15:12:17 +10004038 ALOGVV("new downstream latency %lf ms", latencyMs);
Andy Hung2dbffc22018-08-08 18:50:41 -07004039 } else {
4040 ALOGD("out of range downstream latency %lf ms", latencyMs);
Andy Hung920f6572022-10-06 12:09:49 -07004041 latencyMs = std::clamp(latencyMs, minLatency, maxLatency);
Andy Hung2dbffc22018-08-08 18:50:41 -07004042 }
Dean Wheatley30d28422018-11-06 10:27:40 +11004043 mDownstreamLatencyStatMs.add(latencyMs);
Andy Hung2dbffc22018-08-08 18:50:41 -07004044 }
Andy Hung583043b2023-07-17 17:05:00 -07004045 mAfThreadCallback->mutex().unlock();
Andy Hung2dbffc22018-08-08 18:50:41 -07004046 }
4047 } else {
4048 if (lastDownstreamPatchHandle != AUDIO_PATCH_HANDLE_NONE) {
4049 // our device is no longer AUDIO_DEVICE_OUT_BUS, reset patch handle and stats.
Dean Wheatley30d28422018-11-06 10:27:40 +11004050 mDownstreamLatencyStatMs.reset();
Andy Hung2dbffc22018-08-08 18:50:41 -07004051 lastDownstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
4052 }
4053 }
4054
Eric Laurentb3f315a2021-07-13 15:09:05 +02004055 if (mCheckOutputStageEffects.exchange(false)) {
4056 checkOutputStageEffects();
4057 }
4058
Vlad Popa7e81cea2023-01-19 16:34:16 +01004059 MetadataUpdate metadataUpdate;
Andy Hungc5007f82023-08-29 14:26:09 -07004060 { // scope for mutex()
Eric Laurent81784c32012-11-19 14:55:58 -08004061
Andy Hungc5007f82023-08-29 14:26:09 -07004062 audio_utils::unique_lock _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08004063
Eric Laurent021cf962014-05-13 10:18:14 -07004064 processConfigEvents_l();
Eric Laurentb3f315a2021-07-13 15:09:05 +02004065 if (mCheckOutputStageEffects.load()) {
4066 continue;
4067 }
Eric Laurent10351942014-05-08 18:49:52 -07004068
Andy Hungc5007f82023-08-29 14:26:09 -07004069 // See comment at declaration of logString for why this is done under mutex()
Glenn Kasten9e58b552013-01-18 15:09:48 -08004070 if (logString != NULL) {
4071 mNBLogWriter->logTimestamp();
4072 mNBLogWriter->log(logString);
4073 logString = NULL;
4074 }
4075
Dean Wheatley12473e92021-03-18 23:00:55 +11004076 collectTimestamps_l();
Andy Hungc8fddf32018-08-08 18:32:37 -07004077
Eric Laurent81784c32012-11-19 14:55:58 -08004078 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004079 if (mSignalPending) {
4080 // A signal was raised while we were unlocked
4081 mSignalPending = false;
4082 } else if (waitingAsyncCallback_l()) {
4083 if (exitPending()) {
4084 break;
4085 }
Marco Nelissen078538c2015-05-12 09:17:57 -07004086 bool released = false;
Eric Laurent64667972016-03-30 18:19:46 -07004087 if (!keepWakeLock()) {
Marco Nelissen078538c2015-05-12 09:17:57 -07004088 releaseWakeLock_l();
4089 released = true;
4090 }
Andy Hung10cbff12017-02-21 17:30:14 -08004091
4092 const int64_t waitNs = computeWaitTimeNs_l();
4093 ALOGV("wait async completion (wait time: %lld)", (long long)waitNs);
Andy Hungc5007f82023-08-29 14:26:09 -07004094 std::cv_status cvstatus =
4095 mWaitWorkCV.wait_for(_l, std::chrono::nanoseconds(waitNs));
4096 if (cvstatus == std::cv_status::timeout) {
Andy Hung10cbff12017-02-21 17:30:14 -08004097 mSignalPending = true; // if timeout recheck everything
4098 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004099 ALOGV("async completion/wake");
Marco Nelissen078538c2015-05-12 09:17:57 -07004100 if (released) {
4101 acquireWakeLock_l();
4102 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004103 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
4104 mSleepTimeUs = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07004105
4106 continue;
4107 }
Eric Tan39ec8d62018-07-24 09:49:29 -07004108 if ((mActiveTracks.isEmpty() && systemTime() > mStandbyTimeNs) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08004109 isSuspended()) {
4110 // put audio hardware into standby after short delay
4111 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004112
4113 threadLoop_standby();
4114
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07004115 // This is where we go into standby
4116 if (!mStandby) {
4117 LOG_AUDIO_STATE();
Andy Hungcf10d742020-04-28 15:38:24 -07004118 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07004119 mThreadSnapshot.onEnd();
Eric Laurent19952e12023-04-20 10:08:29 +02004120 setStandby_l();
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07004121 }
Andy Hungd0979812019-02-21 15:51:44 -08004122 sendStatistics(false /* force */);
Eric Laurent81784c32012-11-19 14:55:58 -08004123 }
4124
Eric Tan39ec8d62018-07-24 09:49:29 -07004125 if (mActiveTracks.isEmpty() && mConfigEvents.isEmpty()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004126 // we're about to wait, flush the binder command buffer
4127 IPCThreadState::self()->flushCommands();
4128
4129 clearOutputTracks();
4130
4131 if (exitPending()) {
4132 break;
4133 }
4134
4135 releaseWakeLock_l();
4136 // wait until we have something to do...
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004137 ALOGV("%s going to sleep", myName.c_str());
Andy Hungc5007f82023-08-29 14:26:09 -07004138 mWaitWorkCV.wait(_l);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004139 ALOGV("%s waking up", myName.c_str());
Eric Laurent81784c32012-11-19 14:55:58 -08004140 acquireWakeLock_l();
4141
4142 mMixerStatus = MIXER_IDLE;
4143 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
4144 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004145 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08004146 checkSilentMode_l();
4147
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004148 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
4149 mSleepTimeUs = mIdleSleepTimeUs;
Andy Hungd3639922022-04-28 18:00:49 -07004150 if (mType == MIXER || mType == SPATIALIZER) {
Eric Laurent81784c32012-11-19 14:55:58 -08004151 sleepTimeShift = 0;
4152 }
4153
4154 continue;
4155 }
4156 }
Eric Laurent81784c32012-11-19 14:55:58 -08004157 // mMixerStatusIgnoringFastTracks is also updated internally
4158 mMixerStatus = prepareTracks_l(&tracksToRemove);
4159
Andy Hungab65b182023-09-06 19:41:47 -07004160 mActiveTracks.updatePowerState_l(this);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08004161
Vlad Popa7e81cea2023-01-19 16:34:16 +01004162 metadataUpdate = updateMetadata_l();
Kevin Rocard069c2712018-03-29 19:09:14 -07004163
Eric Laurent81784c32012-11-19 14:55:58 -08004164 // prevent any changes in effect chain list and in each effect chain
4165 // during mixing and effect process as the audio buffers could be deleted
4166 // or modified if an effect is created or deleted
4167 lockEffectChains_l(effectChains);
Andy Hung6e6a2e62019-04-30 16:38:41 -07004168
4169 // Determine which session to pick up haptic data.
4170 // This must be done under the same lock as prepareTracks_l().
jiabineb3bda02020-06-30 14:07:03 -07004171 // The haptic data from the effect is at a higher priority than the one from track.
Andy Hung6e6a2e62019-04-30 16:38:41 -07004172 // TODO: Write haptic data directly to sink buffer when mixing.
Eric Laurentb62d0362021-10-26 17:40:18 +02004173 if (mHapticChannelCount > 0) {
Andy Hung6e6a2e62019-04-30 16:38:41 -07004174 for (const auto& track : mActiveTracks) {
Andy Hung116bc262023-06-20 18:56:17 -07004175 sp<IAfEffectChain> effectChain = getEffectChain_l(track->sessionId());
Eric Laurentb62d0362021-10-26 17:40:18 +02004176 if (effectChain != nullptr
4177 && effectChain->containsHapticGeneratingEffect_l()) {
jiabineb3bda02020-06-30 14:07:03 -07004178 activeHapticSessionId = track->sessionId();
Eric Laurentb62d0362021-10-26 17:40:18 +02004179 isHapticSessionSpatialized =
Eric Laurentb0a7bc92022-04-05 15:06:08 +02004180 mType == SPATIALIZER && track->isSpatialized();
jiabineb3bda02020-06-30 14:07:03 -07004181 break;
4182 }
Eric Laurentb62d0362021-10-26 17:40:18 +02004183 if (activeHapticSessionId == AUDIO_SESSION_NONE
4184 && track->getHapticPlaybackEnabled()) {
Andy Hung6e6a2e62019-04-30 16:38:41 -07004185 activeHapticSessionId = track->sessionId();
Eric Laurentb62d0362021-10-26 17:40:18 +02004186 isHapticSessionSpatialized =
Eric Laurentb0a7bc92022-04-05 15:06:08 +02004187 mType == SPATIALIZER && track->isSpatialized();
Andy Hung6e6a2e62019-04-30 16:38:41 -07004188 }
4189 }
4190 }
4191
Andy Hungc1646382019-04-30 16:12:10 -07004192 // Acquire a local copy of active tracks with lock (release w/o lock).
4193 //
4194 // Control methods on the track acquire the ThreadBase lock (e.g. start()
4195 // stop(), pause(), etc.), but the threadLoop is entitled to call audio
4196 // data / buffer methods on tracks from activeTracks without the ThreadBase lock.
4197 activeTracks.insert(activeTracks.end(), mActiveTracks.begin(), mActiveTracks.end());
Eric Laurent68a40a82022-05-03 18:15:04 +02004198
4199 setHalLatencyMode_l();
Eric Laurent19952e12023-04-20 10:08:29 +02004200
Jiabin Huangfb476842022-12-06 03:18:10 +00004201 for (const auto &track : mActiveTracks ) {
jiabin7434e812023-06-27 18:22:35 +00004202 track->updateTeePatches_l();
Jiabin Huangfb476842022-12-06 03:18:10 +00004203 }
4204
Eric Laurent19952e12023-04-20 10:08:29 +02004205 // signal actual start of output stream when the render position reported by the kernel
4206 // starts moving.
Eric Laurent4edbd8c2023-05-22 17:00:24 +02004207 if (!mHalStarted && ((isSuspended() && (mBytesWritten != 0)) || (!mStandby
4208 && (mKernelPositionOnStandby
4209 != mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL])))) {
Eric Laurent19952e12023-04-20 10:08:29 +02004210 mHalStarted = true;
Andy Hungc5007f82023-08-29 14:26:09 -07004211 mWaitHalStartCV.notify_all();
Eric Laurent19952e12023-04-20 10:08:29 +02004212 }
Andy Hungc5007f82023-08-29 14:26:09 -07004213 } // mutex() scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08004214
Eric Laurentbfb1b832013-01-07 09:53:42 -08004215 if (mBytesRemaining == 0) {
4216 mCurrentWriteLength = 0;
4217 if (mMixerStatus == MIXER_TRACKS_READY) {
4218 // threadLoop_mix() sets mCurrentWriteLength
4219 threadLoop_mix();
4220 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
4221 && (mMixerStatus != MIXER_DRAIN_ALL)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004222 // threadLoop_sleepTime sets mSleepTimeUs to 0 if data
Eric Laurentbfb1b832013-01-07 09:53:42 -08004223 // must be written to HAL
4224 threadLoop_sleepTime();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004225 if (mSleepTimeUs == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08004226 mCurrentWriteLength = mSinkBufferSize;
Andy Hungc1646382019-04-30 16:12:10 -07004227
4228 // Tally underrun frames as we are inserting 0s here.
4229 for (const auto& track : activeTracks) {
Andy Hung8d31fd22023-06-26 19:20:57 -07004230 if (track->fillingStatus() == IAfTrack::FS_ACTIVE
Andy Hunge2e830f2019-12-03 12:54:46 -08004231 && !track->isStopped()
4232 && !track->isPaused()
4233 && !track->isTerminated()) {
4234 ALOGV("%s: track(%d) %s underrun due to thread sleep of %zu frames",
4235 __func__, track->id(), track->getTrackStateAsString(),
4236 mNormalFrameCount);
Andy Hung8d31fd22023-06-26 19:20:57 -07004237 track->audioTrackServerProxy()->tallyUnderrunFrames(
4238 mNormalFrameCount);
Andy Hungc1646382019-04-30 16:12:10 -07004239 }
4240 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004241 }
4242 }
Andy Hung98ef9782014-03-04 14:46:50 -08004243 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004244 // mMixerBuffer with data if mMixerBufferValid is true and mSleepTimeUs == 0.
Andy Hung98ef9782014-03-04 14:46:50 -08004245 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
jiabinc658e452022-10-21 20:52:21 +00004246 // or mSinkBuffer (if there are no effects and there is no data already copied to
4247 // mSinkBuffer).
Andy Hung98ef9782014-03-04 14:46:50 -08004248 //
4249 // This is done pre-effects computation; if effects change to
4250 // support higher precision, this needs to move.
4251 //
4252 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004253 // TODO use mSleepTimeUs == 0 as an additional condition.
Eric Laurent39095982021-08-24 18:29:27 +02004254 uint32_t mixerChannelCount = mEffectBufferValid ?
4255 audio_channel_count_from_out_mask(mMixerChannelMask) : mChannelCount;
jiabinc658e452022-10-21 20:52:21 +00004256 if (mMixerBufferValid && (mEffectBufferValid || !mHasDataCopiedToSinkBuffer)) {
Andy Hung98ef9782014-03-04 14:46:50 -08004257 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
4258 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
4259
David Li88ee0902022-06-22 10:01:21 +08004260 // Apply mono blending and balancing if the effect buffer is not valid. Otherwise,
4261 // do these processes after effects are applied.
4262 if (!mEffectBufferValid) {
4263 // mono blend occurs for mixer threads only (not direct or offloaded)
4264 // and is handled here if we're going directly to the sink.
4265 if (requireMonoBlend()) {
4266 mono_blend(mMixerBuffer, mMixerBufferFormat, mChannelCount,
4267 mNormalFrameCount, true /*limit*/);
4268 }
Andy Hung2ddee192015-12-18 17:34:44 -08004269
David Li88ee0902022-06-22 10:01:21 +08004270 if (!hasFastMixer()) {
4271 // Balance must take effect after mono conversion.
4272 // We do it here if there is no FastMixer.
4273 // mBalance detects zero balance within the class for speed
4274 // (not needed here).
4275 mBalance.setBalance(mMasterBalance.load());
4276 mBalance.process((float *)mMixerBuffer, mNormalFrameCount);
4277 }
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01004278 }
4279
Andy Hung98ef9782014-03-04 14:46:50 -08004280 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
Eric Laurent39095982021-08-24 18:29:27 +02004281 mNormalFrameCount * (mixerChannelCount + mHapticChannelCount));
jiabin245cdd92018-12-07 17:55:15 -08004282
4283 // If we're going directly to the sink and there are haptic channels,
4284 // we should adjust channels as the sample data is partially interleaved
4285 // in this case.
4286 if (!mEffectBufferValid && mHapticChannelCount > 0) {
4287 adjust_channels_non_destructive(buffer, mChannelCount, buffer,
4288 mChannelCount + mHapticChannelCount,
4289 audio_bytes_per_sample(format),
4290 audio_bytes_per_frame(mChannelCount, format) * mNormalFrameCount);
4291 }
Andy Hung98ef9782014-03-04 14:46:50 -08004292 }
4293
Eric Laurentbfb1b832013-01-07 09:53:42 -08004294 mBytesRemaining = mCurrentWriteLength;
4295 if (isSuspended()) {
Andy Hung238fa3d2016-07-28 10:53:22 -07004296 // Simulate write to HAL when suspended (e.g. BT SCO phone call).
4297 mSleepTimeUs = suspendSleepTimeUs(); // assumes full buffer.
4298 const size_t framesRemaining = mBytesRemaining / mFrameSize;
4299 mBytesWritten += mBytesRemaining;
4300 mFramesWritten += framesRemaining;
4301 mSuspendedFrames += framesRemaining; // to adjust kernel HAL position
Eric Laurentbfb1b832013-01-07 09:53:42 -08004302 mBytesRemaining = 0;
4303 }
Eric Laurent81784c32012-11-19 14:55:58 -08004304
Eric Laurentbfb1b832013-01-07 09:53:42 -08004305 // only process effects if we're going to write
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004306 if (mSleepTimeUs == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004307 for (size_t i = 0; i < effectChains.size(); i ++) {
4308 effectChains[i]->process_l();
jiabin47affe52019-04-04 18:02:07 -07004309 // TODO: Write haptic data directly to sink buffer when mixing.
Andy Hung6e6a2e62019-04-30 16:38:41 -07004310 if (activeHapticSessionId != AUDIO_SESSION_NONE
4311 && activeHapticSessionId == effectChains[i]->sessionId()) {
jiabin47affe52019-04-04 18:02:07 -07004312 // Haptic data is active in this case, copy it directly from
4313 // in buffer to out buffer.
Eric Laurentb62d0362021-10-26 17:40:18 +02004314 uint32_t hapticSessionChannelCount = mEffectBufferValid ?
4315 audio_channel_count_from_out_mask(mMixerChannelMask) :
4316 mChannelCount;
4317 if (mType == SPATIALIZER && !isHapticSessionSpatialized) {
4318 hapticSessionChannelCount = mChannelCount;
4319 }
4320
jiabin47affe52019-04-04 18:02:07 -07004321 const size_t audioBufferSize = mNormalFrameCount
Eric Laurentb62d0362021-10-26 17:40:18 +02004322 * audio_bytes_per_frame(hapticSessionChannelCount,
Andy Hung319587b2023-05-23 14:01:03 -07004323 AUDIO_FORMAT_PCM_FLOAT);
jiabin47affe52019-04-04 18:02:07 -07004324 memcpy_by_audio_format(
4325 (uint8_t*)effectChains[i]->outBuffer() + audioBufferSize,
Andy Hung319587b2023-05-23 14:01:03 -07004326 AUDIO_FORMAT_PCM_FLOAT,
jiabin47affe52019-04-04 18:02:07 -07004327 (const uint8_t*)effectChains[i]->inBuffer() + audioBufferSize,
Andy Hung319587b2023-05-23 14:01:03 -07004328 AUDIO_FORMAT_PCM_FLOAT, mNormalFrameCount * mHapticChannelCount);
jiabin47affe52019-04-04 18:02:07 -07004329 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004330 }
Eric Laurent81784c32012-11-19 14:55:58 -08004331 }
4332 }
Eric Laurent59fe0102013-09-27 18:48:26 -07004333 // Process effect chains for offloaded thread even if no audio
4334 // was read from audio track: process only updates effect state
4335 // and thus does have to be synchronized with audio writes but may have
4336 // to be called while waiting for async write callback
4337 if (mType == OFFLOAD) {
4338 for (size_t i = 0; i < effectChains.size(); i ++) {
4339 effectChains[i]->process_l();
4340 }
4341 }
Eric Laurent81784c32012-11-19 14:55:58 -08004342
Andy Hung98ef9782014-03-04 14:46:50 -08004343 // Only if the Effects buffer is enabled and there is data in the
4344 // Effects buffer (buffer valid), we need to
4345 // copy into the sink buffer.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004346 // TODO use mSleepTimeUs == 0 as an additional condition.
jiabinc658e452022-10-21 20:52:21 +00004347 if (mEffectBufferValid && !mHasDataCopiedToSinkBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08004348 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
Eric Laurentb62d0362021-10-26 17:40:18 +02004349 void *effectBuffer = (mType == SPATIALIZER) ? mPostSpatializerBuffer : mEffectBuffer;
Andy Hung2ddee192015-12-18 17:34:44 -08004350 if (requireMonoBlend()) {
Eric Laurentb62d0362021-10-26 17:40:18 +02004351 mono_blend(effectBuffer, mEffectBufferFormat, mChannelCount, mNormalFrameCount,
Glenn Kasten03c48d52016-01-27 17:25:17 -08004352 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08004353 }
4354
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01004355 if (!hasFastMixer()) {
4356 // Balance must take effect after mono conversion.
4357 // We do it here if there is no FastMixer.
4358 // mBalance detects zero balance within the class for speed (not needed here).
4359 mBalance.setBalance(mMasterBalance.load());
Eric Laurentb62d0362021-10-26 17:40:18 +02004360 mBalance.process((float *)effectBuffer, mNormalFrameCount);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01004361 }
4362
Eric Laurentb62d0362021-10-26 17:40:18 +02004363 // for SPATIALIZER thread, Move haptics channels from mEffectBuffer to
4364 // mPostSpatializerBuffer if the haptics track is spatialized.
4365 // Otherwise, the haptics channels are already in mPostSpatializerBuffer.
4366 // For other thread types, the haptics channels are already in mEffectBuffer.
4367 if (mType == SPATIALIZER && isHapticSessionSpatialized) {
4368 const size_t srcBufferSize = mNormalFrameCount *
4369 audio_bytes_per_frame(audio_channel_count_from_out_mask(mMixerChannelMask),
4370 mEffectBufferFormat);
4371 const size_t dstBufferSize = mNormalFrameCount
4372 * audio_bytes_per_frame(mChannelCount, mEffectBufferFormat);
4373
4374 memcpy_by_audio_format((uint8_t*)mPostSpatializerBuffer + dstBufferSize,
4375 mEffectBufferFormat,
4376 (uint8_t*)mEffectBuffer + srcBufferSize,
4377 mEffectBufferFormat,
4378 mNormalFrameCount * mHapticChannelCount);
Eric Laurent39095982021-08-24 18:29:27 +02004379 }
Atneya Nairba9a1072022-09-19 17:51:37 -07004380 const size_t framesToCopy = mNormalFrameCount * (mChannelCount + mHapticChannelCount);
4381 if (mFormat == AUDIO_FORMAT_PCM_FLOAT &&
4382 mEffectBufferFormat == AUDIO_FORMAT_PCM_FLOAT) {
4383 // Clamp PCM float values more than this distance from 0 to insulate
4384 // a HAL which doesn't handle NaN correctly.
4385 static constexpr float HAL_FLOAT_SAMPLE_LIMIT = 2.0f;
4386 memcpy_to_float_from_float_with_clamping(static_cast<float*>(mSinkBuffer),
4387 static_cast<const float*>(effectBuffer),
4388 framesToCopy, HAL_FLOAT_SAMPLE_LIMIT /* absMax */);
4389 } else {
4390 memcpy_by_audio_format(mSinkBuffer, mFormat,
4391 effectBuffer, mEffectBufferFormat, framesToCopy);
4392 }
jiabin245cdd92018-12-07 17:55:15 -08004393 // The sample data is partially interleaved when haptic channels exist,
4394 // we need to adjust channels here.
4395 if (mHapticChannelCount > 0) {
4396 adjust_channels_non_destructive(mSinkBuffer, mChannelCount, mSinkBuffer,
4397 mChannelCount + mHapticChannelCount,
4398 audio_bytes_per_sample(mFormat),
4399 audio_bytes_per_frame(mChannelCount, mFormat) * mNormalFrameCount);
4400 }
Andy Hung98ef9782014-03-04 14:46:50 -08004401 }
4402
Eric Laurent81784c32012-11-19 14:55:58 -08004403 // enable changes in effect chain
4404 unlockEffectChains(effectChains);
4405
Vlad Popafce10862023-02-03 10:37:07 +01004406 if (!metadataUpdate.playbackMetadataUpdate.empty()) {
Andy Hung583043b2023-07-17 17:05:00 -07004407 mAfThreadCallback->getMelReporter()->updateMetadataForCsd(id(),
Vlad Popafce10862023-02-03 10:37:07 +01004408 metadataUpdate.playbackMetadataUpdate);
4409 }
4410
Eric Laurentbfb1b832013-01-07 09:53:42 -08004411 if (!waitingAsyncCallback()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004412 // mSleepTimeUs == 0 means we must write to audio hardware
4413 if (mSleepTimeUs == 0) {
Andy Hung08fb1742015-05-31 23:22:10 -07004414 ssize_t ret = 0;
Andy Hung446f4df2019-02-21 12:26:41 -08004415 // writePeriodNs is updated >= 0 when ret > 0.
4416 int64_t writePeriodNs = -1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004417 if (mBytesRemaining) {
Andy Hung69488c42016-05-16 18:43:33 -07004418 // FIXME rewrite to reduce number of system calls
Andy Hung446f4df2019-02-21 12:26:41 -08004419 const int64_t lastIoBeginNs = systemTime();
Andy Hung08fb1742015-05-31 23:22:10 -07004420 ret = threadLoop_write();
Andy Hung446f4df2019-02-21 12:26:41 -08004421 const int64_t lastIoEndNs = systemTime();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004422 if (ret < 0) {
4423 mBytesRemaining = 0;
Andy Hung446f4df2019-02-21 12:26:41 -08004424 } else if (ret > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004425 mBytesWritten += ret;
4426 mBytesRemaining -= ret;
Andy Hung446f4df2019-02-21 12:26:41 -08004427 const int64_t frames = ret / mFrameSize;
4428 mFramesWritten += frames;
4429
4430 writePeriodNs = lastIoEndNs - mLastIoEndNs;
4431 // process information relating to write time.
4432 if (audio_has_proportional_frames(mFormat)) {
4433 // we are in a continuous mixing cycle
4434 if (mMixerStatus == MIXER_TRACKS_READY &&
4435 loopCount == lastLoopCountWritten + 1) {
4436
4437 const double jitterMs =
4438 TimestampVerifier<int64_t, int64_t>::computeJitterMs(
4439 {frames, writePeriodNs},
4440 {0, 0} /* lastTimestamp */, mSampleRate);
4441 const double processMs =
4442 (lastIoBeginNs - mLastIoEndNs) * 1e-6;
4443
Andy Hung972bec12023-08-31 16:13:39 -07004444 audio_utils::lock_guard _l(mutex());
Andy Hung446f4df2019-02-21 12:26:41 -08004445 mIoJitterMs.add(jitterMs);
4446 mProcessTimeMs.add(processMs);
Robert Wu06db0a32021-08-10 19:05:34 +00004447
4448 if (mPipeSink.get() != nullptr) {
4449 // Using the Monopipe availableToWrite, we estimate the current
4450 // buffer size.
4451 MonoPipe* monoPipe = static_cast<MonoPipe*>(mPipeSink.get());
4452 const ssize_t
4453 availableToWrite = mPipeSink->availableToWrite();
4454 const size_t pipeFrames = monoPipe->maxFrames();
4455 const size_t
4456 remainingFrames = pipeFrames - max(availableToWrite, 0);
4457 mMonopipePipeDepthStats.add(remainingFrames);
4458 }
Andy Hung446f4df2019-02-21 12:26:41 -08004459 }
4460
4461 // write blocked detection
4462 const int64_t deltaWriteNs = lastIoEndNs - lastIoBeginNs;
Andy Hungd3639922022-04-28 18:00:49 -07004463 if ((mType == MIXER || mType == SPATIALIZER)
4464 && deltaWriteNs > maxPeriod) {
Andy Hung446f4df2019-02-21 12:26:41 -08004465 mNumDelayedWrites++;
4466 if ((lastIoEndNs - lastWarning) > kWarningThrottleNs) {
4467 ATRACE_NAME("underrun");
4468 ALOGW("write blocked for %lld msecs, "
4469 "%d delayed writes, thread %d",
4470 (long long)deltaWriteNs / NANOS_PER_MILLISECOND,
4471 mNumDelayedWrites, mId);
4472 lastWarning = lastIoEndNs;
4473 }
4474 }
4475 }
4476 // update timing info.
4477 mLastIoBeginNs = lastIoBeginNs;
4478 mLastIoEndNs = lastIoEndNs;
4479 lastLoopCountWritten = loopCount;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004480 }
4481 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
4482 (mMixerStatus == MIXER_DRAIN_ALL)) {
4483 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08004484 }
Andy Hungd3639922022-04-28 18:00:49 -07004485 if ((mType == MIXER || mType == SPATIALIZER) && !mStandby) {
Andy Hung08fb1742015-05-31 23:22:10 -07004486
4487 if (mThreadThrottle
4488 && mMixerStatus == MIXER_TRACKS_READY // we are mixing (active tracks)
Andy Hung446f4df2019-02-21 12:26:41 -08004489 && writePeriodNs > 0) { // we have write period info
Andy Hung08fb1742015-05-31 23:22:10 -07004490 // Limit MixerThread data processing to no more than twice the
4491 // expected processing rate.
4492 //
4493 // This helps prevent underruns with NuPlayer and other applications
4494 // which may set up buffers that are close to the minimum size, or use
4495 // deep buffers, and rely on a double-buffering sleep strategy to fill.
4496 //
4497 // The throttle smooths out sudden large data drains from the device,
4498 // e.g. when it comes out of standby, which often causes problems with
4499 // (1) mixer threads without a fast mixer (which has its own warm-up)
4500 // (2) minimum buffer sized tracks (even if the track is full,
4501 // the app won't fill fast enough to handle the sudden draw).
Haynes Mathew Georgef92b2172016-05-09 11:34:15 -07004502 //
4503 // Total time spent in last processing cycle equals time spent in
4504 // 1. threadLoop_write, as well as time spent in
4505 // 2. threadLoop_mix (significant for heavy mixing, especially
4506 // on low tier processors)
Andy Hung08fb1742015-05-31 23:22:10 -07004507
Andy Hung446f4df2019-02-21 12:26:41 -08004508 // it's OK if deltaMs is an overestimate.
4509
4510 const int32_t deltaMs = writePeriodNs / NANOS_PER_MILLISECOND;
Ivan Lozanoe02bc542017-10-26 09:51:54 -07004511
Ivan Lozanoea04d392017-11-07 14:37:07 -08004512 const int32_t throttleMs = (int32_t)mHalfBufferMs - deltaMs;
Andy Hung08fb1742015-05-31 23:22:10 -07004513 if ((signed)mHalfBufferMs >= throttleMs && throttleMs > 0) {
Andy Hungcf10d742020-04-28 15:38:24 -07004514 mThreadMetrics.logThrottleMs((double)throttleMs);
Andy Hungb68f5eb2019-12-03 16:49:17 -08004515
Andy Hung08fb1742015-05-31 23:22:10 -07004516 usleep(throttleMs * 1000);
Andy Hung40eb1a12015-06-18 13:42:02 -07004517 // notify of throttle start on verbose log
4518 ALOGV_IF(mThreadThrottleEndMs == mThreadThrottleTimeMs,
4519 "mixer(%p) throttle begin:"
4520 " ret(%zd) deltaMs(%d) requires sleep %d ms",
Andy Hung08fb1742015-05-31 23:22:10 -07004521 this, ret, deltaMs, throttleMs);
Andy Hung40eb1a12015-06-18 13:42:02 -07004522 mThreadThrottleTimeMs += throttleMs;
Andy Hung0a31ddd2016-07-06 19:10:29 -07004523 // Throttle must be attributed to the previous mixer loop's write time
4524 // to allow back-to-back throttling.
Andy Hung446f4df2019-02-21 12:26:41 -08004525 // This also ensures proper timing statistics.
4526 mLastIoEndNs = systemTime(); // we fetch the write end time again.
Andy Hung40eb1a12015-06-18 13:42:02 -07004527 } else {
4528 uint32_t diff = mThreadThrottleTimeMs - mThreadThrottleEndMs;
4529 if (diff > 0) {
4530 // notify of throttle end on debug log
Andy Hung3ea004d2016-05-05 16:48:37 -07004531 // but prevent spamming for bluetooth
jiabinc52b1ff2019-10-31 17:20:42 -07004532 ALOGD_IF(!isSingleDeviceType(
Andy Hungab65b182023-09-06 19:41:47 -07004533 outDeviceTypes_l(), audio_is_a2dp_out_device) &&
jiabinc52b1ff2019-10-31 17:20:42 -07004534 !isSingleDeviceType(
Andy Hungab65b182023-09-06 19:41:47 -07004535 outDeviceTypes_l(),
4536 audio_is_hearing_aid_out_device),
Andy Hung3ea004d2016-05-05 16:48:37 -07004537 "mixer(%p) throttle end: throttle time(%u)", this, diff);
Andy Hung40eb1a12015-06-18 13:42:02 -07004538 mThreadThrottleEndMs = mThreadThrottleTimeMs;
4539 }
Andy Hung08fb1742015-05-31 23:22:10 -07004540 }
4541 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004542 }
Eric Laurent81784c32012-11-19 14:55:58 -08004543
Eric Laurentbfb1b832013-01-07 09:53:42 -08004544 } else {
Glenn Kastene7754022014-10-31 12:11:26 -07004545 ATRACE_BEGIN("sleep");
Andy Hungc5007f82023-08-29 14:26:09 -07004546 audio_utils::unique_lock _l(mutex());
rago1bb90822017-05-02 18:31:48 -07004547 // suspended requires accurate metering of sleep time.
4548 if (isSuspended()) {
4549 // advance by expected sleepTime
4550 timeLoopNextNs += microseconds((nsecs_t)mSleepTimeUs);
4551 const nsecs_t nowNs = systemTime();
4552
4553 // compute expected next time vs current time.
4554 // (negative deltas are treated as delays).
4555 nsecs_t deltaNs = timeLoopNextNs - nowNs;
4556 if (deltaNs < -kMaxNextBufferDelayNs) {
4557 // Delays longer than the max allowed trigger a reset.
4558 ALOGV("DelayNs: %lld, resetting timeLoopNextNs", (long long) deltaNs);
4559 deltaNs = microseconds((nsecs_t)mSleepTimeUs);
4560 timeLoopNextNs = nowNs + deltaNs;
4561 } else if (deltaNs < 0) {
4562 // Delays within the max delay allowed: zero the delta/sleepTime
4563 // to help the system catch up in the next iteration(s)
4564 ALOGV("DelayNs: %lld, catching-up", (long long) deltaNs);
4565 deltaNs = 0;
4566 }
4567 // update sleep time (which is >= 0)
4568 mSleepTimeUs = deltaNs / 1000;
4569 }
Eric Laurente93cc032016-05-05 10:15:10 -07004570 if (!mSignalPending && mConfigEvents.isEmpty() && !exitPending()) {
Andy Hungc5007f82023-08-29 14:26:09 -07004571 mWaitWorkCV.wait_for(_l, std::chrono::microseconds(mSleepTimeUs));
Eric Laurent51716182016-02-29 18:00:56 -08004572 }
Glenn Kastene7754022014-10-31 12:11:26 -07004573 ATRACE_END();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004574 }
Eric Laurent81784c32012-11-19 14:55:58 -08004575 }
4576
4577 // Finally let go of removed track(s), without the lock held
4578 // since we can't guarantee the destructors won't acquire that
4579 // same lock. This will also mutate and push a new fast mixer state.
4580 threadLoop_removeTracks(tracksToRemove);
4581 tracksToRemove.clear();
4582
4583 // FIXME I don't understand the need for this here;
4584 // it was in the original code but maybe the
4585 // assignment in saveOutputTracks() makes this unnecessary?
4586 clearOutputTracks();
4587
4588 // Effect chains will be actually deleted here if they were removed from
4589 // mEffectChains list during mixing or effects processing
4590 effectChains.clear();
4591
4592 // FIXME Note that the above .clear() is no longer necessary since effectChains
4593 // is now local to this block, but will keep it for now (at least until merge done).
4594 }
4595
Eric Laurentbfb1b832013-01-07 09:53:42 -08004596 threadLoop_exit();
4597
Eric Laurentcf817a22014-08-04 20:36:31 -07004598 if (!mStandby) {
4599 threadLoop_standby();
Eric Laurent19952e12023-04-20 10:08:29 +02004600 setStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08004601 }
4602
4603 releaseWakeLock();
4604
4605 ALOGV("Thread %p type %d exiting", this, mType);
4606 return false;
4607}
4608
Andy Hungee58e4a2023-07-07 13:47:37 -07004609void PlaybackThread::collectTimestamps_l()
Dean Wheatley12473e92021-03-18 23:00:55 +11004610{
Dean Wheatley12473e92021-03-18 23:00:55 +11004611 if (mStandby) {
4612 mTimestampVerifier.discontinuity(discontinuityForStandbyOrFlush());
4613 return;
4614 } else if (mHwPaused) {
4615 mTimestampVerifier.discontinuity(mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS);
4616 return;
4617 }
4618
4619 // Gather the framesReleased counters for all active tracks,
4620 // and associate with the sink frames written out. We need
4621 // this to convert the sink timestamp to the track timestamp.
4622 bool kernelLocationUpdate = false;
4623 ExtendedTimestamp timestamp; // use private copy to fetch
4624
4625 // Always query HAL timestamp and update timestamp verifier. In standby or pause,
4626 // HAL may be draining some small duration buffered data for fade out.
4627 if (threadloop_getHalTimestamp_l(&timestamp) == OK) {
4628 mTimestampVerifier.add(timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL],
4629 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4630 mSampleRate);
4631
Andy Hungab65b182023-09-06 19:41:47 -07004632 if (isTimestampCorrectionEnabled_l()) {
Dean Wheatley12473e92021-03-18 23:00:55 +11004633 ALOGVV("TS_BEFORE: %d %lld %lld", id(),
4634 (long long)timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4635 (long long)timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]);
4636 auto correctedTimestamp = mTimestampVerifier.getLastCorrectedTimestamp();
4637 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4638 = correctedTimestamp.mFrames;
4639 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]
4640 = correctedTimestamp.mTimeNs;
4641 ALOGVV("TS_AFTER: %d %lld %lld", id(),
4642 (long long)timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4643 (long long)timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]);
4644
4645 // Note: Downstream latency only added if timestamp correction enabled.
4646 if (mDownstreamLatencyStatMs.getN() > 0) { // we have latency info.
4647 const int64_t newPosition =
4648 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4649 - int64_t(mDownstreamLatencyStatMs.getMean() * mSampleRate * 1e-3);
4650 // prevent retrograde
4651 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = max(
4652 newPosition,
4653 (mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4654 - mSuspendedFrames));
4655 }
4656 }
4657
4658 // We always fetch the timestamp here because often the downstream
4659 // sink will block while writing.
4660
4661 // We keep track of the last valid kernel position in case we are in underrun
4662 // and the normal mixer period is the same as the fast mixer period, or there
4663 // is some error from the HAL.
4664 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
4665 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
4666 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
4667 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
4668 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4669
4670 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
4671 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER];
4672 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
4673 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER];
4674 }
4675
4676 if (timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
4677 kernelLocationUpdate = true;
4678 } else {
4679 ALOGVV("getTimestamp error - no valid kernel position");
4680 }
4681
4682 // copy over kernel info
4683 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] =
4684 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4685 + mSuspendedFrames; // add frames discarded when suspended
4686 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] =
4687 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4688 } else {
4689 mTimestampVerifier.error();
4690 }
4691
4692 // mFramesWritten for non-offloaded tracks are contiguous
4693 // even after standby() is called. This is useful for the track frame
4694 // to sink frame mapping.
4695 bool serverLocationUpdate = false;
4696 if (mFramesWritten != mLastFramesWritten) {
4697 serverLocationUpdate = true;
4698 mLastFramesWritten = mFramesWritten;
4699 }
4700 // Only update timestamps if there is a meaningful change.
4701 // Either the kernel timestamp must be valid or we have written something.
4702 if (kernelLocationUpdate || serverLocationUpdate) {
4703 if (serverLocationUpdate) {
4704 // use the time before we called the HAL write - it is a bit more accurate
4705 // to when the server last read data than the current time here.
4706 //
4707 // If we haven't written anything, mLastIoBeginNs will be -1
4708 // and we use systemTime().
4709 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] = mFramesWritten;
4710 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = mLastIoBeginNs == -1
Andy Hung8d672e02023-09-15 18:19:28 -07004711 ? systemTime() : (int64_t)mLastIoBeginNs;
Dean Wheatley12473e92021-03-18 23:00:55 +11004712 }
4713
Andy Hung8d31fd22023-06-26 19:20:57 -07004714 for (const sp<IAfTrack>& t : mActiveTracks) {
Dean Wheatley12473e92021-03-18 23:00:55 +11004715 if (!t->isFastTrack()) {
4716 t->updateTrackFrameInfo(
Andy Hung8d31fd22023-06-26 19:20:57 -07004717 t->audioTrackServerProxy()->framesReleased(),
Dean Wheatley12473e92021-03-18 23:00:55 +11004718 mFramesWritten,
4719 mSampleRate,
4720 mTimestamp);
4721 }
4722 }
4723 }
4724
4725 if (audio_has_proportional_frames(mFormat)) {
4726 const double latencyMs = mTimestamp.getOutputServerLatencyMs(mSampleRate);
4727 if (latencyMs != 0.) { // note 0. means timestamp is empty.
4728 mLatencyMs.add(latencyMs);
4729 }
4730 }
4731#if 0
4732 // logFormat example
4733 if (z % 100 == 0) {
4734 timespec ts;
4735 clock_gettime(CLOCK_MONOTONIC, &ts);
4736 LOGT("This is an integer %d, this is a float %f, this is my "
4737 "pid %p %% %s %t", 42, 3.14, "and this is a timestamp", ts);
4738 LOGT("A deceptive null-terminated string %\0");
4739 }
4740 ++z;
4741#endif
4742}
4743
Andy Hungc5007f82023-08-29 14:26:09 -07004744// removeTracks_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07004745void PlaybackThread::removeTracks_l(const Vector<sp<IAfTrack>>& tracksToRemove)
Andy Hungc5007f82023-08-29 14:26:09 -07004746NO_THREAD_SAFETY_ANALYSIS // release and re-acquire mutex()
Eric Laurentbfb1b832013-01-07 09:53:42 -08004747{
Andy Hung6c498e92023-12-05 17:28:17 -08004748 if (tracksToRemove.empty()) return;
4749
4750 // Block all incoming TrackHandle requests until we are finished with the release.
4751 setThreadBusy_l(true);
4752
Andy Hungfe726a62018-09-27 15:17:25 -07004753 for (const auto& track : tracksToRemove) {
Andy Hungfe726a62018-09-27 15:17:25 -07004754 ALOGV("%s(%d): removing track on session %d", __func__, track->id(), track->sessionId());
Andy Hung116bc262023-06-20 18:56:17 -07004755 sp<IAfEffectChain> chain = getEffectChain_l(track->sessionId());
Andy Hungfe726a62018-09-27 15:17:25 -07004756 if (chain != 0) {
4757 ALOGV("%s(%d): stopping track on chain %p for session Id: %d",
4758 __func__, track->id(), chain.get(), track->sessionId());
4759 chain->decActiveTrackCnt();
4760 }
Andy Hung6c498e92023-12-05 17:28:17 -08004761
Andy Hungfe726a62018-09-27 15:17:25 -07004762 // If an external client track, inform APM we're no longer active, and remove if needed.
Andy Hung6c498e92023-12-05 17:28:17 -08004763 // Since the track is active, we do it here instead of TrackBase::destroy().
Andy Hungfe726a62018-09-27 15:17:25 -07004764 if (track->isExternalTrack()) {
Andy Hung6c498e92023-12-05 17:28:17 -08004765 mutex().unlock();
Andy Hungfe726a62018-09-27 15:17:25 -07004766 AudioSystem::stopOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08004767 if (track->isTerminated()) {
Andy Hungfe726a62018-09-27 15:17:25 -07004768 AudioSystem::releaseOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08004769 }
Andy Hung6c498e92023-12-05 17:28:17 -08004770 mutex().lock();
Andy Hungfe726a62018-09-27 15:17:25 -07004771 }
jiabineb3bda02020-06-30 14:07:03 -07004772 if (mHapticChannelCount > 0 &&
4773 ((track->channelMask() & AUDIO_CHANNEL_HAPTIC_ALL) != AUDIO_CHANNEL_NONE
4774 || (chain != nullptr && chain->containsHapticGeneratingEffect_l()))) {
Andy Hungc5007f82023-08-29 14:26:09 -07004775 mutex().unlock();
jiabin57303cc2018-12-18 15:45:57 -08004776 // Unlock due to VibratorService will lock for this call and will
4777 // call Tracks.mute/unmute which also require thread's lock.
Andy Hung7fb97e12023-07-20 21:23:42 -07004778 afutils::onExternalVibrationStop(track->getExternalVibration());
Andy Hungc5007f82023-08-29 14:26:09 -07004779 mutex().lock();
jiabine70bc7f2020-06-30 22:07:55 -07004780
4781 // When the track is stop, set the haptic intensity as MUTE
4782 // for the HapticGenerator effect.
4783 if (chain != nullptr) {
Simon Bowden62823412022-10-17 14:52:26 +00004784 chain->setHapticIntensity_l(track->id(), os::HapticScale::MUTE);
jiabine70bc7f2020-06-30 22:07:55 -07004785 }
jiabin245cdd92018-12-07 17:55:15 -08004786 }
Andy Hung6c498e92023-12-05 17:28:17 -08004787
4788 // Under lock, the track is removed from the active tracks list.
4789 //
4790 // Once the track is no longer active, the TrackHandle may directly
4791 // modify it as the threadLoop() is no longer responsible for its maintenance.
4792 // Do not modify the track from threadLoop after the mutex is unlocked
4793 // if it is not active.
4794 mActiveTracks.remove(track);
4795
4796 if (track->isTerminated()) {
4797 // remove from our tracks vector
4798 removeTrack_l(track);
4799 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004800 }
Andy Hung6c498e92023-12-05 17:28:17 -08004801
4802 // Allow incoming TrackHandle requests. We still hold the mutex,
4803 // so pending TrackHandle requests will occur after we unlock it.
4804 setThreadBusy_l(false);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004805}
Eric Laurent81784c32012-11-19 14:55:58 -08004806
Andy Hungee58e4a2023-07-07 13:47:37 -07004807status_t PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
Eric Laurentaccc1472013-09-20 09:36:34 -07004808{
4809 if (mNormalSink != 0) {
Andy Hung818e7a32016-02-16 18:08:07 -08004810 ExtendedTimestamp ets;
4811 status_t status = mNormalSink->getTimestamp(ets);
4812 if (status == NO_ERROR) {
4813 status = ets.getBestTimestamp(&timestamp);
4814 }
4815 return status;
Eric Laurentaccc1472013-09-20 09:36:34 -07004816 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004817 if ((mType == OFFLOAD || mType == DIRECT) && mOutput != NULL) {
Dean Wheatley12473e92021-03-18 23:00:55 +11004818 collectTimestamps_l();
4819 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] <= 0) {
4820 return INVALID_OPERATION;
Eric Laurentaccc1472013-09-20 09:36:34 -07004821 }
Dean Wheatley12473e92021-03-18 23:00:55 +11004822 timestamp.mPosition = mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
4823 const int64_t timeNs = mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4824 timestamp.mTime.tv_sec = timeNs / NANOS_PER_SECOND;
4825 timestamp.mTime.tv_nsec = timeNs - (timestamp.mTime.tv_sec * NANOS_PER_SECOND);
4826 return NO_ERROR;
Eric Laurentaccc1472013-09-20 09:36:34 -07004827 }
4828 return INVALID_OPERATION;
4829}
Eric Laurent1c333e22014-05-20 10:48:17 -07004830
Eric Laurenteab90452019-06-24 15:17:46 -07004831// For dedicated VoIP outputs, let the HAL apply the stream volume. Track volume is
4832// still applied by the mixer.
4833// All tracks attached to a mixer with flag VOIP_RX are tied to the same
4834// stream type STREAM_VOICE_CALL so this will only change the HAL volume once even
4835// if more than one track are active
Andy Hungee58e4a2023-07-07 13:47:37 -07004836status_t PlaybackThread::handleVoipVolume_l(float* volume)
Eric Laurenteab90452019-06-24 15:17:46 -07004837{
4838 status_t result = NO_ERROR;
4839 if ((mOutput->flags & AUDIO_OUTPUT_FLAG_VOIP_RX) != 0) {
4840 if (*volume != mLeftVolFloat) {
4841 result = mOutput->stream->setVolume(*volume, *volume);
Alex Leungc5dedb22023-05-10 08:00:50 -07004842 // HAL can return INVALID_OPERATION if operation is not supported.
4843 ALOGE_IF(result != OK && result != INVALID_OPERATION,
Eric Laurenteab90452019-06-24 15:17:46 -07004844 "Error when setting output stream volume: %d", result);
4845 if (result == NO_ERROR) {
4846 mLeftVolFloat = *volume;
4847 }
4848 }
4849 // if stream volume was successfully sent to the HAL, mLeftVolFloat == v here and we
4850 // remove stream volume contribution from software volume.
4851 if (mLeftVolFloat == *volume) {
4852 *volume = 1.0f;
4853 }
4854 }
4855 return result;
4856}
4857
Andy Hungee58e4a2023-07-07 13:47:37 -07004858status_t MixerThread::createAudioPatch_l(const struct audio_patch* patch,
Eric Laurent054d9d32015-04-24 08:48:48 -07004859 audio_patch_handle_t *handle)
4860{
Andy Hungf60abce2016-08-26 11:37:54 -07004861 status_t status;
4862 if (property_get_bool("af.patch_park", false /* default_value */)) {
4863 // Park FastMixer to avoid potential DOS issues with writing to the HAL
4864 // or if HAL does not properly lock against access.
4865 AutoPark<FastMixer> park(mFastMixer);
4866 status = PlaybackThread::createAudioPatch_l(patch, handle);
4867 } else {
4868 status = PlaybackThread::createAudioPatch_l(patch, handle);
4869 }
Eric Laurentb0463942022-12-20 16:31:10 +01004870
4871 updateHalSupportedLatencyModes_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07004872 return status;
4873}
4874
Andy Hungee58e4a2023-07-07 13:47:37 -07004875status_t PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
Eric Laurent1c333e22014-05-20 10:48:17 -07004876 audio_patch_handle_t *handle)
4877{
4878 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07004879
4880 // store new device and send to effects
4881 audio_devices_t type = AUDIO_DEVICE_NONE;
jiabinc52b1ff2019-10-31 17:20:42 -07004882 AudioDeviceTypeAddrVector deviceTypeAddrs;
Eric Laurent054d9d32015-04-24 08:48:48 -07004883 for (unsigned int i = 0; i < patch->num_sinks; i++) {
jiabinc52b1ff2019-10-31 17:20:42 -07004884 LOG_ALWAYS_FATAL_IF(popcount(patch->sinks[i].ext.device.type) > 1
4885 && !mOutput->audioHwDev->supportsAudioPatches(),
4886 "Enumerated device type(%#x) must not be used "
4887 "as it does not support audio patches",
4888 patch->sinks[i].ext.device.type);
Mikhail Naganov55773032020-10-01 15:08:13 -07004889 type = static_cast<audio_devices_t>(type | patch->sinks[i].ext.device.type);
Andy Hung920f6572022-10-06 12:09:49 -07004890 deviceTypeAddrs.emplace_back(patch->sinks[i].ext.device.type,
4891 patch->sinks[i].ext.device.address);
Eric Laurent054d9d32015-04-24 08:48:48 -07004892 }
4893
François Gaffie0c280aa2018-07-25 10:02:15 +02004894 audio_port_handle_t sinkPortId = patch->sinks[0].id;
Eric Laurent054d9d32015-04-24 08:48:48 -07004895#ifdef ADD_BATTERY_DATA
4896 // when changing the audio output device, call addBatteryData to notify
4897 // the change
jiabinc52b1ff2019-10-31 17:20:42 -07004898 if (outDeviceTypes() != deviceTypes) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004899 uint32_t params = 0;
4900 // check whether speaker is on
jiabinc52b1ff2019-10-31 17:20:42 -07004901 if (deviceTypes.count(AUDIO_DEVICE_OUT_SPEAKER) > 0) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004902 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent1c333e22014-05-20 10:48:17 -07004903 }
4904
Eric Laurent054d9d32015-04-24 08:48:48 -07004905 // check if any other device (except speaker) is on
jiabinc52b1ff2019-10-31 17:20:42 -07004906 if (!isSingleDeviceType(deviceTypes, AUDIO_DEVICE_OUT_SPEAKER)) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004907 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
4908 }
4909
4910 if (params != 0) {
4911 addBatteryData(params);
4912 }
4913 }
4914#endif
4915
4916 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08004917 mEffectChains[i]->setDevices_l(deviceTypeAddrs);
Eric Laurent054d9d32015-04-24 08:48:48 -07004918 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07004919
jiabinc52b1ff2019-10-31 17:20:42 -07004920 // mPatch.num_sinks is not set when the thread is created so that
4921 // the first patch creation triggers an ioConfigChanged callback
4922 bool configChanged = (mPatch.num_sinks == 0) ||
4923 (mPatch.sinks[0].id != sinkPortId);
Eric Laurent296fb132015-05-01 11:38:42 -07004924 mPatch = *patch;
jiabinc52b1ff2019-10-31 17:20:42 -07004925 mOutDeviceTypeAddrs = deviceTypeAddrs;
jiabin0a957d32020-04-29 10:56:20 -07004926 checkSilentMode_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07004927
Mikhail Naganov9ee05402016-10-13 15:58:17 -07004928 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07004929 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
4930 status = hwDevice->createAudioPatch(patch->num_sources,
4931 patch->sources,
4932 patch->num_sinks,
4933 patch->sinks,
4934 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07004935 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08004936 status = mOutput->stream->legacyCreateAudioPatch(patch->sinks[0], std::nullopt, type);
Eric Laurent054d9d32015-04-24 08:48:48 -07004937 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07004938 }
Andy Hungc2b11cb2020-04-22 09:04:01 -07004939 const std::string patchSinksAsString = patchSinksToString(patch);
Andy Hungcf10d742020-04-28 15:38:24 -07004940
4941 mThreadMetrics.logEndInterval();
Andy Hungea840382020-05-05 21:50:17 -07004942 mThreadMetrics.logCreatePatch(/* inDevices */ {}, patchSinksAsString);
Andy Hungcf10d742020-04-28 15:38:24 -07004943 mThreadMetrics.logBeginInterval();
Andy Hungc2b11cb2020-04-22 09:04:01 -07004944 // also dispatch to active AudioTracks for MediaMetrics
4945 for (const auto &track : mActiveTracks) {
4946 track->logEndInterval();
4947 track->logBeginInterval(patchSinksAsString);
4948 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08004949
Eric Laurente8726fe2015-06-26 09:39:24 -07004950 if (configChanged) {
4951 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
4952 }
Vlad Popa7e81cea2023-01-19 16:34:16 +01004953 // Force metadata update after a route change
Eric Laurentdda206a2022-07-08 17:28:35 +02004954 mActiveTracks.setHasChanged();
4955
Eric Laurent1c333e22014-05-20 10:48:17 -07004956 return status;
4957}
4958
Andy Hungee58e4a2023-07-07 13:47:37 -07004959status_t MixerThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
Eric Laurent054d9d32015-04-24 08:48:48 -07004960{
Andy Hungf60abce2016-08-26 11:37:54 -07004961 status_t status;
4962 if (property_get_bool("af.patch_park", false /* default_value */)) {
4963 // Park FastMixer to avoid potential DOS issues with writing to the HAL
4964 // or if HAL does not properly lock against access.
4965 AutoPark<FastMixer> park(mFastMixer);
4966 status = PlaybackThread::releaseAudioPatch_l(handle);
4967 } else {
4968 status = PlaybackThread::releaseAudioPatch_l(handle);
4969 }
Eric Laurent054d9d32015-04-24 08:48:48 -07004970 return status;
4971}
4972
Andy Hungee58e4a2023-07-07 13:47:37 -07004973status_t PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004974{
4975 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07004976
jiabinc52b1ff2019-10-31 17:20:42 -07004977 mPatch = audio_patch{};
4978 mOutDeviceTypeAddrs.clear();
Eric Laurent054d9d32015-04-24 08:48:48 -07004979
Mikhail Naganov9ee05402016-10-13 15:58:17 -07004980 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07004981 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
4982 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07004983 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08004984 status = mOutput->stream->legacyReleaseAudioPatch();
Eric Laurent1c333e22014-05-20 10:48:17 -07004985 }
Eric Laurentdda206a2022-07-08 17:28:35 +02004986 // Force meteadata update after a route change
4987 mActiveTracks.setHasChanged();
4988
Eric Laurent1c333e22014-05-20 10:48:17 -07004989 return status;
4990}
4991
Andy Hungee58e4a2023-07-07 13:47:37 -07004992void PlaybackThread::addPatchTrack(const sp<IAfPatchTrack>& track)
Eric Laurent83b88082014-06-20 18:31:16 -07004993{
Andy Hung972bec12023-08-31 16:13:39 -07004994 audio_utils::lock_guard _l(mutex());
Eric Laurent83b88082014-06-20 18:31:16 -07004995 mTracks.add(track);
4996}
4997
Andy Hungee58e4a2023-07-07 13:47:37 -07004998void PlaybackThread::deletePatchTrack(const sp<IAfPatchTrack>& track)
Eric Laurent83b88082014-06-20 18:31:16 -07004999{
Andy Hung972bec12023-08-31 16:13:39 -07005000 audio_utils::lock_guard _l(mutex());
Eric Laurent83b88082014-06-20 18:31:16 -07005001 destroyTrack_l(track);
5002}
5003
Andy Hungee58e4a2023-07-07 13:47:37 -07005004void PlaybackThread::toAudioPortConfig(struct audio_port_config* config)
Eric Laurent83b88082014-06-20 18:31:16 -07005005{
Mikhail Naganovdc769682018-05-04 15:34:08 -07005006 ThreadBase::toAudioPortConfig(config);
Eric Laurent83b88082014-06-20 18:31:16 -07005007 config->role = AUDIO_PORT_ROLE_SOURCE;
5008 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
5009 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07005010 if (mOutput && mOutput->flags != AUDIO_OUTPUT_FLAG_NONE) {
5011 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
5012 config->flags.output = mOutput->flags;
5013 }
Eric Laurent83b88082014-06-20 18:31:16 -07005014}
5015
Eric Laurent81784c32012-11-19 14:55:58 -08005016// ----------------------------------------------------------------------------
5017
Andy Hungee58e4a2023-07-07 13:47:37 -07005018/* static */
5019sp<IAfPlaybackThread> IAfPlaybackThread::createMixerThread(
Andy Hung583043b2023-07-17 17:05:00 -07005020 const sp<IAfThreadCallback>& afThreadCallback, AudioStreamOut* output,
Andy Hungee58e4a2023-07-07 13:47:37 -07005021 audio_io_handle_t id, bool systemReady, type_t type, audio_config_base_t* mixerConfig) {
Andy Hung583043b2023-07-17 17:05:00 -07005022 return sp<MixerThread>::make(afThreadCallback, output, id, systemReady, type, mixerConfig);
Andy Hungee58e4a2023-07-07 13:47:37 -07005023}
5024
Andy Hung583043b2023-07-17 17:05:00 -07005025MixerThread::MixerThread(const sp<IAfThreadCallback>& afThreadCallback, AudioStreamOut* output,
Eric Laurentf1f22e72021-07-13 14:04:14 +02005026 audio_io_handle_t id, bool systemReady, type_t type, audio_config_base_t *mixerConfig)
Andy Hung583043b2023-07-17 17:05:00 -07005027 : PlaybackThread(afThreadCallback, output, id, type, systemReady, mixerConfig),
Eric Laurent81784c32012-11-19 14:55:58 -08005028 // mAudioMixer below
5029 // mFastMixer below
Eric Laurentb0463942022-12-20 16:31:10 +01005030 mBluetoothLatencyModesEnabled(false),
Andy Hung2ddee192015-12-18 17:34:44 -08005031 mFastMixerFutex(0),
5032 mMasterMono(false)
Eric Laurent81784c32012-11-19 14:55:58 -08005033 // mOutputSink below
5034 // mPipeSink below
5035 // mNormalSink below
5036{
Andy Hung583043b2023-07-17 17:05:00 -07005037 setMasterBalance(afThreadCallback->getMasterBalance_l());
jiabinc52b1ff2019-10-31 17:20:42 -07005038 ALOGV("MixerThread() id=%d type=%d", id, type);
Glenn Kasten49f36ba2017-12-06 13:02:02 -08005039 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%#x, mFrameSize=%zu, "
Glenn Kastenc42e9b42016-03-21 11:35:03 -07005040 "mFrameCount=%zu, mNormalFrameCount=%zu",
Eric Laurent81784c32012-11-19 14:55:58 -08005041 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
5042 mNormalFrameCount);
5043 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
5044
Andy Hungfbfc3952015-01-15 13:33:51 -08005045 if (type == DUPLICATING) {
5046 // The Duplicating thread uses the AudioMixer and delivers data to OutputTracks
5047 // (downstream MixerThreads) in DuplicatingThread::threadLoop_write().
5048 // Do not create or use mFastMixer, mOutputSink, mPipeSink, or mNormalSink.
5049 return;
5050 }
Eric Laurent81784c32012-11-19 14:55:58 -08005051 // create an NBAIO sink for the HAL output stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07005052 mOutputSink = new AudioStreamOutSink(output->stream);
Eric Laurent81784c32012-11-19 14:55:58 -08005053 size_t numCounterOffers = 0;
jiabin245cdd92018-12-07 17:55:15 -08005054 const NBAIO_Format offers[1] = {Format_from_SR_C(
5055 mSampleRate, mChannelCount + mHapticChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005056#if !LOG_NDEBUG
5057 ssize_t index =
5058#else
5059 (void)
5060#endif
5061 mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08005062 ALOG_ASSERT(index == 0);
5063
5064 // initialize fast mixer depending on configuration
5065 bool initFastMixer;
jiabinc658e452022-10-21 20:52:21 +00005066 if (mType == SPATIALIZER || mType == BIT_PERFECT) {
Eric Laurent81784c32012-11-19 14:55:58 -08005067 initFastMixer = false;
Eric Laurentb62d0362021-10-26 17:40:18 +02005068 } else {
5069 switch (kUseFastMixer) {
5070 case FastMixer_Never:
5071 initFastMixer = false;
5072 break;
5073 case FastMixer_Always:
5074 initFastMixer = true;
5075 break;
5076 case FastMixer_Static:
5077 case FastMixer_Dynamic:
5078 initFastMixer = mFrameCount < mNormalFrameCount;
5079 break;
5080 }
5081 ALOGW_IF(initFastMixer == false && mFrameCount < mNormalFrameCount,
5082 "FastMixer is preferred for this sink as frameCount %zu is less than threshold %zu",
5083 mFrameCount, mNormalFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08005084 }
5085 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07005086 audio_format_t fastMixerFormat;
5087 if (mMixerBufferEnabled && mEffectBufferEnabled) {
5088 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
5089 } else {
5090 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
5091 }
5092 if (mFormat != fastMixerFormat) {
5093 // change our Sink format to accept our intermediate precision
5094 mFormat = fastMixerFormat;
5095 free(mSinkBuffer);
jiabin245cdd92018-12-07 17:55:15 -08005096 mFrameSize = audio_bytes_per_frame(mChannelCount + mHapticChannelCount, mFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07005097 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
5098 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
5099 }
Eric Laurent81784c32012-11-19 14:55:58 -08005100
5101 // create a MonoPipe to connect our submix to FastMixer
5102 NBAIO_Format format = mOutputSink->format();
Andy Hung8946a282018-04-19 20:04:56 -07005103
Andy Hung1258c1a2014-05-23 21:22:17 -07005104 // adjust format to match that of the Fast Mixer
Glenn Kasten49f36ba2017-12-06 13:02:02 -08005105 ALOGV("format changed from %#x to %#x", format.mFormat, fastMixerFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07005106 format.mFormat = fastMixerFormat;
5107 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
5108
Eric Laurent81784c32012-11-19 14:55:58 -08005109 // This pipe depth compensates for scheduling latency of the normal mixer thread.
5110 // When it wakes up after a maximum latency, it runs a few cycles quickly before
5111 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
5112 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
Andy Hung920f6572022-10-06 12:09:49 -07005113 const NBAIO_Format offersFast[1] = {format};
5114 size_t numCounterOffersFast = 0;
Andy Hung8946a282018-04-19 20:04:56 -07005115#if !LOG_NDEBUG
Eric Laurent1e28aaa2023-04-16 19:34:23 +02005116 index =
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005117#else
5118 (void)
5119#endif
Andy Hung920f6572022-10-06 12:09:49 -07005120 monoPipe->negotiate(offersFast, std::size(offersFast),
5121 nullptr /* counterOffers */, numCounterOffersFast);
Eric Laurent81784c32012-11-19 14:55:58 -08005122 ALOG_ASSERT(index == 0);
5123 monoPipe->setAvgFrames((mScreenState & 1) ?
5124 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
5125 mPipeSink = monoPipe;
5126
Eric Laurent81784c32012-11-19 14:55:58 -08005127 // create fast mixer and configure it initially with just one fast track for our submix
Andy Hung8946a282018-04-19 20:04:56 -07005128 mFastMixer = new FastMixer(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08005129 FastMixerStateQueue *sq = mFastMixer->sq();
5130#ifdef STATE_QUEUE_DUMP
5131 sq->setObserverDump(&mStateQueueObserverDump);
5132 sq->setMutatorDump(&mStateQueueMutatorDump);
5133#endif
5134 FastMixerState *state = sq->begin();
5135 FastTrack *fastTrack = &state->mFastTracks[0];
5136 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
5137 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
5138 fastTrack->mVolumeProvider = NULL;
Mikhail Naganov55773032020-10-01 15:08:13 -07005139 fastTrack->mChannelMask = static_cast<audio_channel_mask_t>(
5140 mChannelMask | mHapticChannelMask); // mPipeSink channel mask for
5141 // audio to FastMixer
Andy Hunge8a1ced2014-05-09 15:02:21 -07005142 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
jiabin245cdd92018-12-07 17:55:15 -08005143 fastTrack->mHapticPlaybackEnabled = mHapticChannelMask != AUDIO_CHANNEL_NONE;
jiabine70bc7f2020-06-30 22:07:55 -07005144 fastTrack->mHapticIntensity = os::HapticScale::NONE;
Lais Andradebc3f37a2021-07-02 00:13:19 +01005145 fastTrack->mHapticMaxAmplitude = NAN;
Eric Laurent81784c32012-11-19 14:55:58 -08005146 fastTrack->mGeneration++;
5147 state->mFastTracksGen++;
5148 state->mTrackMask = 1;
5149 // fast mixer will use the HAL output sink
5150 state->mOutputSink = mOutputSink.get();
5151 state->mOutputSinkGen++;
5152 state->mFrameCount = mFrameCount;
jiabin245cdd92018-12-07 17:55:15 -08005153 // specify sink channel mask when haptic channel mask present as it can not
5154 // be calculated directly from channel count
5155 state->mSinkChannelMask = mHapticChannelMask == AUDIO_CHANNEL_NONE
Mikhail Naganov55773032020-10-01 15:08:13 -07005156 ? AUDIO_CHANNEL_NONE
5157 : static_cast<audio_channel_mask_t>(mChannelMask | mHapticChannelMask);
Eric Laurent81784c32012-11-19 14:55:58 -08005158 state->mCommand = FastMixerState::COLD_IDLE;
5159 // already done in constructor initialization list
5160 //mFastMixerFutex = 0;
5161 state->mColdFutexAddr = &mFastMixerFutex;
5162 state->mColdGen++;
5163 state->mDumpState = &mFastMixerDumpState;
Andy Hung583043b2023-07-17 17:05:00 -07005164 mFastMixerNBLogWriter = afThreadCallback->newWriter_l(kFastMixerLogSize, "FastMixer");
Glenn Kasten9e58b552013-01-18 15:09:48 -08005165 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08005166 sq->end();
5167 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
5168
Eric Tan0513b5d2018-09-17 10:32:48 -07005169 NBLog::thread_info_t info;
5170 info.id = mId;
5171 info.type = NBLog::FASTMIXER;
5172 mFastMixerNBLogWriter->log<NBLog::EVENT_THREAD_INFO>(info);
5173
Eric Laurent81784c32012-11-19 14:55:58 -08005174 // start the fast mixer
5175 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
5176 pid_t tid = mFastMixer->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07005177 sendPrioConfigEvent(getpid(), tid, kPriorityFastMixer, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08005178 stream()->setHalThreadPriority(kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08005179
5180#ifdef AUDIO_WATCHDOG
5181 // create and start the watchdog
5182 mAudioWatchdog = new AudioWatchdog();
5183 mAudioWatchdog->setDump(&mAudioWatchdogDump);
5184 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
5185 tid = mAudioWatchdog->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07005186 sendPrioConfigEvent(getpid(), tid, kPriorityFastMixer, false /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08005187#endif
Andy Hung8946a282018-04-19 20:04:56 -07005188 } else {
5189#ifdef TEE_SINK
5190 // Only use the MixerThread tee if there is no FastMixer.
5191 mTee.set(mOutputSink->format(), NBAIO_Tee::TEE_FLAG_OUTPUT_THREAD);
5192 mTee.setId(std::string("_") + std::to_string(mId) + "_M");
5193#endif
Eric Laurent81784c32012-11-19 14:55:58 -08005194 }
5195
5196 switch (kUseFastMixer) {
5197 case FastMixer_Never:
5198 case FastMixer_Dynamic:
5199 mNormalSink = mOutputSink;
5200 break;
5201 case FastMixer_Always:
5202 mNormalSink = mPipeSink;
5203 break;
5204 case FastMixer_Static:
5205 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
5206 break;
5207 }
5208}
5209
Andy Hungee58e4a2023-07-07 13:47:37 -07005210MixerThread::~MixerThread()
Eric Laurent81784c32012-11-19 14:55:58 -08005211{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005212 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005213 FastMixerStateQueue *sq = mFastMixer->sq();
5214 FastMixerState *state = sq->begin();
5215 if (state->mCommand == FastMixerState::COLD_IDLE) {
5216 int32_t old = android_atomic_inc(&mFastMixerFutex);
5217 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07005218 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08005219 }
5220 }
5221 state->mCommand = FastMixerState::EXIT;
5222 sq->end();
5223 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
5224 mFastMixer->join();
5225 // Though the fast mixer thread has exited, it's state queue is still valid.
5226 // We'll use that extract the final state which contains one remaining fast track
5227 // corresponding to our sub-mix.
5228 state = sq->begin();
5229 ALOG_ASSERT(state->mTrackMask == 1);
5230 FastTrack *fastTrack = &state->mFastTracks[0];
5231 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
5232 delete fastTrack->mBufferProvider;
5233 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005234 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08005235#ifdef AUDIO_WATCHDOG
5236 if (mAudioWatchdog != 0) {
5237 mAudioWatchdog->requestExit();
5238 mAudioWatchdog->requestExitAndWait();
5239 mAudioWatchdog.clear();
5240 }
5241#endif
5242 }
Andy Hung583043b2023-07-17 17:05:00 -07005243 mAfThreadCallback->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08005244 delete mAudioMixer;
5245}
5246
Andy Hungee58e4a2023-07-07 13:47:37 -07005247void MixerThread::onFirstRef() {
Eric Laurentb0463942022-12-20 16:31:10 +01005248 PlaybackThread::onFirstRef();
5249
Andy Hung972bec12023-08-31 16:13:39 -07005250 audio_utils::lock_guard _l(mutex());
Eric Laurentb0463942022-12-20 16:31:10 +01005251 if (mOutput != nullptr && mOutput->stream != nullptr) {
5252 status_t status = mOutput->stream->setLatencyModeCallback(this);
5253 if (status != INVALID_OPERATION) {
5254 updateHalSupportedLatencyModes_l();
5255 }
5256 // Default to enabled if the HAL supports it. This can be changed by Audioflinger after
5257 // the thread construction according to AudioFlinger::mBluetoothLatencyModesEnabled
5258 mBluetoothLatencyModesEnabled.store(
5259 mOutput->audioHwDev->supportsBluetoothVariableLatency());
5260 }
5261}
Eric Laurent81784c32012-11-19 14:55:58 -08005262
Andy Hungee58e4a2023-07-07 13:47:37 -07005263uint32_t MixerThread::correctLatency_l(uint32_t latency) const
Eric Laurent81784c32012-11-19 14:55:58 -08005264{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005265 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005266 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
5267 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
5268 }
5269 return latency;
5270}
5271
Andy Hungee58e4a2023-07-07 13:47:37 -07005272ssize_t MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08005273{
5274 // FIXME we should only do one push per cycle; confirm this is true
5275 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005276 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005277 FastMixerStateQueue *sq = mFastMixer->sq();
5278 FastMixerState *state = sq->begin();
5279 if (state->mCommand != FastMixerState::MIX_WRITE &&
5280 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
5281 if (state->mCommand == FastMixerState::COLD_IDLE) {
Eric Laurenta2ab4502015-09-09 12:25:51 -07005282
5283 // FIXME workaround for first HAL write being CPU bound on some devices
5284 ATRACE_BEGIN("write");
5285 mOutput->write((char *)mSinkBuffer, 0);
5286 ATRACE_END();
5287
Eric Laurent81784c32012-11-19 14:55:58 -08005288 int32_t old = android_atomic_inc(&mFastMixerFutex);
5289 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07005290 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08005291 }
5292#ifdef AUDIO_WATCHDOG
5293 if (mAudioWatchdog != 0) {
5294 mAudioWatchdog->resume();
5295 }
5296#endif
5297 }
5298 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kastend797a9d2015-03-02 14:19:25 -08005299#ifdef FAST_THREAD_STATISTICS
Andy Hung583043b2023-07-17 17:05:00 -07005300 mFastMixerDumpState.increaseSamplingN(mAfThreadCallback->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08005301 FastThreadDumpState::kSamplingNforLowRamDevice : FastThreadDumpState::kSamplingN);
Glenn Kastend797a9d2015-03-02 14:19:25 -08005302#endif
Eric Laurent81784c32012-11-19 14:55:58 -08005303 sq->end();
5304 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
5305 if (kUseFastMixer == FastMixer_Dynamic) {
5306 mNormalSink = mPipeSink;
5307 }
5308 } else {
5309 sq->end(false /*didModify*/);
5310 }
5311 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005312 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08005313}
5314
Andy Hungee58e4a2023-07-07 13:47:37 -07005315void MixerThread::threadLoop_standby()
Eric Laurent81784c32012-11-19 14:55:58 -08005316{
5317 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005318 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005319 FastMixerStateQueue *sq = mFastMixer->sq();
5320 FastMixerState *state = sq->begin();
5321 if (!(state->mCommand & FastMixerState::IDLE)) {
Andy Hung2148bf02016-11-28 19:01:02 -08005322 // Report any frames trapped in the Monopipe
5323 MonoPipe *monoPipe = (MonoPipe *)mPipeSink.get();
5324 const long long pipeFrames = monoPipe->maxFrames() - monoPipe->availableToWrite();
5325 mLocalLog.log("threadLoop_standby: framesWritten:%lld suspendedFrames:%lld "
5326 "monoPipeWritten:%lld monoPipeLeft:%lld",
5327 (long long)mFramesWritten, (long long)mSuspendedFrames,
5328 (long long)mPipeSink->framesWritten(), pipeFrames);
5329 mLocalLog.log("threadLoop_standby: %s", mTimestamp.toString().c_str());
5330
Eric Laurent81784c32012-11-19 14:55:58 -08005331 state->mCommand = FastMixerState::COLD_IDLE;
5332 state->mColdFutexAddr = &mFastMixerFutex;
5333 state->mColdGen++;
5334 mFastMixerFutex = 0;
5335 sq->end();
5336 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
5337 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
5338 if (kUseFastMixer == FastMixer_Dynamic) {
5339 mNormalSink = mOutputSink;
5340 }
5341#ifdef AUDIO_WATCHDOG
5342 if (mAudioWatchdog != 0) {
5343 mAudioWatchdog->pause();
5344 }
5345#endif
5346 } else {
5347 sq->end(false /*didModify*/);
5348 }
5349 }
5350 PlaybackThread::threadLoop_standby();
5351}
5352
Andy Hungee58e4a2023-07-07 13:47:37 -07005353bool PlaybackThread::waitingAsyncCallback_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08005354{
5355 return false;
5356}
5357
Andy Hungee58e4a2023-07-07 13:47:37 -07005358bool PlaybackThread::shouldStandby_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08005359{
5360 return !mStandby;
5361}
5362
Andy Hungee58e4a2023-07-07 13:47:37 -07005363bool PlaybackThread::waitingAsyncCallback()
Eric Laurentbfb1b832013-01-07 09:53:42 -08005364{
Andy Hung972bec12023-08-31 16:13:39 -07005365 audio_utils::lock_guard _l(mutex());
Eric Laurentbfb1b832013-01-07 09:53:42 -08005366 return waitingAsyncCallback_l();
5367}
5368
Eric Laurent81784c32012-11-19 14:55:58 -08005369// shared by MIXER and DIRECT, overridden by DUPLICATING
Andy Hungee58e4a2023-07-07 13:47:37 -07005370void PlaybackThread::threadLoop_standby()
Eric Laurent81784c32012-11-19 14:55:58 -08005371{
Andy Hung8d672e02023-09-15 18:19:28 -07005372 ALOGV("%s: audio hardware entering standby, mixer %p, suspend count %d",
5373 __func__, this, (int32_t)mSuspended);
Phil Burk062e67a2015-02-11 13:40:50 -08005374 mOutput->standby();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005375 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005376 // discard any pending drain or write ack by incrementing sequence
5377 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
5378 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005379 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005380 mCallbackThread->setWriteBlocked(mWriteAckSequence);
5381 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005382 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08005383 mHwPaused = false;
Eric Laurent68a40a82022-05-03 18:15:04 +02005384 setHalLatencyMode_l();
Eric Laurent81784c32012-11-19 14:55:58 -08005385}
5386
Andy Hungee58e4a2023-07-07 13:47:37 -07005387void PlaybackThread::onAddNewTrack_l()
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08005388{
5389 ALOGV("signal playback thread");
5390 broadcast_l();
5391}
5392
Andy Hungee58e4a2023-07-07 13:47:37 -07005393void PlaybackThread::onAsyncError()
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005394{
5395 for (int i = AUDIO_STREAM_SYSTEM; i < (int)AUDIO_STREAM_CNT; i++) {
5396 invalidateTracks((audio_stream_type_t)i);
5397 }
5398}
5399
Andy Hungee58e4a2023-07-07 13:47:37 -07005400void MixerThread::threadLoop_mix()
Eric Laurent81784c32012-11-19 14:55:58 -08005401{
Eric Laurent81784c32012-11-19 14:55:58 -08005402 // mix buffers...
Glenn Kastend79072e2016-01-06 08:41:20 -08005403 mAudioMixer->process();
Andy Hung25c2dac2014-02-27 14:56:00 -08005404 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005405 // increase sleep time progressively when application underrun condition clears.
5406 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
5407 // that a steady state of alternating ready/not ready conditions keeps the sleep time
5408 // such that we would underrun the audio HAL.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005409 if ((mSleepTimeUs == 0) && (sleepTimeShift > 0)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005410 sleepTimeShift--;
5411 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005412 mSleepTimeUs = 0;
5413 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08005414 //TODO: delay standby when effects have a tail
Glenn Kasten4c053ea2014-09-28 14:41:07 -07005415
Eric Laurent81784c32012-11-19 14:55:58 -08005416}
5417
Andy Hungee58e4a2023-07-07 13:47:37 -07005418void MixerThread::threadLoop_sleepTime()
Eric Laurent81784c32012-11-19 14:55:58 -08005419{
5420 // If no tracks are ready, sleep once for the duration of an output
5421 // buffer size, then write 0s to the output
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005422 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005423 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Andy Hung06d13222018-05-03 20:13:31 -07005424 if (mPipeSink.get() != nullptr && mPipeSink == mNormalSink) {
5425 // Using the Monopipe availableToWrite, we estimate the
5426 // sleep time to retry for more data (before we underrun).
5427 MonoPipe *monoPipe = static_cast<MonoPipe *>(mPipeSink.get());
5428 const ssize_t availableToWrite = mPipeSink->availableToWrite();
5429 const size_t pipeFrames = monoPipe->maxFrames();
5430 const size_t framesLeft = pipeFrames - max(availableToWrite, 0);
5431 // HAL_framecount <= framesDelay ~ framesLeft / 2 <= Normal_Mixer_framecount
5432 const size_t framesDelay = std::min(
5433 mNormalFrameCount, max(framesLeft / 2, mFrameCount));
5434 ALOGV("pipeFrames:%zu framesLeft:%zu framesDelay:%zu",
5435 pipeFrames, framesLeft, framesDelay);
5436 mSleepTimeUs = framesDelay * MICROS_PER_SECOND / mSampleRate;
5437 } else {
5438 mSleepTimeUs = mActiveSleepTimeUs >> sleepTimeShift;
5439 if (mSleepTimeUs < kMinThreadSleepTimeUs) {
5440 mSleepTimeUs = kMinThreadSleepTimeUs;
5441 }
5442 // reduce sleep time in case of consecutive application underruns to avoid
5443 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
5444 // duration we would end up writing less data than needed by the audio HAL if
5445 // the condition persists.
5446 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
5447 sleepTimeShift++;
5448 }
Eric Laurent81784c32012-11-19 14:55:58 -08005449 }
5450 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005451 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005452 }
5453 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08005454 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
5455 // before effects processing or output.
5456 if (mMixerBufferValid) {
5457 memset(mMixerBuffer, 0, mMixerBufferSize);
Eric Laurent39095982021-08-24 18:29:27 +02005458 if (mType == SPATIALIZER) {
5459 memset(mSinkBuffer, 0, mSinkBufferSize);
5460 }
Andy Hung98ef9782014-03-04 14:46:50 -08005461 } else {
5462 memset(mSinkBuffer, 0, mSinkBufferSize);
5463 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005464 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005465 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
5466 "anticipated start");
5467 }
5468 // TODO add standby time extension fct of effect tail
5469}
5470
Andy Hungc5007f82023-08-29 14:26:09 -07005471// prepareTracks_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07005472PlaybackThread::mixer_state MixerThread::prepareTracks_l(
Andy Hung8d31fd22023-06-26 19:20:57 -07005473 Vector<sp<IAfTrack>>* tracksToRemove)
Eric Laurent81784c32012-11-19 14:55:58 -08005474{
Andy Hungc0691382018-09-12 18:01:57 -07005475 // clean up deleted track ids in AudioMixer before allocating new tracks
5476 (void)mTracks.processDeletedTrackIds([this](int trackId) {
5477 // for each trackId, destroy it in the AudioMixer
5478 if (mAudioMixer->exists(trackId)) {
5479 mAudioMixer->destroy(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08005480 }
5481 });
Andy Hungc0691382018-09-12 18:01:57 -07005482 mTracks.clearDeletedTrackIds();
Eric Laurent81784c32012-11-19 14:55:58 -08005483
5484 mixer_state mixerStatus = MIXER_IDLE;
5485 // find out which tracks need to be processed
5486 size_t count = mActiveTracks.size();
5487 size_t mixedTracks = 0;
5488 size_t tracksWithEffect = 0;
5489 // counts only _active_ fast tracks
5490 size_t fastTracks = 0;
5491 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
5492
5493 float masterVolume = mMasterVolume;
5494 bool masterMute = mMasterMute;
5495
5496 if (masterMute) {
5497 masterVolume = 0;
5498 }
5499 // Delegate master volume control to effect in output mix effect chain if needed
Andy Hung116bc262023-06-20 18:56:17 -07005500 sp<IAfEffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Eric Laurent81784c32012-11-19 14:55:58 -08005501 if (chain != 0) {
5502 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
Shunkai Yaof4847652024-01-12 00:25:20 +00005503 chain->setVolume(&v, &v);
Eric Laurent81784c32012-11-19 14:55:58 -08005504 masterVolume = (float)((v + (1 << 23)) >> 24);
5505 chain.clear();
5506 }
5507
5508 // prepare a new state to push
5509 FastMixerStateQueue *sq = NULL;
5510 FastMixerState *state = NULL;
5511 bool didModify = false;
5512 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Andy Hungf2285312017-02-14 18:31:59 -08005513 bool coldIdle = false;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005514 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005515 sq = mFastMixer->sq();
5516 state = sq->begin();
Andy Hungf2285312017-02-14 18:31:59 -08005517 coldIdle = state->mCommand == FastMixerState::COLD_IDLE;
Eric Laurent81784c32012-11-19 14:55:58 -08005518 }
5519
Andy Hung69aed5f2014-02-25 17:24:40 -08005520 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08005521 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08005522
Andy Hungbd3b2b02018-05-21 10:53:11 -07005523 // DeferredOperations handles statistics after setting mixerStatus.
5524 class DeferredOperations {
5525 public:
Andy Hungea840382020-05-05 21:50:17 -07005526 DeferredOperations(mixer_state *mixerStatus, ThreadMetrics *threadMetrics)
5527 : mMixerStatus(mixerStatus)
5528 , mThreadMetrics(threadMetrics) {}
Andy Hungbd3b2b02018-05-21 10:53:11 -07005529
5530 // when leaving scope, tally frames properly.
5531 ~DeferredOperations() {
5532 // Tally underrun frames only if we are actually mixing (MIXER_TRACKS_READY)
5533 // because that is when the underrun occurs.
5534 // We do not distinguish between FastTracks and NormalTracks here.
Andy Hungea840382020-05-05 21:50:17 -07005535 size_t maxUnderrunFrames = 0;
Andy Hungb68f5eb2019-12-03 16:49:17 -08005536 if (*mMixerStatus == MIXER_TRACKS_READY && mUnderrunFrames.size() > 0) {
Andy Hungbd3b2b02018-05-21 10:53:11 -07005537 for (const auto &underrun : mUnderrunFrames) {
Andy Hungc2b11cb2020-04-22 09:04:01 -07005538 underrun.first->tallyUnderrunFrames(underrun.second);
Andy Hungea840382020-05-05 21:50:17 -07005539 maxUnderrunFrames = max(underrun.second, maxUnderrunFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07005540 }
5541 }
Andy Hungea840382020-05-05 21:50:17 -07005542 // send the max underrun frames for this mixer period
5543 mThreadMetrics->logUnderrunFrames(maxUnderrunFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07005544 }
5545
5546 // tallyUnderrunFrames() is called to update the track counters
5547 // with the number of underrun frames for a particular mixer period.
5548 // We defer tallying until we know the final mixer status.
Andy Hung8d31fd22023-06-26 19:20:57 -07005549 void tallyUnderrunFrames(const sp<IAfTrack>& track, size_t underrunFrames) {
Andy Hungbd3b2b02018-05-21 10:53:11 -07005550 mUnderrunFrames.emplace_back(track, underrunFrames);
5551 }
5552
5553 private:
5554 const mixer_state * const mMixerStatus;
Andy Hungea840382020-05-05 21:50:17 -07005555 ThreadMetrics * const mThreadMetrics;
Andy Hung8d31fd22023-06-26 19:20:57 -07005556 std::vector<std::pair<sp<IAfTrack>, size_t>> mUnderrunFrames;
Andy Hungea840382020-05-05 21:50:17 -07005557 } deferredOperations(&mixerStatus, &mThreadMetrics);
Andy Hungb68f5eb2019-12-03 16:49:17 -08005558 // implicit nested scope for variable capture
Andy Hungbd3b2b02018-05-21 10:53:11 -07005559
jiabin245cdd92018-12-07 17:55:15 -08005560 bool noFastHapticTrack = true;
Eric Laurent81784c32012-11-19 14:55:58 -08005561 for (size_t i=0 ; i<count ; i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07005562 const sp<IAfTrack> t = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08005563
5564 // this const just means the local variable doesn't change
Andy Hung8d31fd22023-06-26 19:20:57 -07005565 IAfTrack* const track = t.get();
Eric Laurent81784c32012-11-19 14:55:58 -08005566
5567 // process fast tracks
5568 if (track->isFastTrack()) {
Andy Hungae22b482019-05-09 15:38:55 -07005569 LOG_ALWAYS_FATAL_IF(mFastMixer.get() == nullptr,
5570 "%s(%d): FastTrack(%d) present without FastMixer",
5571 __func__, id(), track->id());
5572
jiabin245cdd92018-12-07 17:55:15 -08005573 if (track->getHapticPlaybackEnabled()) {
5574 noFastHapticTrack = false;
5575 }
Eric Laurent81784c32012-11-19 14:55:58 -08005576
5577 // It's theoretically possible (though unlikely) for a fast track to be created
5578 // and then removed within the same normal mix cycle. This is not a problem, as
5579 // the track never becomes active so it's fast mixer slot is never touched.
5580 // The converse, of removing an (active) track and then creating a new track
5581 // at the identical fast mixer slot within the same normal mix cycle,
5582 // is impossible because the slot isn't marked available until the end of each cycle.
Andy Hung8d31fd22023-06-26 19:20:57 -07005583 int j = track->fastIndex();
Glenn Kastendc2c50b2016-04-21 08:13:14 -07005584 ALOG_ASSERT(0 < j && j < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08005585 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
5586 FastTrack *fastTrack = &state->mFastTracks[j];
5587
5588 // Determine whether the track is currently in underrun condition,
5589 // and whether it had a recent underrun.
5590 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
5591 FastTrackUnderruns underruns = ftDump->mUnderruns;
5592 uint32_t recentFull = (underruns.mBitFields.mFull -
Andy Hung8d31fd22023-06-26 19:20:57 -07005593 track->fastTrackUnderruns().mBitFields.mFull) & UNDERRUN_MASK;
Eric Laurent81784c32012-11-19 14:55:58 -08005594 uint32_t recentPartial = (underruns.mBitFields.mPartial -
Andy Hung8d31fd22023-06-26 19:20:57 -07005595 track->fastTrackUnderruns().mBitFields.mPartial) & UNDERRUN_MASK;
Eric Laurent81784c32012-11-19 14:55:58 -08005596 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
Andy Hung8d31fd22023-06-26 19:20:57 -07005597 track->fastTrackUnderruns().mBitFields.mEmpty) & UNDERRUN_MASK;
Eric Laurent81784c32012-11-19 14:55:58 -08005598 uint32_t recentUnderruns = recentPartial + recentEmpty;
Andy Hung8d31fd22023-06-26 19:20:57 -07005599 track->fastTrackUnderruns() = underruns;
Eric Laurent81784c32012-11-19 14:55:58 -08005600 // don't count underruns that occur while stopping or pausing
5601 // or stopped which can occur when flush() is called while active
Andy Hungbd3b2b02018-05-21 10:53:11 -07005602 size_t underrunFrames = 0;
Glenn Kasten82aaf942013-07-17 16:05:07 -07005603 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
5604 recentUnderruns > 0) {
5605 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
Andy Hungbd3b2b02018-05-21 10:53:11 -07005606 underrunFrames = recentUnderruns * mFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08005607 }
Andy Hungbd3b2b02018-05-21 10:53:11 -07005608 // Immediately account for FastTrack underruns.
Andy Hung8d31fd22023-06-26 19:20:57 -07005609 track->audioTrackServerProxy()->tallyUnderrunFrames(underrunFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08005610
5611 // This is similar to the state machine for normal tracks,
5612 // with a few modifications for fast tracks.
5613 bool isActive = true;
Andy Hung8d31fd22023-06-26 19:20:57 -07005614 switch (track->state()) {
5615 case IAfTrackBase::STOPPING_1:
Eric Laurent81784c32012-11-19 14:55:58 -08005616 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08005617 if (recentUnderruns > 0 || track->isTerminated()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07005618 track->setState(IAfTrackBase::STOPPING_2);
Eric Laurent81784c32012-11-19 14:55:58 -08005619 }
5620 break;
Andy Hung8d31fd22023-06-26 19:20:57 -07005621 case IAfTrackBase::PAUSING:
Eric Laurent81784c32012-11-19 14:55:58 -08005622 // ramp down is not yet implemented
5623 track->setPaused();
5624 break;
Andy Hung8d31fd22023-06-26 19:20:57 -07005625 case IAfTrackBase::RESUMING:
Eric Laurent81784c32012-11-19 14:55:58 -08005626 // ramp up is not yet implemented
Andy Hung8d31fd22023-06-26 19:20:57 -07005627 track->setState(IAfTrackBase::ACTIVE);
Eric Laurent81784c32012-11-19 14:55:58 -08005628 break;
Andy Hung8d31fd22023-06-26 19:20:57 -07005629 case IAfTrackBase::ACTIVE:
Eric Laurent81784c32012-11-19 14:55:58 -08005630 if (recentFull > 0 || recentPartial > 0) {
5631 // track has provided at least some frames recently: reset retry count
Andy Hung8d31fd22023-06-26 19:20:57 -07005632 track->retryCount() = kMaxTrackRetries;
Eric Laurent81784c32012-11-19 14:55:58 -08005633 }
5634 if (recentUnderruns == 0) {
5635 // no recent underruns: stay active
5636 break;
5637 }
5638 // there has recently been an underrun of some kind
5639 if (track->sharedBuffer() == 0) {
5640 // were any of the recent underruns "empty" (no frames available)?
5641 if (recentEmpty == 0) {
5642 // no, then ignore the partial underruns as they are allowed indefinitely
5643 break;
5644 }
5645 // there has recently been an "empty" underrun: decrement the retry counter
Andy Hung8d31fd22023-06-26 19:20:57 -07005646 if (--(track->retryCount()) > 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005647 break;
5648 }
5649 // indicate to client process that the track was disabled because of underrun;
5650 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08005651 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08005652 // remove from active list, but state remains ACTIVE [confusing but true]
5653 isActive = false;
5654 break;
5655 }
Chih-Hung Hsieh2b487032018-09-13 14:16:02 -07005656 FALLTHROUGH_INTENDED;
Andy Hung8d31fd22023-06-26 19:20:57 -07005657 case IAfTrackBase::STOPPING_2:
5658 case IAfTrackBase::PAUSED:
5659 case IAfTrackBase::STOPPED:
5660 case IAfTrackBase::FLUSHED: // flush() while active
Eric Laurent81784c32012-11-19 14:55:58 -08005661 // Check for presentation complete if track is inactive
5662 // We have consumed all the buffers of this track.
5663 // This would be incomplete if we auto-paused on underrun
5664 {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005665 uint32_t latency = 0;
5666 status_t result = mOutput->stream->getLatency(&latency);
5667 ALOGE_IF(result != OK,
5668 "Error when retrieving output stream latency: %d", result);
5669 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08005670 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005671 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
5672 // track stays in active list until presentation is complete
5673 break;
5674 }
5675 }
5676 if (track->isStopping_2()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07005677 track->setState(IAfTrackBase::STOPPED);
Eric Laurent81784c32012-11-19 14:55:58 -08005678 }
5679 if (track->isStopped()) {
5680 // Can't reset directly, as fast mixer is still polling this track
5681 // track->reset();
5682 // So instead mark this track as needing to be reset after push with ack
5683 resetMask |= 1 << i;
5684 }
5685 isActive = false;
5686 break;
Andy Hung8d31fd22023-06-26 19:20:57 -07005687 case IAfTrackBase::IDLE:
Eric Laurent81784c32012-11-19 14:55:58 -08005688 default:
Andy Hung8d31fd22023-06-26 19:20:57 -07005689 LOG_ALWAYS_FATAL("unexpected track state %d", (int)track->state());
Eric Laurent81784c32012-11-19 14:55:58 -08005690 }
5691
5692 if (isActive) {
5693 // was it previously inactive?
5694 if (!(state->mTrackMask & (1 << j))) {
Andy Hung8d31fd22023-06-26 19:20:57 -07005695 ExtendedAudioBufferProvider *eabp = track->asExtendedAudioBufferProvider();
5696 VolumeProvider *vp = track->asVolumeProvider();
Eric Laurent81784c32012-11-19 14:55:58 -08005697 fastTrack->mBufferProvider = eabp;
5698 fastTrack->mVolumeProvider = vp;
Andy Hung8d31fd22023-06-26 19:20:57 -07005699 fastTrack->mChannelMask = track->channelMask();
5700 fastTrack->mFormat = track->format();
jiabin245cdd92018-12-07 17:55:15 -08005701 fastTrack->mHapticPlaybackEnabled = track->getHapticPlaybackEnabled();
jiabin77270b82018-12-18 15:41:29 -08005702 fastTrack->mHapticIntensity = track->getHapticIntensity();
Lais Andradebc3f37a2021-07-02 00:13:19 +01005703 fastTrack->mHapticMaxAmplitude = track->getHapticMaxAmplitude();
Eric Laurent81784c32012-11-19 14:55:58 -08005704 fastTrack->mGeneration++;
5705 state->mTrackMask |= 1 << j;
5706 didModify = true;
5707 // no acknowledgement required for newly active tracks
5708 }
Andy Hung8d31fd22023-06-26 19:20:57 -07005709 sp<AudioTrackServerProxy> proxy = track->audioTrackServerProxy();
Eric Laurenteab90452019-06-24 15:17:46 -07005710 float volume;
5711 if (track->isPlaybackRestricted() || mStreamTypes[track->streamType()].mute) {
5712 volume = 0.f;
5713 } else {
5714 volume = masterVolume * mStreamTypes[track->streamType()].volume;
5715 }
5716
5717 handleVoipVolume_l(&volume);
5718
Eric Laurent81784c32012-11-19 14:55:58 -08005719 // cache the combined master volume and stream type volume for fast mixer; this
5720 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005721 const float vh = track->getVolumeHandler()->getVolume(
Eric Laurenteab90452019-06-24 15:17:46 -07005722 proxy->framesReleased()).first;
5723 volume *= vh;
Andy Hung8d31fd22023-06-26 19:20:57 -07005724 track->setCachedVolume(volume);
Kevin Rocard12381092018-04-11 09:19:59 -07005725 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Vlad Popae2f5aef2022-07-25 16:00:20 +02005726 float vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
5727 float vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
5728
Andy Hung583043b2023-07-17 17:05:00 -07005729 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
Vlad Popae2f5aef2022-07-25 16:00:20 +02005730 /*muteState=*/{masterVolume == 0.f,
5731 mStreamTypes[track->streamType()].volume == 0.f,
5732 mStreamTypes[track->streamType()].mute,
5733 track->isPlaybackRestricted(),
Vlad Popa436c9172022-08-02 15:25:08 +02005734 vlf == 0.f && vrf == 0.f,
5735 vh == 0.f});
Vlad Popae2f5aef2022-07-25 16:00:20 +02005736
5737 vlf *= volume;
5738 vrf *= volume;
Eric Laurenteab90452019-06-24 15:17:46 -07005739
jiabin76d94692022-12-15 21:51:21 +00005740 track->setFinalVolume(vlf, vrf);
Eric Laurent81784c32012-11-19 14:55:58 -08005741 ++fastTracks;
5742 } else {
5743 // was it previously active?
5744 if (state->mTrackMask & (1 << j)) {
5745 fastTrack->mBufferProvider = NULL;
5746 fastTrack->mGeneration++;
5747 state->mTrackMask &= ~(1 << j);
5748 didModify = true;
5749 // If any fast tracks were removed, we must wait for acknowledgement
5750 // because we're about to decrement the last sp<> on those tracks.
5751 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
5752 } else {
Glenn Kastenbf848af2017-12-22 11:55:01 -08005753 // ALOGW rather than LOG_ALWAYS_FATAL because it seems there are cases where an
5754 // AudioTrack may start (which may not be with a start() but with a write()
5755 // after underrun) and immediately paused or released. In that case the
5756 // FastTrack state hasn't had time to update.
5757 // TODO Remove the ALOGW when this theory is confirmed.
5758 ALOGW("fast track %d should have been active; "
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08005759 "mState=%d, mTrackMask=%#x, recentUnderruns=%u, isShared=%d",
Andy Hung8d31fd22023-06-26 19:20:57 -07005760 j, (int)track->state(), state->mTrackMask, recentUnderruns,
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08005761 track->sharedBuffer() != 0);
Glenn Kastenbf848af2017-12-22 11:55:01 -08005762 // Since the FastMixer state already has the track inactive, do nothing here.
Eric Laurent81784c32012-11-19 14:55:58 -08005763 }
5764 tracksToRemove->add(track);
5765 // Avoids a misleading display in dumpsys
Andy Hung8d31fd22023-06-26 19:20:57 -07005766 track->fastTrackUnderruns().mBitFields.mMostRecent = UNDERRUN_FULL;
Eric Laurent81784c32012-11-19 14:55:58 -08005767 }
jiabin245cdd92018-12-07 17:55:15 -08005768 if (fastTrack->mHapticPlaybackEnabled != track->getHapticPlaybackEnabled()) {
5769 fastTrack->mHapticPlaybackEnabled = track->getHapticPlaybackEnabled();
5770 didModify = true;
5771 }
Eric Laurent81784c32012-11-19 14:55:58 -08005772 continue;
5773 }
5774
5775 { // local variable scope to avoid goto warning
5776
5777 audio_track_cblk_t* cblk = track->cblk();
5778
5779 // The first time a track is added we wait
5780 // for all its buffers to be filled before processing it
Andy Hungc0691382018-09-12 18:01:57 -07005781 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08005782
5783 // if an active track doesn't exist in the AudioMixer, create it.
Andy Hungc0691382018-09-12 18:01:57 -07005784 // use the trackId as the AudioMixer name.
5785 if (!mAudioMixer->exists(trackId)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08005786 status_t status = mAudioMixer->create(
Andy Hungc0691382018-09-12 18:01:57 -07005787 trackId,
Andy Hung8d31fd22023-06-26 19:20:57 -07005788 track->channelMask(),
5789 track->format(),
5790 track->sessionId());
Andy Hung1bc088a2018-02-09 15:57:31 -08005791 if (status != OK) {
Andy Hungc0691382018-09-12 18:01:57 -07005792 ALOGW("%s(): AudioMixer cannot create track(%d)"
5793 " mask %#x, format %#x, sessionId %d",
5794 __func__, trackId,
Andy Hung8d31fd22023-06-26 19:20:57 -07005795 track->channelMask(), track->format(), track->sessionId());
Andy Hung1bc088a2018-02-09 15:57:31 -08005796 tracksToRemove->add(track);
5797 track->invalidate(); // consider it dead.
5798 continue;
5799 }
5800 }
5801
Eric Laurent81784c32012-11-19 14:55:58 -08005802 // make sure that we have enough frames to mix one full buffer.
5803 // enforce this condition only once to enable draining the buffer in case the client
5804 // app does not call stop() and relies on underrun to stop:
5805 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
5806 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005807 size_t desiredFrames;
Andy Hung8d31fd22023-06-26 19:20:57 -07005808 const uint32_t sampleRate = track->audioTrackServerProxy()->getSampleRate();
5809 const AudioPlaybackRate playbackRate = track->audioTrackServerProxy()->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07005810
5811 desiredFrames = sourceFramesNeededWithTimestretch(
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07005812 sampleRate, mNormalFrameCount, mSampleRate, playbackRate.mSpeed);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005813 // TODO: ONLY USED FOR LEGACY RESAMPLERS, remove when they are removed.
5814 // add frames already consumed but not yet released by the resampler
5815 // because mAudioTrackServerProxy->framesReady() will include these frames
Andy Hungc0691382018-09-12 18:01:57 -07005816 desiredFrames += mAudioMixer->getUnreleasedFrames(trackId);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005817
Eric Laurent81784c32012-11-19 14:55:58 -08005818 uint32_t minFrames = 1;
5819 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
5820 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005821 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08005822 }
Eric Laurent13e4c962013-12-20 17:36:01 -08005823
5824 size_t framesReady = track->framesReady();
Glenn Kastene7754022014-10-31 12:11:26 -07005825 if (ATRACE_ENABLED()) {
5826 // I wish we had formatted trace names
Andy Hung1bc088a2018-02-09 15:57:31 -08005827 std::string traceName("nRdy");
Andy Hungc0691382018-09-12 18:01:57 -07005828 traceName += std::to_string(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08005829 ATRACE_INT(traceName.c_str(), framesReady);
Glenn Kastene7754022014-10-31 12:11:26 -07005830 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005831 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08005832 !track->isPaused() && !track->isTerminated())
5833 {
Andy Hungc0691382018-09-12 18:01:57 -07005834 ALOGVV("track(%d) s=%08x [OK] on thread %p", trackId, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08005835
5836 mixedTracks++;
5837
Shunkai Yaof4847652024-01-12 00:25:20 +00005838 // track->mainBuffer() != mSinkBuffer and mMixerBuffer means
Andy Hung69aed5f2014-02-25 17:24:40 -08005839 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08005840 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08005841 if (track->mainBuffer() != mSinkBuffer &&
5842 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08005843 if (mEffectBufferEnabled) {
5844 mEffectBufferValid = true; // Later can set directly.
5845 }
Eric Laurent81784c32012-11-19 14:55:58 -08005846 chain = getEffectChain_l(track->sessionId());
5847 // Delegate volume control to effect in track effect chain if needed
5848 if (chain != 0) {
5849 tracksWithEffect++;
5850 } else {
Andy Hungc0691382018-09-12 18:01:57 -07005851 ALOGW("prepareTracks_l(): track(%d) attached to effect but no chain found on "
Eric Laurent81784c32012-11-19 14:55:58 -08005852 "session %d",
Andy Hungc0691382018-09-12 18:01:57 -07005853 trackId, track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08005854 }
5855 }
5856
5857
5858 int param = AudioMixer::VOLUME;
Andy Hung8d31fd22023-06-26 19:20:57 -07005859 if (track->fillingStatus() == IAfTrack::FS_FILLED) {
Eric Laurent81784c32012-11-19 14:55:58 -08005860 // no ramp for the first volume setting
Andy Hung8d31fd22023-06-26 19:20:57 -07005861 track->fillingStatus() = IAfTrack::FS_ACTIVE;
5862 if (track->state() == IAfTrackBase::RESUMING) {
5863 track->setState(IAfTrackBase::ACTIVE);
Revathi Uddaraju453bcb52017-08-14 14:19:40 +08005864 // If a new track is paused immediately after start, do not ramp on resume.
5865 if (cblk->mServer != 0) {
5866 param = AudioMixer::RAMP_VOLUME;
5867 }
Eric Laurent81784c32012-11-19 14:55:58 -08005868 }
Andy Hungc0691382018-09-12 18:01:57 -07005869 mAudioMixer->setParameter(trackId, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Eric Laurent7c29ec92017-09-20 17:54:22 -07005870 mLeftVolFloat = -1.0;
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005871 // FIXME should not make a decision based on mServer
5872 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005873 // If the track is stopped before the first frame was mixed,
5874 // do not apply ramp
5875 param = AudioMixer::RAMP_VOLUME;
5876 }
5877
5878 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07005879 uint32_t vl, vr; // in U8.24 integer format
5880 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Eric Laurent7c29ec92017-09-20 17:54:22 -07005881 // read original volumes with volume control
Eric Laurenteab90452019-06-24 15:17:46 -07005882 float v = masterVolume * mStreamTypes[track->streamType()].volume;
Andy Hung333ab962019-05-28 20:23:35 -07005883 // Always fetch volumeshaper volume to ensure state is updated.
Andy Hung8d31fd22023-06-26 19:20:57 -07005884 const sp<AudioTrackServerProxy> proxy = track->audioTrackServerProxy();
Andy Hung333ab962019-05-28 20:23:35 -07005885 const float vh = track->getVolumeHandler()->getVolume(
Andy Hung8d31fd22023-06-26 19:20:57 -07005886 track->audioTrackServerProxy()->framesReleased()).first;
Eric Laurent7c29ec92017-09-20 17:54:22 -07005887
Eric Laurenteab90452019-06-24 15:17:46 -07005888 if (mStreamTypes[track->streamType()].mute || track->isPlaybackRestricted()) {
5889 v = 0;
5890 }
5891
5892 handleVoipVolume_l(&v);
5893
5894 if (track->isPausing()) {
Andy Hung6be49402014-05-30 10:42:03 -07005895 vl = vr = 0;
5896 vlf = vrf = vaf = 0.;
Eric Laurenteab90452019-06-24 15:17:46 -07005897 track->setPaused();
Eric Laurent81784c32012-11-19 14:55:58 -08005898 } else {
Glenn Kastenc56f3422014-03-21 17:53:17 -07005899 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07005900 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
5901 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08005902 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07005903 if (vlf > GAIN_FLOAT_UNITY) {
5904 ALOGV("Track left volume out of range: %.3g", vlf);
5905 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08005906 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07005907 if (vrf > GAIN_FLOAT_UNITY) {
5908 ALOGV("Track right volume out of range: %.3g", vrf);
5909 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08005910 }
Vlad Popae2f5aef2022-07-25 16:00:20 +02005911
Andy Hung583043b2023-07-17 17:05:00 -07005912 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
Vlad Popae2f5aef2022-07-25 16:00:20 +02005913 /*muteState=*/{masterVolume == 0.f,
5914 mStreamTypes[track->streamType()].volume == 0.f,
5915 mStreamTypes[track->streamType()].mute,
5916 track->isPlaybackRestricted(),
Vlad Popa436c9172022-08-02 15:25:08 +02005917 vlf == 0.f && vrf == 0.f,
5918 vh == 0.f});
Vlad Popae2f5aef2022-07-25 16:00:20 +02005919
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005920 // now apply the master volume and stream type volume and shaper volume
5921 vlf *= v * vh;
5922 vrf *= v * vh;
Eric Laurent81784c32012-11-19 14:55:58 -08005923 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07005924 // then derive vl and vr as U8.24 versions for the effect chain
5925 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
5926 vl = (uint32_t) (scaleto8_24 * vlf);
5927 vr = (uint32_t) (scaleto8_24 * vrf);
5928 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08005929 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08005930 // send level comes from shared memory and so may be corrupt
5931 if (sendLevel > MAX_GAIN_INT) {
5932 ALOGV("Track send level out of range: %04X", sendLevel);
5933 sendLevel = MAX_GAIN_INT;
5934 }
Andy Hung6be49402014-05-30 10:42:03 -07005935 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
5936 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08005937 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005938
jiabin76d94692022-12-15 21:51:21 +00005939 track->setFinalVolume(vrf, vlf);
Kevin Rocard12381092018-04-11 09:19:59 -07005940
Eric Laurent81784c32012-11-19 14:55:58 -08005941 // Delegate volume control to effect in track effect chain if needed
Shunkai Yaof4847652024-01-12 00:25:20 +00005942 if (chain != 0 && chain->setVolume(&vl, &vr)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005943 // Do not ramp volume if volume is controlled by effect
5944 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08005945 // Update remaining floating point volume levels
5946 vlf = (float)vl / (1 << 24);
5947 vrf = (float)vr / (1 << 24);
Andy Hung8d31fd22023-06-26 19:20:57 -07005948 track->setHasVolumeController(true);
Eric Laurent81784c32012-11-19 14:55:58 -08005949 } else {
5950 // force no volume ramp when volume controller was just disabled or removed
5951 // from effect chain to avoid volume spike
Andy Hung8d31fd22023-06-26 19:20:57 -07005952 if (track->hasVolumeController()) {
Eric Laurent81784c32012-11-19 14:55:58 -08005953 param = AudioMixer::VOLUME;
5954 }
Andy Hung8d31fd22023-06-26 19:20:57 -07005955 track->setHasVolumeController(false);
Eric Laurent81784c32012-11-19 14:55:58 -08005956 }
5957
Eric Laurent81784c32012-11-19 14:55:58 -08005958 // XXX: these things DON'T need to be done each time
Andy Hung8d31fd22023-06-26 19:20:57 -07005959 mAudioMixer->setBufferProvider(trackId, track->asExtendedAudioBufferProvider());
Andy Hungc0691382018-09-12 18:01:57 -07005960 mAudioMixer->enable(trackId);
Eric Laurent81784c32012-11-19 14:55:58 -08005961
Andy Hungc0691382018-09-12 18:01:57 -07005962 mAudioMixer->setParameter(trackId, param, AudioMixer::VOLUME0, &vlf);
5963 mAudioMixer->setParameter(trackId, param, AudioMixer::VOLUME1, &vrf);
5964 mAudioMixer->setParameter(trackId, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08005965 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005966 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005967 AudioMixer::TRACK,
5968 AudioMixer::FORMAT, (void *)track->format());
5969 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005970 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005971 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00005972 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Eric Laurent39095982021-08-24 18:29:27 +02005973
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,
5978 AudioMixer::MIXER_CHANNEL_MASK,
5979 (void *)(uintptr_t)(mChannelMask | mHapticChannelMask));
5980 } else {
5981 mAudioMixer->setParameter(
5982 trackId,
5983 AudioMixer::TRACK,
5984 AudioMixer::MIXER_CHANNEL_MASK,
5985 (void *)(uintptr_t)(mMixerChannelMask | mHapticChannelMask));
5986 }
5987
Glenn Kastene3aa6592012-12-04 12:22:46 -08005988 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07005989 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Andy Hung333ab962019-05-28 20:23:35 -07005990 uint32_t reqSampleRate = proxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08005991 if (reqSampleRate == 0) {
5992 reqSampleRate = mSampleRate;
5993 } else if (reqSampleRate > maxSampleRate) {
5994 reqSampleRate = maxSampleRate;
5995 }
Eric Laurent81784c32012-11-19 14:55:58 -08005996 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005997 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005998 AudioMixer::RESAMPLE,
5999 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00006000 (void *)(uintptr_t)reqSampleRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07006001
Andy Hung8edb8dc2015-03-26 19:13:55 -07006002 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07006003 trackId,
Andy Hung8edb8dc2015-03-26 19:13:55 -07006004 AudioMixer::TIMESTRETCH,
6005 AudioMixer::PLAYBACK_RATE,
Andy Hung920f6572022-10-06 12:09:49 -07006006 // cast away constness for this generic API.
6007 const_cast<void *>(reinterpret_cast<const void *>(&playbackRate)));
Andy Hung8edb8dc2015-03-26 19:13:55 -07006008
Andy Hung69aed5f2014-02-25 17:24:40 -08006009 /*
6010 * Select the appropriate output buffer for the track.
6011 *
Andy Hung98ef9782014-03-04 14:46:50 -08006012 * Tracks with effects go into their own effects chain buffer
6013 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08006014 *
6015 * Other tracks can use mMixerBuffer for higher precision
6016 * channel accumulation. If this buffer is enabled
6017 * (mMixerBufferEnabled true), then selected tracks will accumulate
6018 * into it.
6019 *
6020 */
6021 if (mMixerBufferEnabled
6022 && (track->mainBuffer() == mSinkBuffer
6023 || track->mainBuffer() == mMixerBuffer)) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02006024 if (mType == SPATIALIZER && !track->isSpatialized()) {
Eric Laurent39095982021-08-24 18:29:27 +02006025 mAudioMixer->setParameter(
6026 trackId,
6027 AudioMixer::TRACK,
Eric Laurentb62d0362021-10-26 17:40:18 +02006028 AudioMixer::MIXER_FORMAT, (void *)mEffectBufferFormat);
Eric Laurent39095982021-08-24 18:29:27 +02006029 mAudioMixer->setParameter(
6030 trackId,
6031 AudioMixer::TRACK,
Eric Laurentb62d0362021-10-26 17:40:18 +02006032 AudioMixer::MAIN_BUFFER, (void *)mPostSpatializerBuffer);
Eric Laurent39095982021-08-24 18:29:27 +02006033 } else {
6034 mAudioMixer->setParameter(
6035 trackId,
6036 AudioMixer::TRACK,
6037 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
6038 mAudioMixer->setParameter(
6039 trackId,
6040 AudioMixer::TRACK,
6041 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
6042 // TODO: override track->mainBuffer()?
6043 mMixerBufferValid = true;
6044 }
Andy Hung69aed5f2014-02-25 17:24:40 -08006045 } else {
6046 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07006047 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08006048 AudioMixer::TRACK,
Andy Hung319587b2023-05-23 14:01:03 -07006049 AudioMixer::MIXER_FORMAT, (void *)AUDIO_FORMAT_PCM_FLOAT);
Andy Hung69aed5f2014-02-25 17:24:40 -08006050 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07006051 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08006052 AudioMixer::TRACK,
6053 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
6054 }
Eric Laurent81784c32012-11-19 14:55:58 -08006055 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07006056 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08006057 AudioMixer::TRACK,
6058 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
jiabin245cdd92018-12-07 17:55:15 -08006059 mAudioMixer->setParameter(
6060 trackId,
6061 AudioMixer::TRACK,
6062 AudioMixer::HAPTIC_ENABLED, (void *)(uintptr_t)track->getHapticPlaybackEnabled());
jiabin77270b82018-12-18 15:41:29 -08006063 mAudioMixer->setParameter(
6064 trackId,
6065 AudioMixer::TRACK,
6066 AudioMixer::HAPTIC_INTENSITY, (void *)(uintptr_t)track->getHapticIntensity());
Andy Hung8d31fd22023-06-26 19:20:57 -07006067 const float hapticMaxAmplitude = track->getHapticMaxAmplitude();
Lais Andradebc3f37a2021-07-02 00:13:19 +01006068 mAudioMixer->setParameter(
6069 trackId,
6070 AudioMixer::TRACK,
Andy Hung8d31fd22023-06-26 19:20:57 -07006071 AudioMixer::HAPTIC_MAX_AMPLITUDE, (void *)&hapticMaxAmplitude);
Eric Laurent81784c32012-11-19 14:55:58 -08006072
6073 // reset retry count
Andy Hung8d31fd22023-06-26 19:20:57 -07006074 track->retryCount() = kMaxTrackRetries;
Eric Laurent81784c32012-11-19 14:55:58 -08006075
6076 // If one track is ready, set the mixer ready if:
6077 // - the mixer was not ready during previous round OR
6078 // - no other track is not ready
6079 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
6080 mixerStatus != MIXER_TRACKS_ENABLED) {
6081 mixerStatus = MIXER_TRACKS_READY;
6082 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08006083
6084 // Enable the next few lines to instrument a test for underrun log handling.
6085 // TODO: Remove when we have a better way of testing the underrun log.
6086#if 0
6087 static int i;
6088 if ((++i & 0xf) == 0) {
6089 deferredOperations.tallyUnderrunFrames(track, 10 /* underrunFrames */);
6090 }
6091#endif
Eric Laurent81784c32012-11-19 14:55:58 -08006092 } else {
Andy Hungbd3b2b02018-05-21 10:53:11 -07006093 size_t underrunFrames = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08006094 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Andy Hungb68f5eb2019-12-03 16:49:17 -08006095 ALOGV("track(%d) underrun, track state %s framesReady(%zu) < framesDesired(%zd)",
6096 trackId, track->getTrackStateAsString(), framesReady, desiredFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07006097 underrunFrames = desiredFrames;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08006098 }
Andy Hungbd3b2b02018-05-21 10:53:11 -07006099 deferredOperations.tallyUnderrunFrames(track, underrunFrames);
Phil Burk2812d9e2016-01-04 10:34:30 -08006100
Eric Laurent81784c32012-11-19 14:55:58 -08006101 // clear effect chain input buffer if an active track underruns to avoid sending
6102 // previous audio buffer again to effects
6103 chain = getEffectChain_l(track->sessionId());
6104 if (chain != 0) {
6105 chain->clearInputBuffer();
6106 }
6107
Andy Hungc0691382018-09-12 18:01:57 -07006108 ALOGVV("track(%d) s=%08x [NOT READY] on thread %p", trackId, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08006109 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
6110 track->isStopped() || track->isPaused()) {
6111 // We have consumed all the buffers of this track.
6112 // Remove it from the list of active tracks.
6113 // TODO: use actual buffer filling status instead of latency when available from
6114 // audio HAL
6115 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08006116 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08006117 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
6118 if (track->isStopped()) {
6119 track->reset();
6120 }
6121 tracksToRemove->add(track);
6122 }
6123 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08006124 // No buffers for this track. Give it a few chances to
6125 // fill a buffer, then remove it from active list.
Andy Hung8d31fd22023-06-26 19:20:57 -07006126 if (--(track->retryCount()) <= 0) {
Andy Hungc0691382018-09-12 18:01:57 -07006127 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p",
6128 trackId, this);
Eric Laurent81784c32012-11-19 14:55:58 -08006129 tracksToRemove->add(track);
6130 // indicate to client process that the track was disabled because of underrun;
6131 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08006132 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08006133 // If one track is not ready, mark the mixer also not ready if:
6134 // - the mixer was ready during previous round OR
6135 // - no other track is ready
6136 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
6137 mixerStatus != MIXER_TRACKS_READY) {
6138 mixerStatus = MIXER_TRACKS_ENABLED;
6139 }
6140 }
Andy Hungc0691382018-09-12 18:01:57 -07006141 mAudioMixer->disable(trackId);
Eric Laurent81784c32012-11-19 14:55:58 -08006142 }
6143
6144 } // local variable scope to avoid goto warning
Eric Laurent81784c32012-11-19 14:55:58 -08006145
6146 }
6147
jiabin245cdd92018-12-07 17:55:15 -08006148 if (mHapticChannelMask != AUDIO_CHANNEL_NONE && sq != NULL) {
6149 // When there is no fast track playing haptic and FastMixer exists,
6150 // enabling the first FastTrack, which provides mixed data from normal
6151 // tracks, to play haptic data.
6152 FastTrack *fastTrack = &state->mFastTracks[0];
6153 if (fastTrack->mHapticPlaybackEnabled != noFastHapticTrack) {
6154 fastTrack->mHapticPlaybackEnabled = noFastHapticTrack;
6155 didModify = true;
6156 }
6157 }
6158
Eric Laurent81784c32012-11-19 14:55:58 -08006159 // Push the new FastMixer state if necessary
Jing Mike537412f2023-03-12 11:01:47 +08006160 [[maybe_unused]] bool pauseAudioWatchdog = false;
Eric Laurent81784c32012-11-19 14:55:58 -08006161 if (didModify) {
6162 state->mFastTracksGen++;
6163 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
6164 if (kUseFastMixer == FastMixer_Dynamic &&
6165 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
6166 state->mCommand = FastMixerState::COLD_IDLE;
6167 state->mColdFutexAddr = &mFastMixerFutex;
6168 state->mColdGen++;
6169 mFastMixerFutex = 0;
6170 if (kUseFastMixer == FastMixer_Dynamic) {
6171 mNormalSink = mOutputSink;
6172 }
6173 // If we go into cold idle, need to wait for acknowledgement
6174 // so that fast mixer stops doing I/O.
6175 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
6176 pauseAudioWatchdog = true;
6177 }
Eric Laurent81784c32012-11-19 14:55:58 -08006178 }
6179 if (sq != NULL) {
6180 sq->end(didModify);
Andy Hungf2285312017-02-14 18:31:59 -08006181 // No need to block if the FastMixer is in COLD_IDLE as the FastThread
6182 // is not active. (We BLOCK_UNTIL_ACKED when entering COLD_IDLE
6183 // when bringing the output sink into standby.)
6184 //
6185 // We will get the latest FastMixer state when we come out of COLD_IDLE.
6186 //
6187 // This occurs with BT suspend when we idle the FastMixer with
6188 // active tracks, which may be added or removed.
6189 sq->push(coldIdle ? FastMixerStateQueue::BLOCK_NEVER : block);
Eric Laurent81784c32012-11-19 14:55:58 -08006190 }
6191#ifdef AUDIO_WATCHDOG
6192 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
6193 mAudioWatchdog->pause();
6194 }
6195#endif
6196
6197 // Now perform the deferred reset on fast tracks that have stopped
6198 while (resetMask != 0) {
6199 size_t i = __builtin_ctz(resetMask);
6200 ALOG_ASSERT(i < count);
6201 resetMask &= ~(1 << i);
Andy Hung8d31fd22023-06-26 19:20:57 -07006202 sp<IAfTrack> track = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08006203 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
6204 track->reset();
6205 }
6206
Andy Hung80d03d22018-04-10 10:32:11 -07006207 // Track destruction may occur outside of threadLoop once it is removed from active tracks.
6208 // Ensure the AudioMixer doesn't have a raw "buffer provider" pointer to the track if
6209 // it ceases to be active, to allow safe removal from the AudioMixer at the start
6210 // of prepareTracks_l(); this releases any outstanding buffer back to the track.
6211 // See also the implementation of destroyTrack_l().
6212 for (const auto &track : *tracksToRemove) {
Andy Hungc0691382018-09-12 18:01:57 -07006213 const int trackId = track->id();
6214 if (mAudioMixer->exists(trackId)) { // Normal tracks here, fast tracks in FastMixer.
6215 mAudioMixer->setBufferProvider(trackId, nullptr /* bufferProvider */);
Andy Hung80d03d22018-04-10 10:32:11 -07006216 }
6217 }
6218
Eric Laurent81784c32012-11-19 14:55:58 -08006219 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08006220 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08006221
Eric Laurentb3f315a2021-07-13 15:09:05 +02006222 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0 ||
6223 getEffectChain_l(AUDIO_SESSION_OUTPUT_STAGE) != 0) {
Eric Laurent97d547d2014-09-02 14:45:53 -07006224 mEffectBufferValid = true;
Marco Nelissenac302142014-10-20 13:15:38 -07006225 }
6226
6227 if (mEffectBufferValid) {
Marco Nelissen57088b52014-10-17 16:39:39 -07006228 // as long as there are effects we should clear the effects buffer, to avoid
6229 // passing a non-clean buffer to the effect chain
6230 memset(mEffectBuffer, 0, mEffectBufferSize);
Eric Laurentb62d0362021-10-26 17:40:18 +02006231 if (mType == SPATIALIZER) {
6232 memset(mPostSpatializerBuffer, 0, mPostSpatializerBufferSize);
6233 }
Eric Laurent97d547d2014-09-02 14:45:53 -07006234 }
Andy Hung69aed5f2014-02-25 17:24:40 -08006235 // sink or mix buffer must be cleared if all tracks are connected to an
6236 // effect chain as in this case the mixer will not write to the sink or mix buffer
6237 // and track effects will accumulate into it
Eric Laurent39095982021-08-24 18:29:27 +02006238 // always clear sink buffer for spatializer output as the output of the spatializer
6239 // effect will be accumulated into it
6240 if ((mBytesRemaining == 0) && (((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
6241 (mixedTracks == 0 && fastTracks > 0)) || (mType == SPATIALIZER))) {
Eric Laurent81784c32012-11-19 14:55:58 -08006242 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08006243 if (mMixerBufferValid) {
6244 memset(mMixerBuffer, 0, mMixerBufferSize);
6245 // TODO: In testing, mSinkBuffer below need not be cleared because
6246 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
6247 // after mixing.
6248 //
6249 // To enforce this guarantee:
6250 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
6251 // (mixedTracks == 0 && fastTracks > 0))
6252 // must imply MIXER_TRACKS_READY.
6253 // Later, we may clear buffers regardless, and skip much of this logic.
6254 }
Andy Hung98ef9782014-03-04 14:46:50 -08006255 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07006256 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08006257 }
6258
6259 // if any fast tracks, then status is ready
6260 mMixerStatusIgnoringFastTracks = mixerStatus;
6261 if (fastTracks > 0) {
6262 mixerStatus = MIXER_TRACKS_READY;
6263 }
6264 return mixerStatus;
6265}
6266
Andy Hungc5007f82023-08-29 14:26:09 -07006267// trackCountForUid_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07006268uint32_t PlaybackThread::trackCountForUid_l(uid_t uid) const
Eric Laurentad7dd962016-09-22 12:38:37 -07006269{
6270 uint32_t trackCount = 0;
6271 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hung1f12a8a2016-11-07 16:10:30 -08006272 if (mTracks[i]->uid() == uid) {
Eric Laurentad7dd962016-09-22 12:38:37 -07006273 trackCount++;
6274 }
6275 }
6276 return trackCount;
6277}
6278
Andy Hungee58e4a2023-07-07 13:47:37 -07006279bool PlaybackThread::IsTimestampAdvancing::check(AudioStreamOut* output)
ziyangch8f194f12021-12-01 13:48:04 -08006280{
Brian Lindahl65e90012022-07-27 18:01:07 +02006281 // Check the timestamp to see if it's advancing once every 150ms. If we check too frequently, we
6282 // could falsely detect that the frame position has stalled due to underrun because we haven't
6283 // given the Audio HAL enough time to update.
6284 const nsecs_t nowNs = systemTime();
6285 if (nowNs - mPreviousNs < mMinimumTimeBetweenChecksNs) {
6286 return mLatchedValue;
6287 }
6288 mPreviousNs = nowNs;
6289 mLatchedValue = false;
6290 // Determine if the presentation position is still advancing.
ziyangch8f194f12021-12-01 13:48:04 -08006291 uint64_t position = 0;
6292 struct timespec unused;
Brian Lindahl65e90012022-07-27 18:01:07 +02006293 const status_t ret = output->getPresentationPosition(&position, &unused);
ziyangch8f194f12021-12-01 13:48:04 -08006294 if (ret == NO_ERROR) {
Brian Lindahl65e90012022-07-27 18:01:07 +02006295 if (position != mPreviousPosition) {
6296 mPreviousPosition = position;
6297 mLatchedValue = true;
ziyangch8f194f12021-12-01 13:48:04 -08006298 }
6299 }
Brian Lindahl65e90012022-07-27 18:01:07 +02006300 return mLatchedValue;
6301}
6302
Andy Hungee58e4a2023-07-07 13:47:37 -07006303void PlaybackThread::IsTimestampAdvancing::clear()
Brian Lindahl65e90012022-07-27 18:01:07 +02006304{
6305 mLatchedValue = true;
6306 mPreviousPosition = 0;
6307 mPreviousNs = 0;
ziyangch8f194f12021-12-01 13:48:04 -08006308}
6309
Andy Hungc5007f82023-08-29 14:26:09 -07006310// isTrackAllowed_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07006311bool MixerThread::isTrackAllowed_l(
Andy Hung1bc088a2018-02-09 15:57:31 -08006312 audio_channel_mask_t channelMask, audio_format_t format,
6313 audio_session_t sessionId, uid_t uid) const
Eric Laurent81784c32012-11-19 14:55:58 -08006314{
Andy Hung1bc088a2018-02-09 15:57:31 -08006315 if (!PlaybackThread::isTrackAllowed_l(channelMask, format, sessionId, uid)) {
6316 return false;
Eric Laurentad7dd962016-09-22 12:38:37 -07006317 }
Andy Hung1bc088a2018-02-09 15:57:31 -08006318 // Check validity as we don't call AudioMixer::create() here.
Mikhail Naganov7ad7a252019-07-30 14:42:32 -07006319 if (!mAudioMixer->isValidFormat(format)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08006320 ALOGW("%s: invalid format: %#x", __func__, format);
6321 return false;
6322 }
Mikhail Naganov7ad7a252019-07-30 14:42:32 -07006323 if (!mAudioMixer->isValidChannelMask(channelMask)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08006324 ALOGW("%s: invalid channelMask: %#x", __func__, channelMask);
6325 return false;
6326 }
6327 return true;
Eric Laurent81784c32012-11-19 14:55:58 -08006328}
6329
Andy Hungc5007f82023-08-29 14:26:09 -07006330// checkForNewParameter_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07006331bool MixerThread::checkForNewParameter_l(const String8& keyValuePair,
Eric Laurent10351942014-05-08 18:49:52 -07006332 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08006333{
Eric Laurent81784c32012-11-19 14:55:58 -08006334 bool reconfig = false;
Eric Laurent10351942014-05-08 18:49:52 -07006335 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006336
Glenn Kastenc05b8d72016-03-24 09:48:17 -07006337 AutoPark<FastMixer> park(mFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08006338
Eric Laurent10351942014-05-08 18:49:52 -07006339 AudioParameter param = AudioParameter(keyValuePair);
6340 int value;
6341 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
6342 reconfig = true;
6343 }
6344 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung81994d62023-07-20 21:44:14 -07006345 if (!isValidPcmSinkFormat(static_cast<audio_format_t>(value))) {
Eric Laurent10351942014-05-08 18:49:52 -07006346 status = BAD_VALUE;
6347 } else {
6348 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08006349 reconfig = true;
6350 }
Eric Laurent10351942014-05-08 18:49:52 -07006351 }
6352 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hung81994d62023-07-20 21:44:14 -07006353 if (!isValidPcmSinkChannelMask(static_cast<audio_channel_mask_t>(value))) {
Eric Laurent10351942014-05-08 18:49:52 -07006354 status = BAD_VALUE;
6355 } else {
6356 // no need to save value, since it's constant
6357 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006358 }
Eric Laurent10351942014-05-08 18:49:52 -07006359 }
6360 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6361 // do not accept frame count changes if tracks are open as the track buffer
6362 // size depends on frame count and correct behavior would not be guaranteed
6363 // if frame count is changed after track creation
6364 if (!mTracks.isEmpty()) {
6365 status = INVALID_OPERATION;
6366 } else {
6367 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006368 }
Eric Laurent10351942014-05-08 18:49:52 -07006369 }
6370 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07006371 LOG_FATAL("Should not set routing device in MixerThread");
Eric Laurent10351942014-05-08 18:49:52 -07006372 }
Eric Laurent81784c32012-11-19 14:55:58 -08006373
Eric Laurent10351942014-05-08 18:49:52 -07006374 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006375 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07006376 if (!mStandby && status == INVALID_OPERATION) {
Andy Hungdda7aed2023-03-27 15:53:06 -07006377 ALOGW("%s: setParameters failed with keyValuePair %s, entering standby",
6378 __func__, keyValuePair.c_str());
Phil Burk062e67a2015-02-11 13:40:50 -08006379 mOutput->standby();
Andy Hungdda7aed2023-03-27 15:53:06 -07006380 mThreadMetrics.logEndInterval();
6381 mThreadSnapshot.onEnd();
6382 setStandby_l();
Eric Laurent10351942014-05-08 18:49:52 -07006383 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006384 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent81784c32012-11-19 14:55:58 -08006385 }
Eric Laurent10351942014-05-08 18:49:52 -07006386 if (status == NO_ERROR && reconfig) {
6387 readOutputParameters_l();
6388 delete mAudioMixer;
6389 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
Andy Hung1bc088a2018-02-09 15:57:31 -08006390 for (const auto &track : mTracks) {
Andy Hungc0691382018-09-12 18:01:57 -07006391 const int trackId = track->id();
Andy Hung920f6572022-10-06 12:09:49 -07006392 const status_t createStatus = mAudioMixer->create(
Andy Hungc0691382018-09-12 18:01:57 -07006393 trackId,
Andy Hung8d31fd22023-06-26 19:20:57 -07006394 track->channelMask(),
6395 track->format(),
6396 track->sessionId());
Andy Hung920f6572022-10-06 12:09:49 -07006397 ALOGW_IF(createStatus != NO_ERROR,
Andy Hungc0691382018-09-12 18:01:57 -07006398 "%s(): AudioMixer cannot create track(%d)"
6399 " mask %#x, format %#x, sessionId %d",
Andy Hung1bc088a2018-02-09 15:57:31 -08006400 __func__,
Andy Hung8d31fd22023-06-26 19:20:57 -07006401 trackId, track->channelMask(), track->format(), track->sessionId());
Eric Laurent10351942014-05-08 18:49:52 -07006402 }
Eric Laurent73e26b62015-04-27 16:55:58 -07006403 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07006404 }
Eric Laurent81784c32012-11-19 14:55:58 -08006405 }
6406
Dean Wheatley68918102021-03-19 22:09:19 +11006407 return reconfig;
Eric Laurent81784c32012-11-19 14:55:58 -08006408}
6409
6410
Andy Hungee58e4a2023-07-07 13:47:37 -07006411void MixerThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -08006412{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07006413 PlaybackThread::dumpInternals_l(fd, args);
Andy Hung8d672e02023-09-15 18:19:28 -07006414 dprintf(fd, " Thread throttle time (msecs): %u\n", (uint32_t)mThreadThrottleTimeMs);
Andy Hung8ed196a2018-01-05 13:21:11 -08006415 dprintf(fd, " AudioMixer tracks: %s\n", mAudioMixer->trackNames().c_str());
Andy Hung2ddee192015-12-18 17:34:44 -08006416 dprintf(fd, " Master mono: %s\n", mMasterMono ? "on" : "off");
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006417 dprintf(fd, " Master balance: %f (%s)\n", mMasterBalance.load(),
6418 (hasFastMixer() ? std::to_string(mFastMixer->getMasterBalance())
6419 : mBalance.toString()).c_str());
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006420 if (hasFastMixer()) {
6421 dprintf(fd, " FastMixer thread %p tid=%d", mFastMixer.get(), mFastMixer->getTid());
6422
6423 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
6424 // while we are dumping it. It may be inconsistent, but it won't mutate!
6425 // This is a large object so we place it on the heap.
6426 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
Eric Tan2942a4e2018-09-12 17:41:27 -07006427 const std::unique_ptr<FastMixerDumpState> copy =
6428 std::make_unique<FastMixerDumpState>(mFastMixerDumpState);
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006429 copy->dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08006430
6431#ifdef STATE_QUEUE_DUMP
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006432 // Similar for state queue
6433 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
6434 observerCopy.dump(fd);
6435 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
6436 mutatorCopy.dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08006437#endif
6438
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006439#ifdef AUDIO_WATCHDOG
6440 if (mAudioWatchdog != 0) {
6441 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
6442 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
6443 wdCopy.dump(fd);
6444 }
6445#endif
6446
6447 } else {
6448 dprintf(fd, " No FastMixer\n");
6449 }
Eric Laurent90cea102023-05-15 15:08:27 +02006450
6451 dprintf(fd, "Bluetooth latency modes are %senabled\n",
6452 mBluetoothLatencyModesEnabled ? "" : "not ");
6453 dprintf(fd, "HAL does %ssupport Bluetooth latency modes\n", mOutput != nullptr &&
6454 mOutput->audioHwDev->supportsBluetoothVariableLatency() ? "" : "not ");
6455 dprintf(fd, "Supported latency modes: %s\n", toString(mSupportedLatencyModes).c_str());
Eric Laurent81784c32012-11-19 14:55:58 -08006456}
6457
Andy Hungee58e4a2023-07-07 13:47:37 -07006458uint32_t MixerThread::idleSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08006459{
6460 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
6461}
6462
Andy Hungee58e4a2023-07-07 13:47:37 -07006463uint32_t MixerThread::suspendSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08006464{
6465 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
6466}
6467
Andy Hungee58e4a2023-07-07 13:47:37 -07006468void MixerThread::cacheParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08006469{
6470 PlaybackThread::cacheParameters_l();
6471
6472 // FIXME: Relaxed timing because of a certain device that can't meet latency
6473 // Should be reduced to 2x after the vendor fixes the driver issue
6474 // increase threshold again due to low power audio mode. The way this warning
6475 // threshold is calculated and its usefulness should be reconsidered anyway.
6476 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
6477}
6478
Andy Hungee58e4a2023-07-07 13:47:37 -07006479void MixerThread::onHalLatencyModesChanged_l() {
Andy Hung583043b2023-07-17 17:05:00 -07006480 mAfThreadCallback->onSupportedLatencyModesChanged(mId, mSupportedLatencyModes);
Eric Laurentb0463942022-12-20 16:31:10 +01006481}
6482
Andy Hungee58e4a2023-07-07 13:47:37 -07006483void MixerThread::setHalLatencyMode_l() {
Eric Laurentb0463942022-12-20 16:31:10 +01006484 // Only handle latency mode if:
6485 // - mBluetoothLatencyModesEnabled is true
6486 // - the HAL supports latency modes
6487 // - the selected device is Bluetooth LE or A2DP
6488 if (!mBluetoothLatencyModesEnabled.load() || mSupportedLatencyModes.empty()) {
6489 return;
6490 }
6491 if (mOutDeviceTypeAddrs.size() != 1
6492 || !(audio_is_a2dp_out_device(mOutDeviceTypeAddrs[0].mType)
6493 || audio_is_ble_out_device(mOutDeviceTypeAddrs[0].mType))) {
6494 return;
6495 }
6496
6497 audio_latency_mode_t latencyMode = AUDIO_LATENCY_MODE_FREE;
6498 if (mSupportedLatencyModes.size() == 1) {
6499 // If the HAL only support one latency mode currently, confirm the choice
6500 latencyMode = mSupportedLatencyModes[0];
6501 } else if (mSupportedLatencyModes.size() > 1) {
6502 // Request low latency if:
6503 // - At least one active track is either:
6504 // - a fast track with gaming usage or
6505 // - a track with acessibility usage
6506 for (const auto& track : mActiveTracks) {
6507 if ((track->isFastTrack() && track->attributes().usage == AUDIO_USAGE_GAME)
6508 || track->attributes().usage == AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY) {
6509 latencyMode = AUDIO_LATENCY_MODE_LOW;
6510 break;
6511 }
6512 }
6513 }
6514
6515 if (latencyMode != mSetLatencyMode) {
6516 status_t status = mOutput->stream->setLatencyMode(latencyMode);
6517 ALOGD("%s: thread(%d) setLatencyMode(%s) returned %d",
6518 __func__, mId, toString(latencyMode).c_str(), status);
6519 if (status == NO_ERROR) {
6520 mSetLatencyMode = latencyMode;
6521 }
6522 }
6523}
6524
Andy Hungee58e4a2023-07-07 13:47:37 -07006525void MixerThread::updateHalSupportedLatencyModes_l() {
Eric Laurentb0463942022-12-20 16:31:10 +01006526
6527 if (mOutput == nullptr || mOutput->stream == nullptr) {
6528 return;
6529 }
6530 std::vector<audio_latency_mode_t> latencyModes;
6531 const status_t status = mOutput->stream->getRecommendedLatencyModes(&latencyModes);
6532 if (status != NO_ERROR) {
6533 latencyModes.clear();
6534 }
6535 if (latencyModes != mSupportedLatencyModes) {
6536 ALOGD("%s: thread(%d) status %d supported latency modes: %s",
6537 __func__, mId, status, toString(latencyModes).c_str());
6538 mSupportedLatencyModes.swap(latencyModes);
6539 sendHalLatencyModesChangedEvent_l();
6540 }
6541}
6542
Andy Hungee58e4a2023-07-07 13:47:37 -07006543status_t MixerThread::getSupportedLatencyModes(
Eric Laurentb0463942022-12-20 16:31:10 +01006544 std::vector<audio_latency_mode_t>* modes) {
6545 if (modes == nullptr) {
6546 return BAD_VALUE;
6547 }
Andy Hung972bec12023-08-31 16:13:39 -07006548 audio_utils::lock_guard _l(mutex());
Eric Laurentb0463942022-12-20 16:31:10 +01006549 *modes = mSupportedLatencyModes;
6550 return NO_ERROR;
6551}
6552
Andy Hungee58e4a2023-07-07 13:47:37 -07006553void MixerThread::onRecommendedLatencyModeChanged(
Eric Laurentb0463942022-12-20 16:31:10 +01006554 std::vector<audio_latency_mode_t> modes) {
Andy Hung972bec12023-08-31 16:13:39 -07006555 audio_utils::lock_guard _l(mutex());
Eric Laurentb0463942022-12-20 16:31:10 +01006556 if (modes != mSupportedLatencyModes) {
6557 ALOGD("%s: thread(%d) supported latency modes: %s",
6558 __func__, mId, toString(modes).c_str());
6559 mSupportedLatencyModes.swap(modes);
6560 sendHalLatencyModesChangedEvent_l();
6561 }
6562}
6563
Andy Hungee58e4a2023-07-07 13:47:37 -07006564status_t MixerThread::setBluetoothVariableLatencyEnabled(bool enabled) {
Eric Laurentb0463942022-12-20 16:31:10 +01006565 if (mOutput == nullptr || mOutput->audioHwDev == nullptr
6566 || !mOutput->audioHwDev->supportsBluetoothVariableLatency()) {
6567 return INVALID_OPERATION;
6568 }
6569 mBluetoothLatencyModesEnabled.store(enabled);
6570 return NO_ERROR;
6571}
6572
Eric Laurent81784c32012-11-19 14:55:58 -08006573// ----------------------------------------------------------------------------
6574
Andy Hungee58e4a2023-07-07 13:47:37 -07006575/* static */
6576sp<IAfPlaybackThread> IAfPlaybackThread::createDirectOutputThread(
Andy Hung583043b2023-07-17 17:05:00 -07006577 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hungee58e4a2023-07-07 13:47:37 -07006578 AudioStreamOut* output, audio_io_handle_t id, bool systemReady,
6579 const audio_offload_info_t& offloadInfo) {
6580 return sp<DirectOutputThread>::make(
Andy Hung583043b2023-07-17 17:05:00 -07006581 afThreadCallback, output, id, systemReady, offloadInfo);
Andy Hungee58e4a2023-07-07 13:47:37 -07006582}
6583
Andy Hung583043b2023-07-17 17:05:00 -07006584DirectOutputThread::DirectOutputThread(const sp<IAfThreadCallback>& afThreadCallback,
Gareth Fennb18c1a32022-10-05 13:42:36 -07006585 AudioStreamOut* output, audio_io_handle_t id, ThreadBase::type_t type, bool systemReady,
6586 const audio_offload_info_t& offloadInfo)
Andy Hung583043b2023-07-17 17:05:00 -07006587 : PlaybackThread(afThreadCallback, output, id, type, systemReady)
Gareth Fennb18c1a32022-10-05 13:42:36 -07006588 , mOffloadInfo(offloadInfo)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006589{
Andy Hung583043b2023-07-17 17:05:00 -07006590 setMasterBalance(afThreadCallback->getMasterBalance_l());
Eric Laurentbfb1b832013-01-07 09:53:42 -08006591}
6592
Andy Hungee58e4a2023-07-07 13:47:37 -07006593DirectOutputThread::~DirectOutputThread()
Eric Laurent81784c32012-11-19 14:55:58 -08006594{
6595}
6596
Andy Hungee58e4a2023-07-07 13:47:37 -07006597void DirectOutputThread::dumpInternals_l(int fd, const Vector<String16>& args)
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006598{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07006599 PlaybackThread::dumpInternals_l(fd, args);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006600 dprintf(fd, " Master balance: %f Left: %f Right: %f\n",
6601 mMasterBalance.load(), mMasterBalanceLeft, mMasterBalanceRight);
6602}
6603
Andy Hungee58e4a2023-07-07 13:47:37 -07006604void DirectOutputThread::setMasterBalance(float balance)
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006605{
Andy Hung972bec12023-08-31 16:13:39 -07006606 audio_utils::lock_guard _l(mutex());
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006607 if (mMasterBalance != balance) {
6608 mMasterBalance.store(balance);
6609 mBalance.computeStereoBalance(balance, &mMasterBalanceLeft, &mMasterBalanceRight);
6610 broadcast_l();
6611 }
6612}
6613
Andy Hungee58e4a2023-07-07 13:47:37 -07006614void DirectOutputThread::processVolume_l(IAfTrack* track, bool lastTrack)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006615{
Eric Laurentbfb1b832013-01-07 09:53:42 -08006616 float left, right;
6617
Andy Hung333ab962019-05-28 20:23:35 -07006618 // Ensure volumeshaper state always advances even when muted.
Andy Hung8d31fd22023-06-26 19:20:57 -07006619 const sp<AudioTrackServerProxy> proxy = track->audioTrackServerProxy();
Andy Hung398ffa22022-12-13 19:19:53 -08006620
Andy Hung398ffa22022-12-13 19:19:53 -08006621 const int64_t frames = mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
6622 const int64_t time = mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
6623
Dean Wheatleyb11b0022023-09-12 04:07:35 +10006624 ALOGVV("%s: Direct/Offload bufferConsumed:%zu timestamp frames:%lld time:%lld",
6625 __func__, proxy->framesReleased(), (long long)frames, (long long)time);
Andy Hung398ffa22022-12-13 19:19:53 -08006626
6627 const int64_t volumeShaperFrames =
6628 mMonotonicFrameCounter.updateAndGetMonotonicFrameCount(frames, time);
6629 const auto [shaperVolume, shaperActive] =
6630 track->getVolumeHandler()->getVolume(volumeShaperFrames);
Andy Hung333ab962019-05-28 20:23:35 -07006631 mVolumeShaperActive = shaperActive;
6632
Vlad Popae2f5aef2022-07-25 16:00:20 +02006633 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
6634 left = float_from_gain(gain_minifloat_unpack_left(vlr));
6635 right = float_from_gain(gain_minifloat_unpack_right(vlr));
6636
6637 const bool clientVolumeMute = (left == 0.f && right == 0.f);
6638
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08006639 if (mMasterMute || mStreamTypes[track->streamType()].mute || track->isPlaybackRestricted()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08006640 left = right = 0;
6641 } else {
6642 float typeVolume = mStreamTypes[track->streamType()].volume;
Andy Hung333ab962019-05-28 20:23:35 -07006643 const float v = mMasterVolume * typeVolume * shaperVolume;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08006644
Glenn Kastenc56f3422014-03-21 17:53:17 -07006645 if (left > GAIN_FLOAT_UNITY) {
6646 left = GAIN_FLOAT_UNITY;
6647 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07006648 if (right > GAIN_FLOAT_UNITY) {
6649 right = GAIN_FLOAT_UNITY;
6650 }
zhangjincheng86cb3bc2023-01-16 17:17:38 +08006651 left *= v;
6652 right *= v;
Andy Hung583043b2023-07-17 17:05:00 -07006653 if (mAfThreadCallback->getMode() != AUDIO_MODE_IN_COMMUNICATION
zhangjincheng86cb3bc2023-01-16 17:17:38 +08006654 || audio_channel_count_from_out_mask(mChannelMask) > 1) {
6655 left *= mMasterBalanceLeft; // DirectOutputThread balance applied as track volume
6656 right *= mMasterBalanceRight;
6657 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006658 }
6659
Andy Hung583043b2023-07-17 17:05:00 -07006660 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
Vlad Popae8d99472022-06-30 16:02:48 +02006661 /*muteState=*/{mMasterMute,
6662 mStreamTypes[track->streamType()].volume == 0.f,
6663 mStreamTypes[track->streamType()].mute,
Vlad Popae2f5aef2022-07-25 16:00:20 +02006664 track->isPlaybackRestricted(),
Vlad Popa436c9172022-08-02 15:25:08 +02006665 clientVolumeMute,
6666 shaperVolume == 0.f});
Vlad Popae8d99472022-06-30 16:02:48 +02006667
Eric Laurentbfb1b832013-01-07 09:53:42 -08006668 if (lastTrack) {
jiabin76d94692022-12-15 21:51:21 +00006669 track->setFinalVolume(left, right);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006670 if (left != mLeftVolFloat || right != mRightVolFloat) {
6671 mLeftVolFloat = left;
6672 mRightVolFloat = right;
6673
Eric Laurentbfb1b832013-01-07 09:53:42 -08006674 // Delegate volume control to effect in track effect chain if needed
6675 // only one effect chain can be present on DirectOutputThread, so if
6676 // there is one, the track is connected to it
6677 if (!mEffectChains.isEmpty()) {
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09006678 // if effect chain exists, volume is handled by it.
6679 // Convert volumes from float to 8.24
6680 uint32_t vl = (uint32_t)(left * (1 << 24));
6681 uint32_t vr = (uint32_t)(right * (1 << 24));
Shunkai Yaof4847652024-01-12 00:25:20 +00006682 // Direct/Offload effect chains set output volume in setVolume().
6683 (void)mEffectChains[0]->setVolume(&vl, &vr);
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09006684 } else {
6685 // otherwise we directly set the volume.
6686 setVolumeForOutput_l(left, right);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006687 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006688 }
6689 }
6690}
6691
Andy Hungee58e4a2023-07-07 13:47:37 -07006692void DirectOutputThread::onAddNewTrack_l()
Phil Burk43b4dcc2015-06-09 16:53:44 -07006693{
Andy Hung8d31fd22023-06-26 19:20:57 -07006694 sp<IAfTrack> previousTrack = mPreviousTrack.promote();
6695 sp<IAfTrack> latestTrack = mActiveTracks.getLatest();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006696
Eric Laurent0f0631e2015-07-06 18:01:25 -07006697 if (previousTrack != 0 && latestTrack != 0) {
6698 if (mType == DIRECT) {
6699 if (previousTrack.get() != latestTrack.get()) {
6700 mFlushPending = true;
6701 }
6702 } else /* mType == OFFLOAD */ {
Dean Wheatley0f51fd02022-08-31 16:41:40 +10006703 if (previousTrack->sessionId() != latestTrack->sessionId() ||
6704 previousTrack->isFlushPending()) {
Eric Laurent0f0631e2015-07-06 18:01:25 -07006705 mFlushPending = true;
6706 }
6707 }
Revathi Uddaraju20413a92016-10-13 17:16:14 +08006708 } else if (previousTrack == 0) {
6709 // there could be an old track added back during track transition for direct
6710 // output, so always issues flush to flush data of the previous track if it
6711 // was already destroyed with HAL paused, then flush can resume the playback
6712 mFlushPending = true;
Phil Burk43b4dcc2015-06-09 16:53:44 -07006713 }
6714 PlaybackThread::onAddNewTrack_l();
6715}
Eric Laurentbfb1b832013-01-07 09:53:42 -08006716
Andy Hungee58e4a2023-07-07 13:47:37 -07006717PlaybackThread::mixer_state DirectOutputThread::prepareTracks_l(
Andy Hung8d31fd22023-06-26 19:20:57 -07006718 Vector<sp<IAfTrack>>* tracksToRemove
Eric Laurent81784c32012-11-19 14:55:58 -08006719)
6720{
Eric Laurentd595b7c2013-04-03 17:27:56 -07006721 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08006722 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006723 bool doHwPause = false;
6724 bool doHwResume = false;
Eric Laurent81784c32012-11-19 14:55:58 -08006725
6726 // find out which tracks need to be processed
Andy Hung8d31fd22023-06-26 19:20:57 -07006727 for (const sp<IAfTrack>& t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08006728 if (t->isInvalid()) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07006729 ALOGW("An invalidated track shouldn't be in active list");
Eric Laurent5850c4c2016-11-10 13:04:31 -08006730 tracksToRemove->add(t);
Phil Burk43b4dcc2015-06-09 16:53:44 -07006731 continue;
6732 }
6733
Andy Hung8d31fd22023-06-26 19:20:57 -07006734 IAfTrack* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006735#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurent81784c32012-11-19 14:55:58 -08006736 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006737#endif
Eric Laurentfd477972013-10-25 18:10:40 -07006738 // Only consider last track started for volume and mixer state control.
6739 // In theory an older track could underrun and restart after the new one starts
6740 // but as we only care about the transition phase between two tracks on a
6741 // direct output, it is not a problem to ignore the underrun case.
Andy Hung8d31fd22023-06-26 19:20:57 -07006742 sp<IAfTrack> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08006743 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08006744
Kuowei Li23666472021-01-20 10:23:25 +08006745 if (track->isPausePending()) {
6746 track->pauseAck();
6747 // It is possible a track might have been flushed or stopped.
6748 // Other operations such as flush pending might occur on the next prepare.
6749 if (track->isPausing()) {
6750 track->setPaused();
6751 }
6752 // Always perform pause, as an immediate flush will change
6753 // the pause state to be no longer isPausing().
Phil Burk6fc2a7c2015-04-30 16:08:10 -07006754 if (mHwSupportsPause && last && !mHwPaused) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006755 doHwPause = true;
6756 mHwPaused = true;
6757 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08006758 } else if (track->isFlushPending()) {
6759 track->flushAck();
6760 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07006761 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006762 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07006763 } else if (track->isResumePending()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006764 track->resumeAck();
Eric Laurent3df841a2016-07-15 15:15:40 -07006765 if (last) {
6766 mLeftVolFloat = mRightVolFloat = -1.0;
6767 if (mHwPaused) {
6768 doHwResume = true;
6769 mHwPaused = false;
6770 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08006771 }
6772 }
6773
Eric Laurent81784c32012-11-19 14:55:58 -08006774 // The first time a track is added we wait
Phil Burk99adee32014-12-10 16:46:30 -08006775 // for all its buffers to be filled before processing it.
6776 // Allow draining the buffer in case the client
6777 // app does not call stop() and relies on underrun to stop:
Andy Hung8d31fd22023-06-26 19:20:57 -07006778 // hence the test on (track->retryCount() > 1).
6779 // If track->retryCount() <= 1 then track is about to be disabled, paused, removed,
Andy Hung455982f2021-04-27 17:46:12 -07006780 // so we accept any nonzero amount of data delivered by the AudioTrack (which will
6781 // reset the retry counter).
Phil Burkca5e6142015-07-14 09:42:29 -07006782 // Do not use a high threshold for compressed audio.
Andy Hung455982f2021-04-27 17:46:12 -07006783
6784 // target retry count that we will use is based on the time we wait for retries.
6785 const int32_t targetRetryCount = kMaxTrackRetriesDirectMs * 1000 / mActiveSleepTimeUs;
6786 // the retry threshold is when we accept any size for PCM data. This is slightly
6787 // smaller than the retry count so we can push small bits of data without a glitch.
6788 const int32_t retryThreshold = targetRetryCount > 2 ? targetRetryCount - 1 : 1;
Eric Laurent81784c32012-11-19 14:55:58 -08006789 uint32_t minFrames;
Phil Burk99adee32014-12-10 16:46:30 -08006790 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
Andy Hung8d31fd22023-06-26 19:20:57 -07006791 && (track->retryCount() > retryThreshold) && audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006792 minFrames = mNormalFrameCount;
6793 } else {
6794 minFrames = 1;
6795 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006796
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07006797 const size_t framesReady = track->framesReady();
6798 const int trackId = track->id();
6799 if (ATRACE_ENABLED()) {
6800 std::string traceName("nRdy");
6801 traceName += std::to_string(trackId);
6802 ATRACE_INT(traceName.c_str(), framesReady);
6803 }
6804 if ((framesReady >= minFrames) && track->isReady() && !track->isPaused() &&
Eric Laurentab5cdba2014-06-09 17:22:27 -07006805 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08006806 {
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07006807 ALOGVV("track(%d) s=%08x [OK]", trackId, cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08006808
Andy Hung8d31fd22023-06-26 19:20:57 -07006809 if (track->fillingStatus() == IAfTrack::FS_FILLED) {
6810 track->fillingStatus() = IAfTrack::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07006811 if (last) {
6812 // make sure processVolume_l() will apply new volume even if 0
6813 mLeftVolFloat = mRightVolFloat = -1.0;
6814 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08006815 if (!mHwSupportsPause) {
6816 track->resumeAck();
Eric Laurent81784c32012-11-19 14:55:58 -08006817 }
6818 }
6819
6820 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08006821 processVolume_l(track, last);
6822 if (last) {
Andy Hung8d31fd22023-06-26 19:20:57 -07006823 sp<IAfTrack> previousTrack = mPreviousTrack.promote();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006824 if (previousTrack != 0) {
6825 if (track != previousTrack.get()) {
6826 // Flush any data still being written from last track
6827 mBytesRemaining = 0;
Eric Laurent0f0631e2015-07-06 18:01:25 -07006828 // Invalidate previous track to force a seek when resuming.
6829 previousTrack->invalidate();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006830 }
6831 }
6832 mPreviousTrack = track;
6833
Eric Laurentd595b7c2013-04-03 17:27:56 -07006834 // reset retry count
Andy Hung8d31fd22023-06-26 19:20:57 -07006835 track->retryCount() = targetRetryCount;
Eric Laurent5850c4c2016-11-10 13:04:31 -08006836 mActiveTrack = t;
Eric Laurentd595b7c2013-04-03 17:27:56 -07006837 mixerStatus = MIXER_TRACKS_READY;
Eric Laurent5cff4032015-05-26 13:49:58 -07006838 if (mHwPaused) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08006839 doHwResume = true;
6840 mHwPaused = false;
6841 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07006842 }
Eric Laurent81784c32012-11-19 14:55:58 -08006843 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07006844 // clear effect chain input buffer if the last active track started underruns
6845 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07006846 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08006847 mEffectChains[0]->clearInputBuffer();
6848 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07006849 if (track->isStopping_1()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07006850 track->setState(IAfTrackBase::STOPPING_2);
Eric Laurentb369caf2015-03-30 20:51:47 -07006851 if (last && mHwPaused) {
6852 doHwResume = true;
6853 mHwPaused = false;
6854 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07006855 }
6856 if ((track->sharedBuffer() != 0) || track->isStopped() ||
6857 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08006858 // We have consumed all the buffers of this track.
6859 // Remove it from the list of active tracks.
Atneya Nair0cae0432022-05-10 18:12:12 -04006860 bool presComplete = false;
Eric Laurentfd477972013-10-25 18:10:40 -07006861 if (mStandby || !last ||
Atneya Nair0cae0432022-05-10 18:12:12 -04006862 (presComplete = track->presentationComplete(latency_l())) ||
Jindong32dc26e2019-11-11 18:10:01 +08006863 track->isPaused() || mHwPaused) {
Atneya Nair0cae0432022-05-10 18:12:12 -04006864 if (presComplete) {
6865 mOutput->presentationComplete();
6866 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07006867 if (track->isStopping_2()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07006868 track->setState(IAfTrackBase::STOPPED);
Eric Laurentab5cdba2014-06-09 17:22:27 -07006869 }
Eric Laurent81784c32012-11-19 14:55:58 -08006870 if (track->isStopped()) {
6871 track->reset();
6872 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07006873 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08006874 }
6875 } else {
6876 // No buffers for this track. Give it a few chances to
6877 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07006878 // Only consider last track started for mixer state control
Brian Lindahl65e90012022-07-27 18:01:07 +02006879 bool isTimestampAdvancing = mIsTimestampAdvancing.check(mOutput);
Gareth Fennb18c1a32022-10-05 13:42:36 -07006880 if (!isTunerStream() // tuner streams remain active in underrun
Andy Hung8d31fd22023-06-26 19:20:57 -07006881 && --(track->retryCount()) <= 0) {
Brian Lindahl65e90012022-07-27 18:01:07 +02006882 if (isTimestampAdvancing) { // HAL is still playing audio, give us more time.
Andy Hung8d31fd22023-06-26 19:20:57 -07006883 track->retryCount() = kMaxTrackRetriesOffload;
ziyangch8f194f12021-12-01 13:48:04 -08006884 } else {
6885 ALOGV("BUFFER TIMEOUT: remove track(%d) from active list", trackId);
6886 tracksToRemove->add(track);
6887 // indicate to client process that the track was disabled because of
6888 // underrun; it will then automatically call start() when data is available
6889 track->disable();
6890 // only do hw pause when track is going to be removed due to BUFFER TIMEOUT.
6891 // unlike mixerthread, HAL can be paused for direct output
6892 ALOGW("pause because of UNDERRUN, framesReady = %zu,"
6893 "minFrames = %u, mFormat = %#x",
6894 framesReady, minFrames, mFormat);
6895 if (last && mHwSupportsPause && !mHwPaused && !mStandby) {
6896 doHwPause = true;
6897 mHwPaused = true;
6898 }
Eric Laurent0f7b5f22014-12-19 10:43:21 -08006899 }
Haynes Mathew George5c6daae2017-01-24 20:06:05 -08006900 } else if (last) {
6901 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurent81784c32012-11-19 14:55:58 -08006902 }
6903 }
6904 }
6905 }
6906
Eric Laurentd1f69b02014-12-15 14:33:13 -08006907 // if an active track did not command a flush, check for pending flush on stopped tracks
Phil Burk43b4dcc2015-06-09 16:53:44 -07006908 if (!mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006909 for (size_t i = 0; i < mTracks.size(); i++) {
6910 if (mTracks[i]->isFlushPending()) {
6911 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006912 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006913 }
6914 }
6915 }
6916
6917 // make sure the pause/flush/resume sequence is executed in the right order.
6918 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
6919 // before flush and then resume HW. This can happen in case of pause/flush/resume
6920 // if resume is received before pause is executed.
6921 if (mHwSupportsPause && !mStandby &&
Phil Burk43b4dcc2015-06-09 16:53:44 -07006922 (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006923 status_t result = mOutput->stream->pause();
6924 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Gareth Fenncd1e1622022-10-05 11:45:45 -07006925 doHwResume = !doHwPause; // resume if pause is due to flush.
Eric Laurentd1f69b02014-12-15 14:33:13 -08006926 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07006927 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006928 flushHw_l();
6929 }
6930 if (mHwSupportsPause && !mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006931 status_t result = mOutput->stream->resume();
6932 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08006933 }
Eric Laurent81784c32012-11-19 14:55:58 -08006934 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08006935 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08006936
6937 return mixerStatus;
6938}
6939
Andy Hungee58e4a2023-07-07 13:47:37 -07006940void DirectOutputThread::threadLoop_mix()
Eric Laurent81784c32012-11-19 14:55:58 -08006941{
Eric Laurent81784c32012-11-19 14:55:58 -08006942 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08006943 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08006944 // output audio to hardware
6945 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07006946 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08006947 buffer.frameCount = frameCount;
Phil Burk062e67a2015-02-11 13:40:50 -08006948 status_t status = mActiveTrack->getNextBuffer(&buffer);
6949 if (status != NO_ERROR || buffer.raw == NULL) {
Eric Laurent51716182016-02-29 18:00:56 -08006950 // no need to pad with 0 for compressed audio
6951 if (audio_has_proportional_frames(mFormat)) {
6952 memset(curBuf, 0, frameCount * mFrameSize);
6953 }
Eric Laurent81784c32012-11-19 14:55:58 -08006954 break;
6955 }
6956 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
6957 frameCount -= buffer.frameCount;
6958 curBuf += buffer.frameCount * mFrameSize;
6959 mActiveTrack->releaseBuffer(&buffer);
6960 }
Andy Hung2098f272014-02-27 14:00:06 -08006961 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006962 mSleepTimeUs = 0;
6963 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08006964 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08006965}
6966
Andy Hungee58e4a2023-07-07 13:47:37 -07006967void DirectOutputThread::threadLoop_sleepTime()
Eric Laurent81784c32012-11-19 14:55:58 -08006968{
Eric Laurentd1f69b02014-12-15 14:33:13 -08006969 // do not write to HAL when paused
Eric Laurent0f7b5f22014-12-19 10:43:21 -08006970 if (mHwPaused || (usesHwAvSync() && mStandby)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006971 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006972 return;
6973 }
Andy Hung85ba3332021-04-27 17:40:26 -07006974 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
6975 mSleepTimeUs = mActiveSleepTimeUs;
6976 } else {
6977 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006978 }
Andy Hung85ba3332021-04-27 17:40:26 -07006979 // Note: In S or later, we do not write zeroes for
6980 // linear or proportional PCM direct tracks in underrun.
Eric Laurent81784c32012-11-19 14:55:58 -08006981}
6982
Andy Hungee58e4a2023-07-07 13:47:37 -07006983void DirectOutputThread::threadLoop_exit()
Eric Laurentd1f69b02014-12-15 14:33:13 -08006984{
6985 {
Andy Hung972bec12023-08-31 16:13:39 -07006986 audio_utils::lock_guard _l(mutex());
Eric Laurentd1f69b02014-12-15 14:33:13 -08006987 for (size_t i = 0; i < mTracks.size(); i++) {
6988 if (mTracks[i]->isFlushPending()) {
6989 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006990 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006991 }
6992 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07006993 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006994 flushHw_l();
6995 }
6996 }
6997 PlaybackThread::threadLoop_exit();
6998}
6999
7000// must be called with thread mutex locked
Andy Hungee58e4a2023-07-07 13:47:37 -07007001bool DirectOutputThread::shouldStandby_l()
Eric Laurentd1f69b02014-12-15 14:33:13 -08007002{
7003 bool trackPaused = false;
Eric Laurentb369caf2015-03-30 20:51:47 -07007004 bool trackStopped = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08007005
7006 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
7007 // after a timeout and we will enter standby then.
7008 if (mTracks.size() > 0) {
7009 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
Eric Laurentb369caf2015-03-30 20:51:47 -07007010 trackStopped = mTracks[mTracks.size() - 1]->isStopped() ||
Andy Hung8d31fd22023-06-26 19:20:57 -07007011 mTracks[mTracks.size() - 1]->state() == IAfTrackBase::IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08007012 }
7013
Eric Laurent5cff4032015-05-26 13:49:58 -07007014 return !mStandby && !(trackPaused || (mHwPaused && !trackStopped));
Eric Laurentd1f69b02014-12-15 14:33:13 -08007015}
7016
Andy Hungc5007f82023-08-29 14:26:09 -07007017// checkForNewParameter_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07007018bool DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
Eric Laurent10351942014-05-08 18:49:52 -07007019 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08007020{
7021 bool reconfig = false;
Eric Laurent10351942014-05-08 18:49:52 -07007022 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08007023
Eric Laurent10351942014-05-08 18:49:52 -07007024 AudioParameter param = AudioParameter(keyValuePair);
7025 int value;
7026 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07007027 LOG_FATAL("Should not set routing device in DirectOutputThread");
Eric Laurent81784c32012-11-19 14:55:58 -08007028 }
Eric Laurent10351942014-05-08 18:49:52 -07007029 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
7030 // do not accept frame count changes if tracks are open as the track buffer
7031 // size depends on frame count and correct behavior would not be garantied
7032 // if frame count is changed after track creation
7033 if (!mTracks.isEmpty()) {
7034 status = INVALID_OPERATION;
7035 } else {
7036 reconfig = true;
7037 }
7038 }
7039 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007040 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07007041 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08007042 mOutput->standby();
Andy Hungcf10d742020-04-28 15:38:24 -07007043 if (!mStandby) {
7044 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07007045 mThreadSnapshot.onEnd();
Eric Laurent19952e12023-04-20 10:08:29 +02007046 setStandby_l();
Andy Hungcf10d742020-04-28 15:38:24 -07007047 }
Eric Laurent10351942014-05-08 18:49:52 -07007048 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007049 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07007050 }
7051 if (status == NO_ERROR && reconfig) {
7052 readOutputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07007053 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07007054 }
7055 }
7056
Dean Wheatley68918102021-03-19 22:09:19 +11007057 return reconfig;
Eric Laurent81784c32012-11-19 14:55:58 -08007058}
7059
Andy Hungee58e4a2023-07-07 13:47:37 -07007060uint32_t DirectOutputThread::activeSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08007061{
7062 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08007063 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08007064 time = PlaybackThread::activeSleepTimeUs();
7065 } else {
Eric Laurent51716182016-02-29 18:00:56 -08007066 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007067 }
7068 return time;
7069}
7070
Andy Hungee58e4a2023-07-07 13:47:37 -07007071uint32_t DirectOutputThread::idleSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08007072{
7073 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08007074 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08007075 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
7076 } else {
Eric Laurent51716182016-02-29 18:00:56 -08007077 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007078 }
7079 return time;
7080}
7081
Andy Hungee58e4a2023-07-07 13:47:37 -07007082uint32_t DirectOutputThread::suspendSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08007083{
7084 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08007085 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08007086 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
7087 } else {
Eric Laurent51716182016-02-29 18:00:56 -08007088 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007089 }
7090 return time;
7091}
7092
Andy Hungee58e4a2023-07-07 13:47:37 -07007093void DirectOutputThread::cacheParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08007094{
7095 PlaybackThread::cacheParameters_l();
7096
7097 // use shorter standby delay as on normal output to release
7098 // hardware resources as soon as possible
Eric Laurentb369caf2015-03-30 20:51:47 -07007099 // no delay on outputs with HW A/V sync
7100 if (usesHwAvSync()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007101 mStandbyDelayNs = 0;
Phil Burkfdb3c072016-02-09 10:47:02 -08007102 } else if ((mType == OFFLOAD) && !audio_has_proportional_frames(mFormat)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007103 mStandbyDelayNs = kOffloadStandbyDelayNs;
Eric Laurent5cff4032015-05-26 13:49:58 -07007104 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007105 mStandbyDelayNs = microseconds(mActiveSleepTimeUs*2);
Eric Laurent972a1732013-09-04 09:42:59 -07007106 }
Eric Laurent81784c32012-11-19 14:55:58 -08007107}
7108
Andy Hungee58e4a2023-07-07 13:47:37 -07007109void DirectOutputThread::flushHw_l()
Eric Laurente659ef42014-09-29 13:06:46 -07007110{
ziyangch8f194f12021-12-01 13:48:04 -08007111 PlaybackThread::flushHw_l();
Phil Burk062e67a2015-02-11 13:40:50 -08007112 mOutput->flush();
Eric Laurentd1f69b02014-12-15 14:33:13 -08007113 mHwPaused = false;
Phil Burk43b4dcc2015-06-09 16:53:44 -07007114 mFlushPending = false;
Dean Wheatley12473e92021-03-18 23:00:55 +11007115 mTimestampVerifier.discontinuity(discontinuityForStandbyOrFlush());
Sampath Shetty999f0e82020-01-15 10:19:06 +11007116 mTimestamp.clear();
Andy Hung398ffa22022-12-13 19:19:53 -08007117 mMonotonicFrameCounter.onFlush();
Eric Laurente659ef42014-09-29 13:06:46 -07007118}
7119
Andy Hungee58e4a2023-07-07 13:47:37 -07007120int64_t DirectOutputThread::computeWaitTimeNs_l() const {
Andy Hung10cbff12017-02-21 17:30:14 -08007121 // If a VolumeShaper is active, we must wake up periodically to update volume.
7122 const int64_t NS_PER_MS = 1000000;
7123 return mVolumeShaperActive ?
7124 kMinNormalSinkBufferSizeMs * NS_PER_MS : PlaybackThread::computeWaitTimeNs_l();
7125}
7126
Eric Laurent81784c32012-11-19 14:55:58 -08007127// ----------------------------------------------------------------------------
7128
Andy Hungee58e4a2023-07-07 13:47:37 -07007129AsyncCallbackThread::AsyncCallbackThread(
7130 const wp<PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08007131 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07007132 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07007133 mWriteAckSequence(0),
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007134 mDrainSequence(0),
7135 mAsyncError(false)
Eric Laurentbfb1b832013-01-07 09:53:42 -08007136{
7137}
7138
Andy Hungee58e4a2023-07-07 13:47:37 -07007139void AsyncCallbackThread::onFirstRef()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007140{
7141 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
7142}
7143
Andy Hungee58e4a2023-07-07 13:47:37 -07007144bool AsyncCallbackThread::threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007145{
7146 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07007147 uint32_t writeAckSequence;
7148 uint32_t drainSequence;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007149 bool asyncError;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007150
7151 {
Andy Hungc5007f82023-08-29 14:26:09 -07007152 audio_utils::unique_lock _l(mutex());
Haynes Mathew George24a325d2013-12-03 21:26:02 -08007153 while (!((mWriteAckSequence & 1) ||
7154 (mDrainSequence & 1) ||
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007155 mAsyncError ||
Haynes Mathew George24a325d2013-12-03 21:26:02 -08007156 exitPending())) {
Andy Hungc5007f82023-08-29 14:26:09 -07007157 mWaitWorkCV.wait(_l);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08007158 }
7159
Eric Laurentbfb1b832013-01-07 09:53:42 -08007160 if (exitPending()) {
7161 break;
7162 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07007163 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
7164 mWriteAckSequence, mDrainSequence);
7165 writeAckSequence = mWriteAckSequence;
7166 mWriteAckSequence &= ~1;
7167 drainSequence = mDrainSequence;
7168 mDrainSequence &= ~1;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007169 asyncError = mAsyncError;
7170 mAsyncError = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007171 }
7172 {
Andy Hungee58e4a2023-07-07 13:47:37 -07007173 const sp<PlaybackThread> playbackThread = mPlaybackThread.promote();
Eric Laurent4de95592013-09-26 15:28:21 -07007174 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07007175 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07007176 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007177 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07007178 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07007179 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007180 }
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007181 if (asyncError) {
7182 playbackThread->onAsyncError();
7183 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007184 }
7185 }
7186 }
7187 return false;
7188}
7189
Andy Hungee58e4a2023-07-07 13:47:37 -07007190void AsyncCallbackThread::exit()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007191{
7192 ALOGV("AsyncCallbackThread::exit");
Andy Hung972bec12023-08-31 16:13:39 -07007193 audio_utils::lock_guard _l(mutex());
Eric Laurentbfb1b832013-01-07 09:53:42 -08007194 requestExit();
Andy Hungc5007f82023-08-29 14:26:09 -07007195 mWaitWorkCV.notify_all();
Eric Laurentbfb1b832013-01-07 09:53:42 -08007196}
7197
Andy Hungee58e4a2023-07-07 13:47:37 -07007198void AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08007199{
Andy Hung972bec12023-08-31 16:13:39 -07007200 audio_utils::lock_guard _l(mutex());
Eric Laurent3b4529e2013-09-05 18:09:19 -07007201 // bit 0 is cleared
7202 mWriteAckSequence = sequence << 1;
7203}
7204
Andy Hungee58e4a2023-07-07 13:47:37 -07007205void AsyncCallbackThread::resetWriteBlocked()
Eric Laurent3b4529e2013-09-05 18:09:19 -07007206{
Andy Hung972bec12023-08-31 16:13:39 -07007207 audio_utils::lock_guard _l(mutex());
Eric Laurent3b4529e2013-09-05 18:09:19 -07007208 // ignore unexpected callbacks
7209 if (mWriteAckSequence & 2) {
7210 mWriteAckSequence |= 1;
Andy Hungc5007f82023-08-29 14:26:09 -07007211 mWaitWorkCV.notify_one();
Eric Laurentbfb1b832013-01-07 09:53:42 -08007212 }
7213}
7214
Andy Hungee58e4a2023-07-07 13:47:37 -07007215void AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08007216{
Andy Hung972bec12023-08-31 16:13:39 -07007217 audio_utils::lock_guard _l(mutex());
Eric Laurent3b4529e2013-09-05 18:09:19 -07007218 // bit 0 is cleared
7219 mDrainSequence = sequence << 1;
7220}
7221
Andy Hungee58e4a2023-07-07 13:47:37 -07007222void AsyncCallbackThread::resetDraining()
Eric Laurent3b4529e2013-09-05 18:09:19 -07007223{
Andy Hung972bec12023-08-31 16:13:39 -07007224 audio_utils::lock_guard _l(mutex());
Eric Laurent3b4529e2013-09-05 18:09:19 -07007225 // ignore unexpected callbacks
7226 if (mDrainSequence & 2) {
7227 mDrainSequence |= 1;
Andy Hungc5007f82023-08-29 14:26:09 -07007228 mWaitWorkCV.notify_one();
Eric Laurentbfb1b832013-01-07 09:53:42 -08007229 }
7230}
7231
Andy Hungee58e4a2023-07-07 13:47:37 -07007232void AsyncCallbackThread::setAsyncError()
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007233{
Andy Hung972bec12023-08-31 16:13:39 -07007234 audio_utils::lock_guard _l(mutex());
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007235 mAsyncError = true;
Andy Hungc5007f82023-08-29 14:26:09 -07007236 mWaitWorkCV.notify_one();
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007237}
7238
Eric Laurentbfb1b832013-01-07 09:53:42 -08007239
7240// ----------------------------------------------------------------------------
Andy Hungee58e4a2023-07-07 13:47:37 -07007241
7242/* static */
7243sp<IAfPlaybackThread> IAfPlaybackThread::createOffloadThread(
Andy Hung583043b2023-07-17 17:05:00 -07007244 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hungee58e4a2023-07-07 13:47:37 -07007245 AudioStreamOut* output, audio_io_handle_t id, bool systemReady,
7246 const audio_offload_info_t& offloadInfo) {
Andy Hung583043b2023-07-17 17:05:00 -07007247 return sp<OffloadThread>::make(afThreadCallback, output, id, systemReady, offloadInfo);
Andy Hungee58e4a2023-07-07 13:47:37 -07007248}
7249
Andy Hung583043b2023-07-17 17:05:00 -07007250OffloadThread::OffloadThread(const sp<IAfThreadCallback>& afThreadCallback,
Gareth Fennb18c1a32022-10-05 13:42:36 -07007251 AudioStreamOut* output, audio_io_handle_t id, bool systemReady,
7252 const audio_offload_info_t& offloadInfo)
Andy Hung583043b2023-07-17 17:05:00 -07007253 : DirectOutputThread(afThreadCallback, output, id, OFFLOAD, systemReady, offloadInfo),
ziyangch8f194f12021-12-01 13:48:04 -08007254 mPausedWriteLength(0), mPausedBytesRemaining(0), mKeepWakeLock(true)
Eric Laurentbfb1b832013-01-07 09:53:42 -08007255{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07007256 //FIXME: mStandby should be set to true by ThreadBase constructo
Eric Laurentfd477972013-10-25 18:10:40 -07007257 mStandby = true;
Eric Laurent64667972016-03-30 18:19:46 -07007258 mKeepWakeLock = property_get_bool("ro.audio.offload_wakelock", true /* default_value */);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007259}
7260
Andy Hungee58e4a2023-07-07 13:47:37 -07007261void OffloadThread::threadLoop_exit()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007262{
7263 if (mFlushPending || mHwPaused) {
7264 // If a flush is pending or track was paused, just discard buffered data
Andy Hungab65b182023-09-06 19:41:47 -07007265 audio_utils::lock_guard l(mutex());
Eric Laurentbfb1b832013-01-07 09:53:42 -08007266 flushHw_l();
7267 } else {
7268 mMixerStatus = MIXER_DRAIN_ALL;
7269 threadLoop_drain();
7270 }
Uday Gupta56604aa2014-05-13 11:19:17 -07007271 if (mUseAsyncWrite) {
7272 ALOG_ASSERT(mCallbackThread != 0);
7273 mCallbackThread->exit();
7274 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007275 PlaybackThread::threadLoop_exit();
7276}
7277
Andy Hungee58e4a2023-07-07 13:47:37 -07007278PlaybackThread::mixer_state OffloadThread::prepareTracks_l(
Andy Hung8d31fd22023-06-26 19:20:57 -07007279 Vector<sp<IAfTrack>>* tracksToRemove
Eric Laurentbfb1b832013-01-07 09:53:42 -08007280)
7281{
Eric Laurentbfb1b832013-01-07 09:53:42 -08007282 size_t count = mActiveTracks.size();
7283
7284 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07007285 bool doHwPause = false;
7286 bool doHwResume = false;
7287
Glenn Kastenc42e9b42016-03-21 11:35:03 -07007288 ALOGV("OffloadThread::prepareTracks_l active tracks %zu", count);
Eric Laurentede6c3b2013-09-19 14:37:46 -07007289
Eric Laurentbfb1b832013-01-07 09:53:42 -08007290 // find out which tracks need to be processed
Andy Hung8d31fd22023-06-26 19:20:57 -07007291 for (const sp<IAfTrack>& t : mActiveTracks) {
7292 IAfTrack* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07007293#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurentbfb1b832013-01-07 09:53:42 -08007294 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07007295#endif
Eric Laurentfd477972013-10-25 18:10:40 -07007296 // Only consider last track started for volume and mixer state control.
7297 // In theory an older track could underrun and restart after the new one starts
7298 // but as we only care about the transition phase between two tracks on a
7299 // direct output, it is not a problem to ignore the underrun case.
Andy Hung8d31fd22023-06-26 19:20:57 -07007300 sp<IAfTrack> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08007301 bool last = l.get() == track;
Eric Laurentfd477972013-10-25 18:10:40 -07007302
Haynes Mathew George7844f672014-01-15 12:32:55 -08007303 if (track->isInvalid()) {
7304 ALOGW("An invalidated track shouldn't be in active list");
7305 tracksToRemove->add(track);
7306 continue;
7307 }
7308
Andy Hung8d31fd22023-06-26 19:20:57 -07007309 if (track->state() == IAfTrackBase::IDLE) {
Haynes Mathew George7844f672014-01-15 12:32:55 -08007310 ALOGW("An idle track shouldn't be in active list");
7311 continue;
7312 }
7313
Kuowei Li23666472021-01-20 10:23:25 +08007314 if (track->isPausePending()) {
7315 track->pauseAck();
7316 // It is possible a track might have been flushed or stopped.
7317 // Other operations such as flush pending might occur on the next prepare.
7318 if (track->isPausing()) {
7319 track->setPaused();
7320 }
7321 // Always perform pause if last, as an immediate flush will change
7322 // the pause state to be no longer isPausing().
Eric Laurentbfb1b832013-01-07 09:53:42 -08007323 if (last) {
Eric Laurent5cff4032015-05-26 13:49:58 -07007324 if (mHwSupportsPause && !mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07007325 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007326 mHwPaused = true;
7327 }
7328 // If we were part way through writing the mixbuffer to
7329 // the HAL we must save this until we resume
7330 // BUG - this will be wrong if a different track is made active,
7331 // in that case we want to discard the pending data in the
7332 // mixbuffer and tell the client to present it again when the
7333 // track is resumed
7334 mPausedWriteLength = mCurrentWriteLength;
7335 mPausedBytesRemaining = mBytesRemaining;
7336 mBytesRemaining = 0; // stop writing
7337 }
7338 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08007339 } else if (track->isFlushPending()) {
Eric Laurente93cc032016-05-05 10:15:10 -07007340 if (track->isStopping_1()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07007341 track->retryCount() = kMaxTrackStopRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07007342 } else {
Andy Hung8d31fd22023-06-26 19:20:57 -07007343 track->retryCount() = kMaxTrackRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07007344 }
Haynes Mathew George7844f672014-01-15 12:32:55 -08007345 track->flushAck();
7346 if (last) {
7347 mFlushPending = true;
7348 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08007349 } else if (track->isResumePending()){
7350 track->resumeAck();
7351 if (last) {
7352 if (mPausedBytesRemaining) {
7353 // Need to continue write that was interrupted
7354 mCurrentWriteLength = mPausedWriteLength;
7355 mBytesRemaining = mPausedBytesRemaining;
7356 mPausedBytesRemaining = 0;
7357 }
7358 if (mHwPaused) {
7359 doHwResume = true;
7360 mHwPaused = false;
7361 // threadLoop_mix() will handle the case that we need to
7362 // resume an interrupted write
7363 }
7364 // enable write to audio HAL
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007365 mSleepTimeUs = 0;
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08007366
Eric Laurent3df841a2016-07-15 15:15:40 -07007367 mLeftVolFloat = mRightVolFloat = -1.0;
7368
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08007369 // Do not handle new data in this iteration even if track->framesReady()
7370 mixerStatus = MIXER_TRACKS_ENABLED;
7371 }
7372 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07007373 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Andy Hungc0691382018-09-12 18:01:57 -07007374 ALOGVV("OffloadThread: track(%d) s=%08x [OK]", track->id(), cblk->mServer);
Andy Hung8d31fd22023-06-26 19:20:57 -07007375 if (track->fillingStatus() == IAfTrack::FS_FILLED) {
7376 track->fillingStatus() = IAfTrack::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07007377 if (last) {
7378 // make sure processVolume_l() will apply new volume even if 0
7379 mLeftVolFloat = mRightVolFloat = -1.0;
7380 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007381 }
7382
7383 if (last) {
Andy Hung8d31fd22023-06-26 19:20:57 -07007384 sp<IAfTrack> previousTrack = mPreviousTrack.promote();
Eric Laurentd7e59222013-11-15 12:02:28 -08007385 if (previousTrack != 0) {
7386 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08007387 // Flush any data still being written from last track
7388 mBytesRemaining = 0;
7389 if (mPausedBytesRemaining) {
7390 // Last track was paused so we also need to flush saved
7391 // mixbuffer state and invalidate track so that it will
7392 // re-submit that unwritten data when it is next resumed
7393 mPausedBytesRemaining = 0;
7394 // Invalidate is a bit drastic - would be more efficient
7395 // to have a flag to tell client that some of the
7396 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08007397 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08007398 }
7399 // flush data already sent to the DSP if changing audio session as audio
7400 // comes from a different source. Also invalidate previous track to force a
7401 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08007402 if (previousTrack->sessionId() != track->sessionId()) {
7403 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08007404 }
7405 }
7406 }
7407 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007408 // reset retry count
Eric Laurente93cc032016-05-05 10:15:10 -07007409 if (track->isStopping_1()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07007410 track->retryCount() = kMaxTrackStopRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07007411 } else {
Andy Hung8d31fd22023-06-26 19:20:57 -07007412 track->retryCount() = kMaxTrackRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07007413 }
Eric Laurent5850c4c2016-11-10 13:04:31 -08007414 mActiveTrack = t;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007415 mixerStatus = MIXER_TRACKS_READY;
7416 }
7417 } else {
Andy Hungc0691382018-09-12 18:01:57 -07007418 ALOGVV("OffloadThread: track(%d) s=%08x [NOT READY]", track->id(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007419 if (track->isStopping_1()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07007420 if (--(track->retryCount()) <= 0) {
Eric Laurente93cc032016-05-05 10:15:10 -07007421 // Hardware buffer can hold a large amount of audio so we must
7422 // wait for all current track's data to drain before we say
7423 // that the track is stopped.
7424 if (mBytesRemaining == 0) {
7425 // Only start draining when all data in mixbuffer
7426 // has been written
7427 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
Andy Hung8d31fd22023-06-26 19:20:57 -07007428 track->setState(IAfTrackBase::STOPPING_2);
7429 // so presentation completes after
Eric Laurente93cc032016-05-05 10:15:10 -07007430 // drain do not drain if no data was ever sent to HAL (mStandby == true)
7431 if (last && !mStandby) {
7432 // do not modify drain sequence if we are already draining. This happens
7433 // when resuming from pause after drain.
7434 if ((mDrainSequence & 1) == 0) {
7435 mSleepTimeUs = 0;
7436 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
7437 mixerStatus = MIXER_DRAIN_TRACK;
7438 mDrainSequence += 2;
7439 }
7440 if (mHwPaused) {
7441 // It is possible to move from PAUSED to STOPPING_1 without
7442 // a resume so we must ensure hardware is running
7443 doHwResume = true;
7444 mHwPaused = false;
7445 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007446 }
7447 }
Eric Laurente93cc032016-05-05 10:15:10 -07007448 } else if (last) {
Andy Hung8d31fd22023-06-26 19:20:57 -07007449 ALOGV("stopping1 underrun retries left %d", track->retryCount());
Eric Laurente93cc032016-05-05 10:15:10 -07007450 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007451 }
7452 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07007453 // Drain has completed or we are in standby, signal presentation complete
7454 if (!(mDrainSequence & 1) || !last || mStandby) {
Andy Hung8d31fd22023-06-26 19:20:57 -07007455 track->setState(IAfTrackBase::STOPPED);
Atneya Nair0cae0432022-05-10 18:12:12 -04007456 mOutput->presentationComplete();
7457 track->presentationComplete(latency_l()); // always returns true
Eric Laurentbfb1b832013-01-07 09:53:42 -08007458 track->reset();
7459 tracksToRemove->add(track);
Dean Wheatley12473e92021-03-18 23:00:55 +11007460 // OFFLOADED stop resets frame counts.
Andy Hungf3234512018-07-03 14:51:47 -07007461 if (!mUseAsyncWrite) {
7462 // If we don't get explicit drain notification we must
7463 // register discontinuity regardless of whether this is
7464 // the previous (!last) or the upcoming (last) track
7465 // to avoid skipping the discontinuity.
Dean Wheatley12473e92021-03-18 23:00:55 +11007466 mTimestampVerifier.discontinuity(
7467 mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Andy Hungf3234512018-07-03 14:51:47 -07007468 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007469 }
7470 } else {
7471 // No buffers for this track. Give it a few chances to
7472 // fill a buffer, then remove it from active list.
Brian Lindahl65e90012022-07-27 18:01:07 +02007473 bool isTimestampAdvancing = mIsTimestampAdvancing.check(mOutput);
Gareth Fennb18c1a32022-10-05 13:42:36 -07007474 if (!isTunerStream() // tuner streams remain active in underrun
Andy Hung8d31fd22023-06-26 19:20:57 -07007475 && --(track->retryCount()) <= 0) {
Brian Lindahl65e90012022-07-27 18:01:07 +02007476 if (isTimestampAdvancing) { // HAL is still playing audio, give us more time.
Andy Hung8d31fd22023-06-26 19:20:57 -07007477 track->retryCount() = kMaxTrackRetriesOffload;
Andy Hungf8044752016-07-27 14:58:11 -07007478 } else {
Andy Hungc0691382018-09-12 18:01:57 -07007479 ALOGV("OffloadThread: BUFFER TIMEOUT: remove track(%d) from active list",
7480 track->id());
Andy Hungf8044752016-07-27 14:58:11 -07007481 tracksToRemove->add(track);
Glenn Kastend3bb6452016-12-05 18:14:37 -08007482 // tell client process that the track was disabled because of underrun;
Andy Hungf8044752016-07-27 14:58:11 -07007483 // it will then automatically call start() when data is available
7484 track->disable();
7485 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007486 } else if (last){
7487 mixerStatus = MIXER_TRACKS_ENABLED;
7488 }
7489 }
7490 }
7491 // compute volume for this track
Wenfeng Sun79458332019-05-29 20:12:43 +08007492 if (track->isReady()) { // check ready to prevent premature start.
7493 processVolume_l(track, last);
7494 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007495 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007496
Eric Laurentea0fade2013-10-04 16:23:48 -07007497 // make sure the pause/flush/resume sequence is executed in the right order.
7498 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
7499 // before flush and then resume HW. This can happen in case of pause/flush/resume
7500 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07007501 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007502 status_t result = mOutput->stream->pause();
7503 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Gareth Fenncd1e1622022-10-05 11:45:45 -07007504 doHwResume = !doHwPause; // resume if pause is due to flush.
Eric Laurent972a1732013-09-04 09:42:59 -07007505 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007506 if (mFlushPending) {
7507 flushHw_l();
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007508 }
Eric Laurentfd477972013-10-25 18:10:40 -07007509 if (!mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007510 status_t result = mOutput->stream->resume();
7511 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07007512 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007513
Eric Laurentbfb1b832013-01-07 09:53:42 -08007514 // remove all the tracks that need to be...
7515 removeTracks_l(*tracksToRemove);
7516
7517 return mixerStatus;
7518}
7519
Eric Laurentbfb1b832013-01-07 09:53:42 -08007520// must be called with thread mutex locked
Andy Hungee58e4a2023-07-07 13:47:37 -07007521bool OffloadThread::waitingAsyncCallback_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007522{
Eric Laurent3b4529e2013-09-05 18:09:19 -07007523 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
7524 mWriteAckSequence, mDrainSequence);
7525 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08007526 return true;
7527 }
7528 return false;
7529}
7530
Andy Hungee58e4a2023-07-07 13:47:37 -07007531bool OffloadThread::waitingAsyncCallback()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007532{
Andy Hung972bec12023-08-31 16:13:39 -07007533 audio_utils::lock_guard _l(mutex());
Eric Laurentbfb1b832013-01-07 09:53:42 -08007534 return waitingAsyncCallback_l();
7535}
7536
Andy Hungee58e4a2023-07-07 13:47:37 -07007537void OffloadThread::flushHw_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007538{
Eric Laurente659ef42014-09-29 13:06:46 -07007539 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08007540 // Flush anything still waiting in the mixbuffer
7541 mCurrentWriteLength = 0;
7542 mBytesRemaining = 0;
7543 mPausedWriteLength = 0;
7544 mPausedBytesRemaining = 0;
Eric Laurent3eaf66b2016-04-01 14:44:17 -07007545 // reset bytes written count to reflect that DSP buffers are empty after flush.
7546 mBytesWritten = 0;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08007547
Eric Laurentbfb1b832013-01-07 09:53:42 -08007548 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07007549 // discard any pending drain or write ack by incrementing sequence
7550 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
7551 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007552 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07007553 mCallbackThread->setWriteBlocked(mWriteAckSequence);
7554 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007555 }
7556}
7557
Andy Hungee58e4a2023-07-07 13:47:37 -07007558void OffloadThread::invalidateTracks(audio_stream_type_t streamType)
Haynes Mathew George05317d22016-05-03 16:34:26 -07007559{
Andy Hung972bec12023-08-31 16:13:39 -07007560 audio_utils::lock_guard _l(mutex());
Eric Laurent13084622016-05-17 10:51:49 -07007561 if (PlaybackThread::invalidateTracks_l(streamType)) {
7562 mFlushPending = true;
7563 }
Haynes Mathew George05317d22016-05-03 16:34:26 -07007564}
7565
Andy Hungee58e4a2023-07-07 13:47:37 -07007566void OffloadThread::invalidateTracks(std::set<audio_port_handle_t>& portIds) {
Andy Hung972bec12023-08-31 16:13:39 -07007567 audio_utils::lock_guard _l(mutex());
jiabinc44b3462022-12-08 12:52:31 -08007568 if (PlaybackThread::invalidateTracks_l(portIds)) {
7569 mFlushPending = true;
7570 }
7571}
7572
Eric Laurentbfb1b832013-01-07 09:53:42 -08007573// ----------------------------------------------------------------------------
7574
Andy Hungee58e4a2023-07-07 13:47:37 -07007575/* static */
7576sp<IAfDuplicatingThread> IAfDuplicatingThread::create(
Andy Hung583043b2023-07-17 17:05:00 -07007577 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hungee58e4a2023-07-07 13:47:37 -07007578 IAfPlaybackThread* mainThread, audio_io_handle_t id, bool systemReady) {
Andy Hung583043b2023-07-17 17:05:00 -07007579 return sp<DuplicatingThread>::make(afThreadCallback, mainThread, id, systemReady);
Andy Hungee58e4a2023-07-07 13:47:37 -07007580}
7581
Andy Hung583043b2023-07-17 17:05:00 -07007582DuplicatingThread::DuplicatingThread(const sp<IAfThreadCallback>& afThreadCallback,
Andy Hung87c693c2023-07-06 20:56:16 -07007583 IAfPlaybackThread* mainThread, audio_io_handle_t id, bool systemReady)
Andy Hung583043b2023-07-17 17:05:00 -07007584 : MixerThread(afThreadCallback, mainThread->getOutput(), id,
Eric Laurent72e3f392015-05-20 14:43:50 -07007585 systemReady, DUPLICATING),
Eric Laurent81784c32012-11-19 14:55:58 -08007586 mWaitTimeMs(UINT_MAX)
7587{
7588 addOutputTrack(mainThread);
7589}
7590
Andy Hungee58e4a2023-07-07 13:47:37 -07007591DuplicatingThread::~DuplicatingThread()
Eric Laurent81784c32012-11-19 14:55:58 -08007592{
7593 for (size_t i = 0; i < mOutputTracks.size(); i++) {
7594 mOutputTracks[i]->destroy();
7595 }
7596}
7597
Andy Hungee58e4a2023-07-07 13:47:37 -07007598void DuplicatingThread::threadLoop_mix()
Eric Laurent81784c32012-11-19 14:55:58 -08007599{
7600 // mix buffers...
Andy Hung920f6572022-10-06 12:09:49 -07007601 if (outputsReady()) {
Glenn Kastend79072e2016-01-06 08:41:20 -08007602 mAudioMixer->process();
Eric Laurent81784c32012-11-19 14:55:58 -08007603 } else {
Eric Laurent02b57082014-11-07 17:28:28 -08007604 if (mMixerBufferValid) {
7605 memset(mMixerBuffer, 0, mMixerBufferSize);
7606 } else {
7607 memset(mSinkBuffer, 0, mSinkBufferSize);
7608 }
Eric Laurent81784c32012-11-19 14:55:58 -08007609 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007610 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007611 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08007612 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007613 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08007614}
7615
Andy Hungee58e4a2023-07-07 13:47:37 -07007616void DuplicatingThread::threadLoop_sleepTime()
Eric Laurent81784c32012-11-19 14:55:58 -08007617{
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007618 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08007619 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007620 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007621 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007622 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007623 }
7624 } else if (mBytesWritten != 0) {
7625 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
7626 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08007627 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08007628 } else {
7629 // flush remaining overflow buffers in output tracks
7630 writeFrames = 0;
7631 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007632 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007633 }
7634}
7635
Andy Hungee58e4a2023-07-07 13:47:37 -07007636ssize_t DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08007637{
7638 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hung1c86ebe2018-05-29 20:29:08 -07007639 const ssize_t actualWritten = outputTracks[i]->write(mSinkBuffer, writeFrames);
7640
7641 // Consider the first OutputTrack for timestamp and frame counting.
7642
7643 // The threadLoop() generally assumes writing a full sink buffer size at a time.
7644 // Here, we correct for writeFrames of 0 (a stop) or underruns because
7645 // we always claim success.
7646 if (i == 0) {
7647 const ssize_t correction = mSinkBufferSize / mFrameSize - actualWritten;
7648 ALOGD_IF(correction != 0 && writeFrames != 0,
7649 "%s: writeFrames:%u actualWritten:%zd correction:%zd mFramesWritten:%lld",
7650 __func__, writeFrames, actualWritten, correction, (long long)mFramesWritten);
7651 mFramesWritten -= correction;
7652 }
7653
7654 // TODO: Report correction for the other output tracks and show in the dump.
Eric Laurent81784c32012-11-19 14:55:58 -08007655 }
Andy Hungcf10d742020-04-28 15:38:24 -07007656 if (mStandby) {
7657 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07007658 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -07007659 mStandby = false;
7660 }
Andy Hung25c2dac2014-02-27 14:56:00 -08007661 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08007662}
7663
Andy Hungee58e4a2023-07-07 13:47:37 -07007664void DuplicatingThread::threadLoop_standby()
Eric Laurent81784c32012-11-19 14:55:58 -08007665{
7666 // DuplicatingThread implements standby by stopping all tracks
7667 for (size_t i = 0; i < outputTracks.size(); i++) {
7668 outputTracks[i]->stop();
7669 }
7670}
7671
Andy Hung8a5abfd2023-12-07 19:35:12 -08007672void DuplicatingThread::threadLoop_exit()
7673{
7674 // Prevent calling the OutputTrack dtor in the DuplicatingThread dtor
7675 // where other mutexes (i.e. AudioPolicyService_Mutex) may be held.
7676 // Do so here in the threadLoop_exit().
7677
7678 SortedVector <sp<IAfOutputTrack>> localTracks;
7679 {
7680 audio_utils::lock_guard l(mutex());
7681 localTracks = std::move(mOutputTracks);
7682 mOutputTracks.clear();
7683 }
7684 localTracks.clear();
7685 outputTracks.clear();
7686 PlaybackThread::threadLoop_exit();
7687}
7688
Andy Hungee58e4a2023-07-07 13:47:37 -07007689void DuplicatingThread::dumpInternals_l(int fd, const Vector<String16>& args)
Andy Hung1bc088a2018-02-09 15:57:31 -08007690{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07007691 MixerThread::dumpInternals_l(fd, args);
Andy Hung1bc088a2018-02-09 15:57:31 -08007692
7693 std::stringstream ss;
7694 const size_t numTracks = mOutputTracks.size();
7695 ss << " " << numTracks << " OutputTracks";
7696 if (numTracks > 0) {
7697 ss << ":";
7698 for (const auto &track : mOutputTracks) {
Andy Hung87c693c2023-07-06 20:56:16 -07007699 const auto thread = track->thread().promote();
Andy Hungc0691382018-09-12 18:01:57 -07007700 ss << " (" << track->id() << " : ";
Andy Hung1bc088a2018-02-09 15:57:31 -08007701 if (thread.get() != nullptr) {
7702 ss << thread.get() << ", " << thread->id();
7703 } else {
7704 ss << "null";
7705 }
7706 ss << ")";
7707 }
7708 }
7709 ss << "\n";
7710 std::string result = ss.str();
7711 write(fd, result.c_str(), result.size());
7712}
7713
Andy Hungee58e4a2023-07-07 13:47:37 -07007714void DuplicatingThread::saveOutputTracks()
Eric Laurent81784c32012-11-19 14:55:58 -08007715{
7716 outputTracks = mOutputTracks;
7717}
7718
Andy Hungee58e4a2023-07-07 13:47:37 -07007719void DuplicatingThread::clearOutputTracks()
Eric Laurent81784c32012-11-19 14:55:58 -08007720{
7721 outputTracks.clear();
7722}
7723
Andy Hungee58e4a2023-07-07 13:47:37 -07007724void DuplicatingThread::addOutputTrack(IAfPlaybackThread* thread)
Eric Laurent81784c32012-11-19 14:55:58 -08007725{
Andy Hung972bec12023-08-31 16:13:39 -07007726 audio_utils::lock_guard _l(mutex());
Andy Hungc25b84a2015-01-14 19:04:10 -08007727 // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
7728 // Adjust for thread->sampleRate() to determine minimum buffer frame count.
7729 // Then triple buffer because Threads do not run synchronously and may not be clock locked.
7730 const size_t frameCount =
7731 3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
7732 // TODO: Consider asynchronous sample rate conversion to handle clock disparity
7733 // from different OutputTracks and their associated MixerThreads (e.g. one may
7734 // nearly empty and the other may be dropping data).
7735
Svet Ganov33761132021-05-13 22:51:08 +00007736 // TODO b/182392769: use attribution source util, move to server edge
7737 AttributionSourceState attributionSource = AttributionSourceState();
7738 attributionSource.uid = VALUE_OR_FATAL(legacy2aidl_uid_t_int32_t(
Philip P. Moltmannbda45752020-07-17 16:41:18 -07007739 IPCThreadState::self()->getCallingUid()));
Svet Ganov33761132021-05-13 22:51:08 +00007740 attributionSource.pid = VALUE_OR_FATAL(legacy2aidl_pid_t_int32_t(
Philip P. Moltmannbda45752020-07-17 16:41:18 -07007741 IPCThreadState::self()->getCallingPid()));
Svet Ganov33761132021-05-13 22:51:08 +00007742 attributionSource.token = sp<BBinder>::make();
Andy Hung8d31fd22023-06-26 19:20:57 -07007743 sp<IAfOutputTrack> outputTrack = IAfOutputTrack::create(thread,
Eric Laurent81784c32012-11-19 14:55:58 -08007744 this,
7745 mSampleRate,
Andy Hungc25b84a2015-01-14 19:04:10 -08007746 mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08007747 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08007748 frameCount,
Svet Ganov33761132021-05-13 22:51:08 +00007749 attributionSource);
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07007750 status_t status = outputTrack != 0 ? outputTrack->initCheck() : (status_t) NO_MEMORY;
7751 if (status != NO_ERROR) {
7752 ALOGE("addOutputTrack() initCheck failed %d", status);
7753 return;
Eric Laurent81784c32012-11-19 14:55:58 -08007754 }
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07007755 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
7756 mOutputTracks.add(outputTrack);
7757 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
7758 updateWaitTime_l();
Eric Laurent81784c32012-11-19 14:55:58 -08007759}
7760
Andy Hungee58e4a2023-07-07 13:47:37 -07007761void DuplicatingThread::removeOutputTrack(IAfPlaybackThread* thread)
Eric Laurent81784c32012-11-19 14:55:58 -08007762{
Andy Hung972bec12023-08-31 16:13:39 -07007763 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08007764 for (size_t i = 0; i < mOutputTracks.size(); i++) {
7765 if (mOutputTracks[i]->thread() == thread) {
7766 mOutputTracks[i]->destroy();
7767 mOutputTracks.removeAt(i);
7768 updateWaitTime_l();
Andy Hung8d672e02023-09-15 18:19:28 -07007769 // NO_THREAD_SAFETY_ANALYSIS
7770 // Lambda workaround: as thread != this
7771 // we can safely call the remote thread getOutput.
7772 const bool equalOutput =
7773 [&](){ return thread->getOutput() == mOutput; }();
7774 if (equalOutput) {
7775 mOutput = nullptr;
Eric Laurentf6870ae2015-05-08 10:50:03 -07007776 }
Eric Laurent81784c32012-11-19 14:55:58 -08007777 return;
7778 }
7779 }
Eric Laurentf6870ae2015-05-08 10:50:03 -07007780 ALOGV("removeOutputTrack(): unknown thread: %p", thread);
Eric Laurent81784c32012-11-19 14:55:58 -08007781}
7782
Andy Hungc5007f82023-08-29 14:26:09 -07007783// caller must hold mutex()
Andy Hungee58e4a2023-07-07 13:47:37 -07007784void DuplicatingThread::updateWaitTime_l()
Eric Laurent81784c32012-11-19 14:55:58 -08007785{
7786 mWaitTimeMs = UINT_MAX;
7787 for (size_t i = 0; i < mOutputTracks.size(); i++) {
Andy Hung87c693c2023-07-06 20:56:16 -07007788 const auto strong = mOutputTracks[i]->thread().promote();
Eric Laurent81784c32012-11-19 14:55:58 -08007789 if (strong != 0) {
7790 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
7791 if (waitTimeMs < mWaitTimeMs) {
7792 mWaitTimeMs = waitTimeMs;
7793 }
7794 }
7795 }
7796}
7797
Andy Hungee58e4a2023-07-07 13:47:37 -07007798bool DuplicatingThread::outputsReady()
Eric Laurent81784c32012-11-19 14:55:58 -08007799{
7800 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hung87c693c2023-07-06 20:56:16 -07007801 const auto thread = outputTracks[i]->thread().promote();
Eric Laurent81784c32012-11-19 14:55:58 -08007802 if (thread == 0) {
7803 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
7804 outputTracks[i].get());
7805 return false;
7806 }
Andy Hung87c693c2023-07-06 20:56:16 -07007807 IAfPlaybackThread* const playbackThread = thread->asIAfPlaybackThread().get();
Eric Laurent81784c32012-11-19 14:55:58 -08007808 // see note at standby() declaration
Andy Hung440901d2023-06-29 21:19:25 -07007809 if (playbackThread->inStandby() && !playbackThread->isSuspended()) {
Eric Laurent81784c32012-11-19 14:55:58 -08007810 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
7811 thread.get());
7812 return false;
7813 }
7814 }
7815 return true;
7816}
7817
Andy Hungee58e4a2023-07-07 13:47:37 -07007818void DuplicatingThread::sendMetadataToBackend_l(
Kevin Rocard12381092018-04-11 09:19:59 -07007819 const StreamOutHalInterface::SourceMetadata& metadata)
Kevin Rocard069c2712018-03-29 19:09:14 -07007820{
Kevin Rocard12381092018-04-11 09:19:59 -07007821 for (auto& outputTrack : outputTracks) { // not mOutputTracks
7822 outputTrack->setMetadatas(metadata.tracks);
7823 }
Kevin Rocard069c2712018-03-29 19:09:14 -07007824}
7825
Andy Hungee58e4a2023-07-07 13:47:37 -07007826uint32_t DuplicatingThread::activeSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08007827{
Andy Hung7a6a0f02023-11-29 13:42:08 -08007828 // return half the wait time in microseconds.
7829 return std::min(mWaitTimeMs * 500ULL, (unsigned long long)UINT32_MAX); // prevent overflow.
Eric Laurent81784c32012-11-19 14:55:58 -08007830}
7831
Andy Hungee58e4a2023-07-07 13:47:37 -07007832void DuplicatingThread::cacheParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08007833{
7834 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
7835 updateWaitTime_l();
7836
7837 MixerThread::cacheParameters_l();
7838}
7839
Eric Laurentb3f315a2021-07-13 15:09:05 +02007840// ----------------------------------------------------------------------------
7841
Andy Hungee58e4a2023-07-07 13:47:37 -07007842/* static */
7843sp<IAfPlaybackThread> IAfPlaybackThread::createSpatializerThread(
Andy Hung583043b2023-07-17 17:05:00 -07007844 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hungee58e4a2023-07-07 13:47:37 -07007845 AudioStreamOut* output,
7846 audio_io_handle_t id,
7847 bool systemReady,
7848 audio_config_base_t* mixerConfig) {
Andy Hung583043b2023-07-17 17:05:00 -07007849 return sp<SpatializerThread>::make(afThreadCallback, output, id, systemReady, mixerConfig);
Andy Hungee58e4a2023-07-07 13:47:37 -07007850}
7851
Andy Hung583043b2023-07-17 17:05:00 -07007852SpatializerThread::SpatializerThread(const sp<IAfThreadCallback>& afThreadCallback,
Eric Laurentb3f315a2021-07-13 15:09:05 +02007853 AudioStreamOut* output,
7854 audio_io_handle_t id,
7855 bool systemReady,
7856 audio_config_base_t *mixerConfig)
Andy Hung583043b2023-07-17 17:05:00 -07007857 : MixerThread(afThreadCallback, output, id, systemReady, SPATIALIZER, mixerConfig)
Eric Laurentb3f315a2021-07-13 15:09:05 +02007858{
7859}
7860
Andy Hungee58e4a2023-07-07 13:47:37 -07007861void SpatializerThread::setHalLatencyMode_l() {
Eric Laurent68a40a82022-05-03 18:15:04 +02007862 // if mSupportedLatencyModes is empty, the HAL stream does not support
7863 // latency mode control and we can exit.
7864 if (mSupportedLatencyModes.empty()) {
7865 return;
7866 }
7867 audio_latency_mode_t latencyMode = AUDIO_LATENCY_MODE_FREE;
7868 if (mSupportedLatencyModes.size() == 1) {
7869 // If the HAL only support one latency mode currently, confirm the choice
7870 latencyMode = mSupportedLatencyModes[0];
7871 } else if (mSupportedLatencyModes.size() > 1) {
7872 // Request low latency if:
7873 // - The low latency mode is requested by the spatializer controller
7874 // (mRequestedLatencyMode = AUDIO_LATENCY_MODE_LOW)
7875 // AND
7876 // - At least one active track is spatialized
7877 bool hasSpatializedActiveTrack = false;
7878 for (const auto& track : mActiveTracks) {
7879 if (track->isSpatialized()) {
7880 hasSpatializedActiveTrack = true;
7881 break;
7882 }
7883 }
7884 if (hasSpatializedActiveTrack && mRequestedLatencyMode == AUDIO_LATENCY_MODE_LOW) {
7885 latencyMode = AUDIO_LATENCY_MODE_LOW;
7886 }
7887 }
7888
7889 if (latencyMode != mSetLatencyMode) {
7890 status_t status = mOutput->stream->setLatencyMode(latencyMode);
Andy Hung4bd53e72022-11-17 17:21:45 -08007891 ALOGD("%s: thread(%d) setLatencyMode(%s) returned %d",
7892 __func__, mId, toString(latencyMode).c_str(), status);
Eric Laurent68a40a82022-05-03 18:15:04 +02007893 if (status == NO_ERROR) {
7894 mSetLatencyMode = latencyMode;
7895 }
7896 }
7897}
7898
Andy Hungee58e4a2023-07-07 13:47:37 -07007899status_t SpatializerThread::setRequestedLatencyMode(audio_latency_mode_t mode) {
Eric Laurent68a40a82022-05-03 18:15:04 +02007900 if (mode != AUDIO_LATENCY_MODE_LOW && mode != AUDIO_LATENCY_MODE_FREE) {
7901 return BAD_VALUE;
7902 }
Andy Hung972bec12023-08-31 16:13:39 -07007903 audio_utils::lock_guard _l(mutex());
Eric Laurent68a40a82022-05-03 18:15:04 +02007904 mRequestedLatencyMode = mode;
7905 return NO_ERROR;
7906}
7907
Andy Hungee58e4a2023-07-07 13:47:37 -07007908void SpatializerThread::checkOutputStageEffects()
Andy Hung972bec12023-08-31 16:13:39 -07007909NO_THREAD_SAFETY_ANALYSIS
7910// 'createEffect_l' requires holding mutex 'AudioFlinger_Mutex' exclusively
Eric Laurentb3f315a2021-07-13 15:09:05 +02007911{
7912 bool hasVirtualizer = false;
7913 bool hasDownMixer = false;
Andy Hung116bc262023-06-20 18:56:17 -07007914 sp<IAfEffectHandle> finalDownMixer;
Eric Laurentb3f315a2021-07-13 15:09:05 +02007915 {
Andy Hung972bec12023-08-31 16:13:39 -07007916 audio_utils::lock_guard _l(mutex());
Andy Hung116bc262023-06-20 18:56:17 -07007917 sp<IAfEffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_STAGE);
Eric Laurentb3f315a2021-07-13 15:09:05 +02007918 if (chain != 0) {
Eric Laurent1c5e2e32021-08-18 18:50:28 +02007919 hasVirtualizer = chain->getEffectFromType_l(FX_IID_SPATIALIZER) != nullptr;
Eric Laurentb3f315a2021-07-13 15:09:05 +02007920 hasDownMixer = chain->getEffectFromType_l(EFFECT_UIID_DOWNMIX) != nullptr;
7921 }
7922
7923 finalDownMixer = mFinalDownMixer;
7924 mFinalDownMixer.clear();
7925 }
7926
7927 if (hasVirtualizer) {
7928 if (finalDownMixer != nullptr) {
7929 int32_t ret;
Andy Hung116bc262023-06-20 18:56:17 -07007930 finalDownMixer->asIEffect()->disable(&ret);
Eric Laurentb3f315a2021-07-13 15:09:05 +02007931 }
7932 finalDownMixer.clear();
7933 } else if (!hasDownMixer) {
7934 std::vector<effect_descriptor_t> descriptors;
Andy Hung583043b2023-07-17 17:05:00 -07007935 status_t status = mAfThreadCallback->getEffectsFactoryHal()->getDescriptors(
Eric Laurentb3f315a2021-07-13 15:09:05 +02007936 EFFECT_UIID_DOWNMIX, &descriptors);
7937 if (status != NO_ERROR) {
7938 return;
7939 }
7940 ALOG_ASSERT(!descriptors.empty(),
7941 "%s getDescriptors() returned no error but empty list", __func__);
7942
7943 finalDownMixer = createEffect_l(nullptr /*client*/, nullptr /*effectClient*/,
7944 0 /*priority*/, AUDIO_SESSION_OUTPUT_STAGE, &descriptors[0], nullptr /*enabled*/,
Eric Laurentde8caf42021-08-11 17:19:25 +02007945 &status, false /*pinned*/, false /*probe*/, false /*notifyFramesProcessed*/);
Eric Laurentb3f315a2021-07-13 15:09:05 +02007946
7947 if (finalDownMixer == nullptr || (status != NO_ERROR && status != ALREADY_EXISTS)) {
7948 ALOGW("%s error creating downmixer %d", __func__, status);
7949 finalDownMixer.clear();
7950 } else {
7951 int32_t ret;
Andy Hung116bc262023-06-20 18:56:17 -07007952 finalDownMixer->asIEffect()->enable(&ret);
Eric Laurentb3f315a2021-07-13 15:09:05 +02007953 }
7954 }
7955
7956 {
Andy Hung972bec12023-08-31 16:13:39 -07007957 audio_utils::lock_guard _l(mutex());
Eric Laurentb3f315a2021-07-13 15:09:05 +02007958 mFinalDownMixer = finalDownMixer;
7959 }
7960}
7961
Andy Hunge2514462023-12-06 14:59:24 -08007962void SpatializerThread::threadLoop_exit()
7963{
7964 // The Spatializer EffectHandle must be released on the PlaybackThread
7965 // threadLoop() to prevent lock inversion in the SpatializerThread dtor.
7966 mFinalDownMixer.clear();
7967
7968 PlaybackThread::threadLoop_exit();
7969}
7970
Eric Laurent81784c32012-11-19 14:55:58 -08007971// ----------------------------------------------------------------------------
7972// Record
7973// ----------------------------------------------------------------------------
7974
Andy Hung583043b2023-07-17 17:05:00 -07007975sp<IAfRecordThread> IAfRecordThread::create(const sp<IAfThreadCallback>& afThreadCallback,
Andy Hung87c693c2023-07-06 20:56:16 -07007976 AudioStreamIn* input,
7977 audio_io_handle_t id,
7978 bool systemReady) {
Andy Hung583043b2023-07-17 17:05:00 -07007979 return sp<RecordThread>::make(afThreadCallback, input, id, systemReady);
Andy Hung87c693c2023-07-06 20:56:16 -07007980}
7981
Andy Hung583043b2023-07-17 17:05:00 -07007982RecordThread::RecordThread(const sp<IAfThreadCallback>& afThreadCallback,
Eric Laurent81784c32012-11-19 14:55:58 -08007983 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08007984 audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -07007985 bool systemReady
Glenn Kasten46909e72013-02-26 09:20:22 -08007986 ) :
Andy Hung583043b2023-07-17 17:05:00 -07007987 ThreadBase(afThreadCallback, id, RECORD, systemReady, false /* isOut */),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007988 mInput(input),
Mikhail Naganov2534b382019-09-25 13:05:02 -07007989 mSource(mInput),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007990 mActiveTracks(&this->mLocalLog),
7991 mRsmpInBuffer(NULL),
Glenn Kasten1b291842016-07-18 14:55:21 -07007992 // mRsmpInFrames, mRsmpInFramesP2, and mRsmpInFramesOA are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007993 mRsmpInRear(0)
Glenn Kastenb880f5e2014-05-07 08:43:45 -07007994 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
7995 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007996 // mFastCapture below
7997 , mFastCaptureFutex(0)
7998 // mInputSource
7999 // mPipeSink
8000 // mPipeSource
8001 , mPipeFramesP2(0)
8002 // mPipeMemory
8003 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07008004 , mFastTrackAvail(false)
Eric Laurentd8365c52017-07-16 15:27:05 -07008005 , mBtNrecSuspended(false)
Eric Laurent81784c32012-11-19 14:55:58 -08008006{
Glenn Kastend7dca052015-03-05 16:05:54 -08008007 snprintf(mThreadName, kThreadNameLength, "AudioIn_%X", id);
Andy Hung583043b2023-07-17 17:05:00 -07008008 mNBLogWriter = afThreadCallback->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08008009
George Burgess IVa8f90c12020-05-14 11:27:19 -07008010 if (mInput->audioHwDev != nullptr) {
Andy Hungc8fddf32018-08-08 18:32:37 -07008011 mIsMsdDevice = strcmp(
8012 mInput->audioHwDev->moduleName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0;
8013 }
8014
Glenn Kastendeca2ae2014-02-07 10:25:56 -08008015 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008016
Andy Hungc8fddf32018-08-08 18:32:37 -07008017 // TODO: We may also match on address as well as device type for
8018 // AUDIO_DEVICE_IN_BUS, AUDIO_DEVICE_IN_BLUETOOTH_A2DP, AUDIO_DEVICE_IN_REMOTE_SUBMIX
jiabinc52b1ff2019-10-31 17:20:42 -07008019 // TODO: This property should be ensure that only contains one single device type.
8020 mTimestampCorrectedDevice = (audio_devices_t)property_get_int64(
8021 "audio.timestamp.corrected_input_device",
Andy Hungc8fddf32018-08-08 18:32:37 -07008022 (int64_t)(mIsMsdDevice ? AUDIO_DEVICE_IN_BUS // turn on by default for MSD
8023 : AUDIO_DEVICE_NONE));
8024
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008025 // create an NBAIO source for the HAL input stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07008026 mInputSource = new AudioStreamInSource(input->stream);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008027 size_t numCounterOffers = 0;
8028 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07008029#if !LOG_NDEBUG
Jing Mike537412f2023-03-12 11:01:47 +08008030 [[maybe_unused]] ssize_t index =
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07008031#else
8032 (void)
8033#endif
8034 mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008035 ALOG_ASSERT(index == 0);
8036
8037 // initialize fast capture depending on configuration
8038 bool initFastCapture;
8039 switch (kUseFastCapture) {
8040 case FastCapture_Never:
8041 initFastCapture = false;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008042 ALOGV("%p kUseFastCapture = Never, initFastCapture = false", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008043 break;
8044 case FastCapture_Always:
8045 initFastCapture = true;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008046 ALOGV("%p kUseFastCapture = Always, initFastCapture = true", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008047 break;
8048 case FastCapture_Static:
Sampath6fac2332022-12-16 17:34:37 +11008049 initFastCapture = !mIsMsdDevice // Disable fast capture for MSD BUS devices.
Dean Wheatley8e5d9e42023-11-03 12:37:27 +11008050 && audio_is_linear_pcm(mFormat)
Sampath6fac2332022-12-16 17:34:37 +11008051 && (mFrameCount * 1000) / mSampleRate < kMinNormalCaptureBufferSizeMs;
Dean Wheatley8e5d9e42023-11-03 12:37:27 +11008052 ALOGV("%p kUseFastCapture = Static, format = 0x%x, (%lld * 1000) / %u vs %u, "
8053 "initFastCapture = %d, mIsMsdDevice = %d", this, mFormat, (long long)mFrameCount,
8054 mSampleRate, kMinNormalCaptureBufferSizeMs, initFastCapture, mIsMsdDevice);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008055 break;
8056 // case FastCapture_Dynamic:
8057 }
8058
8059 if (initFastCapture) {
Glenn Kastend198b852015-03-16 14:55:53 -07008060 // create a Pipe for FastCapture to write to, and for us and fast tracks to read from
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008061 NBAIO_Format format = mInputSource->format();
Glenn Kasten1b291842016-07-18 14:55:21 -07008062 // quadruple-buffering of 20 ms each; this ensures we can sleep for 20ms in RecordThread
8063 size_t pipeFramesP2 = roundup(4 * FMS_20 * mSampleRate / 1000);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008064 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008065 void *pipeBuffer = nullptr;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008066 const sp<MemoryDealer> roHeap(readOnlyHeap());
8067 sp<IMemory> pipeMemory;
8068 if ((roHeap == 0) ||
8069 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07008070 (pipeBuffer = pipeMemory->unsecurePointer()) == nullptr) {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008071 ALOGE("not enough memory for pipe buffer size=%zu; "
8072 "roHeap=%p, pipeMemory=%p, pipeBuffer=%p; roHeapSize: %lld",
8073 pipeSize, roHeap.get(), pipeMemory.get(), pipeBuffer,
8074 (long long)kRecordThreadReadOnlyHeapSize);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008075 goto failed;
8076 }
8077 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
8078 memset(pipeBuffer, 0, pipeSize);
8079 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
Andy Hung920f6572022-10-06 12:09:49 -07008080 const NBAIO_Format offersFast[1] = {format};
8081 size_t numCounterOffersFast = 0;
Eric Laurent1e28aaa2023-04-16 19:34:23 +02008082 [[maybe_unused]] ssize_t index2 = pipe->negotiate(offersFast, std::size(offersFast),
Andy Hung920f6572022-10-06 12:09:49 -07008083 nullptr /* counterOffers */, numCounterOffersFast);
Eric Laurent1e28aaa2023-04-16 19:34:23 +02008084 ALOG_ASSERT(index2 == 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008085 mPipeSink = pipe;
8086 PipeReader *pipeReader = new PipeReader(*pipe);
Andy Hung920f6572022-10-06 12:09:49 -07008087 numCounterOffersFast = 0;
Eric Laurent1e28aaa2023-04-16 19:34:23 +02008088 index2 = pipeReader->negotiate(offersFast, std::size(offersFast),
Andy Hung920f6572022-10-06 12:09:49 -07008089 nullptr /* counterOffers */, numCounterOffersFast);
Eric Laurent1e28aaa2023-04-16 19:34:23 +02008090 ALOG_ASSERT(index2 == 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008091 mPipeSource = pipeReader;
8092 mPipeFramesP2 = pipeFramesP2;
8093 mPipeMemory = pipeMemory;
8094
8095 // create fast capture
8096 mFastCapture = new FastCapture();
8097 FastCaptureStateQueue *sq = mFastCapture->sq();
8098#ifdef STATE_QUEUE_DUMP
8099 // FIXME
8100#endif
8101 FastCaptureState *state = sq->begin();
8102 state->mCblk = NULL;
8103 state->mInputSource = mInputSource.get();
8104 state->mInputSourceGen++;
8105 state->mPipeSink = pipe;
8106 state->mPipeSinkGen++;
8107 state->mFrameCount = mFrameCount;
8108 state->mCommand = FastCaptureState::COLD_IDLE;
8109 // already done in constructor initialization list
8110 //mFastCaptureFutex = 0;
8111 state->mColdFutexAddr = &mFastCaptureFutex;
8112 state->mColdGen++;
8113 state->mDumpState = &mFastCaptureDumpState;
8114#ifdef TEE_SINK
8115 // FIXME
8116#endif
Andy Hung583043b2023-07-17 17:05:00 -07008117 mFastCaptureNBLogWriter =
8118 afThreadCallback->newWriter_l(kFastCaptureLogSize, "FastCapture");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008119 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
8120 sq->end();
8121 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
8122
8123 // start the fast capture
8124 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
8125 pid_t tid = mFastCapture->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07008126 sendPrioConfigEvent(getpid(), tid, kPriorityFastCapture, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08008127 stream()->setHalThreadPriority(kPriorityFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008128#ifdef AUDIO_WATCHDOG
8129 // FIXME
8130#endif
8131
Glenn Kasten6e6704c2014-07-03 10:20:00 -07008132 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008133 }
Andy Hung8946a282018-04-19 20:04:56 -07008134#ifdef TEE_SINK
8135 mTee.set(mInputSource->format(), NBAIO_Tee::TEE_FLAG_INPUT_THREAD);
8136 mTee.setId(std::string("_") + std::to_string(mId) + "_C");
8137#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008138failed: ;
8139
8140 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08008141}
8142
Andy Hungee58e4a2023-07-07 13:47:37 -07008143RecordThread::~RecordThread()
Eric Laurent81784c32012-11-19 14:55:58 -08008144{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008145 if (mFastCapture != 0) {
8146 FastCaptureStateQueue *sq = mFastCapture->sq();
8147 FastCaptureState *state = sq->begin();
8148 if (state->mCommand == FastCaptureState::COLD_IDLE) {
8149 int32_t old = android_atomic_inc(&mFastCaptureFutex);
8150 if (old == -1) {
8151 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
8152 }
8153 }
8154 state->mCommand = FastCaptureState::EXIT;
8155 sq->end();
8156 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
8157 mFastCapture->join();
8158 mFastCapture.clear();
8159 }
Andy Hung583043b2023-07-17 17:05:00 -07008160 mAfThreadCallback->unregisterWriter(mFastCaptureNBLogWriter);
8161 mAfThreadCallback->unregisterWriter(mNBLogWriter);
Andy Hung57446612015-04-19 23:56:46 -07008162 free(mRsmpInBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08008163}
8164
Andy Hungee58e4a2023-07-07 13:47:37 -07008165void RecordThread::onFirstRef()
Eric Laurent81784c32012-11-19 14:55:58 -08008166{
Glenn Kastend7dca052015-03-05 16:05:54 -08008167 run(mThreadName, PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08008168}
8169
Andy Hungee58e4a2023-07-07 13:47:37 -07008170void RecordThread::preExit()
Eric Laurent555530a2017-02-07 18:17:24 -08008171{
8172 ALOGV(" preExit()");
Andy Hung972bec12023-08-31 16:13:39 -07008173 audio_utils::lock_guard _l(mutex());
Eric Laurent555530a2017-02-07 18:17:24 -08008174 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07008175 sp<IAfRecordTrack> track = mTracks[i];
Eric Laurent555530a2017-02-07 18:17:24 -08008176 track->invalidate();
8177 }
8178 mActiveTracks.clear();
Andy Hungc5007f82023-08-29 14:26:09 -07008179 mStartStopCV.notify_all();
Eric Laurent555530a2017-02-07 18:17:24 -08008180}
8181
Andy Hungee58e4a2023-07-07 13:47:37 -07008182bool RecordThread::threadLoop()
Eric Laurent81784c32012-11-19 14:55:58 -08008183{
Eric Laurent81784c32012-11-19 14:55:58 -08008184 nsecs_t lastWarning = 0;
8185
8186 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08008187
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008188reacquire_wakelock:
Andy Hung8d31fd22023-06-26 19:20:57 -07008189 sp<IAfRecordTrack> activeTrack;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008190 {
Andy Hung972bec12023-08-31 16:13:39 -07008191 audio_utils::lock_guard _l(mutex());
Andy Hungdae27702016-10-31 14:01:16 -07008192 acquireWakeLock_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008193 }
8194
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008195 // used to request a deferred sleep, to be executed later while mutex is unlocked
8196 uint32_t sleepUs = 0;
8197
Andy Hung95c94a22023-10-20 16:41:18 -07008198 // timestamp correction enable is determined under lock, used in processing step.
8199 bool timestampCorrectionEnabled = false;
8200
Andy Hung446f4df2019-02-21 12:26:41 -08008201 int64_t lastLoopCountRead = -2; // never matches "previous" loop, when loopCount = 0.
8202
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008203 // loop while there is work to do
Andy Hung446f4df2019-02-21 12:26:41 -08008204 for (int64_t loopCount = 0;; ++loopCount) { // loopCount used for statistics tracking
Andy Hung116bc262023-06-20 18:56:17 -07008205 Vector<sp<IAfEffectChain>> effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07008206
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008207 // activeTracks accumulates a copy of a subset of mActiveTracks
Andy Hung8d31fd22023-06-26 19:20:57 -07008208 Vector<sp<IAfRecordTrack>> activeTracks;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008209
Glenn Kasten735f45f2014-08-18 15:51:59 -07008210 // reference to the (first and only) active fast track
Andy Hung8d31fd22023-06-26 19:20:57 -07008211 sp<IAfRecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07008212
Glenn Kasten735f45f2014-08-18 15:51:59 -07008213 // reference to a fast track which is about to be removed
Andy Hung8d31fd22023-06-26 19:20:57 -07008214 sp<IAfRecordTrack> fastTrackToRemove;
Glenn Kasten735f45f2014-08-18 15:51:59 -07008215
Eric Laurent33403f02020-05-29 18:35:06 -07008216 bool silenceFastCapture = false;
8217
Andy Hungc5007f82023-08-29 14:26:09 -07008218 { // scope for mutex()
8219 audio_utils::unique_lock _l(mutex());
Eric Laurent000a4192014-01-29 15:17:32 -08008220
Eric Laurent021cf962014-05-13 10:18:14 -07008221 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008222
Eric Laurent000a4192014-01-29 15:17:32 -08008223 // check exitPending here because checkForNewParameters_l() and
Andy Hungc5007f82023-08-29 14:26:09 -07008224 // checkForNewParameters_l() can temporarily release mutex()
Eric Laurent000a4192014-01-29 15:17:32 -08008225 if (exitPending()) {
8226 break;
8227 }
8228
Eric Laurent5c25d562016-07-13 17:17:45 -07008229 // sleep with mutex unlocked
8230 if (sleepUs > 0) {
Glenn Kastenf9715e42016-07-13 14:02:03 -07008231 ATRACE_BEGIN("sleepC");
Andy Hungc5007f82023-08-29 14:26:09 -07008232 (void)mWaitWorkCV.wait_for(_l, std::chrono::microseconds(sleepUs));
Eric Laurent5c25d562016-07-13 17:17:45 -07008233 ATRACE_END();
8234 sleepUs = 0;
8235 continue;
8236 }
8237
Glenn Kasten2b806402013-11-20 16:37:38 -08008238 // if no active track(s), then standby and release wakelock
8239 size_t size = mActiveTracks.size();
8240 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07008241 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07008242 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08008243 releaseWakeLock_l();
8244 ALOGV("RecordThread: loop stopping");
8245 // go to sleep
Andy Hungc5007f82023-08-29 14:26:09 -07008246 mWaitWorkCV.wait(_l);
Eric Laurent81784c32012-11-19 14:55:58 -08008247 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008248 goto reacquire_wakelock;
8249 }
8250
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008251 bool doBroadcast = false;
Eric Laurent5c25d562016-07-13 17:17:45 -07008252 bool allStopped = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008253 for (size_t i = 0; i < size; ) {
Glenn Kasten9e982352013-08-14 14:39:50 -07008254
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008255 activeTrack = mActiveTracks[i];
8256 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07008257 if (activeTrack->isFastTrack()) {
8258 ALOG_ASSERT(fastTrackToRemove == 0);
8259 fastTrackToRemove = activeTrack;
8260 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008261 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08008262 mActiveTracks.remove(activeTrack);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008263 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07008264 continue;
8265 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008266
Andy Hung8d31fd22023-06-26 19:20:57 -07008267 IAfTrackBase::track_state activeTrackState = activeTrack->state();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008268 switch (activeTrackState) {
8269
Andy Hung8d31fd22023-06-26 19:20:57 -07008270 case IAfTrackBase::PAUSING:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008271 mActiveTracks.remove(activeTrack);
Andy Hung8d31fd22023-06-26 19:20:57 -07008272 activeTrack->setState(IAfTrackBase::PAUSED);
François Gaffie39634e42023-10-17 12:13:32 +02008273 if (activeTrack->isFastTrack()) {
8274 ALOGV("%s fast track is paused, thus removed from active list", __func__);
8275 // Keep a ref on fast track to wait for FastCapture thread to get updated
8276 // state before potential track removal
8277 fastTrackToRemove = activeTrack;
8278 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008279 doBroadcast = true;
8280 size--;
8281 continue;
8282
Andy Hung8d31fd22023-06-26 19:20:57 -07008283 case IAfTrackBase::STARTING_1:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008284 sleepUs = 10000;
8285 i++;
Eric Laurent5c25d562016-07-13 17:17:45 -07008286 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008287 continue;
8288
Andy Hung8d31fd22023-06-26 19:20:57 -07008289 case IAfTrackBase::STARTING_2:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008290 doBroadcast = true;
Andy Hungcf10d742020-04-28 15:38:24 -07008291 if (mStandby) {
8292 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07008293 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -07008294 mStandby = false;
8295 }
Andy Hung8d31fd22023-06-26 19:20:57 -07008296 activeTrack->setState(IAfTrackBase::ACTIVE);
Eric Laurent5c25d562016-07-13 17:17:45 -07008297 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008298 break;
8299
Andy Hung8d31fd22023-06-26 19:20:57 -07008300 case IAfTrackBase::ACTIVE:
Eric Laurent5c25d562016-07-13 17:17:45 -07008301 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008302 break;
8303
Andy Hung8d31fd22023-06-26 19:20:57 -07008304 case IAfTrackBase::IDLE: // cannot be on ActiveTracks if idle
8305 case IAfTrackBase::PAUSED: // cannot be on ActiveTracks if paused
8306 case IAfTrackBase::STOPPED: // cannot be on ActiveTracks if destroyed/terminated
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008307 default:
Andy Hungce685402018-10-05 17:23:27 -07008308 LOG_ALWAYS_FATAL("%s: Unexpected active track state:%d, id:%d, tracks:%zu",
8309 __func__, activeTrackState, activeTrack->id(), size);
Glenn Kasten9e982352013-08-14 14:39:50 -07008310 }
Glenn Kasten9e982352013-08-14 14:39:50 -07008311
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008312 if (activeTrack->isFastTrack()) {
8313 ALOG_ASSERT(!mFastTrackAvail);
8314 ALOG_ASSERT(fastTrack == 0);
Eric Laurent33403f02020-05-29 18:35:06 -07008315 // if the active fast track is silenced either:
8316 // 1) silence the whole capture from fast capture buffer if this is
8317 // the only active track
8318 // 2) invalidate this track: this will cause the client to reconnect and possibly
8319 // be invalidated again until unsilenced
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008320 bool invalidate = false;
Eric Laurent33403f02020-05-29 18:35:06 -07008321 if (activeTrack->isSilenced()) {
8322 if (size > 1) {
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008323 invalidate = true;
Eric Laurent33403f02020-05-29 18:35:06 -07008324 } else {
8325 silenceFastCapture = true;
8326 }
8327 }
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008328 // Invalidate fast tracks if access to audio history is required as this is not
8329 // possible with fast tracks. Once the fast track has been invalidated, no new
8330 // fast track will be created until mMaxSharedAudioHistoryMs is cleared.
8331 if (mMaxSharedAudioHistoryMs != 0) {
8332 invalidate = true;
8333 }
8334 if (invalidate) {
8335 activeTrack->invalidate();
8336 ALOG_ASSERT(fastTrackToRemove == 0);
8337 fastTrackToRemove = activeTrack;
8338 removeTrack_l(activeTrack);
8339 mActiveTracks.remove(activeTrack);
8340 size--;
8341 continue;
8342 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008343 fastTrack = activeTrack;
8344 }
Eric Laurent33403f02020-05-29 18:35:06 -07008345
8346 activeTracks.add(activeTrack);
8347 i++;
8348
Glenn Kasten9e982352013-08-14 14:39:50 -07008349 }
Eric Laurent5c25d562016-07-13 17:17:45 -07008350
Andy Hungab65b182023-09-06 19:41:47 -07008351 mActiveTracks.updatePowerState_l(this);
Andy Hungdae27702016-10-31 14:01:16 -07008352
Kevin Rocard069c2712018-03-29 19:09:14 -07008353 updateMetadata_l();
8354
Eric Laurent5c25d562016-07-13 17:17:45 -07008355 if (allStopped) {
8356 standbyIfNotAlreadyInStandby();
8357 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008358 if (doBroadcast) {
Andy Hungc5007f82023-08-29 14:26:09 -07008359 mStartStopCV.notify_all();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008360 }
8361
8362 // sleep if there are no active tracks to process
Eric Tan39ec8d62018-07-24 09:49:29 -07008363 if (activeTracks.isEmpty()) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008364 if (sleepUs == 0) {
8365 sleepUs = kRecordThreadSleepUs;
8366 }
8367 continue;
8368 }
8369 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07008370
Andy Hung95c94a22023-10-20 16:41:18 -07008371 timestampCorrectionEnabled = isTimestampCorrectionEnabled_l();
Eric Laurent81784c32012-11-19 14:55:58 -08008372 lockEffectChains_l(effectChains);
8373 }
8374
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008375 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07008376
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008377 size_t size = effectChains.size();
8378 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008379 // thread mutex is not locked, but effect chain is locked
8380 effectChains[i]->process_l();
8381 }
8382
Glenn Kasten735f45f2014-08-18 15:51:59 -07008383 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008384 if (mFastCapture != 0) {
8385 FastCaptureStateQueue *sq = mFastCapture->sq();
8386 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07008387 bool didModify = false;
8388 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008389 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
8390 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
8391 if (state->mCommand == FastCaptureState::COLD_IDLE) {
8392 int32_t old = android_atomic_inc(&mFastCaptureFutex);
8393 if (old == -1) {
8394 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
8395 }
8396 }
8397 state->mCommand = FastCaptureState::READ_WRITE;
8398#if 0 // FIXME
Andy Hung583043b2023-07-17 17:05:00 -07008399 mFastCaptureDumpState.increaseSamplingN(mAfThreadCallback->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08008400 FastThreadDumpState::kSamplingNforLowRamDevice :
8401 FastThreadDumpState::kSamplingN);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008402#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07008403 didModify = true;
8404 }
8405 audio_track_cblk_t *cblkOld = state->mCblk;
8406 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
8407 if (cblkNew != cblkOld) {
8408 state->mCblk = cblkNew;
8409 // block until acked if removing a fast track
8410 if (cblkOld != NULL) {
8411 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
8412 }
8413 didModify = true;
8414 }
jiabin01c8f562018-07-19 17:47:28 -07008415 AudioBufferProvider* abp = (fastTrack != 0 && fastTrack->isPatchTrack()) ?
8416 reinterpret_cast<AudioBufferProvider*>(fastTrack.get()) : nullptr;
8417 if (state->mFastPatchRecordBufferProvider != abp) {
8418 state->mFastPatchRecordBufferProvider = abp;
8419 state->mFastPatchRecordFormat = fastTrack == 0 ?
8420 AUDIO_FORMAT_INVALID : fastTrack->format();
8421 didModify = true;
8422 }
Eric Laurent33403f02020-05-29 18:35:06 -07008423 if (state->mSilenceCapture != silenceFastCapture) {
8424 state->mSilenceCapture = silenceFastCapture;
8425 didModify = true;
8426 }
Glenn Kasten735f45f2014-08-18 15:51:59 -07008427 sq->end(didModify);
8428 if (didModify) {
8429 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008430#if 0
8431 if (kUseFastCapture == FastCapture_Dynamic) {
8432 mNormalSource = mPipeSource;
8433 }
8434#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008435 }
8436 }
8437
Glenn Kasten735f45f2014-08-18 15:51:59 -07008438 // now run the fast track destructor with thread mutex unlocked
8439 fastTrackToRemove.clear();
8440
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008441 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
8442 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
8443 // slow, then this RecordThread will overrun by not calling HAL read often enough.
8444 // If destination is non-contiguous, first read past the nominal end of buffer, then
8445 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008446
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008447 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Andy Hung920f6572022-10-06 12:09:49 -07008448 ssize_t framesRead = 0; // not needed, remove clang-tidy warning.
Andy Hung446f4df2019-02-21 12:26:41 -08008449 const int64_t lastIoBeginNs = systemTime(); // start IO timing
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008450
8451 // If an NBAIO source is present, use it to read the normal capture's data
8452 if (mPipeSource != 0) {
Andy Hung156317a2018-08-02 11:49:29 -07008453 size_t framesToRead = min(mRsmpInFramesOA - rear, mRsmpInFramesP2 / 2);
Andy Hungd5b638f2018-04-30 13:56:10 -07008454
8455 // The audio fifo read() returns OVERRUN on overflow, and advances the read pointer
8456 // to the full buffer point (clearing the overflow condition). Upon OVERRUN error,
8457 // we immediately retry the read() to get data and prevent another overflow.
8458 for (int retries = 0; retries <= 2; ++retries) {
8459 ALOGW_IF(retries > 0, "overrun on read from pipe, retry #%d", retries);
8460 framesRead = mPipeSource->read((uint8_t*)mRsmpInBuffer + rear * mFrameSize,
8461 framesToRead);
8462 if (framesRead != OVERRUN) break;
8463 }
8464
Andy Hung7a3dc6b2018-05-01 16:39:51 -07008465 const ssize_t availableToRead = mPipeSource->availableToRead();
8466 if (availableToRead >= 0) {
Robert Wu06db0a32021-08-10 19:05:34 +00008467 mMonopipePipeDepthStats.add(availableToRead);
Glenn Kastena2f59b32020-08-03 16:37:24 -07008468 // PipeSource is the primary clock. It is up to the AudioRecord client to keep up.
Andy Hung7a3dc6b2018-05-01 16:39:51 -07008469 LOG_ALWAYS_FATAL_IF((size_t)availableToRead > mPipeFramesP2,
8470 "more frames to read than fifo size, %zd > %zu",
8471 availableToRead, mPipeFramesP2);
8472 const size_t pipeFramesFree = mPipeFramesP2 - availableToRead;
8473 const size_t sleepFrames = min(pipeFramesFree, mRsmpInFramesP2) / 2;
8474 ALOGVV("mPipeFramesP2:%zu mRsmpInFramesP2:%zu sleepFrames:%zu availableToRead:%zd",
8475 mPipeFramesP2, mRsmpInFramesP2, sleepFrames, availableToRead);
Glenn Kasten1b291842016-07-18 14:55:21 -07008476 sleepUs = (sleepFrames * 1000000LL) / mSampleRate;
8477 }
8478 if (framesRead < 0) {
8479 status_t status = (status_t) framesRead;
8480 switch (status) {
8481 case OVERRUN:
8482 ALOGW("overrun on read from pipe");
8483 framesRead = 0;
8484 break;
8485 case NEGOTIATE:
8486 ALOGE("re-negotiation is needed");
8487 framesRead = -1; // Will cause an attempt to recover.
8488 break;
8489 default:
8490 ALOGE("unknown error %d on read from pipe", status);
8491 break;
8492 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008493 }
8494 // otherwise use the HAL / AudioStreamIn directly
8495 } else {
Glenn Kastenec6a7032016-03-14 07:40:23 -07008496 ATRACE_BEGIN("read");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008497 size_t bytesRead;
Mikhail Naganov2534b382019-09-25 13:05:02 -07008498 status_t result = mSource->read(
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008499 (uint8_t*)mRsmpInBuffer + rear * mFrameSize, mBufferSize, &bytesRead);
Glenn Kastenec6a7032016-03-14 07:40:23 -07008500 ATRACE_END();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008501 if (result < 0) {
8502 framesRead = result;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008503 } else {
8504 framesRead = bytesRead / mFrameSize;
8505 }
8506 }
8507
Andy Hung446f4df2019-02-21 12:26:41 -08008508 const int64_t lastIoEndNs = systemTime(); // end IO timing
8509
Andy Hung3f0c9022016-01-15 17:49:46 -08008510 // Update server timestamp with server stats
8511 // systemTime() is optional if the hardware supports timestamps.
Andy Hung743f6402020-06-03 13:17:04 -07008512 if (framesRead >= 0) {
8513 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += framesRead;
8514 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = lastIoEndNs;
8515 }
Andy Hung3f0c9022016-01-15 17:49:46 -08008516
8517 // Update server timestamp with kernel stats
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008518 if (mPipeSource.get() == nullptr /* don't obtain for FastCapture, could block */) {
Andy Hung3f0c9022016-01-15 17:49:46 -08008519 int64_t position, time;
Andy Hung2e2c0bb2018-06-11 19:13:11 -07008520 if (mStandby) {
Dean Wheatley12473e92021-03-18 23:00:55 +11008521 mTimestampVerifier.discontinuity(audio_is_linear_pcm(mFormat) ?
8522 mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS :
8523 mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Mikhail Naganov2534b382019-09-25 13:05:02 -07008524 } else if (mSource->getCapturePosition(&position, &time) == NO_ERROR
Andy Hungc8fddf32018-08-08 18:32:37 -07008525 && time > mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]) {
8526
8527 mTimestampVerifier.add(position, time, mSampleRate);
Andy Hungab65b182023-09-06 19:41:47 -07008528 if (timestampCorrectionEnabled) {
Dean Wheatley56a583e2020-05-08 15:12:17 +10008529 ALOGVV("TS_BEFORE: %d %lld %lld",
Andy Hungc8fddf32018-08-08 18:32:37 -07008530 id(), (long long)time, (long long)position);
8531 auto correctedTimestamp = mTimestampVerifier.getLastCorrectedTimestamp();
8532 position = correctedTimestamp.mFrames;
8533 time = correctedTimestamp.mTimeNs;
Dean Wheatley56a583e2020-05-08 15:12:17 +10008534 ALOGVV("TS_AFTER: %d %lld %lld",
Andy Hungc8fddf32018-08-08 18:32:37 -07008535 id(), (long long)time, (long long)position);
8536 }
8537
Andy Hung3f0c9022016-01-15 17:49:46 -08008538 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = position;
8539 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] = time;
8540 // Note: In general record buffers should tend to be empty in
8541 // a properly running pipeline.
8542 //
8543 // Also, it is not advantageous to call get_presentation_position during the read
8544 // as the read obtains a lock, preventing the timestamp call from executing.
Andy Hung2e2c0bb2018-06-11 19:13:11 -07008545 } else {
8546 mTimestampVerifier.error();
Andy Hung3f0c9022016-01-15 17:49:46 -08008547 }
8548 }
Andy Hunge6c37112019-02-26 17:38:10 -08008549
8550 // From the timestamp, input read latency is negative output write latency.
8551 const audio_input_flags_t flags = mInput != NULL ? mInput->flags : AUDIO_INPUT_FLAG_NONE;
Andy Hung8d31fd22023-06-26 19:20:57 -07008552 const double latencyMs = IAfRecordTrack::checkServerLatencySupported(mFormat, flags)
Andy Hunge6c37112019-02-26 17:38:10 -08008553 ? - mTimestamp.getOutputServerLatencyMs(mSampleRate) : 0.;
8554 if (latencyMs != 0.) { // note 0. means timestamp is empty.
8555 mLatencyMs.add(latencyMs);
8556 }
8557
Andy Hung3f0c9022016-01-15 17:49:46 -08008558 // Use this to track timestamp information
8559 // ALOGD("%s", mTimestamp.toString().c_str());
8560
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008561 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07008562 ALOGE("read failed: framesRead=%zd", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008563 // Force input into standby so that it tries to recover at next read attempt
8564 inputStandBy();
8565 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008566 }
8567 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008568 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008569 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008570 ALOG_ASSERT(framesRead > 0);
Andy Hung6427e442018-08-09 12:51:02 -07008571 mFramesRead += framesRead;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008572
Andy Hung8946a282018-04-19 20:04:56 -07008573#ifdef TEE_SINK
8574 (void)mTee.write((uint8_t*)mRsmpInBuffer + rear * mFrameSize, framesRead);
8575#endif
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008576 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008577 {
8578 size_t part1 = mRsmpInFramesP2 - rear;
8579 if ((size_t) framesRead > part1) {
Andy Hung57446612015-04-19 23:56:46 -07008580 memcpy(mRsmpInBuffer, (uint8_t*)mRsmpInBuffer + mRsmpInFramesP2 * mFrameSize,
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008581 (framesRead - part1) * mFrameSize);
8582 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008583 }
Dean Wheatleyfd56e812020-11-06 22:32:21 +11008584 mRsmpInRear = audio_utils::safe_add_overflow(mRsmpInRear, (int32_t)framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008585
8586 size = activeTracks.size();
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008587
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008588 // loop over each active track
8589 for (size_t i = 0; i < size; i++) {
8590 activeTrack = activeTracks[i];
8591
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008592 // skip fast tracks, as those are handled directly by FastCapture
8593 if (activeTrack->isFastTrack()) {
8594 continue;
8595 }
8596
Andy Hung73c02e42015-03-29 01:13:58 -07008597 // TODO: This code probably should be moved to RecordTrack.
Andy Hung97a893e2015-03-29 01:03:07 -07008598 // TODO: Update the activeTrack buffer converter in case of reconfigure.
8599
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008600 enum {
8601 OVERRUN_UNKNOWN,
8602 OVERRUN_TRUE,
8603 OVERRUN_FALSE
8604 } overrun = OVERRUN_UNKNOWN;
8605
8606 // loop over getNextBuffer to handle circular sink
8607 for (;;) {
8608
Andy Hung8d31fd22023-06-26 19:20:57 -07008609 activeTrack->sinkBuffer().frameCount = ~0;
8610 status_t status = activeTrack->getNextBuffer(&activeTrack->sinkBuffer());
8611 size_t framesOut = activeTrack->sinkBuffer().frameCount;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008612 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
8613
Andy Hung73c02e42015-03-29 01:13:58 -07008614 // check available frames and handle overrun conditions
8615 // if the record track isn't draining fast enough.
8616 bool hasOverrun;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008617 size_t framesIn;
Andy Hung8d31fd22023-06-26 19:20:57 -07008618 activeTrack->resamplerBufferProvider()->sync(&framesIn, &hasOverrun);
Andy Hung73c02e42015-03-29 01:13:58 -07008619 if (hasOverrun) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008620 overrun = OVERRUN_TRUE;
8621 }
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08008622 if (framesOut == 0 || framesIn == 0) {
8623 break;
8624 }
8625
Andy Hung6770c6f2015-04-07 13:43:36 -07008626 // Don't allow framesOut to be larger than what is possible with resampling
8627 // from framesIn.
8628 // This isn't strictly necessary but helps limit buffer resizing in
8629 // RecordBufferConverter. TODO: remove when no longer needed.
Dean Wheatleydea650c2023-11-01 22:49:01 +11008630 if (audio_is_linear_pcm(activeTrack->format())) {
8631 framesOut = min(framesOut,
8632 destinationFramesPossible(
8633 framesIn, mSampleRate, activeTrack->sampleRate()));
8634 }
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008635
8636 if (activeTrack->isDirect()) {
Daniel Van Veen9e2376e2018-09-27 14:37:58 +10008637 // No RecordBufferConverter used for direct streams. Pass
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008638 // straight from RecordThread buffer to RecordTrack buffer.
8639 AudioBufferProvider::Buffer buffer;
8640 buffer.frameCount = framesOut;
Andy Hung920f6572022-10-06 12:09:49 -07008641 const status_t getNextBufferStatus =
Andy Hung8d31fd22023-06-26 19:20:57 -07008642 activeTrack->resamplerBufferProvider()->getNextBuffer(&buffer);
Andy Hung920f6572022-10-06 12:09:49 -07008643 if (getNextBufferStatus == OK && buffer.frameCount != 0) {
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008644 ALOGV_IF(buffer.frameCount != framesOut,
8645 "%s() read less than expected (%zu vs %zu)",
8646 __func__, buffer.frameCount, framesOut);
8647 framesOut = buffer.frameCount;
Andy Hung8d31fd22023-06-26 19:20:57 -07008648 memcpy(activeTrack->sinkBuffer().raw,
8649 buffer.raw, buffer.frameCount * mFrameSize);
8650 activeTrack->resamplerBufferProvider()->releaseBuffer(&buffer);
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008651 } else {
8652 framesOut = 0;
8653 ALOGE("%s() cannot fill request, status: %d, frameCount: %zu",
Andy Hung920f6572022-10-06 12:09:49 -07008654 __func__, getNextBufferStatus, buffer.frameCount);
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008655 }
8656 } else {
8657 // process frames from the RecordThread buffer provider to the RecordTrack
8658 // buffer
Andy Hung8d31fd22023-06-26 19:20:57 -07008659 framesOut = activeTrack->recordBufferConverter()->convert(
8660 activeTrack->sinkBuffer().raw,
8661 activeTrack->resamplerBufferProvider(),
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008662 framesOut);
8663 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008664
8665 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
8666 overrun = OVERRUN_FALSE;
8667 }
8668
Andy Hung93bb5732023-05-04 21:16:34 -07008669 // MediaSyncEvent handling: Synchronize AudioRecord to AudioTrack completion.
8670 const ssize_t framesToDrop =
Andy Hung8d31fd22023-06-26 19:20:57 -07008671 activeTrack->synchronizedRecordState().updateRecordFrames(framesOut);
Andy Hung93bb5732023-05-04 21:16:34 -07008672 if (framesToDrop == 0) {
8673 // no sync event, process normally, otherwise ignore.
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008674 if (framesOut > 0) {
Andy Hung8d31fd22023-06-26 19:20:57 -07008675 activeTrack->sinkBuffer().frameCount = framesOut;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008676 // Sanitize before releasing if the track has no access to the source data
8677 // An idle UID receives silence from non virtual devices until active
8678 if (activeTrack->isSilenced()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07008679 memset(activeTrack->sinkBuffer().raw,
8680 0, framesOut * activeTrack->frameSize());
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008681 }
Andy Hung8d31fd22023-06-26 19:20:57 -07008682 activeTrack->releaseBuffer(&activeTrack->sinkBuffer());
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008683 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008684 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008685 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008686 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008687 }
8688 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008689
8690 switch (overrun) {
8691 case OVERRUN_TRUE:
8692 // client isn't retrieving buffers fast enough
8693 if (!activeTrack->setOverflow()) {
8694 nsecs_t now = systemTime();
8695 // FIXME should lastWarning per track?
8696 if ((now - lastWarning) > kWarningThrottleNs) {
8697 ALOGW("RecordThread: buffer overflow");
8698 lastWarning = now;
8699 }
8700 }
8701 break;
8702 case OVERRUN_FALSE:
8703 activeTrack->clearOverflow();
8704 break;
8705 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008706 break;
8707 }
8708
Andy Hung3f0c9022016-01-15 17:49:46 -08008709 // update frame information and push timestamp out
8710 activeTrack->updateTrackFrameInfo(
Andy Hung8d31fd22023-06-26 19:20:57 -07008711 activeTrack->serverProxy()->framesReleased(),
Andy Hung3f0c9022016-01-15 17:49:46 -08008712 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER],
8713 mSampleRate, mTimestamp);
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008714 }
8715
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008716unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08008717 // enable changes in effect chain
8718 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07008719 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurentcccbc762019-04-05 14:20:05 -07008720 if (audio_has_proportional_frames(mFormat)
8721 && loopCount == lastLoopCountRead + 1) {
8722 const int64_t readPeriodNs = lastIoEndNs - mLastIoEndNs;
8723 const double jitterMs =
8724 TimestampVerifier<int64_t, int64_t>::computeJitterMs(
8725 {framesRead, readPeriodNs},
8726 {0, 0} /* lastTimestamp */, mSampleRate);
8727 const double processMs = (lastIoBeginNs - mLastIoEndNs) * 1e-6;
8728
Andy Hung972bec12023-08-31 16:13:39 -07008729 audio_utils::lock_guard _l(mutex());
Eric Laurentcccbc762019-04-05 14:20:05 -07008730 mIoJitterMs.add(jitterMs);
8731 mProcessTimeMs.add(processMs);
8732 }
8733 // update timing info.
8734 mLastIoBeginNs = lastIoBeginNs;
8735 mLastIoEndNs = lastIoEndNs;
8736 lastLoopCountRead = loopCount;
Eric Laurent81784c32012-11-19 14:55:58 -08008737 }
8738
Glenn Kasten93e471f2013-08-19 08:40:07 -07008739 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08008740
8741 {
Andy Hung972bec12023-08-31 16:13:39 -07008742 audio_utils::lock_guard _l(mutex());
Eric Laurent9a54bc22013-09-09 09:08:44 -07008743 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07008744 sp<IAfRecordTrack> track = mTracks[i];
Eric Laurent9a54bc22013-09-09 09:08:44 -07008745 track->invalidate();
8746 }
Glenn Kasten2b806402013-11-20 16:37:38 -08008747 mActiveTracks.clear();
Andy Hungc5007f82023-08-29 14:26:09 -07008748 mStartStopCV.notify_all();
Eric Laurent81784c32012-11-19 14:55:58 -08008749 }
8750
8751 releaseWakeLock();
8752
8753 ALOGV("RecordThread %p exiting", this);
8754 return false;
8755}
8756
Andy Hungee58e4a2023-07-07 13:47:37 -07008757void RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08008758{
8759 if (!mStandby) {
8760 inputStandBy();
Andy Hungcf10d742020-04-28 15:38:24 -07008761 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07008762 mThreadSnapshot.onEnd();
Eric Laurent81784c32012-11-19 14:55:58 -08008763 mStandby = true;
8764 }
8765}
8766
Andy Hungee58e4a2023-07-07 13:47:37 -07008767void RecordThread::inputStandBy()
Eric Laurent81784c32012-11-19 14:55:58 -08008768{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008769 // Idle the fast capture if it's currently running
8770 if (mFastCapture != 0) {
8771 FastCaptureStateQueue *sq = mFastCapture->sq();
8772 FastCaptureState *state = sq->begin();
8773 if (!(state->mCommand & FastCaptureState::IDLE)) {
8774 state->mCommand = FastCaptureState::COLD_IDLE;
8775 state->mColdFutexAddr = &mFastCaptureFutex;
8776 state->mColdGen++;
8777 mFastCaptureFutex = 0;
8778 sq->end();
8779 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
8780 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
8781#if 0
8782 if (kUseFastCapture == FastCapture_Dynamic) {
8783 // FIXME
8784 }
8785#endif
8786#ifdef AUDIO_WATCHDOG
8787 // FIXME
8788#endif
8789 } else {
8790 sq->end(false /*didModify*/);
8791 }
8792 }
Mikhail Naganov2534b382019-09-25 13:05:02 -07008793 status_t result = mSource->standby();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008794 ALOGE_IF(result != OK, "Error when putting input stream into standby: %d", result);
Andy Hungad6d52d2016-07-18 13:42:03 -07008795
8796 // If going into standby, flush the pipe source.
8797 if (mPipeSource.get() != nullptr) {
8798 const ssize_t flushed = mPipeSource->flush();
8799 if (flushed > 0) {
8800 ALOGV("Input standby flushed PipeSource %zd frames", flushed);
8801 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += flushed;
8802 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
8803 }
8804 }
Eric Laurent81784c32012-11-19 14:55:58 -08008805}
8806
Andy Hungc5007f82023-08-29 14:26:09 -07008807// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07008808sp<IAfRecordTrack> RecordThread::createRecordTrack_l(
Andy Hung88035ac2023-06-27 17:05:02 -07008809 const sp<Client>& client,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07008810 const audio_attributes_t& attr,
Eric Laurentf14db3c2017-12-08 14:20:36 -08008811 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08008812 audio_format_t format,
8813 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08008814 size_t *pFrameCount,
Glenn Kastend848eb42016-03-08 13:42:11 -08008815 audio_session_t sessionId,
Eric Laurentf14db3c2017-12-08 14:20:36 -08008816 size_t *pNotificationFrameCount,
Eric Laurent09f1ed22019-04-24 17:45:17 -07008817 pid_t creatorPid,
Svet Ganov33761132021-05-13 22:51:08 +00008818 const AttributionSourceState& attributionSource,
Eric Laurent05067782016-06-01 18:27:28 -07008819 audio_input_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08008820 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08008821 status_t *status,
Eric Laurentec376dc2021-04-08 20:41:22 +02008822 audio_port_handle_t portId,
8823 int32_t maxSharedAudioHistoryMs)
Eric Laurent81784c32012-11-19 14:55:58 -08008824{
Glenn Kasten74935e42013-12-19 08:56:45 -08008825 size_t frameCount = *pFrameCount;
Eric Laurentf14db3c2017-12-08 14:20:36 -08008826 size_t notificationFrameCount = *pNotificationFrameCount;
Andy Hung8d31fd22023-06-26 19:20:57 -07008827 sp<IAfRecordTrack> track;
Eric Laurent81784c32012-11-19 14:55:58 -08008828 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07008829 audio_input_flags_t inputFlags = mInput->flags;
Eric Laurentf14db3c2017-12-08 14:20:36 -08008830 audio_input_flags_t requestedFlags = *flags;
8831 uint32_t sampleRate;
8832
8833 lStatus = initCheck();
8834 if (lStatus != NO_ERROR) {
8835 ALOGE("createRecordTrack_l() audio driver not initialized");
8836 goto Exit;
8837 }
8838
Mikhail Naganovce9f2652018-07-16 11:09:24 -07008839 if (!audio_is_linear_pcm(mFormat) && (*flags & AUDIO_INPUT_FLAG_DIRECT) == 0) {
8840 ALOGE("createRecordTrack_l() on an encoded stream requires AUDIO_INPUT_FLAG_DIRECT");
8841 lStatus = BAD_VALUE;
8842 goto Exit;
8843 }
8844
Eric Laurentec376dc2021-04-08 20:41:22 +02008845 if (maxSharedAudioHistoryMs != 0) {
Eric Laurent9ff3e532022-11-10 16:04:44 +01008846 if (!captureHotwordAllowed(attributionSource)) {
Eric Laurentec376dc2021-04-08 20:41:22 +02008847 lStatus = PERMISSION_DENIED;
8848 goto Exit;
8849 }
Eric Laurentec376dc2021-04-08 20:41:22 +02008850 if (maxSharedAudioHistoryMs < 0
Andy Hung25a80ac2023-07-19 12:47:35 -07008851 || maxSharedAudioHistoryMs > kMaxSharedAudioHistoryMs) {
Eric Laurentec376dc2021-04-08 20:41:22 +02008852 lStatus = BAD_VALUE;
8853 goto Exit;
8854 }
8855 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08008856 if (*pSampleRate == 0) {
8857 *pSampleRate = mSampleRate;
8858 }
8859 sampleRate = *pSampleRate;
Eric Laurent05067782016-06-01 18:27:28 -07008860
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008861 // special case for FAST flag considered OK if fast capture is present and access to
8862 // audio history is not required
8863 if (hasFastCapture() && mMaxSharedAudioHistoryMs == 0) {
Eric Laurent05067782016-06-01 18:27:28 -07008864 inputFlags = (audio_input_flags_t)(inputFlags | AUDIO_INPUT_FLAG_FAST);
8865 }
8866
Eric Laurentf14db3c2017-12-08 14:20:36 -08008867 // Check if requested flags are compatible with input stream flags
Eric Laurent05067782016-06-01 18:27:28 -07008868 if ((*flags & inputFlags) != *flags) {
8869 ALOGW("createRecordTrack_l(): mismatch between requested flags (%08x) and"
8870 " input flags (%08x)",
8871 *flags, inputFlags);
8872 *flags = (audio_input_flags_t)(*flags & inputFlags);
8873 }
Eric Laurent81784c32012-11-19 14:55:58 -08008874
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008875 // client expresses a preference for FAST and no access to audio history,
8876 // but we get the final say
8877 if (*flags & AUDIO_INPUT_FLAG_FAST && maxSharedAudioHistoryMs == 0) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07008878 if (
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07008879 // we formerly checked for a callback handler (non-0 tid),
8880 // but that is no longer required for TRANSFER_OBTAIN mode
jiabinb00edc32021-08-16 16:27:54 +00008881 // No need to match hardware format, format conversion will be done in client side.
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07008882 //
Phil Burk7ed66a12019-04-18 13:20:30 -07008883 // Frame count is not specified (0), or is less than or equal the pipe depth.
8884 // It is OK to provide a higher capacity than requested.
8885 // We will force it to mPipeFramesP2 below.
8886 (frameCount <= mPipeFramesP2) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07008887 // PCM data
8888 audio_is_linear_pcm(format) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08008889 // hardware channel mask
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008890 (channelMask == mChannelMask) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08008891 // hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07008892 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07008893 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008894 hasFastCapture() &&
8895 // there are sufficient fast track slots available
8896 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07008897 ) {
Eric Laurent4c415062016-06-17 16:14:16 -07008898 // check compatibility with audio effects.
Andy Hung972bec12023-08-31 16:13:39 -07008899 audio_utils::lock_guard _l(mutex());
Eric Laurent4c415062016-06-17 16:14:16 -07008900 // Do not accept FAST flag if the session has software effects
Andy Hung116bc262023-06-20 18:56:17 -07008901 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent4c415062016-06-17 16:14:16 -07008902 if (chain != 0) {
Andy Hungd3bb0ad2016-10-11 17:16:43 -07008903 audio_input_flags_t old = *flags;
8904 chain->checkInputFlagCompatibility(flags);
8905 if (old != *flags) {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008906 ALOGV("%p AUDIO_INPUT_FLAGS denied by effect old=%#x new=%#x",
8907 this, (int)old, (int)*flags);
Eric Laurent4c415062016-06-17 16:14:16 -07008908 }
8909 }
Eric Laurent122f7e72016-06-29 11:53:29 -07008910 ALOGV_IF((*flags & AUDIO_INPUT_FLAG_FAST) != 0,
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008911 "%p AUDIO_INPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
8912 this, frameCount, mFrameCount);
Glenn Kasten90e58b12013-07-31 16:16:02 -07008913 } else {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008914 ALOGV("%p AUDIO_INPUT_FLAG_FAST denied: frameCount=%zu mFrameCount=%zu mPipeFramesP2=%zu "
8915 "format=%#x isLinear=%d mFormat=%#x channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008916 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008917 this, frameCount, mFrameCount, mPipeFramesP2,
8918 format, audio_is_linear_pcm(format), mFormat, channelMask, sampleRate, mSampleRate,
Glenn Kasten74105912014-07-03 12:28:53 -07008919 hasFastCapture(), tid, mFastTrackAvail);
Eric Laurent05067782016-06-01 18:27:28 -07008920 *flags = (audio_input_flags_t)(*flags & ~AUDIO_INPUT_FLAG_FAST);
Glenn Kasten74105912014-07-03 12:28:53 -07008921 }
8922 }
8923
Eric Laurentf14db3c2017-12-08 14:20:36 -08008924 // If FAST or RAW flags were corrected, ask caller to request new input from audio policy
8925 if ((*flags & AUDIO_INPUT_FLAG_FAST) !=
8926 (requestedFlags & AUDIO_INPUT_FLAG_FAST)) {
8927 *flags = (audio_input_flags_t) (*flags & ~(AUDIO_INPUT_FLAG_FAST | AUDIO_INPUT_FLAG_RAW));
8928 lStatus = BAD_TYPE;
8929 goto Exit;
8930 }
8931
Glenn Kasten74105912014-07-03 12:28:53 -07008932 // compute track buffer size in frames, and suggest the notification frame count
Eric Laurent05067782016-06-01 18:27:28 -07008933 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten74105912014-07-03 12:28:53 -07008934 // fast track: frame count is exactly the pipe depth
8935 frameCount = mPipeFramesP2;
8936 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
Eric Laurentf14db3c2017-12-08 14:20:36 -08008937 notificationFrameCount = mFrameCount;
Glenn Kasten74105912014-07-03 12:28:53 -07008938 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07008939 // not fast track: max notification period is resampled equivalent of one HAL buffer time
8940 // or 20 ms if there is a fast capture
8941 // TODO This could be a roundupRatio inline, and const
8942 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
8943 * sampleRate + mSampleRate - 1) / mSampleRate;
8944 // minimum number of notification periods is at least kMinNotifications,
8945 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
8946 static const size_t kMinNotifications = 3;
8947 static const uint32_t kMinMs = 30;
8948 // TODO This could be a roundupRatio inline
8949 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
8950 // TODO This could be a roundupRatio inline
8951 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
8952 maxNotificationFrames;
8953 const size_t minFrameCount = maxNotificationFrames *
8954 max(kMinNotifications, minNotificationsByMs);
8955 frameCount = max(frameCount, minFrameCount);
Eric Laurentf14db3c2017-12-08 14:20:36 -08008956 if (notificationFrameCount == 0 || notificationFrameCount > maxNotificationFrames) {
8957 notificationFrameCount = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07008958 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07008959 }
Glenn Kasten74935e42013-12-19 08:56:45 -08008960 *pFrameCount = frameCount;
Eric Laurentf14db3c2017-12-08 14:20:36 -08008961 *pNotificationFrameCount = notificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08008962
Andy Hungc5007f82023-08-29 14:26:09 -07008963 { // scope for mutex()
Andy Hung972bec12023-08-31 16:13:39 -07008964 audio_utils::lock_guard _l(mutex());
Eric Laurent2407ce32021-04-26 14:56:03 +02008965 int32_t startFrames = -1;
Eric Laurentec376dc2021-04-08 20:41:22 +02008966 if (!mSharedAudioPackageName.empty()
Eric Laurent9ff3e532022-11-10 16:04:44 +01008967 && mSharedAudioPackageName == attributionSource.packageName
Eric Laurentec376dc2021-04-08 20:41:22 +02008968 && mSharedAudioSessionId == sessionId
Eric Laurent9ff3e532022-11-10 16:04:44 +01008969 && captureHotwordAllowed(attributionSource)) {
Eric Laurent2407ce32021-04-26 14:56:03 +02008970 startFrames = mSharedAudioStartFrames;
Eric Laurentec376dc2021-04-08 20:41:22 +02008971 }
Eric Laurent81784c32012-11-19 14:55:58 -08008972
Andy Hung8d31fd22023-06-26 19:20:57 -07008973 track = IAfRecordTrack::create(this, client, attr, sampleRate,
Andy Hung8fe68032017-06-05 16:17:51 -07008974 format, channelMask, frameCount,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07008975 nullptr /* buffer */, (size_t)0 /* bufferSize */, sessionId, creatorPid,
Andy Hung8d31fd22023-06-26 19:20:57 -07008976 attributionSource, *flags, IAfTrackBase::TYPE_DEFAULT, portId,
Svet Ganov33761132021-05-13 22:51:08 +00008977 startFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08008978
Glenn Kasten03003332013-08-06 15:40:54 -07008979 lStatus = track->initCheck();
8980 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07008981 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08008982 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08008983 goto Exit;
8984 }
8985 mTracks.add(track);
8986
Eric Laurent05067782016-06-01 18:27:28 -07008987 if ((*flags & AUDIO_INPUT_FLAG_FAST) && (tid != -1)) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07008988 pid_t callingPid = IPCThreadState::self()->getCallingPid();
8989 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
8990 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07008991 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Glenn Kasten90e58b12013-07-31 16:16:02 -07008992 }
Eric Laurentec376dc2021-04-08 20:41:22 +02008993
8994 if (maxSharedAudioHistoryMs != 0) {
8995 sendResizeBufferConfigEvent_l(maxSharedAudioHistoryMs);
8996 }
Eric Laurent81784c32012-11-19 14:55:58 -08008997 }
Glenn Kasten05997e22014-03-13 15:08:33 -07008998
Eric Laurent81784c32012-11-19 14:55:58 -08008999 lStatus = NO_ERROR;
9000
9001Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07009002 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08009003 return track;
9004}
9005
Andy Hungee58e4a2023-07-07 13:47:37 -07009006status_t RecordThread::start(IAfRecordTrack* recordTrack,
Eric Laurent81784c32012-11-19 14:55:58 -08009007 AudioSystem::sync_event_t event,
Glenn Kastend848eb42016-03-08 13:42:11 -08009008 audio_session_t triggerSession)
Eric Laurent81784c32012-11-19 14:55:58 -08009009{
9010 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
9011 sp<ThreadBase> strongMe = this;
9012 status_t status = NO_ERROR;
9013
9014 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08009015 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08009016 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Andy Hung8d31fd22023-06-26 19:20:57 -07009017 recordTrack->synchronizedRecordState().startRecording(
Andy Hung583043b2023-07-17 17:05:00 -07009018 mAfThreadCallback->createSyncEvent(
Andy Hung93bb5732023-05-04 21:16:34 -07009019 event, triggerSession,
9020 recordTrack->sessionId(), syncStartEventCallback, recordTrack));
Eric Laurent81784c32012-11-19 14:55:58 -08009021 }
9022
9023 {
Glenn Kasten47c20702013-08-13 15:37:35 -07009024 // This section is a rendezvous between binder thread executing start() and RecordThread
Andy Hung972bec12023-08-31 16:13:39 -07009025 audio_utils::lock_guard lock(mutex());
Andy Hungce685402018-10-05 17:23:27 -07009026 if (recordTrack->isInvalid()) {
9027 recordTrack->clearSyncStartEvent();
Eric Laurentd52a28c2020-08-21 17:10:39 -07009028 ALOGW("%s track %d: invalidated before startInput", __func__, recordTrack->portId());
9029 return DEAD_OBJECT;
Andy Hungce685402018-10-05 17:23:27 -07009030 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009031 if (mActiveTracks.indexOf(recordTrack) >= 0) {
Andy Hung8d31fd22023-06-26 19:20:57 -07009032 if (recordTrack->state() == IAfTrackBase::PAUSING) {
Andy Hungce685402018-10-05 17:23:27 -07009033 // We haven't stopped yet (moved to PAUSED and not in mActiveTracks)
9034 // so no need to startInput().
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009035 ALOGV("active record track PAUSING -> ACTIVE");
Andy Hung8d31fd22023-06-26 19:20:57 -07009036 recordTrack->setState(IAfTrackBase::ACTIVE);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009037 } else {
Andy Hung8d31fd22023-06-26 19:20:57 -07009038 ALOGV("active record track state %d", (int)recordTrack->state());
Eric Laurent81784c32012-11-19 14:55:58 -08009039 }
9040 return status;
9041 }
9042
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08009043 // TODO consider other ways of handling this, such as changing the state to :STARTING and
9044 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
9045 // or using a separate command thread
Andy Hung8d31fd22023-06-26 19:20:57 -07009046 recordTrack->setState(IAfTrackBase::STARTING_1);
Glenn Kasten2b806402013-11-20 16:37:38 -08009047 mActiveTracks.add(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07009048 if (recordTrack->isExternalTrack()) {
Andy Hungc5007f82023-08-29 14:26:09 -07009049 mutex().unlock();
Eric Laurent4eb58f12018-12-07 16:41:02 -08009050 status = AudioSystem::startInput(recordTrack->portId());
Andy Hungc5007f82023-08-29 14:26:09 -07009051 mutex().lock();
Andy Hungce685402018-10-05 17:23:27 -07009052 if (recordTrack->isInvalid()) {
9053 recordTrack->clearSyncStartEvent();
Andy Hung8d31fd22023-06-26 19:20:57 -07009054 if (status == NO_ERROR && recordTrack->state() == IAfTrackBase::STARTING_1) {
9055 recordTrack->setState(IAfTrackBase::STARTING_2);
Andy Hungce685402018-10-05 17:23:27 -07009056 // STARTING_2 forces destroy to call stopInput.
9057 }
Eric Laurentd52a28c2020-08-21 17:10:39 -07009058 ALOGW("%s track %d: invalidated after startInput", __func__, recordTrack->portId());
9059 return DEAD_OBJECT;
Andy Hungce685402018-10-05 17:23:27 -07009060 }
Andy Hung8d31fd22023-06-26 19:20:57 -07009061 if (recordTrack->state() != IAfTrackBase::STARTING_1) {
Andy Hungce685402018-10-05 17:23:27 -07009062 ALOGW("%s(%d): unsynchronized mState:%d change",
Andy Hung8d31fd22023-06-26 19:20:57 -07009063 __func__, recordTrack->id(), (int)recordTrack->state());
Andy Hungce685402018-10-05 17:23:27 -07009064 // Someone else has changed state, let them take over,
9065 // leave mState in the new state.
9066 recordTrack->clearSyncStartEvent();
9067 return INVALID_OPERATION;
9068 }
9069 // we're ok, but perhaps startInput has failed
Eric Laurent83b88082014-06-20 18:31:16 -07009070 if (status != NO_ERROR) {
Andy Hungce685402018-10-05 17:23:27 -07009071 ALOGW("%s(%d): startInput failed, status %d",
9072 __func__, recordTrack->id(), status);
9073 // We are in ActiveTracks if STARTING_1 and valid, so remove from ActiveTracks,
9074 // leave in STARTING_1, so destroy() will not call stopInput.
Eric Laurent83b88082014-06-20 18:31:16 -07009075 mActiveTracks.remove(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07009076 recordTrack->clearSyncStartEvent();
Eric Laurent83b88082014-06-20 18:31:16 -07009077 return status;
9078 }
Eric Laurent09f1ed22019-04-24 17:45:17 -07009079 sendIoConfigEvent_l(
9080 AUDIO_CLIENT_STARTED, recordTrack->creatorPid(), recordTrack->portId());
Eric Laurent81784c32012-11-19 14:55:58 -08009081 }
Andy Hungc2b11cb2020-04-22 09:04:01 -07009082
9083 recordTrack->logBeginInterval(patchSourcesToString(&mPatch)); // log to MediaMetrics
9084
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009085 // Catch up with current buffer indices if thread is already running.
9086 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
9087 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
9088 // see previously buffered data before it called start(), but with greater risk of overrun.
9089
Andy Hung8d31fd22023-06-26 19:20:57 -07009090 recordTrack->resamplerBufferProvider()->reset();
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07009091 if (!recordTrack->isDirect()) {
9092 // clear any converter state as new data will be discontinuous
Andy Hung8d31fd22023-06-26 19:20:57 -07009093 recordTrack->recordBufferConverter()->reset();
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07009094 }
Andy Hung8d31fd22023-06-26 19:20:57 -07009095 recordTrack->setState(IAfTrackBase::STARTING_2);
Eric Laurent81784c32012-11-19 14:55:58 -08009096 // signal thread to start
Andy Hungc5007f82023-08-29 14:26:09 -07009097 mWaitWorkCV.notify_all();
Eric Laurent81784c32012-11-19 14:55:58 -08009098 return status;
9099 }
Eric Laurent81784c32012-11-19 14:55:58 -08009100}
9101
Andy Hungee58e4a2023-07-07 13:47:37 -07009102void RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
Eric Laurent81784c32012-11-19 14:55:58 -08009103{
Andy Hungee58e4a2023-07-07 13:47:37 -07009104 const sp<SyncEvent> strongEvent = event.promote();
Eric Laurent81784c32012-11-19 14:55:58 -08009105
9106 if (strongEvent != 0) {
Andy Hungd29af632023-06-23 19:27:19 -07009107 sp<IAfTrackBase> ptr =
9108 std::any_cast<const wp<IAfTrackBase>>(strongEvent->cookie()).promote();
9109 if (ptr != nullptr) {
Andy Hung99b1ba62023-07-14 11:00:08 -07009110 // TODO(b/291317898) handleSyncStartEvent is in IAfTrackBase not IAfRecordTrack.
Andy Hungd29af632023-06-23 19:27:19 -07009111 ptr->handleSyncStartEvent(strongEvent);
Eric Laurent8ea16e42014-02-20 16:26:11 -08009112 }
Eric Laurent81784c32012-11-19 14:55:58 -08009113 }
9114}
9115
Andy Hungee58e4a2023-07-07 13:47:37 -07009116bool RecordThread::stop(IAfRecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08009117 ALOGV("RecordThread::stop");
Andy Hungc5007f82023-08-29 14:26:09 -07009118 audio_utils::unique_lock _l(mutex());
Andy Hungce685402018-10-05 17:23:27 -07009119 // if we're invalid, we can't be on the ActiveTracks.
Andy Hung8d31fd22023-06-26 19:20:57 -07009120 if (mActiveTracks.indexOf(recordTrack) < 0 || recordTrack->state() == IAfTrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08009121 return false;
9122 }
Glenn Kasten47c20702013-08-13 15:37:35 -07009123 // note that threadLoop may still be processing the track at this point [without lock]
Andy Hung8d31fd22023-06-26 19:20:57 -07009124 recordTrack->setState(IAfTrackBase::PAUSING);
Andy Hungce685402018-10-05 17:23:27 -07009125
Andy Hungabfab202019-03-07 19:45:54 -08009126 // NOTE: Waiting here is important to keep stop synchronous.
9127 // This is needed for proper patchRecord peer release.
Andy Hung8d31fd22023-06-26 19:20:57 -07009128 while (recordTrack->state() == IAfTrackBase::PAUSING && !recordTrack->isInvalid()) {
Andy Hungc5007f82023-08-29 14:26:09 -07009129 mWaitWorkCV.notify_all(); // signal thread to stop
9130 mStartStopCV.wait(_l);
Eric Laurent81784c32012-11-19 14:55:58 -08009131 }
Andy Hungce685402018-10-05 17:23:27 -07009132
Andy Hung8d31fd22023-06-26 19:20:57 -07009133 if (recordTrack->state() == IAfTrackBase::PAUSED) { // successful stop
Eric Laurent81784c32012-11-19 14:55:58 -08009134 ALOGV("Record stopped OK");
9135 return true;
9136 }
Andy Hungce685402018-10-05 17:23:27 -07009137
9138 // don't handle anything - we've been invalidated or restarted and in a different state
9139 ALOGW_IF("%s(%d): unsynchronized stop, state: %d",
Andy Hung8d31fd22023-06-26 19:20:57 -07009140 __func__, recordTrack->id(), recordTrack->state());
Eric Laurent81784c32012-11-19 14:55:58 -08009141 return false;
9142}
9143
Andy Hungee58e4a2023-07-07 13:47:37 -07009144bool RecordThread::isValidSyncEvent(const sp<SyncEvent>& /* event */) const
Eric Laurent81784c32012-11-19 14:55:58 -08009145{
9146 return false;
9147}
9148
Andy Hungee58e4a2023-07-07 13:47:37 -07009149status_t RecordThread::setSyncEvent(const sp<SyncEvent>& /* event */)
Eric Laurent81784c32012-11-19 14:55:58 -08009150{
9151#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
9152 if (!isValidSyncEvent(event)) {
9153 return BAD_VALUE;
9154 }
9155
Glenn Kastend848eb42016-03-08 13:42:11 -08009156 audio_session_t eventSession = event->triggerSession();
Eric Laurent81784c32012-11-19 14:55:58 -08009157 status_t ret = NAME_NOT_FOUND;
9158
Andy Hung972bec12023-08-31 16:13:39 -07009159 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08009160
9161 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07009162 sp<IAfRecordTrack> track = mTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08009163 if (eventSession == track->sessionId()) {
9164 (void) track->setSyncEvent(event);
9165 ret = NO_ERROR;
9166 }
9167 }
9168 return ret;
9169#else
9170 return BAD_VALUE;
9171#endif
9172}
9173
Andy Hungee58e4a2023-07-07 13:47:37 -07009174status_t RecordThread::getActiveMicrophones(
Andy Hung87c693c2023-07-06 20:56:16 -07009175 std::vector<media::MicrophoneInfoFw>* activeMicrophones) const
jiabin653cc0a2018-01-17 17:54:10 -08009176{
9177 ALOGV("RecordThread::getActiveMicrophones");
Andy Hung972bec12023-08-31 16:13:39 -07009178 audio_utils::lock_guard _l(mutex());
Jasmine Chaeaa10e42021-05-11 10:11:14 +08009179 if (!isStreamInitialized()) {
Paul McLean8a661a32021-04-12 10:21:42 -06009180 return NO_INIT;
9181 }
jiabin9ff780e2018-03-19 18:19:52 -07009182 status_t status = mInput->stream->getActiveMicrophones(activeMicrophones);
9183 return status;
jiabin653cc0a2018-01-17 17:54:10 -08009184}
9185
Andy Hungee58e4a2023-07-07 13:47:37 -07009186status_t RecordThread::setPreferredMicrophoneDirection(
Paul McLean12340082019-03-19 09:35:05 -06009187 audio_microphone_direction_t direction)
Paul McLean03a6e6a2018-12-04 10:54:13 -07009188{
Paul McLean12340082019-03-19 09:35:05 -06009189 ALOGV("setPreferredMicrophoneDirection(%d)", direction);
Andy Hung972bec12023-08-31 16:13:39 -07009190 audio_utils::lock_guard _l(mutex());
Jasmine Chaeaa10e42021-05-11 10:11:14 +08009191 if (!isStreamInitialized()) {
Paul McLean8a661a32021-04-12 10:21:42 -06009192 return NO_INIT;
9193 }
Paul McLean12340082019-03-19 09:35:05 -06009194 return mInput->stream->setPreferredMicrophoneDirection(direction);
Paul McLean03a6e6a2018-12-04 10:54:13 -07009195}
9196
Andy Hungee58e4a2023-07-07 13:47:37 -07009197status_t RecordThread::setPreferredMicrophoneFieldDimension(float zoom)
Paul McLean03a6e6a2018-12-04 10:54:13 -07009198{
Paul McLean12340082019-03-19 09:35:05 -06009199 ALOGV("setPreferredMicrophoneFieldDimension(%f)", zoom);
Andy Hung972bec12023-08-31 16:13:39 -07009200 audio_utils::lock_guard _l(mutex());
Jasmine Chaeaa10e42021-05-11 10:11:14 +08009201 if (!isStreamInitialized()) {
Paul McLean8a661a32021-04-12 10:21:42 -06009202 return NO_INIT;
9203 }
Paul McLean12340082019-03-19 09:35:05 -06009204 return mInput->stream->setPreferredMicrophoneFieldDimension(zoom);
Paul McLean03a6e6a2018-12-04 10:54:13 -07009205}
9206
Andy Hungee58e4a2023-07-07 13:47:37 -07009207status_t RecordThread::shareAudioHistory(
Eric Laurentec376dc2021-04-08 20:41:22 +02009208 const std::string& sharedAudioPackageName, audio_session_t sharedSessionId,
9209 int64_t sharedAudioStartMs) {
Andy Hung972bec12023-08-31 16:13:39 -07009210 audio_utils::lock_guard _l(mutex());
Eric Laurentec376dc2021-04-08 20:41:22 +02009211 return shareAudioHistory_l(sharedAudioPackageName, sharedSessionId, sharedAudioStartMs);
9212}
9213
Andy Hungee58e4a2023-07-07 13:47:37 -07009214status_t RecordThread::shareAudioHistory_l(
Eric Laurentec376dc2021-04-08 20:41:22 +02009215 const std::string& sharedAudioPackageName, audio_session_t sharedSessionId,
9216 int64_t sharedAudioStartMs) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009217
Eric Laurentec376dc2021-04-08 20:41:22 +02009218 if ((hasAudioSession_l(sharedSessionId) & ThreadBase::TRACK_SESSION) == 0) {
9219 return BAD_VALUE;
9220 }
Eric Laurent2407ce32021-04-26 14:56:03 +02009221
9222 if (sharedAudioStartMs < 0
9223 || sharedAudioStartMs > INT64_MAX / mSampleRate) {
Eric Laurentec376dc2021-04-08 20:41:22 +02009224 return BAD_VALUE;
9225 }
9226
Eric Laurent2407ce32021-04-26 14:56:03 +02009227 // Current implementation of the input resampling buffer wraps around indexes at 32 bit.
9228 // As we cannot detect more than one wraparound, only accept values up current write position
9229 // after one wraparound
9230 // We assume recent wraparounds on mRsmpInRear only given it is unlikely that the requesting
9231 // app waits several hours after the start time was computed.
Eric Laurent92d0a322021-07-16 15:32:33 +02009232 int64_t sharedAudioStartFrames = sharedAudioStartMs * mSampleRate / 1000;
Eric Laurent2407ce32021-04-26 14:56:03 +02009233 const int32_t sharedOffset = audio_utils::safe_sub_overflow(mRsmpInRear,
9234 (int32_t)sharedAudioStartFrames);
Eric Laurent92d0a322021-07-16 15:32:33 +02009235 // Bring the start frame position within the input buffer to match the documented
9236 // "best effort" behavior of the API.
9237 if (sharedOffset < 0) {
9238 sharedAudioStartFrames = mRsmpInRear;
Andy Hung920f6572022-10-06 12:09:49 -07009239 } else if (sharedOffset > static_cast<signed>(mRsmpInFrames)) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009240 sharedAudioStartFrames =
9241 audio_utils::safe_sub_overflow(mRsmpInRear, (int32_t)mRsmpInFrames);
Eric Laurent2407ce32021-04-26 14:56:03 +02009242 }
9243
Eric Laurentec376dc2021-04-08 20:41:22 +02009244 mSharedAudioPackageName = sharedAudioPackageName;
9245 if (mSharedAudioPackageName.empty()) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009246 resetAudioHistory_l();
Eric Laurentec376dc2021-04-08 20:41:22 +02009247 } else {
9248 mSharedAudioSessionId = sharedSessionId;
Eric Laurent2407ce32021-04-26 14:56:03 +02009249 mSharedAudioStartFrames = (int32_t)sharedAudioStartFrames;
Eric Laurentec376dc2021-04-08 20:41:22 +02009250 }
9251 return NO_ERROR;
9252}
9253
Andy Hungee58e4a2023-07-07 13:47:37 -07009254void RecordThread::resetAudioHistory_l() {
Eric Laurent92d0a322021-07-16 15:32:33 +02009255 mSharedAudioSessionId = AUDIO_SESSION_NONE;
9256 mSharedAudioStartFrames = -1;
9257 mSharedAudioPackageName = "";
9258}
9259
Andy Hungee58e4a2023-07-07 13:47:37 -07009260ThreadBase::MetadataUpdate RecordThread::updateMetadata_l()
Kevin Rocard069c2712018-03-29 19:09:14 -07009261{
Jasmine Chaeaa10e42021-05-11 10:11:14 +08009262 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
Vlad Popa7e81cea2023-01-19 16:34:16 +01009263 return {}; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -07009264 }
9265 StreamInHalInterface::SinkMetadata metadata;
Eric Laurent78b07302022-10-07 16:20:34 +02009266 auto backInserter = std::back_inserter(metadata.tracks);
Andy Hung8d31fd22023-06-26 19:20:57 -07009267 for (const sp<IAfRecordTrack>& track : mActiveTracks) {
Eric Laurent78b07302022-10-07 16:20:34 +02009268 track->copyMetadataTo(backInserter);
Kevin Rocard069c2712018-03-29 19:09:14 -07009269 }
9270 mInput->stream->updateSinkMetadata(metadata);
Vlad Popa7e81cea2023-01-19 16:34:16 +01009271 MetadataUpdate change;
9272 change.recordMetadataUpdate = metadata.tracks;
9273 return change;
Kevin Rocard069c2712018-03-29 19:09:14 -07009274}
9275
Andy Hungc5007f82023-08-29 14:26:09 -07009276// destroyTrack_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07009277void RecordThread::destroyTrack_l(const sp<IAfRecordTrack>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08009278{
Eric Laurentbfb1b832013-01-07 09:53:42 -08009279 track->terminate();
Andy Hung8d31fd22023-06-26 19:20:57 -07009280 track->setState(IAfTrackBase::STOPPED);
Eric Laurentec376dc2021-04-08 20:41:22 +02009281
Eric Laurent81784c32012-11-19 14:55:58 -08009282 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08009283 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08009284 removeTrack_l(track);
9285 }
9286}
9287
Andy Hungee58e4a2023-07-07 13:47:37 -07009288void RecordThread::removeTrack_l(const sp<IAfRecordTrack>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08009289{
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009290 String8 result;
9291 track->appendDump(result, false /* active */);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00009292 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.c_str());
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009293
Eric Laurent81784c32012-11-19 14:55:58 -08009294 mTracks.remove(track);
9295 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07009296 if (track->isFastTrack()) {
9297 ALOG_ASSERT(!mFastTrackAvail);
9298 mFastTrackAvail = true;
9299 }
Eric Laurent81784c32012-11-19 14:55:58 -08009300}
9301
Andy Hungee58e4a2023-07-07 13:47:37 -07009302void RecordThread::dumpInternals_l(int fd, const Vector<String16>& /* args */)
Eric Laurent81784c32012-11-19 14:55:58 -08009303{
Mikhail Naganov913d06c2016-11-01 12:49:22 -07009304 AudioStreamIn *input = mInput;
9305 audio_input_flags_t flags = input != NULL ? input->flags : AUDIO_INPUT_FLAG_NONE;
9306 dprintf(fd, " AudioStreamIn: %p flags %#x (%s)\n",
Andy Hung9b181952019-02-25 14:53:36 -08009307 input, flags, toString(flags).c_str());
Andy Hung6427e442018-08-09 12:51:02 -07009308 dprintf(fd, " Frames read: %lld\n", (long long)mFramesRead);
Eric Tan39ec8d62018-07-24 09:49:29 -07009309 if (mActiveTracks.isEmpty()) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07009310 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08009311 }
Andy Hungbfa64962017-06-12 14:43:19 -07009312
9313 if (input != nullptr) {
9314 dprintf(fd, " Hal stream dump:\n");
9315 (void)input->stream->dump(fd);
9316 }
9317
Glenn Kasten6e6704c2014-07-03 10:20:00 -07009318 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07009319 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Glenn Kasten17c9c992015-03-02 15:53:01 -08009320
Glenn Kasten2f90c512015-12-02 11:40:09 -08009321 // Make a non-atomic copy of fast capture dump state so it won't change underneath us
9322 // while we are dumping it. It may be inconsistent, but it won't mutate!
9323 // This is a large object so we place it on the heap.
9324 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
Eric Tan2942a4e2018-09-12 17:41:27 -07009325 const std::unique_ptr<FastCaptureDumpState> copy =
9326 std::make_unique<FastCaptureDumpState>(mFastCaptureDumpState);
Glenn Kasten2f90c512015-12-02 11:40:09 -08009327 copy->dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08009328}
9329
Andy Hungee58e4a2023-07-07 13:47:37 -07009330void RecordThread::dumpTracks_l(int fd, const Vector<String16>& /* args */)
Eric Laurent81784c32012-11-19 14:55:58 -08009331{
Eric Laurent81784c32012-11-19 14:55:58 -08009332 String8 result;
Marco Nelissenb2208842014-02-07 14:00:50 -08009333 size_t numtracks = mTracks.size();
9334 size_t numactive = mActiveTracks.size();
9335 size_t numactiveseen = 0;
Glenn Kastenc42e9b42016-03-21 11:35:03 -07009336 dprintf(fd, " %zu Tracks", numtracks);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009337 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08009338 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07009339 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009340 result.append(prefix);
Andy Hung000adb52018-06-01 15:43:26 -07009341 mTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08009342 for (size_t i = 0; i < numtracks ; ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07009343 sp<IAfRecordTrack> track = mTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08009344 if (track != 0) {
9345 bool active = mActiveTracks.indexOf(track) >= 0;
9346 if (active) {
9347 numactiveseen++;
9348 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009349 result.append(prefix);
9350 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08009351 }
Eric Laurent81784c32012-11-19 14:55:58 -08009352 }
Marco Nelissenb2208842014-02-07 14:00:50 -08009353 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07009354 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08009355 }
9356
Marco Nelissenb2208842014-02-07 14:00:50 -08009357 if (numactiveseen != numactive) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009358 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08009359 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009360 result.append(prefix);
Andy Hung000adb52018-06-01 15:43:26 -07009361 mActiveTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08009362 for (size_t i = 0; i < numactive; ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07009363 sp<IAfRecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08009364 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009365 result.append(prefix);
9366 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08009367 }
Glenn Kasten2b806402013-11-20 16:37:38 -08009368 }
Eric Laurent81784c32012-11-19 14:55:58 -08009369
9370 }
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00009371 write(fd, result.c_str(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08009372}
9373
Andy Hungee58e4a2023-07-07 13:47:37 -07009374void RecordThread::setRecordSilenced(audio_port_handle_t portId, bool silenced)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08009375{
Andy Hung972bec12023-08-31 16:13:39 -07009376 audio_utils::lock_guard _l(mutex());
Svet Ganovf4ddfef2018-01-16 07:37:58 -08009377 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07009378 sp<IAfRecordTrack> track = mTracks[i];
Eric Laurent5ada82e2019-08-29 17:53:54 -07009379 if (track != 0 && track->portId() == portId) {
Svet Ganovf4ddfef2018-01-16 07:37:58 -08009380 track->setSilenced(silenced);
9381 }
9382 }
9383}
Andy Hung73c02e42015-03-29 01:13:58 -07009384
Andy Hung8d31fd22023-06-26 19:20:57 -07009385void ResamplerBufferProvider::reset()
Andy Hung73c02e42015-03-29 01:13:58 -07009386{
Andy Hung87c693c2023-07-06 20:56:16 -07009387 const auto threadBase = mRecordTrack->thread().promote();
Andy Hungee58e4a2023-07-07 13:47:37 -07009388 auto* const recordThread = static_cast<RecordThread *>(threadBase->asIAfRecordThread().get());
Andy Hung73c02e42015-03-29 01:13:58 -07009389 mRsmpInUnrel = 0;
Eric Laurentec376dc2021-04-08 20:41:22 +02009390 const int32_t rear = recordThread->mRsmpInRear;
9391 ssize_t deltaFrames = 0;
Eric Laurent2407ce32021-04-26 14:56:03 +02009392 if (mRecordTrack->startFrames() >= 0) {
9393 int32_t startFrames = mRecordTrack->startFrames();
9394 // Accept a recent wraparound of mRsmpInRear
9395 if (startFrames <= rear) {
9396 deltaFrames = rear - startFrames;
9397 } else {
9398 deltaFrames = (int32_t)((int64_t)rear + UINT32_MAX + 1 - startFrames);
Eric Laurentec376dc2021-04-08 20:41:22 +02009399 }
Eric Laurentec376dc2021-04-08 20:41:22 +02009400 // start frame cannot be further in the past than start of resampling buffer
9401 if ((size_t) deltaFrames > recordThread->mRsmpInFrames) {
9402 deltaFrames = recordThread->mRsmpInFrames;
9403 }
9404 }
9405 mRsmpInFront = audio_utils::safe_sub_overflow(rear, static_cast<int32_t>(deltaFrames));
Andy Hung73c02e42015-03-29 01:13:58 -07009406}
9407
Andy Hung8d31fd22023-06-26 19:20:57 -07009408void ResamplerBufferProvider::sync(
Andy Hung73c02e42015-03-29 01:13:58 -07009409 size_t *framesAvailable, bool *hasOverrun)
9410{
Andy Hung87c693c2023-07-06 20:56:16 -07009411 const auto threadBase = mRecordTrack->thread().promote();
Andy Hungee58e4a2023-07-07 13:47:37 -07009412 auto* const recordThread = static_cast<RecordThread *>(threadBase->asIAfRecordThread().get());
Andy Hung73c02e42015-03-29 01:13:58 -07009413 const int32_t rear = recordThread->mRsmpInRear;
9414 const int32_t front = mRsmpInFront;
Hongwei Wang95e37682019-04-12 11:13:36 -07009415 const ssize_t filled = audio_utils::safe_sub_overflow(rear, front);
Andy Hung73c02e42015-03-29 01:13:58 -07009416
9417 size_t framesIn;
9418 bool overrun = false;
9419 if (filled < 0) {
9420 // should not happen, but treat like a massive overrun and re-sync
9421 framesIn = 0;
9422 mRsmpInFront = rear;
9423 overrun = true;
9424 } else if ((size_t) filled <= recordThread->mRsmpInFrames) {
9425 framesIn = (size_t) filled;
9426 } else {
9427 // client is not keeping up with server, but give it latest data
9428 framesIn = recordThread->mRsmpInFrames;
Hongwei Wang95e37682019-04-12 11:13:36 -07009429 mRsmpInFront = /* front = */ audio_utils::safe_sub_overflow(
9430 rear, static_cast<int32_t>(framesIn));
Andy Hung73c02e42015-03-29 01:13:58 -07009431 overrun = true;
9432 }
9433 if (framesAvailable != NULL) {
9434 *framesAvailable = framesIn;
9435 }
9436 if (hasOverrun != NULL) {
9437 *hasOverrun = overrun;
9438 }
9439}
9440
Eric Laurent81784c32012-11-19 14:55:58 -08009441// AudioBufferProvider interface
Andy Hung8d31fd22023-06-26 19:20:57 -07009442status_t ResamplerBufferProvider::getNextBuffer(
Glenn Kastend79072e2016-01-06 08:41:20 -08009443 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08009444{
Andy Hung87c693c2023-07-06 20:56:16 -07009445 const auto threadBase = mRecordTrack->thread().promote();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009446 if (threadBase == 0) {
9447 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08009448 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009449 return NOT_ENOUGH_DATA;
9450 }
Andy Hungee58e4a2023-07-07 13:47:37 -07009451 auto* const recordThread = static_cast<RecordThread *>(threadBase->asIAfRecordThread().get());
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009452 int32_t rear = recordThread->mRsmpInRear;
Andy Hung73c02e42015-03-29 01:13:58 -07009453 int32_t front = mRsmpInFront;
Hongwei Wang95e37682019-04-12 11:13:36 -07009454 ssize_t filled = audio_utils::safe_sub_overflow(rear, front);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009455 // FIXME should not be P2 (don't want to increase latency)
9456 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08009457 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07009458 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009459
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009460 front &= recordThread->mRsmpInFramesP2 - 1;
9461 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07009462 if (part1 > (size_t) filled) {
9463 part1 = filled;
9464 }
9465 size_t ask = buffer->frameCount;
9466 ALOG_ASSERT(ask > 0);
9467 if (part1 > ask) {
9468 part1 = ask;
9469 }
9470 if (part1 == 0) {
Andy Hung73c02e42015-03-29 01:13:58 -07009471 // out of data is fine since the resampler will return a short-count.
Glenn Kasten85948432013-08-19 12:09:05 -07009472 buffer->raw = NULL;
9473 buffer->frameCount = 0;
Andy Hung73c02e42015-03-29 01:13:58 -07009474 mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07009475 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08009476 }
9477
Andy Hung57446612015-04-19 23:56:46 -07009478 buffer->raw = (uint8_t*)recordThread->mRsmpInBuffer + front * recordThread->mFrameSize;
Glenn Kasten85948432013-08-19 12:09:05 -07009479 buffer->frameCount = part1;
Andy Hung73c02e42015-03-29 01:13:58 -07009480 mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08009481 return NO_ERROR;
9482}
9483
9484// AudioBufferProvider interface
Andy Hung8d31fd22023-06-26 19:20:57 -07009485void ResamplerBufferProvider::releaseBuffer(
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009486 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08009487{
Hongwei Wang95e37682019-04-12 11:13:36 -07009488 int32_t stepCount = static_cast<int32_t>(buffer->frameCount);
Glenn Kasten85948432013-08-19 12:09:05 -07009489 if (stepCount == 0) {
9490 return;
9491 }
Eric Laurent1e28aaa2023-04-16 19:34:23 +02009492 ALOG_ASSERT(stepCount <= (int32_t)mRsmpInUnrel);
Andy Hung73c02e42015-03-29 01:13:58 -07009493 mRsmpInUnrel -= stepCount;
Hongwei Wang95e37682019-04-12 11:13:36 -07009494 mRsmpInFront = audio_utils::safe_add_overflow(mRsmpInFront, stepCount);
Glenn Kasten85948432013-08-19 12:09:05 -07009495 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08009496 buffer->frameCount = 0;
9497}
9498
Andy Hungee58e4a2023-07-07 13:47:37 -07009499void RecordThread::checkBtNrec()
Eric Laurentd8365c52017-07-16 15:27:05 -07009500{
Andy Hung972bec12023-08-31 16:13:39 -07009501 audio_utils::lock_guard _l(mutex());
Eric Laurentd8365c52017-07-16 15:27:05 -07009502 checkBtNrec_l();
9503}
9504
Andy Hungee58e4a2023-07-07 13:47:37 -07009505void RecordThread::checkBtNrec_l()
Eric Laurentd8365c52017-07-16 15:27:05 -07009506{
9507 // disable AEC and NS if the device is a BT SCO headset supporting those
9508 // pre processings
Andy Hungab65b182023-09-06 19:41:47 -07009509 bool suspend = audio_is_bluetooth_sco_device(inDeviceType_l()) &&
Andy Hung583043b2023-07-17 17:05:00 -07009510 mAfThreadCallback->btNrecIsOff();
Eric Laurentd8365c52017-07-16 15:27:05 -07009511 if (mBtNrecSuspended.exchange(suspend) != suspend) {
9512 for (size_t i = 0; i < mEffectChains.size(); i++) {
9513 setEffectSuspended_l(FX_IID_AEC, suspend, mEffectChains[i]->sessionId());
9514 setEffectSuspended_l(FX_IID_NS, suspend, mEffectChains[i]->sessionId());
9515 }
9516 }
9517}
9518
Andy Hung97a893e2015-03-29 01:03:07 -07009519
Andy Hungee58e4a2023-07-07 13:47:37 -07009520bool RecordThread::checkForNewParameter_l(const String8& keyValuePair,
Eric Laurent10351942014-05-08 18:49:52 -07009521 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08009522{
9523 bool reconfig = false;
9524
Eric Laurent10351942014-05-08 18:49:52 -07009525 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08009526
Eric Laurent10351942014-05-08 18:49:52 -07009527 audio_format_t reqFormat = mFormat;
9528 uint32_t samplingRate = mSampleRate;
Glenn Kastene1635ec2015-06-08 15:46:49 -07009529 // 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 +08009530 [[maybe_unused]] audio_channel_mask_t channelMask =
9531 audio_channel_in_mask_from_count(mChannelCount);
Eric Laurent10351942014-05-08 18:49:52 -07009532
9533 AudioParameter param = AudioParameter(keyValuePair);
9534 int value;
Haynes Mathew George9ce67b52015-09-30 11:40:47 -07009535
9536 // scope for AutoPark extends to end of method
9537 AutoPark<FastCapture> park(mFastCapture);
9538
Eric Laurent10351942014-05-08 18:49:52 -07009539 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
9540 // channel count change can be requested. Do we mandate the first client defines the
9541 // HAL sampling rate and channel count or do we allow changes on the fly?
9542 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
9543 samplingRate = value;
9544 reconfig = true;
9545 }
9546 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung97a893e2015-03-29 01:03:07 -07009547 if (!audio_is_linear_pcm((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07009548 status = BAD_VALUE;
9549 } else {
9550 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08009551 reconfig = true;
9552 }
Eric Laurent10351942014-05-08 18:49:52 -07009553 }
9554 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
9555 audio_channel_mask_t mask = (audio_channel_mask_t) value;
Andy Hungd330ee42015-04-20 13:23:41 -07009556 if (!audio_is_input_channel(mask) ||
Andy Hung936845a2021-06-08 00:09:06 -07009557 audio_channel_count_from_in_mask(mask) > FCC_LIMIT) {
Eric Laurent10351942014-05-08 18:49:52 -07009558 status = BAD_VALUE;
9559 } else {
9560 channelMask = mask;
9561 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08009562 }
Eric Laurent10351942014-05-08 18:49:52 -07009563 }
9564 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
9565 // do not accept frame count changes if tracks are open as the track buffer
9566 // size depends on frame count and correct behavior would not be guaranteed
9567 // if frame count is changed after track creation
9568 if (mActiveTracks.size() > 0) {
9569 status = INVALID_OPERATION;
9570 } else {
9571 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08009572 }
Eric Laurent10351942014-05-08 18:49:52 -07009573 }
9574 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07009575 LOG_FATAL("Should not set routing device in RecordThread");
Eric Laurent10351942014-05-08 18:49:52 -07009576 }
9577 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
9578 mAudioSource != (audio_source_t)value) {
jiabinc52b1ff2019-10-31 17:20:42 -07009579 LOG_FATAL("Should not set audio source in RecordThread");
Eric Laurent10351942014-05-08 18:49:52 -07009580 }
Glenn Kastene198c362013-08-13 09:13:36 -07009581
Eric Laurent10351942014-05-08 18:49:52 -07009582 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009583 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07009584 if (status == INVALID_OPERATION) {
9585 inputStandBy();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009586 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07009587 }
9588 if (reconfig) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009589 if (status == BAD_VALUE) {
Mikhail Naganov560637e2021-03-31 22:40:13 +00009590 audio_config_base_t config = AUDIO_CONFIG_BASE_INITIALIZER;
9591 if (mInput->stream->getAudioProperties(&config) == OK &&
9592 audio_is_linear_pcm(config.format) && audio_is_linear_pcm(reqFormat) &&
9593 config.sample_rate <= (AUDIO_RESAMPLER_DOWN_RATIO_MAX * samplingRate) &&
Andy Hung936845a2021-06-08 00:09:06 -07009594 audio_channel_count_from_in_mask(config.channel_mask) <= FCC_LIMIT) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009595 status = NO_ERROR;
9596 }
Eric Laurent81784c32012-11-19 14:55:58 -08009597 }
Eric Laurent10351942014-05-08 18:49:52 -07009598 if (status == NO_ERROR) {
9599 readInputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07009600 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08009601 }
9602 }
Eric Laurent81784c32012-11-19 14:55:58 -08009603 }
Eric Laurent10351942014-05-08 18:49:52 -07009604
Eric Laurent81784c32012-11-19 14:55:58 -08009605 return reconfig;
9606}
9607
Andy Hungee58e4a2023-07-07 13:47:37 -07009608String8 RecordThread::getParameters(const String8& keys)
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 if (initCheck() == NO_ERROR) {
9612 String8 out_s8;
9613 if (mInput->stream->getParameters(keys, &out_s8) == OK) {
9614 return out_s8;
9615 }
Eric Laurent81784c32012-11-19 14:55:58 -08009616 }
Andy Hung920f6572022-10-06 12:09:49 -07009617 return {};
Eric Laurent81784c32012-11-19 14:55:58 -08009618}
9619
Andy Hungab65b182023-09-06 19:41:47 -07009620void RecordThread::ioConfigChanged_l(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -07009621 audio_port_handle_t portId) {
Mikhail Naganov88536df2021-07-26 17:30:29 -07009622 sp<AudioIoDescriptor> desc;
Eric Laurent81784c32012-11-19 14:55:58 -08009623 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07009624 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07009625 case AUDIO_INPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07009626 case AUDIO_INPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07009627 desc = sp<AudioIoDescriptor>::make(mId, mPatch, true /*isInput*/,
9628 mSampleRate, mFormat, mChannelMask, mFrameCount, mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08009629 break;
Eric Laurent09f1ed22019-04-24 17:45:17 -07009630 case AUDIO_CLIENT_STARTED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07009631 desc = sp<AudioIoDescriptor>::make(mId, mPatch, portId);
Eric Laurent09f1ed22019-04-24 17:45:17 -07009632 break;
Eric Laurent73e26b62015-04-27 16:55:58 -07009633 case AUDIO_INPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08009634 default:
Mikhail Naganov88536df2021-07-26 17:30:29 -07009635 desc = sp<AudioIoDescriptor>::make(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08009636 break;
9637 }
Andy Hungab65b182023-09-06 19:41:47 -07009638 mAfThreadCallback->ioConfigChanged_l(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08009639}
9640
Andy Hungee58e4a2023-07-07 13:47:37 -07009641void RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08009642{
Dean Wheatley6c009512023-10-23 09:34:14 +11009643 const audio_config_base_t audioConfig = mInput->getAudioProperties();
9644 mSampleRate = audioConfig.sample_rate;
9645 mChannelMask = audioConfig.channel_mask;
9646 if (!audio_is_input_channel(mChannelMask)) {
9647 LOG_ALWAYS_FATAL("Channel mask %#x not valid for input", mChannelMask);
9648 }
9649
Mikhail Naganovce9f2652018-07-16 11:09:24 -07009650 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
Dean Wheatley6c009512023-10-23 09:34:14 +11009651
9652 // Get actual HAL format.
9653 status_t result = mInput->stream->getAudioProperties(nullptr, nullptr, &mHALFormat);
9654 LOG_ALWAYS_FATAL_IF(result != OK, "Error when retrieving input stream format: %d", result);
9655 // Get format from the shim, which will be different than the HAL format
9656 // if recording compressed audio from IEC61937 wrapped sources.
9657 mFormat = audioConfig.format;
9658 if (!audio_is_valid_format(mFormat)) {
9659 LOG_ALWAYS_FATAL("Format %#x not valid for input", mFormat);
9660 }
Mikhail Naganovce9f2652018-07-16 11:09:24 -07009661 if (audio_is_linear_pcm(mFormat)) {
Andy Hung936845a2021-06-08 00:09:06 -07009662 LOG_ALWAYS_FATAL_IF(mChannelCount > FCC_LIMIT, "HAL channel count %d > %d",
9663 mChannelCount, FCC_LIMIT);
Mikhail Naganovce9f2652018-07-16 11:09:24 -07009664 } else {
Andy Hung936845a2021-06-08 00:09:06 -07009665 // Can have more that FCC_LIMIT channels in encoded streams.
Mikhail Naganovce9f2652018-07-16 11:09:24 -07009666 ALOGI("HAL format %#x is not linear pcm", mFormat);
9667 }
Dean Wheatley6c009512023-10-23 09:34:14 +11009668 mFrameSize = mInput->getFrameSize();
Hayden Gomes1a89ab32020-06-12 11:05:47 -07009669 LOG_ALWAYS_FATAL_IF(mFrameSize <= 0, "Error frame size was %zu but must be greater than zero",
9670 mFrameSize);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009671 result = mInput->stream->getBufferSize(&mBufferSize);
9672 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
Glenn Kasten548efc92012-11-29 08:48:51 -08009673 mFrameCount = mBufferSize / mFrameSize;
Hayden Gomes1a89ab32020-06-12 11:05:47 -07009674 ALOGV("%p RecordThread params: mChannelCount=%u, mFormat=%#x, mFrameSize=%zu, "
9675 "mBufferSize=%zu, mFrameCount=%zu",
9676 this, mChannelCount, mFormat, mFrameSize, mBufferSize, mFrameCount);
Glenn Kasten49d00ad2014-07-21 11:22:03 -07009677
Eric Laurentec376dc2021-04-08 20:41:22 +02009678 // mRsmpInFrames must be 0 before calling resizeInputBuffer_l for the first time
9679 mRsmpInFrames = 0;
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009680 resizeInputBuffer_l(0 /*maxSharedAudioHistoryMs*/);
Eric Laurent81784c32012-11-19 14:55:58 -08009681
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08009682 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
9683 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Andy Hungea840382020-05-05 21:50:17 -07009684
9685 audio_input_flags_t flags = mInput->flags;
9686 mediametrics::LogItem item(mThreadMetrics.getMetricsId());
9687 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
Andy Hung25a80ac2023-07-19 12:47:35 -07009688 .set(AMEDIAMETRICS_PROP_ENCODING, IAfThreadBase::formatToString(mFormat).c_str())
Andy Hungea840382020-05-05 21:50:17 -07009689 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
9690 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
9691 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
9692 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
9693 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mFrameCount)
9694 .record();
Eric Laurent81784c32012-11-19 14:55:58 -08009695}
9696
Andy Hungee58e4a2023-07-07 13:47:37 -07009697uint32_t RecordThread::getInputFramesLost() const
Eric Laurent81784c32012-11-19 14:55:58 -08009698{
Andy Hung972bec12023-08-31 16:13:39 -07009699 audio_utils::lock_guard _l(mutex());
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009700 uint32_t result;
9701 if (initCheck() == NO_ERROR && mInput->stream->getInputFramesLost(&result) == OK) {
9702 return result;
Eric Laurent81784c32012-11-19 14:55:58 -08009703 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009704 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08009705}
9706
Andy Hungee58e4a2023-07-07 13:47:37 -07009707KeyedVector<audio_session_t, bool> RecordThread::sessionIds() const
Eric Laurent81784c32012-11-19 14:55:58 -08009708{
Glenn Kastend848eb42016-03-08 13:42:11 -08009709 KeyedVector<audio_session_t, bool> ids;
Andy Hung972bec12023-08-31 16:13:39 -07009710 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08009711 for (size_t j = 0; j < mTracks.size(); ++j) {
Andy Hung8d31fd22023-06-26 19:20:57 -07009712 sp<IAfRecordTrack> track = mTracks[j];
Glenn Kastend848eb42016-03-08 13:42:11 -08009713 audio_session_t sessionId = track->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08009714 if (ids.indexOfKey(sessionId) < 0) {
9715 ids.add(sessionId, true);
9716 }
9717 }
9718 return ids;
9719}
9720
Andy Hungee58e4a2023-07-07 13:47:37 -07009721AudioStreamIn* RecordThread::clearInput()
Eric Laurent81784c32012-11-19 14:55:58 -08009722{
Andy Hung972bec12023-08-31 16:13:39 -07009723 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08009724 AudioStreamIn *input = mInput;
9725 mInput = NULL;
Mikhail Naganov49aecf02023-09-08 15:14:34 -07009726 mInputSource.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08009727 return input;
9728}
9729
Andy Hungc5007f82023-08-29 14:26:09 -07009730// this method must always be called either with ThreadBase mutex() held or inside the thread loop
Andy Hungee58e4a2023-07-07 13:47:37 -07009731sp<StreamHalInterface> RecordThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08009732{
9733 if (mInput == NULL) {
9734 return NULL;
9735 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009736 return mInput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08009737}
9738
Andy Hungee58e4a2023-07-07 13:47:37 -07009739status_t RecordThread::addEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08009740{
Eric Laurent81784c32012-11-19 14:55:58 -08009741 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurentaaa44472014-09-12 17:41:50 -07009742 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08009743 chain->setInBuffer(NULL);
9744 chain->setOutBuffer(NULL);
9745
9746 checkSuspendOnAddEffectChain_l(chain);
9747
Eric Laurent1b928682014-10-02 19:41:47 -07009748 // make sure enabled pre processing effects state is communicated to the HAL as we
9749 // just moved them to a new input stream.
Shunkai Yaod125e402024-01-20 03:19:06 +00009750 chain->syncHalEffectsState_l();
Eric Laurent1b928682014-10-02 19:41:47 -07009751
Eric Laurent81784c32012-11-19 14:55:58 -08009752 mEffectChains.add(chain);
9753
9754 return NO_ERROR;
9755}
9756
Andy Hungee58e4a2023-07-07 13:47:37 -07009757size_t RecordThread::removeEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08009758{
9759 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
Eric Laurentb20cf7d2019-04-05 19:37:34 -07009760
9761 for (size_t i = 0; i < mEffectChains.size(); i++) {
9762 if (chain == mEffectChains[i]) {
9763 mEffectChains.removeAt(i);
9764 break;
9765 }
Eric Laurent81784c32012-11-19 14:55:58 -08009766 }
Eric Laurentb20cf7d2019-04-05 19:37:34 -07009767 return mEffectChains.size();
Eric Laurent81784c32012-11-19 14:55:58 -08009768}
9769
Andy Hungee58e4a2023-07-07 13:47:37 -07009770status_t RecordThread::createAudioPatch_l(const struct audio_patch* patch,
Eric Laurent1c333e22014-05-20 10:48:17 -07009771 audio_patch_handle_t *handle)
9772{
9773 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07009774
9775 // store new device and send to effects
jiabinc52b1ff2019-10-31 17:20:42 -07009776 mInDeviceTypeAddr.mType = patch->sources[0].ext.device.type;
jiabin0a488932020-08-07 17:32:40 -07009777 mInDeviceTypeAddr.setAddress(patch->sources[0].ext.device.address);
François Gaffie0c280aa2018-07-25 10:02:15 +02009778 audio_port_handle_t deviceId = patch->sources[0].id;
Eric Laurent054d9d32015-04-24 08:48:48 -07009779 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08009780 mEffectChains[i]->setInputDevice_l(inDeviceTypeAddr());
Eric Laurent054d9d32015-04-24 08:48:48 -07009781 }
9782
Eric Laurentd8365c52017-07-16 15:27:05 -07009783 checkBtNrec_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07009784
9785 // store new source and send to effects
9786 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
9787 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent1c333e22014-05-20 10:48:17 -07009788 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent054d9d32015-04-24 08:48:48 -07009789 mEffectChains[i]->setAudioSource_l(mAudioSource);
Eric Laurent1c333e22014-05-20 10:48:17 -07009790 }
Eric Laurent054d9d32015-04-24 08:48:48 -07009791 }
Eric Laurent1c333e22014-05-20 10:48:17 -07009792
Mikhail Naganov9ee05402016-10-13 15:58:17 -07009793 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07009794 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
9795 status = hwDevice->createAudioPatch(patch->num_sources,
9796 patch->sources,
9797 patch->num_sinks,
9798 patch->sinks,
9799 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07009800 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08009801 status = mInput->stream->legacyCreateAudioPatch(patch->sources[0],
9802 patch->sinks[0].ext.mix.usecase.source,
9803 patch->sources[0].ext.device.type);
Eric Laurent054d9d32015-04-24 08:48:48 -07009804 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07009805 }
Eric Laurent054d9d32015-04-24 08:48:48 -07009806
jiabinc52b1ff2019-10-31 17:20:42 -07009807 if ((mPatch.num_sources == 0) || (mPatch.sources[0].id != deviceId)) {
Eric Laurente8726fe2015-06-26 09:39:24 -07009808 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
jiabinc52b1ff2019-10-31 17:20:42 -07009809 mPatch = *patch;
Eric Laurente8726fe2015-06-26 09:39:24 -07009810 }
Eric Laurent296fb132015-05-01 11:38:42 -07009811
Andy Hungc2b11cb2020-04-22 09:04:01 -07009812 const std::string pathSourcesAsString = patchSourcesToString(patch);
Andy Hungcf10d742020-04-28 15:38:24 -07009813 mThreadMetrics.logEndInterval();
Andy Hungea840382020-05-05 21:50:17 -07009814 mThreadMetrics.logCreatePatch(pathSourcesAsString, /* outDevices */ {});
Andy Hungcf10d742020-04-28 15:38:24 -07009815 mThreadMetrics.logBeginInterval();
Andy Hungc2b11cb2020-04-22 09:04:01 -07009816 // also dispatch to active AudioRecords
9817 for (const auto &track : mActiveTracks) {
9818 track->logEndInterval();
9819 track->logBeginInterval(pathSourcesAsString);
9820 }
Eric Laurentdda206a2022-07-08 17:28:35 +02009821 // Force meteadata update after a route change
9822 mActiveTracks.setHasChanged();
9823
Eric Laurent1c333e22014-05-20 10:48:17 -07009824 return status;
9825}
9826
Andy Hungee58e4a2023-07-07 13:47:37 -07009827status_t RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
Eric Laurent1c333e22014-05-20 10:48:17 -07009828{
9829 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07009830
jiabinc52b1ff2019-10-31 17:20:42 -07009831 mPatch = audio_patch{};
9832 mInDeviceTypeAddr.reset();
Eric Laurent054d9d32015-04-24 08:48:48 -07009833
Mikhail Naganov9ee05402016-10-13 15:58:17 -07009834 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07009835 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
9836 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07009837 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08009838 status = mInput->stream->legacyReleaseAudioPatch();
Eric Laurent1c333e22014-05-20 10:48:17 -07009839 }
Eric Laurentdda206a2022-07-08 17:28:35 +02009840 // Force meteadata update after a route change
9841 mActiveTracks.setHasChanged();
9842
Eric Laurent1c333e22014-05-20 10:48:17 -07009843 return status;
9844}
9845
Andy Hungee58e4a2023-07-07 13:47:37 -07009846void RecordThread::updateOutDevices(const DeviceDescriptorBaseVector& outDevices)
jiabinc52b1ff2019-10-31 17:20:42 -07009847{
Andy Hung972bec12023-08-31 16:13:39 -07009848 audio_utils::lock_guard _l(mutex());
jiabinc52b1ff2019-10-31 17:20:42 -07009849 mOutDevices = outDevices;
9850 mOutDeviceTypeAddrs = deviceTypeAddrsFromDescriptors(mOutDevices);
9851 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08009852 mEffectChains[i]->setDevices_l(outDeviceTypeAddrs());
jiabinc52b1ff2019-10-31 17:20:42 -07009853 }
9854}
9855
Andy Hungee58e4a2023-07-07 13:47:37 -07009856int32_t RecordThread::getOldestFront_l()
Eric Laurentec376dc2021-04-08 20:41:22 +02009857{
9858 if (mTracks.size() == 0) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009859 return mRsmpInRear;
Eric Laurentec376dc2021-04-08 20:41:22 +02009860 }
Eric Laurent2407ce32021-04-26 14:56:03 +02009861 int32_t oldestFront = mRsmpInRear;
9862 int32_t maxFilled = 0;
Eric Laurentec376dc2021-04-08 20:41:22 +02009863 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07009864 int32_t front = mTracks[i]->resamplerBufferProvider()->getFront();
Eric Laurent2407ce32021-04-26 14:56:03 +02009865 int32_t filled;
Eric Laurent92d0a322021-07-16 15:32:33 +02009866 (void)__builtin_sub_overflow(mRsmpInRear, front, &filled);
Eric Laurent2407ce32021-04-26 14:56:03 +02009867 if (filled > maxFilled) {
9868 oldestFront = front;
9869 maxFilled = filled;
9870 }
Eric Laurentec376dc2021-04-08 20:41:22 +02009871 }
Andy Hung920f6572022-10-06 12:09:49 -07009872 if (maxFilled > static_cast<signed>(mRsmpInFrames)) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009873 (void)__builtin_sub_overflow(mRsmpInRear, mRsmpInFrames, &oldestFront);
9874 }
Eric Laurent2407ce32021-04-26 14:56:03 +02009875 return oldestFront;
Eric Laurentec376dc2021-04-08 20:41:22 +02009876}
9877
Andy Hungee58e4a2023-07-07 13:47:37 -07009878void RecordThread::updateFronts_l(int32_t offset)
Eric Laurentec376dc2021-04-08 20:41:22 +02009879{
9880 if (offset == 0) {
9881 return;
9882 }
9883 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07009884 int32_t front = mTracks[i]->resamplerBufferProvider()->getFront();
Eric Laurentec376dc2021-04-08 20:41:22 +02009885 front = audio_utils::safe_sub_overflow(front, offset);
Andy Hung8d31fd22023-06-26 19:20:57 -07009886 mTracks[i]->resamplerBufferProvider()->setFront(front);
Eric Laurentec376dc2021-04-08 20:41:22 +02009887 }
9888}
9889
Andy Hungee58e4a2023-07-07 13:47:37 -07009890void RecordThread::resizeInputBuffer_l(int32_t maxSharedAudioHistoryMs)
Eric Laurentec376dc2021-04-08 20:41:22 +02009891{
9892 // This is the formula for calculating the temporary buffer size.
9893 // With 7 HAL buffers, we can guarantee ability to down-sample the input by ratio of 6:1 to
9894 // 1 full output buffer, regardless of the alignment of the available input.
9895 // The value is somewhat arbitrary, and could probably be even larger.
9896 // A larger value should allow more old data to be read after a track calls start(),
9897 // without increasing latency.
9898 //
9899 // Note this is independent of the maximum downsampling ratio permitted for capture.
9900 size_t minRsmpInFrames = mFrameCount * 7;
9901
9902 // maxSharedAudioHistoryMs != 0 indicates a request to possibly make some part of the audio
9903 // capture history available to another client using the same session ID:
9904 // dimension the resampler input buffer accordingly.
9905
9906 // Get oldest client read position: getOldestFront_l() must be called before altering
9907 // mRsmpInRear, or mRsmpInFrames
9908 int32_t previousFront = getOldestFront_l();
9909 size_t previousRsmpInFramesP2 = mRsmpInFramesP2;
9910 int32_t previousRear = mRsmpInRear;
9911 mRsmpInRear = 0;
9912
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009913 ALOG_ASSERT(maxSharedAudioHistoryMs >= 0
Andy Hungee58e4a2023-07-07 13:47:37 -07009914 && maxSharedAudioHistoryMs <= kMaxSharedAudioHistoryMs,
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009915 "resizeInputBuffer_l() called with invalid max shared history %d",
9916 maxSharedAudioHistoryMs);
Eric Laurentec376dc2021-04-08 20:41:22 +02009917 if (maxSharedAudioHistoryMs != 0) {
9918 // resizeInputBuffer_l should never be called with a non zero shared history if the
9919 // buffer was not already allocated
9920 ALOG_ASSERT(mRsmpInBuffer != nullptr && mRsmpInFrames != 0,
9921 "resizeInputBuffer_l() called with shared history and unallocated buffer");
9922 size_t rsmpInFrames = (size_t)maxSharedAudioHistoryMs * mSampleRate / 1000;
9923 // never reduce resampler input buffer size
Eric Laurent92d0a322021-07-16 15:32:33 +02009924 if (rsmpInFrames <= mRsmpInFrames) {
Eric Laurentec376dc2021-04-08 20:41:22 +02009925 return;
9926 }
9927 mRsmpInFrames = rsmpInFrames;
9928 }
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009929 mMaxSharedAudioHistoryMs = maxSharedAudioHistoryMs;
Eric Laurentec376dc2021-04-08 20:41:22 +02009930 // Note: mRsmpInFrames is 0 when called with maxSharedAudioHistoryMs equals to 0 so it is always
9931 // initialized
9932 if (mRsmpInFrames < minRsmpInFrames) {
9933 mRsmpInFrames = minRsmpInFrames;
9934 }
9935 mRsmpInFramesP2 = roundup(mRsmpInFrames);
9936
9937 // TODO optimize audio capture buffer sizes ...
9938 // Here we calculate the size of the sliding buffer used as a source
9939 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
9940 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
9941 // be better to have it derived from the pipe depth in the long term.
9942 // The current value is higher than necessary. However it should not add to latency.
9943
9944 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
9945 mRsmpInFramesOA = mRsmpInFramesP2 + mFrameCount - 1;
9946
9947 void *rsmpInBuffer;
9948 (void)posix_memalign(&rsmpInBuffer, 32, mRsmpInFramesOA * mFrameSize);
9949 // if posix_memalign fails, will segv here.
9950 memset(rsmpInBuffer, 0, mRsmpInFramesOA * mFrameSize);
9951
9952 // Copy audio history if any from old buffer before freeing it
9953 if (previousRear != 0) {
9954 ALOG_ASSERT(mRsmpInBuffer != nullptr,
9955 "resizeInputBuffer_l() called with null buffer but frames already read from HAL");
9956
9957 ssize_t unread = audio_utils::safe_sub_overflow(previousRear, previousFront);
9958 previousFront &= previousRsmpInFramesP2 - 1;
9959 size_t part1 = previousRsmpInFramesP2 - previousFront;
9960 if (part1 > (size_t) unread) {
9961 part1 = unread;
9962 }
9963 if (part1 != 0) {
9964 memcpy(rsmpInBuffer, (const uint8_t*)mRsmpInBuffer + previousFront * mFrameSize,
9965 part1 * mFrameSize);
9966 mRsmpInRear = part1;
9967 part1 = unread - part1;
9968 if (part1 != 0) {
9969 memcpy((uint8_t*)rsmpInBuffer + mRsmpInRear * mFrameSize,
9970 (const uint8_t*)mRsmpInBuffer, part1 * mFrameSize);
9971 mRsmpInRear += part1;
9972 }
9973 }
9974 // Update front for all clients according to new rear
9975 updateFronts_l(audio_utils::safe_sub_overflow(previousRear, mRsmpInRear));
9976 } else {
9977 mRsmpInRear = 0;
9978 }
9979 free(mRsmpInBuffer);
9980 mRsmpInBuffer = rsmpInBuffer;
9981}
9982
Andy Hungee58e4a2023-07-07 13:47:37 -07009983void RecordThread::addPatchTrack(const sp<IAfPatchRecord>& record)
Eric Laurent83b88082014-06-20 18:31:16 -07009984{
Andy Hung972bec12023-08-31 16:13:39 -07009985 audio_utils::lock_guard _l(mutex());
Eric Laurent83b88082014-06-20 18:31:16 -07009986 mTracks.add(record);
Mikhail Naganov2534b382019-09-25 13:05:02 -07009987 if (record->getSource()) {
9988 mSource = record->getSource();
9989 }
Eric Laurent83b88082014-06-20 18:31:16 -07009990}
9991
Andy Hungee58e4a2023-07-07 13:47:37 -07009992void RecordThread::deletePatchTrack(const sp<IAfPatchRecord>& record)
Eric Laurent83b88082014-06-20 18:31:16 -07009993{
Andy Hung972bec12023-08-31 16:13:39 -07009994 audio_utils::lock_guard _l(mutex());
Mikhail Naganov2534b382019-09-25 13:05:02 -07009995 if (mSource == record->getSource()) {
9996 mSource = mInput;
9997 }
Eric Laurent83b88082014-06-20 18:31:16 -07009998 destroyTrack_l(record);
9999}
10000
Andy Hungee58e4a2023-07-07 13:47:37 -070010001void RecordThread::toAudioPortConfig(struct audio_port_config* config)
Eric Laurent83b88082014-06-20 18:31:16 -070010002{
Mikhail Naganovdc769682018-05-04 15:34:08 -070010003 ThreadBase::toAudioPortConfig(config);
Eric Laurent83b88082014-06-20 18:31:16 -070010004 config->role = AUDIO_PORT_ROLE_SINK;
10005 config->ext.mix.hw_module = mInput->audioHwDev->handle();
10006 config->ext.mix.usecase.source = mAudioSource;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -070010007 if (mInput && mInput->flags != AUDIO_INPUT_FLAG_NONE) {
10008 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
10009 config->flags.input = mInput->flags;
10010 }
Eric Laurent83b88082014-06-20 18:31:16 -070010011}
Eric Laurent1c333e22014-05-20 10:48:17 -070010012
Eric Laurent6acd1d42017-01-04 14:23:29 -080010013// ----------------------------------------------------------------------------
10014// Mmap
10015// ----------------------------------------------------------------------------
10016
Andy Hung7aa7d102023-07-07 15:58:48 -070010017// Mmap stream control interface implementation. Each MmapThreadHandle controls one
10018// MmapPlaybackThread or MmapCaptureThread instance.
10019class MmapThreadHandle : public MmapStreamInterface {
10020public:
10021 explicit MmapThreadHandle(const sp<IAfMmapThread>& thread);
10022 ~MmapThreadHandle() override;
10023
10024 // MmapStreamInterface virtuals
10025 status_t createMmapBuffer(int32_t minSizeFrames,
10026 struct audio_mmap_buffer_info* info) final;
10027 status_t getMmapPosition(struct audio_mmap_position* position) final;
10028 status_t getExternalPosition(uint64_t* position, int64_t* timeNanos) final;
10029 status_t start(const AudioClient& client,
10030 const audio_attributes_t* attr, audio_port_handle_t* handle) final;
10031 status_t stop(audio_port_handle_t handle) final;
10032 status_t standby() final;
10033 status_t reportData(const void* buffer, size_t frameCount) final;
10034private:
10035 const sp<IAfMmapThread> mThread;
10036};
10037
10038/* static */
10039sp<MmapStreamInterface> IAfMmapThread::createMmapStreamInterfaceAdapter(
10040 const sp<IAfMmapThread>& mmapThread) {
10041 return sp<MmapThreadHandle>::make(mmapThread);
10042}
10043
10044MmapThreadHandle::MmapThreadHandle(const sp<IAfMmapThread>& thread)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010045 : mThread(thread)
10046{
Phil Burk9fabbf82017-08-03 12:02:00 -070010047 assert(thread != 0); // thread must start non-null and stay non-null
Eric Laurent6acd1d42017-01-04 14:23:29 -080010048}
10049
Andy Hung7aa7d102023-07-07 15:58:48 -070010050// MmapStreamInterface could be directly implemented by MmapThread excepting this
10051// special handling on adapter dtor.
10052MmapThreadHandle::~MmapThreadHandle()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010053{
Phil Burk9fabbf82017-08-03 12:02:00 -070010054 mThread->disconnect();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010055}
10056
Andy Hung7aa7d102023-07-07 15:58:48 -070010057status_t MmapThreadHandle::createMmapBuffer(int32_t minSizeFrames,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010058 struct audio_mmap_buffer_info *info)
10059{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010060 return mThread->createMmapBuffer(minSizeFrames, info);
10061}
10062
Andy Hung7aa7d102023-07-07 15:58:48 -070010063status_t MmapThreadHandle::getMmapPosition(struct audio_mmap_position* position)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010064{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010065 return mThread->getMmapPosition(position);
10066}
10067
Andy Hung7aa7d102023-07-07 15:58:48 -070010068status_t MmapThreadHandle::getExternalPosition(uint64_t* position,
jiabinb7d8c5a2020-08-26 17:24:52 -070010069 int64_t *timeNanos) {
10070 return mThread->getExternalPosition(position, timeNanos);
10071}
10072
Andy Hung7aa7d102023-07-07 15:58:48 -070010073status_t MmapThreadHandle::start(const AudioClient& client,
jiabind1f1cb62020-03-24 11:57:57 -070010074 const audio_attributes_t *attr, audio_port_handle_t *handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010075{
jiabind1f1cb62020-03-24 11:57:57 -070010076 return mThread->start(client, attr, handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010077}
10078
Andy Hung7aa7d102023-07-07 15:58:48 -070010079status_t MmapThreadHandle::stop(audio_port_handle_t handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010080{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010081 return mThread->stop(handle);
10082}
10083
Andy Hung7aa7d102023-07-07 15:58:48 -070010084status_t MmapThreadHandle::standby()
Eric Laurent18b57012017-02-13 16:23:52 -080010085{
Eric Laurent18b57012017-02-13 16:23:52 -080010086 return mThread->standby();
10087}
10088
Andy Hung7aa7d102023-07-07 15:58:48 -070010089status_t MmapThreadHandle::reportData(const void* buffer, size_t frameCount)
10090{
jiabinfc791ee2023-02-15 19:43:40 +000010091 return mThread->reportData(buffer, frameCount);
10092}
10093
Eric Laurent6acd1d42017-01-04 14:23:29 -080010094
Andy Hungee58e4a2023-07-07 13:47:37 -070010095MmapThread::MmapThread(
Andy Hung583043b2023-07-17 17:05:00 -070010096 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
Andy Hung920f6572022-10-06 12:09:49 -070010097 AudioHwDevice *hwDev, const sp<StreamHalInterface>& stream, bool systemReady, bool isOut)
Andy Hung583043b2023-07-17 17:05:00 -070010098 : ThreadBase(afThreadCallback, id, (isOut ? MMAP_PLAYBACK : MMAP_CAPTURE), systemReady, isOut),
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010099 mSessionId(AUDIO_SESSION_NONE),
François Gaffie0c280aa2018-07-25 10:02:15 +020010100 mPortId(AUDIO_PORT_HANDLE_NONE),
Andy Hung2c6c3bb2017-06-16 14:01:45 -070010101 mHalStream(stream), mHalDevice(hwDev->hwDevice()), mAudioHwDev(hwDev),
Eric Laurent67f97292018-04-20 18:05:41 -070010102 mActiveTracks(&this->mLocalLog),
10103 mHalVolFloat(-1.0f), // Initialize to illegal value so it always gets set properly later.
10104 mNoCallbackWarningCount(0)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010105{
Eric Laurent18b57012017-02-13 16:23:52 -080010106 mStandby = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010107 readHalParameters_l();
10108}
10109
Andy Hungee58e4a2023-07-07 13:47:37 -070010110void MmapThread::onFirstRef()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010111{
10112 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
10113}
10114
Andy Hungee58e4a2023-07-07 13:47:37 -070010115void MmapThread::disconnect()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010116{
Andy Hung8d31fd22023-06-26 19:20:57 -070010117 ActiveTracks<IAfMmapTrack> activeTracks;
Andy Hung3f49ebb2023-09-19 14:48:41 -070010118 audio_port_handle_t localPortId;
Eric Laurent331679c2018-04-16 17:03:16 -070010119 {
Andy Hung972bec12023-08-31 16:13:39 -070010120 audio_utils::lock_guard _l(mutex());
Andy Hung8d31fd22023-06-26 19:20:57 -070010121 for (const sp<IAfMmapTrack>& t : mActiveTracks) {
Eric Laurent331679c2018-04-16 17:03:16 -070010122 activeTracks.add(t);
10123 }
Andy Hung3f49ebb2023-09-19 14:48:41 -070010124 localPortId = mPortId;
Eric Laurent331679c2018-04-16 17:03:16 -070010125 }
Andy Hung8d31fd22023-06-26 19:20:57 -070010126 for (const sp<IAfMmapTrack>& t : activeTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010127 stop(t->portId());
10128 }
Phil Burk9fabbf82017-08-03 12:02:00 -070010129 // This will decrement references and may cause the destruction of this thread.
Eric Laurent6acd1d42017-01-04 14:23:29 -080010130 if (isOutput()) {
Andy Hung3f49ebb2023-09-19 14:48:41 -070010131 AudioSystem::releaseOutput(localPortId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010132 } else {
Andy Hung3f49ebb2023-09-19 14:48:41 -070010133 AudioSystem::releaseInput(localPortId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010134 }
10135}
10136
10137
Andy Hung8d672e02023-09-15 18:19:28 -070010138void MmapThread::configure_l(const audio_attributes_t* attr,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010139 audio_stream_type_t streamType __unused,
10140 audio_session_t sessionId,
10141 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010142 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010143 audio_port_handle_t portId)
10144{
10145 mAttr = *attr;
10146 mSessionId = sessionId;
10147 mCallback = callback;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010148 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010149 mPortId = portId;
10150}
10151
Andy Hungee58e4a2023-07-07 13:47:37 -070010152status_t MmapThread::createMmapBuffer(int32_t minSizeFrames,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010153 struct audio_mmap_buffer_info *info)
10154{
Andy Hung3f49ebb2023-09-19 14:48:41 -070010155 audio_utils::lock_guard l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010156 if (mHalStream == 0) {
10157 return NO_INIT;
10158 }
Eric Laurent18b57012017-02-13 16:23:52 -080010159 mStandby = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010160 return mHalStream->createMmapBuffer(minSizeFrames, info);
10161}
10162
Andy Hungee58e4a2023-07-07 13:47:37 -070010163status_t MmapThread::getMmapPosition(struct audio_mmap_position* position) const
Eric Laurent6acd1d42017-01-04 14:23:29 -080010164{
Andy Hung3f49ebb2023-09-19 14:48:41 -070010165 audio_utils::lock_guard l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010166 if (mHalStream == 0) {
10167 return NO_INIT;
10168 }
10169 return mHalStream->getMmapPosition(position);
10170}
10171
Andy Hungee58e4a2023-07-07 13:47:37 -070010172status_t MmapThread::exitStandby_l()
Eric Laurent331679c2018-04-16 17:03:16 -070010173{
Eric Laurentdda206a2022-07-08 17:28:35 +020010174 // The HAL must receive track metadata before starting the stream
10175 updateMetadata_l();
Eric Laurent331679c2018-04-16 17:03:16 -070010176 status_t ret = mHalStream->start();
10177 if (ret != NO_ERROR) {
10178 ALOGE("%s: error mHalStream->start() = %d for first track", __FUNCTION__, ret);
10179 return ret;
10180 }
Andy Hungcf10d742020-04-28 15:38:24 -070010181 if (mStandby) {
10182 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -070010183 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -070010184 mStandby = false;
10185 }
Eric Laurent331679c2018-04-16 17:03:16 -070010186 return NO_ERROR;
10187}
10188
Andy Hungee58e4a2023-07-07 13:47:37 -070010189status_t MmapThread::start(const AudioClient& client,
jiabind1f1cb62020-03-24 11:57:57 -070010190 const audio_attributes_t *attr,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010191 audio_port_handle_t *handle)
10192{
Andy Hung3f49ebb2023-09-19 14:48:41 -070010193 audio_utils::lock_guard l(mutex());
Eric Laurenta54f1282017-07-01 19:39:32 -070010194 ALOGV("%s clientUid %d mStandby %d mPortId %d *handle %d", __FUNCTION__,
Svet Ganov33761132021-05-13 22:51:08 +000010195 client.attributionSource.uid, mStandby, mPortId, *handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010196 if (mHalStream == 0) {
10197 return NO_INIT;
10198 }
10199
10200 status_t ret;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010201
Eric Laurentdda206a2022-07-08 17:28:35 +020010202 // For the first track, reuse portId and session allocated when the stream was opened.
Eric Laurenta54f1282017-07-01 19:39:32 -070010203 if (*handle == mPortId) {
Andy Hung3f49ebb2023-09-19 14:48:41 -070010204 acquireWakeLock_l();
Eric Laurentdda206a2022-07-08 17:28:35 +020010205 return NO_ERROR;
Eric Laurenta54f1282017-07-01 19:39:32 -070010206 }
10207
10208 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
10209
10210 audio_io_handle_t io = mId;
Andy Hung6cd79802023-07-19 16:56:19 -070010211 const AttributionSourceState adjAttributionSource = afutils::checkAttributionSourcePackage(
Atneya Nairf59db5c2023-05-10 21:37:41 -070010212 client.attributionSource);
10213
Andy Hung3f49ebb2023-09-19 14:48:41 -070010214 const auto localSessionId = mSessionId;
10215 auto localAttr = mAttr;
Eric Laurenta54f1282017-07-01 19:39:32 -070010216 if (isOutput()) {
10217 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
10218 config.sample_rate = mSampleRate;
10219 config.channel_mask = mChannelMask;
10220 config.format = mFormat;
Andy Hung3f49ebb2023-09-19 14:48:41 -070010221 audio_stream_type_t stream = streamType_l();
Eric Laurenta54f1282017-07-01 19:39:32 -070010222 audio_output_flags_t flags =
10223 (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010224 audio_port_handle_t deviceId = mDeviceId;
Kevin Rocard153f92d2018-12-18 18:33:28 -080010225 std::vector<audio_io_handle_t> secondaryOutputs;
Eric Laurentb0a7bc92022-04-05 15:06:08 +020010226 bool isSpatialized;
jiabinc658e452022-10-21 20:52:21 +000010227 bool isBitPerfect;
Andy Hung3f49ebb2023-09-19 14:48:41 -070010228 mutex().unlock();
10229 ret = AudioSystem::getOutputForAttr(&localAttr, &io,
10230 localSessionId,
Eric Laurenta54f1282017-07-01 19:39:32 -070010231 &stream,
Atneya Nairf59db5c2023-05-10 21:37:41 -070010232 adjAttributionSource,
Eric Laurenta54f1282017-07-01 19:39:32 -070010233 &config,
10234 flags,
10235 &deviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -080010236 &portId,
Eric Laurentb0a7bc92022-04-05 15:06:08 +020010237 &secondaryOutputs,
jiabinc658e452022-10-21 20:52:21 +000010238 &isSpatialized,
10239 &isBitPerfect);
Andy Hung3f49ebb2023-09-19 14:48:41 -070010240 mutex().lock();
10241 mAttr = localAttr;
Kevin Rocard153f92d2018-12-18 18:33:28 -080010242 ALOGD_IF(!secondaryOutputs.empty(),
10243 "MmapThread::start does not support secondary outputs, ignoring them");
Eric Laurent6acd1d42017-01-04 14:23:29 -080010244 } else {
Eric Laurenta54f1282017-07-01 19:39:32 -070010245 audio_config_base_t config;
10246 config.sample_rate = mSampleRate;
10247 config.channel_mask = mChannelMask;
10248 config.format = mFormat;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010249 audio_port_handle_t deviceId = mDeviceId;
Andy Hung3f49ebb2023-09-19 14:48:41 -070010250 mutex().unlock();
10251 ret = AudioSystem::getInputForAttr(&localAttr, &io,
Mikhail Naganov2996f672019-04-18 12:29:59 -070010252 RECORD_RIID_INVALID,
Andy Hung3f49ebb2023-09-19 14:48:41 -070010253 localSessionId,
Atneya Nairf59db5c2023-05-10 21:37:41 -070010254 adjAttributionSource,
Eric Laurenta54f1282017-07-01 19:39:32 -070010255 &config,
10256 AUDIO_INPUT_FLAG_MMAP_NOIRQ,
10257 &deviceId,
10258 &portId);
Andy Hung3f49ebb2023-09-19 14:48:41 -070010259 mutex().lock();
10260 // localAttr is const for getInputForAttr.
Eric Laurenta54f1282017-07-01 19:39:32 -070010261 }
10262 // APM should not chose a different input or output stream for the same set of attributes
10263 // and audo configuration
10264 if (ret != NO_ERROR || io != mId) {
10265 ALOGE("%s: error getting output or input from APM (error %d, io %d expected io %d)",
10266 __FUNCTION__, ret, io, mId);
10267 return BAD_VALUE;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010268 }
10269
10270 if (isOutput()) {
Andy Hung3f49ebb2023-09-19 14:48:41 -070010271 mutex().unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -070010272 ret = AudioSystem::startOutput(portId);
Andy Hung3f49ebb2023-09-19 14:48:41 -070010273 mutex().lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010274 } else {
jiabin09609032022-06-15 19:26:01 +000010275 {
10276 // Add the track record before starting input so that the silent status for the
10277 // client can be cached.
jiabin09609032022-06-15 19:26:01 +000010278 setClientSilencedState_l(portId, false /*silenced*/);
10279 }
Andy Hung3f49ebb2023-09-19 14:48:41 -070010280 mutex().unlock();
Eric Laurent4eb58f12018-12-07 16:41:02 -080010281 ret = AudioSystem::startInput(portId);
Andy Hung3f49ebb2023-09-19 14:48:41 -070010282 mutex().lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010283 }
10284
10285 // abort if start is rejected by audio policy manager
10286 if (ret != NO_ERROR) {
Phil Burk7f6b40d2017-02-09 13:18:38 -080010287 ALOGE("%s: error start rejected by AudioPolicyManager = %d", __FUNCTION__, ret);
Eric Tan39ec8d62018-07-24 09:49:29 -070010288 if (!mActiveTracks.isEmpty()) {
Andy Hungc5007f82023-08-29 14:26:09 -070010289 mutex().unlock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010290 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -070010291 AudioSystem::releaseOutput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010292 } else {
Eric Laurentfee19762018-01-29 18:44:13 -080010293 AudioSystem::releaseInput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010294 }
Andy Hungc5007f82023-08-29 14:26:09 -070010295 mutex().lock();
Eric Laurent18b57012017-02-13 16:23:52 -080010296 } else {
10297 mHalStream->stop();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010298 }
jiabin09609032022-06-15 19:26:01 +000010299 eraseClientSilencedState_l(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010300 return PERMISSION_DENIED;
10301 }
10302
Kevin Rocard1f564ac2018-03-29 13:53:10 -070010303 // Given that MmapThread::mAttr is mutable, should a MmapTrack have attributes ?
Andy Hung8d31fd22023-06-26 19:20:57 -070010304 sp<IAfMmapTrack> track = IAfMmapTrack::create(
10305 this, attr == nullptr ? mAttr : *attr, mSampleRate, mFormat,
Svet Ganov33761132021-05-13 22:51:08 +000010306 mChannelMask, mSessionId, isOutput(),
10307 client.attributionSource,
Philip P. Moltmannbda45752020-07-17 16:41:18 -070010308 IPCThreadState::self()->getCallingPid(), portId);
jiabin09609032022-06-15 19:26:01 +000010309 if (!isOutput()) {
10310 track->setSilenced_l(isClientSilenced_l(portId));
10311 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010312
Eric Laurent4eb58f12018-12-07 16:41:02 -080010313 if (isOutput()) {
10314 // force volume update when a new track is added
10315 mHalVolFloat = -1.0f;
10316 } else if (!track->isSilenced_l()) {
Andy Hung8d31fd22023-06-26 19:20:57 -070010317 for (const sp<IAfMmapTrack>& t : mActiveTracks) {
Andy Hung920f6572022-10-06 12:09:49 -070010318 if (t->isSilenced_l()
10319 && t->uid() != static_cast<uid_t>(client.attributionSource.uid)) {
Eric Laurent4eb58f12018-12-07 16:41:02 -080010320 t->invalidate();
Andy Hung920f6572022-10-06 12:09:49 -070010321 }
Eric Laurent4eb58f12018-12-07 16:41:02 -080010322 }
10323 }
10324
Eric Laurent6acd1d42017-01-04 14:23:29 -080010325 mActiveTracks.add(track);
Andy Hung116bc262023-06-20 18:56:17 -070010326 sp<IAfEffectChain> chain = getEffectChain_l(mSessionId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010327 if (chain != 0) {
Andy Hung3f49ebb2023-09-19 14:48:41 -070010328 chain->setStrategy(getStrategyForStream(streamType_l()));
Eric Laurent6acd1d42017-01-04 14:23:29 -080010329 chain->incTrackCnt();
10330 chain->incActiveTrackCnt();
10331 }
10332
Andy Hungc2b11cb2020-04-22 09:04:01 -070010333 track->logBeginInterval(patchSinksToString(&mPatch)); // log to MediaMetrics
Eric Laurent6acd1d42017-01-04 14:23:29 -080010334 *handle = portId;
Eric Laurentdda206a2022-07-08 17:28:35 +020010335
10336 if (mActiveTracks.size() == 1) {
10337 ret = exitStandby_l();
10338 }
10339
Eric Laurent6acd1d42017-01-04 14:23:29 -080010340 broadcast_l();
10341
Eric Laurentdda206a2022-07-08 17:28:35 +020010342 ALOGV("%s DONE status %d handle %d stream %p", __FUNCTION__, ret, *handle, mHalStream.get());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010343
Eric Laurentdda206a2022-07-08 17:28:35 +020010344 return ret;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010345}
10346
Andy Hungee58e4a2023-07-07 13:47:37 -070010347status_t MmapThread::stop(audio_port_handle_t handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010348{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010349 ALOGV("%s handle %d", __FUNCTION__, handle);
Andy Hung3f49ebb2023-09-19 14:48:41 -070010350 audio_utils::lock_guard l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010351
10352 if (mHalStream == 0) {
10353 return NO_INIT;
10354 }
10355
Eric Laurenta54f1282017-07-01 19:39:32 -070010356 if (handle == mPortId) {
Andy Hung3f49ebb2023-09-19 14:48:41 -070010357 releaseWakeLock_l();
Eric Laurenta54f1282017-07-01 19:39:32 -070010358 return NO_ERROR;
10359 }
10360
Andy Hung8d31fd22023-06-26 19:20:57 -070010361 sp<IAfMmapTrack> track;
10362 for (const sp<IAfMmapTrack>& t : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010363 if (handle == t->portId()) {
10364 track = t;
10365 break;
10366 }
10367 }
10368 if (track == 0) {
10369 return BAD_VALUE;
10370 }
10371
10372 mActiveTracks.remove(track);
jiabin09609032022-06-15 19:26:01 +000010373 eraseClientSilencedState_l(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010374
Andy Hungc5007f82023-08-29 14:26:09 -070010375 mutex().unlock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010376 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -070010377 AudioSystem::stopOutput(track->portId());
10378 AudioSystem::releaseOutput(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010379 } else {
Eric Laurentfee19762018-01-29 18:44:13 -080010380 AudioSystem::stopInput(track->portId());
10381 AudioSystem::releaseInput(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010382 }
Andy Hungc5007f82023-08-29 14:26:09 -070010383 mutex().lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010384
Andy Hung116bc262023-06-20 18:56:17 -070010385 sp<IAfEffectChain> chain = getEffectChain_l(track->sessionId());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010386 if (chain != 0) {
10387 chain->decActiveTrackCnt();
10388 chain->decTrackCnt();
10389 }
10390
Eric Laurentdda206a2022-07-08 17:28:35 +020010391 if (mActiveTracks.isEmpty()) {
10392 mHalStream->stop();
10393 }
10394
Eric Laurent6acd1d42017-01-04 14:23:29 -080010395 broadcast_l();
10396
Eric Laurent6acd1d42017-01-04 14:23:29 -080010397 return NO_ERROR;
10398}
10399
Andy Hungee58e4a2023-07-07 13:47:37 -070010400status_t MmapThread::standby()
Andy Hung3f49ebb2023-09-19 14:48:41 -070010401NO_THREAD_SAFETY_ANALYSIS // clang bug
Eric Laurent18b57012017-02-13 16:23:52 -080010402{
10403 ALOGV("%s", __FUNCTION__);
Atneya Nair97a73882023-10-30 20:26:21 -070010404 audio_utils::lock_guard l_{mutex()};
Eric Laurent18b57012017-02-13 16:23:52 -080010405
10406 if (mHalStream == 0) {
10407 return NO_INIT;
10408 }
Eric Tan39ec8d62018-07-24 09:49:29 -070010409 if (!mActiveTracks.isEmpty()) {
Eric Laurent18b57012017-02-13 16:23:52 -080010410 return INVALID_OPERATION;
10411 }
10412 mHalStream->standby();
Andy Hungcf10d742020-04-28 15:38:24 -070010413 if (!mStandby) {
10414 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -070010415 mThreadSnapshot.onEnd();
Andy Hungcf10d742020-04-28 15:38:24 -070010416 mStandby = true;
10417 }
Andy Hung3f49ebb2023-09-19 14:48:41 -070010418 releaseWakeLock_l();
Eric Laurent18b57012017-02-13 16:23:52 -080010419 return NO_ERROR;
10420}
10421
Andy Hungee58e4a2023-07-07 13:47:37 -070010422status_t MmapThread::reportData(const void* /*buffer*/, size_t /*frameCount*/) {
jiabinfc791ee2023-02-15 19:43:40 +000010423 // This is a stub implementation. The MmapPlaybackThread overrides this function.
10424 return INVALID_OPERATION;
10425}
10426
Andy Hungee58e4a2023-07-07 13:47:37 -070010427void MmapThread::readHalParameters_l()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010428{
10429 status_t result = mHalStream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
10430 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
10431 mFormat = mHALFormat;
10432 LOG_ALWAYS_FATAL_IF(!audio_is_linear_pcm(mFormat), "HAL format %#x is not linear pcm", mFormat);
10433 result = mHalStream->getFrameSize(&mFrameSize);
10434 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
Hayden Gomes1a89ab32020-06-12 11:05:47 -070010435 LOG_ALWAYS_FATAL_IF(mFrameSize <= 0, "Error frame size was %zu but must be greater than zero",
10436 mFrameSize);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010437 result = mHalStream->getBufferSize(&mBufferSize);
10438 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
10439 mFrameCount = mBufferSize / mFrameSize;
Andy Hungc2b11cb2020-04-22 09:04:01 -070010440
Andy Hungcf10d742020-04-28 15:38:24 -070010441 // TODO: make a readHalParameters call?
10442 mediametrics::LogItem item(mThreadMetrics.getMetricsId());
Andy Hungc2b11cb2020-04-22 09:04:01 -070010443 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
Andy Hung25a80ac2023-07-19 12:47:35 -070010444 .set(AMEDIAMETRICS_PROP_ENCODING, IAfThreadBase::formatToString(mFormat).c_str())
Andy Hungc2b11cb2020-04-22 09:04:01 -070010445 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
10446 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
10447 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
10448 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mFrameCount)
10449 /*
10450 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
10451 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELMASK,
10452 (int32_t)mHapticChannelMask)
10453 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELCOUNT,
10454 (int32_t)mHapticChannelCount)
10455 */
10456 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_ENCODING,
Andy Hung25a80ac2023-07-19 12:47:35 -070010457 IAfThreadBase::formatToString(mHALFormat).c_str())
Andy Hungc2b11cb2020-04-22 09:04:01 -070010458 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_FRAMECOUNT,
10459 (int32_t)mFrameCount) // sic - added HAL
10460 .record();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010461}
10462
Andy Hungee58e4a2023-07-07 13:47:37 -070010463bool MmapThread::threadLoop()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010464{
Andy Hungab65b182023-09-06 19:41:47 -070010465 {
10466 audio_utils::unique_lock _l(mutex());
10467 checkSilentMode_l();
10468 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010469
10470 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
10471
10472 while (!exitPending())
10473 {
Andy Hung116bc262023-06-20 18:56:17 -070010474 Vector<sp<IAfEffectChain>> effectChains;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010475
Andy Hung13850be2019-03-14 11:33:09 -070010476 { // under Thread lock
Andy Hungc5007f82023-08-29 14:26:09 -070010477 audio_utils::unique_lock _l(mutex());
Andy Hung13850be2019-03-14 11:33:09 -070010478
Eric Laurent6acd1d42017-01-04 14:23:29 -080010479 if (mSignalPending) {
10480 // A signal was raised while we were unlocked
10481 mSignalPending = false;
10482 } else {
10483 if (mConfigEvents.isEmpty()) {
10484 // we're about to wait, flush the binder command buffer
10485 IPCThreadState::self()->flushCommands();
10486
10487 if (exitPending()) {
10488 break;
10489 }
10490
Eric Laurent6acd1d42017-01-04 14:23:29 -080010491 // wait until we have something to do...
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +000010492 ALOGV("%s going to sleep", myName.c_str());
Andy Hungc5007f82023-08-29 14:26:09 -070010493 mWaitWorkCV.wait(_l);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +000010494 ALOGV("%s waking up", myName.c_str());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010495
10496 checkSilentMode_l();
10497
10498 continue;
10499 }
10500 }
10501
10502 processConfigEvents_l();
10503
10504 processVolume_l();
10505
10506 checkInvalidTracks_l();
10507
Andy Hungab65b182023-09-06 19:41:47 -070010508 mActiveTracks.updatePowerState_l(this);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010509
Kevin Rocard069c2712018-03-29 19:09:14 -070010510 updateMetadata_l();
10511
Eric Laurent6acd1d42017-01-04 14:23:29 -080010512 lockEffectChains_l(effectChains);
Andy Hung13850be2019-03-14 11:33:09 -070010513 } // release Thread lock
10514
Eric Laurent6acd1d42017-01-04 14:23:29 -080010515 for (size_t i = 0; i < effectChains.size(); i ++) {
Andy Hung13850be2019-03-14 11:33:09 -070010516 effectChains[i]->process_l(); // Thread is not locked, but effect chain is locked
Eric Laurent6acd1d42017-01-04 14:23:29 -080010517 }
Andy Hung13850be2019-03-14 11:33:09 -070010518
10519 // enable changes in effect chain, including moving to another thread.
Eric Laurent6acd1d42017-01-04 14:23:29 -080010520 unlockEffectChains(effectChains);
10521 // Effect chains will be actually deleted here if they were removed from
10522 // mEffectChains list during mixing or effects processing
10523 }
10524
10525 threadLoop_exit();
10526
10527 if (!mStandby) {
10528 threadLoop_standby();
10529 mStandby = true;
10530 }
10531
Eric Laurent6acd1d42017-01-04 14:23:29 -080010532 ALOGV("Thread %p type %d exiting", this, mType);
10533 return false;
10534}
10535
Andy Hungc5007f82023-08-29 14:26:09 -070010536// checkForNewParameter_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -070010537bool MmapThread::checkForNewParameter_l(const String8& keyValuePair,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010538 status_t& status)
10539{
10540 AudioParameter param = AudioParameter(keyValuePair);
10541 int value;
Eric Laurente6e9a482017-07-25 19:26:02 -070010542 bool sendToHal = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010543 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -070010544 LOG_FATAL("Should not happen set routing device in MmapThread");
Eric Laurent6acd1d42017-01-04 14:23:29 -080010545 }
Eric Laurente6e9a482017-07-25 19:26:02 -070010546 if (sendToHal) {
10547 status = mHalStream->setParameters(keyValuePair);
10548 } else {
10549 status = NO_ERROR;
10550 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010551
10552 return false;
10553}
10554
Andy Hungee58e4a2023-07-07 13:47:37 -070010555String8 MmapThread::getParameters(const String8& keys)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010556{
Andy Hung972bec12023-08-31 16:13:39 -070010557 audio_utils::lock_guard _l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010558 String8 out_s8;
10559 if (initCheck() == NO_ERROR && mHalStream->getParameters(keys, &out_s8) == OK) {
10560 return out_s8;
10561 }
Andy Hung920f6572022-10-06 12:09:49 -070010562 return {};
Eric Laurent6acd1d42017-01-04 14:23:29 -080010563}
10564
Andy Hungab65b182023-09-06 19:41:47 -070010565void MmapThread::ioConfigChanged_l(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -070010566 audio_port_handle_t portId __unused) {
Mikhail Naganov88536df2021-07-26 17:30:29 -070010567 sp<AudioIoDescriptor> desc;
10568 bool isInput = false;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010569 switch (event) {
10570 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -070010571 case AUDIO_INPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -080010572 case AUDIO_INPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -070010573 isInput = true;
10574 FALLTHROUGH_INTENDED;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010575 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -070010576 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -080010577 case AUDIO_OUTPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -070010578 desc = sp<AudioIoDescriptor>::make(mId, mPatch, isInput,
10579 mSampleRate, mFormat, mChannelMask, mFrameCount, mFrameCount);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010580 break;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010581 case AUDIO_INPUT_CLOSED:
10582 case AUDIO_OUTPUT_CLOSED:
10583 default:
Mikhail Naganov88536df2021-07-26 17:30:29 -070010584 desc = sp<AudioIoDescriptor>::make(mId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010585 break;
10586 }
Andy Hungab65b182023-09-06 19:41:47 -070010587 mAfThreadCallback->ioConfigChanged_l(event, desc, pid);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010588}
10589
Andy Hungee58e4a2023-07-07 13:47:37 -070010590status_t MmapThread::createAudioPatch_l(const struct audio_patch* patch,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010591 audio_patch_handle_t *handle)
Andy Hungc5007f82023-08-29 14:26:09 -070010592NO_THREAD_SAFETY_ANALYSIS // elease and re-acquire mutex()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010593{
10594 status_t status = NO_ERROR;
10595
10596 // store new device and send to effects
10597 audio_devices_t type = AUDIO_DEVICE_NONE;
10598 audio_port_handle_t deviceId;
jiabinc52b1ff2019-10-31 17:20:42 -070010599 AudioDeviceTypeAddrVector sinkDeviceTypeAddrs;
10600 AudioDeviceTypeAddr sourceDeviceTypeAddr;
10601 uint32_t numDevices = 0;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010602 if (isOutput()) {
10603 for (unsigned int i = 0; i < patch->num_sinks; i++) {
jiabinc52b1ff2019-10-31 17:20:42 -070010604 LOG_ALWAYS_FATAL_IF(popcount(patch->sinks[i].ext.device.type) > 1
10605 && !mAudioHwDev->supportsAudioPatches(),
10606 "Enumerated device type(%#x) must not be used "
10607 "as it does not support audio patches",
10608 patch->sinks[i].ext.device.type);
Mikhail Naganov55773032020-10-01 15:08:13 -070010609 type = static_cast<audio_devices_t>(type | patch->sinks[i].ext.device.type);
Andy Hung920f6572022-10-06 12:09:49 -070010610 sinkDeviceTypeAddrs.emplace_back(patch->sinks[i].ext.device.type,
10611 patch->sinks[i].ext.device.address);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010612 }
10613 deviceId = patch->sinks[0].id;
jiabinc52b1ff2019-10-31 17:20:42 -070010614 numDevices = mPatch.num_sinks;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010615 } else {
10616 type = patch->sources[0].ext.device.type;
10617 deviceId = patch->sources[0].id;
jiabinc52b1ff2019-10-31 17:20:42 -070010618 numDevices = mPatch.num_sources;
10619 sourceDeviceTypeAddr.mType = patch->sources[0].ext.device.type;
jiabin0a488932020-08-07 17:32:40 -070010620 sourceDeviceTypeAddr.setAddress(patch->sources[0].ext.device.address);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010621 }
10622
10623 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -080010624 if (isOutput()) {
10625 mEffectChains[i]->setDevices_l(sinkDeviceTypeAddrs);
10626 } else {
10627 mEffectChains[i]->setInputDevice_l(sourceDeviceTypeAddr);
10628 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010629 }
10630
jiabinc52b1ff2019-10-31 17:20:42 -070010631 if (!isOutput()) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010632 // store new source and send to effects
10633 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
10634 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
10635 for (size_t i = 0; i < mEffectChains.size(); i++) {
10636 mEffectChains[i]->setAudioSource_l(mAudioSource);
10637 }
10638 }
10639 }
10640
10641 if (mAudioHwDev->supportsAudioPatches()) {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010642 status = mHalDevice->createAudioPatch(patch->num_sources, patch->sources, patch->num_sinks,
10643 patch->sinks, handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010644 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010645 audio_port_config port;
10646 std::optional<audio_source_t> source;
10647 if (isOutput()) {
10648 port = patch->sinks[0];
Eric Laurent6acd1d42017-01-04 14:23:29 -080010649 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010650 port = patch->sources[0];
10651 source = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010652 }
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010653 status = mHalStream->legacyCreateAudioPatch(port, source, type);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010654 *handle = AUDIO_PATCH_HANDLE_NONE;
10655 }
10656
jiabinc52b1ff2019-10-31 17:20:42 -070010657 if (numDevices == 0 || mDeviceId != deviceId) {
10658 if (isOutput()) {
10659 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
10660 mOutDeviceTypeAddrs = sinkDeviceTypeAddrs;
jiabin0a957d32020-04-29 10:56:20 -070010661 checkSilentMode_l();
jiabinc52b1ff2019-10-31 17:20:42 -070010662 } else {
10663 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
10664 mInDeviceTypeAddr = sourceDeviceTypeAddr;
10665 }
Phil Burk7f6b40d2017-02-09 13:18:38 -080010666 sp<MmapStreamCallback> callback = mCallback.promote();
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010667 if (mDeviceId != deviceId && callback != 0) {
Andy Hungc5007f82023-08-29 14:26:09 -070010668 mutex().unlock();
Phil Burk7f6b40d2017-02-09 13:18:38 -080010669 callback->onRoutingChanged(deviceId);
Andy Hungc5007f82023-08-29 14:26:09 -070010670 mutex().lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010671 }
jiabinc52b1ff2019-10-31 17:20:42 -070010672 mPatch = *patch;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010673 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010674 }
Eric Laurentdda206a2022-07-08 17:28:35 +020010675 // Force meteadata update after a route change
10676 mActiveTracks.setHasChanged();
10677
Eric Laurent6acd1d42017-01-04 14:23:29 -080010678 return status;
10679}
10680
Andy Hungee58e4a2023-07-07 13:47:37 -070010681status_t MmapThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010682{
10683 status_t status = NO_ERROR;
10684
jiabinc52b1ff2019-10-31 17:20:42 -070010685 mPatch = audio_patch{};
10686 mOutDeviceTypeAddrs.clear();
10687 mInDeviceTypeAddr.reset();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010688
10689 bool supportsAudioPatches = mHalDevice->supportsAudioPatches(&supportsAudioPatches) == OK ?
10690 supportsAudioPatches : false;
10691
10692 if (supportsAudioPatches) {
10693 status = mHalDevice->releaseAudioPatch(handle);
10694 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010695 status = mHalStream->legacyReleaseAudioPatch();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010696 }
Eric Laurentdda206a2022-07-08 17:28:35 +020010697 // Force meteadata update after a route change
10698 mActiveTracks.setHasChanged();
10699
Eric Laurent6acd1d42017-01-04 14:23:29 -080010700 return status;
10701}
10702
Andy Hungee58e4a2023-07-07 13:47:37 -070010703void MmapThread::toAudioPortConfig(struct audio_port_config* config)
Andy Hung3f49ebb2023-09-19 14:48:41 -070010704NO_THREAD_SAFETY_ANALYSIS // mAudioHwDev handle access
Eric Laurent6acd1d42017-01-04 14:23:29 -080010705{
Mikhail Naganovdc769682018-05-04 15:34:08 -070010706 ThreadBase::toAudioPortConfig(config);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010707 if (isOutput()) {
10708 config->role = AUDIO_PORT_ROLE_SOURCE;
10709 config->ext.mix.hw_module = mAudioHwDev->handle();
10710 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
10711 } else {
10712 config->role = AUDIO_PORT_ROLE_SINK;
10713 config->ext.mix.hw_module = mAudioHwDev->handle();
10714 config->ext.mix.usecase.source = mAudioSource;
10715 }
10716}
10717
Andy Hungee58e4a2023-07-07 13:47:37 -070010718status_t MmapThread::addEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010719{
10720 audio_session_t session = chain->sessionId();
10721
10722 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
10723 // Attach all tracks with same session ID to this chain.
10724 // indicate all active tracks in the chain
Andy Hung8d31fd22023-06-26 19:20:57 -070010725 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010726 if (session == track->sessionId()) {
10727 chain->incTrackCnt();
10728 chain->incActiveTrackCnt();
10729 }
10730 }
10731
10732 chain->setThread(this);
10733 chain->setInBuffer(nullptr);
10734 chain->setOutBuffer(nullptr);
Shunkai Yaod125e402024-01-20 03:19:06 +000010735 chain->syncHalEffectsState_l();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010736
10737 mEffectChains.add(chain);
10738 checkSuspendOnAddEffectChain_l(chain);
10739 return NO_ERROR;
10740}
10741
Andy Hungee58e4a2023-07-07 13:47:37 -070010742size_t MmapThread::removeEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010743{
10744 audio_session_t session = chain->sessionId();
10745
10746 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
10747
10748 for (size_t i = 0; i < mEffectChains.size(); i++) {
10749 if (chain == mEffectChains[i]) {
10750 mEffectChains.removeAt(i);
10751 // detach all active tracks from the chain
10752 // detach all tracks with same session ID from this chain
Andy Hung8d31fd22023-06-26 19:20:57 -070010753 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010754 if (session == track->sessionId()) {
10755 chain->decActiveTrackCnt();
10756 chain->decTrackCnt();
10757 }
10758 }
10759 break;
10760 }
10761 }
10762 return mEffectChains.size();
10763}
10764
Andy Hungee58e4a2023-07-07 13:47:37 -070010765void MmapThread::threadLoop_standby()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010766{
10767 mHalStream->standby();
10768}
10769
Andy Hungee58e4a2023-07-07 13:47:37 -070010770void MmapThread::threadLoop_exit()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010771{
Phil Burk7dce7282017-09-27 13:51:41 -070010772 // Do not call callback->onTearDown() because it is redundant for thread exit
10773 // and because it can cause a recursive mutex lock on stop().
Eric Laurent6acd1d42017-01-04 14:23:29 -080010774}
10775
Andy Hungee58e4a2023-07-07 13:47:37 -070010776status_t MmapThread::setSyncEvent(const sp<SyncEvent>& /* event */)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010777{
10778 return BAD_VALUE;
10779}
10780
Andy Hungee58e4a2023-07-07 13:47:37 -070010781bool MmapThread::isValidSyncEvent(
10782 const sp<SyncEvent>& /* event */) const
Eric Laurent6acd1d42017-01-04 14:23:29 -080010783{
10784 return false;
10785}
10786
Andy Hungee58e4a2023-07-07 13:47:37 -070010787status_t MmapThread::checkEffectCompatibility_l(
Eric Laurent6acd1d42017-01-04 14:23:29 -080010788 const effect_descriptor_t *desc, audio_session_t sessionId)
10789{
10790 // No global effect sessions on mmap threads
Eric Laurent3f75a5b2019-11-12 15:55:51 -080010791 if (audio_is_global_session(sessionId)) {
10792 ALOGW("checkEffectCompatibility_l(): global effect %s on MMAP thread %s",
Eric Laurent6acd1d42017-01-04 14:23:29 -080010793 desc->name, mThreadName);
10794 return BAD_VALUE;
10795 }
10796
10797 if (!isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC)) {
10798 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on capture mmap thread",
10799 desc->name);
10800 return BAD_VALUE;
10801 }
10802 if (isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Glenn Kastend3bb6452016-12-05 18:14:37 -080010803 ALOGW("checkEffectCompatibility_l(): pre processing effect %s created on playback mmap "
10804 "thread", desc->name);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010805 return BAD_VALUE;
10806 }
10807
10808 // Only allow effects without processing load or latency
10809 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) != EFFECT_FLAG_NO_PROCESS) {
10810 return BAD_VALUE;
10811 }
10812
Andy Hung116bc262023-06-20 18:56:17 -070010813 if (IAfEffectModule::isHapticGenerator(&desc->type)) {
jiabineb3bda02020-06-30 14:07:03 -070010814 ALOGE("%s(): HapticGenerator is not supported for MmapThread", __func__);
10815 return BAD_VALUE;
10816 }
10817
Eric Laurent6acd1d42017-01-04 14:23:29 -080010818 return NO_ERROR;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010819}
10820
Andy Hungee58e4a2023-07-07 13:47:37 -070010821void MmapThread::checkInvalidTracks_l()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010822{
Eric Laurent039c24a2022-10-07 14:01:59 +020010823 sp<MmapStreamCallback> callback;
Andy Hung8d31fd22023-06-26 19:20:57 -070010824 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010825 if (track->isInvalid()) {
Eric Laurent039c24a2022-10-07 14:01:59 +020010826 callback = mCallback.promote();
10827 if (callback == nullptr && mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
10828 ALOGW("Could not notify MMAP stream tear down: no onRoutingChanged callback!");
10829 mNoCallbackWarningCount++;
10830 }
10831 break;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010832 }
10833 }
Eric Laurent039c24a2022-10-07 14:01:59 +020010834 if (callback != 0) {
Andy Hungc5007f82023-08-29 14:26:09 -070010835 mutex().unlock();
Eric Laurent039c24a2022-10-07 14:01:59 +020010836 callback->onRoutingChanged(AUDIO_PORT_HANDLE_NONE);
Andy Hungc5007f82023-08-29 14:26:09 -070010837 mutex().lock();
jiabindfa32482022-10-06 19:45:50 +000010838 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010839}
10840
Andy Hungee58e4a2023-07-07 13:47:37 -070010841void MmapThread::dumpInternals_l(int fd, const Vector<String16>& /* args */)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010842{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010843 dprintf(fd, " Attributes: content type %d usage %d source %d\n",
10844 mAttr.content_type, mAttr.usage, mAttr.source);
10845 dprintf(fd, " Session: %d port Id: %d\n", mSessionId, mPortId);
Eric Tan39ec8d62018-07-24 09:49:29 -070010846 if (mActiveTracks.isEmpty()) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010847 dprintf(fd, " No active clients\n");
10848 }
10849}
10850
Andy Hungee58e4a2023-07-07 13:47:37 -070010851void MmapThread::dumpTracks_l(int fd, const Vector<String16>& /* args */)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010852{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010853 String8 result;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010854 size_t numtracks = mActiveTracks.size();
Andy Hung2c6c3bb2017-06-16 14:01:45 -070010855 dprintf(fd, " %zu Tracks\n", numtracks);
10856 const char *prefix = " ";
Eric Laurent6acd1d42017-01-04 14:23:29 -080010857 if (numtracks) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -070010858 result.append(prefix);
Kevin Rocard5f2136e2018-05-11 22:03:00 -070010859 mActiveTracks[0]->appendDumpHeader(result);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010860 for (size_t i = 0; i < numtracks ; ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -070010861 sp<IAfMmapTrack> track = mActiveTracks[i];
Andy Hung2c6c3bb2017-06-16 14:01:45 -070010862 result.append(prefix);
10863 track->appendDump(result, true /* active */);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010864 }
10865 } else {
10866 dprintf(fd, "\n");
10867 }
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +000010868 write(fd, result.c_str(), result.size());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010869}
10870
Andy Hungee58e4a2023-07-07 13:47:37 -070010871/* static */
10872sp<IAfMmapPlaybackThread> IAfMmapPlaybackThread::create(
Andy Hung583043b2023-07-17 17:05:00 -070010873 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
Andy Hungee58e4a2023-07-07 13:47:37 -070010874 AudioHwDevice* hwDev, AudioStreamOut* output, bool systemReady) {
Andy Hung583043b2023-07-17 17:05:00 -070010875 return sp<MmapPlaybackThread>::make(afThreadCallback, id, hwDev, output, systemReady);
Andy Hungee58e4a2023-07-07 13:47:37 -070010876}
10877
10878MmapPlaybackThread::MmapPlaybackThread(
Andy Hung583043b2023-07-17 17:05:00 -070010879 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
jiabinc52b1ff2019-10-31 17:20:42 -070010880 AudioHwDevice *hwDev, AudioStreamOut *output, bool systemReady)
Andy Hung583043b2023-07-17 17:05:00 -070010881 : MmapThread(afThreadCallback, id, hwDev, output->stream, systemReady, true /* isOut */),
Eric Laurent6acd1d42017-01-04 14:23:29 -080010882 mStreamType(AUDIO_STREAM_MUSIC),
Phil Burk56ecf3e2018-03-12 15:38:17 -070010883 mOutput(output)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010884{
10885 snprintf(mThreadName, kThreadNameLength, "AudioMmapOut_%X", id);
10886 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Andy Hung583043b2023-07-17 17:05:00 -070010887 mMasterVolume = afThreadCallback->masterVolume_l();
10888 mMasterMute = afThreadCallback->masterMute_l();
Eric Laurent1f9b5e62023-07-03 18:14:07 +020010889
10890 for (int i = AUDIO_STREAM_MIN; i < AUDIO_STREAM_FOR_POLICY_CNT; ++i) {
10891 const audio_stream_type_t stream{static_cast<audio_stream_type_t>(i)};
10892 mStreamTypes[stream].volume = 0.0f;
Andy Hung583043b2023-07-17 17:05:00 -070010893 mStreamTypes[stream].mute = mAfThreadCallback->streamMute_l(stream);
Eric Laurent1f9b5e62023-07-03 18:14:07 +020010894 }
10895 // Audio patch and call assistant volume are always max
10896 mStreamTypes[AUDIO_STREAM_PATCH].volume = 1.0f;
10897 mStreamTypes[AUDIO_STREAM_PATCH].mute = false;
10898 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].volume = 1.0f;
10899 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].mute = false;
10900
Eric Laurent6acd1d42017-01-04 14:23:29 -080010901 if (mAudioHwDev) {
10902 if (mAudioHwDev->canSetMasterVolume()) {
10903 mMasterVolume = 1.0;
10904 }
10905
10906 if (mAudioHwDev->canSetMasterMute()) {
10907 mMasterMute = false;
10908 }
10909 }
10910}
10911
Andy Hungee58e4a2023-07-07 13:47:37 -070010912void MmapPlaybackThread::configure(const audio_attributes_t* attr,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010913 audio_stream_type_t streamType,
10914 audio_session_t sessionId,
10915 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010916 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010917 audio_port_handle_t portId)
10918{
Andy Hung8d672e02023-09-15 18:19:28 -070010919 audio_utils::lock_guard l(mutex());
10920 MmapThread::configure_l(attr, streamType, sessionId, callback, deviceId, portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010921 mStreamType = streamType;
10922}
10923
Andy Hungee58e4a2023-07-07 13:47:37 -070010924AudioStreamOut* MmapPlaybackThread::clearOutput()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010925{
Andy Hung972bec12023-08-31 16:13:39 -070010926 audio_utils::lock_guard _l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010927 AudioStreamOut *output = mOutput;
10928 mOutput = NULL;
10929 return output;
10930}
10931
Andy Hungee58e4a2023-07-07 13:47:37 -070010932void MmapPlaybackThread::setMasterVolume(float value)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010933{
Andy Hung972bec12023-08-31 16:13:39 -070010934 audio_utils::lock_guard _l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010935 // Don't apply master volume in SW if our HAL can do it for us.
10936 if (mAudioHwDev &&
10937 mAudioHwDev->canSetMasterVolume()) {
10938 mMasterVolume = 1.0;
10939 } else {
10940 mMasterVolume = value;
10941 }
10942}
10943
Andy Hungee58e4a2023-07-07 13:47:37 -070010944void MmapPlaybackThread::setMasterMute(bool muted)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010945{
Andy Hung972bec12023-08-31 16:13:39 -070010946 audio_utils::lock_guard _l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010947 // Don't apply master mute in SW if our HAL can do it for us.
10948 if (mAudioHwDev && mAudioHwDev->canSetMasterMute()) {
10949 mMasterMute = false;
10950 } else {
10951 mMasterMute = muted;
10952 }
10953}
10954
Andy Hungee58e4a2023-07-07 13:47:37 -070010955void MmapPlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010956{
Andy Hung972bec12023-08-31 16:13:39 -070010957 audio_utils::lock_guard _l(mutex());
Eric Laurent1f9b5e62023-07-03 18:14:07 +020010958 mStreamTypes[stream].volume = value;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010959 if (stream == mStreamType) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010960 broadcast_l();
10961 }
10962}
10963
Andy Hungee58e4a2023-07-07 13:47:37 -070010964float MmapPlaybackThread::streamVolume(audio_stream_type_t stream) const
Eric Laurent6acd1d42017-01-04 14:23:29 -080010965{
Andy Hung972bec12023-08-31 16:13:39 -070010966 audio_utils::lock_guard _l(mutex());
Eric Laurent1f9b5e62023-07-03 18:14:07 +020010967 return mStreamTypes[stream].volume;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010968}
10969
Andy Hungee58e4a2023-07-07 13:47:37 -070010970void MmapPlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010971{
Andy Hung972bec12023-08-31 16:13:39 -070010972 audio_utils::lock_guard _l(mutex());
Eric Laurent1f9b5e62023-07-03 18:14:07 +020010973 mStreamTypes[stream].mute = muted;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010974 if (stream == mStreamType) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010975 broadcast_l();
10976 }
10977}
10978
Andy Hungee58e4a2023-07-07 13:47:37 -070010979void MmapPlaybackThread::invalidateTracks(audio_stream_type_t streamType)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010980{
Andy Hung972bec12023-08-31 16:13:39 -070010981 audio_utils::lock_guard _l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010982 if (streamType == mStreamType) {
Andy Hung8d31fd22023-06-26 19:20:57 -070010983 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010984 track->invalidate();
10985 }
10986 broadcast_l();
10987 }
10988}
10989
Andy Hungee58e4a2023-07-07 13:47:37 -070010990void MmapPlaybackThread::invalidateTracks(std::set<audio_port_handle_t>& portIds)
jiabinc44b3462022-12-08 12:52:31 -080010991{
Andy Hung972bec12023-08-31 16:13:39 -070010992 audio_utils::lock_guard _l(mutex());
jiabinc44b3462022-12-08 12:52:31 -080010993 bool trackMatch = false;
Andy Hung8d31fd22023-06-26 19:20:57 -070010994 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
jiabinc44b3462022-12-08 12:52:31 -080010995 if (portIds.find(track->portId()) != portIds.end()) {
10996 track->invalidate();
10997 trackMatch = true;
10998 portIds.erase(track->portId());
10999 }
11000 if (portIds.empty()) {
11001 break;
11002 }
11003 }
11004 if (trackMatch) {
11005 broadcast_l();
11006 }
11007}
11008
Andy Hungee58e4a2023-07-07 13:47:37 -070011009void MmapPlaybackThread::processVolume_l()
Andy Hung920f6572022-10-06 12:09:49 -070011010NO_THREAD_SAFETY_ANALYSIS // access of track->processMuteEvent_l
Eric Laurent6acd1d42017-01-04 14:23:29 -080011011{
11012 float volume;
11013
Eric Laurent1f9b5e62023-07-03 18:14:07 +020011014 if (mMasterMute || streamMuted_l()) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080011015 volume = 0;
11016 } else {
Eric Laurent1f9b5e62023-07-03 18:14:07 +020011017 volume = mMasterVolume * streamVolume_l();
Eric Laurent6acd1d42017-01-04 14:23:29 -080011018 }
11019
11020 if (volume != mHalVolFloat) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080011021 // Convert volumes from float to 8.24
11022 uint32_t vol = (uint32_t)(volume * (1 << 24));
11023
11024 // Delegate volume control to effect in track effect chain if needed
11025 // only one effect chain can be present on DirectOutputThread, so if
11026 // there is one, the track is connected to it
11027 if (!mEffectChains.isEmpty()) {
Shunkai Yaof4847652024-01-12 00:25:20 +000011028 mEffectChains[0]->setVolume(&vol, &vol);
Eric Laurent6acd1d42017-01-04 14:23:29 -080011029 volume = (float)vol / (1 << 24);
11030 }
Eric Laurentdff774a2017-04-21 15:29:38 -070011031 // Try to use HW volume control and fall back to SW control if not implemented
Phil Burk56ecf3e2018-03-12 15:38:17 -070011032 if (mOutput->stream->setVolume(volume, volume) == NO_ERROR) {
11033 mHalVolFloat = volume; // HW volume control worked, so update value.
11034 mNoCallbackWarningCount = 0;
11035 } else {
Eric Laurentdff774a2017-04-21 15:29:38 -070011036 sp<MmapStreamCallback> callback = mCallback.promote();
11037 if (callback != 0) {
Phil Burk56ecf3e2018-03-12 15:38:17 -070011038 mHalVolFloat = volume; // SW volume control worked, so update value.
11039 mNoCallbackWarningCount = 0;
Andy Hungc5007f82023-08-29 14:26:09 -070011040 mutex().unlock();
Robert Wu4389ae62022-02-17 18:39:41 +000011041 callback->onVolumeChanged(volume);
Andy Hungc5007f82023-08-29 14:26:09 -070011042 mutex().lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080011043 } else {
Phil Burk56ecf3e2018-03-12 15:38:17 -070011044 if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
11045 ALOGW("Could not set MMAP stream volume: no volume callback!");
11046 mNoCallbackWarningCount++;
11047 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080011048 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080011049 }
Andy Hung8d31fd22023-06-26 19:20:57 -070011050 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Jasmine Chaeaa10e42021-05-11 10:11:14 +080011051 track->setMetadataHasChanged();
Andy Hung583043b2023-07-17 17:05:00 -070011052 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
Vlad Popaec1788e2022-08-04 11:23:30 +020011053 /*muteState=*/{mMasterMute,
Eric Laurent1f9b5e62023-07-03 18:14:07 +020011054 streamVolume_l() == 0.f,
11055 streamMuted_l(),
Vlad Popaec1788e2022-08-04 11:23:30 +020011056 // TODO(b/241533526): adjust logic to include mute from AppOps
11057 false /*muteFromPlaybackRestricted*/,
11058 false /*muteFromClientVolume*/,
11059 false /*muteFromVolumeShaper*/});
Jasmine Chaeaa10e42021-05-11 10:11:14 +080011060 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080011061 }
11062}
11063
Andy Hungee58e4a2023-07-07 13:47:37 -070011064ThreadBase::MetadataUpdate MmapPlaybackThread::updateMetadata_l()
Kevin Rocard069c2712018-03-29 19:09:14 -070011065{
Jasmine Chaeaa10e42021-05-11 10:11:14 +080011066 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
Vlad Popa7e81cea2023-01-19 16:34:16 +010011067 return {}; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -070011068 }
11069 StreamOutHalInterface::SourceMetadata metadata;
Andy Hung8d31fd22023-06-26 19:20:57 -070011070 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Kevin Rocard069c2712018-03-29 19:09:14 -070011071 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurent94579172020-11-20 18:41:04 +010011072 playback_track_metadata_v7_t trackMetadata;
11073 trackMetadata.base = {
Kevin Rocard069c2712018-03-29 19:09:14 -070011074 .usage = track->attributes().usage,
11075 .content_type = track->attributes().content_type,
11076 .gain = mHalVolFloat, // TODO: propagate from aaudio pre-mix volume
Eric Laurent94579172020-11-20 18:41:04 +010011077 };
11078 trackMetadata.channel_mask = track->channelMask(),
11079 strncpy(trackMetadata.tags, track->attributes().tags, AUDIO_ATTRIBUTES_TAGS_MAX_SIZE);
11080 metadata.tracks.push_back(trackMetadata);
Kevin Rocard069c2712018-03-29 19:09:14 -070011081 }
11082 mOutput->stream->updateSourceMetadata(metadata);
Vlad Popa7e81cea2023-01-19 16:34:16 +010011083
11084 MetadataUpdate change;
11085 change.playbackMetadataUpdate = metadata.tracks;
11086 return change;
11087};
Kevin Rocard069c2712018-03-29 19:09:14 -070011088
Andy Hungee58e4a2023-07-07 13:47:37 -070011089void MmapPlaybackThread::checkSilentMode_l()
Eric Laurent6acd1d42017-01-04 14:23:29 -080011090{
11091 if (!mMasterMute) {
11092 char value[PROPERTY_VALUE_MAX];
11093 if (property_get("ro.audio.silent", value, "0") > 0) {
11094 char *endptr;
11095 unsigned long ul = strtoul(value, &endptr, 0);
11096 if (*endptr == '\0' && ul != 0) {
11097 ALOGD("Silence is golden");
11098 // The setprop command will not allow a property to be changed after
11099 // the first time it is set, so we don't have to worry about un-muting.
11100 setMasterMute_l(true);
11101 }
11102 }
11103 }
11104}
11105
Andy Hungee58e4a2023-07-07 13:47:37 -070011106void MmapPlaybackThread::toAudioPortConfig(struct audio_port_config* config)
Mikhail Naganov32abc2b2018-05-24 12:57:11 -070011107{
11108 MmapThread::toAudioPortConfig(config);
11109 if (mOutput && mOutput->flags != AUDIO_OUTPUT_FLAG_NONE) {
11110 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
11111 config->flags.output = mOutput->flags;
11112 }
11113}
11114
Andy Hungee58e4a2023-07-07 13:47:37 -070011115status_t MmapPlaybackThread::getExternalPosition(uint64_t* position,
Andy Hung440901d2023-06-29 21:19:25 -070011116 int64_t* timeNanos) const
jiabinb7d8c5a2020-08-26 17:24:52 -070011117{
11118 if (mOutput == nullptr) {
11119 return NO_INIT;
11120 }
11121 struct timespec timestamp;
11122 status_t status = mOutput->getPresentationPosition(position, &timestamp);
11123 if (status == NO_ERROR) {
11124 *timeNanos = timestamp.tv_sec * NANOS_PER_SECOND + timestamp.tv_nsec;
11125 }
11126 return status;
11127}
11128
Andy Hungee58e4a2023-07-07 13:47:37 -070011129status_t MmapPlaybackThread::reportData(const void* buffer, size_t frameCount) {
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010011130 // Send to MelProcessor for sound dose measurement.
11131 auto processor = mMelProcessor.load();
11132 if (processor) {
11133 processor->process(buffer, frameCount * mFrameSize);
11134 }
11135
jiabinfc791ee2023-02-15 19:43:40 +000011136 return NO_ERROR;
11137}
11138
Andy Hungc5007f82023-08-29 14:26:09 -070011139// startMelComputation_l() must be called with AudioFlinger::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -070011140void MmapPlaybackThread::startMelComputation_l(
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010011141 const sp<audio_utils::MelProcessor>& processor)
11142{
11143 ALOGV("%s: starting mel processor for thread %d", __func__, id());
Vlad Popa1c2f7e12023-03-28 02:08:56 +020011144 mMelProcessor.store(processor);
11145 if (processor) {
11146 processor->resume();
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010011147 }
Vlad Popa1c2f7e12023-03-28 02:08:56 +020011148
11149 // no need to update output format for MMapPlaybackThread since it is
11150 // assigned constant for each thread
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010011151}
11152
Andy Hungc5007f82023-08-29 14:26:09 -070011153// stopMelComputation_l() must be called with AudioFlinger::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -070011154void MmapPlaybackThread::stopMelComputation_l()
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010011155{
Vlad Popa1c2f7e12023-03-28 02:08:56 +020011156 ALOGV("%s: pausing mel processor for thread %d", __func__, id());
11157 auto melProcessor = mMelProcessor.load();
11158 if (melProcessor != nullptr) {
11159 melProcessor->pause();
11160 }
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010011161}
11162
Andy Hungee58e4a2023-07-07 13:47:37 -070011163void MmapPlaybackThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent6acd1d42017-01-04 14:23:29 -080011164{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -070011165 MmapThread::dumpInternals_l(fd, args);
Eric Laurent6acd1d42017-01-04 14:23:29 -080011166
Glenn Kastend3bb6452016-12-05 18:14:37 -080011167 dprintf(fd, " Stream type: %d Stream volume: %f HAL volume: %f Stream mute %d\n",
Eric Laurent1f9b5e62023-07-03 18:14:07 +020011168 mStreamType, streamVolume_l(), mHalVolFloat, streamMuted_l());
Eric Laurent6acd1d42017-01-04 14:23:29 -080011169 dprintf(fd, " Master volume: %f Master mute %d\n", mMasterVolume, mMasterMute);
11170}
11171
Andy Hungee58e4a2023-07-07 13:47:37 -070011172/* static */
11173sp<IAfMmapCaptureThread> IAfMmapCaptureThread::create(
Andy Hung583043b2023-07-17 17:05:00 -070011174 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
Andy Hungee58e4a2023-07-07 13:47:37 -070011175 AudioHwDevice* hwDev, AudioStreamIn* input, bool systemReady) {
Andy Hung583043b2023-07-17 17:05:00 -070011176 return sp<MmapCaptureThread>::make(afThreadCallback, id, hwDev, input, systemReady);
Andy Hungee58e4a2023-07-07 13:47:37 -070011177}
11178
11179MmapCaptureThread::MmapCaptureThread(
Andy Hung583043b2023-07-17 17:05:00 -070011180 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
jiabinc52b1ff2019-10-31 17:20:42 -070011181 AudioHwDevice *hwDev, AudioStreamIn *input, bool systemReady)
Andy Hung583043b2023-07-17 17:05:00 -070011182 : MmapThread(afThreadCallback, id, hwDev, input->stream, systemReady, false /* isOut */),
Eric Laurent6acd1d42017-01-04 14:23:29 -080011183 mInput(input)
11184{
11185 snprintf(mThreadName, kThreadNameLength, "AudioMmapIn_%X", id);
11186 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
11187}
11188
Andy Hungee58e4a2023-07-07 13:47:37 -070011189status_t MmapCaptureThread::exitStandby_l()
Eric Laurent331679c2018-04-16 17:03:16 -070011190{
Phil Burkf054fc32018-12-06 09:45:59 -080011191 {
11192 // mInput might have been cleared by clearInput()
Phil Burkf054fc32018-12-06 09:45:59 -080011193 if (mInput != nullptr && mInput->stream != nullptr) {
11194 mInput->stream->setGain(1.0f);
11195 }
11196 }
Eric Laurentdda206a2022-07-08 17:28:35 +020011197 return MmapThread::exitStandby_l();
Eric Laurent331679c2018-04-16 17:03:16 -070011198}
11199
Andy Hungee58e4a2023-07-07 13:47:37 -070011200AudioStreamIn* MmapCaptureThread::clearInput()
Eric Laurent6acd1d42017-01-04 14:23:29 -080011201{
Andy Hung972bec12023-08-31 16:13:39 -070011202 audio_utils::lock_guard _l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080011203 AudioStreamIn *input = mInput;
11204 mInput = NULL;
11205 return input;
11206}
Kevin Rocard069c2712018-03-29 19:09:14 -070011207
Andy Hungee58e4a2023-07-07 13:47:37 -070011208void MmapCaptureThread::processVolume_l()
Eric Laurent331679c2018-04-16 17:03:16 -070011209{
11210 bool changed = false;
11211 bool silenced = false;
11212
11213 sp<MmapStreamCallback> callback = mCallback.promote();
11214 if (callback == 0) {
11215 if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
11216 ALOGW("Could not set MMAP stream silenced: no onStreamSilenced callback!");
11217 mNoCallbackWarningCount++;
11218 }
11219 }
11220
11221 // After a change occurred in track silenced state, mute capture in audio DSP if at least one
11222 // track is silenced and unmute otherwise
11223 for (size_t i = 0; i < mActiveTracks.size() && !silenced; i++) {
11224 if (!mActiveTracks[i]->getAndSetSilencedNotified_l()) {
11225 changed = true;
11226 silenced = mActiveTracks[i]->isSilenced_l();
11227 }
11228 }
11229
11230 if (changed) {
11231 mInput->stream->setGain(silenced ? 0.0f: 1.0f);
11232 }
11233}
11234
Andy Hungee58e4a2023-07-07 13:47:37 -070011235ThreadBase::MetadataUpdate MmapCaptureThread::updateMetadata_l()
Kevin Rocard069c2712018-03-29 19:09:14 -070011236{
Jasmine Chaeaa10e42021-05-11 10:11:14 +080011237 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
Vlad Popa7e81cea2023-01-19 16:34:16 +010011238 return {}; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -070011239 }
11240 StreamInHalInterface::SinkMetadata metadata;
Andy Hung8d31fd22023-06-26 19:20:57 -070011241 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Kevin Rocard069c2712018-03-29 19:09:14 -070011242 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurent94579172020-11-20 18:41:04 +010011243 record_track_metadata_v7_t trackMetadata;
11244 trackMetadata.base = {
Kevin Rocard069c2712018-03-29 19:09:14 -070011245 .source = track->attributes().source,
11246 .gain = 1, // capture tracks do not have volumes
Eric Laurent94579172020-11-20 18:41:04 +010011247 };
11248 trackMetadata.channel_mask = track->channelMask(),
11249 strncpy(trackMetadata.tags, track->attributes().tags, AUDIO_ATTRIBUTES_TAGS_MAX_SIZE);
11250 metadata.tracks.push_back(trackMetadata);
Kevin Rocard069c2712018-03-29 19:09:14 -070011251 }
11252 mInput->stream->updateSinkMetadata(metadata);
Vlad Popa7e81cea2023-01-19 16:34:16 +010011253 MetadataUpdate change;
11254 change.recordMetadataUpdate = metadata.tracks;
11255 return change;
Kevin Rocard069c2712018-03-29 19:09:14 -070011256}
11257
Andy Hungee58e4a2023-07-07 13:47:37 -070011258void MmapCaptureThread::setRecordSilenced(audio_port_handle_t portId, bool silenced)
Eric Laurent331679c2018-04-16 17:03:16 -070011259{
Andy Hung972bec12023-08-31 16:13:39 -070011260 audio_utils::lock_guard _l(mutex());
Eric Laurent331679c2018-04-16 17:03:16 -070011261 for (size_t i = 0; i < mActiveTracks.size() ; i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -070011262 if (mActiveTracks[i]->portId() == portId) {
Eric Laurent331679c2018-04-16 17:03:16 -070011263 mActiveTracks[i]->setSilenced_l(silenced);
11264 broadcast_l();
11265 }
11266 }
jiabin09609032022-06-15 19:26:01 +000011267 setClientSilencedIfExists_l(portId, silenced);
Eric Laurent331679c2018-04-16 17:03:16 -070011268}
11269
Andy Hungee58e4a2023-07-07 13:47:37 -070011270void MmapCaptureThread::toAudioPortConfig(struct audio_port_config* config)
Mikhail Naganov32abc2b2018-05-24 12:57:11 -070011271{
11272 MmapThread::toAudioPortConfig(config);
11273 if (mInput && mInput->flags != AUDIO_INPUT_FLAG_NONE) {
11274 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
11275 config->flags.input = mInput->flags;
11276 }
11277}
11278
Andy Hungee58e4a2023-07-07 13:47:37 -070011279status_t MmapCaptureThread::getExternalPosition(
Andy Hung440901d2023-06-29 21:19:25 -070011280 uint64_t* position, int64_t* timeNanos) const
jiabinb7d8c5a2020-08-26 17:24:52 -070011281{
11282 if (mInput == nullptr) {
11283 return NO_INIT;
11284 }
11285 return mInput->getCapturePosition((int64_t*)position, timeNanos);
11286}
11287
jiabinc658e452022-10-21 20:52:21 +000011288// ----------------------------------------------------------------------------
11289
Andy Hungee58e4a2023-07-07 13:47:37 -070011290/* static */
11291sp<IAfPlaybackThread> IAfPlaybackThread::createBitPerfectThread(
Andy Hung583043b2023-07-17 17:05:00 -070011292 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hungee58e4a2023-07-07 13:47:37 -070011293 AudioStreamOut* output, audio_io_handle_t id, bool systemReady) {
Andy Hung583043b2023-07-17 17:05:00 -070011294 return sp<BitPerfectThread>::make(afThreadCallback, output, id, systemReady);
Andy Hungee58e4a2023-07-07 13:47:37 -070011295}
11296
Andy Hung583043b2023-07-17 17:05:00 -070011297BitPerfectThread::BitPerfectThread(const sp<IAfThreadCallback> &afThreadCallback,
jiabinc658e452022-10-21 20:52:21 +000011298 AudioStreamOut *output, audio_io_handle_t id, bool systemReady)
Andy Hung583043b2023-07-17 17:05:00 -070011299 : MixerThread(afThreadCallback, output, id, systemReady, BIT_PERFECT) {}
jiabinc658e452022-10-21 20:52:21 +000011300
Andy Hungee58e4a2023-07-07 13:47:37 -070011301PlaybackThread::mixer_state BitPerfectThread::prepareTracks_l(
Andy Hung8d31fd22023-06-26 19:20:57 -070011302 Vector<sp<IAfTrack>>* tracksToRemove) {
jiabinc658e452022-10-21 20:52:21 +000011303 mixer_state result = MixerThread::prepareTracks_l(tracksToRemove);
11304 // If there is only one active track and it is bit-perfect, enable tee buffer.
jiabin76d94692022-12-15 21:51:21 +000011305 float volumeLeft = 1.0f;
11306 float volumeRight = 1.0f;
jiabinc658e452022-10-21 20:52:21 +000011307 if (mActiveTracks.size() == 1 && mActiveTracks[0]->isBitPerfect()) {
11308 const int trackId = mActiveTracks[0]->id();
11309 mAudioMixer->setParameter(
11310 trackId, AudioMixer::TRACK, AudioMixer::TEE_BUFFER, (void *)mSinkBuffer);
11311 mAudioMixer->setParameter(
11312 trackId, AudioMixer::TRACK, AudioMixer::TEE_BUFFER_FRAME_COUNT,
11313 (void *)(uintptr_t)mNormalFrameCount);
jiabin76d94692022-12-15 21:51:21 +000011314 mActiveTracks[0]->getFinalVolume(&volumeLeft, &volumeRight);
jiabinc658e452022-10-21 20:52:21 +000011315 mIsBitPerfect = true;
11316 } else {
11317 mIsBitPerfect = false;
11318 // No need to copy bit-perfect data directly to sink buffer given there are multiple tracks
11319 // active.
11320 for (const auto& track : mActiveTracks) {
11321 const int trackId = track->id();
11322 mAudioMixer->setParameter(
11323 trackId, AudioMixer::TRACK, AudioMixer::TEE_BUFFER, nullptr);
11324 }
11325 }
jiabin76d94692022-12-15 21:51:21 +000011326 if (mVolumeLeft != volumeLeft || mVolumeRight != volumeRight) {
11327 mVolumeLeft = volumeLeft;
11328 mVolumeRight = volumeRight;
11329 setVolumeForOutput_l(volumeLeft, volumeRight);
11330 }
jiabinc658e452022-10-21 20:52:21 +000011331 return result;
11332}
11333
Andy Hungee58e4a2023-07-07 13:47:37 -070011334void BitPerfectThread::threadLoop_mix() {
jiabinc658e452022-10-21 20:52:21 +000011335 MixerThread::threadLoop_mix();
11336 mHasDataCopiedToSinkBuffer = mIsBitPerfect;
11337}
11338
Glenn Kasten63238ef2015-03-02 15:50:29 -080011339} // namespace android