blob: 4e422efb0b4caedc0927e19f3c05279c5f00f11d [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 Hungc5007f82023-08-29 14:26:09 -0700725 if (event->mCondition.wait_for(_l, std::chrono::nanoseconds(kConfigEventTimeoutNs))
726 == std::cv_status::timeout) {
Eric Laurent10351942014-05-08 18:49:52 -0700727 event->mStatus = TIMED_OUT;
728 event->mWaitStatus = false;
729 }
730 }
731 status = event->mStatus;
Eric Laurent81784c32012-11-19 14:55:58 -0800732 }
Andy Hungc5007f82023-08-29 14:26:09 -0700733 mutex().lock();
Eric Laurent81784c32012-11-19 14:55:58 -0800734 return status;
735}
736
Andy Hungee58e4a2023-07-07 13:47:37 -0700737void ThreadBase::sendIoConfigEvent(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -0700738 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -0800739{
Andy Hung972bec12023-08-31 16:13:39 -0700740 audio_utils::lock_guard _l(mutex());
Eric Laurent09f1ed22019-04-24 17:45:17 -0700741 sendIoConfigEvent_l(event, pid, portId);
Eric Laurent81784c32012-11-19 14:55:58 -0800742}
743
Andy Hungc5007f82023-08-29 14:26:09 -0700744// sendIoConfigEvent_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -0700745void ThreadBase::sendIoConfigEvent_l(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -0700746 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -0800747{
Andy Hungd0979812019-02-21 15:51:44 -0800748 // The audio statistics history is exponentially weighted to forget events
749 // about five or more seconds in the past. In order to have
750 // crisper statistics for mediametrics, we reset the statistics on
751 // an IoConfigEvent, to reflect different properties for a new device.
752 mIoJitterMs.reset();
753 mLatencyMs.reset();
754 mProcessTimeMs.reset();
Robert Wu06db0a32021-08-10 19:05:34 +0000755 mMonopipePipeDepthStats.reset();
Dean Wheatley12473e92021-03-18 23:00:55 +1100756 mTimestampVerifier.discontinuity(mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS);
Andy Hungd0979812019-02-21 15:51:44 -0800757
Eric Laurent09f1ed22019-04-24 17:45:17 -0700758 sp<ConfigEvent> configEvent = (ConfigEvent *)new IoConfigEvent(event, pid, portId);
Eric Laurent10351942014-05-08 18:49:52 -0700759 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800760}
761
Andy Hungee58e4a2023-07-07 13:47:37 -0700762void ThreadBase::sendPrioConfigEvent(pid_t pid, pid_t tid, int32_t prio, bool forApp)
Eric Laurent72e3f392015-05-20 14:43:50 -0700763{
Andy Hung972bec12023-08-31 16:13:39 -0700764 audio_utils::lock_guard _l(mutex());
Mikhail Naganov83f04272017-02-07 10:45:09 -0800765 sendPrioConfigEvent_l(pid, tid, prio, forApp);
Eric Laurent72e3f392015-05-20 14:43:50 -0700766}
767
Andy Hungc5007f82023-08-29 14:26:09 -0700768// sendPrioConfigEvent_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -0700769void ThreadBase::sendPrioConfigEvent_l(
Mikhail Naganov83f04272017-02-07 10:45:09 -0800770 pid_t pid, pid_t tid, int32_t prio, bool forApp)
Eric Laurent81784c32012-11-19 14:55:58 -0800771{
Mikhail Naganov83f04272017-02-07 10:45:09 -0800772 sp<ConfigEvent> configEvent = (ConfigEvent *)new PrioConfigEvent(pid, tid, prio, forApp);
Eric Laurent10351942014-05-08 18:49:52 -0700773 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800774}
775
Andy Hungc5007f82023-08-29 14:26:09 -0700776// sendSetParameterConfigEvent_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -0700777status_t ThreadBase::sendSetParameterConfigEvent_l(const String8& keyValuePair)
Eric Laurent81784c32012-11-19 14:55:58 -0800778{
Andy Hung2ddee192015-12-18 17:34:44 -0800779 sp<ConfigEvent> configEvent;
780 AudioParameter param(keyValuePair);
781 int value;
Mikhail Naganov00260b52016-10-13 12:54:24 -0700782 if (param.getInt(String8(AudioParameter::keyMonoOutput), value) == NO_ERROR) {
Andy Hung2ddee192015-12-18 17:34:44 -0800783 setMasterMono_l(value != 0);
784 if (param.size() == 1) {
785 return NO_ERROR; // should be a solo parameter - we don't pass down
786 }
Mikhail Naganov00260b52016-10-13 12:54:24 -0700787 param.remove(String8(AudioParameter::keyMonoOutput));
Andy Hung2ddee192015-12-18 17:34:44 -0800788 configEvent = new SetParameterConfigEvent(param.toString());
789 } else {
790 configEvent = new SetParameterConfigEvent(keyValuePair);
791 }
Eric Laurent10351942014-05-08 18:49:52 -0700792 return sendConfigEvent_l(configEvent);
Glenn Kastenf7773312013-08-13 16:00:42 -0700793}
794
Andy Hungee58e4a2023-07-07 13:47:37 -0700795status_t ThreadBase::sendCreateAudioPatchConfigEvent(
Eric Laurent1c333e22014-05-20 10:48:17 -0700796 const struct audio_patch *patch,
797 audio_patch_handle_t *handle)
798{
Andy Hung972bec12023-08-31 16:13:39 -0700799 audio_utils::lock_guard _l(mutex());
Eric Laurent1c333e22014-05-20 10:48:17 -0700800 sp<ConfigEvent> configEvent = (ConfigEvent *)new CreateAudioPatchConfigEvent(*patch, *handle);
801 status_t status = sendConfigEvent_l(configEvent);
802 if (status == NO_ERROR) {
803 CreateAudioPatchConfigEventData *data =
804 (CreateAudioPatchConfigEventData *)configEvent->mData.get();
805 *handle = data->mHandle;
806 }
807 return status;
808}
809
Andy Hungee58e4a2023-07-07 13:47:37 -0700810status_t ThreadBase::sendReleaseAudioPatchConfigEvent(
Eric Laurent1c333e22014-05-20 10:48:17 -0700811 const audio_patch_handle_t handle)
812{
Andy Hung972bec12023-08-31 16:13:39 -0700813 audio_utils::lock_guard _l(mutex());
Eric Laurent1c333e22014-05-20 10:48:17 -0700814 sp<ConfigEvent> configEvent = (ConfigEvent *)new ReleaseAudioPatchConfigEvent(handle);
815 return sendConfigEvent_l(configEvent);
816}
817
Andy Hungee58e4a2023-07-07 13:47:37 -0700818status_t ThreadBase::sendUpdateOutDeviceConfigEvent(
jiabinc52b1ff2019-10-31 17:20:42 -0700819 const DeviceDescriptorBaseVector& outDevices)
820{
821 if (type() != RECORD) {
822 // The update out device operation is only for record thread.
823 return INVALID_OPERATION;
824 }
Andy Hung972bec12023-08-31 16:13:39 -0700825 audio_utils::lock_guard _l(mutex());
jiabinc52b1ff2019-10-31 17:20:42 -0700826 sp<ConfigEvent> configEvent = (ConfigEvent *)new UpdateOutDevicesConfigEvent(outDevices);
827 return sendConfigEvent_l(configEvent);
828}
829
Andy Hungee58e4a2023-07-07 13:47:37 -0700830void ThreadBase::sendResizeBufferConfigEvent_l(int32_t maxSharedAudioHistoryMs)
Eric Laurentec376dc2021-04-08 20:41:22 +0200831{
832 ALOG_ASSERT(type() == RECORD, "sendResizeBufferConfigEvent_l() called on non record thread");
833 sp<ConfigEvent> configEvent =
834 (ConfigEvent *)new ResizeBufferConfigEvent(maxSharedAudioHistoryMs);
835 sendConfigEvent_l(configEvent);
836}
Eric Laurent1c333e22014-05-20 10:48:17 -0700837
Andy Hungee58e4a2023-07-07 13:47:37 -0700838void ThreadBase::sendCheckOutputStageEffectsEvent()
Eric Laurentb3f315a2021-07-13 15:09:05 +0200839{
Andy Hung972bec12023-08-31 16:13:39 -0700840 audio_utils::lock_guard _l(mutex());
Eric Laurentb3f315a2021-07-13 15:09:05 +0200841 sendCheckOutputStageEffectsEvent_l();
842}
843
Andy Hungee58e4a2023-07-07 13:47:37 -0700844void ThreadBase::sendCheckOutputStageEffectsEvent_l()
Eric Laurentb3f315a2021-07-13 15:09:05 +0200845{
846 sp<ConfigEvent> configEvent =
847 (ConfigEvent *)new CheckOutputStageEffectsEvent();
848 sendConfigEvent_l(configEvent);
849}
850
Andy Hungee58e4a2023-07-07 13:47:37 -0700851void ThreadBase::sendHalLatencyModesChangedEvent_l()
Eric Laurent68a40a82022-05-03 18:15:04 +0200852{
853 sp<ConfigEvent> configEvent = sp<HalLatencyModesChangedEvent>::make();
854 sendConfigEvent_l(configEvent);
855}
856
Glenn Kasten2cfbf882013-08-14 13:12:11 -0700857// post condition: mConfigEvents.isEmpty()
Andy Hungee58e4a2023-07-07 13:47:37 -0700858void ThreadBase::processConfigEvents_l()
Glenn Kastenf7773312013-08-13 16:00:42 -0700859{
Eric Laurent10351942014-05-08 18:49:52 -0700860 bool configChanged = false;
861
Eric Laurent81784c32012-11-19 14:55:58 -0800862 while (!mConfigEvents.isEmpty()) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700863 ALOGV("processConfigEvents_l() remaining events %zu", mConfigEvents.size());
Eric Laurent10351942014-05-08 18:49:52 -0700864 sp<ConfigEvent> event = mConfigEvents[0];
Eric Laurent81784c32012-11-19 14:55:58 -0800865 mConfigEvents.removeAt(0);
Eric Laurent10351942014-05-08 18:49:52 -0700866 switch (event->mType) {
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700867 case CFG_EVENT_PRIO: {
Eric Laurent10351942014-05-08 18:49:52 -0700868 PrioConfigEventData *data = (PrioConfigEventData *)event->mData.get();
869 // FIXME Need to understand why this has to be done asynchronously
Mikhail Naganov83f04272017-02-07 10:45:09 -0800870 int err = requestPriority(data->mPid, data->mTid, data->mPrio, data->mForApp,
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700871 true /*asynchronous*/);
872 if (err != 0) {
873 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Eric Laurent10351942014-05-08 18:49:52 -0700874 data->mPrio, data->mPid, data->mTid, err);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700875 }
876 } break;
877 case CFG_EVENT_IO: {
Eric Laurent10351942014-05-08 18:49:52 -0700878 IoConfigEventData *data = (IoConfigEventData *)event->mData.get();
Andy Hungab65b182023-09-06 19:41:47 -0700879 ioConfigChanged_l(data->mEvent, data->mPid, data->mPortId);
Eric Laurent10351942014-05-08 18:49:52 -0700880 } break;
881 case CFG_EVENT_SET_PARAMETER: {
882 SetParameterConfigEventData *data = (SetParameterConfigEventData *)event->mData.get();
883 if (checkForNewParameter_l(data->mKeyValuePairs, event->mStatus)) {
884 configChanged = true;
Andy Hung293558a2017-03-21 12:19:20 -0700885 mLocalLog.log("CFG_EVENT_SET_PARAMETER: (%s) configuration changed",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +0000886 data->mKeyValuePairs.c_str());
Glenn Kastend5418eb2013-08-14 13:11:06 -0700887 }
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700888 } break;
Eric Laurent1c333e22014-05-20 10:48:17 -0700889 case CFG_EVENT_CREATE_AUDIO_PATCH: {
Andy Hungab65b182023-09-06 19:41:47 -0700890 const DeviceTypeSet oldDevices = getDeviceTypes_l();
Eric Laurent1c333e22014-05-20 10:48:17 -0700891 CreateAudioPatchConfigEventData *data =
892 (CreateAudioPatchConfigEventData *)event->mData.get();
893 event->mStatus = createAudioPatch_l(&data->mPatch, &data->mHandle);
Andy Hungab65b182023-09-06 19:41:47 -0700894 const DeviceTypeSet newDevices = getDeviceTypes_l();
Eric Laurent52568142022-10-28 11:23:28 +0200895 configChanged = oldDevices != newDevices;
jiabinc52b1ff2019-10-31 17:20:42 -0700896 mLocalLog.log("CFG_EVENT_CREATE_AUDIO_PATCH: old device %s (%s) new device %s (%s)",
897 dumpDeviceTypes(oldDevices).c_str(), toString(oldDevices).c_str(),
898 dumpDeviceTypes(newDevices).c_str(), toString(newDevices).c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -0700899 } break;
900 case CFG_EVENT_RELEASE_AUDIO_PATCH: {
Andy Hungab65b182023-09-06 19:41:47 -0700901 const DeviceTypeSet oldDevices = getDeviceTypes_l();
Eric Laurent1c333e22014-05-20 10:48:17 -0700902 ReleaseAudioPatchConfigEventData *data =
903 (ReleaseAudioPatchConfigEventData *)event->mData.get();
904 event->mStatus = releaseAudioPatch_l(data->mHandle);
Andy Hungab65b182023-09-06 19:41:47 -0700905 const DeviceTypeSet newDevices = getDeviceTypes_l();
Eric Laurent52568142022-10-28 11:23:28 +0200906 configChanged = oldDevices != newDevices;
jiabinc52b1ff2019-10-31 17:20:42 -0700907 mLocalLog.log("CFG_EVENT_RELEASE_AUDIO_PATCH: old device %s (%s) new device %s (%s)",
908 dumpDeviceTypes(oldDevices).c_str(), toString(oldDevices).c_str(),
909 dumpDeviceTypes(newDevices).c_str(), toString(newDevices).c_str());
910 } break;
911 case CFG_EVENT_UPDATE_OUT_DEVICE: {
912 UpdateOutDevicesConfigEventData *data =
913 (UpdateOutDevicesConfigEventData *)event->mData.get();
914 updateOutDevices(data->mOutDevices);
Eric Laurent1c333e22014-05-20 10:48:17 -0700915 } break;
Eric Laurentec376dc2021-04-08 20:41:22 +0200916 case CFG_EVENT_RESIZE_BUFFER: {
917 ResizeBufferConfigEventData *data =
918 (ResizeBufferConfigEventData *)event->mData.get();
919 resizeInputBuffer_l(data->mMaxSharedAudioHistoryMs);
920 } break;
Eric Laurentb3f315a2021-07-13 15:09:05 +0200921
922 case CFG_EVENT_CHECK_OUTPUT_STAGE_EFFECTS: {
923 setCheckOutputStageEffects();
924 } break;
925
Eric Laurent68a40a82022-05-03 18:15:04 +0200926 case CFG_EVENT_HAL_LATENCY_MODES_CHANGED: {
927 onHalLatencyModesChanged_l();
928 } break;
929
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700930 default:
Eric Laurent10351942014-05-08 18:49:52 -0700931 ALOG_ASSERT(false, "processConfigEvents_l() unknown event type %d", event->mType);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700932 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800933 }
Eric Laurent10351942014-05-08 18:49:52 -0700934 {
Andy Hung972bec12023-08-31 16:13:39 -0700935 audio_utils::lock_guard _l(event->mutex());
Eric Laurent10351942014-05-08 18:49:52 -0700936 if (event->mWaitStatus) {
937 event->mWaitStatus = false;
Andy Hungc5007f82023-08-29 14:26:09 -0700938 event->mCondition.notify_one();
Eric Laurent10351942014-05-08 18:49:52 -0700939 }
940 }
941 ALOGV_IF(mConfigEvents.isEmpty(), "processConfigEvents_l() DONE thread %p", this);
942 }
943
944 if (configChanged) {
945 cacheParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800946 }
Eric Laurent81784c32012-11-19 14:55:58 -0800947}
948
Marco Nelissenb2208842014-02-07 14:00:50 -0800949String8 channelMaskToString(audio_channel_mask_t mask, bool output) {
950 String8 s;
Glenn Kastene1635ec2015-06-08 15:46:49 -0700951 const audio_channel_representation_t representation =
952 audio_channel_mask_get_representation(mask);
Andy Hungf98ec8d2015-05-19 12:53:24 -0700953
954 switch (representation) {
jiabin245cdd92018-12-07 17:55:15 -0800955 // Travel all single bit channel mask to convert channel mask to string.
Andy Hungf98ec8d2015-05-19 12:53:24 -0700956 case AUDIO_CHANNEL_REPRESENTATION_POSITION: {
957 if (output) {
958 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT) s.append("front-left, ");
959 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT) s.append("front-right, ");
960 if (mask & AUDIO_CHANNEL_OUT_FRONT_CENTER) s.append("front-center, ");
Andy Hungfba71252021-05-07 11:58:32 -0700961 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY) s.append("low-frequency, ");
Andy Hungf98ec8d2015-05-19 12:53:24 -0700962 if (mask & AUDIO_CHANNEL_OUT_BACK_LEFT) s.append("back-left, ");
963 if (mask & AUDIO_CHANNEL_OUT_BACK_RIGHT) s.append("back-right, ");
964 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT_OF_CENTER) s.append("front-left-of-center, ");
965 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT_OF_CENTER) s.append("front-right-of-center, ");
966 if (mask & AUDIO_CHANNEL_OUT_BACK_CENTER) s.append("back-center, ");
967 if (mask & AUDIO_CHANNEL_OUT_SIDE_LEFT) s.append("side-left, ");
968 if (mask & AUDIO_CHANNEL_OUT_SIDE_RIGHT) s.append("side-right, ");
969 if (mask & AUDIO_CHANNEL_OUT_TOP_CENTER) s.append("top-center ,");
970 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_LEFT) s.append("top-front-left, ");
971 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_CENTER) s.append("top-front-center, ");
972 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_RIGHT) s.append("top-front-right, ");
973 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_LEFT) s.append("top-back-left, ");
Andy Hungae81b4c2021-05-07 08:54:28 -0700974 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_CENTER) s.append("top-back-center, ");
975 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_RIGHT) s.append("top-back-right, ");
976 if (mask & AUDIO_CHANNEL_OUT_TOP_SIDE_LEFT) s.append("top-side-left, ");
977 if (mask & AUDIO_CHANNEL_OUT_TOP_SIDE_RIGHT) s.append("top-side-right, ");
978 if (mask & AUDIO_CHANNEL_OUT_BOTTOM_FRONT_LEFT) s.append("bottom-front-left, ");
979 if (mask & AUDIO_CHANNEL_OUT_BOTTOM_FRONT_CENTER) s.append("bottom-front-center, ");
980 if (mask & AUDIO_CHANNEL_OUT_BOTTOM_FRONT_RIGHT) s.append("bottom-front-right, ");
Andy Hungfba71252021-05-07 11:58:32 -0700981 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY_2) s.append("low-frequency-2, ");
Andy Hungae81b4c2021-05-07 08:54:28 -0700982 if (mask & AUDIO_CHANNEL_OUT_HAPTIC_B) s.append("haptic-B, ");
983 if (mask & AUDIO_CHANNEL_OUT_HAPTIC_A) s.append("haptic-A, ");
Andy Hungf98ec8d2015-05-19 12:53:24 -0700984 if (mask & ~AUDIO_CHANNEL_OUT_ALL) s.append("unknown, ");
985 } else {
986 if (mask & AUDIO_CHANNEL_IN_LEFT) s.append("left, ");
987 if (mask & AUDIO_CHANNEL_IN_RIGHT) s.append("right, ");
988 if (mask & AUDIO_CHANNEL_IN_FRONT) s.append("front, ");
989 if (mask & AUDIO_CHANNEL_IN_BACK) s.append("back, ");
990 if (mask & AUDIO_CHANNEL_IN_LEFT_PROCESSED) s.append("left-processed, ");
991 if (mask & AUDIO_CHANNEL_IN_RIGHT_PROCESSED) s.append("right-processed, ");
992 if (mask & AUDIO_CHANNEL_IN_FRONT_PROCESSED) s.append("front-processed, ");
993 if (mask & AUDIO_CHANNEL_IN_BACK_PROCESSED) s.append("back-processed, ");
994 if (mask & AUDIO_CHANNEL_IN_PRESSURE) s.append("pressure, ");
995 if (mask & AUDIO_CHANNEL_IN_X_AXIS) s.append("X, ");
996 if (mask & AUDIO_CHANNEL_IN_Y_AXIS) s.append("Y, ");
997 if (mask & AUDIO_CHANNEL_IN_Z_AXIS) s.append("Z, ");
Mikhail Naganovc9948492018-05-10 17:25:28 -0700998 if (mask & AUDIO_CHANNEL_IN_BACK_LEFT) s.append("back-left, ");
999 if (mask & AUDIO_CHANNEL_IN_BACK_RIGHT) s.append("back-right, ");
1000 if (mask & AUDIO_CHANNEL_IN_CENTER) s.append("center, ");
Andy Hungfba71252021-05-07 11:58:32 -07001001 if (mask & AUDIO_CHANNEL_IN_LOW_FREQUENCY) s.append("low-frequency, ");
Andy Hungae81b4c2021-05-07 08:54:28 -07001002 if (mask & AUDIO_CHANNEL_IN_TOP_LEFT) s.append("top-left, ");
1003 if (mask & AUDIO_CHANNEL_IN_TOP_RIGHT) s.append("top-right, ");
Andy Hungf98ec8d2015-05-19 12:53:24 -07001004 if (mask & AUDIO_CHANNEL_IN_VOICE_UPLINK) s.append("voice-uplink, ");
1005 if (mask & AUDIO_CHANNEL_IN_VOICE_DNLINK) s.append("voice-dnlink, ");
1006 if (mask & ~AUDIO_CHANNEL_IN_ALL) s.append("unknown, ");
1007 }
1008 const int len = s.length();
1009 if (len > 2) {
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07001010 (void) s.lockBuffer(len); // needed?
Andy Hungf98ec8d2015-05-19 12:53:24 -07001011 s.unlockBuffer(len - 2); // remove trailing ", "
1012 }
1013 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -08001014 }
Andy Hungf98ec8d2015-05-19 12:53:24 -07001015 case AUDIO_CHANNEL_REPRESENTATION_INDEX:
1016 s.appendFormat("index mask, bits:%#x", audio_channel_mask_get_bits(mask));
1017 return s;
1018 default:
1019 s.appendFormat("unknown mask, representation:%d bits:%#x",
1020 representation, audio_channel_mask_get_bits(mask));
1021 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -08001022 }
Marco Nelissenb2208842014-02-07 14:00:50 -08001023}
1024
Andy Hungee58e4a2023-07-07 13:47:37 -07001025void ThreadBase::dump(int fd, const Vector<String16>& args)
Andy Hung920f6572022-10-06 12:09:49 -07001026NO_THREAD_SAFETY_ANALYSIS // conditional try lock
Eric Laurent81784c32012-11-19 14:55:58 -08001027{
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08001028 dprintf(fd, "\n%s thread %p, name %s, tid %d, type %d (%s):\n", isOutput() ? "Output" : "Input",
1029 this, mThreadName, getTid(), type(), threadTypeToString(type()));
1030
Andy Hungc5007f82023-08-29 14:26:09 -07001031 const bool locked = afutils::dumpTryLock(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001032 if (!locked) {
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08001033 dprintf(fd, " Thread may be deadlocked\n");
Eric Laurent81784c32012-11-19 14:55:58 -08001034 }
1035
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001036 dumpBase_l(fd, args);
1037 dumpInternals_l(fd, args);
1038 dumpTracks_l(fd, args);
1039 dumpEffectChains_l(fd, args);
1040
1041 if (locked) {
Andy Hungc5007f82023-08-29 14:26:09 -07001042 mutex().unlock();
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001043 }
1044
1045 dprintf(fd, " Local log:\n");
1046 mLocalLog.dump(fd, " " /* prefix */, 40 /* lines */);
Andy Hungafc51db2022-04-08 17:33:40 -07001047
1048 // --all does the statistics
1049 bool dumpAll = false;
1050 for (const auto &arg : args) {
1051 if (arg == String16("--all")) {
1052 dumpAll = true;
1053 }
1054 }
1055 if (dumpAll || type() == SPATIALIZER) {
Andy Hung44d648b2022-04-08 17:33:40 -07001056 const std::string sched = mThreadSnapshot.toString();
Andy Hungafc51db2022-04-08 17:33:40 -07001057 if (!sched.empty()) {
1058 (void)write(fd, sched.c_str(), sched.size());
1059 }
1060 }
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001061}
1062
Andy Hungee58e4a2023-07-07 13:47:37 -07001063void ThreadBase::dumpBase_l(int fd, const Vector<String16>& /* args */)
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001064{
Elliott Hughes87cebad2014-05-22 10:14:43 -07001065 dprintf(fd, " I/O handle: %d\n", mId);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001066 dprintf(fd, " Standby: %s\n", mStandby ? "yes" : "no");
Glenn Kasten97b7b752014-09-28 13:04:24 -07001067 dprintf(fd, " Sample rate: %u Hz\n", mSampleRate);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001068 dprintf(fd, " HAL frame count: %zu\n", mFrameCount);
Andy Hung25a80ac2023-07-19 12:47:35 -07001069 dprintf(fd, " HAL format: 0x%x (%s)\n", mHALFormat,
1070 IAfThreadBase::formatToString(mHALFormat).c_str());
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001071 dprintf(fd, " HAL buffer size: %zu bytes\n", mBufferSize);
Glenn Kasten97b7b752014-09-28 13:04:24 -07001072 dprintf(fd, " Channel count: %u\n", mChannelCount);
1073 dprintf(fd, " Channel mask: 0x%08x (%s)\n", mChannelMask,
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00001074 channelMaskToString(mChannelMask, mType != RECORD).c_str());
Andy Hung25a80ac2023-07-19 12:47:35 -07001075 dprintf(fd, " Processing format: 0x%x (%s)\n", mFormat,
1076 IAfThreadBase::formatToString(mFormat).c_str());
Glenn Kastenf87c2f52015-08-21 08:03:57 -07001077 dprintf(fd, " Processing frame size: %zu bytes\n", mFrameSize);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001078 dprintf(fd, " Pending config events:");
Marco Nelissenb2208842014-02-07 14:00:50 -08001079 size_t numConfig = mConfigEvents.size();
1080 if (numConfig) {
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001081 const size_t SIZE = 256;
1082 char buffer[SIZE];
Marco Nelissenb2208842014-02-07 14:00:50 -08001083 for (size_t i = 0; i < numConfig; i++) {
1084 mConfigEvents[i]->dump(buffer, SIZE);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001085 dprintf(fd, "\n %s", buffer);
Marco Nelissenb2208842014-02-07 14:00:50 -08001086 }
Elliott Hughes87cebad2014-05-22 10:14:43 -07001087 dprintf(fd, "\n");
Marco Nelissenb2208842014-02-07 14:00:50 -08001088 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07001089 dprintf(fd, " none\n");
Eric Laurent81784c32012-11-19 14:55:58 -08001090 }
Andy Hung293558a2017-03-21 12:19:20 -07001091 // Note: output device may be used by capture threads for effects such as AEC.
jiabinc52b1ff2019-10-31 17:20:42 -07001092 dprintf(fd, " Output devices: %s (%s)\n",
Andy Hungab65b182023-09-06 19:41:47 -07001093 dumpDeviceTypes(outDeviceTypes_l()).c_str(), toString(outDeviceTypes_l()).c_str());
jiabinc52b1ff2019-10-31 17:20:42 -07001094 dprintf(fd, " Input device: %#x (%s)\n",
Andy Hungab65b182023-09-06 19:41:47 -07001095 inDeviceType_l(), toString(inDeviceType_l()).c_str());
Andy Hung9b181952019-02-25 14:53:36 -08001096 dprintf(fd, " Audio source: %d (%s)\n", mAudioSource, toString(mAudioSource).c_str());
Eric Laurent81784c32012-11-19 14:55:58 -08001097
Andy Hung2e2c0bb2018-06-11 19:13:11 -07001098 // Dump timestamp statistics for the Thread types that support it.
1099 if (mType == RECORD
1100 || mType == MIXER
1101 || mType == DUPLICATING
Andy Hungf3234512018-07-03 14:51:47 -07001102 || mType == DIRECT
Andy Hung4b7f54f2022-04-28 17:45:28 -07001103 || mType == OFFLOAD
1104 || mType == SPATIALIZER) {
Andy Hung2e2c0bb2018-06-11 19:13:11 -07001105 dprintf(fd, " Timestamp stats: %s\n", mTimestampVerifier.toString().c_str());
Andy Hungab65b182023-09-06 19:41:47 -07001106 dprintf(fd, " Timestamp corrected: %s\n",
1107 isTimestampCorrectionEnabled_l() ? "yes" : "no");
Andy Hung2e2c0bb2018-06-11 19:13:11 -07001108 }
1109
Andy Hung446f4df2019-02-21 12:26:41 -08001110 if (mLastIoBeginNs > 0) { // MMAP may not set this
1111 dprintf(fd, " Last %s occurred (msecs): %lld\n",
1112 isOutput() ? "write" : "read",
1113 (long long) (systemTime() - mLastIoBeginNs) / NANOS_PER_MILLISECOND);
1114 }
1115
1116 if (mProcessTimeMs.getN() > 0) {
1117 dprintf(fd, " Process time ms stats: %s\n", mProcessTimeMs.toString().c_str());
1118 }
1119
1120 if (mIoJitterMs.getN() > 0) {
1121 dprintf(fd, " Hal %s jitter ms stats: %s\n",
1122 isOutput() ? "write" : "read",
1123 mIoJitterMs.toString().c_str());
1124 }
1125
Andy Hunge6c37112019-02-26 17:38:10 -08001126 if (mLatencyMs.getN() > 0) {
1127 dprintf(fd, " Threadloop %s latency stats: %s\n",
1128 isOutput() ? "write" : "read",
1129 mLatencyMs.toString().c_str());
1130 }
Robert Wu06db0a32021-08-10 19:05:34 +00001131
1132 if (mMonopipePipeDepthStats.getN() > 0) {
1133 dprintf(fd, " Monopipe %s pipe depth stats: %s\n",
1134 isOutput() ? "write" : "read",
1135 mMonopipePipeDepthStats.toString().c_str());
1136 }
Eric Laurent81784c32012-11-19 14:55:58 -08001137}
1138
Andy Hungee58e4a2023-07-07 13:47:37 -07001139void ThreadBase::dumpEffectChains_l(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -08001140{
1141 const size_t SIZE = 256;
1142 char buffer[SIZE];
Eric Laurent81784c32012-11-19 14:55:58 -08001143
Marco Nelissenb2208842014-02-07 14:00:50 -08001144 size_t numEffectChains = mEffectChains.size();
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +00001145 snprintf(buffer, SIZE, " %zu Effect Chains\n", numEffectChains);
Eric Laurent81784c32012-11-19 14:55:58 -08001146 write(fd, buffer, strlen(buffer));
1147
Marco Nelissenb2208842014-02-07 14:00:50 -08001148 for (size_t i = 0; i < numEffectChains; ++i) {
Andy Hung116bc262023-06-20 18:56:17 -07001149 sp<IAfEffectChain> chain = mEffectChains[i];
Eric Laurent81784c32012-11-19 14:55:58 -08001150 if (chain != 0) {
1151 chain->dump(fd, args);
1152 }
1153 }
1154}
1155
Andy Hungee58e4a2023-07-07 13:47:37 -07001156void ThreadBase::acquireWakeLock()
Eric Laurent81784c32012-11-19 14:55:58 -08001157{
Andy Hung972bec12023-08-31 16:13:39 -07001158 audio_utils::lock_guard _l(mutex());
Andy Hungdae27702016-10-31 14:01:16 -07001159 acquireWakeLock_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001160}
1161
Andy Hungee58e4a2023-07-07 13:47:37 -07001162String16 ThreadBase::getWakeLockTag()
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001163{
1164 switch (mType) {
Glenn Kastenbcb14862015-03-05 17:11:21 -08001165 case MIXER:
1166 return String16("AudioMix");
1167 case DIRECT:
1168 return String16("AudioDirectOut");
1169 case DUPLICATING:
1170 return String16("AudioDup");
1171 case RECORD:
1172 return String16("AudioIn");
1173 case OFFLOAD:
1174 return String16("AudioOffload");
Andy Hungea840382020-05-05 21:50:17 -07001175 case MMAP_PLAYBACK:
1176 return String16("MmapPlayback");
1177 case MMAP_CAPTURE:
1178 return String16("MmapCapture");
Eric Laurent1c5e2e32021-08-18 18:50:28 +02001179 case SPATIALIZER:
1180 return String16("AudioSpatial");
Glenn Kastenbcb14862015-03-05 17:11:21 -08001181 default:
1182 ALOG_ASSERT(false);
1183 return String16("AudioUnknown");
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001184 }
1185}
1186
Andy Hungee58e4a2023-07-07 13:47:37 -07001187void ThreadBase::acquireWakeLock_l()
Eric Laurent81784c32012-11-19 14:55:58 -08001188{
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001189 getPowerManager_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001190 if (mPowerManager != 0) {
1191 sp<IBinder> binder = new BBinder();
Andy Hungdae27702016-10-31 14:01:16 -07001192 // Uses AID_AUDIOSERVER for wakelock. updateWakeLockUids_l() updates with client uids.
Chris Ye6597d732020-02-28 22:38:25 -08001193 binder::Status status = mPowerManager->acquireWakeLockAsync(binder,
1194 POWERMANAGER_PARTIAL_WAKE_LOCK,
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001195 getWakeLockTag(),
Marco Nelissendcb346b2015-09-09 10:47:29 -07001196 String16("audioserver"),
Chris Ye6597d732020-02-28 22:38:25 -08001197 {} /* workSource */,
1198 {} /* historyTag */);
1199 if (status.isOk()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001200 mWakeLockToken = binder;
1201 }
Chris Ye6597d732020-02-28 22:38:25 -08001202 ALOGV("acquireWakeLock_l() %s status %d", mThreadName, status.exceptionCode());
Eric Laurent81784c32012-11-19 14:55:58 -08001203 }
Wei Jia3f273d12015-11-24 09:06:49 -08001204
Andy Hung3f0c9022016-01-15 17:49:46 -08001205 gBoottime.acquire(mWakeLockToken);
Andy Hung818e7a32016-02-16 18:08:07 -08001206 mTimestamp.mTimebaseOffset[ExtendedTimestamp::TIMEBASE_BOOTTIME] =
1207 gBoottime.getBoottimeOffset();
Eric Laurent81784c32012-11-19 14:55:58 -08001208}
1209
Andy Hungee58e4a2023-07-07 13:47:37 -07001210void ThreadBase::releaseWakeLock()
Eric Laurent81784c32012-11-19 14:55:58 -08001211{
Andy Hung972bec12023-08-31 16:13:39 -07001212 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001213 releaseWakeLock_l();
1214}
1215
Andy Hungee58e4a2023-07-07 13:47:37 -07001216void ThreadBase::releaseWakeLock_l()
Eric Laurent81784c32012-11-19 14:55:58 -08001217{
Andy Hung3f0c9022016-01-15 17:49:46 -08001218 gBoottime.release(mWakeLockToken);
Eric Laurent81784c32012-11-19 14:55:58 -08001219 if (mWakeLockToken != 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -08001220 ALOGV("releaseWakeLock_l() %s", mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08001221 if (mPowerManager != 0) {
Chris Ye6597d732020-02-28 22:38:25 -08001222 mPowerManager->releaseWakeLockAsync(mWakeLockToken, 0);
Eric Laurent81784c32012-11-19 14:55:58 -08001223 }
1224 mWakeLockToken.clear();
1225 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001226}
1227
Andy Hungee58e4a2023-07-07 13:47:37 -07001228void ThreadBase::getPowerManager_l() {
Eric Laurent72e3f392015-05-20 14:43:50 -07001229 if (mSystemReady && mPowerManager == 0) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001230 // use checkService() to avoid blocking if power service is not up yet
1231 sp<IBinder> binder =
1232 defaultServiceManager()->checkService(String16("power"));
1233 if (binder == 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -08001234 ALOGW("Thread %s cannot connect to the power manager service", mThreadName);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001235 } else {
Chris Ye6597d732020-02-28 22:38:25 -08001236 mPowerManager = interface_cast<os::IPowerManager>(binder);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001237 binder->linkToDeath(mDeathRecipient);
1238 }
1239 }
1240}
1241
Andy Hungee58e4a2023-07-07 13:47:37 -07001242void ThreadBase::updateWakeLockUids_l(const SortedVector<uid_t>& uids) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001243 getPowerManager_l();
Andy Hungdae27702016-10-31 14:01:16 -07001244
1245#if !LOG_NDEBUG
1246 std::stringstream s;
Andy Hungd01b0f12016-11-07 16:10:30 -08001247 for (uid_t uid : uids) {
Andy Hungdae27702016-10-31 14:01:16 -07001248 s << uid << " ";
1249 }
1250 ALOGD("updateWakeLockUids_l %s uids:%s", mThreadName, s.str().c_str());
1251#endif
1252
Andy Hung438e7572015-12-14 15:51:17 -08001253 if (mWakeLockToken == NULL) { // token may be NULL if AudioFlinger::systemReady() not called.
1254 if (mSystemReady) {
1255 ALOGE("no wake lock to update, but system ready!");
1256 } else {
1257 ALOGW("no wake lock to update, system not ready yet");
1258 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001259 return;
1260 }
1261 if (mPowerManager != 0) {
Andy Hung1f12a8a2016-11-07 16:10:30 -08001262 std::vector<int> uidsAsInt(uids.begin(), uids.end()); // powermanager expects uids as ints
Chris Ye6597d732020-02-28 22:38:25 -08001263 binder::Status status = mPowerManager->updateWakeLockUidsAsync(
1264 mWakeLockToken, uidsAsInt);
1265 ALOGV("updateWakeLockUids_l() %s status %d", mThreadName, status.exceptionCode());
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001266 }
1267}
1268
Andy Hungee58e4a2023-07-07 13:47:37 -07001269void ThreadBase::clearPowerManager()
Eric Laurent81784c32012-11-19 14:55:58 -08001270{
Andy Hung972bec12023-08-31 16:13:39 -07001271 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001272 releaseWakeLock_l();
1273 mPowerManager.clear();
1274}
1275
Andy Hungee58e4a2023-07-07 13:47:37 -07001276void ThreadBase::updateOutDevices(
jiabinc52b1ff2019-10-31 17:20:42 -07001277 const DeviceDescriptorBaseVector& outDevices __unused)
1278{
1279 ALOGE("%s should only be called in RecordThread", __func__);
1280}
1281
Andy Hungee58e4a2023-07-07 13:47:37 -07001282void ThreadBase::resizeInputBuffer_l(int32_t /* maxSharedAudioHistoryMs */)
Eric Laurentec376dc2021-04-08 20:41:22 +02001283{
1284 ALOGE("%s should only be called in RecordThread", __func__);
1285}
1286
Andy Hungee58e4a2023-07-07 13:47:37 -07001287void ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& /* who */)
Eric Laurent81784c32012-11-19 14:55:58 -08001288{
1289 sp<ThreadBase> thread = mThread.promote();
1290 if (thread != 0) {
1291 thread->clearPowerManager();
1292 }
1293 ALOGW("power manager service died !!!");
1294}
1295
Andy Hungee58e4a2023-07-07 13:47:37 -07001296void ThreadBase::setEffectSuspended_l(
Glenn Kastend848eb42016-03-08 13:42:11 -08001297 const effect_uuid_t *type, bool suspend, audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001298{
Andy Hung116bc262023-06-20 18:56:17 -07001299 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08001300 if (chain != 0) {
1301 if (type != NULL) {
1302 chain->setEffectSuspended_l(type, suspend);
1303 } else {
1304 chain->setEffectSuspendedAll_l(suspend);
1305 }
1306 }
1307
1308 updateSuspendedSessions_l(type, suspend, sessionId);
1309}
1310
Andy Hungee58e4a2023-07-07 13:47:37 -07001311void ThreadBase::checkSuspendOnAddEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08001312{
1313 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
1314 if (index < 0) {
1315 return;
1316 }
1317
1318 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
1319 mSuspendedSessions.valueAt(index);
1320
1321 for (size_t i = 0; i < sessionEffects.size(); i++) {
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07001322 const sp<SuspendedSessionDesc>& desc = sessionEffects.valueAt(i);
Eric Laurent81784c32012-11-19 14:55:58 -08001323 for (int j = 0; j < desc->mRefCount; j++) {
Andy Hung116bc262023-06-20 18:56:17 -07001324 if (sessionEffects.keyAt(i) == IAfEffectChain::kKeyForSuspendAll) {
Eric Laurent81784c32012-11-19 14:55:58 -08001325 chain->setEffectSuspendedAll_l(true);
1326 } else {
1327 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
1328 desc->mType.timeLow);
1329 chain->setEffectSuspended_l(&desc->mType, true);
1330 }
1331 }
1332 }
1333}
1334
Andy Hungee58e4a2023-07-07 13:47:37 -07001335void ThreadBase::updateSuspendedSessions_l(const effect_uuid_t* type,
Eric Laurent81784c32012-11-19 14:55:58 -08001336 bool suspend,
Glenn Kastend848eb42016-03-08 13:42:11 -08001337 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001338{
1339 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
1340
1341 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1342
1343 if (suspend) {
1344 if (index >= 0) {
1345 sessionEffects = mSuspendedSessions.valueAt(index);
1346 } else {
1347 mSuspendedSessions.add(sessionId, sessionEffects);
1348 }
1349 } else {
1350 if (index < 0) {
1351 return;
1352 }
1353 sessionEffects = mSuspendedSessions.valueAt(index);
1354 }
1355
1356
Andy Hung116bc262023-06-20 18:56:17 -07001357 int key = IAfEffectChain::kKeyForSuspendAll;
Eric Laurent81784c32012-11-19 14:55:58 -08001358 if (type != NULL) {
1359 key = type->timeLow;
1360 }
1361 index = sessionEffects.indexOfKey(key);
1362
1363 sp<SuspendedSessionDesc> desc;
1364 if (suspend) {
1365 if (index >= 0) {
1366 desc = sessionEffects.valueAt(index);
1367 } else {
1368 desc = new SuspendedSessionDesc();
1369 if (type != NULL) {
1370 desc->mType = *type;
1371 }
1372 sessionEffects.add(key, desc);
1373 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
1374 }
1375 desc->mRefCount++;
1376 } else {
1377 if (index < 0) {
1378 return;
1379 }
1380 desc = sessionEffects.valueAt(index);
1381 if (--desc->mRefCount == 0) {
1382 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
1383 sessionEffects.removeItemsAt(index);
1384 if (sessionEffects.isEmpty()) {
1385 ALOGV("updateSuspendedSessions_l() restore removing session %d",
1386 sessionId);
1387 mSuspendedSessions.removeItem(sessionId);
1388 }
1389 }
1390 }
1391 if (!sessionEffects.isEmpty()) {
1392 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1393 }
1394}
1395
Andy Hungee58e4a2023-07-07 13:47:37 -07001396void ThreadBase::checkSuspendOnEffectEnabled(bool enabled,
Eric Laurent6b446ce2019-12-13 10:56:31 -08001397 audio_session_t sessionId,
Andy Hung920f6572022-10-06 12:09:49 -07001398 bool threadLocked)
1399NO_THREAD_SAFETY_ANALYSIS // manual locking
1400{
Eric Laurent6b446ce2019-12-13 10:56:31 -08001401 if (!threadLocked) {
Andy Hungc5007f82023-08-29 14:26:09 -07001402 mutex().lock();
Eric Laurent6b446ce2019-12-13 10:56:31 -08001403 }
Eric Laurent81784c32012-11-19 14:55:58 -08001404
Eric Laurent81784c32012-11-19 14:55:58 -08001405 if (mType != RECORD) {
1406 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1407 // another session. This gives the priority to well behaved effect control panels
1408 // and applications not using global effects.
1409 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
1410 // global effects
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001411 if (!audio_is_global_session(sessionId)) {
Eric Laurent81784c32012-11-19 14:55:58 -08001412 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1413 }
1414 }
1415
Eric Laurent6b446ce2019-12-13 10:56:31 -08001416 if (!threadLocked) {
Andy Hungc5007f82023-08-29 14:26:09 -07001417 mutex().unlock();
Eric Laurent81784c32012-11-19 14:55:58 -08001418 }
1419}
1420
Andy Hungc5007f82023-08-29 14:26:09 -07001421// checkEffectCompatibility_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07001422status_t RecordThread::checkEffectCompatibility_l(
Eric Laurent4c415062016-06-17 16:14:16 -07001423 const effect_descriptor_t *desc, audio_session_t sessionId)
1424{
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001425 // No global output effect sessions on record threads
1426 if (sessionId == AUDIO_SESSION_OUTPUT_MIX
1427 || sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Eric Laurent4c415062016-06-17 16:14:16 -07001428 ALOGW("checkEffectCompatibility_l(): global effect %s on record thread %s",
1429 desc->name, mThreadName);
1430 return BAD_VALUE;
1431 }
1432 // only pre processing effects on record thread
1433 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC) {
1434 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on record thread %s",
1435 desc->name, mThreadName);
1436 return BAD_VALUE;
1437 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001438
1439 // always allow effects without processing load or latency
1440 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1441 return NO_ERROR;
1442 }
1443
Eric Laurent4c415062016-06-17 16:14:16 -07001444 audio_input_flags_t flags = mInput->flags;
1445 if (hasFastCapture() || (flags & AUDIO_INPUT_FLAG_FAST)) {
1446 if (flags & AUDIO_INPUT_FLAG_RAW) {
1447 ALOGW("checkEffectCompatibility_l(): effect %s on record thread %s in raw mode",
1448 desc->name, mThreadName);
1449 return BAD_VALUE;
1450 }
1451 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1452 ALOGW("checkEffectCompatibility_l(): non HW effect %s on record thread %s in fast mode",
1453 desc->name, mThreadName);
1454 return BAD_VALUE;
1455 }
1456 }
jiabineb3bda02020-06-30 14:07:03 -07001457
Andy Hung116bc262023-06-20 18:56:17 -07001458 if (IAfEffectModule::isHapticGenerator(&desc->type)) {
jiabineb3bda02020-06-30 14:07:03 -07001459 ALOGE("%s(): HapticGenerator is not supported in RecordThread", __func__);
1460 return BAD_VALUE;
1461 }
Eric Laurent4c415062016-06-17 16:14:16 -07001462 return NO_ERROR;
1463}
1464
Andy Hungc5007f82023-08-29 14:26:09 -07001465// checkEffectCompatibility_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07001466status_t PlaybackThread::checkEffectCompatibility_l(
Eric Laurent4c415062016-06-17 16:14:16 -07001467 const effect_descriptor_t *desc, audio_session_t sessionId)
1468{
1469 // no preprocessing on playback threads
1470 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001471 ALOGW("%s: pre processing effect %s created on playback"
1472 " thread %s", __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001473 return BAD_VALUE;
1474 }
1475
Eric Laurent3e4de772017-07-16 16:55:08 -07001476 // always allow effects without processing load or latency
1477 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1478 return NO_ERROR;
1479 }
1480
Andy Hung116bc262023-06-20 18:56:17 -07001481 if (IAfEffectModule::isHapticGenerator(&desc->type) && mHapticChannelCount == 0) {
jiabineb3bda02020-06-30 14:07:03 -07001482 ALOGW("%s: thread doesn't support haptic playback while the effect is HapticGenerator",
1483 __func__);
1484 return BAD_VALUE;
1485 }
1486
Eric Laurent4eb45d02023-12-20 12:07:17 +01001487 if (IAfEffectModule::isSpatializer(&desc->type)
Eric Laurentf690c462021-09-17 14:47:03 +02001488 && mType != SPATIALIZER) {
1489 ALOGW("%s: attempt to create a spatializer effect on a thread of type %d",
1490 __func__, mType);
1491 return BAD_VALUE;
1492 }
1493
Eric Laurent4c415062016-06-17 16:14:16 -07001494 switch (mType) {
1495 case MIXER: {
Eric Laurent4c415062016-06-17 16:14:16 -07001496 audio_output_flags_t flags = mOutput->flags;
1497 if (hasFastMixer() || (flags & AUDIO_OUTPUT_FLAG_FAST)) {
1498 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1499 // global effects are applied only to non fast tracks if they are SW
1500 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1501 break;
1502 }
1503 } else if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1504 // only post processing on output stage session
1505 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001506 ALOGW("%s: non post processing effect %s not allowed on output stage session",
1507 __func__, desc->name);
Eric Laurent4c415062016-06-17 16:14:16 -07001508 return BAD_VALUE;
1509 }
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001510 } else if (sessionId == AUDIO_SESSION_DEVICE) {
1511 // only post processing on output stage session
1512 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001513 ALOGW("%s: non post processing effect %s not allowed on device session",
1514 __func__, desc->name);
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001515 return BAD_VALUE;
1516 }
Eric Laurent4c415062016-06-17 16:14:16 -07001517 } else {
1518 // no restriction on effects applied on non fast tracks
1519 if ((hasAudioSession_l(sessionId) & ThreadBase::FAST_SESSION) == 0) {
1520 break;
1521 }
1522 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001523
Eric Laurent4c415062016-06-17 16:14:16 -07001524 if (flags & AUDIO_OUTPUT_FLAG_RAW) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001525 ALOGW("%s: effect %s on playback thread in raw mode", __func__, desc->name);
Eric Laurent4c415062016-06-17 16:14:16 -07001526 return BAD_VALUE;
1527 }
1528 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001529 ALOGW("%s: non HW effect %s on playback thread in fast mode",
1530 __func__, desc->name);
Eric Laurent4c415062016-06-17 16:14:16 -07001531 return BAD_VALUE;
1532 }
1533 }
1534 } break;
1535 case OFFLOAD:
Jean-Michel Trivi773ee952016-07-11 16:53:18 -07001536 // nothing actionable on offload threads, if the effect:
1537 // - is offloadable: the effect can be created
1538 // - is NOT offloadable: the effect should still be created, but EffectHandle::enable()
1539 // will take care of invalidating the tracks of the thread
Eric Laurent4c415062016-06-17 16:14:16 -07001540 break;
1541 case DIRECT:
1542 // Reject any effect on Direct output threads for now, since the format of
1543 // mSinkBuffer is not guaranteed to be compatible with effect processing (PCM 16 stereo).
Eric Laurentb62d0362021-10-26 17:40:18 +02001544 ALOGW("%s: effect %s on DIRECT output thread %s",
1545 __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001546 return BAD_VALUE;
1547 case DUPLICATING:
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001548 if (audio_is_global_session(sessionId)) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001549 ALOGW("%s: global effect %s on DUPLICATING thread %s",
1550 __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001551 return BAD_VALUE;
1552 }
1553 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001554 ALOGW("%s: post processing effect %s on DUPLICATING thread %s",
1555 __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001556 return BAD_VALUE;
1557 }
1558 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) != 0) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001559 ALOGW("%s: HW tunneled effect %s on DUPLICATING thread %s",
1560 __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001561 return BAD_VALUE;
1562 }
1563 break;
Eric Laurent1c5e2e32021-08-18 18:50:28 +02001564 case SPATIALIZER:
Eric Laurentb62d0362021-10-26 17:40:18 +02001565 // Global effects (AUDIO_SESSION_OUTPUT_MIX) are not supported on spatializer mixer
1566 // as there is no common accumulation buffer for sptialized and non sptialized tracks.
1567 // Post processing effects (AUDIO_SESSION_OUTPUT_STAGE or AUDIO_SESSION_DEVICE)
1568 // are supported and added after the spatializer.
1569 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1570 ALOGW("%s: global effect %s not supported on spatializer thread %s",
1571 __func__, desc->name, mThreadName);
Eric Laurentb3f315a2021-07-13 15:09:05 +02001572 return BAD_VALUE;
Eric Laurentb62d0362021-10-26 17:40:18 +02001573 } else if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1574 // only post processing , downmixer or spatializer effects on output stage session
Eric Laurent4eb45d02023-12-20 12:07:17 +01001575 if (IAfEffectModule::isSpatializer(&desc->type)
Eric Laurentb62d0362021-10-26 17:40:18 +02001576 || memcmp(&desc->type, EFFECT_UIID_DOWNMIX, sizeof(effect_uuid_t)) == 0) {
1577 break;
1578 }
1579 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
1580 ALOGW("%s: non post processing effect %s not allowed on output stage session",
1581 __func__, desc->name);
1582 return BAD_VALUE;
1583 }
1584 } else if (sessionId == AUDIO_SESSION_DEVICE) {
1585 // only post processing on output stage session
1586 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
1587 ALOGW("%s: non post processing effect %s not allowed on device session",
1588 __func__, desc->name);
1589 return BAD_VALUE;
1590 }
Eric Laurentb3f315a2021-07-13 15:09:05 +02001591 }
1592 break;
jiabinc658e452022-10-21 20:52:21 +00001593 case BIT_PERFECT:
1594 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) != 0) {
1595 // Allow HW accelerated effects of tunnel type
1596 break;
1597 }
1598 // As bit-perfect tracks will not be allowed to apply audio effect that will touch the audio
1599 // data, effects will not be allowed on 1) global effects (AUDIO_SESSION_OUTPUT_MIX),
1600 // 2) post-processing effects (AUDIO_SESSION_OUTPUT_STAGE or AUDIO_SESSION_DEVICE) and
1601 // 3) there is any bit-perfect track with the given session id.
1602 if (sessionId == AUDIO_SESSION_OUTPUT_MIX || sessionId == AUDIO_SESSION_OUTPUT_STAGE ||
1603 sessionId == AUDIO_SESSION_DEVICE) {
1604 ALOGW("%s: effect %s not supported on bit-perfect thread %s",
1605 __func__, desc->name, mThreadName);
1606 return BAD_VALUE;
1607 } else if ((hasAudioSession_l(sessionId) & ThreadBase::BIT_PERFECT_SESSION) != 0) {
1608 ALOGW("%s: effect %s not supported as there is a bit-perfect track with session as %d",
1609 __func__, desc->name, sessionId);
1610 return BAD_VALUE;
1611 }
1612 break;
Eric Laurent4c415062016-06-17 16:14:16 -07001613 default:
1614 LOG_ALWAYS_FATAL("checkEffectCompatibility_l(): wrong thread type %d", mType);
1615 }
1616
1617 return NO_ERROR;
1618}
1619
Andy Hungc5007f82023-08-29 14:26:09 -07001620// ThreadBase::createEffect_l() must be called with AudioFlinger::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07001621sp<IAfEffectHandle> ThreadBase::createEffect_l(
Andy Hung88035ac2023-06-27 17:05:02 -07001622 const sp<Client>& client,
Eric Laurent81784c32012-11-19 14:55:58 -08001623 const sp<IEffectClient>& effectClient,
1624 int32_t priority,
Glenn Kastend848eb42016-03-08 13:42:11 -08001625 audio_session_t sessionId,
Eric Laurent81784c32012-11-19 14:55:58 -08001626 effect_descriptor_t *desc,
1627 int *enabled,
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001628 status_t *status,
Eric Laurent2fe0acd2020-03-13 14:30:46 -07001629 bool pinned,
Eric Laurentde8caf42021-08-11 17:19:25 +02001630 bool probe,
1631 bool notifyFramesProcessed)
Eric Laurent81784c32012-11-19 14:55:58 -08001632{
Andy Hung116bc262023-06-20 18:56:17 -07001633 sp<IAfEffectModule> effect;
1634 sp<IAfEffectHandle> handle;
Eric Laurent81784c32012-11-19 14:55:58 -08001635 status_t lStatus;
Andy Hung116bc262023-06-20 18:56:17 -07001636 sp<IAfEffectChain> chain;
Eric Laurent81784c32012-11-19 14:55:58 -08001637 bool chainCreated = false;
1638 bool effectCreated = false;
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001639 audio_unique_id_t effectId = AUDIO_UNIQUE_ID_USE_UNSPECIFIED;
Eric Laurent81784c32012-11-19 14:55:58 -08001640
1641 lStatus = initCheck();
1642 if (lStatus != NO_ERROR) {
1643 ALOGW("createEffect_l() Audio driver not initialized.");
1644 goto Exit;
1645 }
1646
Eric Laurent81784c32012-11-19 14:55:58 -08001647 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
1648
Andy Hungc5007f82023-08-29 14:26:09 -07001649 { // scope for mutex()
Andy Hung972bec12023-08-31 16:13:39 -07001650 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001651
Eric Laurent4c415062016-06-17 16:14:16 -07001652 lStatus = checkEffectCompatibility_l(desc, sessionId);
Eric Laurent2fe0acd2020-03-13 14:30:46 -07001653 if (probe || lStatus != NO_ERROR) {
Eric Laurent4c415062016-06-17 16:14:16 -07001654 goto Exit;
1655 }
1656
Eric Laurent81784c32012-11-19 14:55:58 -08001657 // check for existing effect chain with the requested audio session
1658 chain = getEffectChain_l(sessionId);
1659 if (chain == 0) {
1660 // create a new chain for this session
1661 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
Andy Hung116bc262023-06-20 18:56:17 -07001662 chain = IAfEffectChain::create(this, sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08001663 addEffectChain_l(chain);
1664 chain->setStrategy(getStrategyForSession_l(sessionId));
1665 chainCreated = true;
1666 } else {
1667 effect = chain->getEffectFromDesc_l(desc);
1668 }
1669
1670 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
1671
1672 if (effect == 0) {
Andy Hung583043b2023-07-17 17:05:00 -07001673 effectId = mAfThreadCallback->nextUniqueId(AUDIO_UNIQUE_ID_USE_EFFECT);
Eric Laurent81784c32012-11-19 14:55:58 -08001674 // create a new effect module if none present in the chain
Eric Laurent6b446ce2019-12-13 10:56:31 -08001675 lStatus = chain->createEffect_l(effect, desc, effectId, sessionId, pinned);
Eric Laurent81784c32012-11-19 14:55:58 -08001676 if (lStatus != NO_ERROR) {
1677 goto Exit;
1678 }
1679 effectCreated = true;
1680
jiabinc52b1ff2019-10-31 17:20:42 -07001681 // FIXME: use vector of device and address when effect interface is ready.
jiabin8f278ee2019-11-11 12:16:27 -08001682 effect->setDevices(outDeviceTypeAddrs());
1683 effect->setInputDevice(inDeviceTypeAddr());
Andy Hung583043b2023-07-17 17:05:00 -07001684 effect->setMode(mAfThreadCallback->getMode());
Eric Laurent81784c32012-11-19 14:55:58 -08001685 effect->setAudioSource(mAudioSource);
1686 }
jiabin1319f5a2021-03-30 22:21:24 +00001687 if (effect->isHapticGenerator()) {
1688 // TODO(b/184194057): Use the vibrator information from the vibrator that will be used
1689 // for the HapticGenerator.
Lais Andradebc3f37a2021-07-02 00:13:19 +01001690 const std::optional<media::AudioVibratorInfo> defaultVibratorInfo =
Andy Hung583043b2023-07-17 17:05:00 -07001691 std::move(mAfThreadCallback->getDefaultVibratorInfo_l());
Lais Andradebc3f37a2021-07-02 00:13:19 +01001692 if (defaultVibratorInfo) {
jiabin1319f5a2021-03-30 22:21:24 +00001693 // Only set the vibrator info when it is a valid one.
Shunkai Yaod125e402024-01-20 03:19:06 +00001694 effect->setVibratorInfo_l(*defaultVibratorInfo);
jiabin1319f5a2021-03-30 22:21:24 +00001695 }
1696 }
Eric Laurent81784c32012-11-19 14:55:58 -08001697 // create effect handle and connect it to effect module
Andy Hung116bc262023-06-20 18:56:17 -07001698 handle = IAfEffectHandle::create(
1699 effect, client, effectClient, priority, notifyFramesProcessed);
Glenn Kastene75da402013-11-20 13:54:52 -08001700 lStatus = handle->initCheck();
1701 if (lStatus == OK) {
1702 lStatus = effect->addHandle(handle.get());
Eric Laurentb3f315a2021-07-13 15:09:05 +02001703 sendCheckOutputStageEffectsEvent_l();
Glenn Kastene75da402013-11-20 13:54:52 -08001704 }
Eric Laurent81784c32012-11-19 14:55:58 -08001705 if (enabled != NULL) {
1706 *enabled = (int)effect->isEnabled();
1707 }
1708 }
1709
1710Exit:
Eric Laurent2fe0acd2020-03-13 14:30:46 -07001711 if (!probe && lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Andy Hung972bec12023-08-31 16:13:39 -07001712 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001713 if (effectCreated) {
1714 chain->removeEffect_l(effect);
1715 }
Eric Laurent81784c32012-11-19 14:55:58 -08001716 if (chainCreated) {
1717 removeEffectChain_l(chain);
1718 }
haobo101735295ff7b0d2017-03-17 17:44:03 +08001719 // handle must be cleared by caller to avoid deadlock.
Eric Laurent81784c32012-11-19 14:55:58 -08001720 }
1721
Glenn Kasten9156ef32013-08-06 15:39:08 -07001722 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001723 return handle;
1724}
1725
Andy Hungee58e4a2023-07-07 13:47:37 -07001726void ThreadBase::disconnectEffectHandle(IAfEffectHandle* handle,
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001727 bool unpinIfLast)
1728{
1729 bool remove = false;
Andy Hung116bc262023-06-20 18:56:17 -07001730 sp<IAfEffectModule> effect;
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001731 {
Andy Hung972bec12023-08-31 16:13:39 -07001732 audio_utils::lock_guard _l(mutex());
Andy Hung116bc262023-06-20 18:56:17 -07001733 sp<IAfEffectBase> effectBase = handle->effect().promote();
Eric Laurent41709552019-12-16 19:34:05 -08001734 if (effectBase == nullptr) {
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001735 return;
1736 }
Eric Laurentb82e6b72019-11-22 17:25:04 -08001737 effect = effectBase->asEffectModule();
1738 if (effect == nullptr) {
1739 return;
1740 }
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001741 // restore suspended effects if the disconnected handle was enabled and the last one.
1742 remove = (effect->removeHandle(handle) == 0) && (!effect->isPinned() || unpinIfLast);
1743 if (remove) {
1744 removeEffect_l(effect, true);
1745 }
Eric Laurentb3f315a2021-07-13 15:09:05 +02001746 sendCheckOutputStageEffectsEvent_l();
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001747 }
1748 if (remove) {
Andy Hung583043b2023-07-17 17:05:00 -07001749 mAfThreadCallback->updateOrphanEffectChains(effect);
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001750 if (handle->enabled()) {
Eric Laurent6b446ce2019-12-13 10:56:31 -08001751 effect->checkSuspendOnEffectEnabled(false, false /*threadLocked*/);
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001752 }
1753 }
1754}
1755
Andy Hungee58e4a2023-07-07 13:47:37 -07001756void ThreadBase::onEffectEnable(const sp<IAfEffectModule>& effect) {
Andy Hungea840382020-05-05 21:50:17 -07001757 if (isOffloadOrMmap()) {
Andy Hung972bec12023-08-31 16:13:39 -07001758 audio_utils::lock_guard _l(mutex());
Eric Laurent6b446ce2019-12-13 10:56:31 -08001759 broadcast_l();
1760 }
1761 if (!effect->isOffloadable()) {
1762 if (mType == ThreadBase::OFFLOAD) {
1763 PlaybackThread *t = (PlaybackThread *)this;
1764 t->invalidateTracks(AUDIO_STREAM_MUSIC);
1765 }
1766 if (effect->sessionId() == AUDIO_SESSION_OUTPUT_MIX) {
Andy Hung583043b2023-07-17 17:05:00 -07001767 mAfThreadCallback->onNonOffloadableGlobalEffectEnable();
Eric Laurent6b446ce2019-12-13 10:56:31 -08001768 }
1769 }
1770}
1771
Andy Hungee58e4a2023-07-07 13:47:37 -07001772void ThreadBase::onEffectDisable() {
Andy Hungea840382020-05-05 21:50:17 -07001773 if (isOffloadOrMmap()) {
Andy Hung972bec12023-08-31 16:13:39 -07001774 audio_utils::lock_guard _l(mutex());
Eric Laurent6b446ce2019-12-13 10:56:31 -08001775 broadcast_l();
1776 }
1777}
1778
Andy Hungee58e4a2023-07-07 13:47:37 -07001779sp<IAfEffectModule> ThreadBase::getEffect(audio_session_t sessionId,
Andy Hung440901d2023-06-29 21:19:25 -07001780 int effectId) const
Eric Laurent81784c32012-11-19 14:55:58 -08001781{
Andy Hung972bec12023-08-31 16:13:39 -07001782 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001783 return getEffect_l(sessionId, effectId);
1784}
1785
Andy Hungee58e4a2023-07-07 13:47:37 -07001786sp<IAfEffectModule> ThreadBase::getEffect_l(audio_session_t sessionId,
Andy Hung440901d2023-06-29 21:19:25 -07001787 int effectId) const
Eric Laurent81784c32012-11-19 14:55:58 -08001788{
Andy Hung116bc262023-06-20 18:56:17 -07001789 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08001790 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
1791}
1792
Andy Hungee58e4a2023-07-07 13:47:37 -07001793std::vector<int> ThreadBase::getEffectIds_l(audio_session_t sessionId) const
Eric Laurent6c796322019-04-09 14:13:17 -07001794{
Andy Hung116bc262023-06-20 18:56:17 -07001795 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Shunkai Yaod125e402024-01-20 03:19:06 +00001796 return chain != nullptr ? chain->getEffectIds_l() : std::vector<int>{};
Eric Laurent6c796322019-04-09 14:13:17 -07001797}
1798
Andy Hung972bec12023-08-31 16:13:39 -07001799// PlaybackThread::addEffect_ll() must be called with AudioFlinger::mutex() and
1800// ThreadBase::mutex() held
1801status_t ThreadBase::addEffect_ll(const sp<IAfEffectModule>& effect)
Eric Laurent81784c32012-11-19 14:55:58 -08001802{
1803 // check for existing effect chain with the requested audio session
Glenn Kastend848eb42016-03-08 13:42:11 -08001804 audio_session_t sessionId = effect->sessionId();
Andy Hung116bc262023-06-20 18:56:17 -07001805 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08001806 bool chainCreated = false;
1807
Eric Laurent5baf2af2013-09-12 17:37:00 -07001808 ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(),
Andy Hung972bec12023-08-31 16:13:39 -07001809 "%s: on offloaded thread %p: effect %s does not support offload flags %#x",
1810 __func__, this, effect->desc().name, effect->desc().flags);
Eric Laurent5baf2af2013-09-12 17:37:00 -07001811
Eric Laurent81784c32012-11-19 14:55:58 -08001812 if (chain == 0) {
1813 // create a new chain for this session
Andy Hung972bec12023-08-31 16:13:39 -07001814 ALOGV("%s: new effect chain for session %d", __func__, sessionId);
Andy Hung116bc262023-06-20 18:56:17 -07001815 chain = IAfEffectChain::create(this, sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08001816 addEffectChain_l(chain);
1817 chain->setStrategy(getStrategyForSession_l(sessionId));
1818 chainCreated = true;
1819 }
Andy Hung972bec12023-08-31 16:13:39 -07001820 ALOGV("%s: %p chain %p effect %p", __func__, this, chain.get(), effect.get());
Eric Laurent81784c32012-11-19 14:55:58 -08001821
1822 if (chain->getEffectFromId_l(effect->id()) != 0) {
Andy Hung972bec12023-08-31 16:13:39 -07001823 ALOGW("%s: %p effect %s already present in chain %p",
1824 __func__, this, effect->desc().name, chain.get());
Eric Laurent81784c32012-11-19 14:55:58 -08001825 return BAD_VALUE;
1826 }
1827
Shunkai Yaod125e402024-01-20 03:19:06 +00001828 effect->setOffloaded_l(mType == OFFLOAD, mId);
Eric Laurent5baf2af2013-09-12 17:37:00 -07001829
Eric Laurent81784c32012-11-19 14:55:58 -08001830 status_t status = chain->addEffect_l(effect);
1831 if (status != NO_ERROR) {
1832 if (chainCreated) {
1833 removeEffectChain_l(chain);
1834 }
1835 return status;
1836 }
1837
jiabin8f278ee2019-11-11 12:16:27 -08001838 effect->setDevices(outDeviceTypeAddrs());
1839 effect->setInputDevice(inDeviceTypeAddr());
Andy Hung583043b2023-07-17 17:05:00 -07001840 effect->setMode(mAfThreadCallback->getMode());
Eric Laurent81784c32012-11-19 14:55:58 -08001841 effect->setAudioSource(mAudioSource);
Eric Laurentd8365c52017-07-16 15:27:05 -07001842
Eric Laurent81784c32012-11-19 14:55:58 -08001843 return NO_ERROR;
1844}
1845
Andy Hungee58e4a2023-07-07 13:47:37 -07001846void ThreadBase::removeEffect_l(const sp<IAfEffectModule>& effect, bool release) {
Eric Laurent81784c32012-11-19 14:55:58 -08001847
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001848 ALOGV("%s %p effect %p", __FUNCTION__, this, effect.get());
Eric Laurent81784c32012-11-19 14:55:58 -08001849 effect_descriptor_t desc = effect->desc();
1850 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
1851 detachAuxEffect_l(effect->id());
1852 }
1853
Andy Hung116bc262023-06-20 18:56:17 -07001854 sp<IAfEffectChain> chain = effect->getCallback()->chain().promote();
Eric Laurent81784c32012-11-19 14:55:58 -08001855 if (chain != 0) {
1856 // remove effect chain if removing last effect
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001857 if (chain->removeEffect_l(effect, release) == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08001858 removeEffectChain_l(chain);
1859 }
1860 } else {
1861 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
1862 }
1863}
1864
Shunkai Yaof4847652024-01-12 00:25:20 +00001865void ThreadBase::lockEffectChains_l(Vector<sp<IAfEffectChain>>& effectChains)
1866 NO_THREAD_SAFETY_ANALYSIS // calls EffectChain::lock()
Eric Laurent81784c32012-11-19 14:55:58 -08001867{
1868 effectChains = mEffectChains;
Shunkai Yaof4847652024-01-12 00:25:20 +00001869 for (const auto& effectChain : effectChains) {
1870 effectChain->mutex().lock();
Eric Laurent81784c32012-11-19 14:55:58 -08001871 }
1872}
1873
Shunkai Yaof4847652024-01-12 00:25:20 +00001874void ThreadBase::unlockEffectChains(const Vector<sp<IAfEffectChain>>& effectChains)
1875 NO_THREAD_SAFETY_ANALYSIS // calls EffectChain::unlock()
Eric Laurent81784c32012-11-19 14:55:58 -08001876{
Shunkai Yaof4847652024-01-12 00:25:20 +00001877 for (const auto& effectChain : effectChains) {
1878 effectChain->mutex().unlock();
Eric Laurent81784c32012-11-19 14:55:58 -08001879 }
1880}
1881
Andy Hungee58e4a2023-07-07 13:47:37 -07001882sp<IAfEffectChain> ThreadBase::getEffectChain(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08001883{
Andy Hung972bec12023-08-31 16:13:39 -07001884 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001885 return getEffectChain_l(sessionId);
1886}
1887
Andy Hungee58e4a2023-07-07 13:47:37 -07001888sp<IAfEffectChain> ThreadBase::getEffectChain_l(audio_session_t sessionId)
Glenn Kastend848eb42016-03-08 13:42:11 -08001889 const
Eric Laurent81784c32012-11-19 14:55:58 -08001890{
1891 size_t size = mEffectChains.size();
1892 for (size_t i = 0; i < size; i++) {
1893 if (mEffectChains[i]->sessionId() == sessionId) {
1894 return mEffectChains[i];
1895 }
1896 }
1897 return 0;
1898}
1899
Andy Hungee58e4a2023-07-07 13:47:37 -07001900void ThreadBase::setMode(audio_mode_t mode)
Eric Laurent81784c32012-11-19 14:55:58 -08001901{
Andy Hung972bec12023-08-31 16:13:39 -07001902 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001903 size_t size = mEffectChains.size();
1904 for (size_t i = 0; i < size; i++) {
1905 mEffectChains[i]->setMode_l(mode);
1906 }
1907}
1908
Andy Hungee58e4a2023-07-07 13:47:37 -07001909void ThreadBase::toAudioPortConfig(struct audio_port_config* config)
Eric Laurent83b88082014-06-20 18:31:16 -07001910{
1911 config->type = AUDIO_PORT_TYPE_MIX;
1912 config->ext.mix.handle = mId;
1913 config->sample_rate = mSampleRate;
Mikhail Naganov88d54da2023-09-11 11:53:50 -07001914 config->format = mHALFormat;
Eric Laurent83b88082014-06-20 18:31:16 -07001915 config->channel_mask = mChannelMask;
1916 config->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
1917 AUDIO_PORT_CONFIG_FORMAT;
1918}
1919
Andy Hungee58e4a2023-07-07 13:47:37 -07001920void ThreadBase::systemReady()
Eric Laurent72e3f392015-05-20 14:43:50 -07001921{
Andy Hung972bec12023-08-31 16:13:39 -07001922 audio_utils::lock_guard _l(mutex());
Eric Laurent72e3f392015-05-20 14:43:50 -07001923 if (mSystemReady) {
1924 return;
1925 }
1926 mSystemReady = true;
1927
1928 for (size_t i = 0; i < mPendingConfigEvents.size(); i++) {
1929 sendConfigEvent_l(mPendingConfigEvents.editItemAt(i));
1930 }
1931 mPendingConfigEvents.clear();
1932}
1933
Andy Hungdae27702016-10-31 14:01:16 -07001934template <typename T>
Andy Hungee58e4a2023-07-07 13:47:37 -07001935ssize_t ThreadBase::ActiveTracks<T>::add(const sp<T>& track) {
Andy Hungdae27702016-10-31 14:01:16 -07001936 ssize_t index = mActiveTracks.indexOf(track);
1937 if (index >= 0) {
1938 ALOGW("ActiveTracks<T>::add track %p already there", track.get());
1939 return index;
1940 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001941 logTrack("add", track);
Andy Hungdae27702016-10-31 14:01:16 -07001942 mActiveTracksGeneration++;
1943 mLatestActiveTrack = track;
Atneya Nair166663a2023-06-27 19:16:24 -07001944 track->beginBatteryAttribution();
Kevin Rocard069c2712018-03-29 19:09:14 -07001945 mHasChanged = true;
Andy Hungdae27702016-10-31 14:01:16 -07001946 return mActiveTracks.add(track);
1947}
1948
1949template <typename T>
Andy Hungee58e4a2023-07-07 13:47:37 -07001950ssize_t ThreadBase::ActiveTracks<T>::remove(const sp<T>& track) {
Andy Hungdae27702016-10-31 14:01:16 -07001951 ssize_t index = mActiveTracks.remove(track);
1952 if (index < 0) {
1953 ALOGW("ActiveTracks<T>::remove nonexistent track %p", track.get());
1954 return index;
1955 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001956 logTrack("remove", track);
Andy Hungdae27702016-10-31 14:01:16 -07001957 mActiveTracksGeneration++;
Atneya Nair166663a2023-06-27 19:16:24 -07001958 track->endBatteryAttribution();
Andy Hungdae27702016-10-31 14:01:16 -07001959 // mLatestActiveTrack is not cleared even if is the same as track.
Kevin Rocard069c2712018-03-29 19:09:14 -07001960 mHasChanged = true;
Andy Hung8946a282018-04-19 20:04:56 -07001961#ifdef TEE_SINK
1962 track->dumpTee(-1 /* fd */, "_REMOVE");
1963#endif
Andy Hungc2b11cb2020-04-22 09:04:01 -07001964 track->logEndInterval(); // log to MediaMetrics
Andy Hungdae27702016-10-31 14:01:16 -07001965 return index;
1966}
1967
1968template <typename T>
Andy Hungee58e4a2023-07-07 13:47:37 -07001969void ThreadBase::ActiveTracks<T>::clear() {
Andy Hungdae27702016-10-31 14:01:16 -07001970 for (const sp<T> &track : mActiveTracks) {
Atneya Nair166663a2023-06-27 19:16:24 -07001971 track->endBatteryAttribution();
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001972 logTrack("clear", track);
Andy Hungdae27702016-10-31 14:01:16 -07001973 }
1974 mLastActiveTracksGeneration = mActiveTracksGeneration;
Kevin Rocard069c2712018-03-29 19:09:14 -07001975 if (!mActiveTracks.empty()) { mHasChanged = true; }
Andy Hungdae27702016-10-31 14:01:16 -07001976 mActiveTracks.clear();
1977 mLatestActiveTrack.clear();
Andy Hungdae27702016-10-31 14:01:16 -07001978}
1979
1980template <typename T>
Andy Hungab65b182023-09-06 19:41:47 -07001981void ThreadBase::ActiveTracks<T>::updatePowerState_l(
Andy Hung920f6572022-10-06 12:09:49 -07001982 const sp<ThreadBase>& thread, bool force) {
Andy Hungdae27702016-10-31 14:01:16 -07001983 // Updates ActiveTracks client uids to the thread wakelock.
1984 if (mActiveTracksGeneration != mLastActiveTracksGeneration || force) {
1985 thread->updateWakeLockUids_l(getWakeLockUids());
1986 mLastActiveTracksGeneration = mActiveTracksGeneration;
1987 }
Andy Hungdae27702016-10-31 14:01:16 -07001988}
Eric Laurent83b88082014-06-20 18:31:16 -07001989
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001990template <typename T>
Andy Hungee58e4a2023-07-07 13:47:37 -07001991bool ThreadBase::ActiveTracks<T>::readAndClearHasChanged() {
Jasmine Chaeaa10e42021-05-11 10:11:14 +08001992 bool hasChanged = mHasChanged;
Kevin Rocard069c2712018-03-29 19:09:14 -07001993 mHasChanged = false;
Jasmine Chaeaa10e42021-05-11 10:11:14 +08001994
1995 for (const sp<T> &track : mActiveTracks) {
1996 // Do not short-circuit as all hasChanged states must be reset
1997 // as all the metadata are going to be sent
1998 hasChanged |= track->readAndClearHasChanged();
1999 }
Kevin Rocard069c2712018-03-29 19:09:14 -07002000 return hasChanged;
2001}
2002
2003template <typename T>
Andy Hungee58e4a2023-07-07 13:47:37 -07002004void ThreadBase::ActiveTracks<T>::logTrack(
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002005 const char *funcName, const sp<T> &track) const {
2006 if (mLocalLog != nullptr) {
2007 String8 result;
2008 track->appendDump(result, false /* active */);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00002009 mLocalLog->log("AT::%-10s(%p) %s", funcName, track.get(), result.c_str());
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002010 }
2011}
2012
Andy Hungee58e4a2023-07-07 13:47:37 -07002013void ThreadBase::broadcast_l()
Eric Laurent6acd1d42017-01-04 14:23:29 -08002014{
2015 // Thread could be blocked waiting for async
2016 // so signal it to handle state changes immediately
2017 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
2018 // be lost so we also flag to prevent it blocking on mWaitWorkCV
2019 mSignalPending = true;
Andy Hungc5007f82023-08-29 14:26:09 -07002020 mWaitWorkCV.notify_all();
Eric Laurent6acd1d42017-01-04 14:23:29 -08002021}
2022
Andy Hungd0979812019-02-21 15:51:44 -08002023// Call only from threadLoop() or when it is idle.
2024// Do not call from high performance code as this may do binder rpc to the MediaMetrics service.
Andy Hungee58e4a2023-07-07 13:47:37 -07002025void ThreadBase::sendStatistics(bool force)
Andy Hungab65b182023-09-06 19:41:47 -07002026NO_THREAD_SAFETY_ANALYSIS
Andy Hungd0979812019-02-21 15:51:44 -08002027{
2028 // Do not log if we have no stats.
2029 // We choose the timestamp verifier because it is the most likely item to be present.
2030 const int64_t nstats = mTimestampVerifier.getN() - mLastRecordedTimestampVerifierN;
2031 if (nstats == 0) {
2032 return;
2033 }
2034
2035 // Don't log more frequently than once per 12 hours.
2036 // We use BOOTTIME to include suspend time.
2037 const int64_t timeNs = systemTime(SYSTEM_TIME_BOOTTIME);
2038 const int64_t sinceNs = timeNs - mLastRecordedTimeNs; // ok if mLastRecordedTimeNs = 0
2039 if (!force && sinceNs <= 12 * NANOS_PER_HOUR) {
2040 return;
2041 }
2042
2043 mLastRecordedTimestampVerifierN = mTimestampVerifier.getN();
2044 mLastRecordedTimeNs = timeNs;
2045
Ray Essickf27e9872019-12-07 06:28:46 -08002046 std::unique_ptr<mediametrics::Item> item(mediametrics::Item::create("audiothread"));
Andy Hungd0979812019-02-21 15:51:44 -08002047
2048#define MM_PREFIX "android.media.audiothread." // avoid cut-n-paste errors.
2049
2050 // thread configuration
2051 item->setInt32(MM_PREFIX "id", (int32_t)mId); // IO handle
2052 // item->setInt32(MM_PREFIX "portId", (int32_t)mPortId);
2053 item->setCString(MM_PREFIX "type", threadTypeToString(mType));
2054 item->setInt32(MM_PREFIX "sampleRate", (int32_t)mSampleRate);
2055 item->setInt64(MM_PREFIX "channelMask", (int64_t)mChannelMask);
2056 item->setCString(MM_PREFIX "encoding", toString(mFormat).c_str());
2057 item->setInt32(MM_PREFIX "frameCount", (int32_t)mFrameCount);
Andy Hungab65b182023-09-06 19:41:47 -07002058 item->setCString(MM_PREFIX "outDevice", toString(outDeviceTypes_l()).c_str());
2059 item->setCString(MM_PREFIX "inDevice", toString(inDeviceType_l()).c_str());
Andy Hungd0979812019-02-21 15:51:44 -08002060
2061 // thread statistics
2062 if (mIoJitterMs.getN() > 0) {
2063 item->setDouble(MM_PREFIX "ioJitterMs.mean", mIoJitterMs.getMean());
2064 item->setDouble(MM_PREFIX "ioJitterMs.std", mIoJitterMs.getStdDev());
2065 }
2066 if (mProcessTimeMs.getN() > 0) {
2067 item->setDouble(MM_PREFIX "processTimeMs.mean", mProcessTimeMs.getMean());
2068 item->setDouble(MM_PREFIX "processTimeMs.std", mProcessTimeMs.getStdDev());
2069 }
2070 const auto tsjitter = mTimestampVerifier.getJitterMs();
2071 if (tsjitter.getN() > 0) {
2072 item->setDouble(MM_PREFIX "timestampJitterMs.mean", tsjitter.getMean());
2073 item->setDouble(MM_PREFIX "timestampJitterMs.std", tsjitter.getStdDev());
2074 }
2075 if (mLatencyMs.getN() > 0) {
2076 item->setDouble(MM_PREFIX "latencyMs.mean", mLatencyMs.getMean());
2077 item->setDouble(MM_PREFIX "latencyMs.std", mLatencyMs.getStdDev());
2078 }
Robert Wu06db0a32021-08-10 19:05:34 +00002079 if (mMonopipePipeDepthStats.getN() > 0) {
2080 item->setDouble(MM_PREFIX "monopipePipeDepthStats.mean",
2081 mMonopipePipeDepthStats.getMean());
2082 item->setDouble(MM_PREFIX "monopipePipeDepthStats.std",
2083 mMonopipePipeDepthStats.getStdDev());
2084 }
Andy Hungd0979812019-02-21 15:51:44 -08002085
2086 item->selfrecord();
2087}
2088
Andy Hungee58e4a2023-07-07 13:47:37 -07002089product_strategy_t ThreadBase::getStrategyForStream(audio_stream_type_t stream) const
Eric Laurentd66d7a12021-07-13 13:35:32 +02002090{
Andy Hung583043b2023-07-17 17:05:00 -07002091 if (!mAfThreadCallback->isAudioPolicyReady()) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02002092 return PRODUCT_STRATEGY_NONE;
2093 }
2094 return AudioSystem::getStrategyForStream(stream);
2095}
2096
Andy Hungc5007f82023-08-29 14:26:09 -07002097// startMelComputation_l() must be called with AudioFlinger::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07002098void ThreadBase::startMelComputation_l(
Vlad Popa6fbbfbf2023-02-22 15:05:43 +01002099 const sp<audio_utils::MelProcessor>& /*processor*/)
2100{
2101 // Do nothing
2102 ALOGW("%s: ThreadBase does not support CSD", __func__);
2103}
2104
Andy Hungc5007f82023-08-29 14:26:09 -07002105// stopMelComputation_l() must be called with AudioFlinger::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07002106void ThreadBase::stopMelComputation_l()
Vlad Popa6fbbfbf2023-02-22 15:05:43 +01002107{
2108 // Do nothing
2109 ALOGW("%s: ThreadBase does not support CSD", __func__);
2110}
2111
Eric Laurent81784c32012-11-19 14:55:58 -08002112// ----------------------------------------------------------------------------
2113// Playback
2114// ----------------------------------------------------------------------------
2115
Andy Hung583043b2023-07-17 17:05:00 -07002116PlaybackThread::PlaybackThread(const sp<IAfThreadCallback>& afThreadCallback,
Eric Laurent81784c32012-11-19 14:55:58 -08002117 AudioStreamOut* output,
2118 audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -07002119 type_t type,
Eric Laurentf1f22e72021-07-13 14:04:14 +02002120 bool systemReady,
2121 audio_config_base_t *mixerConfig)
Andy Hung583043b2023-07-17 17:05:00 -07002122 : ThreadBase(afThreadCallback, id, type, systemReady, true /* isOut */),
Andy Hung2098f272014-02-27 14:00:06 -08002123 mNormalFrameCount(0), mSinkBuffer(NULL),
Andy Hung81994d62023-07-20 21:44:14 -07002124 mMixerBufferEnabled(kEnableExtendedPrecision || type == SPATIALIZER),
Andy Hung69aed5f2014-02-25 17:24:40 -08002125 mMixerBuffer(NULL),
2126 mMixerBufferSize(0),
2127 mMixerBufferFormat(AUDIO_FORMAT_INVALID),
2128 mMixerBufferValid(false),
Andy Hung81994d62023-07-20 21:44:14 -07002129 mEffectBufferEnabled(kEnableExtendedPrecision || type == SPATIALIZER),
Andy Hung98ef9782014-03-04 14:46:50 -08002130 mEffectBuffer(NULL),
2131 mEffectBufferSize(0),
2132 mEffectBufferFormat(AUDIO_FORMAT_INVALID),
2133 mEffectBufferValid(false),
Glenn Kastenc1fac192013-08-06 07:41:36 -07002134 mSuspended(0), mBytesWritten(0),
Andy Hungc54b1ff2016-02-23 14:07:07 -08002135 mFramesWritten(0),
Andy Hung238fa3d2016-07-28 10:53:22 -07002136 mSuspendedFrames(0),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002137 mActiveTracks(&this->mLocalLog),
Eric Laurent81784c32012-11-19 14:55:58 -08002138 // mStreamTypes[] initialized in constructor body
Andy Hung1bc088a2018-02-09 15:57:31 -08002139 mTracks(type == MIXER),
Eric Laurent81784c32012-11-19 14:55:58 -08002140 mOutput(output),
Andy Hung446f4df2019-02-21 12:26:41 -08002141 mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
Eric Laurent81784c32012-11-19 14:55:58 -08002142 mMixerStatus(MIXER_IDLE),
2143 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
Andy Hung8fe87eb2023-07-20 21:31:38 -07002144 mStandbyDelayNs(getStandbyTimeInNanos()),
Eric Laurentbfb1b832013-01-07 09:53:42 -08002145 mBytesRemaining(0),
2146 mCurrentWriteLength(0),
2147 mUseAsyncWrite(false),
Eric Laurent3b4529e2013-09-05 18:09:19 -07002148 mWriteAckSequence(0),
2149 mDrainSequence(0),
Andy Hung1d2d2aea2023-07-19 16:22:58 -07002150 mScreenState(mAfThreadCallback->getScreenState()),
Eric Laurent81784c32012-11-19 14:55:58 -08002151 // index 0 is reserved for normal mixer's submix
Glenn Kastendc2c50b2016-04-21 08:13:14 -07002152 mFastTrackAvailMask(((1 << FastMixerState::sMaxFastTracks) - 1) & ~1),
Eric Laurent7c29ec92017-09-20 17:54:22 -07002153 mHwSupportsPause(false), mHwPaused(false), mFlushPending(false),
Eric Laurent74c38dc2020-12-23 18:19:44 +01002154 mLeftVolFloat(-1.0), mRightVolFloat(-1.0),
Brian Lindahl65e90012022-07-27 18:01:07 +02002155 mDownStreamPatch{},
Eric Laurentb0463942022-12-20 16:31:10 +01002156 mIsTimestampAdvancing(kMinimumTimeBetweenTimestampChecksNs)
Eric Laurent81784c32012-11-19 14:55:58 -08002157{
Glenn Kastend7dca052015-03-05 16:05:54 -08002158 snprintf(mThreadName, kThreadNameLength, "AudioOut_%X", id);
Andy Hung583043b2023-07-17 17:05:00 -07002159 mNBLogWriter = afThreadCallback->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08002160
Andy Hungc5007f82023-08-29 14:26:09 -07002161 // Assumes constructor is called by AudioFlinger with its mutex() held, but
Eric Laurent81784c32012-11-19 14:55:58 -08002162 // it would be safer to explicitly pass initial masterVolume/masterMute as
2163 // parameter.
2164 //
2165 // If the HAL we are using has support for master volume or master mute,
2166 // then do not attenuate or mute during mixing (just leave the volume at 1.0
2167 // and the mute set to false).
Andy Hung583043b2023-07-17 17:05:00 -07002168 mMasterVolume = afThreadCallback->masterVolume_l();
2169 mMasterMute = afThreadCallback->masterMute_l();
George Burgess IV5e4d86f2020-02-18 12:55:36 -08002170 if (mOutput->audioHwDev) {
Eric Laurent81784c32012-11-19 14:55:58 -08002171 if (mOutput->audioHwDev->canSetMasterVolume()) {
2172 mMasterVolume = 1.0;
2173 }
2174
2175 if (mOutput->audioHwDev->canSetMasterMute()) {
2176 mMasterMute = false;
2177 }
Andy Hungc8fddf32018-08-08 18:32:37 -07002178 mIsMsdDevice = strcmp(
2179 mOutput->audioHwDev->moduleName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002180 }
2181
Eric Laurentf1f22e72021-07-13 14:04:14 +02002182 if (mixerConfig != nullptr && mixerConfig->channel_mask != AUDIO_CHANNEL_NONE) {
2183 mMixerChannelMask = mixerConfig->channel_mask;
2184 }
2185
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002186 readOutputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002187
Eric Laurent1c5e2e32021-08-18 18:50:28 +02002188 if (mType != SPATIALIZER
Eric Laurentb3f315a2021-07-13 15:09:05 +02002189 && mMixerChannelMask != mChannelMask) {
2190 LOG_ALWAYS_FATAL("HAL channel mask %#x does not match mixer channel mask %#x",
2191 mChannelMask, mMixerChannelMask);
2192 }
2193
Andy Hungc8fddf32018-08-08 18:32:37 -07002194 // TODO: We may also match on address as well as device type for
2195 // AUDIO_DEVICE_OUT_BUS, AUDIO_DEVICE_OUT_ALL_A2DP, AUDIO_DEVICE_OUT_REMOTE_SUBMIX
Dean Wheatleyf8726f02019-12-02 14:12:01 +11002196 if (type == MIXER || type == DIRECT || type == OFFLOAD) {
jiabinc52b1ff2019-10-31 17:20:42 -07002197 // TODO: This property should be ensure that only contains one single device type.
2198 mTimestampCorrectedDevice = (audio_devices_t)property_get_int64(
2199 "audio.timestamp.corrected_output_device",
Andy Hungc8fddf32018-08-08 18:32:37 -07002200 (int64_t)(mIsMsdDevice ? AUDIO_DEVICE_OUT_BUS // turn on by default for MSD
2201 : AUDIO_DEVICE_NONE));
2202 }
2203
Mikhail Naganovf33115d2020-09-25 23:03:05 +00002204 for (int i = AUDIO_STREAM_MIN; i < AUDIO_STREAM_FOR_POLICY_CNT; ++i) {
2205 const audio_stream_type_t stream{static_cast<audio_stream_type_t>(i)};
Eric Laurent98e38192018-02-15 18:31:53 -08002206 mStreamTypes[stream].volume = 0.0f;
Andy Hung583043b2023-07-17 17:05:00 -07002207 mStreamTypes[stream].mute = mAfThreadCallback->streamMute_l(stream);
Eric Laurent81784c32012-11-19 14:55:58 -08002208 }
Eric Laurent35f8c7c2020-02-08 11:42:35 -08002209 // Audio patch and call assistant volume are always max
Eric Laurent98e38192018-02-15 18:31:53 -08002210 mStreamTypes[AUDIO_STREAM_PATCH].volume = 1.0f;
2211 mStreamTypes[AUDIO_STREAM_PATCH].mute = false;
Eric Laurent35f8c7c2020-02-08 11:42:35 -08002212 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].volume = 1.0f;
2213 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].mute = false;
Eric Laurent81784c32012-11-19 14:55:58 -08002214}
2215
Andy Hungee58e4a2023-07-07 13:47:37 -07002216PlaybackThread::~PlaybackThread()
Eric Laurent81784c32012-11-19 14:55:58 -08002217{
Andy Hung583043b2023-07-17 17:05:00 -07002218 mAfThreadCallback->unregisterWriter(mNBLogWriter);
Andy Hung010a1a12014-03-13 13:57:33 -07002219 free(mSinkBuffer);
Andy Hung69aed5f2014-02-25 17:24:40 -08002220 free(mMixerBuffer);
Andy Hung98ef9782014-03-04 14:46:50 -08002221 free(mEffectBuffer);
Eric Laurentb62d0362021-10-26 17:40:18 +02002222 free(mPostSpatializerBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08002223}
2224
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002225// Thread virtuals
2226
Andy Hungee58e4a2023-07-07 13:47:37 -07002227void PlaybackThread::onFirstRef()
Eric Laurent81784c32012-11-19 14:55:58 -08002228{
Jasmine Chaeaa10e42021-05-11 10:11:14 +08002229 if (!isStreamInitialized()) {
jiabinf6eb4c32020-02-25 14:06:25 -08002230 ALOGE("The stream is not open yet"); // This should not happen.
2231 } else {
Mikhail Naganovaec565e2023-02-22 16:31:28 -08002232 // Callbacks take strong or weak pointers as a parameter.
2233 // Since PlaybackThread passes itself as a callback handler, it can only
2234 // be done outside of the constructor. Creating weak and especially strong
2235 // pointers to a refcounted object in its own constructor is strongly
2236 // discouraged, see comments in system/core/libutils/include/utils/RefBase.h.
2237 // Even if a function takes a weak pointer, it is possible that it will
2238 // need to convert it to a strong pointer down the line.
2239 if (mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING &&
2240 mOutput->stream->setCallback(this) == OK) {
2241 mUseAsyncWrite = true;
Andy Hungee58e4a2023-07-07 13:47:37 -07002242 mCallbackThread = sp<AsyncCallbackThread>::make(this);
Mikhail Naganovaec565e2023-02-22 16:31:28 -08002243 }
2244
jiabinf6eb4c32020-02-25 14:06:25 -08002245 if (mOutput->stream->setEventCallback(this) != OK) {
jiabinf1a36052020-08-19 14:33:31 -07002246 ALOGD("Failed to add event callback");
jiabinf6eb4c32020-02-25 14:06:25 -08002247 }
2248 }
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002249 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
Andy Hung44d648b2022-04-08 17:33:40 -07002250 mThreadSnapshot.setTid(getTid());
Eric Laurent81784c32012-11-19 14:55:58 -08002251}
2252
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002253// ThreadBase virtuals
Andy Hungee58e4a2023-07-07 13:47:37 -07002254void PlaybackThread::preExit()
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002255{
2256 ALOGV(" preExit()");
Ytai Ben-Tsvi7e0183f2022-02-04 10:49:54 -08002257 status_t result = mOutput->stream->exit();
2258 ALOGE_IF(result != OK, "Error when calling exit(): %d", result);
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002259}
2260
Andy Hungee58e4a2023-07-07 13:47:37 -07002261void PlaybackThread::dumpTracks_l(int fd, const Vector<String16>& /* args */)
Eric Laurent81784c32012-11-19 14:55:58 -08002262{
Eric Laurent81784c32012-11-19 14:55:58 -08002263 String8 result;
2264
Marco Nelissenb2208842014-02-07 14:00:50 -08002265 result.appendFormat(" Stream volumes in dB: ");
Eric Laurent81784c32012-11-19 14:55:58 -08002266 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
2267 const stream_type_t *st = &mStreamTypes[i];
2268 if (i > 0) {
2269 result.appendFormat(", ");
2270 }
2271 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
2272 if (st->mute) {
2273 result.append("M");
2274 }
2275 }
2276 result.append("\n");
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00002277 write(fd, result.c_str(), result.length());
Eric Laurent81784c32012-11-19 14:55:58 -08002278 result.clear();
2279
Eric Laurent81784c32012-11-19 14:55:58 -08002280 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
2281 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
Elliott Hughes87cebad2014-05-22 10:14:43 -07002282 dprintf(fd, " Normal mixer raw underrun counters: partial=%u empty=%u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08002283 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Marco Nelissenb2208842014-02-07 14:00:50 -08002284
2285 size_t numtracks = mTracks.size();
2286 size_t numactive = mActiveTracks.size();
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002287 dprintf(fd, " %zu Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08002288 size_t numactiveseen = 0;
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002289 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08002290 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002291 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002292 result.append(prefix);
Andy Hungf6ab58d2018-05-25 12:50:39 -07002293 mTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08002294 for (size_t i = 0; i < numtracks; ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07002295 sp<IAfTrack> track = mTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08002296 if (track != 0) {
2297 bool active = mActiveTracks.indexOf(track) >= 0;
2298 if (active) {
2299 numactiveseen++;
2300 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002301 result.append(prefix);
2302 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08002303 }
2304 }
2305 } else {
2306 result.append("\n");
2307 }
2308 if (numactiveseen != numactive) {
2309 // some tracks in the active list were not in the tracks list
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002310 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08002311 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002312 result.append(prefix);
Andy Hungf6ab58d2018-05-25 12:50:39 -07002313 mActiveTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08002314 for (size_t i = 0; i < numactive; ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07002315 sp<IAfTrack> track = mActiveTracks[i];
Andy Hungdae27702016-10-31 14:01:16 -07002316 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002317 result.append(prefix);
2318 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08002319 }
2320 }
2321 }
2322
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00002323 write(fd, result.c_str(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08002324}
2325
Andy Hungee58e4a2023-07-07 13:47:37 -07002326void PlaybackThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -08002327{
Andy Hung04cb8f72020-03-20 13:44:33 -07002328 dprintf(fd, " Master volume: %f\n", mMasterVolume);
Mikhail Naganovdfb411f2018-09-11 13:39:56 -07002329 dprintf(fd, " Master mute: %s\n", mMasterMute ? "on" : "off");
Eric Laurentf1f22e72021-07-13 14:04:14 +02002330 dprintf(fd, " Mixer channel Mask: %#x (%s)\n",
2331 mMixerChannelMask, channelMaskToString(mMixerChannelMask, true /* output */).c_str());
jiabin245cdd92018-12-07 17:55:15 -08002332 if (mHapticChannelMask != AUDIO_CHANNEL_NONE) {
2333 dprintf(fd, " Haptic channel mask: %#x (%s)\n", mHapticChannelMask,
2334 channelMaskToString(mHapticChannelMask, true /* output */).c_str());
2335 }
Elliott Hughes87cebad2014-05-22 10:14:43 -07002336 dprintf(fd, " Normal frame count: %zu\n", mNormalFrameCount);
Elliott Hughes87cebad2014-05-22 10:14:43 -07002337 dprintf(fd, " Total writes: %d\n", mNumWrites);
2338 dprintf(fd, " Delayed writes: %d\n", mNumDelayedWrites);
2339 dprintf(fd, " Blocked in write: %s\n", mInWrite ? "yes" : "no");
Andy Hung8d672e02023-09-15 18:19:28 -07002340 dprintf(fd, " Suspend count: %d\n", (int32_t)mSuspended);
Elliott Hughes87cebad2014-05-22 10:14:43 -07002341 dprintf(fd, " Fast track availMask=%#x\n", mFastTrackAvailMask);
Eric Laurent42537be2016-01-08 17:16:42 -08002342 dprintf(fd, " Standby delay ns=%lld\n", (long long)mStandbyDelayNs);
Glenn Kasten97b7b752014-09-28 13:04:24 -07002343 AudioStreamOut *output = mOutput;
2344 audio_output_flags_t flags = output != NULL ? output->flags : AUDIO_OUTPUT_FLAG_NONE;
Mikhail Naganov913d06c2016-11-01 12:49:22 -07002345 dprintf(fd, " AudioStreamOut: %p flags %#x (%s)\n",
Andy Hung9b181952019-02-25 14:53:36 -08002346 output, flags, toString(flags).c_str());
Andy Hungb54c8542016-09-21 12:55:15 -07002347 dprintf(fd, " Frames written: %lld\n", (long long)mFramesWritten);
2348 dprintf(fd, " Suspended frames: %lld\n", (long long)mSuspendedFrames);
2349 if (mPipeSink.get() != nullptr) {
2350 dprintf(fd, " PipeSink frames written: %lld\n", (long long)mPipeSink->framesWritten());
2351 }
2352 if (output != nullptr) {
2353 dprintf(fd, " Hal stream dump:\n");
Andy Hung61589a42021-06-16 09:37:53 -07002354 (void)output->stream->dump(fd, args);
Andy Hungb54c8542016-09-21 12:55:15 -07002355 }
Eric Laurent81784c32012-11-19 14:55:58 -08002356}
2357
Andy Hungc5007f82023-08-29 14:26:09 -07002358// PlaybackThread::createTrack_l() must be called with AudioFlinger::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07002359sp<IAfTrack> PlaybackThread::createTrack_l(
Andy Hung88035ac2023-06-27 17:05:02 -07002360 const sp<Client>& client,
Eric Laurent81784c32012-11-19 14:55:58 -08002361 audio_stream_type_t streamType,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07002362 const audio_attributes_t& attr,
Eric Laurent21da6472017-11-09 16:29:26 -08002363 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08002364 audio_format_t format,
2365 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08002366 size_t *pFrameCount,
Eric Laurent21da6472017-11-09 16:29:26 -08002367 size_t *pNotificationFrameCount,
2368 uint32_t notificationsPerBuffer,
2369 float speed,
Eric Laurent81784c32012-11-19 14:55:58 -08002370 const sp<IMemory>& sharedBuffer,
Glenn Kastend848eb42016-03-08 13:42:11 -08002371 audio_session_t sessionId,
Eric Laurent05067782016-06-01 18:27:28 -07002372 audio_output_flags_t *flags,
Eric Laurent09f1ed22019-04-24 17:45:17 -07002373 pid_t creatorPid,
Svet Ganov33761132021-05-13 22:51:08 +00002374 const AttributionSourceState& attributionSource,
Eric Laurent81784c32012-11-19 14:55:58 -08002375 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002376 status_t *status,
jiabinf6eb4c32020-02-25 14:06:25 -08002377 audio_port_handle_t portId,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02002378 const sp<media::IAudioTrackCallback>& callback,
jiabinc658e452022-10-21 20:52:21 +00002379 bool isSpatialized,
jiabin94ed47c2023-07-27 23:34:20 +00002380 bool isBitPerfect,
2381 audio_output_flags_t *afTrackFlags)
Eric Laurent81784c32012-11-19 14:55:58 -08002382{
Glenn Kasten74935e42013-12-19 08:56:45 -08002383 size_t frameCount = *pFrameCount;
Eric Laurent21da6472017-11-09 16:29:26 -08002384 size_t notificationFrameCount = *pNotificationFrameCount;
Andy Hung8d31fd22023-06-26 19:20:57 -07002385 sp<IAfTrack> track;
Eric Laurent81784c32012-11-19 14:55:58 -08002386 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07002387 audio_output_flags_t outputFlags = mOutput->flags;
Eric Laurent21da6472017-11-09 16:29:26 -08002388 audio_output_flags_t requestedFlags = *flags;
Eric Laurent9b11c022018-06-06 19:19:22 -07002389 uint32_t sampleRate;
2390
2391 if (sharedBuffer != 0 && checkIMemory(sharedBuffer) != NO_ERROR) {
2392 lStatus = BAD_VALUE;
2393 goto Exit;
2394 }
Eric Laurent21da6472017-11-09 16:29:26 -08002395
2396 if (*pSampleRate == 0) {
2397 *pSampleRate = mSampleRate;
2398 }
Eric Laurent9b11c022018-06-06 19:19:22 -07002399 sampleRate = *pSampleRate;
Eric Laurent05067782016-06-01 18:27:28 -07002400
2401 // special case for FAST flag considered OK if fast mixer is present
2402 if (hasFastMixer()) {
2403 outputFlags = (audio_output_flags_t)(outputFlags | AUDIO_OUTPUT_FLAG_FAST);
2404 }
2405
2406 // Check if requested flags are compatible with output stream flags
2407 if ((*flags & outputFlags) != *flags) {
2408 ALOGW("createTrack_l(): mismatch between requested flags (%08x) and output flags (%08x)",
2409 *flags, outputFlags);
2410 *flags = (audio_output_flags_t)(*flags & outputFlags);
2411 }
Eric Laurent81784c32012-11-19 14:55:58 -08002412
jiabinc658e452022-10-21 20:52:21 +00002413 if (isBitPerfect) {
Andy Hung8d672e02023-09-15 18:19:28 -07002414 audio_utils::lock_guard _l(mutex());
Andy Hung116bc262023-06-20 18:56:17 -07002415 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
jiabinc658e452022-10-21 20:52:21 +00002416 if (chain.get() != nullptr) {
2417 // Bit-perfect is required according to the configuration and preferred mixer
2418 // attributes, but it is not in the output flag from the client's request. Explicitly
2419 // adding bit-perfect flag to check the compatibility
2420 audio_output_flags_t flagsToCheck =
2421 (audio_output_flags_t)(*flags & AUDIO_OUTPUT_FLAG_BIT_PERFECT);
2422 chain->checkOutputFlagCompatibility(&flagsToCheck);
2423 if ((flagsToCheck & AUDIO_OUTPUT_FLAG_BIT_PERFECT) == AUDIO_OUTPUT_FLAG_NONE) {
2424 ALOGE("%s cannot create track as there is data-processing effect attached to "
2425 "given session id(%d)", __func__, sessionId);
2426 lStatus = BAD_VALUE;
2427 goto Exit;
2428 }
2429 *flags = flagsToCheck;
2430 }
2431 }
2432
Eric Laurent81784c32012-11-19 14:55:58 -08002433 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07002434 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
Eric Laurent81784c32012-11-19 14:55:58 -08002435 if (
Eric Laurent81784c32012-11-19 14:55:58 -08002436 // PCM data
2437 audio_is_linear_pcm(format) &&
Andy Hung1f439e12015-05-19 12:57:41 -07002438 // TODO: extract as a data library function that checks that a computationally
2439 // expensive downmixer is not required: isFastOutputChannelConversion()
jiabin245cdd92018-12-07 17:55:15 -08002440 (channelMask == (mChannelMask | mHapticChannelMask) ||
Andy Hung1f439e12015-05-19 12:57:41 -07002441 mChannelMask != AUDIO_CHANNEL_OUT_STEREO ||
2442 (channelMask == AUDIO_CHANNEL_OUT_MONO
2443 /* && mChannelMask == AUDIO_CHANNEL_OUT_STEREO */)) &&
Eric Laurent81784c32012-11-19 14:55:58 -08002444 // hardware sample rate
2445 (sampleRate == mSampleRate) &&
Eric Laurent81784c32012-11-19 14:55:58 -08002446 // normal mixer has an associated fast mixer
2447 hasFastMixer() &&
2448 // there are sufficient fast track slots available
2449 (mFastTrackAvailMask != 0)
2450 // FIXME test that MixerThread for this fast track has a capable output HAL
2451 // FIXME add a permission test also?
2452 ) {
Andy Hunge0a269a2016-03-23 15:13:42 -07002453 // static tracks can have any nonzero framecount, streaming tracks check against minimum.
2454 if (sharedBuffer == 0) {
Glenn Kasten03490092014-05-27 12:30:54 -07002455 // read the fast track multiplier property the first time it is needed
2456 int ok = pthread_once(&sFastTrackMultiplierOnce, sFastTrackMultiplierInit);
2457 if (ok != 0) {
2458 ALOGE("%s pthread_once failed: %d", __func__, ok);
2459 }
Andy Hunge0a269a2016-03-23 15:13:42 -07002460 frameCount = max(frameCount, mFrameCount * sFastTrackMultiplier); // incl framecount 0
Eric Laurent81784c32012-11-19 14:55:58 -08002461 }
Eric Laurent4c415062016-06-17 16:14:16 -07002462
2463 // check compatibility with audio effects.
Andy Hungc5007f82023-08-29 14:26:09 -07002464 { // scope for mutex()
Andy Hung972bec12023-08-31 16:13:39 -07002465 audio_utils::lock_guard _l(mutex());
Andy Hungd3bb0ad2016-10-11 17:16:43 -07002466 for (audio_session_t session : {
Eric Laurent3f75a5b2019-11-12 15:55:51 -08002467 AUDIO_SESSION_DEVICE,
Andy Hungd3bb0ad2016-10-11 17:16:43 -07002468 AUDIO_SESSION_OUTPUT_STAGE,
2469 AUDIO_SESSION_OUTPUT_MIX,
2470 sessionId,
2471 }) {
Andy Hung116bc262023-06-20 18:56:17 -07002472 sp<IAfEffectChain> chain = getEffectChain_l(session);
Andy Hungd3bb0ad2016-10-11 17:16:43 -07002473 if (chain.get() != nullptr) {
2474 audio_output_flags_t old = *flags;
2475 chain->checkOutputFlagCompatibility(flags);
2476 if (old != *flags) {
2477 ALOGV("AUDIO_OUTPUT_FLAGS denied by effect, session=%d old=%#x new=%#x",
2478 (int)session, (int)old, (int)*flags);
2479 }
Eric Laurent4c415062016-06-17 16:14:16 -07002480 }
2481 }
2482 }
Eric Laurent122f7e72016-06-29 11:53:29 -07002483 ALOGV_IF((*flags & AUDIO_OUTPUT_FLAG_FAST) != 0,
Eric Laurent4c415062016-06-17 16:14:16 -07002484 "AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
2485 frameCount, mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08002486 } else {
Robert Wu4c7bb7d2021-08-12 18:50:13 +00002487 ALOGD("AUDIO_OUTPUT_FLAG_FAST denied: sharedBuffer=%p frameCount=%zu "
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002488 "mFrameCount=%zu format=%#x mFormat=%#x isLinear=%d channelMask=%#x "
Andy Hung6146c082014-03-18 11:56:15 -07002489 "sampleRate=%u mSampleRate=%u "
Eric Laurent81784c32012-11-19 14:55:58 -08002490 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
Glenn Kastend79072e2016-01-06 08:41:20 -08002491 sharedBuffer.get(), frameCount, mFrameCount, format, mFormat,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07002492 audio_is_linear_pcm(format), channelMask, sampleRate,
2493 mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
Eric Laurent4c415062016-06-17 16:14:16 -07002494 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_FAST);
Andy Hung0e48d252015-01-26 11:43:15 -08002495 }
2496 }
Eric Laurent21da6472017-11-09 16:29:26 -08002497
2498 if (!audio_has_proportional_frames(format)) {
2499 if (sharedBuffer != 0) {
2500 // Same comment as below about ignoring frameCount parameter for set()
2501 frameCount = sharedBuffer->size();
2502 } else if (frameCount == 0) {
2503 frameCount = mNormalFrameCount;
2504 }
2505 if (notificationFrameCount != frameCount) {
2506 notificationFrameCount = frameCount;
2507 }
2508 } else if (sharedBuffer != 0) {
2509 // FIXME: Ensure client side memory buffers need
2510 // not have additional alignment beyond sample
2511 // (e.g. 16 bit stereo accessed as 32 bit frame).
2512 size_t alignment = audio_bytes_per_sample(format);
2513 if (alignment & 1) {
2514 // for AUDIO_FORMAT_PCM_24_BIT_PACKED (not exposed through Java).
2515 alignment = 1;
2516 }
2517 uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
2518 size_t frameSize = channelCount * audio_bytes_per_sample(format);
2519 if (channelCount > 1) {
2520 // More than 2 channels does not require stronger alignment than stereo
2521 alignment <<= 1;
2522 }
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07002523 if (((uintptr_t)sharedBuffer->unsecurePointer() & (alignment - 1)) != 0) {
Eric Laurent21da6472017-11-09 16:29:26 -08002524 ALOGE("Invalid buffer alignment: address %p, channel count %u",
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07002525 sharedBuffer->unsecurePointer(), channelCount);
Eric Laurent21da6472017-11-09 16:29:26 -08002526 lStatus = BAD_VALUE;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002527 goto Exit;
2528 }
Eric Laurent21da6472017-11-09 16:29:26 -08002529
2530 // When initializing a shared buffer AudioTrack via constructors,
2531 // there's no frameCount parameter.
2532 // But when initializing a shared buffer AudioTrack via set(),
2533 // there _is_ a frameCount parameter. We silently ignore it.
2534 frameCount = sharedBuffer->size() / frameSize;
2535 } else {
2536 size_t minFrameCount = 0;
2537 // For fast tracks we try to respect the application's request for notifications per buffer.
2538 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
2539 if (notificationsPerBuffer > 0) {
2540 // Avoid possible arithmetic overflow during multiplication.
2541 if (notificationsPerBuffer > SIZE_MAX / mFrameCount) {
2542 ALOGE("Requested notificationPerBuffer=%u ignored for HAL frameCount=%zu",
2543 notificationsPerBuffer, mFrameCount);
2544 } else {
2545 minFrameCount = mFrameCount * notificationsPerBuffer;
2546 }
2547 }
2548 } else {
2549 // For normal PCM streaming tracks, update minimum frame count.
2550 // Buffer depth is forced to be at least 2 x the normal mixer frame count and
2551 // cover audio hardware latency.
2552 // This is probably too conservative, but legacy application code may depend on it.
2553 // If you change this calculation, also review the start threshold which is related.
2554 uint32_t latencyMs = latency_l();
2555 if (latencyMs == 0) {
2556 ALOGE("Error when retrieving output stream latency");
2557 lStatus = UNKNOWN_ERROR;
2558 goto Exit;
2559 }
2560
2561 minFrameCount = AudioSystem::calculateMinFrameCount(latencyMs, mNormalFrameCount,
2562 mSampleRate, sampleRate, speed /*, 0 mNotificationsPerBufferReq*/);
2563
Eric Laurent81784c32012-11-19 14:55:58 -08002564 }
Eric Laurent21da6472017-11-09 16:29:26 -08002565 if (frameCount < minFrameCount) {
Eric Laurent81784c32012-11-19 14:55:58 -08002566 frameCount = minFrameCount;
2567 }
Eric Laurent81784c32012-11-19 14:55:58 -08002568 }
Eric Laurent21da6472017-11-09 16:29:26 -08002569
2570 // Make sure that application is notified with sufficient margin before underrun.
2571 // The client can divide the AudioTrack buffer into sub-buffers,
2572 // and expresses its desire to server as the notification frame count.
2573 if (sharedBuffer == 0 && audio_is_linear_pcm(format)) {
2574 size_t maxNotificationFrames;
2575 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
2576 // notify every HAL buffer, regardless of the size of the track buffer
2577 maxNotificationFrames = mFrameCount;
2578 } else {
Andy Hungfa117802019-04-12 13:50:39 -07002579 // Triple buffer the notification period for a triple buffered mixer period;
2580 // otherwise, double buffering for the notification period is fine.
2581 //
2582 // TODO: This should be moved to AudioTrack to modify the notification period
2583 // on AudioTrack::setBufferSizeInFrames() changes.
2584 const int nBuffering =
2585 (uint64_t{frameCount} * mSampleRate)
2586 / (uint64_t{mNormalFrameCount} * sampleRate) == 3 ? 3 : 2;
2587
Eric Laurent21da6472017-11-09 16:29:26 -08002588 maxNotificationFrames = frameCount / nBuffering;
2589 // If client requested a fast track but this was denied, then use the smaller maximum.
2590 if (requestedFlags & AUDIO_OUTPUT_FLAG_FAST) {
2591 size_t maxNotificationFramesFastDenied = FMS_20 * sampleRate / 1000;
2592 if (maxNotificationFrames > maxNotificationFramesFastDenied) {
2593 maxNotificationFrames = maxNotificationFramesFastDenied;
2594 }
2595 }
2596 }
2597 if (notificationFrameCount == 0 || notificationFrameCount > maxNotificationFrames) {
2598 if (notificationFrameCount == 0) {
2599 ALOGD("Client defaulted notificationFrames to %zu for frameCount %zu",
2600 maxNotificationFrames, frameCount);
2601 } else {
2602 ALOGW("Client adjusted notificationFrames from %zu to %zu for frameCount %zu",
2603 notificationFrameCount, maxNotificationFrames, frameCount);
2604 }
2605 notificationFrameCount = maxNotificationFrames;
2606 }
2607 }
2608
Glenn Kasten74935e42013-12-19 08:56:45 -08002609 *pFrameCount = frameCount;
Eric Laurent21da6472017-11-09 16:29:26 -08002610 *pNotificationFrameCount = notificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08002611
Glenn Kastenc3df8382014-03-13 15:05:25 -07002612 switch (mType) {
jiabinc658e452022-10-21 20:52:21 +00002613 case BIT_PERFECT:
2614 if (isBitPerfect) {
2615 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
2616 ALOGE("%s, bad parameter when request streaming bit-perfect, sampleRate=%u, "
2617 "format=%#x, channelMask=%#x, mSampleRate=%u, mFormat=%#x, mChannelMask=%#x",
2618 __func__, sampleRate, format, channelMask, mSampleRate, mFormat,
2619 mChannelMask);
2620 lStatus = BAD_VALUE;
2621 goto Exit;
2622 }
2623 }
2624 break;
Glenn Kastenc3df8382014-03-13 15:05:25 -07002625
2626 case DIRECT:
Phil Burkfdb3c072016-02-09 10:47:02 -08002627 if (audio_is_linear_pcm(format)) { // TODO maybe use audio_has_proportional_frames()?
Eric Laurent81784c32012-11-19 14:55:58 -08002628 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002629 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
2630 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08002631 sampleRate, format, channelMask, mOutput, mFormat);
2632 lStatus = BAD_VALUE;
2633 goto Exit;
2634 }
2635 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002636 break;
2637
2638 case OFFLOAD:
Eric Laurentbfb1b832013-01-07 09:53:42 -08002639 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002640 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
2641 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002642 sampleRate, format, channelMask, mOutput, mFormat);
2643 lStatus = BAD_VALUE;
2644 goto Exit;
2645 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002646 break;
2647
2648 default:
Glenn Kasten993fa062014-05-02 11:14:34 -07002649 if (!audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002650 ALOGE("createTrack_l() Bad parameter: format %#x \""
2651 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002652 format, mOutput, mFormat);
2653 lStatus = BAD_VALUE;
2654 goto Exit;
2655 }
Andy Hungcd044842014-08-07 11:04:34 -07002656 if (sampleRate > mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Eric Laurent81784c32012-11-19 14:55:58 -08002657 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
2658 lStatus = BAD_VALUE;
2659 goto Exit;
2660 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002661 break;
2662
Eric Laurent81784c32012-11-19 14:55:58 -08002663 }
2664
2665 lStatus = initCheck();
2666 if (lStatus != NO_ERROR) {
Glenn Kasten15e57982013-09-24 11:52:37 -07002667 ALOGE("createTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08002668 goto Exit;
2669 }
2670
Andy Hungc5007f82023-08-29 14:26:09 -07002671 { // scope for mutex()
Andy Hung972bec12023-08-31 16:13:39 -07002672 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002673
2674 // all tracks in same audio session must share the same routing strategy otherwise
2675 // conflicts will happen when tracks are moved from one output to another by audio policy
2676 // manager
Eric Laurentd66d7a12021-07-13 13:35:32 +02002677 product_strategy_t strategy = getStrategyForStream(streamType);
Eric Laurent81784c32012-11-19 14:55:58 -08002678 for (size_t i = 0; i < mTracks.size(); ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07002679 sp<IAfTrack> t = mTracks[i];
Eric Laurent83b88082014-06-20 18:31:16 -07002680 if (t != 0 && t->isExternalTrack()) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02002681 product_strategy_t actual = getStrategyForStream(t->streamType());
Eric Laurent81784c32012-11-19 14:55:58 -08002682 if (sessionId == t->sessionId() && strategy != actual) {
2683 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
2684 strategy, actual);
2685 lStatus = BAD_VALUE;
2686 goto Exit;
2687 }
2688 }
2689 }
2690
yucliuc9c49cd2020-07-13 16:25:21 -07002691 // Set DIRECT flag if current thread is DirectOutputThread. This can
2692 // happen when the playback is rerouted to direct output thread by
2693 // dynamic audio policy.
2694 // Do NOT report the flag changes back to client, since the client
2695 // doesn't explicitly request a direct flag.
2696 audio_output_flags_t trackFlags = *flags;
2697 if (mType == DIRECT) {
2698 trackFlags = static_cast<audio_output_flags_t>(trackFlags | AUDIO_OUTPUT_FLAG_DIRECT);
2699 }
jiabin94ed47c2023-07-27 23:34:20 +00002700 *afTrackFlags = trackFlags;
yucliuc9c49cd2020-07-13 16:25:21 -07002701
Andy Hung8d31fd22023-06-26 19:20:57 -07002702 track = IAfTrack::create(this, client, streamType, attr, sampleRate, format,
Andy Hung8fe68032017-06-05 16:17:51 -07002703 channelMask, frameCount,
2704 nullptr /* buffer */, (size_t)0 /* bufferSize */, sharedBuffer,
Svet Ganov33761132021-05-13 22:51:08 +00002705 sessionId, creatorPid, attributionSource, trackFlags,
Andy Hung8d31fd22023-06-26 19:20:57 -07002706 IAfTrackBase::TYPE_DEFAULT, portId, SIZE_MAX /*frameCountToBeReady*/,
jiabinc658e452022-10-21 20:52:21 +00002707 speed, isSpatialized, isBitPerfect);
Glenn Kasten03003332013-08-06 15:40:54 -07002708
Glenn Kasten03003332013-08-06 15:40:54 -07002709 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
2710 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08002711 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08002712 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08002713 goto Exit;
2714 }
2715 mTracks.add(track);
jiabinf6eb4c32020-02-25 14:06:25 -08002716 {
Andy Hung972bec12023-08-31 16:13:39 -07002717 audio_utils::lock_guard _atCbL(audioTrackCbMutex());
jiabinf6eb4c32020-02-25 14:06:25 -08002718 if (callback.get() != nullptr) {
jiabin18a4b1c2020-09-17 11:40:42 -07002719 mAudioTrackCallbacks.emplace(track, callback);
jiabinf6eb4c32020-02-25 14:06:25 -08002720 }
2721 }
Eric Laurent81784c32012-11-19 14:55:58 -08002722
Andy Hung116bc262023-06-20 18:56:17 -07002723 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08002724 if (chain != 0) {
2725 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
2726 track->setMainBuffer(chain->inBuffer());
Eric Laurentd66d7a12021-07-13 13:35:32 +02002727 chain->setStrategy(getStrategyForStream(track->streamType()));
Eric Laurent81784c32012-11-19 14:55:58 -08002728 chain->incTrackCnt();
2729 }
2730
Eric Laurent05067782016-06-01 18:27:28 -07002731 if ((*flags & AUDIO_OUTPUT_FLAG_FAST) && (tid != -1)) {
Eric Laurent81784c32012-11-19 14:55:58 -08002732 pid_t callingPid = IPCThreadState::self()->getCallingPid();
2733 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
2734 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07002735 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08002736 }
2737 }
2738
2739 lStatus = NO_ERROR;
2740
2741Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07002742 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08002743 return track;
2744}
2745
Andy Hung1bc088a2018-02-09 15:57:31 -08002746template<typename T>
Andy Hungee58e4a2023-07-07 13:47:37 -07002747ssize_t PlaybackThread::Tracks<T>::remove(const sp<T>& track)
Andy Hung1bc088a2018-02-09 15:57:31 -08002748{
Andy Hungc0691382018-09-12 18:01:57 -07002749 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08002750 const ssize_t index = mTracks.remove(track);
2751 if (index >= 0) {
Andy Hungc0691382018-09-12 18:01:57 -07002752 if (mSaveDeletedTrackIds) {
Andy Hung1bc088a2018-02-09 15:57:31 -08002753 // We can't directly access mAudioMixer since the caller may be outside of threadLoop.
Andy Hungc0691382018-09-12 18:01:57 -07002754 // Instead, we add to mDeletedTrackIds which is solely used for mAudioMixer update,
Andy Hung1bc088a2018-02-09 15:57:31 -08002755 // to be handled when MixerThread::prepareTracks_l() next changes mAudioMixer.
Andy Hungc0691382018-09-12 18:01:57 -07002756 mDeletedTrackIds.emplace(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08002757 }
Andy Hung1bc088a2018-02-09 15:57:31 -08002758 }
2759 return index;
2760}
2761
Andy Hungee58e4a2023-07-07 13:47:37 -07002762uint32_t PlaybackThread::correctLatency_l(uint32_t latency) const
Eric Laurent81784c32012-11-19 14:55:58 -08002763{
2764 return latency;
2765}
2766
Andy Hungee58e4a2023-07-07 13:47:37 -07002767uint32_t PlaybackThread::latency() const
Eric Laurent81784c32012-11-19 14:55:58 -08002768{
Andy Hung972bec12023-08-31 16:13:39 -07002769 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002770 return latency_l();
2771}
Andy Hungee58e4a2023-07-07 13:47:37 -07002772uint32_t PlaybackThread::latency_l() const
Andy Hungab65b182023-09-06 19:41:47 -07002773NO_THREAD_SAFETY_ANALYSIS
2774// Fix later.
Eric Laurent81784c32012-11-19 14:55:58 -08002775{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002776 uint32_t latency;
2777 if (initCheck() == NO_ERROR && mOutput->stream->getLatency(&latency) == OK) {
2778 return correctLatency_l(latency);
Eric Laurent81784c32012-11-19 14:55:58 -08002779 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002780 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002781}
2782
Andy Hungee58e4a2023-07-07 13:47:37 -07002783void PlaybackThread::setMasterVolume(float value)
Eric Laurent81784c32012-11-19 14:55:58 -08002784{
Andy Hung972bec12023-08-31 16:13:39 -07002785 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002786 // Don't apply master volume in SW if our HAL can do it for us.
2787 if (mOutput && mOutput->audioHwDev &&
2788 mOutput->audioHwDev->canSetMasterVolume()) {
2789 mMasterVolume = 1.0;
2790 } else {
2791 mMasterVolume = value;
2792 }
2793}
2794
Andy Hungee58e4a2023-07-07 13:47:37 -07002795void PlaybackThread::setMasterBalance(float balance)
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01002796{
2797 mMasterBalance.store(balance);
2798}
2799
Andy Hungee58e4a2023-07-07 13:47:37 -07002800void PlaybackThread::setMasterMute(bool muted)
Eric Laurent81784c32012-11-19 14:55:58 -08002801{
Eric Laurent6acd1d42017-01-04 14:23:29 -08002802 if (isDuplicating()) {
2803 return;
2804 }
Andy Hung972bec12023-08-31 16:13:39 -07002805 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002806 // Don't apply master mute in SW if our HAL can do it for us.
2807 if (mOutput && mOutput->audioHwDev &&
2808 mOutput->audioHwDev->canSetMasterMute()) {
2809 mMasterMute = false;
2810 } else {
2811 mMasterMute = muted;
2812 }
2813}
2814
Andy Hungee58e4a2023-07-07 13:47:37 -07002815void PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
Eric Laurent81784c32012-11-19 14:55:58 -08002816{
Andy Hung972bec12023-08-31 16:13:39 -07002817 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002818 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002819 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002820}
2821
Andy Hungee58e4a2023-07-07 13:47:37 -07002822void PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
Eric Laurent81784c32012-11-19 14:55:58 -08002823{
Andy Hung972bec12023-08-31 16:13:39 -07002824 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002825 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002826 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002827}
2828
Andy Hungee58e4a2023-07-07 13:47:37 -07002829float PlaybackThread::streamVolume(audio_stream_type_t stream) const
Eric Laurent81784c32012-11-19 14:55:58 -08002830{
Andy Hung972bec12023-08-31 16:13:39 -07002831 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002832 return mStreamTypes[stream].volume;
2833}
2834
Andy Hungee58e4a2023-07-07 13:47:37 -07002835void PlaybackThread::setVolumeForOutput_l(float left, float right) const
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09002836{
2837 mOutput->stream->setVolume(left, right);
2838}
2839
Andy Hungc5007f82023-08-29 14:26:09 -07002840// addTrack_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07002841status_t PlaybackThread::addTrack_l(const sp<IAfTrack>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002842{
2843 status_t status = ALREADY_EXISTS;
2844
Eric Laurent81784c32012-11-19 14:55:58 -08002845 if (mActiveTracks.indexOf(track) < 0) {
2846 // the track is newly added, make sure it fills up all its
2847 // buffers before playing. This is to ensure the client will
2848 // effectively get the latency it requested.
Eric Laurent83b88082014-06-20 18:31:16 -07002849 if (track->isExternalTrack()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07002850 IAfTrackBase::track_state state = track->state();
Andy Hung6c498e92023-12-05 17:28:17 -08002851 // Because the track is not on the ActiveTracks,
2852 // at this point, only the TrackHandle will be adding the track.
Andy Hungc5007f82023-08-29 14:26:09 -07002853 mutex().unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002854 status = AudioSystem::startOutput(track->portId());
Andy Hungc5007f82023-08-29 14:26:09 -07002855 mutex().lock();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002856 // abort track was stopped/paused while we released the lock
Andy Hung8d31fd22023-06-26 19:20:57 -07002857 if (state != track->state()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002858 if (status == NO_ERROR) {
Andy Hungc5007f82023-08-29 14:26:09 -07002859 mutex().unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002860 AudioSystem::stopOutput(track->portId());
Andy Hungc5007f82023-08-29 14:26:09 -07002861 mutex().lock();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002862 }
2863 return INVALID_OPERATION;
2864 }
2865 // abort if start is rejected by audio policy manager
2866 if (status != NO_ERROR) {
jiabina84c3d32022-12-02 18:59:55 +00002867 // Do not replace the error if it is DEAD_OBJECT. When this happens, it indicates
2868 // current playback thread is reopened, which may happen when clients set preferred
2869 // mixer configuration. Returning DEAD_OBJECT will make the client restore track
2870 // immediately.
2871 return status == DEAD_OBJECT ? status : PERMISSION_DENIED;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002872 }
2873#ifdef ADD_BATTERY_DATA
2874 // to track the speaker usage
2875 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
2876#endif
Eric Laurent09f1ed22019-04-24 17:45:17 -07002877 sendIoConfigEvent_l(AUDIO_CLIENT_STARTED, track->creatorPid(), track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002878 }
2879
Eric Laurent51716182016-02-29 18:00:56 -08002880 // set retry count for buffer fill
2881 if (track->isOffloaded()) {
Eric Laurente93cc032016-05-05 10:15:10 -07002882 if (track->isStopping_1()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07002883 track->retryCount() = kMaxTrackStopRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07002884 } else {
Andy Hung8d31fd22023-06-26 19:20:57 -07002885 track->retryCount() = kMaxTrackStartupRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07002886 }
Andy Hung8d31fd22023-06-26 19:20:57 -07002887 track->fillingStatus() = mStandby ? IAfTrack::FS_FILLING : IAfTrack::FS_FILLED;
Eric Laurent51716182016-02-29 18:00:56 -08002888 } else {
Andy Hung8d31fd22023-06-26 19:20:57 -07002889 track->retryCount() = kMaxTrackStartupRetries;
2890 track->fillingStatus() =
2891 track->sharedBuffer() != 0 ? IAfTrack::FS_FILLED : IAfTrack::FS_FILLING;
Eric Laurent51716182016-02-29 18:00:56 -08002892 }
2893
Andy Hung116bc262023-06-20 18:56:17 -07002894 sp<IAfEffectChain> chain = getEffectChain_l(track->sessionId());
jiabineb3bda02020-06-30 14:07:03 -07002895 if (mHapticChannelMask != AUDIO_CHANNEL_NONE
2896 && ((track->channelMask() & AUDIO_CHANNEL_HAPTIC_ALL) != AUDIO_CHANNEL_NONE
2897 || (chain != nullptr && chain->containsHapticGeneratingEffect_l()))) {
jiabin57303cc2018-12-18 15:45:57 -08002898 // Unlock due to VibratorService will lock for this call and will
2899 // call Tracks.mute/unmute which also require thread's lock.
Andy Hungc5007f82023-08-29 14:26:09 -07002900 mutex().unlock();
Andy Hung7fb97e12023-07-20 21:23:42 -07002901 const os::HapticScale intensity = afutils::onExternalVibrationStart(
jiabin57303cc2018-12-18 15:45:57 -08002902 track->getExternalVibration());
Lais Andradebc3f37a2021-07-02 00:13:19 +01002903 std::optional<media::AudioVibratorInfo> vibratorInfo;
2904 {
2905 // TODO(b/184194780): Use the vibrator information from the vibrator that will be
2906 // used to play this track.
Andy Hung972bec12023-08-31 16:13:39 -07002907 audio_utils::lock_guard _l(mAfThreadCallback->mutex());
Andy Hung583043b2023-07-17 17:05:00 -07002908 vibratorInfo = std::move(mAfThreadCallback->getDefaultVibratorInfo_l());
Lais Andradebc3f37a2021-07-02 00:13:19 +01002909 }
Andy Hungc5007f82023-08-29 14:26:09 -07002910 mutex().lock();
Simon Bowden62823412022-10-17 14:52:26 +00002911 track->setHapticIntensity(intensity);
Lais Andradebc3f37a2021-07-02 00:13:19 +01002912 if (vibratorInfo) {
2913 track->setHapticMaxAmplitude(vibratorInfo->maxAmplitude);
2914 }
2915
jiabin57303cc2018-12-18 15:45:57 -08002916 // Haptic playback should be enabled by vibrator service.
2917 if (track->getHapticPlaybackEnabled()) {
2918 // Disable haptic playback of all active track to ensure only
2919 // one track playing haptic if current track should play haptic.
2920 for (const auto &t : mActiveTracks) {
2921 t->setHapticPlaybackEnabled(false);
2922 }
jiabin245cdd92018-12-07 17:55:15 -08002923 }
jiabine70bc7f2020-06-30 22:07:55 -07002924
2925 // Set haptic intensity for effect
2926 if (chain != nullptr) {
2927 chain->setHapticIntensity_l(track->id(), intensity);
2928 }
jiabin245cdd92018-12-07 17:55:15 -08002929 }
2930
Andy Hung8d31fd22023-06-26 19:20:57 -07002931 track->setResetDone(false);
Andy Hung59de4262021-06-14 10:53:54 -07002932 track->resetPresentationComplete();
Andy Hung6c498e92023-12-05 17:28:17 -08002933
2934 // Do not release the ThreadBase mutex after the track is added to mActiveTracks unless
2935 // all key changes are complete. It is possible that the threadLoop will begin
2936 // processing the added track immediately after the ThreadBase mutex is released.
Eric Laurent81784c32012-11-19 14:55:58 -08002937 mActiveTracks.add(track);
Andy Hung6c498e92023-12-05 17:28:17 -08002938
Eric Laurentd0107bc2013-06-11 14:38:48 -07002939 if (chain != 0) {
2940 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
2941 track->sessionId());
2942 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08002943 }
2944
Andy Hungc2b11cb2020-04-22 09:04:01 -07002945 track->logBeginInterval(patchSinksToString(&mPatch)); // log to MediaMetrics
Eric Laurent81784c32012-11-19 14:55:58 -08002946 status = NO_ERROR;
2947 }
2948
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08002949 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002950 return status;
2951}
2952
Andy Hungee58e4a2023-07-07 13:47:37 -07002953bool PlaybackThread::destroyTrack_l(const sp<IAfTrack>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002954{
Eric Laurentbfb1b832013-01-07 09:53:42 -08002955 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08002956 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002957 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
Andy Hung8d31fd22023-06-26 19:20:57 -07002958 track->setState(IAfTrackBase::STOPPED);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002959 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08002960 removeTrack_l(track);
Eric Laurentab5cdba2014-06-09 17:22:27 -07002961 } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) {
Andy Hung916987e2023-03-20 19:08:16 -07002962 if (track->isPausePending()) {
2963 track->pauseAck();
2964 }
Andy Hung8d31fd22023-06-26 19:20:57 -07002965 track->setState(IAfTrackBase::STOPPING_1);
Eric Laurent81784c32012-11-19 14:55:58 -08002966 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002967
2968 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08002969}
2970
Andy Hungee58e4a2023-07-07 13:47:37 -07002971void PlaybackThread::removeTrack_l(const sp<IAfTrack>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002972{
2973 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Andy Hung2148bf02016-11-28 19:01:02 -08002974
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002975 String8 result;
2976 track->appendDump(result, false /* active */);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00002977 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.c_str());
Andy Hung2148bf02016-11-28 19:01:02 -08002978
Eric Laurent81784c32012-11-19 14:55:58 -08002979 mTracks.remove(track);
jiabin18a4b1c2020-09-17 11:40:42 -07002980 {
Andy Hung972bec12023-08-31 16:13:39 -07002981 audio_utils::lock_guard _atCbL(audioTrackCbMutex());
jiabin18a4b1c2020-09-17 11:40:42 -07002982 mAudioTrackCallbacks.erase(track);
2983 }
Eric Laurent81784c32012-11-19 14:55:58 -08002984 if (track->isFastTrack()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07002985 int index = track->fastIndex();
Glenn Kastendc2c50b2016-04-21 08:13:14 -07002986 ALOG_ASSERT(0 < index && index < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08002987 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
2988 mFastTrackAvailMask |= 1 << index;
2989 // redundant as track is about to be destroyed, for dumpsys only
Andy Hung8d31fd22023-06-26 19:20:57 -07002990 track->fastIndex() = -1;
Eric Laurent81784c32012-11-19 14:55:58 -08002991 }
Andy Hung116bc262023-06-20 18:56:17 -07002992 sp<IAfEffectChain> chain = getEffectChain_l(track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08002993 if (chain != 0) {
2994 chain->decTrackCnt();
2995 }
2996}
2997
Andy Hungee58e4a2023-07-07 13:47:37 -07002998String8 PlaybackThread::getParameters(const String8& keys)
Eric Laurent81784c32012-11-19 14:55:58 -08002999{
Andy Hung972bec12023-08-31 16:13:39 -07003000 audio_utils::lock_guard _l(mutex());
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003001 String8 out_s8;
3002 if (initCheck() == NO_ERROR && mOutput->stream->getParameters(keys, &out_s8) == OK) {
3003 return out_s8;
Eric Laurent81784c32012-11-19 14:55:58 -08003004 }
Andy Hung920f6572022-10-06 12:09:49 -07003005 return {};
Eric Laurent81784c32012-11-19 14:55:58 -08003006}
3007
Andy Hungee58e4a2023-07-07 13:47:37 -07003008status_t DirectOutputThread::selectPresentation(int presentationId, int programId) {
Andy Hung972bec12023-08-31 16:13:39 -07003009 audio_utils::lock_guard _l(mutex());
Jasmine Chaeaa10e42021-05-11 10:11:14 +08003010 if (!isStreamInitialized()) {
Mikhail Naganovac917ac2018-11-28 14:03:52 -08003011 return NO_INIT;
3012 }
3013 return mOutput->stream->selectPresentation(presentationId, programId);
3014}
3015
Andy Hungab65b182023-09-06 19:41:47 -07003016void PlaybackThread::ioConfigChanged_l(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -07003017 audio_port_handle_t portId) {
Eric Laurent73e26b62015-04-27 16:55:58 -07003018 ALOGV("PlaybackThread::ioConfigChanged, thread %p, event %d", this, event);
Mikhail Naganov88536df2021-07-26 17:30:29 -07003019 sp<AudioIoDescriptor> desc;
3020 const struct audio_patch patch = isMsdDevice() ? mDownStreamPatch : mPatch;
Eric Laurent81784c32012-11-19 14:55:58 -08003021 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07003022 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07003023 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07003024 case AUDIO_OUTPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07003025 desc = sp<AudioIoDescriptor>::make(mId, patch, false /*isInput*/,
3026 mSampleRate, mFormat, mChannelMask,
3027 // FIXME AudioFlinger::frameCount(audio_io_handle_t) instead of mNormalFrameCount?
3028 mNormalFrameCount, mFrameCount, latency_l());
Eric Laurent81784c32012-11-19 14:55:58 -08003029 break;
Eric Laurent09f1ed22019-04-24 17:45:17 -07003030 case AUDIO_CLIENT_STARTED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07003031 desc = sp<AudioIoDescriptor>::make(mId, patch, portId);
Eric Laurent09f1ed22019-04-24 17:45:17 -07003032 break;
Eric Laurent73e26b62015-04-27 16:55:58 -07003033 case AUDIO_OUTPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08003034 default:
Mikhail Naganov88536df2021-07-26 17:30:29 -07003035 desc = sp<AudioIoDescriptor>::make(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08003036 break;
3037 }
Andy Hungab65b182023-09-06 19:41:47 -07003038 mAfThreadCallback->ioConfigChanged_l(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08003039}
3040
Andy Hungee58e4a2023-07-07 13:47:37 -07003041void PlaybackThread::onWriteReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08003042{
Eric Laurent3b4529e2013-09-05 18:09:19 -07003043 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003044}
3045
Andy Hungee58e4a2023-07-07 13:47:37 -07003046void PlaybackThread::onDrainReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08003047{
Eric Laurent3b4529e2013-09-05 18:09:19 -07003048 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003049}
3050
Andy Hungee58e4a2023-07-07 13:47:37 -07003051void PlaybackThread::onError()
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07003052{
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07003053 mCallbackThread->setAsyncError();
3054}
3055
Andy Hungee58e4a2023-07-07 13:47:37 -07003056void PlaybackThread::onCodecFormatChanged(
jiabinf6eb4c32020-02-25 14:06:25 -08003057 const std::basic_string<uint8_t>& metadataBs)
3058{
Andy Hungee58e4a2023-07-07 13:47:37 -07003059 const auto weakPointerThis = wp<PlaybackThread>::fromExisting(this);
Kuowei Li9e2f6162022-11-23 16:25:26 +08003060 std::thread([this, metadataBs, weakPointerThis]() {
Andy Hungee58e4a2023-07-07 13:47:37 -07003061 const sp<PlaybackThread> playbackThread = weakPointerThis.promote();
Kuowei Li9e2f6162022-11-23 16:25:26 +08003062 if (playbackThread == nullptr) {
3063 ALOGW("PlaybackThread was destroyed, skip codec format change event");
3064 return;
3065 }
3066
jiabinf6eb4c32020-02-25 14:06:25 -08003067 audio_utils::metadata::Data metadata =
3068 audio_utils::metadata::dataFromByteString(metadataBs);
3069 if (metadata.empty()) {
3070 ALOGW("Can not transform the buffer to audio metadata, %s, %d",
3071 reinterpret_cast<char*>(const_cast<uint8_t*>(metadataBs.data())),
3072 (int)metadataBs.size());
3073 return;
3074 }
3075
3076 audio_utils::metadata::ByteString metaDataStr =
3077 audio_utils::metadata::byteStringFromData(metadata);
3078 std::vector metadataVec(metaDataStr.begin(), metaDataStr.end());
Andy Hung972bec12023-08-31 16:13:39 -07003079 audio_utils::lock_guard _l(audioTrackCbMutex());
jiabin18a4b1c2020-09-17 11:40:42 -07003080 for (const auto& callbackPair : mAudioTrackCallbacks) {
3081 callbackPair.second->onCodecFormatChanged(metadataVec);
jiabinf6eb4c32020-02-25 14:06:25 -08003082 }
3083 }).detach();
3084}
3085
Andy Hungee58e4a2023-07-07 13:47:37 -07003086void PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08003087{
Andy Hung972bec12023-08-31 16:13:39 -07003088 audio_utils::lock_guard _l(mutex());
Eric Laurent3b4529e2013-09-05 18:09:19 -07003089 // reject out of sequence requests
3090 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
3091 mWriteAckSequence &= ~1;
Andy Hungc5007f82023-08-29 14:26:09 -07003092 mWaitWorkCV.notify_one();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003093 }
3094}
3095
Andy Hungee58e4a2023-07-07 13:47:37 -07003096void PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08003097{
Andy Hung972bec12023-08-31 16:13:39 -07003098 audio_utils::lock_guard _l(mutex());
Eric Laurent3b4529e2013-09-05 18:09:19 -07003099 // reject out of sequence requests
3100 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
Andy Hungf3234512018-07-03 14:51:47 -07003101 // Register discontinuity when HW drain is completed because that can cause
3102 // the timestamp frame position to reset to 0 for direct and offload threads.
3103 // (Out of sequence requests are ignored, since the discontinuity would be handled
3104 // elsewhere, e.g. in flush).
Dean Wheatley12473e92021-03-18 23:00:55 +11003105 mTimestampVerifier.discontinuity(mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003106 mDrainSequence &= ~1;
Andy Hungc5007f82023-08-29 14:26:09 -07003107 mWaitWorkCV.notify_one();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003108 }
3109}
3110
Andy Hungee58e4a2023-07-07 13:47:37 -07003111void PlaybackThread::readOutputParameters_l()
Andy Hung972bec12023-08-31 16:13:39 -07003112NO_THREAD_SAFETY_ANALYSIS
3113// 'moveEffectChain_ll' requires holding mutex 'AudioFlinger_Mutex' exclusively
Eric Laurent81784c32012-11-19 14:55:58 -08003114{
Glenn Kastenadad3d72014-02-21 14:51:43 -08003115 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Mikhail Naganov560637e2021-03-31 22:40:13 +00003116 const audio_config_base_t audioConfig = mOutput->getAudioProperties();
3117 mSampleRate = audioConfig.sample_rate;
3118 mChannelMask = audioConfig.channel_mask;
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003119 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08003120 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003121 }
Andy Hung81994d62023-07-20 21:44:14 -07003122 if (hasMixer() && !isValidPcmSinkChannelMask(mChannelMask)) {
Andy Hung9a592762014-07-21 21:56:01 -07003123 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output",
3124 mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003125 }
Eric Laurentf1f22e72021-07-13 14:04:14 +02003126
3127 if (mMixerChannelMask == AUDIO_CHANNEL_NONE) {
3128 mMixerChannelMask = mChannelMask;
3129 }
3130
Andy Hunge5412692014-05-16 11:25:07 -07003131 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01003132 mBalance.setChannelMask(mChannelMask);
Phil Burkca5e6142015-07-14 09:42:29 -07003133
Eric Laurentf1f22e72021-07-13 14:04:14 +02003134 uint32_t mixerChannelCount = audio_channel_count_from_out_mask(mMixerChannelMask);
3135
Phil Burkca5e6142015-07-14 09:42:29 -07003136 // Get actual HAL format.
Mikhail Naganov560637e2021-03-31 22:40:13 +00003137 status_t result = mOutput->stream->getAudioProperties(nullptr, nullptr, &mHALFormat);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003138 LOG_ALWAYS_FATAL_IF(result != OK, "Error when retrieving output stream format: %d", result);
Phil Burkca5e6142015-07-14 09:42:29 -07003139 // Get format from the shim, which will be different than the HAL format
3140 // if playing compressed audio over HDMI passthrough.
Mikhail Naganov560637e2021-03-31 22:40:13 +00003141 mFormat = audioConfig.format;
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003142 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08003143 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003144 }
Andy Hung81994d62023-07-20 21:44:14 -07003145 if (hasMixer() && !isValidPcmSinkFormat(mFormat)) {
Andy Hung6146c082014-03-18 11:56:15 -07003146 LOG_FATAL("HAL format %#x not supported for mixed output",
3147 mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003148 }
Phil Burk062e67a2015-02-11 13:40:50 -08003149 mFrameSize = mOutput->getFrameSize();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003150 result = mOutput->stream->getBufferSize(&mBufferSize);
3151 LOG_ALWAYS_FATAL_IF(result != OK,
3152 "Error when retrieving output stream buffer size: %d", result);
Glenn Kasten70949c42013-08-06 07:40:12 -07003153 mFrameCount = mBufferSize / mFrameSize;
Eric Laurentb3f315a2021-07-13 15:09:05 +02003154 if (hasMixer() && (mFrameCount & 15)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003155 ALOGW("HAL output buffer size is %zu frames but AudioMixer requires multiples of 16 frames",
Eric Laurent81784c32012-11-19 14:55:58 -08003156 mFrameCount);
3157 }
3158
Eric Laurentd1f69b02014-12-15 14:33:13 -08003159 mHwSupportsPause = false;
3160 if (mOutput->flags & AUDIO_OUTPUT_FLAG_DIRECT) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003161 bool supportsPause = false, supportsResume = false;
3162 if (mOutput->stream->supportsPauseAndResume(&supportsPause, &supportsResume) == OK) {
3163 if (supportsPause && supportsResume) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08003164 mHwSupportsPause = true;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003165 } else if (supportsPause) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08003166 ALOGW("direct output implements pause but not resume");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003167 } else if (supportsResume) {
3168 ALOGW("direct output implements resume but not pause");
Eric Laurentd1f69b02014-12-15 14:33:13 -08003169 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08003170 }
3171 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07003172 if (!mHwSupportsPause && mOutput->flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) {
3173 LOG_ALWAYS_FATAL("HW_AV_SYNC requested but HAL does not implement pause and resume");
3174 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08003175
Andy Hungfbfc3952015-01-15 13:33:51 -08003176 if (mType == DUPLICATING && mMixerBufferEnabled && mEffectBufferEnabled) {
3177 // For best precision, we use float instead of the associated output
3178 // device format (typically PCM 16 bit).
3179
3180 mFormat = AUDIO_FORMAT_PCM_FLOAT;
3181 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
3182 mBufferSize = mFrameSize * mFrameCount;
3183
3184 // TODO: We currently use the associated output device channel mask and sample rate.
3185 // (1) Perhaps use the ORed channel mask of all downstream MixerThreads
3186 // (if a valid mask) to avoid premature downmix.
3187 // (2) Perhaps use the maximum sample rate of all downstream MixerThreads
3188 // instead of the output device sample rate to avoid loss of high frequency information.
3189 // This may need to be updated as MixerThread/OutputTracks are added and not here.
3190 }
3191
Andy Hung09a50072014-02-27 14:30:47 -08003192 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08003193 double multiplier = 1.0;
Andy Hungd3639922022-04-28 18:00:49 -07003194 // Note: mType == SPATIALIZER does not support FastMixer.
Eric Laurent81784c32012-11-19 14:55:58 -08003195 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
3196 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08003197 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
3198 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Haynes Mathew George227a14b2016-05-09 12:45:48 -07003199
Eric Laurent81784c32012-11-19 14:55:58 -08003200 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
3201 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
3202 maxNormalFrameCount = maxNormalFrameCount & ~15;
3203 if (maxNormalFrameCount < minNormalFrameCount) {
3204 maxNormalFrameCount = minNormalFrameCount;
3205 }
3206 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
3207 if (multiplier <= 1.0) {
3208 multiplier = 1.0;
3209 } else if (multiplier <= 2.0) {
3210 if (2 * mFrameCount <= maxNormalFrameCount) {
3211 multiplier = 2.0;
3212 } else {
3213 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
3214 }
3215 } else {
Haynes Mathew George227a14b2016-05-09 12:45:48 -07003216 multiplier = floor(multiplier);
Eric Laurent81784c32012-11-19 14:55:58 -08003217 }
3218 }
3219 mNormalFrameCount = multiplier * mFrameCount;
3220 // round up to nearest 16 frames to satisfy AudioMixer
Eric Laurentb3f315a2021-07-13 15:09:05 +02003221 if (hasMixer()) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07003222 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
3223 }
Andy Hungab65b182023-09-06 19:41:47 -07003224 ALOGI("HAL output buffer size %zu frames, normal sink buffer size %zu frames",
3225 (size_t)mFrameCount, mNormalFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08003226
Andy Hung08fb1742015-05-31 23:22:10 -07003227 // Check if we want to throttle the processing to no more than 2x normal rate
3228 mThreadThrottle = property_get_bool("af.thread.throttle", true /* default_value */);
Andy Hung40eb1a12015-06-18 13:42:02 -07003229 mThreadThrottleTimeMs = 0;
3230 mThreadThrottleEndMs = 0;
Andy Hung08fb1742015-05-31 23:22:10 -07003231 mHalfBufferMs = mNormalFrameCount * 1000 / (2 * mSampleRate);
3232
Andy Hung010a1a12014-03-13 13:57:33 -07003233 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
3234 // Originally this was int16_t[] array, need to remove legacy implications.
3235 free(mSinkBuffer);
3236 mSinkBuffer = NULL;
Eric Laurent39095982021-08-24 18:29:27 +02003237
Andy Hung5b10a202014-03-13 13:59:29 -07003238 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
3239 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
3240 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07003241 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08003242
Andy Hung69aed5f2014-02-25 17:24:40 -08003243 // We resize the mMixerBuffer according to the requirements of the sink buffer which
3244 // drives the output.
3245 free(mMixerBuffer);
3246 mMixerBuffer = NULL;
3247 if (mMixerBufferEnabled) {
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01003248 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // no longer valid: AUDIO_FORMAT_PCM_16_BIT.
Eric Laurentf1f22e72021-07-13 14:04:14 +02003249 mMixerBufferSize = mNormalFrameCount * mixerChannelCount
Andy Hung69aed5f2014-02-25 17:24:40 -08003250 * audio_bytes_per_sample(mMixerBufferFormat);
3251 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
3252 }
Andy Hung98ef9782014-03-04 14:46:50 -08003253 free(mEffectBuffer);
3254 mEffectBuffer = NULL;
3255 if (mEffectBufferEnabled) {
Andy Hung319587b2023-05-23 14:01:03 -07003256 mEffectBufferFormat = AUDIO_FORMAT_PCM_FLOAT;
Eric Laurentf1f22e72021-07-13 14:04:14 +02003257 mEffectBufferSize = mNormalFrameCount * mixerChannelCount
Andy Hung98ef9782014-03-04 14:46:50 -08003258 * audio_bytes_per_sample(mEffectBufferFormat);
3259 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
3260 }
Andy Hung69aed5f2014-02-25 17:24:40 -08003261
Eric Laurentb62d0362021-10-26 17:40:18 +02003262 if (mType == SPATIALIZER) {
3263 free(mPostSpatializerBuffer);
3264 mPostSpatializerBuffer = nullptr;
3265 mPostSpatializerBufferSize = mNormalFrameCount * mChannelCount
3266 * audio_bytes_per_sample(mEffectBufferFormat);
3267 (void)posix_memalign(&mPostSpatializerBuffer, 32, mPostSpatializerBufferSize);
3268 }
3269
Mikhail Naganov55773032020-10-01 15:08:13 -07003270 mHapticChannelMask = static_cast<audio_channel_mask_t>(mChannelMask & AUDIO_CHANNEL_HAPTIC_ALL);
3271 mChannelMask = static_cast<audio_channel_mask_t>(mChannelMask & ~mHapticChannelMask);
jiabin245cdd92018-12-07 17:55:15 -08003272 mHapticChannelCount = audio_channel_count_from_out_mask(mHapticChannelMask);
3273 mChannelCount -= mHapticChannelCount;
Eric Laurentf1f22e72021-07-13 14:04:14 +02003274 mMixerChannelMask = static_cast<audio_channel_mask_t>(mMixerChannelMask & ~mHapticChannelMask);
jiabin245cdd92018-12-07 17:55:15 -08003275
Eric Laurent81784c32012-11-19 14:55:58 -08003276 // force reconfiguration of effect chains and engines to take new buffer size and audio
3277 // parameters into account
Andy Hungc5007f82023-08-29 14:26:09 -07003278 // Note that mutex() is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08003279 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
3280 // matter.
Andy Hung972bec12023-08-31 16:13:39 -07003281 // create a copy of mEffectChains as calling moveEffectChain_ll()
3282 // can reorder some effect chains
Andy Hung116bc262023-06-20 18:56:17 -07003283 Vector<sp<IAfEffectChain>> effectChains = mEffectChains;
Eric Laurent81784c32012-11-19 14:55:58 -08003284 for (size_t i = 0; i < effectChains.size(); i ++) {
Andy Hung972bec12023-08-31 16:13:39 -07003285 mAfThreadCallback->moveEffectChain_ll(effectChains[i]->sessionId(),
Eric Laurent6c796322019-04-09 14:13:17 -07003286 this/* srcThread */, this/* dstThread */);
Eric Laurent81784c32012-11-19 14:55:58 -08003287 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08003288
George Burgess IV5e4d86f2020-02-18 12:55:36 -08003289 audio_output_flags_t flags = mOutput->flags;
Andy Hungcf10d742020-04-28 15:38:24 -07003290 mediametrics::LogItem item(mThreadMetrics.getMetricsId()); // TODO: method in ThreadMetrics?
Andy Hungb68f5eb2019-12-03 16:49:17 -08003291 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
Andy Hung25a80ac2023-07-19 12:47:35 -07003292 .set(AMEDIAMETRICS_PROP_ENCODING, IAfThreadBase::formatToString(mFormat).c_str())
Andy Hungb68f5eb2019-12-03 16:49:17 -08003293 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
3294 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
3295 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
3296 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mNormalFrameCount)
3297 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
3298 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELMASK,
3299 (int32_t)mHapticChannelMask)
3300 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELCOUNT,
3301 (int32_t)mHapticChannelCount)
3302 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_ENCODING,
Andy Hung25a80ac2023-07-19 12:47:35 -07003303 IAfThreadBase::formatToString(mHALFormat).c_str())
Andy Hungb68f5eb2019-12-03 16:49:17 -08003304 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_FRAMECOUNT,
3305 (int32_t)mFrameCount) // sic - added HAL
3306 ;
3307 uint32_t latencyMs;
3308 if (mOutput->stream->getLatency(&latencyMs) == NO_ERROR) {
3309 item.set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_LATENCYMS, (double)latencyMs);
3310 }
3311 item.record();
Eric Laurent81784c32012-11-19 14:55:58 -08003312}
3313
Andy Hungee58e4a2023-07-07 13:47:37 -07003314ThreadBase::MetadataUpdate PlaybackThread::updateMetadata_l()
Kevin Rocard069c2712018-03-29 19:09:14 -07003315{
Jasmine Chaeaa10e42021-05-11 10:11:14 +08003316 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
Vlad Popa7e81cea2023-01-19 16:34:16 +01003317 return {}; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -07003318 }
3319 StreamOutHalInterface::SourceMetadata metadata;
Eric Laurent4eb45d02023-12-20 12:07:17 +01003320 if (com_android_media_audio_stereo_spatialization()) {
3321 std::map<audio_session_t, std::vector<playback_track_metadata_v7_t> >allSessionsMetadata;
3322 for (const sp<IAfTrack>& track : mActiveTracks) {
3323 std::vector<playback_track_metadata_v7_t>& sessionMetadata =
3324 allSessionsMetadata[track->sessionId()];
3325 auto backInserter = std::back_inserter(sessionMetadata);
3326 // No track is invalid as this is called after prepareTrack_l in the same
3327 // critical section
3328 track->copyMetadataTo(backInserter);
3329 }
3330 std::vector<playback_track_metadata_v7_t> spatializedTracksMetaData;
3331 for (const auto& [session, sessionTrackMetadata] : allSessionsMetadata) {
3332 metadata.tracks.insert(metadata.tracks.end(),
3333 sessionTrackMetadata.begin(), sessionTrackMetadata.end());
3334 if (auto chain = getEffectChain_l(session) ; chain != nullptr) {
3335 chain->sendMetadata_l(sessionTrackMetadata, {});
3336 }
3337 if ((hasAudioSession_l(session) & IAfThreadBase::SPATIALIZED_SESSION) != 0) {
3338 spatializedTracksMetaData.insert(spatializedTracksMetaData.end(),
3339 sessionTrackMetadata.begin(), sessionTrackMetadata.end());
3340 }
3341 }
3342 if (auto chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX); chain != nullptr) {
3343 chain->sendMetadata_l(metadata.tracks, {});
3344 }
3345 if (auto chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_STAGE); chain != nullptr) {
3346 chain->sendMetadata_l(metadata.tracks, spatializedTracksMetaData);
3347 }
3348 if (auto chain = getEffectChain_l(AUDIO_SESSION_DEVICE); chain != nullptr) {
3349 chain->sendMetadata_l(metadata.tracks, {});
3350 }
3351 } else {
3352 auto backInserter = std::back_inserter(metadata.tracks);
3353 for (const sp<IAfTrack>& track : mActiveTracks) {
3354 // No track is invalid as this is called after prepareTrack_l in the same
3355 // critical section
3356 track->copyMetadataTo(backInserter);
3357 }
Kevin Rocard069c2712018-03-29 19:09:14 -07003358 }
Kevin Rocard12381092018-04-11 09:19:59 -07003359 sendMetadataToBackend_l(metadata);
Vlad Popa7e81cea2023-01-19 16:34:16 +01003360 MetadataUpdate change;
3361 change.playbackMetadataUpdate = metadata.tracks;
3362 return change;
Kevin Rocard80ee2722018-04-11 15:53:48 +00003363}
Kevin Rocardc86a7f72018-04-03 09:00:09 -07003364
Andy Hungee58e4a2023-07-07 13:47:37 -07003365void PlaybackThread::sendMetadataToBackend_l(
Kevin Rocard12381092018-04-11 09:19:59 -07003366 const StreamOutHalInterface::SourceMetadata& metadata)
3367{
3368 mOutput->stream->updateSourceMetadata(metadata);
3369};
3370
Andy Hungee58e4a2023-07-07 13:47:37 -07003371status_t PlaybackThread::getRenderPosition(
Andy Hung440901d2023-06-29 21:19:25 -07003372 uint32_t* halFrames, uint32_t* dspFrames) const
Eric Laurent81784c32012-11-19 14:55:58 -08003373{
3374 if (halFrames == NULL || dspFrames == NULL) {
3375 return BAD_VALUE;
3376 }
Andy Hung972bec12023-08-31 16:13:39 -07003377 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08003378 if (initCheck() != NO_ERROR) {
3379 return INVALID_OPERATION;
3380 }
Andy Hung818e7a32016-02-16 18:08:07 -08003381 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08003382 *halFrames = framesWritten;
3383
3384 if (isSuspended()) {
3385 // return an estimation of rendered frames when the output is suspended
3386 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08003387 *dspFrames = (uint32_t)
3388 (framesWritten >= (int64_t)latencyFrames ? framesWritten - latencyFrames : 0);
Eric Laurent81784c32012-11-19 14:55:58 -08003389 return NO_ERROR;
3390 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003391 status_t status;
3392 uint32_t frames;
Phil Burk062e67a2015-02-11 13:40:50 -08003393 status = mOutput->getRenderPosition(&frames);
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003394 *dspFrames = (size_t)frames;
3395 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08003396 }
3397}
3398
Andy Hungee58e4a2023-07-07 13:47:37 -07003399product_strategy_t PlaybackThread::getStrategyForSession_l(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08003400{
3401 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
3402 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
3403 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02003404 return getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurent81784c32012-11-19 14:55:58 -08003405 }
3406 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003407 sp<IAfTrack> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08003408 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02003409 return getStrategyForStream(track->streamType());
Eric Laurent81784c32012-11-19 14:55:58 -08003410 }
3411 }
Eric Laurentd66d7a12021-07-13 13:35:32 +02003412 return getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurent81784c32012-11-19 14:55:58 -08003413}
3414
3415
Andy Hungee58e4a2023-07-07 13:47:37 -07003416AudioStreamOut* PlaybackThread::getOutput() const
Eric Laurent81784c32012-11-19 14:55:58 -08003417{
Andy Hung972bec12023-08-31 16:13:39 -07003418 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08003419 return mOutput;
3420}
3421
Andy Hungee58e4a2023-07-07 13:47:37 -07003422AudioStreamOut* PlaybackThread::clearOutput()
Eric Laurent81784c32012-11-19 14:55:58 -08003423{
Andy Hung972bec12023-08-31 16:13:39 -07003424 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08003425 AudioStreamOut *output = mOutput;
3426 mOutput = NULL;
3427 // FIXME FastMixer might also have a raw ptr to mOutputSink;
3428 // must push a NULL and wait for ack
3429 mOutputSink.clear();
3430 mPipeSink.clear();
3431 mNormalSink.clear();
3432 return output;
3433}
3434
Andy Hungc5007f82023-08-29 14:26:09 -07003435// this method must always be called either with ThreadBase mutex() held or inside the thread loop
Andy Hungee58e4a2023-07-07 13:47:37 -07003436sp<StreamHalInterface> PlaybackThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08003437{
3438 if (mOutput == NULL) {
3439 return NULL;
3440 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003441 return mOutput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08003442}
3443
Andy Hungee58e4a2023-07-07 13:47:37 -07003444uint32_t PlaybackThread::activeSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08003445{
3446 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
3447}
3448
Andy Hungee58e4a2023-07-07 13:47:37 -07003449status_t PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
Eric Laurent81784c32012-11-19 14:55:58 -08003450{
3451 if (!isValidSyncEvent(event)) {
3452 return BAD_VALUE;
3453 }
3454
Andy Hung972bec12023-08-31 16:13:39 -07003455 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08003456
3457 for (size_t i = 0; i < mTracks.size(); ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003458 sp<IAfTrack> track = mTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08003459 if (event->triggerSession() == track->sessionId()) {
3460 (void) track->setSyncEvent(event);
3461 return NO_ERROR;
3462 }
3463 }
3464
3465 return NAME_NOT_FOUND;
3466}
3467
Andy Hungee58e4a2023-07-07 13:47:37 -07003468bool PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
Eric Laurent81784c32012-11-19 14:55:58 -08003469{
3470 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
3471}
3472
Andy Hungee58e4a2023-07-07 13:47:37 -07003473void PlaybackThread::threadLoop_removeTracks(
Andy Hung8d31fd22023-06-26 19:20:57 -07003474 [[maybe_unused]] const Vector<sp<IAfTrack>>& tracksToRemove)
Eric Laurent81784c32012-11-19 14:55:58 -08003475{
Andy Hungfe726a62018-09-27 15:17:25 -07003476 // Miscellaneous track cleanup when removed from the active list,
3477 // called without Thread lock but synchronized with threadLoop processing.
Eric Laurentbfb1b832013-01-07 09:53:42 -08003478#ifdef ADD_BATTERY_DATA
Andy Hungfe726a62018-09-27 15:17:25 -07003479 for (const auto& track : tracksToRemove) {
3480 if (track->isExternalTrack()) {
3481 // to track the speaker usage
3482 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Eric Laurent81784c32012-11-19 14:55:58 -08003483 }
3484 }
Andy Hungfe726a62018-09-27 15:17:25 -07003485#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003486}
3487
Andy Hungee58e4a2023-07-07 13:47:37 -07003488void PlaybackThread::checkSilentMode_l()
Eric Laurent81784c32012-11-19 14:55:58 -08003489{
3490 if (!mMasterMute) {
3491 char value[PROPERTY_VALUE_MAX];
jiabin0a957d32020-04-29 10:56:20 -07003492 if (mOutDeviceTypeAddrs.empty()) {
3493 ALOGD("ro.audio.silent is ignored since no output device is set");
3494 return;
3495 }
Andy Hungab65b182023-09-06 19:41:47 -07003496 if (isSingleDeviceType(outDeviceTypes_l(), AUDIO_DEVICE_OUT_REMOTE_SUBMIX)) {
Jean-Michel Trivi32f37c22016-03-31 16:00:32 -07003497 ALOGD("ro.audio.silent will be ignored for threads on AUDIO_DEVICE_OUT_REMOTE_SUBMIX");
3498 return;
3499 }
Eric Laurent81784c32012-11-19 14:55:58 -08003500 if (property_get("ro.audio.silent", value, "0") > 0) {
3501 char *endptr;
3502 unsigned long ul = strtoul(value, &endptr, 0);
3503 if (*endptr == '\0' && ul != 0) {
3504 ALOGD("Silence is golden");
3505 // The setprop command will not allow a property to be changed after
3506 // the first time it is set, so we don't have to worry about un-muting.
3507 setMasterMute_l(true);
3508 }
3509 }
3510 }
3511}
3512
3513// shared by MIXER and DIRECT, overridden by DUPLICATING
Andy Hungee58e4a2023-07-07 13:47:37 -07003514ssize_t PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08003515{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07003516 LOG_HIST_TS();
Eric Laurent81784c32012-11-19 14:55:58 -08003517 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003518 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07003519 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08003520
3521 // If an NBAIO sink is present, use it to write the normal mixer's submix
3522 if (mNormalSink != 0) {
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003523
Andy Hung010a1a12014-03-13 13:57:33 -07003524 const size_t count = mBytesRemaining / mFrameSize;
3525
Simon Wilson2d590962012-11-29 15:18:50 -08003526 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08003527 // update the setpoint when AudioFlinger::mScreenState changes
Andy Hung1d2d2aea2023-07-19 16:22:58 -07003528 const uint32_t screenState = mAfThreadCallback->getScreenState();
Eric Laurent81784c32012-11-19 14:55:58 -08003529 if (screenState != mScreenState) {
3530 mScreenState = screenState;
3531 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
3532 if (pipe != NULL) {
3533 pipe->setAvgFrames((mScreenState & 1) ?
3534 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
3535 }
3536 }
Andy Hung010a1a12014-03-13 13:57:33 -07003537 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08003538 ATRACE_END();
Vlad Popab042ee62022-10-20 18:05:00 +02003539
Eric Laurent81784c32012-11-19 14:55:58 -08003540 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07003541 bytesWritten = framesWritten * mFrameSize;
Andy Hung58e32872022-11-15 16:12:24 -08003542
Andy Hung8946a282018-04-19 20:04:56 -07003543#ifdef TEE_SINK
3544 mTee.write((char *)mSinkBuffer + offset, framesWritten);
3545#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003546 } else {
3547 bytesWritten = framesWritten;
3548 }
3549 // otherwise use the HAL / AudioStreamOut directly
3550 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003551 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07003552
Eric Laurentbfb1b832013-01-07 09:53:42 -08003553 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003554 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
3555 mWriteAckSequence += 2;
3556 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003557 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003558 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003559 }
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07003560 ATRACE_BEGIN("write");
Glenn Kasten767094d2013-08-23 13:51:43 -07003561 // FIXME We should have an implementation of timestamps for direct output threads.
3562 // They are used e.g for multichannel PCM playback over HDMI.
Phil Burk062e67a2015-02-11 13:40:50 -08003563 bytesWritten = mOutput->write((char *)mSinkBuffer + offset, mBytesRemaining);
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07003564 ATRACE_END();
Eric Laurent51716182016-02-29 18:00:56 -08003565
Eric Laurentbfb1b832013-01-07 09:53:42 -08003566 if (mUseAsyncWrite &&
3567 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
3568 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07003569 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003570 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003571 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003572 }
Eric Laurent81784c32012-11-19 14:55:58 -08003573 }
3574
Eric Laurent81784c32012-11-19 14:55:58 -08003575 mNumWrites++;
3576 mInWrite = false;
Andy Hungcf10d742020-04-28 15:38:24 -07003577 if (mStandby) {
3578 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07003579 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -07003580 mStandby = false;
3581 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003582 return bytesWritten;
3583}
3584
Andy Hungc5007f82023-08-29 14:26:09 -07003585// startMelComputation_l() must be called with AudioFlinger::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07003586void PlaybackThread::startMelComputation_l(
Vlad Popaf09e93f2022-10-31 16:27:12 +01003587 const sp<audio_utils::MelProcessor>& processor)
Vlad Popab042ee62022-10-20 18:05:00 +02003588{
Vlad Popa3c7a2662023-02-14 20:09:47 +01003589 auto outputSink = static_cast<AudioStreamOutSink*>(mOutputSink.get());
Vlad Popa1a0c3ab2023-03-17 01:07:01 +01003590 if (outputSink != nullptr) {
3591 outputSink->startMelComputation(processor);
3592 }
Vlad Popab042ee62022-10-20 18:05:00 +02003593}
3594
Andy Hungc5007f82023-08-29 14:26:09 -07003595// stopMelComputation_l() must be called with AudioFlinger::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07003596void PlaybackThread::stopMelComputation_l()
Vlad Popa3c7a2662023-02-14 20:09:47 +01003597{
3598 auto outputSink = static_cast<AudioStreamOutSink*>(mOutputSink.get());
Vlad Popa1a0c3ab2023-03-17 01:07:01 +01003599 if (outputSink != nullptr) {
3600 outputSink->stopMelComputation();
3601 }
Vlad Popab042ee62022-10-20 18:05:00 +02003602}
3603
Andy Hungee58e4a2023-07-07 13:47:37 -07003604void PlaybackThread::threadLoop_drain()
Eric Laurentbfb1b832013-01-07 09:53:42 -08003605{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003606 bool supportsDrain = false;
3607 if (mOutput->stream->supportsDrain(&supportsDrain) == OK && supportsDrain) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003608 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
3609 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003610 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
3611 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003612 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003613 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003614 }
Mikhail Naganovcbc8f612016-10-11 18:05:13 -07003615 status_t result = mOutput->stream->drain(mMixerStatus == MIXER_DRAIN_TRACK);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003616 ALOGE_IF(result != OK, "Error when draining stream: %d", result);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003617 }
3618}
3619
Andy Hungee58e4a2023-07-07 13:47:37 -07003620void PlaybackThread::threadLoop_exit()
Eric Laurentbfb1b832013-01-07 09:53:42 -08003621{
Eric Laurent275e8e92014-11-30 15:14:47 -08003622 {
Andy Hung972bec12023-08-31 16:13:39 -07003623 audio_utils::lock_guard _l(mutex());
Eric Laurent275e8e92014-11-30 15:14:47 -08003624 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003625 sp<IAfTrack> track = mTracks[i];
Eric Laurent275e8e92014-11-30 15:14:47 -08003626 track->invalidate();
3627 }
Andy Hungdae27702016-10-31 14:01:16 -07003628 // Clear ActiveTracks to update BatteryNotifier in case active tracks remain.
3629 // After we exit there are no more track changes sent to BatteryNotifier
3630 // because that requires an active threadLoop.
3631 // TODO: should we decActiveTrackCnt() of the cleared track effect chain?
3632 mActiveTracks.clear();
Eric Laurent275e8e92014-11-30 15:14:47 -08003633 }
Eric Laurent81784c32012-11-19 14:55:58 -08003634}
3635
3636/*
3637The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08003638 - mSinkBufferSize from frame count * frame size
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003639 - mActiveSleepTimeUs from activeSleepTimeUs()
3640 - mIdleSleepTimeUs from idleSleepTimeUs()
Eric Laurent42537be2016-01-08 17:16:42 -08003641 - mStandbyDelayNs from mActiveSleepTimeUs (DIRECT only) or forced to at least
3642 kDefaultStandbyTimeInNsecs when connected to an A2DP device.
Eric Laurent81784c32012-11-19 14:55:58 -08003643 - maxPeriod from frame count and sample rate (MIXER only)
3644
3645The parameters that affect these derived values are:
3646 - frame count
3647 - frame size
3648 - sample rate
3649 - device type: A2DP or not
3650 - device latency
3651 - format: PCM or not
3652 - active sleep time
3653 - idle sleep time
3654*/
3655
Andy Hungee58e4a2023-07-07 13:47:37 -07003656void PlaybackThread::cacheParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08003657{
Andy Hung25c2dac2014-02-27 14:56:00 -08003658 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003659 mActiveSleepTimeUs = activeSleepTimeUs();
3660 mIdleSleepTimeUs = idleSleepTimeUs();
Eric Laurent42537be2016-01-08 17:16:42 -08003661
Andy Hung8fe87eb2023-07-20 21:31:38 -07003662 mStandbyDelayNs = getStandbyTimeInNanos();
Carter Hsu0ca47c22023-06-02 18:01:45 +08003663
Eric Laurent42537be2016-01-08 17:16:42 -08003664 // make sure standby delay is not too short when connected to an A2DP sink to avoid
3665 // truncating audio when going to standby.
Andy Hungab65b182023-09-06 19:41:47 -07003666 if (!Intersection(outDeviceTypes_l(), getAudioDeviceOutAllA2dpSet()).empty()) {
Eric Laurent42537be2016-01-08 17:16:42 -08003667 if (mStandbyDelayNs < kDefaultStandbyTimeInNsecs) {
3668 mStandbyDelayNs = kDefaultStandbyTimeInNsecs;
3669 }
3670 }
Eric Laurent81784c32012-11-19 14:55:58 -08003671}
3672
Andy Hungee58e4a2023-07-07 13:47:37 -07003673bool PlaybackThread::invalidateTracks_l(audio_stream_type_t streamType)
Eric Laurent81784c32012-11-19 14:55:58 -08003674{
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003675 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %zu",
Eric Laurent81784c32012-11-19 14:55:58 -08003676 this, streamType, mTracks.size());
Eric Laurent13084622016-05-17 10:51:49 -07003677 bool trackMatch = false;
Eric Laurent81784c32012-11-19 14:55:58 -08003678 size_t size = mTracks.size();
3679 for (size_t i = 0; i < size; i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003680 sp<IAfTrack> t = mTracks[i];
Eric Laurentd60560a2015-04-10 11:31:20 -07003681 if (t->streamType() == streamType && t->isExternalTrack()) {
Glenn Kasten5736c352012-12-04 12:12:34 -08003682 t->invalidate();
Eric Laurent13084622016-05-17 10:51:49 -07003683 trackMatch = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003684 }
3685 }
Eric Laurent13084622016-05-17 10:51:49 -07003686 return trackMatch;
Eric Laurent81784c32012-11-19 14:55:58 -08003687}
3688
Andy Hungee58e4a2023-07-07 13:47:37 -07003689void PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
Haynes Mathew George05317d22016-05-03 16:34:26 -07003690{
Andy Hung972bec12023-08-31 16:13:39 -07003691 audio_utils::lock_guard _l(mutex());
Haynes Mathew George05317d22016-05-03 16:34:26 -07003692 invalidateTracks_l(streamType);
3693}
3694
Andy Hungee58e4a2023-07-07 13:47:37 -07003695void PlaybackThread::invalidateTracks(std::set<audio_port_handle_t>& portIds) {
Andy Hung972bec12023-08-31 16:13:39 -07003696 audio_utils::lock_guard _l(mutex());
jiabinc44b3462022-12-08 12:52:31 -08003697 invalidateTracks_l(portIds);
3698}
3699
Andy Hungee58e4a2023-07-07 13:47:37 -07003700bool PlaybackThread::invalidateTracks_l(std::set<audio_port_handle_t>& portIds) {
jiabinc44b3462022-12-08 12:52:31 -08003701 bool trackMatch = false;
3702 const size_t size = mTracks.size();
3703 for (size_t i = 0; i < size; i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003704 sp<IAfTrack> t = mTracks[i];
jiabinc44b3462022-12-08 12:52:31 -08003705 if (t->isExternalTrack() && portIds.find(t->portId()) != portIds.end()) {
3706 t->invalidate();
3707 portIds.erase(t->portId());
3708 trackMatch = true;
3709 }
3710 if (portIds.empty()) {
3711 break;
3712 }
3713 }
3714 return trackMatch;
3715}
3716
jiabinf042b9b2021-05-07 23:46:28 +00003717// getTrackById_l must be called with holding thread lock
Andy Hungee58e4a2023-07-07 13:47:37 -07003718IAfTrack* PlaybackThread::getTrackById_l(
jiabinf042b9b2021-05-07 23:46:28 +00003719 audio_port_handle_t trackPortId) {
3720 for (size_t i = 0; i < mTracks.size(); i++) {
3721 if (mTracks[i]->portId() == trackPortId) {
3722 return mTracks[i].get();
3723 }
3724 }
3725 return nullptr;
3726}
3727
Andy Hungee58e4a2023-07-07 13:47:37 -07003728status_t PlaybackThread::addEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08003729{
Glenn Kastend848eb42016-03-08 13:42:11 -08003730 audio_session_t session = chain->sessionId();
Mikhail Naganov022b9952017-01-04 16:36:51 -08003731 sp<EffectBufferHalInterface> halInBuffer, halOutBuffer;
Andy Hung319587b2023-05-23 14:01:03 -07003732 float *buffer = nullptr; // only used for non global sessions
Eric Laurentb62d0362021-10-26 17:40:18 +02003733
Andy Hungd3639922022-04-28 18:00:49 -07003734 if (mType == SPATIALIZER) {
Eric Laurentb62d0362021-10-26 17:40:18 +02003735 if (!audio_is_global_session(session)) {
3736 // player sessions on a spatializer output will use a dedicated input buffer and
3737 // will either output multi channel to mEffectBuffer if the track is spatilaized
3738 // or stereo to mPostSpatializerBuffer if not spatialized.
3739 uint32_t channelMask;
3740 bool isSessionSpatialized =
3741 (hasAudioSession_l(session) & ThreadBase::SPATIALIZED_SESSION) != 0;
3742 if (isSessionSpatialized) {
3743 channelMask = mMixerChannelMask;
3744 } else {
3745 channelMask = mChannelMask;
3746 }
Eric Laurentf1f22e72021-07-13 14:04:14 +02003747 size_t numSamples = mNormalFrameCount
Eric Laurentb62d0362021-10-26 17:40:18 +02003748 * (audio_channel_count_from_out_mask(channelMask) + mHapticChannelCount);
Andy Hung583043b2023-07-17 17:05:00 -07003749 status_t result = mAfThreadCallback->getEffectsFactoryHal()->allocateBuffer(
Andy Hung319587b2023-05-23 14:01:03 -07003750 numSamples * sizeof(float),
Mikhail Naganov022b9952017-01-04 16:36:51 -08003751 &halInBuffer);
3752 if (result != OK) return result;
Eric Laurentb62d0362021-10-26 17:40:18 +02003753
Andy Hung583043b2023-07-17 17:05:00 -07003754 result = mAfThreadCallback->getEffectsFactoryHal()->mirrorBuffer(
Eric Laurentb62d0362021-10-26 17:40:18 +02003755 isSessionSpatialized ? mEffectBuffer : mPostSpatializerBuffer,
3756 isSessionSpatialized ? mEffectBufferSize : mPostSpatializerBufferSize,
3757 &halOutBuffer);
3758 if (result != OK) return result;
3759
Shunkai Yao44bdbad2023-01-14 05:11:58 +00003760 buffer = halInBuffer ? halInBuffer->audioBuffer()->f32 : buffer;
Andy Hung26836922023-05-22 17:31:57 -07003761
Mikhail Naganov022b9952017-01-04 16:36:51 -08003762 ALOGV("addEffectChain_l() creating new input buffer %p session %d",
3763 buffer, session);
Eric Laurentb62d0362021-10-26 17:40:18 +02003764 } else {
3765 // A global session on a SPATIALIZER thread is either OUTPUT_STAGE or DEVICE
3766 // - OUTPUT_STAGE session uses the mEffectBuffer as input buffer and
3767 // mPostSpatializerBuffer as output buffer
3768 // - DEVICE session uses the mPostSpatializerBuffer as input and output buffer.
Andy Hung583043b2023-07-17 17:05:00 -07003769 status_t result = mAfThreadCallback->getEffectsFactoryHal()->mirrorBuffer(
Eric Laurentb62d0362021-10-26 17:40:18 +02003770 mEffectBuffer, mEffectBufferSize, &halInBuffer);
3771 if (result != OK) return result;
Andy Hung583043b2023-07-17 17:05:00 -07003772 result = mAfThreadCallback->getEffectsFactoryHal()->mirrorBuffer(
Eric Laurentb62d0362021-10-26 17:40:18 +02003773 mPostSpatializerBuffer, mPostSpatializerBufferSize, &halOutBuffer);
3774 if (result != OK) return result;
Eric Laurent81784c32012-11-19 14:55:58 -08003775
Eric Laurentb62d0362021-10-26 17:40:18 +02003776 if (session == AUDIO_SESSION_DEVICE) {
3777 halInBuffer = halOutBuffer;
3778 }
3779 }
3780 } else {
Andy Hung583043b2023-07-17 17:05:00 -07003781 status_t result = mAfThreadCallback->getEffectsFactoryHal()->mirrorBuffer(
Eric Laurentb62d0362021-10-26 17:40:18 +02003782 mEffectBufferEnabled ? mEffectBuffer : mSinkBuffer,
3783 mEffectBufferEnabled ? mEffectBufferSize : mSinkBufferSize,
3784 &halInBuffer);
3785 if (result != OK) return result;
3786 halOutBuffer = halInBuffer;
3787 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
3788 if (!audio_is_global_session(session)) {
Andy Hung319587b2023-05-23 14:01:03 -07003789 buffer = halInBuffer ? reinterpret_cast<float*>(halInBuffer->externalData())
Shunkai Yao44bdbad2023-01-14 05:11:58 +00003790 : buffer;
Eric Laurentb62d0362021-10-26 17:40:18 +02003791 // Only one effect chain can be present in direct output thread and it uses
3792 // the sink buffer as input
3793 if (mType != DIRECT) {
3794 size_t numSamples = mNormalFrameCount
3795 * (audio_channel_count_from_out_mask(mMixerChannelMask)
3796 + mHapticChannelCount);
Andy Hung583043b2023-07-17 17:05:00 -07003797 const status_t allocateStatus =
3798 mAfThreadCallback->getEffectsFactoryHal()->allocateBuffer(
Andy Hung319587b2023-05-23 14:01:03 -07003799 numSamples * sizeof(float),
Eric Laurentb62d0362021-10-26 17:40:18 +02003800 &halInBuffer);
Andy Hung920f6572022-10-06 12:09:49 -07003801 if (allocateStatus != OK) return allocateStatus;
Andy Hung26836922023-05-22 17:31:57 -07003802
Shunkai Yao44bdbad2023-01-14 05:11:58 +00003803 buffer = halInBuffer ? halInBuffer->audioBuffer()->f32 : buffer;
Eric Laurentb62d0362021-10-26 17:40:18 +02003804 ALOGV("addEffectChain_l() creating new input buffer %p session %d",
3805 buffer, session);
3806 }
3807 }
3808 }
3809
3810 if (!audio_is_global_session(session)) {
Eric Laurent81784c32012-11-19 14:55:58 -08003811 // Attach all tracks with same session ID to this chain.
3812 for (size_t i = 0; i < mTracks.size(); ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003813 sp<IAfTrack> track = mTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08003814 if (session == track->sessionId()) {
Eric Laurentb62d0362021-10-26 17:40:18 +02003815 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p",
3816 track.get(), buffer);
Eric Laurent81784c32012-11-19 14:55:58 -08003817 track->setMainBuffer(buffer);
3818 chain->incTrackCnt();
3819 }
3820 }
3821
3822 // indicate all active tracks in the chain
Andy Hung8d31fd22023-06-26 19:20:57 -07003823 for (const sp<IAfTrack>& track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08003824 if (session == track->sessionId()) {
Eric Laurentb62d0362021-10-26 17:40:18 +02003825 ALOGV("addEffectChain_l() activating track %p on session %d",
3826 track.get(), session);
Eric Laurent81784c32012-11-19 14:55:58 -08003827 chain->incActiveTrackCnt();
3828 }
3829 }
3830 }
Eric Laurentb62d0362021-10-26 17:40:18 +02003831
Eric Laurentaaa44472014-09-12 17:41:50 -07003832 chain->setThread(this);
Mikhail Naganov022b9952017-01-04 16:36:51 -08003833 chain->setInBuffer(halInBuffer);
3834 chain->setOutBuffer(halOutBuffer);
Eric Laurent3f75a5b2019-11-12 15:55:51 -08003835 // Effect chain for session AUDIO_SESSION_DEVICE is inserted at end of effect
3836 // chains list in order to be processed last as it contains output device effects.
3837 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted just before to apply post
3838 // processing effects specific to an output stream before effects applied to all streams
3839 // routed to a given device.
Eric Laurent81784c32012-11-19 14:55:58 -08003840 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
3841 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Glenn Kastend848eb42016-03-08 13:42:11 -08003842 // after track specific effects and before output stage.
Eric Laurent81784c32012-11-19 14:55:58 -08003843 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
Glenn Kastend848eb42016-03-08 13:42:11 -08003844 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX.
Eric Laurent81784c32012-11-19 14:55:58 -08003845 // Effect chain for other sessions are inserted at beginning of effect
3846 // chains list to be processed before output mix effects. Relative order between other
Glenn Kastend848eb42016-03-08 13:42:11 -08003847 // sessions is not important.
3848 static_assert(AUDIO_SESSION_OUTPUT_MIX == 0 &&
Eric Laurent3f75a5b2019-11-12 15:55:51 -08003849 AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX &&
3850 AUDIO_SESSION_DEVICE < AUDIO_SESSION_OUTPUT_STAGE,
Glenn Kastend848eb42016-03-08 13:42:11 -08003851 "audio_session_t constants misdefined");
Eric Laurent81784c32012-11-19 14:55:58 -08003852 size_t size = mEffectChains.size();
3853 size_t i = 0;
3854 for (i = 0; i < size; i++) {
3855 if (mEffectChains[i]->sessionId() < session) {
3856 break;
3857 }
3858 }
3859 mEffectChains.insertAt(chain, i);
3860 checkSuspendOnAddEffectChain_l(chain);
3861
3862 return NO_ERROR;
3863}
3864
Andy Hungee58e4a2023-07-07 13:47:37 -07003865size_t PlaybackThread::removeEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08003866{
Glenn Kastend848eb42016-03-08 13:42:11 -08003867 audio_session_t session = chain->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08003868
3869 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
3870
3871 for (size_t i = 0; i < mEffectChains.size(); i++) {
3872 if (chain == mEffectChains[i]) {
3873 mEffectChains.removeAt(i);
3874 // detach all active tracks from the chain
Andy Hung8d31fd22023-06-26 19:20:57 -07003875 for (const sp<IAfTrack>& track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08003876 if (session == track->sessionId()) {
3877 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
3878 chain.get(), session);
3879 chain->decActiveTrackCnt();
3880 }
3881 }
3882
3883 // detach all tracks with same session ID from this chain
Andy Hung920f6572022-10-06 12:09:49 -07003884 for (size_t j = 0; j < mTracks.size(); ++j) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003885 sp<IAfTrack> track = mTracks[j];
Eric Laurent81784c32012-11-19 14:55:58 -08003886 if (session == track->sessionId()) {
Andy Hung319587b2023-05-23 14:01:03 -07003887 track->setMainBuffer(reinterpret_cast<float*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08003888 chain->decTrackCnt();
3889 }
3890 }
3891 break;
3892 }
3893 }
3894 return mEffectChains.size();
3895}
3896
Andy Hungee58e4a2023-07-07 13:47:37 -07003897status_t PlaybackThread::attachAuxEffect(
Andy Hung8d31fd22023-06-26 19:20:57 -07003898 const sp<IAfTrack>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003899{
Andy Hung972bec12023-08-31 16:13:39 -07003900 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08003901 return attachAuxEffect_l(track, EffectId);
3902}
3903
Andy Hungee58e4a2023-07-07 13:47:37 -07003904status_t PlaybackThread::attachAuxEffect_l(
Andy Hung8d31fd22023-06-26 19:20:57 -07003905 const sp<IAfTrack>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003906{
3907 status_t status = NO_ERROR;
3908
3909 if (EffectId == 0) {
3910 track->setAuxBuffer(0, NULL);
3911 } else {
3912 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
Andy Hung116bc262023-06-20 18:56:17 -07003913 sp<IAfEffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Eric Laurent81784c32012-11-19 14:55:58 -08003914 if (effect != 0) {
3915 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
3916 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
3917 } else {
3918 status = INVALID_OPERATION;
3919 }
3920 } else {
3921 status = BAD_VALUE;
3922 }
3923 }
3924 return status;
3925}
3926
Andy Hungee58e4a2023-07-07 13:47:37 -07003927void PlaybackThread::detachAuxEffect_l(int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003928{
3929 for (size_t i = 0; i < mTracks.size(); ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003930 sp<IAfTrack> track = mTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08003931 if (track->auxEffectId() == effectId) {
3932 attachAuxEffect_l(track, 0);
3933 }
3934 }
3935}
3936
Andy Hungee58e4a2023-07-07 13:47:37 -07003937bool PlaybackThread::threadLoop()
Andy Hung920f6572022-10-06 12:09:49 -07003938NO_THREAD_SAFETY_ANALYSIS // manual locking of AudioFlinger
Eric Laurent81784c32012-11-19 14:55:58 -08003939{
Andy Hung78d8d952023-05-30 18:10:23 -07003940 aflog::setThreadWriter(mNBLogWriter.get());
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003941
Andy Hung077d62e2023-10-03 10:49:34 -07003942 if (mType == SPATIALIZER) {
3943 const pid_t tid = getTid();
3944 if (tid == -1) { // odd: we are here, we must be a running thread.
3945 ALOGW("%s: Cannot update Spatializer mixer thread priority, no tid", __func__);
3946 } else {
Andy Hung639dbc92023-11-28 18:21:55 +00003947 const int priorityBoost = requestSpatializerPriority(getpid(), tid);
3948 if (priorityBoost > 0) {
3949 stream()->setHalThreadPriority(priorityBoost);
3950 }
Andy Hung077d62e2023-10-03 10:49:34 -07003951 }
3952 }
3953
Andy Hung8d31fd22023-06-26 19:20:57 -07003954 Vector<sp<IAfTrack>> tracksToRemove;
Eric Laurent81784c32012-11-19 14:55:58 -08003955
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003956 mStandbyTimeNs = systemTime();
Andy Hung446f4df2019-02-21 12:26:41 -08003957 int64_t lastLoopCountWritten = -2; // never matches "previous" loop, when loopCount = 0.
Eric Laurent81784c32012-11-19 14:55:58 -08003958
3959 // MIXER
3960 nsecs_t lastWarning = 0;
3961
3962 // DUPLICATING
3963 // FIXME could this be made local to while loop?
3964 writeFrames = 0;
3965
3966 cacheParameters_l();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003967 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003968
Andy Hungd3639922022-04-28 18:00:49 -07003969 if (mType == MIXER || mType == SPATIALIZER) {
Eric Laurent81784c32012-11-19 14:55:58 -08003970 sleepTimeShift = 0;
3971 }
3972
3973 CpuStats cpuStats;
3974 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
3975
3976 acquireWakeLock();
3977
Glenn Kasteneef598c2017-04-03 14:41:13 -07003978 // mNBLogWriter logging APIs can only be called by a single thread, typically the
3979 // thread associated with this PlaybackThread.
3980 // If you want to share the mNBLogWriter with other threads (for example, binder threads)
3981 // then all such threads must agree to hold a common mutex before logging.
Glenn Kasten9e58b552013-01-18 15:09:48 -08003982 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
3983 // and then that string will be logged at the next convenient opportunity.
Glenn Kasteneef598c2017-04-03 14:41:13 -07003984 // See reference to logString below.
Glenn Kasten9e58b552013-01-18 15:09:48 -08003985 const char *logString = NULL;
3986
rago1bb90822017-05-02 18:31:48 -07003987 // Estimated time for next buffer to be written to hal. This is used only on
3988 // suspended mode (for now) to help schedule the wait time until next iteration.
3989 nsecs_t timeLoopNextNs = 0;
3990
Eric Laurent664539d2013-09-23 18:24:31 -07003991 checkSilentMode_l();
Glenn Kasteneef598c2017-04-03 14:41:13 -07003992
Andy Hung2dbffc22018-08-08 18:50:41 -07003993 audio_patch_handle_t lastDownstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Andy Hungf3234512018-07-03 14:51:47 -07003994
Eric Laurentb3f315a2021-07-13 15:09:05 +02003995 sendCheckOutputStageEffectsEvent();
3996
Andy Hung446f4df2019-02-21 12:26:41 -08003997 // loopCount is used for statistics and diagnostics.
3998 for (int64_t loopCount = 0; !exitPending(); ++loopCount)
Eric Laurent81784c32012-11-19 14:55:58 -08003999 {
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08004000 // Log merge requests are performed during AudioFlinger binder transactions, but
4001 // that does not cover audio playback. It's requested here for that reason.
Andy Hung583043b2023-07-17 17:05:00 -07004002 mAfThreadCallback->requestLogMerge();
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08004003
Eric Laurent81784c32012-11-19 14:55:58 -08004004 cpuStats.sample(myName);
4005
Andy Hung116bc262023-06-20 18:56:17 -07004006 Vector<sp<IAfEffectChain>> effectChains;
Andy Hung6e6a2e62019-04-30 16:38:41 -07004007 audio_session_t activeHapticSessionId = AUDIO_SESSION_NONE;
Eric Laurentb62d0362021-10-26 17:40:18 +02004008 bool isHapticSessionSpatialized = false;
Andy Hung8d31fd22023-06-26 19:20:57 -07004009 std::vector<sp<IAfTrack>> activeTracks;
Eric Laurent81784c32012-11-19 14:55:58 -08004010
Andy Hung2dbffc22018-08-08 18:50:41 -07004011 // If the device is AUDIO_DEVICE_OUT_BUS, check for downstream latency.
4012 //
Andy Hungc5007f82023-08-29 14:26:09 -07004013 // Note: we access outDeviceTypes() outside of mutex().
Andy Hungab65b182023-09-06 19:41:47 -07004014 if (isMsdDevice() && outDeviceTypes_l().count(AUDIO_DEVICE_OUT_BUS) != 0) {
Andy Hung2dbffc22018-08-08 18:50:41 -07004015 // Here, we try for the AF lock, but do not block on it as the latency
4016 // is more informational.
Andy Hung954b9712023-08-28 18:36:53 -07004017 if (mAfThreadCallback->mutex().try_lock()) {
Andy Hungb6692eb2023-07-13 16:52:46 -07004018 std::vector<SoftwarePatch> swPatches;
Andy Hung920f6572022-10-06 12:09:49 -07004019 double latencyMs = 0.; // not required; initialized for clang-tidy
Andy Hung2dbffc22018-08-08 18:50:41 -07004020 status_t status = INVALID_OPERATION;
4021 audio_patch_handle_t downstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Andy Hung583043b2023-07-17 17:05:00 -07004022 if (mAfThreadCallback->getPatchPanel()->getDownstreamSoftwarePatches(
Andy Hungb6692eb2023-07-13 16:52:46 -07004023 id(), &swPatches) == OK
Andy Hung2dbffc22018-08-08 18:50:41 -07004024 && swPatches.size() > 0) {
4025 status = swPatches[0].getLatencyMs_l(&latencyMs);
4026 downstreamPatchHandle = swPatches[0].getPatchHandle();
4027 }
4028 if (downstreamPatchHandle != lastDownstreamPatchHandle) {
Dean Wheatley30d28422018-11-06 10:27:40 +11004029 mDownstreamLatencyStatMs.reset();
Andy Hung2dbffc22018-08-08 18:50:41 -07004030 lastDownstreamPatchHandle = downstreamPatchHandle;
4031 }
4032 if (status == OK) {
4033 // verify downstream latency (we assume a max reasonable
Mikhail Naganov6aa0a312018-11-09 11:00:01 -08004034 // latency of 5 seconds).
4035 const double minLatency = 0., maxLatency = 5000.;
4036 if (latencyMs >= minLatency && latencyMs <= maxLatency) {
Dean Wheatley56a583e2020-05-08 15:12:17 +10004037 ALOGVV("new downstream latency %lf ms", latencyMs);
Andy Hung2dbffc22018-08-08 18:50:41 -07004038 } else {
4039 ALOGD("out of range downstream latency %lf ms", latencyMs);
Andy Hung920f6572022-10-06 12:09:49 -07004040 latencyMs = std::clamp(latencyMs, minLatency, maxLatency);
Andy Hung2dbffc22018-08-08 18:50:41 -07004041 }
Dean Wheatley30d28422018-11-06 10:27:40 +11004042 mDownstreamLatencyStatMs.add(latencyMs);
Andy Hung2dbffc22018-08-08 18:50:41 -07004043 }
Andy Hung583043b2023-07-17 17:05:00 -07004044 mAfThreadCallback->mutex().unlock();
Andy Hung2dbffc22018-08-08 18:50:41 -07004045 }
4046 } else {
4047 if (lastDownstreamPatchHandle != AUDIO_PATCH_HANDLE_NONE) {
4048 // our device is no longer AUDIO_DEVICE_OUT_BUS, reset patch handle and stats.
Dean Wheatley30d28422018-11-06 10:27:40 +11004049 mDownstreamLatencyStatMs.reset();
Andy Hung2dbffc22018-08-08 18:50:41 -07004050 lastDownstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
4051 }
4052 }
4053
Eric Laurentb3f315a2021-07-13 15:09:05 +02004054 if (mCheckOutputStageEffects.exchange(false)) {
4055 checkOutputStageEffects();
4056 }
4057
Vlad Popa7e81cea2023-01-19 16:34:16 +01004058 MetadataUpdate metadataUpdate;
Andy Hungc5007f82023-08-29 14:26:09 -07004059 { // scope for mutex()
Eric Laurent81784c32012-11-19 14:55:58 -08004060
Andy Hungc5007f82023-08-29 14:26:09 -07004061 audio_utils::unique_lock _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08004062
Eric Laurent021cf962014-05-13 10:18:14 -07004063 processConfigEvents_l();
Eric Laurentb3f315a2021-07-13 15:09:05 +02004064 if (mCheckOutputStageEffects.load()) {
4065 continue;
4066 }
Eric Laurent10351942014-05-08 18:49:52 -07004067
Andy Hungc5007f82023-08-29 14:26:09 -07004068 // See comment at declaration of logString for why this is done under mutex()
Glenn Kasten9e58b552013-01-18 15:09:48 -08004069 if (logString != NULL) {
4070 mNBLogWriter->logTimestamp();
4071 mNBLogWriter->log(logString);
4072 logString = NULL;
4073 }
4074
Dean Wheatley12473e92021-03-18 23:00:55 +11004075 collectTimestamps_l();
Andy Hungc8fddf32018-08-08 18:32:37 -07004076
Eric Laurent81784c32012-11-19 14:55:58 -08004077 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004078 if (mSignalPending) {
4079 // A signal was raised while we were unlocked
4080 mSignalPending = false;
4081 } else if (waitingAsyncCallback_l()) {
4082 if (exitPending()) {
4083 break;
4084 }
Marco Nelissen078538c2015-05-12 09:17:57 -07004085 bool released = false;
Eric Laurent64667972016-03-30 18:19:46 -07004086 if (!keepWakeLock()) {
Marco Nelissen078538c2015-05-12 09:17:57 -07004087 releaseWakeLock_l();
4088 released = true;
4089 }
Andy Hung10cbff12017-02-21 17:30:14 -08004090
4091 const int64_t waitNs = computeWaitTimeNs_l();
4092 ALOGV("wait async completion (wait time: %lld)", (long long)waitNs);
Andy Hungc5007f82023-08-29 14:26:09 -07004093 std::cv_status cvstatus =
4094 mWaitWorkCV.wait_for(_l, std::chrono::nanoseconds(waitNs));
4095 if (cvstatus == std::cv_status::timeout) {
Andy Hung10cbff12017-02-21 17:30:14 -08004096 mSignalPending = true; // if timeout recheck everything
4097 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004098 ALOGV("async completion/wake");
Marco Nelissen078538c2015-05-12 09:17:57 -07004099 if (released) {
4100 acquireWakeLock_l();
4101 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004102 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
4103 mSleepTimeUs = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07004104
4105 continue;
4106 }
Eric Tan39ec8d62018-07-24 09:49:29 -07004107 if ((mActiveTracks.isEmpty() && systemTime() > mStandbyTimeNs) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08004108 isSuspended()) {
4109 // put audio hardware into standby after short delay
4110 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004111
4112 threadLoop_standby();
4113
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07004114 // This is where we go into standby
4115 if (!mStandby) {
4116 LOG_AUDIO_STATE();
Andy Hungcf10d742020-04-28 15:38:24 -07004117 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07004118 mThreadSnapshot.onEnd();
Eric Laurent19952e12023-04-20 10:08:29 +02004119 setStandby_l();
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07004120 }
Andy Hungd0979812019-02-21 15:51:44 -08004121 sendStatistics(false /* force */);
Eric Laurent81784c32012-11-19 14:55:58 -08004122 }
4123
Eric Tan39ec8d62018-07-24 09:49:29 -07004124 if (mActiveTracks.isEmpty() && mConfigEvents.isEmpty()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004125 // we're about to wait, flush the binder command buffer
4126 IPCThreadState::self()->flushCommands();
4127
4128 clearOutputTracks();
4129
4130 if (exitPending()) {
4131 break;
4132 }
4133
4134 releaseWakeLock_l();
4135 // wait until we have something to do...
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004136 ALOGV("%s going to sleep", myName.c_str());
Andy Hungc5007f82023-08-29 14:26:09 -07004137 mWaitWorkCV.wait(_l);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004138 ALOGV("%s waking up", myName.c_str());
Eric Laurent81784c32012-11-19 14:55:58 -08004139 acquireWakeLock_l();
4140
4141 mMixerStatus = MIXER_IDLE;
4142 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
4143 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004144 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08004145 checkSilentMode_l();
4146
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004147 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
4148 mSleepTimeUs = mIdleSleepTimeUs;
Andy Hungd3639922022-04-28 18:00:49 -07004149 if (mType == MIXER || mType == SPATIALIZER) {
Eric Laurent81784c32012-11-19 14:55:58 -08004150 sleepTimeShift = 0;
4151 }
4152
4153 continue;
4154 }
4155 }
Eric Laurent81784c32012-11-19 14:55:58 -08004156 // mMixerStatusIgnoringFastTracks is also updated internally
4157 mMixerStatus = prepareTracks_l(&tracksToRemove);
4158
Andy Hungab65b182023-09-06 19:41:47 -07004159 mActiveTracks.updatePowerState_l(this);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08004160
Vlad Popa7e81cea2023-01-19 16:34:16 +01004161 metadataUpdate = updateMetadata_l();
Kevin Rocard069c2712018-03-29 19:09:14 -07004162
Andy Hungf302e812024-01-26 11:55:15 -08004163 // Acquire a local copy of active tracks with lock (release w/o lock).
4164 //
4165 // Control methods on the track acquire the ThreadBase lock (e.g. start()
4166 // stop(), pause(), etc.), but the threadLoop is entitled to call audio
4167 // data / buffer methods on tracks from activeTracks without the ThreadBase lock.
4168 activeTracks.insert(activeTracks.end(), mActiveTracks.begin(), mActiveTracks.end());
4169
4170 setHalLatencyMode_l();
4171
4172 // updateTeePatches_l will acquire the ThreadBase_Mutex of other threads,
4173 // so this is done before we lock our effect chains.
4174 for (const auto& track : mActiveTracks) {
4175 track->updateTeePatches_l();
4176 }
4177
4178 // signal actual start of output stream when the render position reported by
4179 // the kernel starts moving.
4180 if (!mHalStarted && ((isSuspended() && (mBytesWritten != 0)) || (!mStandby
4181 && (mKernelPositionOnStandby
4182 != mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL])))) {
4183 mHalStarted = true;
4184 mWaitHalStartCV.notify_all();
4185 }
4186
Eric Laurent81784c32012-11-19 14:55:58 -08004187 // prevent any changes in effect chain list and in each effect chain
4188 // during mixing and effect process as the audio buffers could be deleted
4189 // or modified if an effect is created or deleted
4190 lockEffectChains_l(effectChains);
Andy Hung6e6a2e62019-04-30 16:38:41 -07004191
4192 // Determine which session to pick up haptic data.
4193 // This must be done under the same lock as prepareTracks_l().
jiabineb3bda02020-06-30 14:07:03 -07004194 // The haptic data from the effect is at a higher priority than the one from track.
Andy Hung6e6a2e62019-04-30 16:38:41 -07004195 // TODO: Write haptic data directly to sink buffer when mixing.
Eric Laurentb62d0362021-10-26 17:40:18 +02004196 if (mHapticChannelCount > 0) {
Andy Hung6e6a2e62019-04-30 16:38:41 -07004197 for (const auto& track : mActiveTracks) {
Andy Hung116bc262023-06-20 18:56:17 -07004198 sp<IAfEffectChain> effectChain = getEffectChain_l(track->sessionId());
Eric Laurentb62d0362021-10-26 17:40:18 +02004199 if (effectChain != nullptr
4200 && effectChain->containsHapticGeneratingEffect_l()) {
jiabineb3bda02020-06-30 14:07:03 -07004201 activeHapticSessionId = track->sessionId();
Eric Laurentb62d0362021-10-26 17:40:18 +02004202 isHapticSessionSpatialized =
Eric Laurentb0a7bc92022-04-05 15:06:08 +02004203 mType == SPATIALIZER && track->isSpatialized();
jiabineb3bda02020-06-30 14:07:03 -07004204 break;
4205 }
Eric Laurentb62d0362021-10-26 17:40:18 +02004206 if (activeHapticSessionId == AUDIO_SESSION_NONE
4207 && track->getHapticPlaybackEnabled()) {
Andy Hung6e6a2e62019-04-30 16:38:41 -07004208 activeHapticSessionId = track->sessionId();
Eric Laurentb62d0362021-10-26 17:40:18 +02004209 isHapticSessionSpatialized =
Eric Laurentb0a7bc92022-04-05 15:06:08 +02004210 mType == SPATIALIZER && track->isSpatialized();
Andy Hung6e6a2e62019-04-30 16:38:41 -07004211 }
4212 }
4213 }
Andy Hungc5007f82023-08-29 14:26:09 -07004214 } // mutex() scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08004215
Eric Laurentbfb1b832013-01-07 09:53:42 -08004216 if (mBytesRemaining == 0) {
4217 mCurrentWriteLength = 0;
4218 if (mMixerStatus == MIXER_TRACKS_READY) {
4219 // threadLoop_mix() sets mCurrentWriteLength
4220 threadLoop_mix();
4221 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
4222 && (mMixerStatus != MIXER_DRAIN_ALL)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004223 // threadLoop_sleepTime sets mSleepTimeUs to 0 if data
Eric Laurentbfb1b832013-01-07 09:53:42 -08004224 // must be written to HAL
4225 threadLoop_sleepTime();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004226 if (mSleepTimeUs == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08004227 mCurrentWriteLength = mSinkBufferSize;
Andy Hungc1646382019-04-30 16:12:10 -07004228
4229 // Tally underrun frames as we are inserting 0s here.
4230 for (const auto& track : activeTracks) {
Andy Hung8d31fd22023-06-26 19:20:57 -07004231 if (track->fillingStatus() == IAfTrack::FS_ACTIVE
Andy Hunge2e830f2019-12-03 12:54:46 -08004232 && !track->isStopped()
4233 && !track->isPaused()
4234 && !track->isTerminated()) {
4235 ALOGV("%s: track(%d) %s underrun due to thread sleep of %zu frames",
4236 __func__, track->id(), track->getTrackStateAsString(),
4237 mNormalFrameCount);
Andy Hung8d31fd22023-06-26 19:20:57 -07004238 track->audioTrackServerProxy()->tallyUnderrunFrames(
4239 mNormalFrameCount);
Andy Hungc1646382019-04-30 16:12:10 -07004240 }
4241 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004242 }
4243 }
Andy Hung98ef9782014-03-04 14:46:50 -08004244 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004245 // mMixerBuffer with data if mMixerBufferValid is true and mSleepTimeUs == 0.
Andy Hung98ef9782014-03-04 14:46:50 -08004246 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
jiabinc658e452022-10-21 20:52:21 +00004247 // or mSinkBuffer (if there are no effects and there is no data already copied to
4248 // mSinkBuffer).
Andy Hung98ef9782014-03-04 14:46:50 -08004249 //
4250 // This is done pre-effects computation; if effects change to
4251 // support higher precision, this needs to move.
4252 //
4253 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004254 // TODO use mSleepTimeUs == 0 as an additional condition.
Eric Laurent39095982021-08-24 18:29:27 +02004255 uint32_t mixerChannelCount = mEffectBufferValid ?
4256 audio_channel_count_from_out_mask(mMixerChannelMask) : mChannelCount;
jiabinc658e452022-10-21 20:52:21 +00004257 if (mMixerBufferValid && (mEffectBufferValid || !mHasDataCopiedToSinkBuffer)) {
Andy Hung98ef9782014-03-04 14:46:50 -08004258 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
4259 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
4260
David Li88ee0902022-06-22 10:01:21 +08004261 // Apply mono blending and balancing if the effect buffer is not valid. Otherwise,
4262 // do these processes after effects are applied.
4263 if (!mEffectBufferValid) {
4264 // mono blend occurs for mixer threads only (not direct or offloaded)
4265 // and is handled here if we're going directly to the sink.
4266 if (requireMonoBlend()) {
4267 mono_blend(mMixerBuffer, mMixerBufferFormat, mChannelCount,
4268 mNormalFrameCount, true /*limit*/);
4269 }
Andy Hung2ddee192015-12-18 17:34:44 -08004270
David Li88ee0902022-06-22 10:01:21 +08004271 if (!hasFastMixer()) {
4272 // Balance must take effect after mono conversion.
4273 // We do it here if there is no FastMixer.
4274 // mBalance detects zero balance within the class for speed
4275 // (not needed here).
4276 mBalance.setBalance(mMasterBalance.load());
4277 mBalance.process((float *)mMixerBuffer, mNormalFrameCount);
4278 }
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01004279 }
4280
Andy Hung98ef9782014-03-04 14:46:50 -08004281 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
Eric Laurent39095982021-08-24 18:29:27 +02004282 mNormalFrameCount * (mixerChannelCount + mHapticChannelCount));
jiabin245cdd92018-12-07 17:55:15 -08004283
4284 // If we're going directly to the sink and there are haptic channels,
4285 // we should adjust channels as the sample data is partially interleaved
4286 // in this case.
4287 if (!mEffectBufferValid && mHapticChannelCount > 0) {
4288 adjust_channels_non_destructive(buffer, mChannelCount, buffer,
4289 mChannelCount + mHapticChannelCount,
4290 audio_bytes_per_sample(format),
4291 audio_bytes_per_frame(mChannelCount, format) * mNormalFrameCount);
4292 }
Andy Hung98ef9782014-03-04 14:46:50 -08004293 }
4294
Eric Laurentbfb1b832013-01-07 09:53:42 -08004295 mBytesRemaining = mCurrentWriteLength;
4296 if (isSuspended()) {
Andy Hung238fa3d2016-07-28 10:53:22 -07004297 // Simulate write to HAL when suspended (e.g. BT SCO phone call).
4298 mSleepTimeUs = suspendSleepTimeUs(); // assumes full buffer.
4299 const size_t framesRemaining = mBytesRemaining / mFrameSize;
4300 mBytesWritten += mBytesRemaining;
4301 mFramesWritten += framesRemaining;
4302 mSuspendedFrames += framesRemaining; // to adjust kernel HAL position
Eric Laurentbfb1b832013-01-07 09:53:42 -08004303 mBytesRemaining = 0;
4304 }
Eric Laurent81784c32012-11-19 14:55:58 -08004305
Eric Laurentbfb1b832013-01-07 09:53:42 -08004306 // only process effects if we're going to write
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004307 if (mSleepTimeUs == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004308 for (size_t i = 0; i < effectChains.size(); i ++) {
4309 effectChains[i]->process_l();
jiabin47affe52019-04-04 18:02:07 -07004310 // TODO: Write haptic data directly to sink buffer when mixing.
Andy Hung6e6a2e62019-04-30 16:38:41 -07004311 if (activeHapticSessionId != AUDIO_SESSION_NONE
4312 && activeHapticSessionId == effectChains[i]->sessionId()) {
jiabin47affe52019-04-04 18:02:07 -07004313 // Haptic data is active in this case, copy it directly from
4314 // in buffer to out buffer.
Eric Laurentb62d0362021-10-26 17:40:18 +02004315 uint32_t hapticSessionChannelCount = mEffectBufferValid ?
4316 audio_channel_count_from_out_mask(mMixerChannelMask) :
4317 mChannelCount;
4318 if (mType == SPATIALIZER && !isHapticSessionSpatialized) {
4319 hapticSessionChannelCount = mChannelCount;
4320 }
4321
jiabin47affe52019-04-04 18:02:07 -07004322 const size_t audioBufferSize = mNormalFrameCount
Eric Laurentb62d0362021-10-26 17:40:18 +02004323 * audio_bytes_per_frame(hapticSessionChannelCount,
Andy Hung319587b2023-05-23 14:01:03 -07004324 AUDIO_FORMAT_PCM_FLOAT);
jiabin47affe52019-04-04 18:02:07 -07004325 memcpy_by_audio_format(
4326 (uint8_t*)effectChains[i]->outBuffer() + audioBufferSize,
Andy Hung319587b2023-05-23 14:01:03 -07004327 AUDIO_FORMAT_PCM_FLOAT,
jiabin47affe52019-04-04 18:02:07 -07004328 (const uint8_t*)effectChains[i]->inBuffer() + audioBufferSize,
Andy Hung319587b2023-05-23 14:01:03 -07004329 AUDIO_FORMAT_PCM_FLOAT, mNormalFrameCount * mHapticChannelCount);
jiabin47affe52019-04-04 18:02:07 -07004330 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004331 }
Eric Laurent81784c32012-11-19 14:55:58 -08004332 }
4333 }
Eric Laurent59fe0102013-09-27 18:48:26 -07004334 // Process effect chains for offloaded thread even if no audio
4335 // was read from audio track: process only updates effect state
4336 // and thus does have to be synchronized with audio writes but may have
4337 // to be called while waiting for async write callback
4338 if (mType == OFFLOAD) {
4339 for (size_t i = 0; i < effectChains.size(); i ++) {
4340 effectChains[i]->process_l();
4341 }
4342 }
Eric Laurent81784c32012-11-19 14:55:58 -08004343
Andy Hung98ef9782014-03-04 14:46:50 -08004344 // Only if the Effects buffer is enabled and there is data in the
4345 // Effects buffer (buffer valid), we need to
4346 // copy into the sink buffer.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004347 // TODO use mSleepTimeUs == 0 as an additional condition.
jiabinc658e452022-10-21 20:52:21 +00004348 if (mEffectBufferValid && !mHasDataCopiedToSinkBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08004349 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
Eric Laurentb62d0362021-10-26 17:40:18 +02004350 void *effectBuffer = (mType == SPATIALIZER) ? mPostSpatializerBuffer : mEffectBuffer;
Andy Hung2ddee192015-12-18 17:34:44 -08004351 if (requireMonoBlend()) {
Eric Laurentb62d0362021-10-26 17:40:18 +02004352 mono_blend(effectBuffer, mEffectBufferFormat, mChannelCount, mNormalFrameCount,
Glenn Kasten03c48d52016-01-27 17:25:17 -08004353 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08004354 }
4355
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01004356 if (!hasFastMixer()) {
4357 // Balance must take effect after mono conversion.
4358 // We do it here if there is no FastMixer.
4359 // mBalance detects zero balance within the class for speed (not needed here).
4360 mBalance.setBalance(mMasterBalance.load());
Eric Laurentb62d0362021-10-26 17:40:18 +02004361 mBalance.process((float *)effectBuffer, mNormalFrameCount);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01004362 }
4363
Eric Laurentb62d0362021-10-26 17:40:18 +02004364 // for SPATIALIZER thread, Move haptics channels from mEffectBuffer to
4365 // mPostSpatializerBuffer if the haptics track is spatialized.
4366 // Otherwise, the haptics channels are already in mPostSpatializerBuffer.
4367 // For other thread types, the haptics channels are already in mEffectBuffer.
4368 if (mType == SPATIALIZER && isHapticSessionSpatialized) {
4369 const size_t srcBufferSize = mNormalFrameCount *
4370 audio_bytes_per_frame(audio_channel_count_from_out_mask(mMixerChannelMask),
4371 mEffectBufferFormat);
4372 const size_t dstBufferSize = mNormalFrameCount
4373 * audio_bytes_per_frame(mChannelCount, mEffectBufferFormat);
4374
4375 memcpy_by_audio_format((uint8_t*)mPostSpatializerBuffer + dstBufferSize,
4376 mEffectBufferFormat,
4377 (uint8_t*)mEffectBuffer + srcBufferSize,
4378 mEffectBufferFormat,
4379 mNormalFrameCount * mHapticChannelCount);
Eric Laurent39095982021-08-24 18:29:27 +02004380 }
Atneya Nairba9a1072022-09-19 17:51:37 -07004381 const size_t framesToCopy = mNormalFrameCount * (mChannelCount + mHapticChannelCount);
4382 if (mFormat == AUDIO_FORMAT_PCM_FLOAT &&
4383 mEffectBufferFormat == AUDIO_FORMAT_PCM_FLOAT) {
4384 // Clamp PCM float values more than this distance from 0 to insulate
4385 // a HAL which doesn't handle NaN correctly.
4386 static constexpr float HAL_FLOAT_SAMPLE_LIMIT = 2.0f;
4387 memcpy_to_float_from_float_with_clamping(static_cast<float*>(mSinkBuffer),
4388 static_cast<const float*>(effectBuffer),
4389 framesToCopy, HAL_FLOAT_SAMPLE_LIMIT /* absMax */);
4390 } else {
4391 memcpy_by_audio_format(mSinkBuffer, mFormat,
4392 effectBuffer, mEffectBufferFormat, framesToCopy);
4393 }
jiabin245cdd92018-12-07 17:55:15 -08004394 // The sample data is partially interleaved when haptic channels exist,
4395 // we need to adjust channels here.
4396 if (mHapticChannelCount > 0) {
4397 adjust_channels_non_destructive(mSinkBuffer, mChannelCount, mSinkBuffer,
4398 mChannelCount + mHapticChannelCount,
4399 audio_bytes_per_sample(mFormat),
4400 audio_bytes_per_frame(mChannelCount, mFormat) * mNormalFrameCount);
4401 }
Andy Hung98ef9782014-03-04 14:46:50 -08004402 }
4403
Eric Laurent81784c32012-11-19 14:55:58 -08004404 // enable changes in effect chain
4405 unlockEffectChains(effectChains);
4406
Vlad Popafce10862023-02-03 10:37:07 +01004407 if (!metadataUpdate.playbackMetadataUpdate.empty()) {
Andy Hung583043b2023-07-17 17:05:00 -07004408 mAfThreadCallback->getMelReporter()->updateMetadataForCsd(id(),
Vlad Popafce10862023-02-03 10:37:07 +01004409 metadataUpdate.playbackMetadataUpdate);
4410 }
4411
Eric Laurentbfb1b832013-01-07 09:53:42 -08004412 if (!waitingAsyncCallback()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004413 // mSleepTimeUs == 0 means we must write to audio hardware
4414 if (mSleepTimeUs == 0) {
Andy Hung08fb1742015-05-31 23:22:10 -07004415 ssize_t ret = 0;
Andy Hung446f4df2019-02-21 12:26:41 -08004416 // writePeriodNs is updated >= 0 when ret > 0.
4417 int64_t writePeriodNs = -1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004418 if (mBytesRemaining) {
Andy Hung69488c42016-05-16 18:43:33 -07004419 // FIXME rewrite to reduce number of system calls
Andy Hung446f4df2019-02-21 12:26:41 -08004420 const int64_t lastIoBeginNs = systemTime();
Andy Hung08fb1742015-05-31 23:22:10 -07004421 ret = threadLoop_write();
Andy Hung446f4df2019-02-21 12:26:41 -08004422 const int64_t lastIoEndNs = systemTime();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004423 if (ret < 0) {
4424 mBytesRemaining = 0;
Andy Hung446f4df2019-02-21 12:26:41 -08004425 } else if (ret > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004426 mBytesWritten += ret;
4427 mBytesRemaining -= ret;
Andy Hung446f4df2019-02-21 12:26:41 -08004428 const int64_t frames = ret / mFrameSize;
4429 mFramesWritten += frames;
4430
4431 writePeriodNs = lastIoEndNs - mLastIoEndNs;
4432 // process information relating to write time.
4433 if (audio_has_proportional_frames(mFormat)) {
4434 // we are in a continuous mixing cycle
4435 if (mMixerStatus == MIXER_TRACKS_READY &&
4436 loopCount == lastLoopCountWritten + 1) {
4437
4438 const double jitterMs =
4439 TimestampVerifier<int64_t, int64_t>::computeJitterMs(
4440 {frames, writePeriodNs},
4441 {0, 0} /* lastTimestamp */, mSampleRate);
4442 const double processMs =
4443 (lastIoBeginNs - mLastIoEndNs) * 1e-6;
4444
Andy Hung972bec12023-08-31 16:13:39 -07004445 audio_utils::lock_guard _l(mutex());
Andy Hung446f4df2019-02-21 12:26:41 -08004446 mIoJitterMs.add(jitterMs);
4447 mProcessTimeMs.add(processMs);
Robert Wu06db0a32021-08-10 19:05:34 +00004448
4449 if (mPipeSink.get() != nullptr) {
4450 // Using the Monopipe availableToWrite, we estimate the current
4451 // buffer size.
4452 MonoPipe* monoPipe = static_cast<MonoPipe*>(mPipeSink.get());
4453 const ssize_t
4454 availableToWrite = mPipeSink->availableToWrite();
4455 const size_t pipeFrames = monoPipe->maxFrames();
4456 const size_t
4457 remainingFrames = pipeFrames - max(availableToWrite, 0);
4458 mMonopipePipeDepthStats.add(remainingFrames);
4459 }
Andy Hung446f4df2019-02-21 12:26:41 -08004460 }
4461
4462 // write blocked detection
4463 const int64_t deltaWriteNs = lastIoEndNs - lastIoBeginNs;
Andy Hungd3639922022-04-28 18:00:49 -07004464 if ((mType == MIXER || mType == SPATIALIZER)
4465 && deltaWriteNs > maxPeriod) {
Andy Hung446f4df2019-02-21 12:26:41 -08004466 mNumDelayedWrites++;
4467 if ((lastIoEndNs - lastWarning) > kWarningThrottleNs) {
4468 ATRACE_NAME("underrun");
4469 ALOGW("write blocked for %lld msecs, "
4470 "%d delayed writes, thread %d",
4471 (long long)deltaWriteNs / NANOS_PER_MILLISECOND,
4472 mNumDelayedWrites, mId);
4473 lastWarning = lastIoEndNs;
4474 }
4475 }
4476 }
4477 // update timing info.
4478 mLastIoBeginNs = lastIoBeginNs;
4479 mLastIoEndNs = lastIoEndNs;
4480 lastLoopCountWritten = loopCount;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004481 }
4482 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
4483 (mMixerStatus == MIXER_DRAIN_ALL)) {
4484 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08004485 }
Andy Hungd3639922022-04-28 18:00:49 -07004486 if ((mType == MIXER || mType == SPATIALIZER) && !mStandby) {
Andy Hung08fb1742015-05-31 23:22:10 -07004487
4488 if (mThreadThrottle
4489 && mMixerStatus == MIXER_TRACKS_READY // we are mixing (active tracks)
Andy Hung446f4df2019-02-21 12:26:41 -08004490 && writePeriodNs > 0) { // we have write period info
Andy Hung08fb1742015-05-31 23:22:10 -07004491 // Limit MixerThread data processing to no more than twice the
4492 // expected processing rate.
4493 //
4494 // This helps prevent underruns with NuPlayer and other applications
4495 // which may set up buffers that are close to the minimum size, or use
4496 // deep buffers, and rely on a double-buffering sleep strategy to fill.
4497 //
4498 // The throttle smooths out sudden large data drains from the device,
4499 // e.g. when it comes out of standby, which often causes problems with
4500 // (1) mixer threads without a fast mixer (which has its own warm-up)
4501 // (2) minimum buffer sized tracks (even if the track is full,
4502 // the app won't fill fast enough to handle the sudden draw).
Haynes Mathew Georgef92b2172016-05-09 11:34:15 -07004503 //
4504 // Total time spent in last processing cycle equals time spent in
4505 // 1. threadLoop_write, as well as time spent in
4506 // 2. threadLoop_mix (significant for heavy mixing, especially
4507 // on low tier processors)
Andy Hung08fb1742015-05-31 23:22:10 -07004508
Andy Hung446f4df2019-02-21 12:26:41 -08004509 // it's OK if deltaMs is an overestimate.
4510
4511 const int32_t deltaMs = writePeriodNs / NANOS_PER_MILLISECOND;
Ivan Lozanoe02bc542017-10-26 09:51:54 -07004512
Ivan Lozanoea04d392017-11-07 14:37:07 -08004513 const int32_t throttleMs = (int32_t)mHalfBufferMs - deltaMs;
Andy Hung08fb1742015-05-31 23:22:10 -07004514 if ((signed)mHalfBufferMs >= throttleMs && throttleMs > 0) {
Andy Hungcf10d742020-04-28 15:38:24 -07004515 mThreadMetrics.logThrottleMs((double)throttleMs);
Andy Hungb68f5eb2019-12-03 16:49:17 -08004516
Andy Hung08fb1742015-05-31 23:22:10 -07004517 usleep(throttleMs * 1000);
Andy Hung40eb1a12015-06-18 13:42:02 -07004518 // notify of throttle start on verbose log
4519 ALOGV_IF(mThreadThrottleEndMs == mThreadThrottleTimeMs,
4520 "mixer(%p) throttle begin:"
4521 " ret(%zd) deltaMs(%d) requires sleep %d ms",
Andy Hung08fb1742015-05-31 23:22:10 -07004522 this, ret, deltaMs, throttleMs);
Andy Hung40eb1a12015-06-18 13:42:02 -07004523 mThreadThrottleTimeMs += throttleMs;
Andy Hung0a31ddd2016-07-06 19:10:29 -07004524 // Throttle must be attributed to the previous mixer loop's write time
4525 // to allow back-to-back throttling.
Andy Hung446f4df2019-02-21 12:26:41 -08004526 // This also ensures proper timing statistics.
4527 mLastIoEndNs = systemTime(); // we fetch the write end time again.
Andy Hung40eb1a12015-06-18 13:42:02 -07004528 } else {
4529 uint32_t diff = mThreadThrottleTimeMs - mThreadThrottleEndMs;
4530 if (diff > 0) {
4531 // notify of throttle end on debug log
Andy Hung3ea004d2016-05-05 16:48:37 -07004532 // but prevent spamming for bluetooth
jiabinc52b1ff2019-10-31 17:20:42 -07004533 ALOGD_IF(!isSingleDeviceType(
Andy Hungab65b182023-09-06 19:41:47 -07004534 outDeviceTypes_l(), audio_is_a2dp_out_device) &&
jiabinc52b1ff2019-10-31 17:20:42 -07004535 !isSingleDeviceType(
Andy Hungab65b182023-09-06 19:41:47 -07004536 outDeviceTypes_l(),
4537 audio_is_hearing_aid_out_device),
Andy Hung3ea004d2016-05-05 16:48:37 -07004538 "mixer(%p) throttle end: throttle time(%u)", this, diff);
Andy Hung40eb1a12015-06-18 13:42:02 -07004539 mThreadThrottleEndMs = mThreadThrottleTimeMs;
4540 }
Andy Hung08fb1742015-05-31 23:22:10 -07004541 }
4542 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004543 }
Eric Laurent81784c32012-11-19 14:55:58 -08004544
Eric Laurentbfb1b832013-01-07 09:53:42 -08004545 } else {
Glenn Kastene7754022014-10-31 12:11:26 -07004546 ATRACE_BEGIN("sleep");
Andy Hungc5007f82023-08-29 14:26:09 -07004547 audio_utils::unique_lock _l(mutex());
rago1bb90822017-05-02 18:31:48 -07004548 // suspended requires accurate metering of sleep time.
4549 if (isSuspended()) {
4550 // advance by expected sleepTime
4551 timeLoopNextNs += microseconds((nsecs_t)mSleepTimeUs);
4552 const nsecs_t nowNs = systemTime();
4553
4554 // compute expected next time vs current time.
4555 // (negative deltas are treated as delays).
4556 nsecs_t deltaNs = timeLoopNextNs - nowNs;
4557 if (deltaNs < -kMaxNextBufferDelayNs) {
4558 // Delays longer than the max allowed trigger a reset.
4559 ALOGV("DelayNs: %lld, resetting timeLoopNextNs", (long long) deltaNs);
4560 deltaNs = microseconds((nsecs_t)mSleepTimeUs);
4561 timeLoopNextNs = nowNs + deltaNs;
4562 } else if (deltaNs < 0) {
4563 // Delays within the max delay allowed: zero the delta/sleepTime
4564 // to help the system catch up in the next iteration(s)
4565 ALOGV("DelayNs: %lld, catching-up", (long long) deltaNs);
4566 deltaNs = 0;
4567 }
4568 // update sleep time (which is >= 0)
4569 mSleepTimeUs = deltaNs / 1000;
4570 }
Eric Laurente93cc032016-05-05 10:15:10 -07004571 if (!mSignalPending && mConfigEvents.isEmpty() && !exitPending()) {
Andy Hungc5007f82023-08-29 14:26:09 -07004572 mWaitWorkCV.wait_for(_l, std::chrono::microseconds(mSleepTimeUs));
Eric Laurent51716182016-02-29 18:00:56 -08004573 }
Glenn Kastene7754022014-10-31 12:11:26 -07004574 ATRACE_END();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004575 }
Eric Laurent81784c32012-11-19 14:55:58 -08004576 }
4577
4578 // Finally let go of removed track(s), without the lock held
4579 // since we can't guarantee the destructors won't acquire that
4580 // same lock. This will also mutate and push a new fast mixer state.
4581 threadLoop_removeTracks(tracksToRemove);
4582 tracksToRemove.clear();
4583
4584 // FIXME I don't understand the need for this here;
4585 // it was in the original code but maybe the
4586 // assignment in saveOutputTracks() makes this unnecessary?
4587 clearOutputTracks();
4588
4589 // Effect chains will be actually deleted here if they were removed from
4590 // mEffectChains list during mixing or effects processing
4591 effectChains.clear();
4592
4593 // FIXME Note that the above .clear() is no longer necessary since effectChains
4594 // is now local to this block, but will keep it for now (at least until merge done).
4595 }
4596
Eric Laurentbfb1b832013-01-07 09:53:42 -08004597 threadLoop_exit();
4598
Eric Laurentcf817a22014-08-04 20:36:31 -07004599 if (!mStandby) {
4600 threadLoop_standby();
Eric Laurent19952e12023-04-20 10:08:29 +02004601 setStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08004602 }
4603
4604 releaseWakeLock();
4605
4606 ALOGV("Thread %p type %d exiting", this, mType);
4607 return false;
4608}
4609
Andy Hungee58e4a2023-07-07 13:47:37 -07004610void PlaybackThread::collectTimestamps_l()
Dean Wheatley12473e92021-03-18 23:00:55 +11004611{
Dean Wheatley12473e92021-03-18 23:00:55 +11004612 if (mStandby) {
4613 mTimestampVerifier.discontinuity(discontinuityForStandbyOrFlush());
4614 return;
4615 } else if (mHwPaused) {
4616 mTimestampVerifier.discontinuity(mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS);
4617 return;
4618 }
4619
4620 // Gather the framesReleased counters for all active tracks,
4621 // and associate with the sink frames written out. We need
4622 // this to convert the sink timestamp to the track timestamp.
4623 bool kernelLocationUpdate = false;
4624 ExtendedTimestamp timestamp; // use private copy to fetch
4625
4626 // Always query HAL timestamp and update timestamp verifier. In standby or pause,
4627 // HAL may be draining some small duration buffered data for fade out.
4628 if (threadloop_getHalTimestamp_l(&timestamp) == OK) {
4629 mTimestampVerifier.add(timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL],
4630 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4631 mSampleRate);
4632
Andy Hungab65b182023-09-06 19:41:47 -07004633 if (isTimestampCorrectionEnabled_l()) {
Dean Wheatley12473e92021-03-18 23:00:55 +11004634 ALOGVV("TS_BEFORE: %d %lld %lld", id(),
4635 (long long)timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4636 (long long)timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]);
4637 auto correctedTimestamp = mTimestampVerifier.getLastCorrectedTimestamp();
4638 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4639 = correctedTimestamp.mFrames;
4640 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]
4641 = correctedTimestamp.mTimeNs;
4642 ALOGVV("TS_AFTER: %d %lld %lld", id(),
4643 (long long)timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4644 (long long)timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]);
4645
4646 // Note: Downstream latency only added if timestamp correction enabled.
4647 if (mDownstreamLatencyStatMs.getN() > 0) { // we have latency info.
4648 const int64_t newPosition =
4649 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4650 - int64_t(mDownstreamLatencyStatMs.getMean() * mSampleRate * 1e-3);
4651 // prevent retrograde
4652 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = max(
4653 newPosition,
4654 (mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4655 - mSuspendedFrames));
4656 }
4657 }
4658
4659 // We always fetch the timestamp here because often the downstream
4660 // sink will block while writing.
4661
4662 // We keep track of the last valid kernel position in case we are in underrun
4663 // and the normal mixer period is the same as the fast mixer period, or there
4664 // is some error from the HAL.
4665 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
4666 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
4667 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
4668 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
4669 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4670
4671 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
4672 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER];
4673 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
4674 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER];
4675 }
4676
4677 if (timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
4678 kernelLocationUpdate = true;
4679 } else {
4680 ALOGVV("getTimestamp error - no valid kernel position");
4681 }
4682
4683 // copy over kernel info
4684 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] =
4685 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4686 + mSuspendedFrames; // add frames discarded when suspended
4687 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] =
4688 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4689 } else {
4690 mTimestampVerifier.error();
4691 }
4692
4693 // mFramesWritten for non-offloaded tracks are contiguous
4694 // even after standby() is called. This is useful for the track frame
4695 // to sink frame mapping.
4696 bool serverLocationUpdate = false;
4697 if (mFramesWritten != mLastFramesWritten) {
4698 serverLocationUpdate = true;
4699 mLastFramesWritten = mFramesWritten;
4700 }
4701 // Only update timestamps if there is a meaningful change.
4702 // Either the kernel timestamp must be valid or we have written something.
4703 if (kernelLocationUpdate || serverLocationUpdate) {
4704 if (serverLocationUpdate) {
4705 // use the time before we called the HAL write - it is a bit more accurate
4706 // to when the server last read data than the current time here.
4707 //
4708 // If we haven't written anything, mLastIoBeginNs will be -1
4709 // and we use systemTime().
4710 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] = mFramesWritten;
4711 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = mLastIoBeginNs == -1
Andy Hung8d672e02023-09-15 18:19:28 -07004712 ? systemTime() : (int64_t)mLastIoBeginNs;
Dean Wheatley12473e92021-03-18 23:00:55 +11004713 }
4714
Andy Hung8d31fd22023-06-26 19:20:57 -07004715 for (const sp<IAfTrack>& t : mActiveTracks) {
Dean Wheatley12473e92021-03-18 23:00:55 +11004716 if (!t->isFastTrack()) {
4717 t->updateTrackFrameInfo(
Andy Hung8d31fd22023-06-26 19:20:57 -07004718 t->audioTrackServerProxy()->framesReleased(),
Dean Wheatley12473e92021-03-18 23:00:55 +11004719 mFramesWritten,
4720 mSampleRate,
4721 mTimestamp);
4722 }
4723 }
4724 }
4725
4726 if (audio_has_proportional_frames(mFormat)) {
4727 const double latencyMs = mTimestamp.getOutputServerLatencyMs(mSampleRate);
4728 if (latencyMs != 0.) { // note 0. means timestamp is empty.
4729 mLatencyMs.add(latencyMs);
4730 }
4731 }
4732#if 0
4733 // logFormat example
4734 if (z % 100 == 0) {
4735 timespec ts;
4736 clock_gettime(CLOCK_MONOTONIC, &ts);
4737 LOGT("This is an integer %d, this is a float %f, this is my "
4738 "pid %p %% %s %t", 42, 3.14, "and this is a timestamp", ts);
4739 LOGT("A deceptive null-terminated string %\0");
4740 }
4741 ++z;
4742#endif
4743}
4744
Andy Hungc5007f82023-08-29 14:26:09 -07004745// removeTracks_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07004746void PlaybackThread::removeTracks_l(const Vector<sp<IAfTrack>>& tracksToRemove)
Andy Hungc5007f82023-08-29 14:26:09 -07004747NO_THREAD_SAFETY_ANALYSIS // release and re-acquire mutex()
Eric Laurentbfb1b832013-01-07 09:53:42 -08004748{
Andy Hung6c498e92023-12-05 17:28:17 -08004749 if (tracksToRemove.empty()) return;
4750
4751 // Block all incoming TrackHandle requests until we are finished with the release.
4752 setThreadBusy_l(true);
4753
Andy Hungfe726a62018-09-27 15:17:25 -07004754 for (const auto& track : tracksToRemove) {
Andy Hungfe726a62018-09-27 15:17:25 -07004755 ALOGV("%s(%d): removing track on session %d", __func__, track->id(), track->sessionId());
Andy Hung116bc262023-06-20 18:56:17 -07004756 sp<IAfEffectChain> chain = getEffectChain_l(track->sessionId());
Andy Hungfe726a62018-09-27 15:17:25 -07004757 if (chain != 0) {
4758 ALOGV("%s(%d): stopping track on chain %p for session Id: %d",
4759 __func__, track->id(), chain.get(), track->sessionId());
4760 chain->decActiveTrackCnt();
4761 }
Andy Hung6c498e92023-12-05 17:28:17 -08004762
Andy Hungfe726a62018-09-27 15:17:25 -07004763 // If an external client track, inform APM we're no longer active, and remove if needed.
Andy Hung6c498e92023-12-05 17:28:17 -08004764 // Since the track is active, we do it here instead of TrackBase::destroy().
Andy Hungfe726a62018-09-27 15:17:25 -07004765 if (track->isExternalTrack()) {
Andy Hung6c498e92023-12-05 17:28:17 -08004766 mutex().unlock();
Andy Hungfe726a62018-09-27 15:17:25 -07004767 AudioSystem::stopOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08004768 if (track->isTerminated()) {
Andy Hungfe726a62018-09-27 15:17:25 -07004769 AudioSystem::releaseOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08004770 }
Andy Hung6c498e92023-12-05 17:28:17 -08004771 mutex().lock();
Andy Hungfe726a62018-09-27 15:17:25 -07004772 }
jiabineb3bda02020-06-30 14:07:03 -07004773 if (mHapticChannelCount > 0 &&
4774 ((track->channelMask() & AUDIO_CHANNEL_HAPTIC_ALL) != AUDIO_CHANNEL_NONE
4775 || (chain != nullptr && chain->containsHapticGeneratingEffect_l()))) {
Andy Hungc5007f82023-08-29 14:26:09 -07004776 mutex().unlock();
jiabin57303cc2018-12-18 15:45:57 -08004777 // Unlock due to VibratorService will lock for this call and will
4778 // call Tracks.mute/unmute which also require thread's lock.
Andy Hung7fb97e12023-07-20 21:23:42 -07004779 afutils::onExternalVibrationStop(track->getExternalVibration());
Andy Hungc5007f82023-08-29 14:26:09 -07004780 mutex().lock();
jiabine70bc7f2020-06-30 22:07:55 -07004781
4782 // When the track is stop, set the haptic intensity as MUTE
4783 // for the HapticGenerator effect.
4784 if (chain != nullptr) {
Simon Bowden62823412022-10-17 14:52:26 +00004785 chain->setHapticIntensity_l(track->id(), os::HapticScale::MUTE);
jiabine70bc7f2020-06-30 22:07:55 -07004786 }
jiabin245cdd92018-12-07 17:55:15 -08004787 }
Andy Hung6c498e92023-12-05 17:28:17 -08004788
4789 // Under lock, the track is removed from the active tracks list.
4790 //
4791 // Once the track is no longer active, the TrackHandle may directly
4792 // modify it as the threadLoop() is no longer responsible for its maintenance.
4793 // Do not modify the track from threadLoop after the mutex is unlocked
4794 // if it is not active.
4795 mActiveTracks.remove(track);
4796
4797 if (track->isTerminated()) {
4798 // remove from our tracks vector
4799 removeTrack_l(track);
4800 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004801 }
Andy Hung6c498e92023-12-05 17:28:17 -08004802
4803 // Allow incoming TrackHandle requests. We still hold the mutex,
4804 // so pending TrackHandle requests will occur after we unlock it.
4805 setThreadBusy_l(false);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004806}
Eric Laurent81784c32012-11-19 14:55:58 -08004807
Andy Hungee58e4a2023-07-07 13:47:37 -07004808status_t PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
Eric Laurentaccc1472013-09-20 09:36:34 -07004809{
4810 if (mNormalSink != 0) {
Andy Hung818e7a32016-02-16 18:08:07 -08004811 ExtendedTimestamp ets;
4812 status_t status = mNormalSink->getTimestamp(ets);
4813 if (status == NO_ERROR) {
4814 status = ets.getBestTimestamp(&timestamp);
4815 }
4816 return status;
Eric Laurentaccc1472013-09-20 09:36:34 -07004817 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004818 if ((mType == OFFLOAD || mType == DIRECT) && mOutput != NULL) {
Dean Wheatley12473e92021-03-18 23:00:55 +11004819 collectTimestamps_l();
4820 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] <= 0) {
4821 return INVALID_OPERATION;
Eric Laurentaccc1472013-09-20 09:36:34 -07004822 }
Dean Wheatley12473e92021-03-18 23:00:55 +11004823 timestamp.mPosition = mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
4824 const int64_t timeNs = mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4825 timestamp.mTime.tv_sec = timeNs / NANOS_PER_SECOND;
4826 timestamp.mTime.tv_nsec = timeNs - (timestamp.mTime.tv_sec * NANOS_PER_SECOND);
4827 return NO_ERROR;
Eric Laurentaccc1472013-09-20 09:36:34 -07004828 }
4829 return INVALID_OPERATION;
4830}
Eric Laurent1c333e22014-05-20 10:48:17 -07004831
Eric Laurenteab90452019-06-24 15:17:46 -07004832// For dedicated VoIP outputs, let the HAL apply the stream volume. Track volume is
4833// still applied by the mixer.
4834// All tracks attached to a mixer with flag VOIP_RX are tied to the same
4835// stream type STREAM_VOICE_CALL so this will only change the HAL volume once even
4836// if more than one track are active
Andy Hungee58e4a2023-07-07 13:47:37 -07004837status_t PlaybackThread::handleVoipVolume_l(float* volume)
Eric Laurenteab90452019-06-24 15:17:46 -07004838{
4839 status_t result = NO_ERROR;
4840 if ((mOutput->flags & AUDIO_OUTPUT_FLAG_VOIP_RX) != 0) {
4841 if (*volume != mLeftVolFloat) {
4842 result = mOutput->stream->setVolume(*volume, *volume);
Alex Leungc5dedb22023-05-10 08:00:50 -07004843 // HAL can return INVALID_OPERATION if operation is not supported.
4844 ALOGE_IF(result != OK && result != INVALID_OPERATION,
Eric Laurenteab90452019-06-24 15:17:46 -07004845 "Error when setting output stream volume: %d", result);
4846 if (result == NO_ERROR) {
4847 mLeftVolFloat = *volume;
4848 }
4849 }
4850 // if stream volume was successfully sent to the HAL, mLeftVolFloat == v here and we
4851 // remove stream volume contribution from software volume.
4852 if (mLeftVolFloat == *volume) {
4853 *volume = 1.0f;
4854 }
4855 }
4856 return result;
4857}
4858
Andy Hungee58e4a2023-07-07 13:47:37 -07004859status_t MixerThread::createAudioPatch_l(const struct audio_patch* patch,
Eric Laurent054d9d32015-04-24 08:48:48 -07004860 audio_patch_handle_t *handle)
4861{
Andy Hungf60abce2016-08-26 11:37:54 -07004862 status_t status;
4863 if (property_get_bool("af.patch_park", false /* default_value */)) {
4864 // Park FastMixer to avoid potential DOS issues with writing to the HAL
4865 // or if HAL does not properly lock against access.
4866 AutoPark<FastMixer> park(mFastMixer);
4867 status = PlaybackThread::createAudioPatch_l(patch, handle);
4868 } else {
4869 status = PlaybackThread::createAudioPatch_l(patch, handle);
4870 }
Eric Laurentb0463942022-12-20 16:31:10 +01004871
4872 updateHalSupportedLatencyModes_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07004873 return status;
4874}
4875
Andy Hungee58e4a2023-07-07 13:47:37 -07004876status_t PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
Eric Laurent1c333e22014-05-20 10:48:17 -07004877 audio_patch_handle_t *handle)
4878{
4879 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07004880
4881 // store new device and send to effects
4882 audio_devices_t type = AUDIO_DEVICE_NONE;
jiabinc52b1ff2019-10-31 17:20:42 -07004883 AudioDeviceTypeAddrVector deviceTypeAddrs;
Eric Laurent054d9d32015-04-24 08:48:48 -07004884 for (unsigned int i = 0; i < patch->num_sinks; i++) {
jiabinc52b1ff2019-10-31 17:20:42 -07004885 LOG_ALWAYS_FATAL_IF(popcount(patch->sinks[i].ext.device.type) > 1
4886 && !mOutput->audioHwDev->supportsAudioPatches(),
4887 "Enumerated device type(%#x) must not be used "
4888 "as it does not support audio patches",
4889 patch->sinks[i].ext.device.type);
Mikhail Naganov55773032020-10-01 15:08:13 -07004890 type = static_cast<audio_devices_t>(type | patch->sinks[i].ext.device.type);
Andy Hung920f6572022-10-06 12:09:49 -07004891 deviceTypeAddrs.emplace_back(patch->sinks[i].ext.device.type,
4892 patch->sinks[i].ext.device.address);
Eric Laurent054d9d32015-04-24 08:48:48 -07004893 }
4894
François Gaffie0c280aa2018-07-25 10:02:15 +02004895 audio_port_handle_t sinkPortId = patch->sinks[0].id;
Eric Laurent054d9d32015-04-24 08:48:48 -07004896#ifdef ADD_BATTERY_DATA
4897 // when changing the audio output device, call addBatteryData to notify
4898 // the change
jiabinc52b1ff2019-10-31 17:20:42 -07004899 if (outDeviceTypes() != deviceTypes) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004900 uint32_t params = 0;
4901 // check whether speaker is on
jiabinc52b1ff2019-10-31 17:20:42 -07004902 if (deviceTypes.count(AUDIO_DEVICE_OUT_SPEAKER) > 0) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004903 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent1c333e22014-05-20 10:48:17 -07004904 }
4905
Eric Laurent054d9d32015-04-24 08:48:48 -07004906 // check if any other device (except speaker) is on
jiabinc52b1ff2019-10-31 17:20:42 -07004907 if (!isSingleDeviceType(deviceTypes, AUDIO_DEVICE_OUT_SPEAKER)) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004908 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
4909 }
4910
4911 if (params != 0) {
4912 addBatteryData(params);
4913 }
4914 }
4915#endif
4916
4917 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08004918 mEffectChains[i]->setDevices_l(deviceTypeAddrs);
Eric Laurent054d9d32015-04-24 08:48:48 -07004919 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07004920
jiabinc52b1ff2019-10-31 17:20:42 -07004921 // mPatch.num_sinks is not set when the thread is created so that
4922 // the first patch creation triggers an ioConfigChanged callback
4923 bool configChanged = (mPatch.num_sinks == 0) ||
4924 (mPatch.sinks[0].id != sinkPortId);
Eric Laurent296fb132015-05-01 11:38:42 -07004925 mPatch = *patch;
jiabinc52b1ff2019-10-31 17:20:42 -07004926 mOutDeviceTypeAddrs = deviceTypeAddrs;
jiabin0a957d32020-04-29 10:56:20 -07004927 checkSilentMode_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07004928
Mikhail Naganov9ee05402016-10-13 15:58:17 -07004929 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07004930 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
4931 status = hwDevice->createAudioPatch(patch->num_sources,
4932 patch->sources,
4933 patch->num_sinks,
4934 patch->sinks,
4935 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07004936 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08004937 status = mOutput->stream->legacyCreateAudioPatch(patch->sinks[0], std::nullopt, type);
Eric Laurent054d9d32015-04-24 08:48:48 -07004938 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07004939 }
Andy Hungc2b11cb2020-04-22 09:04:01 -07004940 const std::string patchSinksAsString = patchSinksToString(patch);
Andy Hungcf10d742020-04-28 15:38:24 -07004941
4942 mThreadMetrics.logEndInterval();
Andy Hungea840382020-05-05 21:50:17 -07004943 mThreadMetrics.logCreatePatch(/* inDevices */ {}, patchSinksAsString);
Andy Hungcf10d742020-04-28 15:38:24 -07004944 mThreadMetrics.logBeginInterval();
Andy Hungc2b11cb2020-04-22 09:04:01 -07004945 // also dispatch to active AudioTracks for MediaMetrics
4946 for (const auto &track : mActiveTracks) {
4947 track->logEndInterval();
4948 track->logBeginInterval(patchSinksAsString);
4949 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08004950
Eric Laurente8726fe2015-06-26 09:39:24 -07004951 if (configChanged) {
4952 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
4953 }
Vlad Popa7e81cea2023-01-19 16:34:16 +01004954 // Force metadata update after a route change
Eric Laurentdda206a2022-07-08 17:28:35 +02004955 mActiveTracks.setHasChanged();
4956
Eric Laurent1c333e22014-05-20 10:48:17 -07004957 return status;
4958}
4959
Andy Hungee58e4a2023-07-07 13:47:37 -07004960status_t MixerThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
Eric Laurent054d9d32015-04-24 08:48:48 -07004961{
Andy Hungf60abce2016-08-26 11:37:54 -07004962 status_t status;
4963 if (property_get_bool("af.patch_park", false /* default_value */)) {
4964 // Park FastMixer to avoid potential DOS issues with writing to the HAL
4965 // or if HAL does not properly lock against access.
4966 AutoPark<FastMixer> park(mFastMixer);
4967 status = PlaybackThread::releaseAudioPatch_l(handle);
4968 } else {
4969 status = PlaybackThread::releaseAudioPatch_l(handle);
4970 }
Eric Laurent054d9d32015-04-24 08:48:48 -07004971 return status;
4972}
4973
Andy Hungee58e4a2023-07-07 13:47:37 -07004974status_t PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004975{
4976 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07004977
jiabinc52b1ff2019-10-31 17:20:42 -07004978 mPatch = audio_patch{};
4979 mOutDeviceTypeAddrs.clear();
Eric Laurent054d9d32015-04-24 08:48:48 -07004980
Mikhail Naganov9ee05402016-10-13 15:58:17 -07004981 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07004982 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
4983 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07004984 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08004985 status = mOutput->stream->legacyReleaseAudioPatch();
Eric Laurent1c333e22014-05-20 10:48:17 -07004986 }
Eric Laurentdda206a2022-07-08 17:28:35 +02004987 // Force meteadata update after a route change
4988 mActiveTracks.setHasChanged();
4989
Eric Laurent1c333e22014-05-20 10:48:17 -07004990 return status;
4991}
4992
Andy Hungee58e4a2023-07-07 13:47:37 -07004993void PlaybackThread::addPatchTrack(const sp<IAfPatchTrack>& track)
Eric Laurent83b88082014-06-20 18:31:16 -07004994{
Andy Hung972bec12023-08-31 16:13:39 -07004995 audio_utils::lock_guard _l(mutex());
Eric Laurent83b88082014-06-20 18:31:16 -07004996 mTracks.add(track);
4997}
4998
Andy Hungee58e4a2023-07-07 13:47:37 -07004999void PlaybackThread::deletePatchTrack(const sp<IAfPatchTrack>& track)
Eric Laurent83b88082014-06-20 18:31:16 -07005000{
Andy Hung972bec12023-08-31 16:13:39 -07005001 audio_utils::lock_guard _l(mutex());
Eric Laurent83b88082014-06-20 18:31:16 -07005002 destroyTrack_l(track);
5003}
5004
Andy Hungee58e4a2023-07-07 13:47:37 -07005005void PlaybackThread::toAudioPortConfig(struct audio_port_config* config)
Eric Laurent83b88082014-06-20 18:31:16 -07005006{
Mikhail Naganovdc769682018-05-04 15:34:08 -07005007 ThreadBase::toAudioPortConfig(config);
Eric Laurent83b88082014-06-20 18:31:16 -07005008 config->role = AUDIO_PORT_ROLE_SOURCE;
5009 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
5010 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07005011 if (mOutput && mOutput->flags != AUDIO_OUTPUT_FLAG_NONE) {
5012 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
5013 config->flags.output = mOutput->flags;
5014 }
Eric Laurent83b88082014-06-20 18:31:16 -07005015}
5016
Eric Laurent81784c32012-11-19 14:55:58 -08005017// ----------------------------------------------------------------------------
5018
Andy Hungee58e4a2023-07-07 13:47:37 -07005019/* static */
5020sp<IAfPlaybackThread> IAfPlaybackThread::createMixerThread(
Andy Hung583043b2023-07-17 17:05:00 -07005021 const sp<IAfThreadCallback>& afThreadCallback, AudioStreamOut* output,
Andy Hungee58e4a2023-07-07 13:47:37 -07005022 audio_io_handle_t id, bool systemReady, type_t type, audio_config_base_t* mixerConfig) {
Andy Hung583043b2023-07-17 17:05:00 -07005023 return sp<MixerThread>::make(afThreadCallback, output, id, systemReady, type, mixerConfig);
Andy Hungee58e4a2023-07-07 13:47:37 -07005024}
5025
Andy Hung583043b2023-07-17 17:05:00 -07005026MixerThread::MixerThread(const sp<IAfThreadCallback>& afThreadCallback, AudioStreamOut* output,
Eric Laurentf1f22e72021-07-13 14:04:14 +02005027 audio_io_handle_t id, bool systemReady, type_t type, audio_config_base_t *mixerConfig)
Andy Hung583043b2023-07-17 17:05:00 -07005028 : PlaybackThread(afThreadCallback, output, id, type, systemReady, mixerConfig),
Eric Laurent81784c32012-11-19 14:55:58 -08005029 // mAudioMixer below
5030 // mFastMixer below
Eric Laurentb0463942022-12-20 16:31:10 +01005031 mBluetoothLatencyModesEnabled(false),
Andy Hung2ddee192015-12-18 17:34:44 -08005032 mFastMixerFutex(0),
5033 mMasterMono(false)
Eric Laurent81784c32012-11-19 14:55:58 -08005034 // mOutputSink below
5035 // mPipeSink below
5036 // mNormalSink below
5037{
Andy Hung583043b2023-07-17 17:05:00 -07005038 setMasterBalance(afThreadCallback->getMasterBalance_l());
jiabinc52b1ff2019-10-31 17:20:42 -07005039 ALOGV("MixerThread() id=%d type=%d", id, type);
Glenn Kasten49f36ba2017-12-06 13:02:02 -08005040 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%#x, mFrameSize=%zu, "
Glenn Kastenc42e9b42016-03-21 11:35:03 -07005041 "mFrameCount=%zu, mNormalFrameCount=%zu",
Eric Laurent81784c32012-11-19 14:55:58 -08005042 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
5043 mNormalFrameCount);
5044 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
5045
Andy Hungfbfc3952015-01-15 13:33:51 -08005046 if (type == DUPLICATING) {
5047 // The Duplicating thread uses the AudioMixer and delivers data to OutputTracks
5048 // (downstream MixerThreads) in DuplicatingThread::threadLoop_write().
5049 // Do not create or use mFastMixer, mOutputSink, mPipeSink, or mNormalSink.
5050 return;
5051 }
Eric Laurent81784c32012-11-19 14:55:58 -08005052 // create an NBAIO sink for the HAL output stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07005053 mOutputSink = new AudioStreamOutSink(output->stream);
Eric Laurent81784c32012-11-19 14:55:58 -08005054 size_t numCounterOffers = 0;
jiabin245cdd92018-12-07 17:55:15 -08005055 const NBAIO_Format offers[1] = {Format_from_SR_C(
5056 mSampleRate, mChannelCount + mHapticChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005057#if !LOG_NDEBUG
5058 ssize_t index =
5059#else
5060 (void)
5061#endif
5062 mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08005063 ALOG_ASSERT(index == 0);
5064
5065 // initialize fast mixer depending on configuration
5066 bool initFastMixer;
jiabinc658e452022-10-21 20:52:21 +00005067 if (mType == SPATIALIZER || mType == BIT_PERFECT) {
Eric Laurent81784c32012-11-19 14:55:58 -08005068 initFastMixer = false;
Eric Laurentb62d0362021-10-26 17:40:18 +02005069 } else {
5070 switch (kUseFastMixer) {
5071 case FastMixer_Never:
5072 initFastMixer = false;
5073 break;
5074 case FastMixer_Always:
5075 initFastMixer = true;
5076 break;
5077 case FastMixer_Static:
5078 case FastMixer_Dynamic:
5079 initFastMixer = mFrameCount < mNormalFrameCount;
5080 break;
5081 }
5082 ALOGW_IF(initFastMixer == false && mFrameCount < mNormalFrameCount,
5083 "FastMixer is preferred for this sink as frameCount %zu is less than threshold %zu",
5084 mFrameCount, mNormalFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08005085 }
5086 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07005087 audio_format_t fastMixerFormat;
5088 if (mMixerBufferEnabled && mEffectBufferEnabled) {
5089 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
5090 } else {
5091 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
5092 }
5093 if (mFormat != fastMixerFormat) {
5094 // change our Sink format to accept our intermediate precision
5095 mFormat = fastMixerFormat;
5096 free(mSinkBuffer);
jiabin245cdd92018-12-07 17:55:15 -08005097 mFrameSize = audio_bytes_per_frame(mChannelCount + mHapticChannelCount, mFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07005098 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
5099 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
5100 }
Eric Laurent81784c32012-11-19 14:55:58 -08005101
5102 // create a MonoPipe to connect our submix to FastMixer
5103 NBAIO_Format format = mOutputSink->format();
Andy Hung8946a282018-04-19 20:04:56 -07005104
Andy Hung1258c1a2014-05-23 21:22:17 -07005105 // adjust format to match that of the Fast Mixer
Glenn Kasten49f36ba2017-12-06 13:02:02 -08005106 ALOGV("format changed from %#x to %#x", format.mFormat, fastMixerFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07005107 format.mFormat = fastMixerFormat;
5108 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
5109
Eric Laurent81784c32012-11-19 14:55:58 -08005110 // This pipe depth compensates for scheduling latency of the normal mixer thread.
5111 // When it wakes up after a maximum latency, it runs a few cycles quickly before
5112 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
5113 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
Andy Hung920f6572022-10-06 12:09:49 -07005114 const NBAIO_Format offersFast[1] = {format};
5115 size_t numCounterOffersFast = 0;
Andy Hung8946a282018-04-19 20:04:56 -07005116#if !LOG_NDEBUG
Eric Laurent1e28aaa2023-04-16 19:34:23 +02005117 index =
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005118#else
5119 (void)
5120#endif
Andy Hung920f6572022-10-06 12:09:49 -07005121 monoPipe->negotiate(offersFast, std::size(offersFast),
5122 nullptr /* counterOffers */, numCounterOffersFast);
Eric Laurent81784c32012-11-19 14:55:58 -08005123 ALOG_ASSERT(index == 0);
5124 monoPipe->setAvgFrames((mScreenState & 1) ?
5125 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
5126 mPipeSink = monoPipe;
5127
Eric Laurent81784c32012-11-19 14:55:58 -08005128 // create fast mixer and configure it initially with just one fast track for our submix
Andy Hung8946a282018-04-19 20:04:56 -07005129 mFastMixer = new FastMixer(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08005130 FastMixerStateQueue *sq = mFastMixer->sq();
5131#ifdef STATE_QUEUE_DUMP
5132 sq->setObserverDump(&mStateQueueObserverDump);
5133 sq->setMutatorDump(&mStateQueueMutatorDump);
5134#endif
5135 FastMixerState *state = sq->begin();
5136 FastTrack *fastTrack = &state->mFastTracks[0];
5137 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
5138 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
5139 fastTrack->mVolumeProvider = NULL;
Mikhail Naganov55773032020-10-01 15:08:13 -07005140 fastTrack->mChannelMask = static_cast<audio_channel_mask_t>(
5141 mChannelMask | mHapticChannelMask); // mPipeSink channel mask for
5142 // audio to FastMixer
Andy Hunge8a1ced2014-05-09 15:02:21 -07005143 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
jiabin245cdd92018-12-07 17:55:15 -08005144 fastTrack->mHapticPlaybackEnabled = mHapticChannelMask != AUDIO_CHANNEL_NONE;
jiabine70bc7f2020-06-30 22:07:55 -07005145 fastTrack->mHapticIntensity = os::HapticScale::NONE;
Lais Andradebc3f37a2021-07-02 00:13:19 +01005146 fastTrack->mHapticMaxAmplitude = NAN;
Eric Laurent81784c32012-11-19 14:55:58 -08005147 fastTrack->mGeneration++;
5148 state->mFastTracksGen++;
5149 state->mTrackMask = 1;
5150 // fast mixer will use the HAL output sink
5151 state->mOutputSink = mOutputSink.get();
5152 state->mOutputSinkGen++;
5153 state->mFrameCount = mFrameCount;
jiabin245cdd92018-12-07 17:55:15 -08005154 // specify sink channel mask when haptic channel mask present as it can not
5155 // be calculated directly from channel count
5156 state->mSinkChannelMask = mHapticChannelMask == AUDIO_CHANNEL_NONE
Mikhail Naganov55773032020-10-01 15:08:13 -07005157 ? AUDIO_CHANNEL_NONE
5158 : static_cast<audio_channel_mask_t>(mChannelMask | mHapticChannelMask);
Eric Laurent81784c32012-11-19 14:55:58 -08005159 state->mCommand = FastMixerState::COLD_IDLE;
5160 // already done in constructor initialization list
5161 //mFastMixerFutex = 0;
5162 state->mColdFutexAddr = &mFastMixerFutex;
5163 state->mColdGen++;
5164 state->mDumpState = &mFastMixerDumpState;
Andy Hung583043b2023-07-17 17:05:00 -07005165 mFastMixerNBLogWriter = afThreadCallback->newWriter_l(kFastMixerLogSize, "FastMixer");
Glenn Kasten9e58b552013-01-18 15:09:48 -08005166 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08005167 sq->end();
5168 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
5169
Eric Tan0513b5d2018-09-17 10:32:48 -07005170 NBLog::thread_info_t info;
5171 info.id = mId;
5172 info.type = NBLog::FASTMIXER;
5173 mFastMixerNBLogWriter->log<NBLog::EVENT_THREAD_INFO>(info);
5174
Eric Laurent81784c32012-11-19 14:55:58 -08005175 // start the fast mixer
5176 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
5177 pid_t tid = mFastMixer->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07005178 sendPrioConfigEvent(getpid(), tid, kPriorityFastMixer, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08005179 stream()->setHalThreadPriority(kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08005180
5181#ifdef AUDIO_WATCHDOG
5182 // create and start the watchdog
5183 mAudioWatchdog = new AudioWatchdog();
5184 mAudioWatchdog->setDump(&mAudioWatchdogDump);
5185 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
5186 tid = mAudioWatchdog->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07005187 sendPrioConfigEvent(getpid(), tid, kPriorityFastMixer, false /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08005188#endif
Andy Hung8946a282018-04-19 20:04:56 -07005189 } else {
5190#ifdef TEE_SINK
5191 // Only use the MixerThread tee if there is no FastMixer.
5192 mTee.set(mOutputSink->format(), NBAIO_Tee::TEE_FLAG_OUTPUT_THREAD);
5193 mTee.setId(std::string("_") + std::to_string(mId) + "_M");
5194#endif
Eric Laurent81784c32012-11-19 14:55:58 -08005195 }
5196
5197 switch (kUseFastMixer) {
5198 case FastMixer_Never:
5199 case FastMixer_Dynamic:
5200 mNormalSink = mOutputSink;
5201 break;
5202 case FastMixer_Always:
5203 mNormalSink = mPipeSink;
5204 break;
5205 case FastMixer_Static:
5206 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
5207 break;
5208 }
5209}
5210
Andy Hungee58e4a2023-07-07 13:47:37 -07005211MixerThread::~MixerThread()
Eric Laurent81784c32012-11-19 14:55:58 -08005212{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005213 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005214 FastMixerStateQueue *sq = mFastMixer->sq();
5215 FastMixerState *state = sq->begin();
5216 if (state->mCommand == FastMixerState::COLD_IDLE) {
5217 int32_t old = android_atomic_inc(&mFastMixerFutex);
5218 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07005219 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08005220 }
5221 }
5222 state->mCommand = FastMixerState::EXIT;
5223 sq->end();
5224 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
5225 mFastMixer->join();
5226 // Though the fast mixer thread has exited, it's state queue is still valid.
5227 // We'll use that extract the final state which contains one remaining fast track
5228 // corresponding to our sub-mix.
5229 state = sq->begin();
5230 ALOG_ASSERT(state->mTrackMask == 1);
5231 FastTrack *fastTrack = &state->mFastTracks[0];
5232 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
5233 delete fastTrack->mBufferProvider;
5234 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005235 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08005236#ifdef AUDIO_WATCHDOG
5237 if (mAudioWatchdog != 0) {
5238 mAudioWatchdog->requestExit();
5239 mAudioWatchdog->requestExitAndWait();
5240 mAudioWatchdog.clear();
5241 }
5242#endif
5243 }
Andy Hung583043b2023-07-17 17:05:00 -07005244 mAfThreadCallback->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08005245 delete mAudioMixer;
5246}
5247
Andy Hungee58e4a2023-07-07 13:47:37 -07005248void MixerThread::onFirstRef() {
Eric Laurentb0463942022-12-20 16:31:10 +01005249 PlaybackThread::onFirstRef();
5250
Andy Hung972bec12023-08-31 16:13:39 -07005251 audio_utils::lock_guard _l(mutex());
Eric Laurentb0463942022-12-20 16:31:10 +01005252 if (mOutput != nullptr && mOutput->stream != nullptr) {
5253 status_t status = mOutput->stream->setLatencyModeCallback(this);
5254 if (status != INVALID_OPERATION) {
5255 updateHalSupportedLatencyModes_l();
5256 }
5257 // Default to enabled if the HAL supports it. This can be changed by Audioflinger after
5258 // the thread construction according to AudioFlinger::mBluetoothLatencyModesEnabled
5259 mBluetoothLatencyModesEnabled.store(
5260 mOutput->audioHwDev->supportsBluetoothVariableLatency());
5261 }
5262}
Eric Laurent81784c32012-11-19 14:55:58 -08005263
Andy Hungee58e4a2023-07-07 13:47:37 -07005264uint32_t MixerThread::correctLatency_l(uint32_t latency) const
Eric Laurent81784c32012-11-19 14:55:58 -08005265{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005266 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005267 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
5268 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
5269 }
5270 return latency;
5271}
5272
Andy Hungee58e4a2023-07-07 13:47:37 -07005273ssize_t MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08005274{
5275 // FIXME we should only do one push per cycle; confirm this is true
5276 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005277 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005278 FastMixerStateQueue *sq = mFastMixer->sq();
5279 FastMixerState *state = sq->begin();
5280 if (state->mCommand != FastMixerState::MIX_WRITE &&
5281 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
5282 if (state->mCommand == FastMixerState::COLD_IDLE) {
Eric Laurenta2ab4502015-09-09 12:25:51 -07005283
5284 // FIXME workaround for first HAL write being CPU bound on some devices
5285 ATRACE_BEGIN("write");
5286 mOutput->write((char *)mSinkBuffer, 0);
5287 ATRACE_END();
5288
Eric Laurent81784c32012-11-19 14:55:58 -08005289 int32_t old = android_atomic_inc(&mFastMixerFutex);
5290 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07005291 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08005292 }
5293#ifdef AUDIO_WATCHDOG
5294 if (mAudioWatchdog != 0) {
5295 mAudioWatchdog->resume();
5296 }
5297#endif
5298 }
5299 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kastend797a9d2015-03-02 14:19:25 -08005300#ifdef FAST_THREAD_STATISTICS
Andy Hung583043b2023-07-17 17:05:00 -07005301 mFastMixerDumpState.increaseSamplingN(mAfThreadCallback->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08005302 FastThreadDumpState::kSamplingNforLowRamDevice : FastThreadDumpState::kSamplingN);
Glenn Kastend797a9d2015-03-02 14:19:25 -08005303#endif
Eric Laurent81784c32012-11-19 14:55:58 -08005304 sq->end();
5305 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
5306 if (kUseFastMixer == FastMixer_Dynamic) {
5307 mNormalSink = mPipeSink;
5308 }
5309 } else {
5310 sq->end(false /*didModify*/);
5311 }
5312 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005313 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08005314}
5315
Andy Hungee58e4a2023-07-07 13:47:37 -07005316void MixerThread::threadLoop_standby()
Eric Laurent81784c32012-11-19 14:55:58 -08005317{
5318 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005319 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005320 FastMixerStateQueue *sq = mFastMixer->sq();
5321 FastMixerState *state = sq->begin();
5322 if (!(state->mCommand & FastMixerState::IDLE)) {
Andy Hung2148bf02016-11-28 19:01:02 -08005323 // Report any frames trapped in the Monopipe
5324 MonoPipe *monoPipe = (MonoPipe *)mPipeSink.get();
5325 const long long pipeFrames = monoPipe->maxFrames() - monoPipe->availableToWrite();
5326 mLocalLog.log("threadLoop_standby: framesWritten:%lld suspendedFrames:%lld "
5327 "monoPipeWritten:%lld monoPipeLeft:%lld",
5328 (long long)mFramesWritten, (long long)mSuspendedFrames,
5329 (long long)mPipeSink->framesWritten(), pipeFrames);
5330 mLocalLog.log("threadLoop_standby: %s", mTimestamp.toString().c_str());
5331
Eric Laurent81784c32012-11-19 14:55:58 -08005332 state->mCommand = FastMixerState::COLD_IDLE;
5333 state->mColdFutexAddr = &mFastMixerFutex;
5334 state->mColdGen++;
5335 mFastMixerFutex = 0;
5336 sq->end();
5337 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
5338 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
5339 if (kUseFastMixer == FastMixer_Dynamic) {
5340 mNormalSink = mOutputSink;
5341 }
5342#ifdef AUDIO_WATCHDOG
5343 if (mAudioWatchdog != 0) {
5344 mAudioWatchdog->pause();
5345 }
5346#endif
5347 } else {
5348 sq->end(false /*didModify*/);
5349 }
5350 }
5351 PlaybackThread::threadLoop_standby();
5352}
5353
Andy Hungee58e4a2023-07-07 13:47:37 -07005354bool PlaybackThread::waitingAsyncCallback_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08005355{
5356 return false;
5357}
5358
Andy Hungee58e4a2023-07-07 13:47:37 -07005359bool PlaybackThread::shouldStandby_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08005360{
5361 return !mStandby;
5362}
5363
Andy Hungee58e4a2023-07-07 13:47:37 -07005364bool PlaybackThread::waitingAsyncCallback()
Eric Laurentbfb1b832013-01-07 09:53:42 -08005365{
Andy Hung972bec12023-08-31 16:13:39 -07005366 audio_utils::lock_guard _l(mutex());
Eric Laurentbfb1b832013-01-07 09:53:42 -08005367 return waitingAsyncCallback_l();
5368}
5369
Eric Laurent81784c32012-11-19 14:55:58 -08005370// shared by MIXER and DIRECT, overridden by DUPLICATING
Andy Hungee58e4a2023-07-07 13:47:37 -07005371void PlaybackThread::threadLoop_standby()
Eric Laurent81784c32012-11-19 14:55:58 -08005372{
Andy Hung8d672e02023-09-15 18:19:28 -07005373 ALOGV("%s: audio hardware entering standby, mixer %p, suspend count %d",
5374 __func__, this, (int32_t)mSuspended);
Phil Burk062e67a2015-02-11 13:40:50 -08005375 mOutput->standby();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005376 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005377 // discard any pending drain or write ack by incrementing sequence
5378 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
5379 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005380 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005381 mCallbackThread->setWriteBlocked(mWriteAckSequence);
5382 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005383 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08005384 mHwPaused = false;
Eric Laurent68a40a82022-05-03 18:15:04 +02005385 setHalLatencyMode_l();
Eric Laurent81784c32012-11-19 14:55:58 -08005386}
5387
Andy Hungee58e4a2023-07-07 13:47:37 -07005388void PlaybackThread::onAddNewTrack_l()
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08005389{
5390 ALOGV("signal playback thread");
5391 broadcast_l();
5392}
5393
Andy Hungee58e4a2023-07-07 13:47:37 -07005394void PlaybackThread::onAsyncError()
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005395{
5396 for (int i = AUDIO_STREAM_SYSTEM; i < (int)AUDIO_STREAM_CNT; i++) {
5397 invalidateTracks((audio_stream_type_t)i);
5398 }
5399}
5400
Andy Hungee58e4a2023-07-07 13:47:37 -07005401void MixerThread::threadLoop_mix()
Eric Laurent81784c32012-11-19 14:55:58 -08005402{
Eric Laurent81784c32012-11-19 14:55:58 -08005403 // mix buffers...
Glenn Kastend79072e2016-01-06 08:41:20 -08005404 mAudioMixer->process();
Andy Hung25c2dac2014-02-27 14:56:00 -08005405 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005406 // increase sleep time progressively when application underrun condition clears.
5407 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
5408 // that a steady state of alternating ready/not ready conditions keeps the sleep time
5409 // such that we would underrun the audio HAL.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005410 if ((mSleepTimeUs == 0) && (sleepTimeShift > 0)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005411 sleepTimeShift--;
5412 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005413 mSleepTimeUs = 0;
5414 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08005415 //TODO: delay standby when effects have a tail
Glenn Kasten4c053ea2014-09-28 14:41:07 -07005416
Eric Laurent81784c32012-11-19 14:55:58 -08005417}
5418
Andy Hungee58e4a2023-07-07 13:47:37 -07005419void MixerThread::threadLoop_sleepTime()
Eric Laurent81784c32012-11-19 14:55:58 -08005420{
5421 // If no tracks are ready, sleep once for the duration of an output
5422 // buffer size, then write 0s to the output
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005423 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005424 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Andy Hung06d13222018-05-03 20:13:31 -07005425 if (mPipeSink.get() != nullptr && mPipeSink == mNormalSink) {
5426 // Using the Monopipe availableToWrite, we estimate the
5427 // sleep time to retry for more data (before we underrun).
5428 MonoPipe *monoPipe = static_cast<MonoPipe *>(mPipeSink.get());
5429 const ssize_t availableToWrite = mPipeSink->availableToWrite();
5430 const size_t pipeFrames = monoPipe->maxFrames();
5431 const size_t framesLeft = pipeFrames - max(availableToWrite, 0);
5432 // HAL_framecount <= framesDelay ~ framesLeft / 2 <= Normal_Mixer_framecount
5433 const size_t framesDelay = std::min(
5434 mNormalFrameCount, max(framesLeft / 2, mFrameCount));
5435 ALOGV("pipeFrames:%zu framesLeft:%zu framesDelay:%zu",
5436 pipeFrames, framesLeft, framesDelay);
5437 mSleepTimeUs = framesDelay * MICROS_PER_SECOND / mSampleRate;
5438 } else {
5439 mSleepTimeUs = mActiveSleepTimeUs >> sleepTimeShift;
5440 if (mSleepTimeUs < kMinThreadSleepTimeUs) {
5441 mSleepTimeUs = kMinThreadSleepTimeUs;
5442 }
5443 // reduce sleep time in case of consecutive application underruns to avoid
5444 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
5445 // duration we would end up writing less data than needed by the audio HAL if
5446 // the condition persists.
5447 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
5448 sleepTimeShift++;
5449 }
Eric Laurent81784c32012-11-19 14:55:58 -08005450 }
5451 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005452 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005453 }
5454 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08005455 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
5456 // before effects processing or output.
5457 if (mMixerBufferValid) {
5458 memset(mMixerBuffer, 0, mMixerBufferSize);
Eric Laurent39095982021-08-24 18:29:27 +02005459 if (mType == SPATIALIZER) {
5460 memset(mSinkBuffer, 0, mSinkBufferSize);
5461 }
Andy Hung98ef9782014-03-04 14:46:50 -08005462 } else {
5463 memset(mSinkBuffer, 0, mSinkBufferSize);
5464 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005465 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005466 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
5467 "anticipated start");
5468 }
5469 // TODO add standby time extension fct of effect tail
5470}
5471
Andy Hungc5007f82023-08-29 14:26:09 -07005472// prepareTracks_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07005473PlaybackThread::mixer_state MixerThread::prepareTracks_l(
Andy Hung8d31fd22023-06-26 19:20:57 -07005474 Vector<sp<IAfTrack>>* tracksToRemove)
Eric Laurent81784c32012-11-19 14:55:58 -08005475{
Andy Hungc0691382018-09-12 18:01:57 -07005476 // clean up deleted track ids in AudioMixer before allocating new tracks
5477 (void)mTracks.processDeletedTrackIds([this](int trackId) {
5478 // for each trackId, destroy it in the AudioMixer
5479 if (mAudioMixer->exists(trackId)) {
5480 mAudioMixer->destroy(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08005481 }
5482 });
Andy Hungc0691382018-09-12 18:01:57 -07005483 mTracks.clearDeletedTrackIds();
Eric Laurent81784c32012-11-19 14:55:58 -08005484
5485 mixer_state mixerStatus = MIXER_IDLE;
5486 // find out which tracks need to be processed
5487 size_t count = mActiveTracks.size();
5488 size_t mixedTracks = 0;
5489 size_t tracksWithEffect = 0;
5490 // counts only _active_ fast tracks
5491 size_t fastTracks = 0;
5492 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
5493
5494 float masterVolume = mMasterVolume;
5495 bool masterMute = mMasterMute;
5496
5497 if (masterMute) {
5498 masterVolume = 0;
5499 }
5500 // Delegate master volume control to effect in output mix effect chain if needed
Andy Hung116bc262023-06-20 18:56:17 -07005501 sp<IAfEffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Eric Laurent81784c32012-11-19 14:55:58 -08005502 if (chain != 0) {
5503 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
Shunkai Yaof4847652024-01-12 00:25:20 +00005504 chain->setVolume(&v, &v);
Eric Laurent81784c32012-11-19 14:55:58 -08005505 masterVolume = (float)((v + (1 << 23)) >> 24);
5506 chain.clear();
5507 }
5508
5509 // prepare a new state to push
5510 FastMixerStateQueue *sq = NULL;
5511 FastMixerState *state = NULL;
5512 bool didModify = false;
5513 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Andy Hungf2285312017-02-14 18:31:59 -08005514 bool coldIdle = false;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005515 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005516 sq = mFastMixer->sq();
5517 state = sq->begin();
Andy Hungf2285312017-02-14 18:31:59 -08005518 coldIdle = state->mCommand == FastMixerState::COLD_IDLE;
Eric Laurent81784c32012-11-19 14:55:58 -08005519 }
5520
Andy Hung69aed5f2014-02-25 17:24:40 -08005521 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08005522 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08005523
Andy Hungbd3b2b02018-05-21 10:53:11 -07005524 // DeferredOperations handles statistics after setting mixerStatus.
5525 class DeferredOperations {
5526 public:
Andy Hungea840382020-05-05 21:50:17 -07005527 DeferredOperations(mixer_state *mixerStatus, ThreadMetrics *threadMetrics)
5528 : mMixerStatus(mixerStatus)
5529 , mThreadMetrics(threadMetrics) {}
Andy Hungbd3b2b02018-05-21 10:53:11 -07005530
5531 // when leaving scope, tally frames properly.
5532 ~DeferredOperations() {
5533 // Tally underrun frames only if we are actually mixing (MIXER_TRACKS_READY)
5534 // because that is when the underrun occurs.
5535 // We do not distinguish between FastTracks and NormalTracks here.
Andy Hungea840382020-05-05 21:50:17 -07005536 size_t maxUnderrunFrames = 0;
Andy Hungb68f5eb2019-12-03 16:49:17 -08005537 if (*mMixerStatus == MIXER_TRACKS_READY && mUnderrunFrames.size() > 0) {
Andy Hungbd3b2b02018-05-21 10:53:11 -07005538 for (const auto &underrun : mUnderrunFrames) {
Andy Hungc2b11cb2020-04-22 09:04:01 -07005539 underrun.first->tallyUnderrunFrames(underrun.second);
Andy Hungea840382020-05-05 21:50:17 -07005540 maxUnderrunFrames = max(underrun.second, maxUnderrunFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07005541 }
5542 }
Andy Hungea840382020-05-05 21:50:17 -07005543 // send the max underrun frames for this mixer period
5544 mThreadMetrics->logUnderrunFrames(maxUnderrunFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07005545 }
5546
5547 // tallyUnderrunFrames() is called to update the track counters
5548 // with the number of underrun frames for a particular mixer period.
5549 // We defer tallying until we know the final mixer status.
Andy Hung8d31fd22023-06-26 19:20:57 -07005550 void tallyUnderrunFrames(const sp<IAfTrack>& track, size_t underrunFrames) {
Andy Hungbd3b2b02018-05-21 10:53:11 -07005551 mUnderrunFrames.emplace_back(track, underrunFrames);
5552 }
5553
5554 private:
5555 const mixer_state * const mMixerStatus;
Andy Hungea840382020-05-05 21:50:17 -07005556 ThreadMetrics * const mThreadMetrics;
Andy Hung8d31fd22023-06-26 19:20:57 -07005557 std::vector<std::pair<sp<IAfTrack>, size_t>> mUnderrunFrames;
Andy Hungea840382020-05-05 21:50:17 -07005558 } deferredOperations(&mixerStatus, &mThreadMetrics);
Andy Hungb68f5eb2019-12-03 16:49:17 -08005559 // implicit nested scope for variable capture
Andy Hungbd3b2b02018-05-21 10:53:11 -07005560
jiabin245cdd92018-12-07 17:55:15 -08005561 bool noFastHapticTrack = true;
Eric Laurent81784c32012-11-19 14:55:58 -08005562 for (size_t i=0 ; i<count ; i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07005563 const sp<IAfTrack> t = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08005564
5565 // this const just means the local variable doesn't change
Andy Hung8d31fd22023-06-26 19:20:57 -07005566 IAfTrack* const track = t.get();
Eric Laurent81784c32012-11-19 14:55:58 -08005567
5568 // process fast tracks
5569 if (track->isFastTrack()) {
Andy Hungae22b482019-05-09 15:38:55 -07005570 LOG_ALWAYS_FATAL_IF(mFastMixer.get() == nullptr,
5571 "%s(%d): FastTrack(%d) present without FastMixer",
5572 __func__, id(), track->id());
5573
jiabin245cdd92018-12-07 17:55:15 -08005574 if (track->getHapticPlaybackEnabled()) {
5575 noFastHapticTrack = false;
5576 }
Eric Laurent81784c32012-11-19 14:55:58 -08005577
5578 // It's theoretically possible (though unlikely) for a fast track to be created
5579 // and then removed within the same normal mix cycle. This is not a problem, as
5580 // the track never becomes active so it's fast mixer slot is never touched.
5581 // The converse, of removing an (active) track and then creating a new track
5582 // at the identical fast mixer slot within the same normal mix cycle,
5583 // is impossible because the slot isn't marked available until the end of each cycle.
Andy Hung8d31fd22023-06-26 19:20:57 -07005584 int j = track->fastIndex();
Glenn Kastendc2c50b2016-04-21 08:13:14 -07005585 ALOG_ASSERT(0 < j && j < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08005586 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
5587 FastTrack *fastTrack = &state->mFastTracks[j];
5588
5589 // Determine whether the track is currently in underrun condition,
5590 // and whether it had a recent underrun.
5591 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
5592 FastTrackUnderruns underruns = ftDump->mUnderruns;
5593 uint32_t recentFull = (underruns.mBitFields.mFull -
Andy Hung8d31fd22023-06-26 19:20:57 -07005594 track->fastTrackUnderruns().mBitFields.mFull) & UNDERRUN_MASK;
Eric Laurent81784c32012-11-19 14:55:58 -08005595 uint32_t recentPartial = (underruns.mBitFields.mPartial -
Andy Hung8d31fd22023-06-26 19:20:57 -07005596 track->fastTrackUnderruns().mBitFields.mPartial) & UNDERRUN_MASK;
Eric Laurent81784c32012-11-19 14:55:58 -08005597 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
Andy Hung8d31fd22023-06-26 19:20:57 -07005598 track->fastTrackUnderruns().mBitFields.mEmpty) & UNDERRUN_MASK;
Eric Laurent81784c32012-11-19 14:55:58 -08005599 uint32_t recentUnderruns = recentPartial + recentEmpty;
Andy Hung8d31fd22023-06-26 19:20:57 -07005600 track->fastTrackUnderruns() = underruns;
Eric Laurent81784c32012-11-19 14:55:58 -08005601 // don't count underruns that occur while stopping or pausing
5602 // or stopped which can occur when flush() is called while active
Andy Hungbd3b2b02018-05-21 10:53:11 -07005603 size_t underrunFrames = 0;
Glenn Kasten82aaf942013-07-17 16:05:07 -07005604 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
5605 recentUnderruns > 0) {
5606 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
Andy Hungbd3b2b02018-05-21 10:53:11 -07005607 underrunFrames = recentUnderruns * mFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08005608 }
Andy Hungbd3b2b02018-05-21 10:53:11 -07005609 // Immediately account for FastTrack underruns.
Andy Hung8d31fd22023-06-26 19:20:57 -07005610 track->audioTrackServerProxy()->tallyUnderrunFrames(underrunFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08005611
5612 // This is similar to the state machine for normal tracks,
5613 // with a few modifications for fast tracks.
5614 bool isActive = true;
Andy Hung8d31fd22023-06-26 19:20:57 -07005615 switch (track->state()) {
5616 case IAfTrackBase::STOPPING_1:
Eric Laurent81784c32012-11-19 14:55:58 -08005617 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08005618 if (recentUnderruns > 0 || track->isTerminated()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07005619 track->setState(IAfTrackBase::STOPPING_2);
Eric Laurent81784c32012-11-19 14:55:58 -08005620 }
5621 break;
Andy Hung8d31fd22023-06-26 19:20:57 -07005622 case IAfTrackBase::PAUSING:
Eric Laurent81784c32012-11-19 14:55:58 -08005623 // ramp down is not yet implemented
5624 track->setPaused();
5625 break;
Andy Hung8d31fd22023-06-26 19:20:57 -07005626 case IAfTrackBase::RESUMING:
Eric Laurent81784c32012-11-19 14:55:58 -08005627 // ramp up is not yet implemented
Andy Hung8d31fd22023-06-26 19:20:57 -07005628 track->setState(IAfTrackBase::ACTIVE);
Eric Laurent81784c32012-11-19 14:55:58 -08005629 break;
Andy Hung8d31fd22023-06-26 19:20:57 -07005630 case IAfTrackBase::ACTIVE:
Eric Laurent81784c32012-11-19 14:55:58 -08005631 if (recentFull > 0 || recentPartial > 0) {
5632 // track has provided at least some frames recently: reset retry count
Andy Hung8d31fd22023-06-26 19:20:57 -07005633 track->retryCount() = kMaxTrackRetries;
Eric Laurent81784c32012-11-19 14:55:58 -08005634 }
5635 if (recentUnderruns == 0) {
5636 // no recent underruns: stay active
5637 break;
5638 }
5639 // there has recently been an underrun of some kind
5640 if (track->sharedBuffer() == 0) {
5641 // were any of the recent underruns "empty" (no frames available)?
5642 if (recentEmpty == 0) {
5643 // no, then ignore the partial underruns as they are allowed indefinitely
5644 break;
5645 }
5646 // there has recently been an "empty" underrun: decrement the retry counter
Andy Hung8d31fd22023-06-26 19:20:57 -07005647 if (--(track->retryCount()) > 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005648 break;
5649 }
5650 // indicate to client process that the track was disabled because of underrun;
5651 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08005652 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08005653 // remove from active list, but state remains ACTIVE [confusing but true]
5654 isActive = false;
5655 break;
5656 }
Chih-Hung Hsieh2b487032018-09-13 14:16:02 -07005657 FALLTHROUGH_INTENDED;
Andy Hung8d31fd22023-06-26 19:20:57 -07005658 case IAfTrackBase::STOPPING_2:
5659 case IAfTrackBase::PAUSED:
5660 case IAfTrackBase::STOPPED:
5661 case IAfTrackBase::FLUSHED: // flush() while active
Eric Laurent81784c32012-11-19 14:55:58 -08005662 // Check for presentation complete if track is inactive
5663 // We have consumed all the buffers of this track.
5664 // This would be incomplete if we auto-paused on underrun
5665 {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005666 uint32_t latency = 0;
5667 status_t result = mOutput->stream->getLatency(&latency);
5668 ALOGE_IF(result != OK,
5669 "Error when retrieving output stream latency: %d", result);
5670 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08005671 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005672 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
5673 // track stays in active list until presentation is complete
5674 break;
5675 }
5676 }
5677 if (track->isStopping_2()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07005678 track->setState(IAfTrackBase::STOPPED);
Eric Laurent81784c32012-11-19 14:55:58 -08005679 }
5680 if (track->isStopped()) {
5681 // Can't reset directly, as fast mixer is still polling this track
5682 // track->reset();
5683 // So instead mark this track as needing to be reset after push with ack
5684 resetMask |= 1 << i;
5685 }
5686 isActive = false;
5687 break;
Andy Hung8d31fd22023-06-26 19:20:57 -07005688 case IAfTrackBase::IDLE:
Eric Laurent81784c32012-11-19 14:55:58 -08005689 default:
Andy Hung8d31fd22023-06-26 19:20:57 -07005690 LOG_ALWAYS_FATAL("unexpected track state %d", (int)track->state());
Eric Laurent81784c32012-11-19 14:55:58 -08005691 }
5692
5693 if (isActive) {
5694 // was it previously inactive?
5695 if (!(state->mTrackMask & (1 << j))) {
Andy Hung8d31fd22023-06-26 19:20:57 -07005696 ExtendedAudioBufferProvider *eabp = track->asExtendedAudioBufferProvider();
5697 VolumeProvider *vp = track->asVolumeProvider();
Eric Laurent81784c32012-11-19 14:55:58 -08005698 fastTrack->mBufferProvider = eabp;
5699 fastTrack->mVolumeProvider = vp;
Andy Hung8d31fd22023-06-26 19:20:57 -07005700 fastTrack->mChannelMask = track->channelMask();
5701 fastTrack->mFormat = track->format();
jiabin245cdd92018-12-07 17:55:15 -08005702 fastTrack->mHapticPlaybackEnabled = track->getHapticPlaybackEnabled();
jiabin77270b82018-12-18 15:41:29 -08005703 fastTrack->mHapticIntensity = track->getHapticIntensity();
Lais Andradebc3f37a2021-07-02 00:13:19 +01005704 fastTrack->mHapticMaxAmplitude = track->getHapticMaxAmplitude();
Eric Laurent81784c32012-11-19 14:55:58 -08005705 fastTrack->mGeneration++;
5706 state->mTrackMask |= 1 << j;
5707 didModify = true;
5708 // no acknowledgement required for newly active tracks
5709 }
Andy Hung8d31fd22023-06-26 19:20:57 -07005710 sp<AudioTrackServerProxy> proxy = track->audioTrackServerProxy();
Eric Laurenteab90452019-06-24 15:17:46 -07005711 float volume;
5712 if (track->isPlaybackRestricted() || mStreamTypes[track->streamType()].mute) {
5713 volume = 0.f;
5714 } else {
5715 volume = masterVolume * mStreamTypes[track->streamType()].volume;
5716 }
5717
5718 handleVoipVolume_l(&volume);
5719
Eric Laurent81784c32012-11-19 14:55:58 -08005720 // cache the combined master volume and stream type volume for fast mixer; this
5721 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005722 const float vh = track->getVolumeHandler()->getVolume(
Eric Laurenteab90452019-06-24 15:17:46 -07005723 proxy->framesReleased()).first;
5724 volume *= vh;
Andy Hung8d31fd22023-06-26 19:20:57 -07005725 track->setCachedVolume(volume);
Kevin Rocard12381092018-04-11 09:19:59 -07005726 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Vlad Popae2f5aef2022-07-25 16:00:20 +02005727 float vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
5728 float vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
5729
Andy Hung583043b2023-07-17 17:05:00 -07005730 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
Vlad Popae2f5aef2022-07-25 16:00:20 +02005731 /*muteState=*/{masterVolume == 0.f,
5732 mStreamTypes[track->streamType()].volume == 0.f,
5733 mStreamTypes[track->streamType()].mute,
5734 track->isPlaybackRestricted(),
Vlad Popa436c9172022-08-02 15:25:08 +02005735 vlf == 0.f && vrf == 0.f,
5736 vh == 0.f});
Vlad Popae2f5aef2022-07-25 16:00:20 +02005737
5738 vlf *= volume;
5739 vrf *= volume;
Eric Laurenteab90452019-06-24 15:17:46 -07005740
jiabin76d94692022-12-15 21:51:21 +00005741 track->setFinalVolume(vlf, vrf);
Eric Laurent81784c32012-11-19 14:55:58 -08005742 ++fastTracks;
5743 } else {
5744 // was it previously active?
5745 if (state->mTrackMask & (1 << j)) {
5746 fastTrack->mBufferProvider = NULL;
5747 fastTrack->mGeneration++;
5748 state->mTrackMask &= ~(1 << j);
5749 didModify = true;
5750 // If any fast tracks were removed, we must wait for acknowledgement
5751 // because we're about to decrement the last sp<> on those tracks.
5752 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
5753 } else {
Glenn Kastenbf848af2017-12-22 11:55:01 -08005754 // ALOGW rather than LOG_ALWAYS_FATAL because it seems there are cases where an
5755 // AudioTrack may start (which may not be with a start() but with a write()
5756 // after underrun) and immediately paused or released. In that case the
5757 // FastTrack state hasn't had time to update.
5758 // TODO Remove the ALOGW when this theory is confirmed.
5759 ALOGW("fast track %d should have been active; "
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08005760 "mState=%d, mTrackMask=%#x, recentUnderruns=%u, isShared=%d",
Andy Hung8d31fd22023-06-26 19:20:57 -07005761 j, (int)track->state(), state->mTrackMask, recentUnderruns,
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08005762 track->sharedBuffer() != 0);
Glenn Kastenbf848af2017-12-22 11:55:01 -08005763 // Since the FastMixer state already has the track inactive, do nothing here.
Eric Laurent81784c32012-11-19 14:55:58 -08005764 }
5765 tracksToRemove->add(track);
5766 // Avoids a misleading display in dumpsys
Andy Hung8d31fd22023-06-26 19:20:57 -07005767 track->fastTrackUnderruns().mBitFields.mMostRecent = UNDERRUN_FULL;
Eric Laurent81784c32012-11-19 14:55:58 -08005768 }
jiabin245cdd92018-12-07 17:55:15 -08005769 if (fastTrack->mHapticPlaybackEnabled != track->getHapticPlaybackEnabled()) {
5770 fastTrack->mHapticPlaybackEnabled = track->getHapticPlaybackEnabled();
5771 didModify = true;
5772 }
Eric Laurent81784c32012-11-19 14:55:58 -08005773 continue;
5774 }
5775
5776 { // local variable scope to avoid goto warning
5777
5778 audio_track_cblk_t* cblk = track->cblk();
5779
5780 // The first time a track is added we wait
5781 // for all its buffers to be filled before processing it
Andy Hungc0691382018-09-12 18:01:57 -07005782 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08005783
5784 // if an active track doesn't exist in the AudioMixer, create it.
Andy Hungc0691382018-09-12 18:01:57 -07005785 // use the trackId as the AudioMixer name.
5786 if (!mAudioMixer->exists(trackId)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08005787 status_t status = mAudioMixer->create(
Andy Hungc0691382018-09-12 18:01:57 -07005788 trackId,
Andy Hung8d31fd22023-06-26 19:20:57 -07005789 track->channelMask(),
5790 track->format(),
5791 track->sessionId());
Andy Hung1bc088a2018-02-09 15:57:31 -08005792 if (status != OK) {
Andy Hungc0691382018-09-12 18:01:57 -07005793 ALOGW("%s(): AudioMixer cannot create track(%d)"
5794 " mask %#x, format %#x, sessionId %d",
5795 __func__, trackId,
Andy Hung8d31fd22023-06-26 19:20:57 -07005796 track->channelMask(), track->format(), track->sessionId());
Andy Hung1bc088a2018-02-09 15:57:31 -08005797 tracksToRemove->add(track);
5798 track->invalidate(); // consider it dead.
5799 continue;
5800 }
5801 }
5802
Eric Laurent81784c32012-11-19 14:55:58 -08005803 // make sure that we have enough frames to mix one full buffer.
5804 // enforce this condition only once to enable draining the buffer in case the client
5805 // app does not call stop() and relies on underrun to stop:
5806 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
5807 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005808 size_t desiredFrames;
Andy Hung8d31fd22023-06-26 19:20:57 -07005809 const uint32_t sampleRate = track->audioTrackServerProxy()->getSampleRate();
5810 const AudioPlaybackRate playbackRate = track->audioTrackServerProxy()->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07005811
5812 desiredFrames = sourceFramesNeededWithTimestretch(
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07005813 sampleRate, mNormalFrameCount, mSampleRate, playbackRate.mSpeed);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005814 // TODO: ONLY USED FOR LEGACY RESAMPLERS, remove when they are removed.
5815 // add frames already consumed but not yet released by the resampler
5816 // because mAudioTrackServerProxy->framesReady() will include these frames
Andy Hungc0691382018-09-12 18:01:57 -07005817 desiredFrames += mAudioMixer->getUnreleasedFrames(trackId);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005818
Eric Laurent81784c32012-11-19 14:55:58 -08005819 uint32_t minFrames = 1;
5820 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
5821 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005822 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08005823 }
Eric Laurent13e4c962013-12-20 17:36:01 -08005824
5825 size_t framesReady = track->framesReady();
Glenn Kastene7754022014-10-31 12:11:26 -07005826 if (ATRACE_ENABLED()) {
5827 // I wish we had formatted trace names
Andy Hung1bc088a2018-02-09 15:57:31 -08005828 std::string traceName("nRdy");
Andy Hungc0691382018-09-12 18:01:57 -07005829 traceName += std::to_string(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08005830 ATRACE_INT(traceName.c_str(), framesReady);
Glenn Kastene7754022014-10-31 12:11:26 -07005831 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005832 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08005833 !track->isPaused() && !track->isTerminated())
5834 {
Andy Hungc0691382018-09-12 18:01:57 -07005835 ALOGVV("track(%d) s=%08x [OK] on thread %p", trackId, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08005836
5837 mixedTracks++;
5838
Shunkai Yaof4847652024-01-12 00:25:20 +00005839 // track->mainBuffer() != mSinkBuffer and mMixerBuffer means
Andy Hung69aed5f2014-02-25 17:24:40 -08005840 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08005841 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08005842 if (track->mainBuffer() != mSinkBuffer &&
5843 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08005844 if (mEffectBufferEnabled) {
5845 mEffectBufferValid = true; // Later can set directly.
5846 }
Eric Laurent81784c32012-11-19 14:55:58 -08005847 chain = getEffectChain_l(track->sessionId());
5848 // Delegate volume control to effect in track effect chain if needed
5849 if (chain != 0) {
5850 tracksWithEffect++;
5851 } else {
Andy Hungc0691382018-09-12 18:01:57 -07005852 ALOGW("prepareTracks_l(): track(%d) attached to effect but no chain found on "
Eric Laurent81784c32012-11-19 14:55:58 -08005853 "session %d",
Andy Hungc0691382018-09-12 18:01:57 -07005854 trackId, track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08005855 }
5856 }
5857
5858
5859 int param = AudioMixer::VOLUME;
Andy Hung8d31fd22023-06-26 19:20:57 -07005860 if (track->fillingStatus() == IAfTrack::FS_FILLED) {
Eric Laurent81784c32012-11-19 14:55:58 -08005861 // no ramp for the first volume setting
Andy Hung8d31fd22023-06-26 19:20:57 -07005862 track->fillingStatus() = IAfTrack::FS_ACTIVE;
5863 if (track->state() == IAfTrackBase::RESUMING) {
5864 track->setState(IAfTrackBase::ACTIVE);
Revathi Uddaraju453bcb52017-08-14 14:19:40 +08005865 // If a new track is paused immediately after start, do not ramp on resume.
5866 if (cblk->mServer != 0) {
5867 param = AudioMixer::RAMP_VOLUME;
5868 }
Eric Laurent81784c32012-11-19 14:55:58 -08005869 }
Andy Hungc0691382018-09-12 18:01:57 -07005870 mAudioMixer->setParameter(trackId, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Eric Laurent7c29ec92017-09-20 17:54:22 -07005871 mLeftVolFloat = -1.0;
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005872 // FIXME should not make a decision based on mServer
5873 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005874 // If the track is stopped before the first frame was mixed,
5875 // do not apply ramp
5876 param = AudioMixer::RAMP_VOLUME;
5877 }
5878
5879 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07005880 uint32_t vl, vr; // in U8.24 integer format
5881 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Eric Laurent7c29ec92017-09-20 17:54:22 -07005882 // read original volumes with volume control
Eric Laurenteab90452019-06-24 15:17:46 -07005883 float v = masterVolume * mStreamTypes[track->streamType()].volume;
Andy Hung333ab962019-05-28 20:23:35 -07005884 // Always fetch volumeshaper volume to ensure state is updated.
Andy Hung8d31fd22023-06-26 19:20:57 -07005885 const sp<AudioTrackServerProxy> proxy = track->audioTrackServerProxy();
Andy Hung333ab962019-05-28 20:23:35 -07005886 const float vh = track->getVolumeHandler()->getVolume(
Andy Hung8d31fd22023-06-26 19:20:57 -07005887 track->audioTrackServerProxy()->framesReleased()).first;
Eric Laurent7c29ec92017-09-20 17:54:22 -07005888
Eric Laurenteab90452019-06-24 15:17:46 -07005889 if (mStreamTypes[track->streamType()].mute || track->isPlaybackRestricted()) {
5890 v = 0;
5891 }
5892
5893 handleVoipVolume_l(&v);
5894
5895 if (track->isPausing()) {
Andy Hung6be49402014-05-30 10:42:03 -07005896 vl = vr = 0;
5897 vlf = vrf = vaf = 0.;
Eric Laurenteab90452019-06-24 15:17:46 -07005898 track->setPaused();
Eric Laurent81784c32012-11-19 14:55:58 -08005899 } else {
Glenn Kastenc56f3422014-03-21 17:53:17 -07005900 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07005901 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
5902 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08005903 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07005904 if (vlf > GAIN_FLOAT_UNITY) {
5905 ALOGV("Track left volume out of range: %.3g", vlf);
5906 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08005907 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07005908 if (vrf > GAIN_FLOAT_UNITY) {
5909 ALOGV("Track right volume out of range: %.3g", vrf);
5910 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08005911 }
Vlad Popae2f5aef2022-07-25 16:00:20 +02005912
Andy Hung583043b2023-07-17 17:05:00 -07005913 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
Vlad Popae2f5aef2022-07-25 16:00:20 +02005914 /*muteState=*/{masterVolume == 0.f,
5915 mStreamTypes[track->streamType()].volume == 0.f,
5916 mStreamTypes[track->streamType()].mute,
5917 track->isPlaybackRestricted(),
Vlad Popa436c9172022-08-02 15:25:08 +02005918 vlf == 0.f && vrf == 0.f,
5919 vh == 0.f});
Vlad Popae2f5aef2022-07-25 16:00:20 +02005920
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005921 // now apply the master volume and stream type volume and shaper volume
5922 vlf *= v * vh;
5923 vrf *= v * vh;
Eric Laurent81784c32012-11-19 14:55:58 -08005924 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07005925 // then derive vl and vr as U8.24 versions for the effect chain
5926 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
5927 vl = (uint32_t) (scaleto8_24 * vlf);
5928 vr = (uint32_t) (scaleto8_24 * vrf);
5929 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08005930 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08005931 // send level comes from shared memory and so may be corrupt
5932 if (sendLevel > MAX_GAIN_INT) {
5933 ALOGV("Track send level out of range: %04X", sendLevel);
5934 sendLevel = MAX_GAIN_INT;
5935 }
Andy Hung6be49402014-05-30 10:42:03 -07005936 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
5937 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08005938 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005939
jiabin76d94692022-12-15 21:51:21 +00005940 track->setFinalVolume(vrf, vlf);
Kevin Rocard12381092018-04-11 09:19:59 -07005941
Eric Laurent81784c32012-11-19 14:55:58 -08005942 // Delegate volume control to effect in track effect chain if needed
Shunkai Yaof4847652024-01-12 00:25:20 +00005943 if (chain != 0 && chain->setVolume(&vl, &vr)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005944 // Do not ramp volume if volume is controlled by effect
5945 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08005946 // Update remaining floating point volume levels
5947 vlf = (float)vl / (1 << 24);
5948 vrf = (float)vr / (1 << 24);
Andy Hung8d31fd22023-06-26 19:20:57 -07005949 track->setHasVolumeController(true);
Eric Laurent81784c32012-11-19 14:55:58 -08005950 } else {
5951 // force no volume ramp when volume controller was just disabled or removed
5952 // from effect chain to avoid volume spike
Andy Hung8d31fd22023-06-26 19:20:57 -07005953 if (track->hasVolumeController()) {
Eric Laurent81784c32012-11-19 14:55:58 -08005954 param = AudioMixer::VOLUME;
5955 }
Andy Hung8d31fd22023-06-26 19:20:57 -07005956 track->setHasVolumeController(false);
Eric Laurent81784c32012-11-19 14:55:58 -08005957 }
5958
Eric Laurent81784c32012-11-19 14:55:58 -08005959 // XXX: these things DON'T need to be done each time
Andy Hung8d31fd22023-06-26 19:20:57 -07005960 mAudioMixer->setBufferProvider(trackId, track->asExtendedAudioBufferProvider());
Andy Hungc0691382018-09-12 18:01:57 -07005961 mAudioMixer->enable(trackId);
Eric Laurent81784c32012-11-19 14:55:58 -08005962
Andy Hungc0691382018-09-12 18:01:57 -07005963 mAudioMixer->setParameter(trackId, param, AudioMixer::VOLUME0, &vlf);
5964 mAudioMixer->setParameter(trackId, param, AudioMixer::VOLUME1, &vrf);
5965 mAudioMixer->setParameter(trackId, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08005966 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005967 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005968 AudioMixer::TRACK,
5969 AudioMixer::FORMAT, (void *)track->format());
5970 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005971 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005972 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00005973 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Eric Laurent39095982021-08-24 18:29:27 +02005974
Eric Laurentb0a7bc92022-04-05 15:06:08 +02005975 if (mType == SPATIALIZER && !track->isSpatialized()) {
Eric Laurent39095982021-08-24 18:29:27 +02005976 mAudioMixer->setParameter(
5977 trackId,
5978 AudioMixer::TRACK,
5979 AudioMixer::MIXER_CHANNEL_MASK,
5980 (void *)(uintptr_t)(mChannelMask | mHapticChannelMask));
5981 } else {
5982 mAudioMixer->setParameter(
5983 trackId,
5984 AudioMixer::TRACK,
5985 AudioMixer::MIXER_CHANNEL_MASK,
5986 (void *)(uintptr_t)(mMixerChannelMask | mHapticChannelMask));
5987 }
5988
Glenn Kastene3aa6592012-12-04 12:22:46 -08005989 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07005990 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Andy Hung333ab962019-05-28 20:23:35 -07005991 uint32_t reqSampleRate = proxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08005992 if (reqSampleRate == 0) {
5993 reqSampleRate = mSampleRate;
5994 } else if (reqSampleRate > maxSampleRate) {
5995 reqSampleRate = maxSampleRate;
5996 }
Eric Laurent81784c32012-11-19 14:55:58 -08005997 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005998 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005999 AudioMixer::RESAMPLE,
6000 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00006001 (void *)(uintptr_t)reqSampleRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07006002
Andy Hung8edb8dc2015-03-26 19:13:55 -07006003 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07006004 trackId,
Andy Hung8edb8dc2015-03-26 19:13:55 -07006005 AudioMixer::TIMESTRETCH,
6006 AudioMixer::PLAYBACK_RATE,
Andy Hung920f6572022-10-06 12:09:49 -07006007 // cast away constness for this generic API.
6008 const_cast<void *>(reinterpret_cast<const void *>(&playbackRate)));
Andy Hung8edb8dc2015-03-26 19:13:55 -07006009
Andy Hung69aed5f2014-02-25 17:24:40 -08006010 /*
6011 * Select the appropriate output buffer for the track.
6012 *
Andy Hung98ef9782014-03-04 14:46:50 -08006013 * Tracks with effects go into their own effects chain buffer
6014 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08006015 *
6016 * Other tracks can use mMixerBuffer for higher precision
6017 * channel accumulation. If this buffer is enabled
6018 * (mMixerBufferEnabled true), then selected tracks will accumulate
6019 * into it.
6020 *
6021 */
6022 if (mMixerBufferEnabled
6023 && (track->mainBuffer() == mSinkBuffer
6024 || track->mainBuffer() == mMixerBuffer)) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02006025 if (mType == SPATIALIZER && !track->isSpatialized()) {
Eric Laurent39095982021-08-24 18:29:27 +02006026 mAudioMixer->setParameter(
6027 trackId,
6028 AudioMixer::TRACK,
Eric Laurentb62d0362021-10-26 17:40:18 +02006029 AudioMixer::MIXER_FORMAT, (void *)mEffectBufferFormat);
Eric Laurent39095982021-08-24 18:29:27 +02006030 mAudioMixer->setParameter(
6031 trackId,
6032 AudioMixer::TRACK,
Eric Laurentb62d0362021-10-26 17:40:18 +02006033 AudioMixer::MAIN_BUFFER, (void *)mPostSpatializerBuffer);
Eric Laurent39095982021-08-24 18:29:27 +02006034 } else {
6035 mAudioMixer->setParameter(
6036 trackId,
6037 AudioMixer::TRACK,
6038 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
6039 mAudioMixer->setParameter(
6040 trackId,
6041 AudioMixer::TRACK,
6042 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
6043 // TODO: override track->mainBuffer()?
6044 mMixerBufferValid = true;
6045 }
Andy Hung69aed5f2014-02-25 17:24:40 -08006046 } else {
6047 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07006048 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08006049 AudioMixer::TRACK,
Andy Hung319587b2023-05-23 14:01:03 -07006050 AudioMixer::MIXER_FORMAT, (void *)AUDIO_FORMAT_PCM_FLOAT);
Andy Hung69aed5f2014-02-25 17:24:40 -08006051 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07006052 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08006053 AudioMixer::TRACK,
6054 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
6055 }
Eric Laurent81784c32012-11-19 14:55:58 -08006056 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07006057 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08006058 AudioMixer::TRACK,
6059 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
jiabin245cdd92018-12-07 17:55:15 -08006060 mAudioMixer->setParameter(
6061 trackId,
6062 AudioMixer::TRACK,
6063 AudioMixer::HAPTIC_ENABLED, (void *)(uintptr_t)track->getHapticPlaybackEnabled());
jiabin77270b82018-12-18 15:41:29 -08006064 mAudioMixer->setParameter(
6065 trackId,
6066 AudioMixer::TRACK,
6067 AudioMixer::HAPTIC_INTENSITY, (void *)(uintptr_t)track->getHapticIntensity());
Andy Hung8d31fd22023-06-26 19:20:57 -07006068 const float hapticMaxAmplitude = track->getHapticMaxAmplitude();
Lais Andradebc3f37a2021-07-02 00:13:19 +01006069 mAudioMixer->setParameter(
6070 trackId,
6071 AudioMixer::TRACK,
Andy Hung8d31fd22023-06-26 19:20:57 -07006072 AudioMixer::HAPTIC_MAX_AMPLITUDE, (void *)&hapticMaxAmplitude);
Eric Laurent81784c32012-11-19 14:55:58 -08006073
6074 // reset retry count
Andy Hung8d31fd22023-06-26 19:20:57 -07006075 track->retryCount() = kMaxTrackRetries;
Eric Laurent81784c32012-11-19 14:55:58 -08006076
6077 // If one track is ready, set the mixer ready if:
6078 // - the mixer was not ready during previous round OR
6079 // - no other track is not ready
6080 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
6081 mixerStatus != MIXER_TRACKS_ENABLED) {
6082 mixerStatus = MIXER_TRACKS_READY;
6083 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08006084
6085 // Enable the next few lines to instrument a test for underrun log handling.
6086 // TODO: Remove when we have a better way of testing the underrun log.
6087#if 0
6088 static int i;
6089 if ((++i & 0xf) == 0) {
6090 deferredOperations.tallyUnderrunFrames(track, 10 /* underrunFrames */);
6091 }
6092#endif
Eric Laurent81784c32012-11-19 14:55:58 -08006093 } else {
Andy Hungbd3b2b02018-05-21 10:53:11 -07006094 size_t underrunFrames = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08006095 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Andy Hungb68f5eb2019-12-03 16:49:17 -08006096 ALOGV("track(%d) underrun, track state %s framesReady(%zu) < framesDesired(%zd)",
6097 trackId, track->getTrackStateAsString(), framesReady, desiredFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07006098 underrunFrames = desiredFrames;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08006099 }
Andy Hungbd3b2b02018-05-21 10:53:11 -07006100 deferredOperations.tallyUnderrunFrames(track, underrunFrames);
Phil Burk2812d9e2016-01-04 10:34:30 -08006101
Eric Laurent81784c32012-11-19 14:55:58 -08006102 // clear effect chain input buffer if an active track underruns to avoid sending
6103 // previous audio buffer again to effects
6104 chain = getEffectChain_l(track->sessionId());
6105 if (chain != 0) {
6106 chain->clearInputBuffer();
6107 }
6108
Andy Hungc0691382018-09-12 18:01:57 -07006109 ALOGVV("track(%d) s=%08x [NOT READY] on thread %p", trackId, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08006110 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
6111 track->isStopped() || track->isPaused()) {
6112 // We have consumed all the buffers of this track.
6113 // Remove it from the list of active tracks.
6114 // TODO: use actual buffer filling status instead of latency when available from
6115 // audio HAL
6116 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08006117 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08006118 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
6119 if (track->isStopped()) {
6120 track->reset();
6121 }
6122 tracksToRemove->add(track);
6123 }
6124 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08006125 // No buffers for this track. Give it a few chances to
6126 // fill a buffer, then remove it from active list.
Andy Hung8d31fd22023-06-26 19:20:57 -07006127 if (--(track->retryCount()) <= 0) {
Andy Hungc0691382018-09-12 18:01:57 -07006128 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p",
6129 trackId, this);
Eric Laurent81784c32012-11-19 14:55:58 -08006130 tracksToRemove->add(track);
6131 // indicate to client process that the track was disabled because of underrun;
6132 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08006133 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08006134 // If one track is not ready, mark the mixer also not ready if:
6135 // - the mixer was ready during previous round OR
6136 // - no other track is ready
6137 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
6138 mixerStatus != MIXER_TRACKS_READY) {
6139 mixerStatus = MIXER_TRACKS_ENABLED;
6140 }
6141 }
Andy Hungc0691382018-09-12 18:01:57 -07006142 mAudioMixer->disable(trackId);
Eric Laurent81784c32012-11-19 14:55:58 -08006143 }
6144
6145 } // local variable scope to avoid goto warning
Eric Laurent81784c32012-11-19 14:55:58 -08006146
6147 }
6148
jiabin245cdd92018-12-07 17:55:15 -08006149 if (mHapticChannelMask != AUDIO_CHANNEL_NONE && sq != NULL) {
6150 // When there is no fast track playing haptic and FastMixer exists,
6151 // enabling the first FastTrack, which provides mixed data from normal
6152 // tracks, to play haptic data.
6153 FastTrack *fastTrack = &state->mFastTracks[0];
6154 if (fastTrack->mHapticPlaybackEnabled != noFastHapticTrack) {
6155 fastTrack->mHapticPlaybackEnabled = noFastHapticTrack;
6156 didModify = true;
6157 }
6158 }
6159
Eric Laurent81784c32012-11-19 14:55:58 -08006160 // Push the new FastMixer state if necessary
Jing Mike537412f2023-03-12 11:01:47 +08006161 [[maybe_unused]] bool pauseAudioWatchdog = false;
Eric Laurent81784c32012-11-19 14:55:58 -08006162 if (didModify) {
6163 state->mFastTracksGen++;
6164 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
6165 if (kUseFastMixer == FastMixer_Dynamic &&
6166 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
6167 state->mCommand = FastMixerState::COLD_IDLE;
6168 state->mColdFutexAddr = &mFastMixerFutex;
6169 state->mColdGen++;
6170 mFastMixerFutex = 0;
6171 if (kUseFastMixer == FastMixer_Dynamic) {
6172 mNormalSink = mOutputSink;
6173 }
6174 // If we go into cold idle, need to wait for acknowledgement
6175 // so that fast mixer stops doing I/O.
6176 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
6177 pauseAudioWatchdog = true;
6178 }
Eric Laurent81784c32012-11-19 14:55:58 -08006179 }
6180 if (sq != NULL) {
6181 sq->end(didModify);
Andy Hungf2285312017-02-14 18:31:59 -08006182 // No need to block if the FastMixer is in COLD_IDLE as the FastThread
6183 // is not active. (We BLOCK_UNTIL_ACKED when entering COLD_IDLE
6184 // when bringing the output sink into standby.)
6185 //
6186 // We will get the latest FastMixer state when we come out of COLD_IDLE.
6187 //
6188 // This occurs with BT suspend when we idle the FastMixer with
6189 // active tracks, which may be added or removed.
6190 sq->push(coldIdle ? FastMixerStateQueue::BLOCK_NEVER : block);
Eric Laurent81784c32012-11-19 14:55:58 -08006191 }
6192#ifdef AUDIO_WATCHDOG
6193 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
6194 mAudioWatchdog->pause();
6195 }
6196#endif
6197
6198 // Now perform the deferred reset on fast tracks that have stopped
6199 while (resetMask != 0) {
6200 size_t i = __builtin_ctz(resetMask);
6201 ALOG_ASSERT(i < count);
6202 resetMask &= ~(1 << i);
Andy Hung8d31fd22023-06-26 19:20:57 -07006203 sp<IAfTrack> track = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08006204 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
6205 track->reset();
6206 }
6207
Andy Hung80d03d22018-04-10 10:32:11 -07006208 // Track destruction may occur outside of threadLoop once it is removed from active tracks.
6209 // Ensure the AudioMixer doesn't have a raw "buffer provider" pointer to the track if
6210 // it ceases to be active, to allow safe removal from the AudioMixer at the start
6211 // of prepareTracks_l(); this releases any outstanding buffer back to the track.
6212 // See also the implementation of destroyTrack_l().
6213 for (const auto &track : *tracksToRemove) {
Andy Hungc0691382018-09-12 18:01:57 -07006214 const int trackId = track->id();
6215 if (mAudioMixer->exists(trackId)) { // Normal tracks here, fast tracks in FastMixer.
6216 mAudioMixer->setBufferProvider(trackId, nullptr /* bufferProvider */);
Andy Hung80d03d22018-04-10 10:32:11 -07006217 }
6218 }
6219
Eric Laurent81784c32012-11-19 14:55:58 -08006220 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08006221 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08006222
Eric Laurentb3f315a2021-07-13 15:09:05 +02006223 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0 ||
6224 getEffectChain_l(AUDIO_SESSION_OUTPUT_STAGE) != 0) {
Eric Laurent97d547d2014-09-02 14:45:53 -07006225 mEffectBufferValid = true;
Marco Nelissenac302142014-10-20 13:15:38 -07006226 }
6227
6228 if (mEffectBufferValid) {
Marco Nelissen57088b52014-10-17 16:39:39 -07006229 // as long as there are effects we should clear the effects buffer, to avoid
6230 // passing a non-clean buffer to the effect chain
6231 memset(mEffectBuffer, 0, mEffectBufferSize);
Eric Laurentb62d0362021-10-26 17:40:18 +02006232 if (mType == SPATIALIZER) {
6233 memset(mPostSpatializerBuffer, 0, mPostSpatializerBufferSize);
6234 }
Eric Laurent97d547d2014-09-02 14:45:53 -07006235 }
Andy Hung69aed5f2014-02-25 17:24:40 -08006236 // sink or mix buffer must be cleared if all tracks are connected to an
6237 // effect chain as in this case the mixer will not write to the sink or mix buffer
6238 // and track effects will accumulate into it
Eric Laurent39095982021-08-24 18:29:27 +02006239 // always clear sink buffer for spatializer output as the output of the spatializer
6240 // effect will be accumulated into it
6241 if ((mBytesRemaining == 0) && (((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
6242 (mixedTracks == 0 && fastTracks > 0)) || (mType == SPATIALIZER))) {
Eric Laurent81784c32012-11-19 14:55:58 -08006243 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08006244 if (mMixerBufferValid) {
6245 memset(mMixerBuffer, 0, mMixerBufferSize);
6246 // TODO: In testing, mSinkBuffer below need not be cleared because
6247 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
6248 // after mixing.
6249 //
6250 // To enforce this guarantee:
6251 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
6252 // (mixedTracks == 0 && fastTracks > 0))
6253 // must imply MIXER_TRACKS_READY.
6254 // Later, we may clear buffers regardless, and skip much of this logic.
6255 }
Andy Hung98ef9782014-03-04 14:46:50 -08006256 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07006257 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08006258 }
6259
6260 // if any fast tracks, then status is ready
6261 mMixerStatusIgnoringFastTracks = mixerStatus;
6262 if (fastTracks > 0) {
6263 mixerStatus = MIXER_TRACKS_READY;
6264 }
6265 return mixerStatus;
6266}
6267
Andy Hungc5007f82023-08-29 14:26:09 -07006268// trackCountForUid_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07006269uint32_t PlaybackThread::trackCountForUid_l(uid_t uid) const
Eric Laurentad7dd962016-09-22 12:38:37 -07006270{
6271 uint32_t trackCount = 0;
6272 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hung1f12a8a2016-11-07 16:10:30 -08006273 if (mTracks[i]->uid() == uid) {
Eric Laurentad7dd962016-09-22 12:38:37 -07006274 trackCount++;
6275 }
6276 }
6277 return trackCount;
6278}
6279
Andy Hungee58e4a2023-07-07 13:47:37 -07006280bool PlaybackThread::IsTimestampAdvancing::check(AudioStreamOut* output)
ziyangch8f194f12021-12-01 13:48:04 -08006281{
Brian Lindahl65e90012022-07-27 18:01:07 +02006282 // Check the timestamp to see if it's advancing once every 150ms. If we check too frequently, we
6283 // could falsely detect that the frame position has stalled due to underrun because we haven't
6284 // given the Audio HAL enough time to update.
6285 const nsecs_t nowNs = systemTime();
6286 if (nowNs - mPreviousNs < mMinimumTimeBetweenChecksNs) {
6287 return mLatchedValue;
6288 }
6289 mPreviousNs = nowNs;
6290 mLatchedValue = false;
6291 // Determine if the presentation position is still advancing.
ziyangch8f194f12021-12-01 13:48:04 -08006292 uint64_t position = 0;
6293 struct timespec unused;
Brian Lindahl65e90012022-07-27 18:01:07 +02006294 const status_t ret = output->getPresentationPosition(&position, &unused);
ziyangch8f194f12021-12-01 13:48:04 -08006295 if (ret == NO_ERROR) {
Brian Lindahl65e90012022-07-27 18:01:07 +02006296 if (position != mPreviousPosition) {
6297 mPreviousPosition = position;
6298 mLatchedValue = true;
ziyangch8f194f12021-12-01 13:48:04 -08006299 }
6300 }
Brian Lindahl65e90012022-07-27 18:01:07 +02006301 return mLatchedValue;
6302}
6303
Andy Hungee58e4a2023-07-07 13:47:37 -07006304void PlaybackThread::IsTimestampAdvancing::clear()
Brian Lindahl65e90012022-07-27 18:01:07 +02006305{
6306 mLatchedValue = true;
6307 mPreviousPosition = 0;
6308 mPreviousNs = 0;
ziyangch8f194f12021-12-01 13:48:04 -08006309}
6310
Andy Hungc5007f82023-08-29 14:26:09 -07006311// isTrackAllowed_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07006312bool MixerThread::isTrackAllowed_l(
Andy Hung1bc088a2018-02-09 15:57:31 -08006313 audio_channel_mask_t channelMask, audio_format_t format,
6314 audio_session_t sessionId, uid_t uid) const
Eric Laurent81784c32012-11-19 14:55:58 -08006315{
Andy Hung1bc088a2018-02-09 15:57:31 -08006316 if (!PlaybackThread::isTrackAllowed_l(channelMask, format, sessionId, uid)) {
6317 return false;
Eric Laurentad7dd962016-09-22 12:38:37 -07006318 }
Andy Hung1bc088a2018-02-09 15:57:31 -08006319 // Check validity as we don't call AudioMixer::create() here.
Mikhail Naganov7ad7a252019-07-30 14:42:32 -07006320 if (!mAudioMixer->isValidFormat(format)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08006321 ALOGW("%s: invalid format: %#x", __func__, format);
6322 return false;
6323 }
Mikhail Naganov7ad7a252019-07-30 14:42:32 -07006324 if (!mAudioMixer->isValidChannelMask(channelMask)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08006325 ALOGW("%s: invalid channelMask: %#x", __func__, channelMask);
6326 return false;
6327 }
6328 return true;
Eric Laurent81784c32012-11-19 14:55:58 -08006329}
6330
Andy Hungc5007f82023-08-29 14:26:09 -07006331// checkForNewParameter_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07006332bool MixerThread::checkForNewParameter_l(const String8& keyValuePair,
Eric Laurent10351942014-05-08 18:49:52 -07006333 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08006334{
Eric Laurent81784c32012-11-19 14:55:58 -08006335 bool reconfig = false;
Eric Laurent10351942014-05-08 18:49:52 -07006336 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006337
Glenn Kastenc05b8d72016-03-24 09:48:17 -07006338 AutoPark<FastMixer> park(mFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08006339
Eric Laurent10351942014-05-08 18:49:52 -07006340 AudioParameter param = AudioParameter(keyValuePair);
6341 int value;
6342 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
6343 reconfig = true;
6344 }
6345 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung81994d62023-07-20 21:44:14 -07006346 if (!isValidPcmSinkFormat(static_cast<audio_format_t>(value))) {
Eric Laurent10351942014-05-08 18:49:52 -07006347 status = BAD_VALUE;
6348 } else {
6349 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08006350 reconfig = true;
6351 }
Eric Laurent10351942014-05-08 18:49:52 -07006352 }
6353 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hung81994d62023-07-20 21:44:14 -07006354 if (!isValidPcmSinkChannelMask(static_cast<audio_channel_mask_t>(value))) {
Eric Laurent10351942014-05-08 18:49:52 -07006355 status = BAD_VALUE;
6356 } else {
6357 // no need to save value, since it's constant
6358 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006359 }
Eric Laurent10351942014-05-08 18:49:52 -07006360 }
6361 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6362 // do not accept frame count changes if tracks are open as the track buffer
6363 // size depends on frame count and correct behavior would not be guaranteed
6364 // if frame count is changed after track creation
6365 if (!mTracks.isEmpty()) {
6366 status = INVALID_OPERATION;
6367 } else {
6368 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006369 }
Eric Laurent10351942014-05-08 18:49:52 -07006370 }
6371 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07006372 LOG_FATAL("Should not set routing device in MixerThread");
Eric Laurent10351942014-05-08 18:49:52 -07006373 }
Eric Laurent81784c32012-11-19 14:55:58 -08006374
Eric Laurent10351942014-05-08 18:49:52 -07006375 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006376 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07006377 if (!mStandby && status == INVALID_OPERATION) {
Andy Hungdda7aed2023-03-27 15:53:06 -07006378 ALOGW("%s: setParameters failed with keyValuePair %s, entering standby",
6379 __func__, keyValuePair.c_str());
Phil Burk062e67a2015-02-11 13:40:50 -08006380 mOutput->standby();
Andy Hungdda7aed2023-03-27 15:53:06 -07006381 mThreadMetrics.logEndInterval();
6382 mThreadSnapshot.onEnd();
6383 setStandby_l();
Eric Laurent10351942014-05-08 18:49:52 -07006384 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006385 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent81784c32012-11-19 14:55:58 -08006386 }
Eric Laurent10351942014-05-08 18:49:52 -07006387 if (status == NO_ERROR && reconfig) {
6388 readOutputParameters_l();
6389 delete mAudioMixer;
6390 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
Andy Hung1bc088a2018-02-09 15:57:31 -08006391 for (const auto &track : mTracks) {
Andy Hungc0691382018-09-12 18:01:57 -07006392 const int trackId = track->id();
Andy Hung920f6572022-10-06 12:09:49 -07006393 const status_t createStatus = mAudioMixer->create(
Andy Hungc0691382018-09-12 18:01:57 -07006394 trackId,
Andy Hung8d31fd22023-06-26 19:20:57 -07006395 track->channelMask(),
6396 track->format(),
6397 track->sessionId());
Andy Hung920f6572022-10-06 12:09:49 -07006398 ALOGW_IF(createStatus != NO_ERROR,
Andy Hungc0691382018-09-12 18:01:57 -07006399 "%s(): AudioMixer cannot create track(%d)"
6400 " mask %#x, format %#x, sessionId %d",
Andy Hung1bc088a2018-02-09 15:57:31 -08006401 __func__,
Andy Hung8d31fd22023-06-26 19:20:57 -07006402 trackId, track->channelMask(), track->format(), track->sessionId());
Eric Laurent10351942014-05-08 18:49:52 -07006403 }
Eric Laurent73e26b62015-04-27 16:55:58 -07006404 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07006405 }
Eric Laurent81784c32012-11-19 14:55:58 -08006406 }
6407
Dean Wheatley68918102021-03-19 22:09:19 +11006408 return reconfig;
Eric Laurent81784c32012-11-19 14:55:58 -08006409}
6410
6411
Andy Hungee58e4a2023-07-07 13:47:37 -07006412void MixerThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -08006413{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07006414 PlaybackThread::dumpInternals_l(fd, args);
Andy Hung8d672e02023-09-15 18:19:28 -07006415 dprintf(fd, " Thread throttle time (msecs): %u\n", (uint32_t)mThreadThrottleTimeMs);
Andy Hung8ed196a2018-01-05 13:21:11 -08006416 dprintf(fd, " AudioMixer tracks: %s\n", mAudioMixer->trackNames().c_str());
Andy Hung2ddee192015-12-18 17:34:44 -08006417 dprintf(fd, " Master mono: %s\n", mMasterMono ? "on" : "off");
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006418 dprintf(fd, " Master balance: %f (%s)\n", mMasterBalance.load(),
6419 (hasFastMixer() ? std::to_string(mFastMixer->getMasterBalance())
6420 : mBalance.toString()).c_str());
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006421 if (hasFastMixer()) {
6422 dprintf(fd, " FastMixer thread %p tid=%d", mFastMixer.get(), mFastMixer->getTid());
6423
6424 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
6425 // while we are dumping it. It may be inconsistent, but it won't mutate!
6426 // This is a large object so we place it on the heap.
6427 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
Eric Tan2942a4e2018-09-12 17:41:27 -07006428 const std::unique_ptr<FastMixerDumpState> copy =
6429 std::make_unique<FastMixerDumpState>(mFastMixerDumpState);
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006430 copy->dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08006431
6432#ifdef STATE_QUEUE_DUMP
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006433 // Similar for state queue
6434 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
6435 observerCopy.dump(fd);
6436 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
6437 mutatorCopy.dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08006438#endif
6439
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006440#ifdef AUDIO_WATCHDOG
6441 if (mAudioWatchdog != 0) {
6442 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
6443 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
6444 wdCopy.dump(fd);
6445 }
6446#endif
6447
6448 } else {
6449 dprintf(fd, " No FastMixer\n");
6450 }
Eric Laurent90cea102023-05-15 15:08:27 +02006451
6452 dprintf(fd, "Bluetooth latency modes are %senabled\n",
6453 mBluetoothLatencyModesEnabled ? "" : "not ");
6454 dprintf(fd, "HAL does %ssupport Bluetooth latency modes\n", mOutput != nullptr &&
6455 mOutput->audioHwDev->supportsBluetoothVariableLatency() ? "" : "not ");
6456 dprintf(fd, "Supported latency modes: %s\n", toString(mSupportedLatencyModes).c_str());
Eric Laurent81784c32012-11-19 14:55:58 -08006457}
6458
Andy Hungee58e4a2023-07-07 13:47:37 -07006459uint32_t MixerThread::idleSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08006460{
6461 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
6462}
6463
Andy Hungee58e4a2023-07-07 13:47:37 -07006464uint32_t MixerThread::suspendSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08006465{
6466 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
6467}
6468
Andy Hungee58e4a2023-07-07 13:47:37 -07006469void MixerThread::cacheParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08006470{
6471 PlaybackThread::cacheParameters_l();
6472
6473 // FIXME: Relaxed timing because of a certain device that can't meet latency
6474 // Should be reduced to 2x after the vendor fixes the driver issue
6475 // increase threshold again due to low power audio mode. The way this warning
6476 // threshold is calculated and its usefulness should be reconsidered anyway.
6477 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
6478}
6479
Andy Hungee58e4a2023-07-07 13:47:37 -07006480void MixerThread::onHalLatencyModesChanged_l() {
Andy Hung583043b2023-07-17 17:05:00 -07006481 mAfThreadCallback->onSupportedLatencyModesChanged(mId, mSupportedLatencyModes);
Eric Laurentb0463942022-12-20 16:31:10 +01006482}
6483
Andy Hungee58e4a2023-07-07 13:47:37 -07006484void MixerThread::setHalLatencyMode_l() {
Eric Laurentb0463942022-12-20 16:31:10 +01006485 // Only handle latency mode if:
6486 // - mBluetoothLatencyModesEnabled is true
6487 // - the HAL supports latency modes
6488 // - the selected device is Bluetooth LE or A2DP
6489 if (!mBluetoothLatencyModesEnabled.load() || mSupportedLatencyModes.empty()) {
6490 return;
6491 }
6492 if (mOutDeviceTypeAddrs.size() != 1
6493 || !(audio_is_a2dp_out_device(mOutDeviceTypeAddrs[0].mType)
6494 || audio_is_ble_out_device(mOutDeviceTypeAddrs[0].mType))) {
6495 return;
6496 }
6497
6498 audio_latency_mode_t latencyMode = AUDIO_LATENCY_MODE_FREE;
6499 if (mSupportedLatencyModes.size() == 1) {
6500 // If the HAL only support one latency mode currently, confirm the choice
6501 latencyMode = mSupportedLatencyModes[0];
6502 } else if (mSupportedLatencyModes.size() > 1) {
6503 // Request low latency if:
6504 // - At least one active track is either:
6505 // - a fast track with gaming usage or
6506 // - a track with acessibility usage
6507 for (const auto& track : mActiveTracks) {
6508 if ((track->isFastTrack() && track->attributes().usage == AUDIO_USAGE_GAME)
6509 || track->attributes().usage == AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY) {
6510 latencyMode = AUDIO_LATENCY_MODE_LOW;
6511 break;
6512 }
6513 }
6514 }
6515
6516 if (latencyMode != mSetLatencyMode) {
6517 status_t status = mOutput->stream->setLatencyMode(latencyMode);
6518 ALOGD("%s: thread(%d) setLatencyMode(%s) returned %d",
6519 __func__, mId, toString(latencyMode).c_str(), status);
6520 if (status == NO_ERROR) {
6521 mSetLatencyMode = latencyMode;
6522 }
6523 }
6524}
6525
Andy Hungee58e4a2023-07-07 13:47:37 -07006526void MixerThread::updateHalSupportedLatencyModes_l() {
Eric Laurentb0463942022-12-20 16:31:10 +01006527
6528 if (mOutput == nullptr || mOutput->stream == nullptr) {
6529 return;
6530 }
6531 std::vector<audio_latency_mode_t> latencyModes;
6532 const status_t status = mOutput->stream->getRecommendedLatencyModes(&latencyModes);
6533 if (status != NO_ERROR) {
6534 latencyModes.clear();
6535 }
6536 if (latencyModes != mSupportedLatencyModes) {
6537 ALOGD("%s: thread(%d) status %d supported latency modes: %s",
6538 __func__, mId, status, toString(latencyModes).c_str());
6539 mSupportedLatencyModes.swap(latencyModes);
6540 sendHalLatencyModesChangedEvent_l();
6541 }
6542}
6543
Andy Hungee58e4a2023-07-07 13:47:37 -07006544status_t MixerThread::getSupportedLatencyModes(
Eric Laurentb0463942022-12-20 16:31:10 +01006545 std::vector<audio_latency_mode_t>* modes) {
6546 if (modes == nullptr) {
6547 return BAD_VALUE;
6548 }
Andy Hung972bec12023-08-31 16:13:39 -07006549 audio_utils::lock_guard _l(mutex());
Eric Laurentb0463942022-12-20 16:31:10 +01006550 *modes = mSupportedLatencyModes;
6551 return NO_ERROR;
6552}
6553
Andy Hungee58e4a2023-07-07 13:47:37 -07006554void MixerThread::onRecommendedLatencyModeChanged(
Eric Laurentb0463942022-12-20 16:31:10 +01006555 std::vector<audio_latency_mode_t> modes) {
Andy Hung972bec12023-08-31 16:13:39 -07006556 audio_utils::lock_guard _l(mutex());
Eric Laurentb0463942022-12-20 16:31:10 +01006557 if (modes != mSupportedLatencyModes) {
6558 ALOGD("%s: thread(%d) supported latency modes: %s",
6559 __func__, mId, toString(modes).c_str());
6560 mSupportedLatencyModes.swap(modes);
6561 sendHalLatencyModesChangedEvent_l();
6562 }
6563}
6564
Andy Hungee58e4a2023-07-07 13:47:37 -07006565status_t MixerThread::setBluetoothVariableLatencyEnabled(bool enabled) {
Eric Laurentb0463942022-12-20 16:31:10 +01006566 if (mOutput == nullptr || mOutput->audioHwDev == nullptr
6567 || !mOutput->audioHwDev->supportsBluetoothVariableLatency()) {
6568 return INVALID_OPERATION;
6569 }
6570 mBluetoothLatencyModesEnabled.store(enabled);
6571 return NO_ERROR;
6572}
6573
Eric Laurent81784c32012-11-19 14:55:58 -08006574// ----------------------------------------------------------------------------
6575
Andy Hungee58e4a2023-07-07 13:47:37 -07006576/* static */
6577sp<IAfPlaybackThread> IAfPlaybackThread::createDirectOutputThread(
Andy Hung583043b2023-07-17 17:05:00 -07006578 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hungee58e4a2023-07-07 13:47:37 -07006579 AudioStreamOut* output, audio_io_handle_t id, bool systemReady,
6580 const audio_offload_info_t& offloadInfo) {
6581 return sp<DirectOutputThread>::make(
Andy Hung583043b2023-07-17 17:05:00 -07006582 afThreadCallback, output, id, systemReady, offloadInfo);
Andy Hungee58e4a2023-07-07 13:47:37 -07006583}
6584
Andy Hung583043b2023-07-17 17:05:00 -07006585DirectOutputThread::DirectOutputThread(const sp<IAfThreadCallback>& afThreadCallback,
Gareth Fennb18c1a32022-10-05 13:42:36 -07006586 AudioStreamOut* output, audio_io_handle_t id, ThreadBase::type_t type, bool systemReady,
6587 const audio_offload_info_t& offloadInfo)
Andy Hung583043b2023-07-17 17:05:00 -07006588 : PlaybackThread(afThreadCallback, output, id, type, systemReady)
Gareth Fennb18c1a32022-10-05 13:42:36 -07006589 , mOffloadInfo(offloadInfo)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006590{
Andy Hung583043b2023-07-17 17:05:00 -07006591 setMasterBalance(afThreadCallback->getMasterBalance_l());
Eric Laurentbfb1b832013-01-07 09:53:42 -08006592}
6593
Andy Hungee58e4a2023-07-07 13:47:37 -07006594DirectOutputThread::~DirectOutputThread()
Eric Laurent81784c32012-11-19 14:55:58 -08006595{
6596}
6597
Andy Hungee58e4a2023-07-07 13:47:37 -07006598void DirectOutputThread::dumpInternals_l(int fd, const Vector<String16>& args)
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006599{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07006600 PlaybackThread::dumpInternals_l(fd, args);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006601 dprintf(fd, " Master balance: %f Left: %f Right: %f\n",
6602 mMasterBalance.load(), mMasterBalanceLeft, mMasterBalanceRight);
6603}
6604
Andy Hungee58e4a2023-07-07 13:47:37 -07006605void DirectOutputThread::setMasterBalance(float balance)
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006606{
Andy Hung972bec12023-08-31 16:13:39 -07006607 audio_utils::lock_guard _l(mutex());
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006608 if (mMasterBalance != balance) {
6609 mMasterBalance.store(balance);
6610 mBalance.computeStereoBalance(balance, &mMasterBalanceLeft, &mMasterBalanceRight);
6611 broadcast_l();
6612 }
6613}
6614
Andy Hungee58e4a2023-07-07 13:47:37 -07006615void DirectOutputThread::processVolume_l(IAfTrack* track, bool lastTrack)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006616{
Eric Laurentbfb1b832013-01-07 09:53:42 -08006617 float left, right;
6618
Andy Hung333ab962019-05-28 20:23:35 -07006619 // Ensure volumeshaper state always advances even when muted.
Andy Hung8d31fd22023-06-26 19:20:57 -07006620 const sp<AudioTrackServerProxy> proxy = track->audioTrackServerProxy();
Andy Hung398ffa22022-12-13 19:19:53 -08006621
Andy Hung398ffa22022-12-13 19:19:53 -08006622 const int64_t frames = mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
6623 const int64_t time = mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
6624
Dean Wheatleyb11b0022023-09-12 04:07:35 +10006625 ALOGVV("%s: Direct/Offload bufferConsumed:%zu timestamp frames:%lld time:%lld",
6626 __func__, proxy->framesReleased(), (long long)frames, (long long)time);
Andy Hung398ffa22022-12-13 19:19:53 -08006627
6628 const int64_t volumeShaperFrames =
6629 mMonotonicFrameCounter.updateAndGetMonotonicFrameCount(frames, time);
6630 const auto [shaperVolume, shaperActive] =
6631 track->getVolumeHandler()->getVolume(volumeShaperFrames);
Andy Hung333ab962019-05-28 20:23:35 -07006632 mVolumeShaperActive = shaperActive;
6633
Vlad Popae2f5aef2022-07-25 16:00:20 +02006634 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
6635 left = float_from_gain(gain_minifloat_unpack_left(vlr));
6636 right = float_from_gain(gain_minifloat_unpack_right(vlr));
6637
6638 const bool clientVolumeMute = (left == 0.f && right == 0.f);
6639
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08006640 if (mMasterMute || mStreamTypes[track->streamType()].mute || track->isPlaybackRestricted()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08006641 left = right = 0;
6642 } else {
6643 float typeVolume = mStreamTypes[track->streamType()].volume;
Andy Hung333ab962019-05-28 20:23:35 -07006644 const float v = mMasterVolume * typeVolume * shaperVolume;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08006645
Glenn Kastenc56f3422014-03-21 17:53:17 -07006646 if (left > GAIN_FLOAT_UNITY) {
6647 left = GAIN_FLOAT_UNITY;
6648 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07006649 if (right > GAIN_FLOAT_UNITY) {
6650 right = GAIN_FLOAT_UNITY;
6651 }
zhangjincheng86cb3bc2023-01-16 17:17:38 +08006652 left *= v;
6653 right *= v;
Andy Hung583043b2023-07-17 17:05:00 -07006654 if (mAfThreadCallback->getMode() != AUDIO_MODE_IN_COMMUNICATION
zhangjincheng86cb3bc2023-01-16 17:17:38 +08006655 || audio_channel_count_from_out_mask(mChannelMask) > 1) {
6656 left *= mMasterBalanceLeft; // DirectOutputThread balance applied as track volume
6657 right *= mMasterBalanceRight;
6658 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006659 }
6660
Andy Hung583043b2023-07-17 17:05:00 -07006661 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
Vlad Popae8d99472022-06-30 16:02:48 +02006662 /*muteState=*/{mMasterMute,
6663 mStreamTypes[track->streamType()].volume == 0.f,
6664 mStreamTypes[track->streamType()].mute,
Vlad Popae2f5aef2022-07-25 16:00:20 +02006665 track->isPlaybackRestricted(),
Vlad Popa436c9172022-08-02 15:25:08 +02006666 clientVolumeMute,
6667 shaperVolume == 0.f});
Vlad Popae8d99472022-06-30 16:02:48 +02006668
Eric Laurentbfb1b832013-01-07 09:53:42 -08006669 if (lastTrack) {
jiabin76d94692022-12-15 21:51:21 +00006670 track->setFinalVolume(left, right);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006671 if (left != mLeftVolFloat || right != mRightVolFloat) {
6672 mLeftVolFloat = left;
6673 mRightVolFloat = right;
6674
Eric Laurentbfb1b832013-01-07 09:53:42 -08006675 // Delegate volume control to effect in track effect chain if needed
6676 // only one effect chain can be present on DirectOutputThread, so if
6677 // there is one, the track is connected to it
6678 if (!mEffectChains.isEmpty()) {
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09006679 // if effect chain exists, volume is handled by it.
6680 // Convert volumes from float to 8.24
6681 uint32_t vl = (uint32_t)(left * (1 << 24));
6682 uint32_t vr = (uint32_t)(right * (1 << 24));
Shunkai Yaof4847652024-01-12 00:25:20 +00006683 // Direct/Offload effect chains set output volume in setVolume().
6684 (void)mEffectChains[0]->setVolume(&vl, &vr);
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09006685 } else {
6686 // otherwise we directly set the volume.
6687 setVolumeForOutput_l(left, right);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006688 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006689 }
6690 }
6691}
6692
Andy Hungee58e4a2023-07-07 13:47:37 -07006693void DirectOutputThread::onAddNewTrack_l()
Phil Burk43b4dcc2015-06-09 16:53:44 -07006694{
Andy Hung8d31fd22023-06-26 19:20:57 -07006695 sp<IAfTrack> previousTrack = mPreviousTrack.promote();
6696 sp<IAfTrack> latestTrack = mActiveTracks.getLatest();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006697
Eric Laurent0f0631e2015-07-06 18:01:25 -07006698 if (previousTrack != 0 && latestTrack != 0) {
6699 if (mType == DIRECT) {
6700 if (previousTrack.get() != latestTrack.get()) {
6701 mFlushPending = true;
6702 }
6703 } else /* mType == OFFLOAD */ {
Dean Wheatley0f51fd02022-08-31 16:41:40 +10006704 if (previousTrack->sessionId() != latestTrack->sessionId() ||
6705 previousTrack->isFlushPending()) {
Eric Laurent0f0631e2015-07-06 18:01:25 -07006706 mFlushPending = true;
6707 }
6708 }
Revathi Uddaraju20413a92016-10-13 17:16:14 +08006709 } else if (previousTrack == 0) {
6710 // there could be an old track added back during track transition for direct
6711 // output, so always issues flush to flush data of the previous track if it
6712 // was already destroyed with HAL paused, then flush can resume the playback
6713 mFlushPending = true;
Phil Burk43b4dcc2015-06-09 16:53:44 -07006714 }
6715 PlaybackThread::onAddNewTrack_l();
6716}
Eric Laurentbfb1b832013-01-07 09:53:42 -08006717
Andy Hungee58e4a2023-07-07 13:47:37 -07006718PlaybackThread::mixer_state DirectOutputThread::prepareTracks_l(
Andy Hung8d31fd22023-06-26 19:20:57 -07006719 Vector<sp<IAfTrack>>* tracksToRemove
Eric Laurent81784c32012-11-19 14:55:58 -08006720)
6721{
Eric Laurentd595b7c2013-04-03 17:27:56 -07006722 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08006723 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006724 bool doHwPause = false;
6725 bool doHwResume = false;
Eric Laurent81784c32012-11-19 14:55:58 -08006726
6727 // find out which tracks need to be processed
Andy Hung8d31fd22023-06-26 19:20:57 -07006728 for (const sp<IAfTrack>& t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08006729 if (t->isInvalid()) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07006730 ALOGW("An invalidated track shouldn't be in active list");
Eric Laurent5850c4c2016-11-10 13:04:31 -08006731 tracksToRemove->add(t);
Phil Burk43b4dcc2015-06-09 16:53:44 -07006732 continue;
6733 }
6734
Andy Hung8d31fd22023-06-26 19:20:57 -07006735 IAfTrack* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006736#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurent81784c32012-11-19 14:55:58 -08006737 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006738#endif
Eric Laurentfd477972013-10-25 18:10:40 -07006739 // Only consider last track started for volume and mixer state control.
6740 // In theory an older track could underrun and restart after the new one starts
6741 // but as we only care about the transition phase between two tracks on a
6742 // direct output, it is not a problem to ignore the underrun case.
Andy Hung8d31fd22023-06-26 19:20:57 -07006743 sp<IAfTrack> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08006744 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08006745
Kuowei Li23666472021-01-20 10:23:25 +08006746 if (track->isPausePending()) {
6747 track->pauseAck();
6748 // It is possible a track might have been flushed or stopped.
6749 // Other operations such as flush pending might occur on the next prepare.
6750 if (track->isPausing()) {
6751 track->setPaused();
6752 }
6753 // Always perform pause, as an immediate flush will change
6754 // the pause state to be no longer isPausing().
Phil Burk6fc2a7c2015-04-30 16:08:10 -07006755 if (mHwSupportsPause && last && !mHwPaused) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006756 doHwPause = true;
6757 mHwPaused = true;
6758 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08006759 } else if (track->isFlushPending()) {
6760 track->flushAck();
6761 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07006762 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006763 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07006764 } else if (track->isResumePending()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006765 track->resumeAck();
Eric Laurent3df841a2016-07-15 15:15:40 -07006766 if (last) {
6767 mLeftVolFloat = mRightVolFloat = -1.0;
6768 if (mHwPaused) {
6769 doHwResume = true;
6770 mHwPaused = false;
6771 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08006772 }
6773 }
6774
Eric Laurent81784c32012-11-19 14:55:58 -08006775 // The first time a track is added we wait
Phil Burk99adee32014-12-10 16:46:30 -08006776 // for all its buffers to be filled before processing it.
6777 // Allow draining the buffer in case the client
6778 // app does not call stop() and relies on underrun to stop:
Andy Hung8d31fd22023-06-26 19:20:57 -07006779 // hence the test on (track->retryCount() > 1).
6780 // If track->retryCount() <= 1 then track is about to be disabled, paused, removed,
Andy Hung455982f2021-04-27 17:46:12 -07006781 // so we accept any nonzero amount of data delivered by the AudioTrack (which will
6782 // reset the retry counter).
Phil Burkca5e6142015-07-14 09:42:29 -07006783 // Do not use a high threshold for compressed audio.
Andy Hung455982f2021-04-27 17:46:12 -07006784
6785 // target retry count that we will use is based on the time we wait for retries.
6786 const int32_t targetRetryCount = kMaxTrackRetriesDirectMs * 1000 / mActiveSleepTimeUs;
6787 // the retry threshold is when we accept any size for PCM data. This is slightly
6788 // smaller than the retry count so we can push small bits of data without a glitch.
6789 const int32_t retryThreshold = targetRetryCount > 2 ? targetRetryCount - 1 : 1;
Eric Laurent81784c32012-11-19 14:55:58 -08006790 uint32_t minFrames;
Phil Burk99adee32014-12-10 16:46:30 -08006791 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
Andy Hung8d31fd22023-06-26 19:20:57 -07006792 && (track->retryCount() > retryThreshold) && audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006793 minFrames = mNormalFrameCount;
6794 } else {
6795 minFrames = 1;
6796 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006797
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07006798 const size_t framesReady = track->framesReady();
6799 const int trackId = track->id();
6800 if (ATRACE_ENABLED()) {
6801 std::string traceName("nRdy");
6802 traceName += std::to_string(trackId);
6803 ATRACE_INT(traceName.c_str(), framesReady);
6804 }
6805 if ((framesReady >= minFrames) && track->isReady() && !track->isPaused() &&
Eric Laurentab5cdba2014-06-09 17:22:27 -07006806 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08006807 {
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07006808 ALOGVV("track(%d) s=%08x [OK]", trackId, cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08006809
Andy Hung8d31fd22023-06-26 19:20:57 -07006810 if (track->fillingStatus() == IAfTrack::FS_FILLED) {
6811 track->fillingStatus() = IAfTrack::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07006812 if (last) {
6813 // make sure processVolume_l() will apply new volume even if 0
6814 mLeftVolFloat = mRightVolFloat = -1.0;
6815 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08006816 if (!mHwSupportsPause) {
6817 track->resumeAck();
Eric Laurent81784c32012-11-19 14:55:58 -08006818 }
6819 }
6820
6821 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08006822 processVolume_l(track, last);
6823 if (last) {
Andy Hung8d31fd22023-06-26 19:20:57 -07006824 sp<IAfTrack> previousTrack = mPreviousTrack.promote();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006825 if (previousTrack != 0) {
6826 if (track != previousTrack.get()) {
6827 // Flush any data still being written from last track
6828 mBytesRemaining = 0;
Eric Laurent0f0631e2015-07-06 18:01:25 -07006829 // Invalidate previous track to force a seek when resuming.
6830 previousTrack->invalidate();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006831 }
6832 }
6833 mPreviousTrack = track;
6834
Eric Laurentd595b7c2013-04-03 17:27:56 -07006835 // reset retry count
Andy Hung8d31fd22023-06-26 19:20:57 -07006836 track->retryCount() = targetRetryCount;
Eric Laurent5850c4c2016-11-10 13:04:31 -08006837 mActiveTrack = t;
Eric Laurentd595b7c2013-04-03 17:27:56 -07006838 mixerStatus = MIXER_TRACKS_READY;
Eric Laurent5cff4032015-05-26 13:49:58 -07006839 if (mHwPaused) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08006840 doHwResume = true;
6841 mHwPaused = false;
6842 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07006843 }
Eric Laurent81784c32012-11-19 14:55:58 -08006844 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07006845 // clear effect chain input buffer if the last active track started underruns
6846 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07006847 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08006848 mEffectChains[0]->clearInputBuffer();
6849 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07006850 if (track->isStopping_1()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07006851 track->setState(IAfTrackBase::STOPPING_2);
Eric Laurentb369caf2015-03-30 20:51:47 -07006852 if (last && mHwPaused) {
6853 doHwResume = true;
6854 mHwPaused = false;
6855 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07006856 }
6857 if ((track->sharedBuffer() != 0) || track->isStopped() ||
6858 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08006859 // We have consumed all the buffers of this track.
6860 // Remove it from the list of active tracks.
Atneya Nair0cae0432022-05-10 18:12:12 -04006861 bool presComplete = false;
Eric Laurentfd477972013-10-25 18:10:40 -07006862 if (mStandby || !last ||
Atneya Nair0cae0432022-05-10 18:12:12 -04006863 (presComplete = track->presentationComplete(latency_l())) ||
Jindong32dc26e2019-11-11 18:10:01 +08006864 track->isPaused() || mHwPaused) {
Atneya Nair0cae0432022-05-10 18:12:12 -04006865 if (presComplete) {
6866 mOutput->presentationComplete();
6867 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07006868 if (track->isStopping_2()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07006869 track->setState(IAfTrackBase::STOPPED);
Eric Laurentab5cdba2014-06-09 17:22:27 -07006870 }
Eric Laurent81784c32012-11-19 14:55:58 -08006871 if (track->isStopped()) {
6872 track->reset();
6873 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07006874 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08006875 }
6876 } else {
6877 // No buffers for this track. Give it a few chances to
6878 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07006879 // Only consider last track started for mixer state control
Brian Lindahl65e90012022-07-27 18:01:07 +02006880 bool isTimestampAdvancing = mIsTimestampAdvancing.check(mOutput);
Gareth Fennb18c1a32022-10-05 13:42:36 -07006881 if (!isTunerStream() // tuner streams remain active in underrun
Andy Hung8d31fd22023-06-26 19:20:57 -07006882 && --(track->retryCount()) <= 0) {
Brian Lindahl65e90012022-07-27 18:01:07 +02006883 if (isTimestampAdvancing) { // HAL is still playing audio, give us more time.
Andy Hung8d31fd22023-06-26 19:20:57 -07006884 track->retryCount() = kMaxTrackRetriesOffload;
ziyangch8f194f12021-12-01 13:48:04 -08006885 } else {
6886 ALOGV("BUFFER TIMEOUT: remove track(%d) from active list", trackId);
6887 tracksToRemove->add(track);
6888 // indicate to client process that the track was disabled because of
6889 // underrun; it will then automatically call start() when data is available
6890 track->disable();
6891 // only do hw pause when track is going to be removed due to BUFFER TIMEOUT.
6892 // unlike mixerthread, HAL can be paused for direct output
6893 ALOGW("pause because of UNDERRUN, framesReady = %zu,"
6894 "minFrames = %u, mFormat = %#x",
6895 framesReady, minFrames, mFormat);
6896 if (last && mHwSupportsPause && !mHwPaused && !mStandby) {
6897 doHwPause = true;
6898 mHwPaused = true;
6899 }
Eric Laurent0f7b5f22014-12-19 10:43:21 -08006900 }
Haynes Mathew George5c6daae2017-01-24 20:06:05 -08006901 } else if (last) {
6902 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurent81784c32012-11-19 14:55:58 -08006903 }
6904 }
6905 }
6906 }
6907
Eric Laurentd1f69b02014-12-15 14:33:13 -08006908 // if an active track did not command a flush, check for pending flush on stopped tracks
Phil Burk43b4dcc2015-06-09 16:53:44 -07006909 if (!mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006910 for (size_t i = 0; i < mTracks.size(); i++) {
6911 if (mTracks[i]->isFlushPending()) {
6912 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006913 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006914 }
6915 }
6916 }
6917
6918 // make sure the pause/flush/resume sequence is executed in the right order.
6919 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
6920 // before flush and then resume HW. This can happen in case of pause/flush/resume
6921 // if resume is received before pause is executed.
6922 if (mHwSupportsPause && !mStandby &&
Phil Burk43b4dcc2015-06-09 16:53:44 -07006923 (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006924 status_t result = mOutput->stream->pause();
6925 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Gareth Fenncd1e1622022-10-05 11:45:45 -07006926 doHwResume = !doHwPause; // resume if pause is due to flush.
Eric Laurentd1f69b02014-12-15 14:33:13 -08006927 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07006928 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006929 flushHw_l();
6930 }
6931 if (mHwSupportsPause && !mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006932 status_t result = mOutput->stream->resume();
6933 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08006934 }
Eric Laurent81784c32012-11-19 14:55:58 -08006935 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08006936 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08006937
6938 return mixerStatus;
6939}
6940
Andy Hungee58e4a2023-07-07 13:47:37 -07006941void DirectOutputThread::threadLoop_mix()
Eric Laurent81784c32012-11-19 14:55:58 -08006942{
Eric Laurent81784c32012-11-19 14:55:58 -08006943 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08006944 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08006945 // output audio to hardware
6946 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07006947 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08006948 buffer.frameCount = frameCount;
Phil Burk062e67a2015-02-11 13:40:50 -08006949 status_t status = mActiveTrack->getNextBuffer(&buffer);
6950 if (status != NO_ERROR || buffer.raw == NULL) {
Eric Laurent51716182016-02-29 18:00:56 -08006951 // no need to pad with 0 for compressed audio
6952 if (audio_has_proportional_frames(mFormat)) {
6953 memset(curBuf, 0, frameCount * mFrameSize);
6954 }
Eric Laurent81784c32012-11-19 14:55:58 -08006955 break;
6956 }
6957 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
6958 frameCount -= buffer.frameCount;
6959 curBuf += buffer.frameCount * mFrameSize;
6960 mActiveTrack->releaseBuffer(&buffer);
6961 }
Andy Hung2098f272014-02-27 14:00:06 -08006962 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006963 mSleepTimeUs = 0;
6964 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08006965 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08006966}
6967
Andy Hungee58e4a2023-07-07 13:47:37 -07006968void DirectOutputThread::threadLoop_sleepTime()
Eric Laurent81784c32012-11-19 14:55:58 -08006969{
Eric Laurentd1f69b02014-12-15 14:33:13 -08006970 // do not write to HAL when paused
Eric Laurent0f7b5f22014-12-19 10:43:21 -08006971 if (mHwPaused || (usesHwAvSync() && mStandby)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006972 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006973 return;
6974 }
Andy Hung85ba3332021-04-27 17:40:26 -07006975 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
6976 mSleepTimeUs = mActiveSleepTimeUs;
6977 } else {
6978 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006979 }
Andy Hung85ba3332021-04-27 17:40:26 -07006980 // Note: In S or later, we do not write zeroes for
6981 // linear or proportional PCM direct tracks in underrun.
Eric Laurent81784c32012-11-19 14:55:58 -08006982}
6983
Andy Hungee58e4a2023-07-07 13:47:37 -07006984void DirectOutputThread::threadLoop_exit()
Eric Laurentd1f69b02014-12-15 14:33:13 -08006985{
6986 {
Andy Hung972bec12023-08-31 16:13:39 -07006987 audio_utils::lock_guard _l(mutex());
Eric Laurentd1f69b02014-12-15 14:33:13 -08006988 for (size_t i = 0; i < mTracks.size(); i++) {
6989 if (mTracks[i]->isFlushPending()) {
6990 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006991 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006992 }
6993 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07006994 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006995 flushHw_l();
6996 }
6997 }
6998 PlaybackThread::threadLoop_exit();
6999}
7000
7001// must be called with thread mutex locked
Andy Hungee58e4a2023-07-07 13:47:37 -07007002bool DirectOutputThread::shouldStandby_l()
Eric Laurentd1f69b02014-12-15 14:33:13 -08007003{
7004 bool trackPaused = false;
Eric Laurentb369caf2015-03-30 20:51:47 -07007005 bool trackStopped = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08007006
7007 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
7008 // after a timeout and we will enter standby then.
7009 if (mTracks.size() > 0) {
7010 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
Eric Laurentb369caf2015-03-30 20:51:47 -07007011 trackStopped = mTracks[mTracks.size() - 1]->isStopped() ||
Andy Hung8d31fd22023-06-26 19:20:57 -07007012 mTracks[mTracks.size() - 1]->state() == IAfTrackBase::IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08007013 }
7014
Eric Laurent5cff4032015-05-26 13:49:58 -07007015 return !mStandby && !(trackPaused || (mHwPaused && !trackStopped));
Eric Laurentd1f69b02014-12-15 14:33:13 -08007016}
7017
Andy Hungc5007f82023-08-29 14:26:09 -07007018// checkForNewParameter_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07007019bool DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
Eric Laurent10351942014-05-08 18:49:52 -07007020 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08007021{
7022 bool reconfig = false;
Eric Laurent10351942014-05-08 18:49:52 -07007023 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08007024
Eric Laurent10351942014-05-08 18:49:52 -07007025 AudioParameter param = AudioParameter(keyValuePair);
7026 int value;
7027 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07007028 LOG_FATAL("Should not set routing device in DirectOutputThread");
Eric Laurent81784c32012-11-19 14:55:58 -08007029 }
Eric Laurent10351942014-05-08 18:49:52 -07007030 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
7031 // do not accept frame count changes if tracks are open as the track buffer
7032 // size depends on frame count and correct behavior would not be garantied
7033 // if frame count is changed after track creation
7034 if (!mTracks.isEmpty()) {
7035 status = INVALID_OPERATION;
7036 } else {
7037 reconfig = true;
7038 }
7039 }
7040 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007041 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07007042 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08007043 mOutput->standby();
Andy Hungcf10d742020-04-28 15:38:24 -07007044 if (!mStandby) {
7045 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07007046 mThreadSnapshot.onEnd();
Eric Laurent19952e12023-04-20 10:08:29 +02007047 setStandby_l();
Andy Hungcf10d742020-04-28 15:38:24 -07007048 }
Eric Laurent10351942014-05-08 18:49:52 -07007049 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007050 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07007051 }
7052 if (status == NO_ERROR && reconfig) {
7053 readOutputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07007054 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07007055 }
7056 }
7057
Dean Wheatley68918102021-03-19 22:09:19 +11007058 return reconfig;
Eric Laurent81784c32012-11-19 14:55:58 -08007059}
7060
Andy Hungee58e4a2023-07-07 13:47:37 -07007061uint32_t DirectOutputThread::activeSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08007062{
7063 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08007064 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08007065 time = PlaybackThread::activeSleepTimeUs();
7066 } else {
Eric Laurent51716182016-02-29 18:00:56 -08007067 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007068 }
7069 return time;
7070}
7071
Andy Hungee58e4a2023-07-07 13:47:37 -07007072uint32_t DirectOutputThread::idleSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08007073{
7074 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08007075 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08007076 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
7077 } else {
Eric Laurent51716182016-02-29 18:00:56 -08007078 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007079 }
7080 return time;
7081}
7082
Andy Hungee58e4a2023-07-07 13:47:37 -07007083uint32_t DirectOutputThread::suspendSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08007084{
7085 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08007086 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08007087 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
7088 } else {
Eric Laurent51716182016-02-29 18:00:56 -08007089 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007090 }
7091 return time;
7092}
7093
Andy Hungee58e4a2023-07-07 13:47:37 -07007094void DirectOutputThread::cacheParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08007095{
7096 PlaybackThread::cacheParameters_l();
7097
7098 // use shorter standby delay as on normal output to release
7099 // hardware resources as soon as possible
Eric Laurentb369caf2015-03-30 20:51:47 -07007100 // no delay on outputs with HW A/V sync
7101 if (usesHwAvSync()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007102 mStandbyDelayNs = 0;
Phil Burkfdb3c072016-02-09 10:47:02 -08007103 } else if ((mType == OFFLOAD) && !audio_has_proportional_frames(mFormat)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007104 mStandbyDelayNs = kOffloadStandbyDelayNs;
Eric Laurent5cff4032015-05-26 13:49:58 -07007105 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007106 mStandbyDelayNs = microseconds(mActiveSleepTimeUs*2);
Eric Laurent972a1732013-09-04 09:42:59 -07007107 }
Eric Laurent81784c32012-11-19 14:55:58 -08007108}
7109
Andy Hungee58e4a2023-07-07 13:47:37 -07007110void DirectOutputThread::flushHw_l()
Eric Laurente659ef42014-09-29 13:06:46 -07007111{
ziyangch8f194f12021-12-01 13:48:04 -08007112 PlaybackThread::flushHw_l();
Phil Burk062e67a2015-02-11 13:40:50 -08007113 mOutput->flush();
Eric Laurentd1f69b02014-12-15 14:33:13 -08007114 mHwPaused = false;
Phil Burk43b4dcc2015-06-09 16:53:44 -07007115 mFlushPending = false;
Dean Wheatley12473e92021-03-18 23:00:55 +11007116 mTimestampVerifier.discontinuity(discontinuityForStandbyOrFlush());
Sampath Shetty999f0e82020-01-15 10:19:06 +11007117 mTimestamp.clear();
Andy Hung398ffa22022-12-13 19:19:53 -08007118 mMonotonicFrameCounter.onFlush();
Eric Laurente659ef42014-09-29 13:06:46 -07007119}
7120
Andy Hungee58e4a2023-07-07 13:47:37 -07007121int64_t DirectOutputThread::computeWaitTimeNs_l() const {
Andy Hung10cbff12017-02-21 17:30:14 -08007122 // If a VolumeShaper is active, we must wake up periodically to update volume.
7123 const int64_t NS_PER_MS = 1000000;
7124 return mVolumeShaperActive ?
7125 kMinNormalSinkBufferSizeMs * NS_PER_MS : PlaybackThread::computeWaitTimeNs_l();
7126}
7127
Eric Laurent81784c32012-11-19 14:55:58 -08007128// ----------------------------------------------------------------------------
7129
Andy Hungee58e4a2023-07-07 13:47:37 -07007130AsyncCallbackThread::AsyncCallbackThread(
7131 const wp<PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08007132 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07007133 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07007134 mWriteAckSequence(0),
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007135 mDrainSequence(0),
7136 mAsyncError(false)
Eric Laurentbfb1b832013-01-07 09:53:42 -08007137{
7138}
7139
Andy Hungee58e4a2023-07-07 13:47:37 -07007140void AsyncCallbackThread::onFirstRef()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007141{
7142 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
7143}
7144
Andy Hungee58e4a2023-07-07 13:47:37 -07007145bool AsyncCallbackThread::threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007146{
7147 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07007148 uint32_t writeAckSequence;
7149 uint32_t drainSequence;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007150 bool asyncError;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007151
7152 {
Andy Hungc5007f82023-08-29 14:26:09 -07007153 audio_utils::unique_lock _l(mutex());
Haynes Mathew George24a325d2013-12-03 21:26:02 -08007154 while (!((mWriteAckSequence & 1) ||
7155 (mDrainSequence & 1) ||
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007156 mAsyncError ||
Haynes Mathew George24a325d2013-12-03 21:26:02 -08007157 exitPending())) {
Andy Hungc5007f82023-08-29 14:26:09 -07007158 mWaitWorkCV.wait(_l);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08007159 }
7160
Eric Laurentbfb1b832013-01-07 09:53:42 -08007161 if (exitPending()) {
7162 break;
7163 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07007164 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
7165 mWriteAckSequence, mDrainSequence);
7166 writeAckSequence = mWriteAckSequence;
7167 mWriteAckSequence &= ~1;
7168 drainSequence = mDrainSequence;
7169 mDrainSequence &= ~1;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007170 asyncError = mAsyncError;
7171 mAsyncError = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007172 }
7173 {
Andy Hungee58e4a2023-07-07 13:47:37 -07007174 const sp<PlaybackThread> playbackThread = mPlaybackThread.promote();
Eric Laurent4de95592013-09-26 15:28:21 -07007175 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07007176 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07007177 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007178 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07007179 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07007180 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007181 }
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007182 if (asyncError) {
7183 playbackThread->onAsyncError();
7184 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007185 }
7186 }
7187 }
7188 return false;
7189}
7190
Andy Hungee58e4a2023-07-07 13:47:37 -07007191void AsyncCallbackThread::exit()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007192{
7193 ALOGV("AsyncCallbackThread::exit");
Andy Hung972bec12023-08-31 16:13:39 -07007194 audio_utils::lock_guard _l(mutex());
Eric Laurentbfb1b832013-01-07 09:53:42 -08007195 requestExit();
Andy Hungc5007f82023-08-29 14:26:09 -07007196 mWaitWorkCV.notify_all();
Eric Laurentbfb1b832013-01-07 09:53:42 -08007197}
7198
Andy Hungee58e4a2023-07-07 13:47:37 -07007199void AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08007200{
Andy Hung972bec12023-08-31 16:13:39 -07007201 audio_utils::lock_guard _l(mutex());
Eric Laurent3b4529e2013-09-05 18:09:19 -07007202 // bit 0 is cleared
7203 mWriteAckSequence = sequence << 1;
7204}
7205
Andy Hungee58e4a2023-07-07 13:47:37 -07007206void AsyncCallbackThread::resetWriteBlocked()
Eric Laurent3b4529e2013-09-05 18:09:19 -07007207{
Andy Hung972bec12023-08-31 16:13:39 -07007208 audio_utils::lock_guard _l(mutex());
Eric Laurent3b4529e2013-09-05 18:09:19 -07007209 // ignore unexpected callbacks
7210 if (mWriteAckSequence & 2) {
7211 mWriteAckSequence |= 1;
Andy Hungc5007f82023-08-29 14:26:09 -07007212 mWaitWorkCV.notify_one();
Eric Laurentbfb1b832013-01-07 09:53:42 -08007213 }
7214}
7215
Andy Hungee58e4a2023-07-07 13:47:37 -07007216void AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08007217{
Andy Hung972bec12023-08-31 16:13:39 -07007218 audio_utils::lock_guard _l(mutex());
Eric Laurent3b4529e2013-09-05 18:09:19 -07007219 // bit 0 is cleared
7220 mDrainSequence = sequence << 1;
7221}
7222
Andy Hungee58e4a2023-07-07 13:47:37 -07007223void AsyncCallbackThread::resetDraining()
Eric Laurent3b4529e2013-09-05 18:09:19 -07007224{
Andy Hung972bec12023-08-31 16:13:39 -07007225 audio_utils::lock_guard _l(mutex());
Eric Laurent3b4529e2013-09-05 18:09:19 -07007226 // ignore unexpected callbacks
7227 if (mDrainSequence & 2) {
7228 mDrainSequence |= 1;
Andy Hungc5007f82023-08-29 14:26:09 -07007229 mWaitWorkCV.notify_one();
Eric Laurentbfb1b832013-01-07 09:53:42 -08007230 }
7231}
7232
Andy Hungee58e4a2023-07-07 13:47:37 -07007233void AsyncCallbackThread::setAsyncError()
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007234{
Andy Hung972bec12023-08-31 16:13:39 -07007235 audio_utils::lock_guard _l(mutex());
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007236 mAsyncError = true;
Andy Hungc5007f82023-08-29 14:26:09 -07007237 mWaitWorkCV.notify_one();
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007238}
7239
Eric Laurentbfb1b832013-01-07 09:53:42 -08007240
7241// ----------------------------------------------------------------------------
Andy Hungee58e4a2023-07-07 13:47:37 -07007242
7243/* static */
7244sp<IAfPlaybackThread> IAfPlaybackThread::createOffloadThread(
Andy Hung583043b2023-07-17 17:05:00 -07007245 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hungee58e4a2023-07-07 13:47:37 -07007246 AudioStreamOut* output, audio_io_handle_t id, bool systemReady,
7247 const audio_offload_info_t& offloadInfo) {
Andy Hung583043b2023-07-17 17:05:00 -07007248 return sp<OffloadThread>::make(afThreadCallback, output, id, systemReady, offloadInfo);
Andy Hungee58e4a2023-07-07 13:47:37 -07007249}
7250
Andy Hung583043b2023-07-17 17:05:00 -07007251OffloadThread::OffloadThread(const sp<IAfThreadCallback>& afThreadCallback,
Gareth Fennb18c1a32022-10-05 13:42:36 -07007252 AudioStreamOut* output, audio_io_handle_t id, bool systemReady,
7253 const audio_offload_info_t& offloadInfo)
Andy Hung583043b2023-07-17 17:05:00 -07007254 : DirectOutputThread(afThreadCallback, output, id, OFFLOAD, systemReady, offloadInfo),
ziyangch8f194f12021-12-01 13:48:04 -08007255 mPausedWriteLength(0), mPausedBytesRemaining(0), mKeepWakeLock(true)
Eric Laurentbfb1b832013-01-07 09:53:42 -08007256{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07007257 //FIXME: mStandby should be set to true by ThreadBase constructo
Eric Laurentfd477972013-10-25 18:10:40 -07007258 mStandby = true;
Eric Laurent64667972016-03-30 18:19:46 -07007259 mKeepWakeLock = property_get_bool("ro.audio.offload_wakelock", true /* default_value */);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007260}
7261
Andy Hungee58e4a2023-07-07 13:47:37 -07007262void OffloadThread::threadLoop_exit()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007263{
7264 if (mFlushPending || mHwPaused) {
7265 // If a flush is pending or track was paused, just discard buffered data
Andy Hungab65b182023-09-06 19:41:47 -07007266 audio_utils::lock_guard l(mutex());
Eric Laurentbfb1b832013-01-07 09:53:42 -08007267 flushHw_l();
7268 } else {
7269 mMixerStatus = MIXER_DRAIN_ALL;
7270 threadLoop_drain();
7271 }
Uday Gupta56604aa2014-05-13 11:19:17 -07007272 if (mUseAsyncWrite) {
7273 ALOG_ASSERT(mCallbackThread != 0);
7274 mCallbackThread->exit();
7275 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007276 PlaybackThread::threadLoop_exit();
7277}
7278
Andy Hungee58e4a2023-07-07 13:47:37 -07007279PlaybackThread::mixer_state OffloadThread::prepareTracks_l(
Andy Hung8d31fd22023-06-26 19:20:57 -07007280 Vector<sp<IAfTrack>>* tracksToRemove
Eric Laurentbfb1b832013-01-07 09:53:42 -08007281)
7282{
Eric Laurentbfb1b832013-01-07 09:53:42 -08007283 size_t count = mActiveTracks.size();
7284
7285 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07007286 bool doHwPause = false;
7287 bool doHwResume = false;
7288
Glenn Kastenc42e9b42016-03-21 11:35:03 -07007289 ALOGV("OffloadThread::prepareTracks_l active tracks %zu", count);
Eric Laurentede6c3b2013-09-19 14:37:46 -07007290
Eric Laurentbfb1b832013-01-07 09:53:42 -08007291 // find out which tracks need to be processed
Andy Hung8d31fd22023-06-26 19:20:57 -07007292 for (const sp<IAfTrack>& t : mActiveTracks) {
7293 IAfTrack* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07007294#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurentbfb1b832013-01-07 09:53:42 -08007295 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07007296#endif
Eric Laurentfd477972013-10-25 18:10:40 -07007297 // Only consider last track started for volume and mixer state control.
7298 // In theory an older track could underrun and restart after the new one starts
7299 // but as we only care about the transition phase between two tracks on a
7300 // direct output, it is not a problem to ignore the underrun case.
Andy Hung8d31fd22023-06-26 19:20:57 -07007301 sp<IAfTrack> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08007302 bool last = l.get() == track;
Eric Laurentfd477972013-10-25 18:10:40 -07007303
Haynes Mathew George7844f672014-01-15 12:32:55 -08007304 if (track->isInvalid()) {
7305 ALOGW("An invalidated track shouldn't be in active list");
7306 tracksToRemove->add(track);
7307 continue;
7308 }
7309
Andy Hung8d31fd22023-06-26 19:20:57 -07007310 if (track->state() == IAfTrackBase::IDLE) {
Haynes Mathew George7844f672014-01-15 12:32:55 -08007311 ALOGW("An idle track shouldn't be in active list");
7312 continue;
7313 }
7314
Kuowei Li23666472021-01-20 10:23:25 +08007315 if (track->isPausePending()) {
7316 track->pauseAck();
7317 // It is possible a track might have been flushed or stopped.
7318 // Other operations such as flush pending might occur on the next prepare.
7319 if (track->isPausing()) {
7320 track->setPaused();
7321 }
7322 // Always perform pause if last, as an immediate flush will change
7323 // the pause state to be no longer isPausing().
Eric Laurentbfb1b832013-01-07 09:53:42 -08007324 if (last) {
Eric Laurent5cff4032015-05-26 13:49:58 -07007325 if (mHwSupportsPause && !mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07007326 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007327 mHwPaused = true;
7328 }
7329 // If we were part way through writing the mixbuffer to
7330 // the HAL we must save this until we resume
7331 // BUG - this will be wrong if a different track is made active,
7332 // in that case we want to discard the pending data in the
7333 // mixbuffer and tell the client to present it again when the
7334 // track is resumed
7335 mPausedWriteLength = mCurrentWriteLength;
7336 mPausedBytesRemaining = mBytesRemaining;
7337 mBytesRemaining = 0; // stop writing
7338 }
7339 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08007340 } else if (track->isFlushPending()) {
Eric Laurente93cc032016-05-05 10:15:10 -07007341 if (track->isStopping_1()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07007342 track->retryCount() = kMaxTrackStopRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07007343 } else {
Andy Hung8d31fd22023-06-26 19:20:57 -07007344 track->retryCount() = kMaxTrackRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07007345 }
Haynes Mathew George7844f672014-01-15 12:32:55 -08007346 track->flushAck();
7347 if (last) {
7348 mFlushPending = true;
7349 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08007350 } else if (track->isResumePending()){
7351 track->resumeAck();
7352 if (last) {
7353 if (mPausedBytesRemaining) {
7354 // Need to continue write that was interrupted
7355 mCurrentWriteLength = mPausedWriteLength;
7356 mBytesRemaining = mPausedBytesRemaining;
7357 mPausedBytesRemaining = 0;
7358 }
7359 if (mHwPaused) {
7360 doHwResume = true;
7361 mHwPaused = false;
7362 // threadLoop_mix() will handle the case that we need to
7363 // resume an interrupted write
7364 }
7365 // enable write to audio HAL
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007366 mSleepTimeUs = 0;
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08007367
Eric Laurent3df841a2016-07-15 15:15:40 -07007368 mLeftVolFloat = mRightVolFloat = -1.0;
7369
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08007370 // Do not handle new data in this iteration even if track->framesReady()
7371 mixerStatus = MIXER_TRACKS_ENABLED;
7372 }
7373 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07007374 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Andy Hungc0691382018-09-12 18:01:57 -07007375 ALOGVV("OffloadThread: track(%d) s=%08x [OK]", track->id(), cblk->mServer);
Andy Hung8d31fd22023-06-26 19:20:57 -07007376 if (track->fillingStatus() == IAfTrack::FS_FILLED) {
7377 track->fillingStatus() = IAfTrack::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07007378 if (last) {
7379 // make sure processVolume_l() will apply new volume even if 0
7380 mLeftVolFloat = mRightVolFloat = -1.0;
7381 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007382 }
7383
7384 if (last) {
Andy Hung8d31fd22023-06-26 19:20:57 -07007385 sp<IAfTrack> previousTrack = mPreviousTrack.promote();
Eric Laurentd7e59222013-11-15 12:02:28 -08007386 if (previousTrack != 0) {
7387 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08007388 // Flush any data still being written from last track
7389 mBytesRemaining = 0;
7390 if (mPausedBytesRemaining) {
7391 // Last track was paused so we also need to flush saved
7392 // mixbuffer state and invalidate track so that it will
7393 // re-submit that unwritten data when it is next resumed
7394 mPausedBytesRemaining = 0;
7395 // Invalidate is a bit drastic - would be more efficient
7396 // to have a flag to tell client that some of the
7397 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08007398 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08007399 }
7400 // flush data already sent to the DSP if changing audio session as audio
7401 // comes from a different source. Also invalidate previous track to force a
7402 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08007403 if (previousTrack->sessionId() != track->sessionId()) {
7404 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08007405 }
7406 }
7407 }
7408 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007409 // reset retry count
Eric Laurente93cc032016-05-05 10:15:10 -07007410 if (track->isStopping_1()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07007411 track->retryCount() = kMaxTrackStopRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07007412 } else {
Andy Hung8d31fd22023-06-26 19:20:57 -07007413 track->retryCount() = kMaxTrackRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07007414 }
Eric Laurent5850c4c2016-11-10 13:04:31 -08007415 mActiveTrack = t;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007416 mixerStatus = MIXER_TRACKS_READY;
7417 }
7418 } else {
Andy Hungc0691382018-09-12 18:01:57 -07007419 ALOGVV("OffloadThread: track(%d) s=%08x [NOT READY]", track->id(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007420 if (track->isStopping_1()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07007421 if (--(track->retryCount()) <= 0) {
Eric Laurente93cc032016-05-05 10:15:10 -07007422 // Hardware buffer can hold a large amount of audio so we must
7423 // wait for all current track's data to drain before we say
7424 // that the track is stopped.
7425 if (mBytesRemaining == 0) {
7426 // Only start draining when all data in mixbuffer
7427 // has been written
7428 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
Andy Hung8d31fd22023-06-26 19:20:57 -07007429 track->setState(IAfTrackBase::STOPPING_2);
7430 // so presentation completes after
Eric Laurente93cc032016-05-05 10:15:10 -07007431 // drain do not drain if no data was ever sent to HAL (mStandby == true)
7432 if (last && !mStandby) {
7433 // do not modify drain sequence if we are already draining. This happens
7434 // when resuming from pause after drain.
7435 if ((mDrainSequence & 1) == 0) {
7436 mSleepTimeUs = 0;
7437 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
7438 mixerStatus = MIXER_DRAIN_TRACK;
7439 mDrainSequence += 2;
7440 }
7441 if (mHwPaused) {
7442 // It is possible to move from PAUSED to STOPPING_1 without
7443 // a resume so we must ensure hardware is running
7444 doHwResume = true;
7445 mHwPaused = false;
7446 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007447 }
7448 }
Eric Laurente93cc032016-05-05 10:15:10 -07007449 } else if (last) {
Andy Hung8d31fd22023-06-26 19:20:57 -07007450 ALOGV("stopping1 underrun retries left %d", track->retryCount());
Eric Laurente93cc032016-05-05 10:15:10 -07007451 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007452 }
7453 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07007454 // Drain has completed or we are in standby, signal presentation complete
7455 if (!(mDrainSequence & 1) || !last || mStandby) {
Andy Hung8d31fd22023-06-26 19:20:57 -07007456 track->setState(IAfTrackBase::STOPPED);
Atneya Nair0cae0432022-05-10 18:12:12 -04007457 mOutput->presentationComplete();
7458 track->presentationComplete(latency_l()); // always returns true
Eric Laurentbfb1b832013-01-07 09:53:42 -08007459 track->reset();
7460 tracksToRemove->add(track);
Dean Wheatley12473e92021-03-18 23:00:55 +11007461 // OFFLOADED stop resets frame counts.
Andy Hungf3234512018-07-03 14:51:47 -07007462 if (!mUseAsyncWrite) {
7463 // If we don't get explicit drain notification we must
7464 // register discontinuity regardless of whether this is
7465 // the previous (!last) or the upcoming (last) track
7466 // to avoid skipping the discontinuity.
Dean Wheatley12473e92021-03-18 23:00:55 +11007467 mTimestampVerifier.discontinuity(
7468 mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Andy Hungf3234512018-07-03 14:51:47 -07007469 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007470 }
7471 } else {
7472 // No buffers for this track. Give it a few chances to
7473 // fill a buffer, then remove it from active list.
Brian Lindahl65e90012022-07-27 18:01:07 +02007474 bool isTimestampAdvancing = mIsTimestampAdvancing.check(mOutput);
Gareth Fennb18c1a32022-10-05 13:42:36 -07007475 if (!isTunerStream() // tuner streams remain active in underrun
Andy Hung8d31fd22023-06-26 19:20:57 -07007476 && --(track->retryCount()) <= 0) {
Brian Lindahl65e90012022-07-27 18:01:07 +02007477 if (isTimestampAdvancing) { // HAL is still playing audio, give us more time.
Andy Hung8d31fd22023-06-26 19:20:57 -07007478 track->retryCount() = kMaxTrackRetriesOffload;
Andy Hungf8044752016-07-27 14:58:11 -07007479 } else {
Andy Hungc0691382018-09-12 18:01:57 -07007480 ALOGV("OffloadThread: BUFFER TIMEOUT: remove track(%d) from active list",
7481 track->id());
Andy Hungf8044752016-07-27 14:58:11 -07007482 tracksToRemove->add(track);
Glenn Kastend3bb6452016-12-05 18:14:37 -08007483 // tell client process that the track was disabled because of underrun;
Andy Hungf8044752016-07-27 14:58:11 -07007484 // it will then automatically call start() when data is available
7485 track->disable();
7486 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007487 } else if (last){
7488 mixerStatus = MIXER_TRACKS_ENABLED;
7489 }
7490 }
7491 }
7492 // compute volume for this track
Wenfeng Sun79458332019-05-29 20:12:43 +08007493 if (track->isReady()) { // check ready to prevent premature start.
7494 processVolume_l(track, last);
7495 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007496 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007497
Eric Laurentea0fade2013-10-04 16:23:48 -07007498 // make sure the pause/flush/resume sequence is executed in the right order.
7499 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
7500 // before flush and then resume HW. This can happen in case of pause/flush/resume
7501 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07007502 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007503 status_t result = mOutput->stream->pause();
7504 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Gareth Fenncd1e1622022-10-05 11:45:45 -07007505 doHwResume = !doHwPause; // resume if pause is due to flush.
Eric Laurent972a1732013-09-04 09:42:59 -07007506 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007507 if (mFlushPending) {
7508 flushHw_l();
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007509 }
Eric Laurentfd477972013-10-25 18:10:40 -07007510 if (!mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007511 status_t result = mOutput->stream->resume();
7512 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07007513 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007514
Eric Laurentbfb1b832013-01-07 09:53:42 -08007515 // remove all the tracks that need to be...
7516 removeTracks_l(*tracksToRemove);
7517
7518 return mixerStatus;
7519}
7520
Eric Laurentbfb1b832013-01-07 09:53:42 -08007521// must be called with thread mutex locked
Andy Hungee58e4a2023-07-07 13:47:37 -07007522bool OffloadThread::waitingAsyncCallback_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007523{
Eric Laurent3b4529e2013-09-05 18:09:19 -07007524 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
7525 mWriteAckSequence, mDrainSequence);
7526 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08007527 return true;
7528 }
7529 return false;
7530}
7531
Andy Hungee58e4a2023-07-07 13:47:37 -07007532bool OffloadThread::waitingAsyncCallback()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007533{
Andy Hung972bec12023-08-31 16:13:39 -07007534 audio_utils::lock_guard _l(mutex());
Eric Laurentbfb1b832013-01-07 09:53:42 -08007535 return waitingAsyncCallback_l();
7536}
7537
Andy Hungee58e4a2023-07-07 13:47:37 -07007538void OffloadThread::flushHw_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007539{
Eric Laurente659ef42014-09-29 13:06:46 -07007540 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08007541 // Flush anything still waiting in the mixbuffer
7542 mCurrentWriteLength = 0;
7543 mBytesRemaining = 0;
7544 mPausedWriteLength = 0;
7545 mPausedBytesRemaining = 0;
Eric Laurent3eaf66b2016-04-01 14:44:17 -07007546 // reset bytes written count to reflect that DSP buffers are empty after flush.
7547 mBytesWritten = 0;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08007548
Eric Laurentbfb1b832013-01-07 09:53:42 -08007549 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07007550 // discard any pending drain or write ack by incrementing sequence
7551 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
7552 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007553 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07007554 mCallbackThread->setWriteBlocked(mWriteAckSequence);
7555 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007556 }
7557}
7558
Andy Hungee58e4a2023-07-07 13:47:37 -07007559void OffloadThread::invalidateTracks(audio_stream_type_t streamType)
Haynes Mathew George05317d22016-05-03 16:34:26 -07007560{
Andy Hung972bec12023-08-31 16:13:39 -07007561 audio_utils::lock_guard _l(mutex());
Eric Laurent13084622016-05-17 10:51:49 -07007562 if (PlaybackThread::invalidateTracks_l(streamType)) {
7563 mFlushPending = true;
7564 }
Haynes Mathew George05317d22016-05-03 16:34:26 -07007565}
7566
Andy Hungee58e4a2023-07-07 13:47:37 -07007567void OffloadThread::invalidateTracks(std::set<audio_port_handle_t>& portIds) {
Andy Hung972bec12023-08-31 16:13:39 -07007568 audio_utils::lock_guard _l(mutex());
jiabinc44b3462022-12-08 12:52:31 -08007569 if (PlaybackThread::invalidateTracks_l(portIds)) {
7570 mFlushPending = true;
7571 }
7572}
7573
Eric Laurentbfb1b832013-01-07 09:53:42 -08007574// ----------------------------------------------------------------------------
7575
Andy Hungee58e4a2023-07-07 13:47:37 -07007576/* static */
7577sp<IAfDuplicatingThread> IAfDuplicatingThread::create(
Andy Hung583043b2023-07-17 17:05:00 -07007578 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hungee58e4a2023-07-07 13:47:37 -07007579 IAfPlaybackThread* mainThread, audio_io_handle_t id, bool systemReady) {
Andy Hung583043b2023-07-17 17:05:00 -07007580 return sp<DuplicatingThread>::make(afThreadCallback, mainThread, id, systemReady);
Andy Hungee58e4a2023-07-07 13:47:37 -07007581}
7582
Andy Hung583043b2023-07-17 17:05:00 -07007583DuplicatingThread::DuplicatingThread(const sp<IAfThreadCallback>& afThreadCallback,
Andy Hung87c693c2023-07-06 20:56:16 -07007584 IAfPlaybackThread* mainThread, audio_io_handle_t id, bool systemReady)
Andy Hung583043b2023-07-17 17:05:00 -07007585 : MixerThread(afThreadCallback, mainThread->getOutput(), id,
Eric Laurent72e3f392015-05-20 14:43:50 -07007586 systemReady, DUPLICATING),
Eric Laurent81784c32012-11-19 14:55:58 -08007587 mWaitTimeMs(UINT_MAX)
7588{
7589 addOutputTrack(mainThread);
7590}
7591
Andy Hungee58e4a2023-07-07 13:47:37 -07007592DuplicatingThread::~DuplicatingThread()
Eric Laurent81784c32012-11-19 14:55:58 -08007593{
7594 for (size_t i = 0; i < mOutputTracks.size(); i++) {
7595 mOutputTracks[i]->destroy();
7596 }
7597}
7598
Andy Hungee58e4a2023-07-07 13:47:37 -07007599void DuplicatingThread::threadLoop_mix()
Eric Laurent81784c32012-11-19 14:55:58 -08007600{
7601 // mix buffers...
Andy Hung920f6572022-10-06 12:09:49 -07007602 if (outputsReady()) {
Glenn Kastend79072e2016-01-06 08:41:20 -08007603 mAudioMixer->process();
Eric Laurent81784c32012-11-19 14:55:58 -08007604 } else {
Eric Laurent02b57082014-11-07 17:28:28 -08007605 if (mMixerBufferValid) {
7606 memset(mMixerBuffer, 0, mMixerBufferSize);
7607 } else {
7608 memset(mSinkBuffer, 0, mSinkBufferSize);
7609 }
Eric Laurent81784c32012-11-19 14:55:58 -08007610 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007611 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007612 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08007613 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007614 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08007615}
7616
Andy Hungee58e4a2023-07-07 13:47:37 -07007617void DuplicatingThread::threadLoop_sleepTime()
Eric Laurent81784c32012-11-19 14:55:58 -08007618{
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007619 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08007620 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007621 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007622 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007623 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007624 }
7625 } else if (mBytesWritten != 0) {
7626 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
7627 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08007628 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08007629 } else {
7630 // flush remaining overflow buffers in output tracks
7631 writeFrames = 0;
7632 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007633 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007634 }
7635}
7636
Andy Hungee58e4a2023-07-07 13:47:37 -07007637ssize_t DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08007638{
7639 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hung1c86ebe2018-05-29 20:29:08 -07007640 const ssize_t actualWritten = outputTracks[i]->write(mSinkBuffer, writeFrames);
7641
7642 // Consider the first OutputTrack for timestamp and frame counting.
7643
7644 // The threadLoop() generally assumes writing a full sink buffer size at a time.
7645 // Here, we correct for writeFrames of 0 (a stop) or underruns because
7646 // we always claim success.
7647 if (i == 0) {
7648 const ssize_t correction = mSinkBufferSize / mFrameSize - actualWritten;
7649 ALOGD_IF(correction != 0 && writeFrames != 0,
7650 "%s: writeFrames:%u actualWritten:%zd correction:%zd mFramesWritten:%lld",
7651 __func__, writeFrames, actualWritten, correction, (long long)mFramesWritten);
7652 mFramesWritten -= correction;
7653 }
7654
7655 // TODO: Report correction for the other output tracks and show in the dump.
Eric Laurent81784c32012-11-19 14:55:58 -08007656 }
Andy Hungcf10d742020-04-28 15:38:24 -07007657 if (mStandby) {
7658 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07007659 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -07007660 mStandby = false;
7661 }
Andy Hung25c2dac2014-02-27 14:56:00 -08007662 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08007663}
7664
Andy Hungee58e4a2023-07-07 13:47:37 -07007665void DuplicatingThread::threadLoop_standby()
Eric Laurent81784c32012-11-19 14:55:58 -08007666{
7667 // DuplicatingThread implements standby by stopping all tracks
7668 for (size_t i = 0; i < outputTracks.size(); i++) {
7669 outputTracks[i]->stop();
7670 }
7671}
7672
Andy Hung8a5abfd2023-12-07 19:35:12 -08007673void DuplicatingThread::threadLoop_exit()
7674{
7675 // Prevent calling the OutputTrack dtor in the DuplicatingThread dtor
7676 // where other mutexes (i.e. AudioPolicyService_Mutex) may be held.
7677 // Do so here in the threadLoop_exit().
7678
7679 SortedVector <sp<IAfOutputTrack>> localTracks;
7680 {
7681 audio_utils::lock_guard l(mutex());
7682 localTracks = std::move(mOutputTracks);
7683 mOutputTracks.clear();
7684 }
7685 localTracks.clear();
7686 outputTracks.clear();
7687 PlaybackThread::threadLoop_exit();
7688}
7689
Andy Hungee58e4a2023-07-07 13:47:37 -07007690void DuplicatingThread::dumpInternals_l(int fd, const Vector<String16>& args)
Andy Hung1bc088a2018-02-09 15:57:31 -08007691{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07007692 MixerThread::dumpInternals_l(fd, args);
Andy Hung1bc088a2018-02-09 15:57:31 -08007693
7694 std::stringstream ss;
7695 const size_t numTracks = mOutputTracks.size();
7696 ss << " " << numTracks << " OutputTracks";
7697 if (numTracks > 0) {
7698 ss << ":";
7699 for (const auto &track : mOutputTracks) {
Andy Hung87c693c2023-07-06 20:56:16 -07007700 const auto thread = track->thread().promote();
Andy Hungc0691382018-09-12 18:01:57 -07007701 ss << " (" << track->id() << " : ";
Andy Hung1bc088a2018-02-09 15:57:31 -08007702 if (thread.get() != nullptr) {
7703 ss << thread.get() << ", " << thread->id();
7704 } else {
7705 ss << "null";
7706 }
7707 ss << ")";
7708 }
7709 }
7710 ss << "\n";
7711 std::string result = ss.str();
7712 write(fd, result.c_str(), result.size());
7713}
7714
Andy Hungee58e4a2023-07-07 13:47:37 -07007715void DuplicatingThread::saveOutputTracks()
Eric Laurent81784c32012-11-19 14:55:58 -08007716{
7717 outputTracks = mOutputTracks;
7718}
7719
Andy Hungee58e4a2023-07-07 13:47:37 -07007720void DuplicatingThread::clearOutputTracks()
Eric Laurent81784c32012-11-19 14:55:58 -08007721{
7722 outputTracks.clear();
7723}
7724
Andy Hungee58e4a2023-07-07 13:47:37 -07007725void DuplicatingThread::addOutputTrack(IAfPlaybackThread* thread)
Eric Laurent81784c32012-11-19 14:55:58 -08007726{
Andy Hung972bec12023-08-31 16:13:39 -07007727 audio_utils::lock_guard _l(mutex());
Andy Hungc25b84a2015-01-14 19:04:10 -08007728 // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
7729 // Adjust for thread->sampleRate() to determine minimum buffer frame count.
7730 // Then triple buffer because Threads do not run synchronously and may not be clock locked.
7731 const size_t frameCount =
7732 3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
7733 // TODO: Consider asynchronous sample rate conversion to handle clock disparity
7734 // from different OutputTracks and their associated MixerThreads (e.g. one may
7735 // nearly empty and the other may be dropping data).
7736
Svet Ganov33761132021-05-13 22:51:08 +00007737 // TODO b/182392769: use attribution source util, move to server edge
7738 AttributionSourceState attributionSource = AttributionSourceState();
7739 attributionSource.uid = VALUE_OR_FATAL(legacy2aidl_uid_t_int32_t(
Philip P. Moltmannbda45752020-07-17 16:41:18 -07007740 IPCThreadState::self()->getCallingUid()));
Svet Ganov33761132021-05-13 22:51:08 +00007741 attributionSource.pid = VALUE_OR_FATAL(legacy2aidl_pid_t_int32_t(
Philip P. Moltmannbda45752020-07-17 16:41:18 -07007742 IPCThreadState::self()->getCallingPid()));
Svet Ganov33761132021-05-13 22:51:08 +00007743 attributionSource.token = sp<BBinder>::make();
Andy Hung8d31fd22023-06-26 19:20:57 -07007744 sp<IAfOutputTrack> outputTrack = IAfOutputTrack::create(thread,
Eric Laurent81784c32012-11-19 14:55:58 -08007745 this,
7746 mSampleRate,
Andy Hungc25b84a2015-01-14 19:04:10 -08007747 mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08007748 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08007749 frameCount,
Svet Ganov33761132021-05-13 22:51:08 +00007750 attributionSource);
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07007751 status_t status = outputTrack != 0 ? outputTrack->initCheck() : (status_t) NO_MEMORY;
7752 if (status != NO_ERROR) {
7753 ALOGE("addOutputTrack() initCheck failed %d", status);
7754 return;
Eric Laurent81784c32012-11-19 14:55:58 -08007755 }
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07007756 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
7757 mOutputTracks.add(outputTrack);
7758 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
7759 updateWaitTime_l();
Eric Laurent81784c32012-11-19 14:55:58 -08007760}
7761
Andy Hungee58e4a2023-07-07 13:47:37 -07007762void DuplicatingThread::removeOutputTrack(IAfPlaybackThread* thread)
Eric Laurent81784c32012-11-19 14:55:58 -08007763{
Andy Hung972bec12023-08-31 16:13:39 -07007764 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08007765 for (size_t i = 0; i < mOutputTracks.size(); i++) {
7766 if (mOutputTracks[i]->thread() == thread) {
7767 mOutputTracks[i]->destroy();
7768 mOutputTracks.removeAt(i);
7769 updateWaitTime_l();
Andy Hung8d672e02023-09-15 18:19:28 -07007770 // NO_THREAD_SAFETY_ANALYSIS
7771 // Lambda workaround: as thread != this
7772 // we can safely call the remote thread getOutput.
7773 const bool equalOutput =
7774 [&](){ return thread->getOutput() == mOutput; }();
7775 if (equalOutput) {
7776 mOutput = nullptr;
Eric Laurentf6870ae2015-05-08 10:50:03 -07007777 }
Eric Laurent81784c32012-11-19 14:55:58 -08007778 return;
7779 }
7780 }
Eric Laurentf6870ae2015-05-08 10:50:03 -07007781 ALOGV("removeOutputTrack(): unknown thread: %p", thread);
Eric Laurent81784c32012-11-19 14:55:58 -08007782}
7783
Andy Hungc5007f82023-08-29 14:26:09 -07007784// caller must hold mutex()
Andy Hungee58e4a2023-07-07 13:47:37 -07007785void DuplicatingThread::updateWaitTime_l()
Eric Laurent81784c32012-11-19 14:55:58 -08007786{
7787 mWaitTimeMs = UINT_MAX;
7788 for (size_t i = 0; i < mOutputTracks.size(); i++) {
Andy Hung87c693c2023-07-06 20:56:16 -07007789 const auto strong = mOutputTracks[i]->thread().promote();
Eric Laurent81784c32012-11-19 14:55:58 -08007790 if (strong != 0) {
7791 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
7792 if (waitTimeMs < mWaitTimeMs) {
7793 mWaitTimeMs = waitTimeMs;
7794 }
7795 }
7796 }
7797}
7798
Andy Hungee58e4a2023-07-07 13:47:37 -07007799bool DuplicatingThread::outputsReady()
Eric Laurent81784c32012-11-19 14:55:58 -08007800{
7801 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hung87c693c2023-07-06 20:56:16 -07007802 const auto thread = outputTracks[i]->thread().promote();
Eric Laurent81784c32012-11-19 14:55:58 -08007803 if (thread == 0) {
7804 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
7805 outputTracks[i].get());
7806 return false;
7807 }
Andy Hung87c693c2023-07-06 20:56:16 -07007808 IAfPlaybackThread* const playbackThread = thread->asIAfPlaybackThread().get();
Eric Laurent81784c32012-11-19 14:55:58 -08007809 // see note at standby() declaration
Andy Hung440901d2023-06-29 21:19:25 -07007810 if (playbackThread->inStandby() && !playbackThread->isSuspended()) {
Eric Laurent81784c32012-11-19 14:55:58 -08007811 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
7812 thread.get());
7813 return false;
7814 }
7815 }
7816 return true;
7817}
7818
Andy Hungee58e4a2023-07-07 13:47:37 -07007819void DuplicatingThread::sendMetadataToBackend_l(
Kevin Rocard12381092018-04-11 09:19:59 -07007820 const StreamOutHalInterface::SourceMetadata& metadata)
Kevin Rocard069c2712018-03-29 19:09:14 -07007821{
Kevin Rocard12381092018-04-11 09:19:59 -07007822 for (auto& outputTrack : outputTracks) { // not mOutputTracks
7823 outputTrack->setMetadatas(metadata.tracks);
7824 }
Kevin Rocard069c2712018-03-29 19:09:14 -07007825}
7826
Andy Hungee58e4a2023-07-07 13:47:37 -07007827uint32_t DuplicatingThread::activeSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08007828{
Andy Hung7a6a0f02023-11-29 13:42:08 -08007829 // return half the wait time in microseconds.
7830 return std::min(mWaitTimeMs * 500ULL, (unsigned long long)UINT32_MAX); // prevent overflow.
Eric Laurent81784c32012-11-19 14:55:58 -08007831}
7832
Andy Hungee58e4a2023-07-07 13:47:37 -07007833void DuplicatingThread::cacheParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08007834{
7835 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
7836 updateWaitTime_l();
7837
7838 MixerThread::cacheParameters_l();
7839}
7840
Eric Laurentb3f315a2021-07-13 15:09:05 +02007841// ----------------------------------------------------------------------------
7842
Andy Hungee58e4a2023-07-07 13:47:37 -07007843/* static */
7844sp<IAfPlaybackThread> IAfPlaybackThread::createSpatializerThread(
Andy Hung583043b2023-07-17 17:05:00 -07007845 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hungee58e4a2023-07-07 13:47:37 -07007846 AudioStreamOut* output,
7847 audio_io_handle_t id,
7848 bool systemReady,
7849 audio_config_base_t* mixerConfig) {
Andy Hung583043b2023-07-17 17:05:00 -07007850 return sp<SpatializerThread>::make(afThreadCallback, output, id, systemReady, mixerConfig);
Andy Hungee58e4a2023-07-07 13:47:37 -07007851}
7852
Andy Hung583043b2023-07-17 17:05:00 -07007853SpatializerThread::SpatializerThread(const sp<IAfThreadCallback>& afThreadCallback,
Eric Laurentb3f315a2021-07-13 15:09:05 +02007854 AudioStreamOut* output,
7855 audio_io_handle_t id,
7856 bool systemReady,
7857 audio_config_base_t *mixerConfig)
Andy Hung583043b2023-07-17 17:05:00 -07007858 : MixerThread(afThreadCallback, output, id, systemReady, SPATIALIZER, mixerConfig)
Eric Laurentb3f315a2021-07-13 15:09:05 +02007859{
7860}
7861
Andy Hungee58e4a2023-07-07 13:47:37 -07007862void SpatializerThread::setHalLatencyMode_l() {
Eric Laurent68a40a82022-05-03 18:15:04 +02007863 // if mSupportedLatencyModes is empty, the HAL stream does not support
7864 // latency mode control and we can exit.
7865 if (mSupportedLatencyModes.empty()) {
7866 return;
7867 }
7868 audio_latency_mode_t latencyMode = AUDIO_LATENCY_MODE_FREE;
7869 if (mSupportedLatencyModes.size() == 1) {
7870 // If the HAL only support one latency mode currently, confirm the choice
7871 latencyMode = mSupportedLatencyModes[0];
7872 } else if (mSupportedLatencyModes.size() > 1) {
7873 // Request low latency if:
7874 // - The low latency mode is requested by the spatializer controller
7875 // (mRequestedLatencyMode = AUDIO_LATENCY_MODE_LOW)
7876 // AND
7877 // - At least one active track is spatialized
7878 bool hasSpatializedActiveTrack = false;
7879 for (const auto& track : mActiveTracks) {
7880 if (track->isSpatialized()) {
7881 hasSpatializedActiveTrack = true;
7882 break;
7883 }
7884 }
7885 if (hasSpatializedActiveTrack && mRequestedLatencyMode == AUDIO_LATENCY_MODE_LOW) {
7886 latencyMode = AUDIO_LATENCY_MODE_LOW;
7887 }
7888 }
7889
7890 if (latencyMode != mSetLatencyMode) {
7891 status_t status = mOutput->stream->setLatencyMode(latencyMode);
Andy Hung4bd53e72022-11-17 17:21:45 -08007892 ALOGD("%s: thread(%d) setLatencyMode(%s) returned %d",
7893 __func__, mId, toString(latencyMode).c_str(), status);
Eric Laurent68a40a82022-05-03 18:15:04 +02007894 if (status == NO_ERROR) {
7895 mSetLatencyMode = latencyMode;
7896 }
7897 }
7898}
7899
Andy Hungee58e4a2023-07-07 13:47:37 -07007900status_t SpatializerThread::setRequestedLatencyMode(audio_latency_mode_t mode) {
Eric Laurent68a40a82022-05-03 18:15:04 +02007901 if (mode != AUDIO_LATENCY_MODE_LOW && mode != AUDIO_LATENCY_MODE_FREE) {
7902 return BAD_VALUE;
7903 }
Andy Hung972bec12023-08-31 16:13:39 -07007904 audio_utils::lock_guard _l(mutex());
Eric Laurent68a40a82022-05-03 18:15:04 +02007905 mRequestedLatencyMode = mode;
7906 return NO_ERROR;
7907}
7908
Andy Hungee58e4a2023-07-07 13:47:37 -07007909void SpatializerThread::checkOutputStageEffects()
Andy Hung972bec12023-08-31 16:13:39 -07007910NO_THREAD_SAFETY_ANALYSIS
7911// 'createEffect_l' requires holding mutex 'AudioFlinger_Mutex' exclusively
Eric Laurentb3f315a2021-07-13 15:09:05 +02007912{
7913 bool hasVirtualizer = false;
7914 bool hasDownMixer = false;
Andy Hung116bc262023-06-20 18:56:17 -07007915 sp<IAfEffectHandle> finalDownMixer;
Eric Laurentb3f315a2021-07-13 15:09:05 +02007916 {
Andy Hung972bec12023-08-31 16:13:39 -07007917 audio_utils::lock_guard _l(mutex());
Andy Hung116bc262023-06-20 18:56:17 -07007918 sp<IAfEffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_STAGE);
Eric Laurentb3f315a2021-07-13 15:09:05 +02007919 if (chain != 0) {
Eric Laurent1c5e2e32021-08-18 18:50:28 +02007920 hasVirtualizer = chain->getEffectFromType_l(FX_IID_SPATIALIZER) != nullptr;
Eric Laurentb3f315a2021-07-13 15:09:05 +02007921 hasDownMixer = chain->getEffectFromType_l(EFFECT_UIID_DOWNMIX) != nullptr;
7922 }
7923
7924 finalDownMixer = mFinalDownMixer;
7925 mFinalDownMixer.clear();
7926 }
7927
7928 if (hasVirtualizer) {
7929 if (finalDownMixer != nullptr) {
7930 int32_t ret;
Andy Hung116bc262023-06-20 18:56:17 -07007931 finalDownMixer->asIEffect()->disable(&ret);
Eric Laurentb3f315a2021-07-13 15:09:05 +02007932 }
7933 finalDownMixer.clear();
7934 } else if (!hasDownMixer) {
7935 std::vector<effect_descriptor_t> descriptors;
Andy Hung583043b2023-07-17 17:05:00 -07007936 status_t status = mAfThreadCallback->getEffectsFactoryHal()->getDescriptors(
Eric Laurentb3f315a2021-07-13 15:09:05 +02007937 EFFECT_UIID_DOWNMIX, &descriptors);
7938 if (status != NO_ERROR) {
7939 return;
7940 }
7941 ALOG_ASSERT(!descriptors.empty(),
7942 "%s getDescriptors() returned no error but empty list", __func__);
7943
7944 finalDownMixer = createEffect_l(nullptr /*client*/, nullptr /*effectClient*/,
7945 0 /*priority*/, AUDIO_SESSION_OUTPUT_STAGE, &descriptors[0], nullptr /*enabled*/,
Eric Laurentde8caf42021-08-11 17:19:25 +02007946 &status, false /*pinned*/, false /*probe*/, false /*notifyFramesProcessed*/);
Eric Laurentb3f315a2021-07-13 15:09:05 +02007947
7948 if (finalDownMixer == nullptr || (status != NO_ERROR && status != ALREADY_EXISTS)) {
7949 ALOGW("%s error creating downmixer %d", __func__, status);
7950 finalDownMixer.clear();
7951 } else {
7952 int32_t ret;
Andy Hung116bc262023-06-20 18:56:17 -07007953 finalDownMixer->asIEffect()->enable(&ret);
Eric Laurentb3f315a2021-07-13 15:09:05 +02007954 }
7955 }
7956
7957 {
Andy Hung972bec12023-08-31 16:13:39 -07007958 audio_utils::lock_guard _l(mutex());
Eric Laurentb3f315a2021-07-13 15:09:05 +02007959 mFinalDownMixer = finalDownMixer;
7960 }
7961}
7962
Andy Hunge2514462023-12-06 14:59:24 -08007963void SpatializerThread::threadLoop_exit()
7964{
7965 // The Spatializer EffectHandle must be released on the PlaybackThread
7966 // threadLoop() to prevent lock inversion in the SpatializerThread dtor.
7967 mFinalDownMixer.clear();
7968
7969 PlaybackThread::threadLoop_exit();
7970}
7971
Eric Laurent81784c32012-11-19 14:55:58 -08007972// ----------------------------------------------------------------------------
7973// Record
7974// ----------------------------------------------------------------------------
7975
Andy Hung583043b2023-07-17 17:05:00 -07007976sp<IAfRecordThread> IAfRecordThread::create(const sp<IAfThreadCallback>& afThreadCallback,
Andy Hung87c693c2023-07-06 20:56:16 -07007977 AudioStreamIn* input,
7978 audio_io_handle_t id,
7979 bool systemReady) {
Andy Hung583043b2023-07-17 17:05:00 -07007980 return sp<RecordThread>::make(afThreadCallback, input, id, systemReady);
Andy Hung87c693c2023-07-06 20:56:16 -07007981}
7982
Andy Hung583043b2023-07-17 17:05:00 -07007983RecordThread::RecordThread(const sp<IAfThreadCallback>& afThreadCallback,
Eric Laurent81784c32012-11-19 14:55:58 -08007984 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08007985 audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -07007986 bool systemReady
Glenn Kasten46909e72013-02-26 09:20:22 -08007987 ) :
Andy Hung583043b2023-07-17 17:05:00 -07007988 ThreadBase(afThreadCallback, id, RECORD, systemReady, false /* isOut */),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007989 mInput(input),
Mikhail Naganov2534b382019-09-25 13:05:02 -07007990 mSource(mInput),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007991 mActiveTracks(&this->mLocalLog),
7992 mRsmpInBuffer(NULL),
Glenn Kasten1b291842016-07-18 14:55:21 -07007993 // mRsmpInFrames, mRsmpInFramesP2, and mRsmpInFramesOA are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007994 mRsmpInRear(0)
Glenn Kastenb880f5e2014-05-07 08:43:45 -07007995 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
7996 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007997 // mFastCapture below
7998 , mFastCaptureFutex(0)
7999 // mInputSource
8000 // mPipeSink
8001 // mPipeSource
8002 , mPipeFramesP2(0)
8003 // mPipeMemory
8004 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07008005 , mFastTrackAvail(false)
Eric Laurentd8365c52017-07-16 15:27:05 -07008006 , mBtNrecSuspended(false)
Eric Laurent81784c32012-11-19 14:55:58 -08008007{
Glenn Kastend7dca052015-03-05 16:05:54 -08008008 snprintf(mThreadName, kThreadNameLength, "AudioIn_%X", id);
Andy Hung583043b2023-07-17 17:05:00 -07008009 mNBLogWriter = afThreadCallback->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08008010
George Burgess IVa8f90c12020-05-14 11:27:19 -07008011 if (mInput->audioHwDev != nullptr) {
Andy Hungc8fddf32018-08-08 18:32:37 -07008012 mIsMsdDevice = strcmp(
8013 mInput->audioHwDev->moduleName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0;
8014 }
8015
Glenn Kastendeca2ae2014-02-07 10:25:56 -08008016 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008017
Andy Hungc8fddf32018-08-08 18:32:37 -07008018 // TODO: We may also match on address as well as device type for
8019 // AUDIO_DEVICE_IN_BUS, AUDIO_DEVICE_IN_BLUETOOTH_A2DP, AUDIO_DEVICE_IN_REMOTE_SUBMIX
jiabinc52b1ff2019-10-31 17:20:42 -07008020 // TODO: This property should be ensure that only contains one single device type.
8021 mTimestampCorrectedDevice = (audio_devices_t)property_get_int64(
8022 "audio.timestamp.corrected_input_device",
Andy Hungc8fddf32018-08-08 18:32:37 -07008023 (int64_t)(mIsMsdDevice ? AUDIO_DEVICE_IN_BUS // turn on by default for MSD
8024 : AUDIO_DEVICE_NONE));
8025
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008026 // create an NBAIO source for the HAL input stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07008027 mInputSource = new AudioStreamInSource(input->stream);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008028 size_t numCounterOffers = 0;
8029 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07008030#if !LOG_NDEBUG
Jing Mike537412f2023-03-12 11:01:47 +08008031 [[maybe_unused]] ssize_t index =
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07008032#else
8033 (void)
8034#endif
8035 mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008036 ALOG_ASSERT(index == 0);
8037
8038 // initialize fast capture depending on configuration
8039 bool initFastCapture;
8040 switch (kUseFastCapture) {
8041 case FastCapture_Never:
8042 initFastCapture = false;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008043 ALOGV("%p kUseFastCapture = Never, initFastCapture = false", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008044 break;
8045 case FastCapture_Always:
8046 initFastCapture = true;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008047 ALOGV("%p kUseFastCapture = Always, initFastCapture = true", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008048 break;
8049 case FastCapture_Static:
Sampath6fac2332022-12-16 17:34:37 +11008050 initFastCapture = !mIsMsdDevice // Disable fast capture for MSD BUS devices.
Dean Wheatley8e5d9e42023-11-03 12:37:27 +11008051 && audio_is_linear_pcm(mFormat)
Sampath6fac2332022-12-16 17:34:37 +11008052 && (mFrameCount * 1000) / mSampleRate < kMinNormalCaptureBufferSizeMs;
Dean Wheatley8e5d9e42023-11-03 12:37:27 +11008053 ALOGV("%p kUseFastCapture = Static, format = 0x%x, (%lld * 1000) / %u vs %u, "
8054 "initFastCapture = %d, mIsMsdDevice = %d", this, mFormat, (long long)mFrameCount,
8055 mSampleRate, kMinNormalCaptureBufferSizeMs, initFastCapture, mIsMsdDevice);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008056 break;
8057 // case FastCapture_Dynamic:
8058 }
8059
8060 if (initFastCapture) {
Glenn Kastend198b852015-03-16 14:55:53 -07008061 // create a Pipe for FastCapture to write to, and for us and fast tracks to read from
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008062 NBAIO_Format format = mInputSource->format();
Glenn Kasten1b291842016-07-18 14:55:21 -07008063 // quadruple-buffering of 20 ms each; this ensures we can sleep for 20ms in RecordThread
8064 size_t pipeFramesP2 = roundup(4 * FMS_20 * mSampleRate / 1000);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008065 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008066 void *pipeBuffer = nullptr;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008067 const sp<MemoryDealer> roHeap(readOnlyHeap());
8068 sp<IMemory> pipeMemory;
8069 if ((roHeap == 0) ||
8070 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07008071 (pipeBuffer = pipeMemory->unsecurePointer()) == nullptr) {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008072 ALOGE("not enough memory for pipe buffer size=%zu; "
8073 "roHeap=%p, pipeMemory=%p, pipeBuffer=%p; roHeapSize: %lld",
8074 pipeSize, roHeap.get(), pipeMemory.get(), pipeBuffer,
8075 (long long)kRecordThreadReadOnlyHeapSize);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008076 goto failed;
8077 }
8078 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
8079 memset(pipeBuffer, 0, pipeSize);
8080 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
Andy Hung920f6572022-10-06 12:09:49 -07008081 const NBAIO_Format offersFast[1] = {format};
8082 size_t numCounterOffersFast = 0;
Eric Laurent1e28aaa2023-04-16 19:34:23 +02008083 [[maybe_unused]] ssize_t index2 = pipe->negotiate(offersFast, std::size(offersFast),
Andy Hung920f6572022-10-06 12:09:49 -07008084 nullptr /* counterOffers */, numCounterOffersFast);
Eric Laurent1e28aaa2023-04-16 19:34:23 +02008085 ALOG_ASSERT(index2 == 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008086 mPipeSink = pipe;
8087 PipeReader *pipeReader = new PipeReader(*pipe);
Andy Hung920f6572022-10-06 12:09:49 -07008088 numCounterOffersFast = 0;
Eric Laurent1e28aaa2023-04-16 19:34:23 +02008089 index2 = pipeReader->negotiate(offersFast, std::size(offersFast),
Andy Hung920f6572022-10-06 12:09:49 -07008090 nullptr /* counterOffers */, numCounterOffersFast);
Eric Laurent1e28aaa2023-04-16 19:34:23 +02008091 ALOG_ASSERT(index2 == 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008092 mPipeSource = pipeReader;
8093 mPipeFramesP2 = pipeFramesP2;
8094 mPipeMemory = pipeMemory;
8095
8096 // create fast capture
8097 mFastCapture = new FastCapture();
8098 FastCaptureStateQueue *sq = mFastCapture->sq();
8099#ifdef STATE_QUEUE_DUMP
8100 // FIXME
8101#endif
8102 FastCaptureState *state = sq->begin();
8103 state->mCblk = NULL;
8104 state->mInputSource = mInputSource.get();
8105 state->mInputSourceGen++;
8106 state->mPipeSink = pipe;
8107 state->mPipeSinkGen++;
8108 state->mFrameCount = mFrameCount;
8109 state->mCommand = FastCaptureState::COLD_IDLE;
8110 // already done in constructor initialization list
8111 //mFastCaptureFutex = 0;
8112 state->mColdFutexAddr = &mFastCaptureFutex;
8113 state->mColdGen++;
8114 state->mDumpState = &mFastCaptureDumpState;
8115#ifdef TEE_SINK
8116 // FIXME
8117#endif
Andy Hung583043b2023-07-17 17:05:00 -07008118 mFastCaptureNBLogWriter =
8119 afThreadCallback->newWriter_l(kFastCaptureLogSize, "FastCapture");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008120 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
8121 sq->end();
8122 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
8123
8124 // start the fast capture
8125 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
8126 pid_t tid = mFastCapture->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07008127 sendPrioConfigEvent(getpid(), tid, kPriorityFastCapture, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08008128 stream()->setHalThreadPriority(kPriorityFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008129#ifdef AUDIO_WATCHDOG
8130 // FIXME
8131#endif
8132
Glenn Kasten6e6704c2014-07-03 10:20:00 -07008133 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008134 }
Andy Hung8946a282018-04-19 20:04:56 -07008135#ifdef TEE_SINK
8136 mTee.set(mInputSource->format(), NBAIO_Tee::TEE_FLAG_INPUT_THREAD);
8137 mTee.setId(std::string("_") + std::to_string(mId) + "_C");
8138#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008139failed: ;
8140
8141 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08008142}
8143
Andy Hungee58e4a2023-07-07 13:47:37 -07008144RecordThread::~RecordThread()
Eric Laurent81784c32012-11-19 14:55:58 -08008145{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008146 if (mFastCapture != 0) {
8147 FastCaptureStateQueue *sq = mFastCapture->sq();
8148 FastCaptureState *state = sq->begin();
8149 if (state->mCommand == FastCaptureState::COLD_IDLE) {
8150 int32_t old = android_atomic_inc(&mFastCaptureFutex);
8151 if (old == -1) {
8152 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
8153 }
8154 }
8155 state->mCommand = FastCaptureState::EXIT;
8156 sq->end();
8157 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
8158 mFastCapture->join();
8159 mFastCapture.clear();
8160 }
Andy Hung583043b2023-07-17 17:05:00 -07008161 mAfThreadCallback->unregisterWriter(mFastCaptureNBLogWriter);
8162 mAfThreadCallback->unregisterWriter(mNBLogWriter);
Andy Hung57446612015-04-19 23:56:46 -07008163 free(mRsmpInBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08008164}
8165
Andy Hungee58e4a2023-07-07 13:47:37 -07008166void RecordThread::onFirstRef()
Eric Laurent81784c32012-11-19 14:55:58 -08008167{
Glenn Kastend7dca052015-03-05 16:05:54 -08008168 run(mThreadName, PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08008169}
8170
Andy Hungee58e4a2023-07-07 13:47:37 -07008171void RecordThread::preExit()
Eric Laurent555530a2017-02-07 18:17:24 -08008172{
8173 ALOGV(" preExit()");
Andy Hung972bec12023-08-31 16:13:39 -07008174 audio_utils::lock_guard _l(mutex());
Eric Laurent555530a2017-02-07 18:17:24 -08008175 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07008176 sp<IAfRecordTrack> track = mTracks[i];
Eric Laurent555530a2017-02-07 18:17:24 -08008177 track->invalidate();
8178 }
8179 mActiveTracks.clear();
Andy Hungc5007f82023-08-29 14:26:09 -07008180 mStartStopCV.notify_all();
Eric Laurent555530a2017-02-07 18:17:24 -08008181}
8182
Andy Hungee58e4a2023-07-07 13:47:37 -07008183bool RecordThread::threadLoop()
Eric Laurent81784c32012-11-19 14:55:58 -08008184{
Eric Laurent81784c32012-11-19 14:55:58 -08008185 nsecs_t lastWarning = 0;
8186
8187 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08008188
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008189reacquire_wakelock:
Andy Hung8d31fd22023-06-26 19:20:57 -07008190 sp<IAfRecordTrack> activeTrack;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008191 {
Andy Hung972bec12023-08-31 16:13:39 -07008192 audio_utils::lock_guard _l(mutex());
Andy Hungdae27702016-10-31 14:01:16 -07008193 acquireWakeLock_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008194 }
8195
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008196 // used to request a deferred sleep, to be executed later while mutex is unlocked
8197 uint32_t sleepUs = 0;
8198
Andy Hung95c94a22023-10-20 16:41:18 -07008199 // timestamp correction enable is determined under lock, used in processing step.
8200 bool timestampCorrectionEnabled = false;
8201
Andy Hung446f4df2019-02-21 12:26:41 -08008202 int64_t lastLoopCountRead = -2; // never matches "previous" loop, when loopCount = 0.
8203
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008204 // loop while there is work to do
Andy Hung446f4df2019-02-21 12:26:41 -08008205 for (int64_t loopCount = 0;; ++loopCount) { // loopCount used for statistics tracking
Andy Hung116bc262023-06-20 18:56:17 -07008206 Vector<sp<IAfEffectChain>> effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07008207
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008208 // activeTracks accumulates a copy of a subset of mActiveTracks
Andy Hung8d31fd22023-06-26 19:20:57 -07008209 Vector<sp<IAfRecordTrack>> activeTracks;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008210
Glenn Kasten735f45f2014-08-18 15:51:59 -07008211 // reference to the (first and only) active fast track
Andy Hung8d31fd22023-06-26 19:20:57 -07008212 sp<IAfRecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07008213
Glenn Kasten735f45f2014-08-18 15:51:59 -07008214 // reference to a fast track which is about to be removed
Andy Hung8d31fd22023-06-26 19:20:57 -07008215 sp<IAfRecordTrack> fastTrackToRemove;
Glenn Kasten735f45f2014-08-18 15:51:59 -07008216
Eric Laurent33403f02020-05-29 18:35:06 -07008217 bool silenceFastCapture = false;
8218
Andy Hungc5007f82023-08-29 14:26:09 -07008219 { // scope for mutex()
8220 audio_utils::unique_lock _l(mutex());
Eric Laurent000a4192014-01-29 15:17:32 -08008221
Eric Laurent021cf962014-05-13 10:18:14 -07008222 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008223
Eric Laurent000a4192014-01-29 15:17:32 -08008224 // check exitPending here because checkForNewParameters_l() and
Andy Hungc5007f82023-08-29 14:26:09 -07008225 // checkForNewParameters_l() can temporarily release mutex()
Eric Laurent000a4192014-01-29 15:17:32 -08008226 if (exitPending()) {
8227 break;
8228 }
8229
Eric Laurent5c25d562016-07-13 17:17:45 -07008230 // sleep with mutex unlocked
8231 if (sleepUs > 0) {
Glenn Kastenf9715e42016-07-13 14:02:03 -07008232 ATRACE_BEGIN("sleepC");
Andy Hungc5007f82023-08-29 14:26:09 -07008233 (void)mWaitWorkCV.wait_for(_l, std::chrono::microseconds(sleepUs));
Eric Laurent5c25d562016-07-13 17:17:45 -07008234 ATRACE_END();
8235 sleepUs = 0;
8236 continue;
8237 }
8238
Glenn Kasten2b806402013-11-20 16:37:38 -08008239 // if no active track(s), then standby and release wakelock
8240 size_t size = mActiveTracks.size();
8241 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07008242 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07008243 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08008244 releaseWakeLock_l();
8245 ALOGV("RecordThread: loop stopping");
8246 // go to sleep
Andy Hungc5007f82023-08-29 14:26:09 -07008247 mWaitWorkCV.wait(_l);
Eric Laurent81784c32012-11-19 14:55:58 -08008248 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008249 goto reacquire_wakelock;
8250 }
8251
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008252 bool doBroadcast = false;
Eric Laurent5c25d562016-07-13 17:17:45 -07008253 bool allStopped = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008254 for (size_t i = 0; i < size; ) {
Glenn Kasten9e982352013-08-14 14:39:50 -07008255
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008256 activeTrack = mActiveTracks[i];
8257 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07008258 if (activeTrack->isFastTrack()) {
8259 ALOG_ASSERT(fastTrackToRemove == 0);
8260 fastTrackToRemove = activeTrack;
8261 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008262 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08008263 mActiveTracks.remove(activeTrack);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008264 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07008265 continue;
8266 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008267
Andy Hung8d31fd22023-06-26 19:20:57 -07008268 IAfTrackBase::track_state activeTrackState = activeTrack->state();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008269 switch (activeTrackState) {
8270
Andy Hung8d31fd22023-06-26 19:20:57 -07008271 case IAfTrackBase::PAUSING:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008272 mActiveTracks.remove(activeTrack);
Andy Hung8d31fd22023-06-26 19:20:57 -07008273 activeTrack->setState(IAfTrackBase::PAUSED);
François Gaffie39634e42023-10-17 12:13:32 +02008274 if (activeTrack->isFastTrack()) {
8275 ALOGV("%s fast track is paused, thus removed from active list", __func__);
8276 // Keep a ref on fast track to wait for FastCapture thread to get updated
8277 // state before potential track removal
8278 fastTrackToRemove = activeTrack;
8279 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008280 doBroadcast = true;
8281 size--;
8282 continue;
8283
Andy Hung8d31fd22023-06-26 19:20:57 -07008284 case IAfTrackBase::STARTING_1:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008285 sleepUs = 10000;
8286 i++;
Eric Laurent5c25d562016-07-13 17:17:45 -07008287 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008288 continue;
8289
Andy Hung8d31fd22023-06-26 19:20:57 -07008290 case IAfTrackBase::STARTING_2:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008291 doBroadcast = true;
Andy Hungcf10d742020-04-28 15:38:24 -07008292 if (mStandby) {
8293 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07008294 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -07008295 mStandby = false;
8296 }
Andy Hung8d31fd22023-06-26 19:20:57 -07008297 activeTrack->setState(IAfTrackBase::ACTIVE);
Eric Laurent5c25d562016-07-13 17:17:45 -07008298 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008299 break;
8300
Andy Hung8d31fd22023-06-26 19:20:57 -07008301 case IAfTrackBase::ACTIVE:
Eric Laurent5c25d562016-07-13 17:17:45 -07008302 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008303 break;
8304
Andy Hung8d31fd22023-06-26 19:20:57 -07008305 case IAfTrackBase::IDLE: // cannot be on ActiveTracks if idle
8306 case IAfTrackBase::PAUSED: // cannot be on ActiveTracks if paused
8307 case IAfTrackBase::STOPPED: // cannot be on ActiveTracks if destroyed/terminated
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008308 default:
Andy Hungce685402018-10-05 17:23:27 -07008309 LOG_ALWAYS_FATAL("%s: Unexpected active track state:%d, id:%d, tracks:%zu",
8310 __func__, activeTrackState, activeTrack->id(), size);
Glenn Kasten9e982352013-08-14 14:39:50 -07008311 }
Glenn Kasten9e982352013-08-14 14:39:50 -07008312
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008313 if (activeTrack->isFastTrack()) {
8314 ALOG_ASSERT(!mFastTrackAvail);
8315 ALOG_ASSERT(fastTrack == 0);
Eric Laurent33403f02020-05-29 18:35:06 -07008316 // if the active fast track is silenced either:
8317 // 1) silence the whole capture from fast capture buffer if this is
8318 // the only active track
8319 // 2) invalidate this track: this will cause the client to reconnect and possibly
8320 // be invalidated again until unsilenced
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008321 bool invalidate = false;
Eric Laurent33403f02020-05-29 18:35:06 -07008322 if (activeTrack->isSilenced()) {
8323 if (size > 1) {
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008324 invalidate = true;
Eric Laurent33403f02020-05-29 18:35:06 -07008325 } else {
8326 silenceFastCapture = true;
8327 }
8328 }
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008329 // Invalidate fast tracks if access to audio history is required as this is not
8330 // possible with fast tracks. Once the fast track has been invalidated, no new
8331 // fast track will be created until mMaxSharedAudioHistoryMs is cleared.
8332 if (mMaxSharedAudioHistoryMs != 0) {
8333 invalidate = true;
8334 }
8335 if (invalidate) {
8336 activeTrack->invalidate();
8337 ALOG_ASSERT(fastTrackToRemove == 0);
8338 fastTrackToRemove = activeTrack;
8339 removeTrack_l(activeTrack);
8340 mActiveTracks.remove(activeTrack);
8341 size--;
8342 continue;
8343 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008344 fastTrack = activeTrack;
8345 }
Eric Laurent33403f02020-05-29 18:35:06 -07008346
8347 activeTracks.add(activeTrack);
8348 i++;
8349
Glenn Kasten9e982352013-08-14 14:39:50 -07008350 }
Eric Laurent5c25d562016-07-13 17:17:45 -07008351
Andy Hungab65b182023-09-06 19:41:47 -07008352 mActiveTracks.updatePowerState_l(this);
Andy Hungdae27702016-10-31 14:01:16 -07008353
Kevin Rocard069c2712018-03-29 19:09:14 -07008354 updateMetadata_l();
8355
Eric Laurent5c25d562016-07-13 17:17:45 -07008356 if (allStopped) {
8357 standbyIfNotAlreadyInStandby();
8358 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008359 if (doBroadcast) {
Andy Hungc5007f82023-08-29 14:26:09 -07008360 mStartStopCV.notify_all();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008361 }
8362
8363 // sleep if there are no active tracks to process
Eric Tan39ec8d62018-07-24 09:49:29 -07008364 if (activeTracks.isEmpty()) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008365 if (sleepUs == 0) {
8366 sleepUs = kRecordThreadSleepUs;
8367 }
8368 continue;
8369 }
8370 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07008371
Andy Hung95c94a22023-10-20 16:41:18 -07008372 timestampCorrectionEnabled = isTimestampCorrectionEnabled_l();
Eric Laurent81784c32012-11-19 14:55:58 -08008373 lockEffectChains_l(effectChains);
8374 }
8375
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008376 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07008377
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008378 size_t size = effectChains.size();
8379 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008380 // thread mutex is not locked, but effect chain is locked
8381 effectChains[i]->process_l();
8382 }
8383
Glenn Kasten735f45f2014-08-18 15:51:59 -07008384 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008385 if (mFastCapture != 0) {
8386 FastCaptureStateQueue *sq = mFastCapture->sq();
8387 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07008388 bool didModify = false;
8389 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008390 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
8391 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
8392 if (state->mCommand == FastCaptureState::COLD_IDLE) {
8393 int32_t old = android_atomic_inc(&mFastCaptureFutex);
8394 if (old == -1) {
8395 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
8396 }
8397 }
8398 state->mCommand = FastCaptureState::READ_WRITE;
8399#if 0 // FIXME
Andy Hung583043b2023-07-17 17:05:00 -07008400 mFastCaptureDumpState.increaseSamplingN(mAfThreadCallback->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08008401 FastThreadDumpState::kSamplingNforLowRamDevice :
8402 FastThreadDumpState::kSamplingN);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008403#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07008404 didModify = true;
8405 }
8406 audio_track_cblk_t *cblkOld = state->mCblk;
8407 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
8408 if (cblkNew != cblkOld) {
8409 state->mCblk = cblkNew;
8410 // block until acked if removing a fast track
8411 if (cblkOld != NULL) {
8412 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
8413 }
8414 didModify = true;
8415 }
jiabin01c8f562018-07-19 17:47:28 -07008416 AudioBufferProvider* abp = (fastTrack != 0 && fastTrack->isPatchTrack()) ?
8417 reinterpret_cast<AudioBufferProvider*>(fastTrack.get()) : nullptr;
8418 if (state->mFastPatchRecordBufferProvider != abp) {
8419 state->mFastPatchRecordBufferProvider = abp;
8420 state->mFastPatchRecordFormat = fastTrack == 0 ?
8421 AUDIO_FORMAT_INVALID : fastTrack->format();
8422 didModify = true;
8423 }
Eric Laurent33403f02020-05-29 18:35:06 -07008424 if (state->mSilenceCapture != silenceFastCapture) {
8425 state->mSilenceCapture = silenceFastCapture;
8426 didModify = true;
8427 }
Glenn Kasten735f45f2014-08-18 15:51:59 -07008428 sq->end(didModify);
8429 if (didModify) {
8430 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008431#if 0
8432 if (kUseFastCapture == FastCapture_Dynamic) {
8433 mNormalSource = mPipeSource;
8434 }
8435#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008436 }
8437 }
8438
Glenn Kasten735f45f2014-08-18 15:51:59 -07008439 // now run the fast track destructor with thread mutex unlocked
8440 fastTrackToRemove.clear();
8441
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008442 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
8443 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
8444 // slow, then this RecordThread will overrun by not calling HAL read often enough.
8445 // If destination is non-contiguous, first read past the nominal end of buffer, then
8446 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008447
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008448 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Andy Hung920f6572022-10-06 12:09:49 -07008449 ssize_t framesRead = 0; // not needed, remove clang-tidy warning.
Andy Hung446f4df2019-02-21 12:26:41 -08008450 const int64_t lastIoBeginNs = systemTime(); // start IO timing
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008451
8452 // If an NBAIO source is present, use it to read the normal capture's data
8453 if (mPipeSource != 0) {
Andy Hung156317a2018-08-02 11:49:29 -07008454 size_t framesToRead = min(mRsmpInFramesOA - rear, mRsmpInFramesP2 / 2);
Andy Hungd5b638f2018-04-30 13:56:10 -07008455
8456 // The audio fifo read() returns OVERRUN on overflow, and advances the read pointer
8457 // to the full buffer point (clearing the overflow condition). Upon OVERRUN error,
8458 // we immediately retry the read() to get data and prevent another overflow.
8459 for (int retries = 0; retries <= 2; ++retries) {
8460 ALOGW_IF(retries > 0, "overrun on read from pipe, retry #%d", retries);
8461 framesRead = mPipeSource->read((uint8_t*)mRsmpInBuffer + rear * mFrameSize,
8462 framesToRead);
8463 if (framesRead != OVERRUN) break;
8464 }
8465
Andy Hung7a3dc6b2018-05-01 16:39:51 -07008466 const ssize_t availableToRead = mPipeSource->availableToRead();
8467 if (availableToRead >= 0) {
Robert Wu06db0a32021-08-10 19:05:34 +00008468 mMonopipePipeDepthStats.add(availableToRead);
Glenn Kastena2f59b32020-08-03 16:37:24 -07008469 // PipeSource is the primary clock. It is up to the AudioRecord client to keep up.
Andy Hung7a3dc6b2018-05-01 16:39:51 -07008470 LOG_ALWAYS_FATAL_IF((size_t)availableToRead > mPipeFramesP2,
8471 "more frames to read than fifo size, %zd > %zu",
8472 availableToRead, mPipeFramesP2);
8473 const size_t pipeFramesFree = mPipeFramesP2 - availableToRead;
8474 const size_t sleepFrames = min(pipeFramesFree, mRsmpInFramesP2) / 2;
8475 ALOGVV("mPipeFramesP2:%zu mRsmpInFramesP2:%zu sleepFrames:%zu availableToRead:%zd",
8476 mPipeFramesP2, mRsmpInFramesP2, sleepFrames, availableToRead);
Glenn Kasten1b291842016-07-18 14:55:21 -07008477 sleepUs = (sleepFrames * 1000000LL) / mSampleRate;
8478 }
8479 if (framesRead < 0) {
8480 status_t status = (status_t) framesRead;
8481 switch (status) {
8482 case OVERRUN:
8483 ALOGW("overrun on read from pipe");
8484 framesRead = 0;
8485 break;
8486 case NEGOTIATE:
8487 ALOGE("re-negotiation is needed");
8488 framesRead = -1; // Will cause an attempt to recover.
8489 break;
8490 default:
8491 ALOGE("unknown error %d on read from pipe", status);
8492 break;
8493 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008494 }
8495 // otherwise use the HAL / AudioStreamIn directly
8496 } else {
Glenn Kastenec6a7032016-03-14 07:40:23 -07008497 ATRACE_BEGIN("read");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008498 size_t bytesRead;
Mikhail Naganov2534b382019-09-25 13:05:02 -07008499 status_t result = mSource->read(
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008500 (uint8_t*)mRsmpInBuffer + rear * mFrameSize, mBufferSize, &bytesRead);
Glenn Kastenec6a7032016-03-14 07:40:23 -07008501 ATRACE_END();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008502 if (result < 0) {
8503 framesRead = result;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008504 } else {
8505 framesRead = bytesRead / mFrameSize;
8506 }
8507 }
8508
Andy Hung446f4df2019-02-21 12:26:41 -08008509 const int64_t lastIoEndNs = systemTime(); // end IO timing
8510
Andy Hung3f0c9022016-01-15 17:49:46 -08008511 // Update server timestamp with server stats
8512 // systemTime() is optional if the hardware supports timestamps.
Andy Hung743f6402020-06-03 13:17:04 -07008513 if (framesRead >= 0) {
8514 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += framesRead;
8515 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = lastIoEndNs;
8516 }
Andy Hung3f0c9022016-01-15 17:49:46 -08008517
8518 // Update server timestamp with kernel stats
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008519 if (mPipeSource.get() == nullptr /* don't obtain for FastCapture, could block */) {
Andy Hung3f0c9022016-01-15 17:49:46 -08008520 int64_t position, time;
Andy Hung2e2c0bb2018-06-11 19:13:11 -07008521 if (mStandby) {
Dean Wheatley12473e92021-03-18 23:00:55 +11008522 mTimestampVerifier.discontinuity(audio_is_linear_pcm(mFormat) ?
8523 mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS :
8524 mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Mikhail Naganov2534b382019-09-25 13:05:02 -07008525 } else if (mSource->getCapturePosition(&position, &time) == NO_ERROR
Andy Hungc8fddf32018-08-08 18:32:37 -07008526 && time > mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]) {
8527
8528 mTimestampVerifier.add(position, time, mSampleRate);
Andy Hungab65b182023-09-06 19:41:47 -07008529 if (timestampCorrectionEnabled) {
Dean Wheatley56a583e2020-05-08 15:12:17 +10008530 ALOGVV("TS_BEFORE: %d %lld %lld",
Andy Hungc8fddf32018-08-08 18:32:37 -07008531 id(), (long long)time, (long long)position);
8532 auto correctedTimestamp = mTimestampVerifier.getLastCorrectedTimestamp();
8533 position = correctedTimestamp.mFrames;
8534 time = correctedTimestamp.mTimeNs;
Dean Wheatley56a583e2020-05-08 15:12:17 +10008535 ALOGVV("TS_AFTER: %d %lld %lld",
Andy Hungc8fddf32018-08-08 18:32:37 -07008536 id(), (long long)time, (long long)position);
8537 }
8538
Andy Hung3f0c9022016-01-15 17:49:46 -08008539 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = position;
8540 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] = time;
8541 // Note: In general record buffers should tend to be empty in
8542 // a properly running pipeline.
8543 //
8544 // Also, it is not advantageous to call get_presentation_position during the read
8545 // as the read obtains a lock, preventing the timestamp call from executing.
Andy Hung2e2c0bb2018-06-11 19:13:11 -07008546 } else {
8547 mTimestampVerifier.error();
Andy Hung3f0c9022016-01-15 17:49:46 -08008548 }
8549 }
Andy Hunge6c37112019-02-26 17:38:10 -08008550
8551 // From the timestamp, input read latency is negative output write latency.
8552 const audio_input_flags_t flags = mInput != NULL ? mInput->flags : AUDIO_INPUT_FLAG_NONE;
Andy Hung8d31fd22023-06-26 19:20:57 -07008553 const double latencyMs = IAfRecordTrack::checkServerLatencySupported(mFormat, flags)
Andy Hunge6c37112019-02-26 17:38:10 -08008554 ? - mTimestamp.getOutputServerLatencyMs(mSampleRate) : 0.;
8555 if (latencyMs != 0.) { // note 0. means timestamp is empty.
8556 mLatencyMs.add(latencyMs);
8557 }
8558
Andy Hung3f0c9022016-01-15 17:49:46 -08008559 // Use this to track timestamp information
8560 // ALOGD("%s", mTimestamp.toString().c_str());
8561
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008562 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07008563 ALOGE("read failed: framesRead=%zd", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008564 // Force input into standby so that it tries to recover at next read attempt
8565 inputStandBy();
8566 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008567 }
8568 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008569 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008570 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008571 ALOG_ASSERT(framesRead > 0);
Andy Hung6427e442018-08-09 12:51:02 -07008572 mFramesRead += framesRead;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008573
Andy Hung8946a282018-04-19 20:04:56 -07008574#ifdef TEE_SINK
8575 (void)mTee.write((uint8_t*)mRsmpInBuffer + rear * mFrameSize, framesRead);
8576#endif
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008577 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008578 {
8579 size_t part1 = mRsmpInFramesP2 - rear;
8580 if ((size_t) framesRead > part1) {
Andy Hung57446612015-04-19 23:56:46 -07008581 memcpy(mRsmpInBuffer, (uint8_t*)mRsmpInBuffer + mRsmpInFramesP2 * mFrameSize,
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008582 (framesRead - part1) * mFrameSize);
8583 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008584 }
Dean Wheatleyfd56e812020-11-06 22:32:21 +11008585 mRsmpInRear = audio_utils::safe_add_overflow(mRsmpInRear, (int32_t)framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008586
8587 size = activeTracks.size();
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008588
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008589 // loop over each active track
8590 for (size_t i = 0; i < size; i++) {
8591 activeTrack = activeTracks[i];
8592
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008593 // skip fast tracks, as those are handled directly by FastCapture
8594 if (activeTrack->isFastTrack()) {
8595 continue;
8596 }
8597
Andy Hung73c02e42015-03-29 01:13:58 -07008598 // TODO: This code probably should be moved to RecordTrack.
Andy Hung97a893e2015-03-29 01:03:07 -07008599 // TODO: Update the activeTrack buffer converter in case of reconfigure.
8600
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008601 enum {
8602 OVERRUN_UNKNOWN,
8603 OVERRUN_TRUE,
8604 OVERRUN_FALSE
8605 } overrun = OVERRUN_UNKNOWN;
8606
8607 // loop over getNextBuffer to handle circular sink
8608 for (;;) {
8609
Andy Hung8d31fd22023-06-26 19:20:57 -07008610 activeTrack->sinkBuffer().frameCount = ~0;
8611 status_t status = activeTrack->getNextBuffer(&activeTrack->sinkBuffer());
8612 size_t framesOut = activeTrack->sinkBuffer().frameCount;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008613 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
8614
Andy Hung73c02e42015-03-29 01:13:58 -07008615 // check available frames and handle overrun conditions
8616 // if the record track isn't draining fast enough.
8617 bool hasOverrun;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008618 size_t framesIn;
Andy Hung8d31fd22023-06-26 19:20:57 -07008619 activeTrack->resamplerBufferProvider()->sync(&framesIn, &hasOverrun);
Andy Hung73c02e42015-03-29 01:13:58 -07008620 if (hasOverrun) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008621 overrun = OVERRUN_TRUE;
8622 }
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08008623 if (framesOut == 0 || framesIn == 0) {
8624 break;
8625 }
8626
Andy Hung6770c6f2015-04-07 13:43:36 -07008627 // Don't allow framesOut to be larger than what is possible with resampling
8628 // from framesIn.
8629 // This isn't strictly necessary but helps limit buffer resizing in
8630 // RecordBufferConverter. TODO: remove when no longer needed.
Dean Wheatleydea650c2023-11-01 22:49:01 +11008631 if (audio_is_linear_pcm(activeTrack->format())) {
8632 framesOut = min(framesOut,
8633 destinationFramesPossible(
8634 framesIn, mSampleRate, activeTrack->sampleRate()));
8635 }
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008636
8637 if (activeTrack->isDirect()) {
Daniel Van Veen9e2376e2018-09-27 14:37:58 +10008638 // No RecordBufferConverter used for direct streams. Pass
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008639 // straight from RecordThread buffer to RecordTrack buffer.
8640 AudioBufferProvider::Buffer buffer;
8641 buffer.frameCount = framesOut;
Andy Hung920f6572022-10-06 12:09:49 -07008642 const status_t getNextBufferStatus =
Andy Hung8d31fd22023-06-26 19:20:57 -07008643 activeTrack->resamplerBufferProvider()->getNextBuffer(&buffer);
Andy Hung920f6572022-10-06 12:09:49 -07008644 if (getNextBufferStatus == OK && buffer.frameCount != 0) {
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008645 ALOGV_IF(buffer.frameCount != framesOut,
8646 "%s() read less than expected (%zu vs %zu)",
8647 __func__, buffer.frameCount, framesOut);
8648 framesOut = buffer.frameCount;
Andy Hung8d31fd22023-06-26 19:20:57 -07008649 memcpy(activeTrack->sinkBuffer().raw,
8650 buffer.raw, buffer.frameCount * mFrameSize);
8651 activeTrack->resamplerBufferProvider()->releaseBuffer(&buffer);
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008652 } else {
8653 framesOut = 0;
8654 ALOGE("%s() cannot fill request, status: %d, frameCount: %zu",
Andy Hung920f6572022-10-06 12:09:49 -07008655 __func__, getNextBufferStatus, buffer.frameCount);
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008656 }
8657 } else {
8658 // process frames from the RecordThread buffer provider to the RecordTrack
8659 // buffer
Andy Hung8d31fd22023-06-26 19:20:57 -07008660 framesOut = activeTrack->recordBufferConverter()->convert(
8661 activeTrack->sinkBuffer().raw,
8662 activeTrack->resamplerBufferProvider(),
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008663 framesOut);
8664 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008665
8666 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
8667 overrun = OVERRUN_FALSE;
8668 }
8669
Andy Hung93bb5732023-05-04 21:16:34 -07008670 // MediaSyncEvent handling: Synchronize AudioRecord to AudioTrack completion.
8671 const ssize_t framesToDrop =
Andy Hung8d31fd22023-06-26 19:20:57 -07008672 activeTrack->synchronizedRecordState().updateRecordFrames(framesOut);
Andy Hung93bb5732023-05-04 21:16:34 -07008673 if (framesToDrop == 0) {
8674 // no sync event, process normally, otherwise ignore.
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008675 if (framesOut > 0) {
Andy Hung8d31fd22023-06-26 19:20:57 -07008676 activeTrack->sinkBuffer().frameCount = framesOut;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008677 // Sanitize before releasing if the track has no access to the source data
8678 // An idle UID receives silence from non virtual devices until active
8679 if (activeTrack->isSilenced()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07008680 memset(activeTrack->sinkBuffer().raw,
8681 0, framesOut * activeTrack->frameSize());
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008682 }
Andy Hung8d31fd22023-06-26 19:20:57 -07008683 activeTrack->releaseBuffer(&activeTrack->sinkBuffer());
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008684 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008685 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008686 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008687 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008688 }
8689 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008690
8691 switch (overrun) {
8692 case OVERRUN_TRUE:
8693 // client isn't retrieving buffers fast enough
8694 if (!activeTrack->setOverflow()) {
8695 nsecs_t now = systemTime();
8696 // FIXME should lastWarning per track?
8697 if ((now - lastWarning) > kWarningThrottleNs) {
8698 ALOGW("RecordThread: buffer overflow");
8699 lastWarning = now;
8700 }
8701 }
8702 break;
8703 case OVERRUN_FALSE:
8704 activeTrack->clearOverflow();
8705 break;
8706 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008707 break;
8708 }
8709
Andy Hung3f0c9022016-01-15 17:49:46 -08008710 // update frame information and push timestamp out
8711 activeTrack->updateTrackFrameInfo(
Andy Hung8d31fd22023-06-26 19:20:57 -07008712 activeTrack->serverProxy()->framesReleased(),
Andy Hung3f0c9022016-01-15 17:49:46 -08008713 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER],
8714 mSampleRate, mTimestamp);
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008715 }
8716
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008717unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08008718 // enable changes in effect chain
8719 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07008720 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurentcccbc762019-04-05 14:20:05 -07008721 if (audio_has_proportional_frames(mFormat)
8722 && loopCount == lastLoopCountRead + 1) {
8723 const int64_t readPeriodNs = lastIoEndNs - mLastIoEndNs;
8724 const double jitterMs =
8725 TimestampVerifier<int64_t, int64_t>::computeJitterMs(
8726 {framesRead, readPeriodNs},
8727 {0, 0} /* lastTimestamp */, mSampleRate);
8728 const double processMs = (lastIoBeginNs - mLastIoEndNs) * 1e-6;
8729
Andy Hung972bec12023-08-31 16:13:39 -07008730 audio_utils::lock_guard _l(mutex());
Eric Laurentcccbc762019-04-05 14:20:05 -07008731 mIoJitterMs.add(jitterMs);
8732 mProcessTimeMs.add(processMs);
8733 }
8734 // update timing info.
8735 mLastIoBeginNs = lastIoBeginNs;
8736 mLastIoEndNs = lastIoEndNs;
8737 lastLoopCountRead = loopCount;
Eric Laurent81784c32012-11-19 14:55:58 -08008738 }
8739
Glenn Kasten93e471f2013-08-19 08:40:07 -07008740 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08008741
8742 {
Andy Hung972bec12023-08-31 16:13:39 -07008743 audio_utils::lock_guard _l(mutex());
Eric Laurent9a54bc22013-09-09 09:08:44 -07008744 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07008745 sp<IAfRecordTrack> track = mTracks[i];
Eric Laurent9a54bc22013-09-09 09:08:44 -07008746 track->invalidate();
8747 }
Glenn Kasten2b806402013-11-20 16:37:38 -08008748 mActiveTracks.clear();
Andy Hungc5007f82023-08-29 14:26:09 -07008749 mStartStopCV.notify_all();
Eric Laurent81784c32012-11-19 14:55:58 -08008750 }
8751
8752 releaseWakeLock();
8753
8754 ALOGV("RecordThread %p exiting", this);
8755 return false;
8756}
8757
Andy Hungee58e4a2023-07-07 13:47:37 -07008758void RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08008759{
8760 if (!mStandby) {
8761 inputStandBy();
Andy Hungcf10d742020-04-28 15:38:24 -07008762 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07008763 mThreadSnapshot.onEnd();
Eric Laurent81784c32012-11-19 14:55:58 -08008764 mStandby = true;
8765 }
8766}
8767
Andy Hungee58e4a2023-07-07 13:47:37 -07008768void RecordThread::inputStandBy()
Eric Laurent81784c32012-11-19 14:55:58 -08008769{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008770 // Idle the fast capture if it's currently running
8771 if (mFastCapture != 0) {
8772 FastCaptureStateQueue *sq = mFastCapture->sq();
8773 FastCaptureState *state = sq->begin();
8774 if (!(state->mCommand & FastCaptureState::IDLE)) {
8775 state->mCommand = FastCaptureState::COLD_IDLE;
8776 state->mColdFutexAddr = &mFastCaptureFutex;
8777 state->mColdGen++;
8778 mFastCaptureFutex = 0;
8779 sq->end();
8780 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
8781 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
8782#if 0
8783 if (kUseFastCapture == FastCapture_Dynamic) {
8784 // FIXME
8785 }
8786#endif
8787#ifdef AUDIO_WATCHDOG
8788 // FIXME
8789#endif
8790 } else {
8791 sq->end(false /*didModify*/);
8792 }
8793 }
Mikhail Naganov2534b382019-09-25 13:05:02 -07008794 status_t result = mSource->standby();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008795 ALOGE_IF(result != OK, "Error when putting input stream into standby: %d", result);
Andy Hungad6d52d2016-07-18 13:42:03 -07008796
8797 // If going into standby, flush the pipe source.
8798 if (mPipeSource.get() != nullptr) {
8799 const ssize_t flushed = mPipeSource->flush();
8800 if (flushed > 0) {
8801 ALOGV("Input standby flushed PipeSource %zd frames", flushed);
8802 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += flushed;
8803 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
8804 }
8805 }
Eric Laurent81784c32012-11-19 14:55:58 -08008806}
8807
Andy Hungc5007f82023-08-29 14:26:09 -07008808// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07008809sp<IAfRecordTrack> RecordThread::createRecordTrack_l(
Andy Hung88035ac2023-06-27 17:05:02 -07008810 const sp<Client>& client,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07008811 const audio_attributes_t& attr,
Eric Laurentf14db3c2017-12-08 14:20:36 -08008812 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08008813 audio_format_t format,
8814 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08008815 size_t *pFrameCount,
Glenn Kastend848eb42016-03-08 13:42:11 -08008816 audio_session_t sessionId,
Eric Laurentf14db3c2017-12-08 14:20:36 -08008817 size_t *pNotificationFrameCount,
Eric Laurent09f1ed22019-04-24 17:45:17 -07008818 pid_t creatorPid,
Svet Ganov33761132021-05-13 22:51:08 +00008819 const AttributionSourceState& attributionSource,
Eric Laurent05067782016-06-01 18:27:28 -07008820 audio_input_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08008821 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08008822 status_t *status,
Eric Laurentec376dc2021-04-08 20:41:22 +02008823 audio_port_handle_t portId,
8824 int32_t maxSharedAudioHistoryMs)
Eric Laurent81784c32012-11-19 14:55:58 -08008825{
Glenn Kasten74935e42013-12-19 08:56:45 -08008826 size_t frameCount = *pFrameCount;
Eric Laurentf14db3c2017-12-08 14:20:36 -08008827 size_t notificationFrameCount = *pNotificationFrameCount;
Andy Hung8d31fd22023-06-26 19:20:57 -07008828 sp<IAfRecordTrack> track;
Eric Laurent81784c32012-11-19 14:55:58 -08008829 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07008830 audio_input_flags_t inputFlags = mInput->flags;
Eric Laurentf14db3c2017-12-08 14:20:36 -08008831 audio_input_flags_t requestedFlags = *flags;
8832 uint32_t sampleRate;
8833
8834 lStatus = initCheck();
8835 if (lStatus != NO_ERROR) {
8836 ALOGE("createRecordTrack_l() audio driver not initialized");
8837 goto Exit;
8838 }
8839
Mikhail Naganovce9f2652018-07-16 11:09:24 -07008840 if (!audio_is_linear_pcm(mFormat) && (*flags & AUDIO_INPUT_FLAG_DIRECT) == 0) {
8841 ALOGE("createRecordTrack_l() on an encoded stream requires AUDIO_INPUT_FLAG_DIRECT");
8842 lStatus = BAD_VALUE;
8843 goto Exit;
8844 }
8845
Eric Laurentec376dc2021-04-08 20:41:22 +02008846 if (maxSharedAudioHistoryMs != 0) {
Eric Laurent9ff3e532022-11-10 16:04:44 +01008847 if (!captureHotwordAllowed(attributionSource)) {
Eric Laurentec376dc2021-04-08 20:41:22 +02008848 lStatus = PERMISSION_DENIED;
8849 goto Exit;
8850 }
Eric Laurentec376dc2021-04-08 20:41:22 +02008851 if (maxSharedAudioHistoryMs < 0
Andy Hung25a80ac2023-07-19 12:47:35 -07008852 || maxSharedAudioHistoryMs > kMaxSharedAudioHistoryMs) {
Eric Laurentec376dc2021-04-08 20:41:22 +02008853 lStatus = BAD_VALUE;
8854 goto Exit;
8855 }
8856 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08008857 if (*pSampleRate == 0) {
8858 *pSampleRate = mSampleRate;
8859 }
8860 sampleRate = *pSampleRate;
Eric Laurent05067782016-06-01 18:27:28 -07008861
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008862 // special case for FAST flag considered OK if fast capture is present and access to
8863 // audio history is not required
8864 if (hasFastCapture() && mMaxSharedAudioHistoryMs == 0) {
Eric Laurent05067782016-06-01 18:27:28 -07008865 inputFlags = (audio_input_flags_t)(inputFlags | AUDIO_INPUT_FLAG_FAST);
8866 }
8867
Eric Laurentf14db3c2017-12-08 14:20:36 -08008868 // Check if requested flags are compatible with input stream flags
Eric Laurent05067782016-06-01 18:27:28 -07008869 if ((*flags & inputFlags) != *flags) {
8870 ALOGW("createRecordTrack_l(): mismatch between requested flags (%08x) and"
8871 " input flags (%08x)",
8872 *flags, inputFlags);
8873 *flags = (audio_input_flags_t)(*flags & inputFlags);
8874 }
Eric Laurent81784c32012-11-19 14:55:58 -08008875
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008876 // client expresses a preference for FAST and no access to audio history,
8877 // but we get the final say
8878 if (*flags & AUDIO_INPUT_FLAG_FAST && maxSharedAudioHistoryMs == 0) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07008879 if (
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07008880 // we formerly checked for a callback handler (non-0 tid),
8881 // but that is no longer required for TRANSFER_OBTAIN mode
jiabinb00edc32021-08-16 16:27:54 +00008882 // No need to match hardware format, format conversion will be done in client side.
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07008883 //
Phil Burk7ed66a12019-04-18 13:20:30 -07008884 // Frame count is not specified (0), or is less than or equal the pipe depth.
8885 // It is OK to provide a higher capacity than requested.
8886 // We will force it to mPipeFramesP2 below.
8887 (frameCount <= mPipeFramesP2) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07008888 // PCM data
8889 audio_is_linear_pcm(format) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08008890 // hardware channel mask
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008891 (channelMask == mChannelMask) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08008892 // hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07008893 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07008894 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008895 hasFastCapture() &&
8896 // there are sufficient fast track slots available
8897 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07008898 ) {
Eric Laurent4c415062016-06-17 16:14:16 -07008899 // check compatibility with audio effects.
Andy Hung972bec12023-08-31 16:13:39 -07008900 audio_utils::lock_guard _l(mutex());
Eric Laurent4c415062016-06-17 16:14:16 -07008901 // Do not accept FAST flag if the session has software effects
Andy Hung116bc262023-06-20 18:56:17 -07008902 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent4c415062016-06-17 16:14:16 -07008903 if (chain != 0) {
Andy Hungd3bb0ad2016-10-11 17:16:43 -07008904 audio_input_flags_t old = *flags;
8905 chain->checkInputFlagCompatibility(flags);
8906 if (old != *flags) {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008907 ALOGV("%p AUDIO_INPUT_FLAGS denied by effect old=%#x new=%#x",
8908 this, (int)old, (int)*flags);
Eric Laurent4c415062016-06-17 16:14:16 -07008909 }
8910 }
Eric Laurent122f7e72016-06-29 11:53:29 -07008911 ALOGV_IF((*flags & AUDIO_INPUT_FLAG_FAST) != 0,
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008912 "%p AUDIO_INPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
8913 this, frameCount, mFrameCount);
Glenn Kasten90e58b12013-07-31 16:16:02 -07008914 } else {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008915 ALOGV("%p AUDIO_INPUT_FLAG_FAST denied: frameCount=%zu mFrameCount=%zu mPipeFramesP2=%zu "
8916 "format=%#x isLinear=%d mFormat=%#x channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008917 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008918 this, frameCount, mFrameCount, mPipeFramesP2,
8919 format, audio_is_linear_pcm(format), mFormat, channelMask, sampleRate, mSampleRate,
Glenn Kasten74105912014-07-03 12:28:53 -07008920 hasFastCapture(), tid, mFastTrackAvail);
Eric Laurent05067782016-06-01 18:27:28 -07008921 *flags = (audio_input_flags_t)(*flags & ~AUDIO_INPUT_FLAG_FAST);
Glenn Kasten74105912014-07-03 12:28:53 -07008922 }
8923 }
8924
Eric Laurentf14db3c2017-12-08 14:20:36 -08008925 // If FAST or RAW flags were corrected, ask caller to request new input from audio policy
8926 if ((*flags & AUDIO_INPUT_FLAG_FAST) !=
8927 (requestedFlags & AUDIO_INPUT_FLAG_FAST)) {
8928 *flags = (audio_input_flags_t) (*flags & ~(AUDIO_INPUT_FLAG_FAST | AUDIO_INPUT_FLAG_RAW));
8929 lStatus = BAD_TYPE;
8930 goto Exit;
8931 }
8932
Glenn Kasten74105912014-07-03 12:28:53 -07008933 // compute track buffer size in frames, and suggest the notification frame count
Eric Laurent05067782016-06-01 18:27:28 -07008934 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten74105912014-07-03 12:28:53 -07008935 // fast track: frame count is exactly the pipe depth
8936 frameCount = mPipeFramesP2;
8937 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
Eric Laurentf14db3c2017-12-08 14:20:36 -08008938 notificationFrameCount = mFrameCount;
Glenn Kasten74105912014-07-03 12:28:53 -07008939 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07008940 // not fast track: max notification period is resampled equivalent of one HAL buffer time
8941 // or 20 ms if there is a fast capture
8942 // TODO This could be a roundupRatio inline, and const
8943 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
8944 * sampleRate + mSampleRate - 1) / mSampleRate;
8945 // minimum number of notification periods is at least kMinNotifications,
8946 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
8947 static const size_t kMinNotifications = 3;
8948 static const uint32_t kMinMs = 30;
8949 // TODO This could be a roundupRatio inline
8950 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
8951 // TODO This could be a roundupRatio inline
8952 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
8953 maxNotificationFrames;
8954 const size_t minFrameCount = maxNotificationFrames *
8955 max(kMinNotifications, minNotificationsByMs);
8956 frameCount = max(frameCount, minFrameCount);
Eric Laurentf14db3c2017-12-08 14:20:36 -08008957 if (notificationFrameCount == 0 || notificationFrameCount > maxNotificationFrames) {
8958 notificationFrameCount = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07008959 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07008960 }
Glenn Kasten74935e42013-12-19 08:56:45 -08008961 *pFrameCount = frameCount;
Eric Laurentf14db3c2017-12-08 14:20:36 -08008962 *pNotificationFrameCount = notificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08008963
Andy Hungc5007f82023-08-29 14:26:09 -07008964 { // scope for mutex()
Andy Hung972bec12023-08-31 16:13:39 -07008965 audio_utils::lock_guard _l(mutex());
Eric Laurent2407ce32021-04-26 14:56:03 +02008966 int32_t startFrames = -1;
Eric Laurentec376dc2021-04-08 20:41:22 +02008967 if (!mSharedAudioPackageName.empty()
Eric Laurent9ff3e532022-11-10 16:04:44 +01008968 && mSharedAudioPackageName == attributionSource.packageName
Eric Laurentec376dc2021-04-08 20:41:22 +02008969 && mSharedAudioSessionId == sessionId
Eric Laurent9ff3e532022-11-10 16:04:44 +01008970 && captureHotwordAllowed(attributionSource)) {
Eric Laurent2407ce32021-04-26 14:56:03 +02008971 startFrames = mSharedAudioStartFrames;
Eric Laurentec376dc2021-04-08 20:41:22 +02008972 }
Eric Laurent81784c32012-11-19 14:55:58 -08008973
Andy Hung8d31fd22023-06-26 19:20:57 -07008974 track = IAfRecordTrack::create(this, client, attr, sampleRate,
Andy Hung8fe68032017-06-05 16:17:51 -07008975 format, channelMask, frameCount,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07008976 nullptr /* buffer */, (size_t)0 /* bufferSize */, sessionId, creatorPid,
Andy Hung8d31fd22023-06-26 19:20:57 -07008977 attributionSource, *flags, IAfTrackBase::TYPE_DEFAULT, portId,
Svet Ganov33761132021-05-13 22:51:08 +00008978 startFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08008979
Glenn Kasten03003332013-08-06 15:40:54 -07008980 lStatus = track->initCheck();
8981 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07008982 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08008983 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08008984 goto Exit;
8985 }
8986 mTracks.add(track);
8987
Eric Laurent05067782016-06-01 18:27:28 -07008988 if ((*flags & AUDIO_INPUT_FLAG_FAST) && (tid != -1)) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07008989 pid_t callingPid = IPCThreadState::self()->getCallingPid();
8990 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
8991 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07008992 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Glenn Kasten90e58b12013-07-31 16:16:02 -07008993 }
Eric Laurentec376dc2021-04-08 20:41:22 +02008994
8995 if (maxSharedAudioHistoryMs != 0) {
8996 sendResizeBufferConfigEvent_l(maxSharedAudioHistoryMs);
8997 }
Eric Laurent81784c32012-11-19 14:55:58 -08008998 }
Glenn Kasten05997e22014-03-13 15:08:33 -07008999
Eric Laurent81784c32012-11-19 14:55:58 -08009000 lStatus = NO_ERROR;
9001
9002Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07009003 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08009004 return track;
9005}
9006
Andy Hungee58e4a2023-07-07 13:47:37 -07009007status_t RecordThread::start(IAfRecordTrack* recordTrack,
Eric Laurent81784c32012-11-19 14:55:58 -08009008 AudioSystem::sync_event_t event,
Glenn Kastend848eb42016-03-08 13:42:11 -08009009 audio_session_t triggerSession)
Eric Laurent81784c32012-11-19 14:55:58 -08009010{
9011 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
9012 sp<ThreadBase> strongMe = this;
9013 status_t status = NO_ERROR;
9014
9015 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08009016 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08009017 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Andy Hung8d31fd22023-06-26 19:20:57 -07009018 recordTrack->synchronizedRecordState().startRecording(
Andy Hung583043b2023-07-17 17:05:00 -07009019 mAfThreadCallback->createSyncEvent(
Andy Hung93bb5732023-05-04 21:16:34 -07009020 event, triggerSession,
9021 recordTrack->sessionId(), syncStartEventCallback, recordTrack));
Eric Laurent81784c32012-11-19 14:55:58 -08009022 }
9023
9024 {
Glenn Kasten47c20702013-08-13 15:37:35 -07009025 // This section is a rendezvous between binder thread executing start() and RecordThread
Andy Hung972bec12023-08-31 16:13:39 -07009026 audio_utils::lock_guard lock(mutex());
Andy Hungce685402018-10-05 17:23:27 -07009027 if (recordTrack->isInvalid()) {
9028 recordTrack->clearSyncStartEvent();
Eric Laurentd52a28c2020-08-21 17:10:39 -07009029 ALOGW("%s track %d: invalidated before startInput", __func__, recordTrack->portId());
9030 return DEAD_OBJECT;
Andy Hungce685402018-10-05 17:23:27 -07009031 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009032 if (mActiveTracks.indexOf(recordTrack) >= 0) {
Andy Hung8d31fd22023-06-26 19:20:57 -07009033 if (recordTrack->state() == IAfTrackBase::PAUSING) {
Andy Hungce685402018-10-05 17:23:27 -07009034 // We haven't stopped yet (moved to PAUSED and not in mActiveTracks)
9035 // so no need to startInput().
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009036 ALOGV("active record track PAUSING -> ACTIVE");
Andy Hung8d31fd22023-06-26 19:20:57 -07009037 recordTrack->setState(IAfTrackBase::ACTIVE);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009038 } else {
Andy Hung8d31fd22023-06-26 19:20:57 -07009039 ALOGV("active record track state %d", (int)recordTrack->state());
Eric Laurent81784c32012-11-19 14:55:58 -08009040 }
9041 return status;
9042 }
9043
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08009044 // TODO consider other ways of handling this, such as changing the state to :STARTING and
9045 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
9046 // or using a separate command thread
Andy Hung8d31fd22023-06-26 19:20:57 -07009047 recordTrack->setState(IAfTrackBase::STARTING_1);
Glenn Kasten2b806402013-11-20 16:37:38 -08009048 mActiveTracks.add(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07009049 if (recordTrack->isExternalTrack()) {
Andy Hungc5007f82023-08-29 14:26:09 -07009050 mutex().unlock();
Eric Laurent4eb58f12018-12-07 16:41:02 -08009051 status = AudioSystem::startInput(recordTrack->portId());
Andy Hungc5007f82023-08-29 14:26:09 -07009052 mutex().lock();
Andy Hungce685402018-10-05 17:23:27 -07009053 if (recordTrack->isInvalid()) {
9054 recordTrack->clearSyncStartEvent();
Andy Hung8d31fd22023-06-26 19:20:57 -07009055 if (status == NO_ERROR && recordTrack->state() == IAfTrackBase::STARTING_1) {
9056 recordTrack->setState(IAfTrackBase::STARTING_2);
Andy Hungce685402018-10-05 17:23:27 -07009057 // STARTING_2 forces destroy to call stopInput.
9058 }
Eric Laurentd52a28c2020-08-21 17:10:39 -07009059 ALOGW("%s track %d: invalidated after startInput", __func__, recordTrack->portId());
9060 return DEAD_OBJECT;
Andy Hungce685402018-10-05 17:23:27 -07009061 }
Andy Hung8d31fd22023-06-26 19:20:57 -07009062 if (recordTrack->state() != IAfTrackBase::STARTING_1) {
Andy Hungce685402018-10-05 17:23:27 -07009063 ALOGW("%s(%d): unsynchronized mState:%d change",
Andy Hung8d31fd22023-06-26 19:20:57 -07009064 __func__, recordTrack->id(), (int)recordTrack->state());
Andy Hungce685402018-10-05 17:23:27 -07009065 // Someone else has changed state, let them take over,
9066 // leave mState in the new state.
9067 recordTrack->clearSyncStartEvent();
9068 return INVALID_OPERATION;
9069 }
9070 // we're ok, but perhaps startInput has failed
Eric Laurent83b88082014-06-20 18:31:16 -07009071 if (status != NO_ERROR) {
Andy Hungce685402018-10-05 17:23:27 -07009072 ALOGW("%s(%d): startInput failed, status %d",
9073 __func__, recordTrack->id(), status);
9074 // We are in ActiveTracks if STARTING_1 and valid, so remove from ActiveTracks,
9075 // leave in STARTING_1, so destroy() will not call stopInput.
Eric Laurent83b88082014-06-20 18:31:16 -07009076 mActiveTracks.remove(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07009077 recordTrack->clearSyncStartEvent();
Eric Laurent83b88082014-06-20 18:31:16 -07009078 return status;
9079 }
Eric Laurent09f1ed22019-04-24 17:45:17 -07009080 sendIoConfigEvent_l(
9081 AUDIO_CLIENT_STARTED, recordTrack->creatorPid(), recordTrack->portId());
Eric Laurent81784c32012-11-19 14:55:58 -08009082 }
Andy Hungc2b11cb2020-04-22 09:04:01 -07009083
9084 recordTrack->logBeginInterval(patchSourcesToString(&mPatch)); // log to MediaMetrics
9085
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009086 // Catch up with current buffer indices if thread is already running.
9087 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
9088 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
9089 // see previously buffered data before it called start(), but with greater risk of overrun.
9090
Andy Hung8d31fd22023-06-26 19:20:57 -07009091 recordTrack->resamplerBufferProvider()->reset();
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07009092 if (!recordTrack->isDirect()) {
9093 // clear any converter state as new data will be discontinuous
Andy Hung8d31fd22023-06-26 19:20:57 -07009094 recordTrack->recordBufferConverter()->reset();
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07009095 }
Andy Hung8d31fd22023-06-26 19:20:57 -07009096 recordTrack->setState(IAfTrackBase::STARTING_2);
Eric Laurent81784c32012-11-19 14:55:58 -08009097 // signal thread to start
Andy Hungc5007f82023-08-29 14:26:09 -07009098 mWaitWorkCV.notify_all();
Eric Laurent81784c32012-11-19 14:55:58 -08009099 return status;
9100 }
Eric Laurent81784c32012-11-19 14:55:58 -08009101}
9102
Andy Hungee58e4a2023-07-07 13:47:37 -07009103void RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
Eric Laurent81784c32012-11-19 14:55:58 -08009104{
Andy Hungee58e4a2023-07-07 13:47:37 -07009105 const sp<SyncEvent> strongEvent = event.promote();
Eric Laurent81784c32012-11-19 14:55:58 -08009106
9107 if (strongEvent != 0) {
Andy Hungd29af632023-06-23 19:27:19 -07009108 sp<IAfTrackBase> ptr =
9109 std::any_cast<const wp<IAfTrackBase>>(strongEvent->cookie()).promote();
9110 if (ptr != nullptr) {
Andy Hung99b1ba62023-07-14 11:00:08 -07009111 // TODO(b/291317898) handleSyncStartEvent is in IAfTrackBase not IAfRecordTrack.
Andy Hungd29af632023-06-23 19:27:19 -07009112 ptr->handleSyncStartEvent(strongEvent);
Eric Laurent8ea16e42014-02-20 16:26:11 -08009113 }
Eric Laurent81784c32012-11-19 14:55:58 -08009114 }
9115}
9116
Andy Hungee58e4a2023-07-07 13:47:37 -07009117bool RecordThread::stop(IAfRecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08009118 ALOGV("RecordThread::stop");
Andy Hungc5007f82023-08-29 14:26:09 -07009119 audio_utils::unique_lock _l(mutex());
Andy Hungce685402018-10-05 17:23:27 -07009120 // if we're invalid, we can't be on the ActiveTracks.
Andy Hung8d31fd22023-06-26 19:20:57 -07009121 if (mActiveTracks.indexOf(recordTrack) < 0 || recordTrack->state() == IAfTrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08009122 return false;
9123 }
Glenn Kasten47c20702013-08-13 15:37:35 -07009124 // note that threadLoop may still be processing the track at this point [without lock]
Andy Hung8d31fd22023-06-26 19:20:57 -07009125 recordTrack->setState(IAfTrackBase::PAUSING);
Andy Hungce685402018-10-05 17:23:27 -07009126
Andy Hungabfab202019-03-07 19:45:54 -08009127 // NOTE: Waiting here is important to keep stop synchronous.
9128 // This is needed for proper patchRecord peer release.
Andy Hung8d31fd22023-06-26 19:20:57 -07009129 while (recordTrack->state() == IAfTrackBase::PAUSING && !recordTrack->isInvalid()) {
Andy Hungc5007f82023-08-29 14:26:09 -07009130 mWaitWorkCV.notify_all(); // signal thread to stop
9131 mStartStopCV.wait(_l);
Eric Laurent81784c32012-11-19 14:55:58 -08009132 }
Andy Hungce685402018-10-05 17:23:27 -07009133
Andy Hung8d31fd22023-06-26 19:20:57 -07009134 if (recordTrack->state() == IAfTrackBase::PAUSED) { // successful stop
Eric Laurent81784c32012-11-19 14:55:58 -08009135 ALOGV("Record stopped OK");
9136 return true;
9137 }
Andy Hungce685402018-10-05 17:23:27 -07009138
9139 // don't handle anything - we've been invalidated or restarted and in a different state
9140 ALOGW_IF("%s(%d): unsynchronized stop, state: %d",
Andy Hung8d31fd22023-06-26 19:20:57 -07009141 __func__, recordTrack->id(), recordTrack->state());
Eric Laurent81784c32012-11-19 14:55:58 -08009142 return false;
9143}
9144
Andy Hungee58e4a2023-07-07 13:47:37 -07009145bool RecordThread::isValidSyncEvent(const sp<SyncEvent>& /* event */) const
Eric Laurent81784c32012-11-19 14:55:58 -08009146{
9147 return false;
9148}
9149
Andy Hungee58e4a2023-07-07 13:47:37 -07009150status_t RecordThread::setSyncEvent(const sp<SyncEvent>& /* event */)
Eric Laurent81784c32012-11-19 14:55:58 -08009151{
9152#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
9153 if (!isValidSyncEvent(event)) {
9154 return BAD_VALUE;
9155 }
9156
Glenn Kastend848eb42016-03-08 13:42:11 -08009157 audio_session_t eventSession = event->triggerSession();
Eric Laurent81784c32012-11-19 14:55:58 -08009158 status_t ret = NAME_NOT_FOUND;
9159
Andy Hung972bec12023-08-31 16:13:39 -07009160 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08009161
9162 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07009163 sp<IAfRecordTrack> track = mTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08009164 if (eventSession == track->sessionId()) {
9165 (void) track->setSyncEvent(event);
9166 ret = NO_ERROR;
9167 }
9168 }
9169 return ret;
9170#else
9171 return BAD_VALUE;
9172#endif
9173}
9174
Andy Hungee58e4a2023-07-07 13:47:37 -07009175status_t RecordThread::getActiveMicrophones(
Andy Hung87c693c2023-07-06 20:56:16 -07009176 std::vector<media::MicrophoneInfoFw>* activeMicrophones) const
jiabin653cc0a2018-01-17 17:54:10 -08009177{
9178 ALOGV("RecordThread::getActiveMicrophones");
Andy Hung972bec12023-08-31 16:13:39 -07009179 audio_utils::lock_guard _l(mutex());
Jasmine Chaeaa10e42021-05-11 10:11:14 +08009180 if (!isStreamInitialized()) {
Paul McLean8a661a32021-04-12 10:21:42 -06009181 return NO_INIT;
9182 }
jiabin9ff780e2018-03-19 18:19:52 -07009183 status_t status = mInput->stream->getActiveMicrophones(activeMicrophones);
9184 return status;
jiabin653cc0a2018-01-17 17:54:10 -08009185}
9186
Andy Hungee58e4a2023-07-07 13:47:37 -07009187status_t RecordThread::setPreferredMicrophoneDirection(
Paul McLean12340082019-03-19 09:35:05 -06009188 audio_microphone_direction_t direction)
Paul McLean03a6e6a2018-12-04 10:54:13 -07009189{
Paul McLean12340082019-03-19 09:35:05 -06009190 ALOGV("setPreferredMicrophoneDirection(%d)", direction);
Andy Hung972bec12023-08-31 16:13:39 -07009191 audio_utils::lock_guard _l(mutex());
Jasmine Chaeaa10e42021-05-11 10:11:14 +08009192 if (!isStreamInitialized()) {
Paul McLean8a661a32021-04-12 10:21:42 -06009193 return NO_INIT;
9194 }
Paul McLean12340082019-03-19 09:35:05 -06009195 return mInput->stream->setPreferredMicrophoneDirection(direction);
Paul McLean03a6e6a2018-12-04 10:54:13 -07009196}
9197
Andy Hungee58e4a2023-07-07 13:47:37 -07009198status_t RecordThread::setPreferredMicrophoneFieldDimension(float zoom)
Paul McLean03a6e6a2018-12-04 10:54:13 -07009199{
Paul McLean12340082019-03-19 09:35:05 -06009200 ALOGV("setPreferredMicrophoneFieldDimension(%f)", zoom);
Andy Hung972bec12023-08-31 16:13:39 -07009201 audio_utils::lock_guard _l(mutex());
Jasmine Chaeaa10e42021-05-11 10:11:14 +08009202 if (!isStreamInitialized()) {
Paul McLean8a661a32021-04-12 10:21:42 -06009203 return NO_INIT;
9204 }
Paul McLean12340082019-03-19 09:35:05 -06009205 return mInput->stream->setPreferredMicrophoneFieldDimension(zoom);
Paul McLean03a6e6a2018-12-04 10:54:13 -07009206}
9207
Andy Hungee58e4a2023-07-07 13:47:37 -07009208status_t RecordThread::shareAudioHistory(
Eric Laurentec376dc2021-04-08 20:41:22 +02009209 const std::string& sharedAudioPackageName, audio_session_t sharedSessionId,
9210 int64_t sharedAudioStartMs) {
Andy Hung972bec12023-08-31 16:13:39 -07009211 audio_utils::lock_guard _l(mutex());
Eric Laurentec376dc2021-04-08 20:41:22 +02009212 return shareAudioHistory_l(sharedAudioPackageName, sharedSessionId, sharedAudioStartMs);
9213}
9214
Andy Hungee58e4a2023-07-07 13:47:37 -07009215status_t RecordThread::shareAudioHistory_l(
Eric Laurentec376dc2021-04-08 20:41:22 +02009216 const std::string& sharedAudioPackageName, audio_session_t sharedSessionId,
9217 int64_t sharedAudioStartMs) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009218
Eric Laurentec376dc2021-04-08 20:41:22 +02009219 if ((hasAudioSession_l(sharedSessionId) & ThreadBase::TRACK_SESSION) == 0) {
9220 return BAD_VALUE;
9221 }
Eric Laurent2407ce32021-04-26 14:56:03 +02009222
9223 if (sharedAudioStartMs < 0
9224 || sharedAudioStartMs > INT64_MAX / mSampleRate) {
Eric Laurentec376dc2021-04-08 20:41:22 +02009225 return BAD_VALUE;
9226 }
9227
Eric Laurent2407ce32021-04-26 14:56:03 +02009228 // Current implementation of the input resampling buffer wraps around indexes at 32 bit.
9229 // As we cannot detect more than one wraparound, only accept values up current write position
9230 // after one wraparound
9231 // We assume recent wraparounds on mRsmpInRear only given it is unlikely that the requesting
9232 // app waits several hours after the start time was computed.
Eric Laurent92d0a322021-07-16 15:32:33 +02009233 int64_t sharedAudioStartFrames = sharedAudioStartMs * mSampleRate / 1000;
Eric Laurent2407ce32021-04-26 14:56:03 +02009234 const int32_t sharedOffset = audio_utils::safe_sub_overflow(mRsmpInRear,
9235 (int32_t)sharedAudioStartFrames);
Eric Laurent92d0a322021-07-16 15:32:33 +02009236 // Bring the start frame position within the input buffer to match the documented
9237 // "best effort" behavior of the API.
9238 if (sharedOffset < 0) {
9239 sharedAudioStartFrames = mRsmpInRear;
Andy Hung920f6572022-10-06 12:09:49 -07009240 } else if (sharedOffset > static_cast<signed>(mRsmpInFrames)) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009241 sharedAudioStartFrames =
9242 audio_utils::safe_sub_overflow(mRsmpInRear, (int32_t)mRsmpInFrames);
Eric Laurent2407ce32021-04-26 14:56:03 +02009243 }
9244
Eric Laurentec376dc2021-04-08 20:41:22 +02009245 mSharedAudioPackageName = sharedAudioPackageName;
9246 if (mSharedAudioPackageName.empty()) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009247 resetAudioHistory_l();
Eric Laurentec376dc2021-04-08 20:41:22 +02009248 } else {
9249 mSharedAudioSessionId = sharedSessionId;
Eric Laurent2407ce32021-04-26 14:56:03 +02009250 mSharedAudioStartFrames = (int32_t)sharedAudioStartFrames;
Eric Laurentec376dc2021-04-08 20:41:22 +02009251 }
9252 return NO_ERROR;
9253}
9254
Andy Hungee58e4a2023-07-07 13:47:37 -07009255void RecordThread::resetAudioHistory_l() {
Eric Laurent92d0a322021-07-16 15:32:33 +02009256 mSharedAudioSessionId = AUDIO_SESSION_NONE;
9257 mSharedAudioStartFrames = -1;
9258 mSharedAudioPackageName = "";
9259}
9260
Andy Hungee58e4a2023-07-07 13:47:37 -07009261ThreadBase::MetadataUpdate RecordThread::updateMetadata_l()
Kevin Rocard069c2712018-03-29 19:09:14 -07009262{
Jasmine Chaeaa10e42021-05-11 10:11:14 +08009263 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
Vlad Popa7e81cea2023-01-19 16:34:16 +01009264 return {}; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -07009265 }
9266 StreamInHalInterface::SinkMetadata metadata;
Eric Laurent78b07302022-10-07 16:20:34 +02009267 auto backInserter = std::back_inserter(metadata.tracks);
Andy Hung8d31fd22023-06-26 19:20:57 -07009268 for (const sp<IAfRecordTrack>& track : mActiveTracks) {
Eric Laurent78b07302022-10-07 16:20:34 +02009269 track->copyMetadataTo(backInserter);
Kevin Rocard069c2712018-03-29 19:09:14 -07009270 }
9271 mInput->stream->updateSinkMetadata(metadata);
Vlad Popa7e81cea2023-01-19 16:34:16 +01009272 MetadataUpdate change;
9273 change.recordMetadataUpdate = metadata.tracks;
9274 return change;
Kevin Rocard069c2712018-03-29 19:09:14 -07009275}
9276
Andy Hungc5007f82023-08-29 14:26:09 -07009277// destroyTrack_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07009278void RecordThread::destroyTrack_l(const sp<IAfRecordTrack>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08009279{
Eric Laurentbfb1b832013-01-07 09:53:42 -08009280 track->terminate();
Andy Hung8d31fd22023-06-26 19:20:57 -07009281 track->setState(IAfTrackBase::STOPPED);
Eric Laurentec376dc2021-04-08 20:41:22 +02009282
Eric Laurent81784c32012-11-19 14:55:58 -08009283 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08009284 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08009285 removeTrack_l(track);
9286 }
9287}
9288
Andy Hungee58e4a2023-07-07 13:47:37 -07009289void RecordThread::removeTrack_l(const sp<IAfRecordTrack>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08009290{
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009291 String8 result;
9292 track->appendDump(result, false /* active */);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00009293 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.c_str());
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009294
Eric Laurent81784c32012-11-19 14:55:58 -08009295 mTracks.remove(track);
9296 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07009297 if (track->isFastTrack()) {
9298 ALOG_ASSERT(!mFastTrackAvail);
9299 mFastTrackAvail = true;
9300 }
Eric Laurent81784c32012-11-19 14:55:58 -08009301}
9302
Andy Hungee58e4a2023-07-07 13:47:37 -07009303void RecordThread::dumpInternals_l(int fd, const Vector<String16>& /* args */)
Eric Laurent81784c32012-11-19 14:55:58 -08009304{
Mikhail Naganov913d06c2016-11-01 12:49:22 -07009305 AudioStreamIn *input = mInput;
9306 audio_input_flags_t flags = input != NULL ? input->flags : AUDIO_INPUT_FLAG_NONE;
9307 dprintf(fd, " AudioStreamIn: %p flags %#x (%s)\n",
Andy Hung9b181952019-02-25 14:53:36 -08009308 input, flags, toString(flags).c_str());
Andy Hung6427e442018-08-09 12:51:02 -07009309 dprintf(fd, " Frames read: %lld\n", (long long)mFramesRead);
Eric Tan39ec8d62018-07-24 09:49:29 -07009310 if (mActiveTracks.isEmpty()) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07009311 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08009312 }
Andy Hungbfa64962017-06-12 14:43:19 -07009313
9314 if (input != nullptr) {
9315 dprintf(fd, " Hal stream dump:\n");
9316 (void)input->stream->dump(fd);
9317 }
9318
Glenn Kasten6e6704c2014-07-03 10:20:00 -07009319 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07009320 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Glenn Kasten17c9c992015-03-02 15:53:01 -08009321
Glenn Kasten2f90c512015-12-02 11:40:09 -08009322 // Make a non-atomic copy of fast capture dump state so it won't change underneath us
9323 // while we are dumping it. It may be inconsistent, but it won't mutate!
9324 // This is a large object so we place it on the heap.
9325 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
Eric Tan2942a4e2018-09-12 17:41:27 -07009326 const std::unique_ptr<FastCaptureDumpState> copy =
9327 std::make_unique<FastCaptureDumpState>(mFastCaptureDumpState);
Glenn Kasten2f90c512015-12-02 11:40:09 -08009328 copy->dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08009329}
9330
Andy Hungee58e4a2023-07-07 13:47:37 -07009331void RecordThread::dumpTracks_l(int fd, const Vector<String16>& /* args */)
Eric Laurent81784c32012-11-19 14:55:58 -08009332{
Eric Laurent81784c32012-11-19 14:55:58 -08009333 String8 result;
Marco Nelissenb2208842014-02-07 14:00:50 -08009334 size_t numtracks = mTracks.size();
9335 size_t numactive = mActiveTracks.size();
9336 size_t numactiveseen = 0;
Glenn Kastenc42e9b42016-03-21 11:35:03 -07009337 dprintf(fd, " %zu Tracks", numtracks);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009338 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08009339 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07009340 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009341 result.append(prefix);
Andy Hung000adb52018-06-01 15:43:26 -07009342 mTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08009343 for (size_t i = 0; i < numtracks ; ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07009344 sp<IAfRecordTrack> track = mTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08009345 if (track != 0) {
9346 bool active = mActiveTracks.indexOf(track) >= 0;
9347 if (active) {
9348 numactiveseen++;
9349 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009350 result.append(prefix);
9351 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08009352 }
Eric Laurent81784c32012-11-19 14:55:58 -08009353 }
Marco Nelissenb2208842014-02-07 14:00:50 -08009354 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07009355 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08009356 }
9357
Marco Nelissenb2208842014-02-07 14:00:50 -08009358 if (numactiveseen != numactive) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009359 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08009360 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009361 result.append(prefix);
Andy Hung000adb52018-06-01 15:43:26 -07009362 mActiveTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08009363 for (size_t i = 0; i < numactive; ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07009364 sp<IAfRecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08009365 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009366 result.append(prefix);
9367 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08009368 }
Glenn Kasten2b806402013-11-20 16:37:38 -08009369 }
Eric Laurent81784c32012-11-19 14:55:58 -08009370
9371 }
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00009372 write(fd, result.c_str(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08009373}
9374
Andy Hungee58e4a2023-07-07 13:47:37 -07009375void RecordThread::setRecordSilenced(audio_port_handle_t portId, bool silenced)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08009376{
Andy Hung972bec12023-08-31 16:13:39 -07009377 audio_utils::lock_guard _l(mutex());
Svet Ganovf4ddfef2018-01-16 07:37:58 -08009378 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07009379 sp<IAfRecordTrack> track = mTracks[i];
Eric Laurent5ada82e2019-08-29 17:53:54 -07009380 if (track != 0 && track->portId() == portId) {
Svet Ganovf4ddfef2018-01-16 07:37:58 -08009381 track->setSilenced(silenced);
9382 }
9383 }
9384}
Andy Hung73c02e42015-03-29 01:13:58 -07009385
Andy Hung8d31fd22023-06-26 19:20:57 -07009386void ResamplerBufferProvider::reset()
Andy Hung73c02e42015-03-29 01:13:58 -07009387{
Andy Hung87c693c2023-07-06 20:56:16 -07009388 const auto threadBase = mRecordTrack->thread().promote();
Andy Hungee58e4a2023-07-07 13:47:37 -07009389 auto* const recordThread = static_cast<RecordThread *>(threadBase->asIAfRecordThread().get());
Andy Hung73c02e42015-03-29 01:13:58 -07009390 mRsmpInUnrel = 0;
Eric Laurentec376dc2021-04-08 20:41:22 +02009391 const int32_t rear = recordThread->mRsmpInRear;
9392 ssize_t deltaFrames = 0;
Eric Laurent2407ce32021-04-26 14:56:03 +02009393 if (mRecordTrack->startFrames() >= 0) {
9394 int32_t startFrames = mRecordTrack->startFrames();
9395 // Accept a recent wraparound of mRsmpInRear
9396 if (startFrames <= rear) {
9397 deltaFrames = rear - startFrames;
9398 } else {
9399 deltaFrames = (int32_t)((int64_t)rear + UINT32_MAX + 1 - startFrames);
Eric Laurentec376dc2021-04-08 20:41:22 +02009400 }
Eric Laurentec376dc2021-04-08 20:41:22 +02009401 // start frame cannot be further in the past than start of resampling buffer
9402 if ((size_t) deltaFrames > recordThread->mRsmpInFrames) {
9403 deltaFrames = recordThread->mRsmpInFrames;
9404 }
9405 }
9406 mRsmpInFront = audio_utils::safe_sub_overflow(rear, static_cast<int32_t>(deltaFrames));
Andy Hung73c02e42015-03-29 01:13:58 -07009407}
9408
Andy Hung8d31fd22023-06-26 19:20:57 -07009409void ResamplerBufferProvider::sync(
Andy Hung73c02e42015-03-29 01:13:58 -07009410 size_t *framesAvailable, bool *hasOverrun)
9411{
Andy Hung87c693c2023-07-06 20:56:16 -07009412 const auto threadBase = mRecordTrack->thread().promote();
Andy Hungee58e4a2023-07-07 13:47:37 -07009413 auto* const recordThread = static_cast<RecordThread *>(threadBase->asIAfRecordThread().get());
Andy Hung73c02e42015-03-29 01:13:58 -07009414 const int32_t rear = recordThread->mRsmpInRear;
9415 const int32_t front = mRsmpInFront;
Hongwei Wang95e37682019-04-12 11:13:36 -07009416 const ssize_t filled = audio_utils::safe_sub_overflow(rear, front);
Andy Hung73c02e42015-03-29 01:13:58 -07009417
9418 size_t framesIn;
9419 bool overrun = false;
9420 if (filled < 0) {
9421 // should not happen, but treat like a massive overrun and re-sync
9422 framesIn = 0;
9423 mRsmpInFront = rear;
9424 overrun = true;
9425 } else if ((size_t) filled <= recordThread->mRsmpInFrames) {
9426 framesIn = (size_t) filled;
9427 } else {
9428 // client is not keeping up with server, but give it latest data
9429 framesIn = recordThread->mRsmpInFrames;
Hongwei Wang95e37682019-04-12 11:13:36 -07009430 mRsmpInFront = /* front = */ audio_utils::safe_sub_overflow(
9431 rear, static_cast<int32_t>(framesIn));
Andy Hung73c02e42015-03-29 01:13:58 -07009432 overrun = true;
9433 }
9434 if (framesAvailable != NULL) {
9435 *framesAvailable = framesIn;
9436 }
9437 if (hasOverrun != NULL) {
9438 *hasOverrun = overrun;
9439 }
9440}
9441
Eric Laurent81784c32012-11-19 14:55:58 -08009442// AudioBufferProvider interface
Andy Hung8d31fd22023-06-26 19:20:57 -07009443status_t ResamplerBufferProvider::getNextBuffer(
Glenn Kastend79072e2016-01-06 08:41:20 -08009444 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08009445{
Andy Hung87c693c2023-07-06 20:56:16 -07009446 const auto threadBase = mRecordTrack->thread().promote();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009447 if (threadBase == 0) {
9448 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08009449 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009450 return NOT_ENOUGH_DATA;
9451 }
Andy Hungee58e4a2023-07-07 13:47:37 -07009452 auto* const recordThread = static_cast<RecordThread *>(threadBase->asIAfRecordThread().get());
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009453 int32_t rear = recordThread->mRsmpInRear;
Andy Hung73c02e42015-03-29 01:13:58 -07009454 int32_t front = mRsmpInFront;
Hongwei Wang95e37682019-04-12 11:13:36 -07009455 ssize_t filled = audio_utils::safe_sub_overflow(rear, front);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009456 // FIXME should not be P2 (don't want to increase latency)
9457 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08009458 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07009459 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009460
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009461 front &= recordThread->mRsmpInFramesP2 - 1;
9462 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07009463 if (part1 > (size_t) filled) {
9464 part1 = filled;
9465 }
9466 size_t ask = buffer->frameCount;
9467 ALOG_ASSERT(ask > 0);
9468 if (part1 > ask) {
9469 part1 = ask;
9470 }
9471 if (part1 == 0) {
Andy Hung73c02e42015-03-29 01:13:58 -07009472 // out of data is fine since the resampler will return a short-count.
Glenn Kasten85948432013-08-19 12:09:05 -07009473 buffer->raw = NULL;
9474 buffer->frameCount = 0;
Andy Hung73c02e42015-03-29 01:13:58 -07009475 mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07009476 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08009477 }
9478
Andy Hung57446612015-04-19 23:56:46 -07009479 buffer->raw = (uint8_t*)recordThread->mRsmpInBuffer + front * recordThread->mFrameSize;
Glenn Kasten85948432013-08-19 12:09:05 -07009480 buffer->frameCount = part1;
Andy Hung73c02e42015-03-29 01:13:58 -07009481 mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08009482 return NO_ERROR;
9483}
9484
9485// AudioBufferProvider interface
Andy Hung8d31fd22023-06-26 19:20:57 -07009486void ResamplerBufferProvider::releaseBuffer(
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009487 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08009488{
Hongwei Wang95e37682019-04-12 11:13:36 -07009489 int32_t stepCount = static_cast<int32_t>(buffer->frameCount);
Glenn Kasten85948432013-08-19 12:09:05 -07009490 if (stepCount == 0) {
9491 return;
9492 }
Eric Laurent1e28aaa2023-04-16 19:34:23 +02009493 ALOG_ASSERT(stepCount <= (int32_t)mRsmpInUnrel);
Andy Hung73c02e42015-03-29 01:13:58 -07009494 mRsmpInUnrel -= stepCount;
Hongwei Wang95e37682019-04-12 11:13:36 -07009495 mRsmpInFront = audio_utils::safe_add_overflow(mRsmpInFront, stepCount);
Glenn Kasten85948432013-08-19 12:09:05 -07009496 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08009497 buffer->frameCount = 0;
9498}
9499
Andy Hungee58e4a2023-07-07 13:47:37 -07009500void RecordThread::checkBtNrec()
Eric Laurentd8365c52017-07-16 15:27:05 -07009501{
Andy Hung972bec12023-08-31 16:13:39 -07009502 audio_utils::lock_guard _l(mutex());
Eric Laurentd8365c52017-07-16 15:27:05 -07009503 checkBtNrec_l();
9504}
9505
Andy Hungee58e4a2023-07-07 13:47:37 -07009506void RecordThread::checkBtNrec_l()
Eric Laurentd8365c52017-07-16 15:27:05 -07009507{
9508 // disable AEC and NS if the device is a BT SCO headset supporting those
9509 // pre processings
Andy Hungab65b182023-09-06 19:41:47 -07009510 bool suspend = audio_is_bluetooth_sco_device(inDeviceType_l()) &&
Andy Hung583043b2023-07-17 17:05:00 -07009511 mAfThreadCallback->btNrecIsOff();
Eric Laurentd8365c52017-07-16 15:27:05 -07009512 if (mBtNrecSuspended.exchange(suspend) != suspend) {
9513 for (size_t i = 0; i < mEffectChains.size(); i++) {
9514 setEffectSuspended_l(FX_IID_AEC, suspend, mEffectChains[i]->sessionId());
9515 setEffectSuspended_l(FX_IID_NS, suspend, mEffectChains[i]->sessionId());
9516 }
9517 }
9518}
9519
Andy Hung97a893e2015-03-29 01:03:07 -07009520
Andy Hungee58e4a2023-07-07 13:47:37 -07009521bool RecordThread::checkForNewParameter_l(const String8& keyValuePair,
Eric Laurent10351942014-05-08 18:49:52 -07009522 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08009523{
9524 bool reconfig = false;
9525
Eric Laurent10351942014-05-08 18:49:52 -07009526 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08009527
Eric Laurent10351942014-05-08 18:49:52 -07009528 audio_format_t reqFormat = mFormat;
9529 uint32_t samplingRate = mSampleRate;
Glenn Kastene1635ec2015-06-08 15:46:49 -07009530 // 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 +08009531 [[maybe_unused]] audio_channel_mask_t channelMask =
9532 audio_channel_in_mask_from_count(mChannelCount);
Eric Laurent10351942014-05-08 18:49:52 -07009533
9534 AudioParameter param = AudioParameter(keyValuePair);
9535 int value;
Haynes Mathew George9ce67b52015-09-30 11:40:47 -07009536
9537 // scope for AutoPark extends to end of method
9538 AutoPark<FastCapture> park(mFastCapture);
9539
Eric Laurent10351942014-05-08 18:49:52 -07009540 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
9541 // channel count change can be requested. Do we mandate the first client defines the
9542 // HAL sampling rate and channel count or do we allow changes on the fly?
9543 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
9544 samplingRate = value;
9545 reconfig = true;
9546 }
9547 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung97a893e2015-03-29 01:03:07 -07009548 if (!audio_is_linear_pcm((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07009549 status = BAD_VALUE;
9550 } else {
9551 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08009552 reconfig = true;
9553 }
Eric Laurent10351942014-05-08 18:49:52 -07009554 }
9555 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
9556 audio_channel_mask_t mask = (audio_channel_mask_t) value;
Andy Hungd330ee42015-04-20 13:23:41 -07009557 if (!audio_is_input_channel(mask) ||
Andy Hung936845a2021-06-08 00:09:06 -07009558 audio_channel_count_from_in_mask(mask) > FCC_LIMIT) {
Eric Laurent10351942014-05-08 18:49:52 -07009559 status = BAD_VALUE;
9560 } else {
9561 channelMask = mask;
9562 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08009563 }
Eric Laurent10351942014-05-08 18:49:52 -07009564 }
9565 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
9566 // do not accept frame count changes if tracks are open as the track buffer
9567 // size depends on frame count and correct behavior would not be guaranteed
9568 // if frame count is changed after track creation
9569 if (mActiveTracks.size() > 0) {
9570 status = INVALID_OPERATION;
9571 } else {
9572 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08009573 }
Eric Laurent10351942014-05-08 18:49:52 -07009574 }
9575 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07009576 LOG_FATAL("Should not set routing device in RecordThread");
Eric Laurent10351942014-05-08 18:49:52 -07009577 }
9578 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
9579 mAudioSource != (audio_source_t)value) {
jiabinc52b1ff2019-10-31 17:20:42 -07009580 LOG_FATAL("Should not set audio source in RecordThread");
Eric Laurent10351942014-05-08 18:49:52 -07009581 }
Glenn Kastene198c362013-08-13 09:13:36 -07009582
Eric Laurent10351942014-05-08 18:49:52 -07009583 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009584 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07009585 if (status == INVALID_OPERATION) {
9586 inputStandBy();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009587 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07009588 }
9589 if (reconfig) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009590 if (status == BAD_VALUE) {
Mikhail Naganov560637e2021-03-31 22:40:13 +00009591 audio_config_base_t config = AUDIO_CONFIG_BASE_INITIALIZER;
9592 if (mInput->stream->getAudioProperties(&config) == OK &&
9593 audio_is_linear_pcm(config.format) && audio_is_linear_pcm(reqFormat) &&
9594 config.sample_rate <= (AUDIO_RESAMPLER_DOWN_RATIO_MAX * samplingRate) &&
Andy Hung936845a2021-06-08 00:09:06 -07009595 audio_channel_count_from_in_mask(config.channel_mask) <= FCC_LIMIT) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009596 status = NO_ERROR;
9597 }
Eric Laurent81784c32012-11-19 14:55:58 -08009598 }
Eric Laurent10351942014-05-08 18:49:52 -07009599 if (status == NO_ERROR) {
9600 readInputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07009601 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08009602 }
9603 }
Eric Laurent81784c32012-11-19 14:55:58 -08009604 }
Eric Laurent10351942014-05-08 18:49:52 -07009605
Eric Laurent81784c32012-11-19 14:55:58 -08009606 return reconfig;
9607}
9608
Andy Hungee58e4a2023-07-07 13:47:37 -07009609String8 RecordThread::getParameters(const String8& keys)
Eric Laurent81784c32012-11-19 14:55:58 -08009610{
Andy Hung972bec12023-08-31 16:13:39 -07009611 audio_utils::lock_guard _l(mutex());
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009612 if (initCheck() == NO_ERROR) {
9613 String8 out_s8;
9614 if (mInput->stream->getParameters(keys, &out_s8) == OK) {
9615 return out_s8;
9616 }
Eric Laurent81784c32012-11-19 14:55:58 -08009617 }
Andy Hung920f6572022-10-06 12:09:49 -07009618 return {};
Eric Laurent81784c32012-11-19 14:55:58 -08009619}
9620
Andy Hungab65b182023-09-06 19:41:47 -07009621void RecordThread::ioConfigChanged_l(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -07009622 audio_port_handle_t portId) {
Mikhail Naganov88536df2021-07-26 17:30:29 -07009623 sp<AudioIoDescriptor> desc;
Eric Laurent81784c32012-11-19 14:55:58 -08009624 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07009625 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07009626 case AUDIO_INPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07009627 case AUDIO_INPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07009628 desc = sp<AudioIoDescriptor>::make(mId, mPatch, true /*isInput*/,
9629 mSampleRate, mFormat, mChannelMask, mFrameCount, mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08009630 break;
Eric Laurent09f1ed22019-04-24 17:45:17 -07009631 case AUDIO_CLIENT_STARTED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07009632 desc = sp<AudioIoDescriptor>::make(mId, mPatch, portId);
Eric Laurent09f1ed22019-04-24 17:45:17 -07009633 break;
Eric Laurent73e26b62015-04-27 16:55:58 -07009634 case AUDIO_INPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08009635 default:
Mikhail Naganov88536df2021-07-26 17:30:29 -07009636 desc = sp<AudioIoDescriptor>::make(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08009637 break;
9638 }
Andy Hungab65b182023-09-06 19:41:47 -07009639 mAfThreadCallback->ioConfigChanged_l(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08009640}
9641
Andy Hungee58e4a2023-07-07 13:47:37 -07009642void RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08009643{
Dean Wheatley6c009512023-10-23 09:34:14 +11009644 const audio_config_base_t audioConfig = mInput->getAudioProperties();
9645 mSampleRate = audioConfig.sample_rate;
9646 mChannelMask = audioConfig.channel_mask;
9647 if (!audio_is_input_channel(mChannelMask)) {
9648 LOG_ALWAYS_FATAL("Channel mask %#x not valid for input", mChannelMask);
9649 }
9650
Mikhail Naganovce9f2652018-07-16 11:09:24 -07009651 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
Dean Wheatley6c009512023-10-23 09:34:14 +11009652
9653 // Get actual HAL format.
9654 status_t result = mInput->stream->getAudioProperties(nullptr, nullptr, &mHALFormat);
9655 LOG_ALWAYS_FATAL_IF(result != OK, "Error when retrieving input stream format: %d", result);
9656 // Get format from the shim, which will be different than the HAL format
9657 // if recording compressed audio from IEC61937 wrapped sources.
9658 mFormat = audioConfig.format;
9659 if (!audio_is_valid_format(mFormat)) {
9660 LOG_ALWAYS_FATAL("Format %#x not valid for input", mFormat);
9661 }
Mikhail Naganovce9f2652018-07-16 11:09:24 -07009662 if (audio_is_linear_pcm(mFormat)) {
Andy Hung936845a2021-06-08 00:09:06 -07009663 LOG_ALWAYS_FATAL_IF(mChannelCount > FCC_LIMIT, "HAL channel count %d > %d",
9664 mChannelCount, FCC_LIMIT);
Mikhail Naganovce9f2652018-07-16 11:09:24 -07009665 } else {
Andy Hung936845a2021-06-08 00:09:06 -07009666 // Can have more that FCC_LIMIT channels in encoded streams.
Mikhail Naganovce9f2652018-07-16 11:09:24 -07009667 ALOGI("HAL format %#x is not linear pcm", mFormat);
9668 }
Dean Wheatley6c009512023-10-23 09:34:14 +11009669 mFrameSize = mInput->getFrameSize();
Hayden Gomes1a89ab32020-06-12 11:05:47 -07009670 LOG_ALWAYS_FATAL_IF(mFrameSize <= 0, "Error frame size was %zu but must be greater than zero",
9671 mFrameSize);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009672 result = mInput->stream->getBufferSize(&mBufferSize);
9673 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
Glenn Kasten548efc92012-11-29 08:48:51 -08009674 mFrameCount = mBufferSize / mFrameSize;
Hayden Gomes1a89ab32020-06-12 11:05:47 -07009675 ALOGV("%p RecordThread params: mChannelCount=%u, mFormat=%#x, mFrameSize=%zu, "
9676 "mBufferSize=%zu, mFrameCount=%zu",
9677 this, mChannelCount, mFormat, mFrameSize, mBufferSize, mFrameCount);
Glenn Kasten49d00ad2014-07-21 11:22:03 -07009678
Eric Laurentec376dc2021-04-08 20:41:22 +02009679 // mRsmpInFrames must be 0 before calling resizeInputBuffer_l for the first time
9680 mRsmpInFrames = 0;
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009681 resizeInputBuffer_l(0 /*maxSharedAudioHistoryMs*/);
Eric Laurent81784c32012-11-19 14:55:58 -08009682
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08009683 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
9684 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Andy Hungea840382020-05-05 21:50:17 -07009685
9686 audio_input_flags_t flags = mInput->flags;
9687 mediametrics::LogItem item(mThreadMetrics.getMetricsId());
9688 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
Andy Hung25a80ac2023-07-19 12:47:35 -07009689 .set(AMEDIAMETRICS_PROP_ENCODING, IAfThreadBase::formatToString(mFormat).c_str())
Andy Hungea840382020-05-05 21:50:17 -07009690 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
9691 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
9692 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
9693 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
9694 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mFrameCount)
9695 .record();
Eric Laurent81784c32012-11-19 14:55:58 -08009696}
9697
Andy Hungee58e4a2023-07-07 13:47:37 -07009698uint32_t RecordThread::getInputFramesLost() const
Eric Laurent81784c32012-11-19 14:55:58 -08009699{
Andy Hung972bec12023-08-31 16:13:39 -07009700 audio_utils::lock_guard _l(mutex());
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009701 uint32_t result;
9702 if (initCheck() == NO_ERROR && mInput->stream->getInputFramesLost(&result) == OK) {
9703 return result;
Eric Laurent81784c32012-11-19 14:55:58 -08009704 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009705 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08009706}
9707
Andy Hungee58e4a2023-07-07 13:47:37 -07009708KeyedVector<audio_session_t, bool> RecordThread::sessionIds() const
Eric Laurent81784c32012-11-19 14:55:58 -08009709{
Glenn Kastend848eb42016-03-08 13:42:11 -08009710 KeyedVector<audio_session_t, bool> ids;
Andy Hung972bec12023-08-31 16:13:39 -07009711 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08009712 for (size_t j = 0; j < mTracks.size(); ++j) {
Andy Hung8d31fd22023-06-26 19:20:57 -07009713 sp<IAfRecordTrack> track = mTracks[j];
Glenn Kastend848eb42016-03-08 13:42:11 -08009714 audio_session_t sessionId = track->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08009715 if (ids.indexOfKey(sessionId) < 0) {
9716 ids.add(sessionId, true);
9717 }
9718 }
9719 return ids;
9720}
9721
Andy Hungee58e4a2023-07-07 13:47:37 -07009722AudioStreamIn* RecordThread::clearInput()
Eric Laurent81784c32012-11-19 14:55:58 -08009723{
Andy Hung972bec12023-08-31 16:13:39 -07009724 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08009725 AudioStreamIn *input = mInput;
9726 mInput = NULL;
Mikhail Naganov49aecf02023-09-08 15:14:34 -07009727 mInputSource.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08009728 return input;
9729}
9730
Andy Hungc5007f82023-08-29 14:26:09 -07009731// this method must always be called either with ThreadBase mutex() held or inside the thread loop
Andy Hungee58e4a2023-07-07 13:47:37 -07009732sp<StreamHalInterface> RecordThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08009733{
9734 if (mInput == NULL) {
9735 return NULL;
9736 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009737 return mInput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08009738}
9739
Andy Hungee58e4a2023-07-07 13:47:37 -07009740status_t RecordThread::addEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08009741{
Eric Laurent81784c32012-11-19 14:55:58 -08009742 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurentaaa44472014-09-12 17:41:50 -07009743 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08009744 chain->setInBuffer(NULL);
9745 chain->setOutBuffer(NULL);
9746
9747 checkSuspendOnAddEffectChain_l(chain);
9748
Eric Laurent1b928682014-10-02 19:41:47 -07009749 // make sure enabled pre processing effects state is communicated to the HAL as we
9750 // just moved them to a new input stream.
Shunkai Yaod125e402024-01-20 03:19:06 +00009751 chain->syncHalEffectsState_l();
Eric Laurent1b928682014-10-02 19:41:47 -07009752
Eric Laurent81784c32012-11-19 14:55:58 -08009753 mEffectChains.add(chain);
9754
9755 return NO_ERROR;
9756}
9757
Andy Hungee58e4a2023-07-07 13:47:37 -07009758size_t RecordThread::removeEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08009759{
9760 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
Eric Laurentb20cf7d2019-04-05 19:37:34 -07009761
9762 for (size_t i = 0; i < mEffectChains.size(); i++) {
9763 if (chain == mEffectChains[i]) {
9764 mEffectChains.removeAt(i);
9765 break;
9766 }
Eric Laurent81784c32012-11-19 14:55:58 -08009767 }
Eric Laurentb20cf7d2019-04-05 19:37:34 -07009768 return mEffectChains.size();
Eric Laurent81784c32012-11-19 14:55:58 -08009769}
9770
Andy Hungee58e4a2023-07-07 13:47:37 -07009771status_t RecordThread::createAudioPatch_l(const struct audio_patch* patch,
Eric Laurent1c333e22014-05-20 10:48:17 -07009772 audio_patch_handle_t *handle)
9773{
9774 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07009775
9776 // store new device and send to effects
jiabinc52b1ff2019-10-31 17:20:42 -07009777 mInDeviceTypeAddr.mType = patch->sources[0].ext.device.type;
jiabin0a488932020-08-07 17:32:40 -07009778 mInDeviceTypeAddr.setAddress(patch->sources[0].ext.device.address);
François Gaffie0c280aa2018-07-25 10:02:15 +02009779 audio_port_handle_t deviceId = patch->sources[0].id;
Eric Laurent054d9d32015-04-24 08:48:48 -07009780 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08009781 mEffectChains[i]->setInputDevice_l(inDeviceTypeAddr());
Eric Laurent054d9d32015-04-24 08:48:48 -07009782 }
9783
Eric Laurentd8365c52017-07-16 15:27:05 -07009784 checkBtNrec_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07009785
9786 // store new source and send to effects
9787 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
9788 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent1c333e22014-05-20 10:48:17 -07009789 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent054d9d32015-04-24 08:48:48 -07009790 mEffectChains[i]->setAudioSource_l(mAudioSource);
Eric Laurent1c333e22014-05-20 10:48:17 -07009791 }
Eric Laurent054d9d32015-04-24 08:48:48 -07009792 }
Eric Laurent1c333e22014-05-20 10:48:17 -07009793
Mikhail Naganov9ee05402016-10-13 15:58:17 -07009794 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07009795 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
9796 status = hwDevice->createAudioPatch(patch->num_sources,
9797 patch->sources,
9798 patch->num_sinks,
9799 patch->sinks,
9800 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07009801 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08009802 status = mInput->stream->legacyCreateAudioPatch(patch->sources[0],
9803 patch->sinks[0].ext.mix.usecase.source,
9804 patch->sources[0].ext.device.type);
Eric Laurent054d9d32015-04-24 08:48:48 -07009805 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07009806 }
Eric Laurent054d9d32015-04-24 08:48:48 -07009807
jiabinc52b1ff2019-10-31 17:20:42 -07009808 if ((mPatch.num_sources == 0) || (mPatch.sources[0].id != deviceId)) {
Eric Laurente8726fe2015-06-26 09:39:24 -07009809 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
jiabinc52b1ff2019-10-31 17:20:42 -07009810 mPatch = *patch;
Eric Laurente8726fe2015-06-26 09:39:24 -07009811 }
Eric Laurent296fb132015-05-01 11:38:42 -07009812
Andy Hungc2b11cb2020-04-22 09:04:01 -07009813 const std::string pathSourcesAsString = patchSourcesToString(patch);
Andy Hungcf10d742020-04-28 15:38:24 -07009814 mThreadMetrics.logEndInterval();
Andy Hungea840382020-05-05 21:50:17 -07009815 mThreadMetrics.logCreatePatch(pathSourcesAsString, /* outDevices */ {});
Andy Hungcf10d742020-04-28 15:38:24 -07009816 mThreadMetrics.logBeginInterval();
Andy Hungc2b11cb2020-04-22 09:04:01 -07009817 // also dispatch to active AudioRecords
9818 for (const auto &track : mActiveTracks) {
9819 track->logEndInterval();
9820 track->logBeginInterval(pathSourcesAsString);
9821 }
Eric Laurentdda206a2022-07-08 17:28:35 +02009822 // Force meteadata update after a route change
9823 mActiveTracks.setHasChanged();
9824
Eric Laurent1c333e22014-05-20 10:48:17 -07009825 return status;
9826}
9827
Andy Hungee58e4a2023-07-07 13:47:37 -07009828status_t RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
Eric Laurent1c333e22014-05-20 10:48:17 -07009829{
9830 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07009831
jiabinc52b1ff2019-10-31 17:20:42 -07009832 mPatch = audio_patch{};
9833 mInDeviceTypeAddr.reset();
Eric Laurent054d9d32015-04-24 08:48:48 -07009834
Mikhail Naganov9ee05402016-10-13 15:58:17 -07009835 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07009836 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
9837 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07009838 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08009839 status = mInput->stream->legacyReleaseAudioPatch();
Eric Laurent1c333e22014-05-20 10:48:17 -07009840 }
Eric Laurentdda206a2022-07-08 17:28:35 +02009841 // Force meteadata update after a route change
9842 mActiveTracks.setHasChanged();
9843
Eric Laurent1c333e22014-05-20 10:48:17 -07009844 return status;
9845}
9846
Andy Hungee58e4a2023-07-07 13:47:37 -07009847void RecordThread::updateOutDevices(const DeviceDescriptorBaseVector& outDevices)
jiabinc52b1ff2019-10-31 17:20:42 -07009848{
Andy Hung972bec12023-08-31 16:13:39 -07009849 audio_utils::lock_guard _l(mutex());
jiabinc52b1ff2019-10-31 17:20:42 -07009850 mOutDevices = outDevices;
9851 mOutDeviceTypeAddrs = deviceTypeAddrsFromDescriptors(mOutDevices);
9852 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08009853 mEffectChains[i]->setDevices_l(outDeviceTypeAddrs());
jiabinc52b1ff2019-10-31 17:20:42 -07009854 }
9855}
9856
Andy Hungee58e4a2023-07-07 13:47:37 -07009857int32_t RecordThread::getOldestFront_l()
Eric Laurentec376dc2021-04-08 20:41:22 +02009858{
9859 if (mTracks.size() == 0) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009860 return mRsmpInRear;
Eric Laurentec376dc2021-04-08 20:41:22 +02009861 }
Eric Laurent2407ce32021-04-26 14:56:03 +02009862 int32_t oldestFront = mRsmpInRear;
9863 int32_t maxFilled = 0;
Eric Laurentec376dc2021-04-08 20:41:22 +02009864 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07009865 int32_t front = mTracks[i]->resamplerBufferProvider()->getFront();
Eric Laurent2407ce32021-04-26 14:56:03 +02009866 int32_t filled;
Eric Laurent92d0a322021-07-16 15:32:33 +02009867 (void)__builtin_sub_overflow(mRsmpInRear, front, &filled);
Eric Laurent2407ce32021-04-26 14:56:03 +02009868 if (filled > maxFilled) {
9869 oldestFront = front;
9870 maxFilled = filled;
9871 }
Eric Laurentec376dc2021-04-08 20:41:22 +02009872 }
Andy Hung920f6572022-10-06 12:09:49 -07009873 if (maxFilled > static_cast<signed>(mRsmpInFrames)) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009874 (void)__builtin_sub_overflow(mRsmpInRear, mRsmpInFrames, &oldestFront);
9875 }
Eric Laurent2407ce32021-04-26 14:56:03 +02009876 return oldestFront;
Eric Laurentec376dc2021-04-08 20:41:22 +02009877}
9878
Andy Hungee58e4a2023-07-07 13:47:37 -07009879void RecordThread::updateFronts_l(int32_t offset)
Eric Laurentec376dc2021-04-08 20:41:22 +02009880{
9881 if (offset == 0) {
9882 return;
9883 }
9884 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07009885 int32_t front = mTracks[i]->resamplerBufferProvider()->getFront();
Eric Laurentec376dc2021-04-08 20:41:22 +02009886 front = audio_utils::safe_sub_overflow(front, offset);
Andy Hung8d31fd22023-06-26 19:20:57 -07009887 mTracks[i]->resamplerBufferProvider()->setFront(front);
Eric Laurentec376dc2021-04-08 20:41:22 +02009888 }
9889}
9890
Andy Hungee58e4a2023-07-07 13:47:37 -07009891void RecordThread::resizeInputBuffer_l(int32_t maxSharedAudioHistoryMs)
Eric Laurentec376dc2021-04-08 20:41:22 +02009892{
9893 // This is the formula for calculating the temporary buffer size.
9894 // With 7 HAL buffers, we can guarantee ability to down-sample the input by ratio of 6:1 to
9895 // 1 full output buffer, regardless of the alignment of the available input.
9896 // The value is somewhat arbitrary, and could probably be even larger.
9897 // A larger value should allow more old data to be read after a track calls start(),
9898 // without increasing latency.
9899 //
9900 // Note this is independent of the maximum downsampling ratio permitted for capture.
9901 size_t minRsmpInFrames = mFrameCount * 7;
9902
9903 // maxSharedAudioHistoryMs != 0 indicates a request to possibly make some part of the audio
9904 // capture history available to another client using the same session ID:
9905 // dimension the resampler input buffer accordingly.
9906
9907 // Get oldest client read position: getOldestFront_l() must be called before altering
9908 // mRsmpInRear, or mRsmpInFrames
9909 int32_t previousFront = getOldestFront_l();
9910 size_t previousRsmpInFramesP2 = mRsmpInFramesP2;
9911 int32_t previousRear = mRsmpInRear;
9912 mRsmpInRear = 0;
9913
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009914 ALOG_ASSERT(maxSharedAudioHistoryMs >= 0
Andy Hungee58e4a2023-07-07 13:47:37 -07009915 && maxSharedAudioHistoryMs <= kMaxSharedAudioHistoryMs,
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009916 "resizeInputBuffer_l() called with invalid max shared history %d",
9917 maxSharedAudioHistoryMs);
Eric Laurentec376dc2021-04-08 20:41:22 +02009918 if (maxSharedAudioHistoryMs != 0) {
9919 // resizeInputBuffer_l should never be called with a non zero shared history if the
9920 // buffer was not already allocated
9921 ALOG_ASSERT(mRsmpInBuffer != nullptr && mRsmpInFrames != 0,
9922 "resizeInputBuffer_l() called with shared history and unallocated buffer");
9923 size_t rsmpInFrames = (size_t)maxSharedAudioHistoryMs * mSampleRate / 1000;
9924 // never reduce resampler input buffer size
Eric Laurent92d0a322021-07-16 15:32:33 +02009925 if (rsmpInFrames <= mRsmpInFrames) {
Eric Laurentec376dc2021-04-08 20:41:22 +02009926 return;
9927 }
9928 mRsmpInFrames = rsmpInFrames;
9929 }
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009930 mMaxSharedAudioHistoryMs = maxSharedAudioHistoryMs;
Eric Laurentec376dc2021-04-08 20:41:22 +02009931 // Note: mRsmpInFrames is 0 when called with maxSharedAudioHistoryMs equals to 0 so it is always
9932 // initialized
9933 if (mRsmpInFrames < minRsmpInFrames) {
9934 mRsmpInFrames = minRsmpInFrames;
9935 }
9936 mRsmpInFramesP2 = roundup(mRsmpInFrames);
9937
9938 // TODO optimize audio capture buffer sizes ...
9939 // Here we calculate the size of the sliding buffer used as a source
9940 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
9941 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
9942 // be better to have it derived from the pipe depth in the long term.
9943 // The current value is higher than necessary. However it should not add to latency.
9944
9945 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
9946 mRsmpInFramesOA = mRsmpInFramesP2 + mFrameCount - 1;
9947
9948 void *rsmpInBuffer;
9949 (void)posix_memalign(&rsmpInBuffer, 32, mRsmpInFramesOA * mFrameSize);
9950 // if posix_memalign fails, will segv here.
9951 memset(rsmpInBuffer, 0, mRsmpInFramesOA * mFrameSize);
9952
9953 // Copy audio history if any from old buffer before freeing it
9954 if (previousRear != 0) {
9955 ALOG_ASSERT(mRsmpInBuffer != nullptr,
9956 "resizeInputBuffer_l() called with null buffer but frames already read from HAL");
9957
9958 ssize_t unread = audio_utils::safe_sub_overflow(previousRear, previousFront);
9959 previousFront &= previousRsmpInFramesP2 - 1;
9960 size_t part1 = previousRsmpInFramesP2 - previousFront;
9961 if (part1 > (size_t) unread) {
9962 part1 = unread;
9963 }
9964 if (part1 != 0) {
9965 memcpy(rsmpInBuffer, (const uint8_t*)mRsmpInBuffer + previousFront * mFrameSize,
9966 part1 * mFrameSize);
9967 mRsmpInRear = part1;
9968 part1 = unread - part1;
9969 if (part1 != 0) {
9970 memcpy((uint8_t*)rsmpInBuffer + mRsmpInRear * mFrameSize,
9971 (const uint8_t*)mRsmpInBuffer, part1 * mFrameSize);
9972 mRsmpInRear += part1;
9973 }
9974 }
9975 // Update front for all clients according to new rear
9976 updateFronts_l(audio_utils::safe_sub_overflow(previousRear, mRsmpInRear));
9977 } else {
9978 mRsmpInRear = 0;
9979 }
9980 free(mRsmpInBuffer);
9981 mRsmpInBuffer = rsmpInBuffer;
9982}
9983
Andy Hungee58e4a2023-07-07 13:47:37 -07009984void RecordThread::addPatchTrack(const sp<IAfPatchRecord>& record)
Eric Laurent83b88082014-06-20 18:31:16 -07009985{
Andy Hung972bec12023-08-31 16:13:39 -07009986 audio_utils::lock_guard _l(mutex());
Eric Laurent83b88082014-06-20 18:31:16 -07009987 mTracks.add(record);
Mikhail Naganov2534b382019-09-25 13:05:02 -07009988 if (record->getSource()) {
9989 mSource = record->getSource();
9990 }
Eric Laurent83b88082014-06-20 18:31:16 -07009991}
9992
Andy Hungee58e4a2023-07-07 13:47:37 -07009993void RecordThread::deletePatchTrack(const sp<IAfPatchRecord>& record)
Eric Laurent83b88082014-06-20 18:31:16 -07009994{
Andy Hung972bec12023-08-31 16:13:39 -07009995 audio_utils::lock_guard _l(mutex());
Mikhail Naganov2534b382019-09-25 13:05:02 -07009996 if (mSource == record->getSource()) {
9997 mSource = mInput;
9998 }
Eric Laurent83b88082014-06-20 18:31:16 -07009999 destroyTrack_l(record);
10000}
10001
Andy Hungee58e4a2023-07-07 13:47:37 -070010002void RecordThread::toAudioPortConfig(struct audio_port_config* config)
Eric Laurent83b88082014-06-20 18:31:16 -070010003{
Mikhail Naganovdc769682018-05-04 15:34:08 -070010004 ThreadBase::toAudioPortConfig(config);
Eric Laurent83b88082014-06-20 18:31:16 -070010005 config->role = AUDIO_PORT_ROLE_SINK;
10006 config->ext.mix.hw_module = mInput->audioHwDev->handle();
10007 config->ext.mix.usecase.source = mAudioSource;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -070010008 if (mInput && mInput->flags != AUDIO_INPUT_FLAG_NONE) {
10009 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
10010 config->flags.input = mInput->flags;
10011 }
Eric Laurent83b88082014-06-20 18:31:16 -070010012}
Eric Laurent1c333e22014-05-20 10:48:17 -070010013
Eric Laurent6acd1d42017-01-04 14:23:29 -080010014// ----------------------------------------------------------------------------
10015// Mmap
10016// ----------------------------------------------------------------------------
10017
Andy Hung7aa7d102023-07-07 15:58:48 -070010018// Mmap stream control interface implementation. Each MmapThreadHandle controls one
10019// MmapPlaybackThread or MmapCaptureThread instance.
10020class MmapThreadHandle : public MmapStreamInterface {
10021public:
10022 explicit MmapThreadHandle(const sp<IAfMmapThread>& thread);
10023 ~MmapThreadHandle() override;
10024
10025 // MmapStreamInterface virtuals
10026 status_t createMmapBuffer(int32_t minSizeFrames,
10027 struct audio_mmap_buffer_info* info) final;
10028 status_t getMmapPosition(struct audio_mmap_position* position) final;
10029 status_t getExternalPosition(uint64_t* position, int64_t* timeNanos) final;
10030 status_t start(const AudioClient& client,
10031 const audio_attributes_t* attr, audio_port_handle_t* handle) final;
10032 status_t stop(audio_port_handle_t handle) final;
10033 status_t standby() final;
10034 status_t reportData(const void* buffer, size_t frameCount) final;
10035private:
10036 const sp<IAfMmapThread> mThread;
10037};
10038
10039/* static */
10040sp<MmapStreamInterface> IAfMmapThread::createMmapStreamInterfaceAdapter(
10041 const sp<IAfMmapThread>& mmapThread) {
10042 return sp<MmapThreadHandle>::make(mmapThread);
10043}
10044
10045MmapThreadHandle::MmapThreadHandle(const sp<IAfMmapThread>& thread)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010046 : mThread(thread)
10047{
Phil Burk9fabbf82017-08-03 12:02:00 -070010048 assert(thread != 0); // thread must start non-null and stay non-null
Eric Laurent6acd1d42017-01-04 14:23:29 -080010049}
10050
Andy Hung7aa7d102023-07-07 15:58:48 -070010051// MmapStreamInterface could be directly implemented by MmapThread excepting this
10052// special handling on adapter dtor.
10053MmapThreadHandle::~MmapThreadHandle()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010054{
Phil Burk9fabbf82017-08-03 12:02:00 -070010055 mThread->disconnect();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010056}
10057
Andy Hung7aa7d102023-07-07 15:58:48 -070010058status_t MmapThreadHandle::createMmapBuffer(int32_t minSizeFrames,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010059 struct audio_mmap_buffer_info *info)
10060{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010061 return mThread->createMmapBuffer(minSizeFrames, info);
10062}
10063
Andy Hung7aa7d102023-07-07 15:58:48 -070010064status_t MmapThreadHandle::getMmapPosition(struct audio_mmap_position* position)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010065{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010066 return mThread->getMmapPosition(position);
10067}
10068
Andy Hung7aa7d102023-07-07 15:58:48 -070010069status_t MmapThreadHandle::getExternalPosition(uint64_t* position,
jiabinb7d8c5a2020-08-26 17:24:52 -070010070 int64_t *timeNanos) {
10071 return mThread->getExternalPosition(position, timeNanos);
10072}
10073
Andy Hung7aa7d102023-07-07 15:58:48 -070010074status_t MmapThreadHandle::start(const AudioClient& client,
jiabind1f1cb62020-03-24 11:57:57 -070010075 const audio_attributes_t *attr, audio_port_handle_t *handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010076{
jiabind1f1cb62020-03-24 11:57:57 -070010077 return mThread->start(client, attr, handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010078}
10079
Andy Hung7aa7d102023-07-07 15:58:48 -070010080status_t MmapThreadHandle::stop(audio_port_handle_t handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010081{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010082 return mThread->stop(handle);
10083}
10084
Andy Hung7aa7d102023-07-07 15:58:48 -070010085status_t MmapThreadHandle::standby()
Eric Laurent18b57012017-02-13 16:23:52 -080010086{
Eric Laurent18b57012017-02-13 16:23:52 -080010087 return mThread->standby();
10088}
10089
Andy Hung7aa7d102023-07-07 15:58:48 -070010090status_t MmapThreadHandle::reportData(const void* buffer, size_t frameCount)
10091{
jiabinfc791ee2023-02-15 19:43:40 +000010092 return mThread->reportData(buffer, frameCount);
10093}
10094
Eric Laurent6acd1d42017-01-04 14:23:29 -080010095
Andy Hungee58e4a2023-07-07 13:47:37 -070010096MmapThread::MmapThread(
Andy Hung583043b2023-07-17 17:05:00 -070010097 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
Andy Hung920f6572022-10-06 12:09:49 -070010098 AudioHwDevice *hwDev, const sp<StreamHalInterface>& stream, bool systemReady, bool isOut)
Andy Hung583043b2023-07-17 17:05:00 -070010099 : ThreadBase(afThreadCallback, id, (isOut ? MMAP_PLAYBACK : MMAP_CAPTURE), systemReady, isOut),
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010100 mSessionId(AUDIO_SESSION_NONE),
François Gaffie0c280aa2018-07-25 10:02:15 +020010101 mPortId(AUDIO_PORT_HANDLE_NONE),
Andy Hung2c6c3bb2017-06-16 14:01:45 -070010102 mHalStream(stream), mHalDevice(hwDev->hwDevice()), mAudioHwDev(hwDev),
Eric Laurent67f97292018-04-20 18:05:41 -070010103 mActiveTracks(&this->mLocalLog),
10104 mHalVolFloat(-1.0f), // Initialize to illegal value so it always gets set properly later.
10105 mNoCallbackWarningCount(0)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010106{
Eric Laurent18b57012017-02-13 16:23:52 -080010107 mStandby = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010108 readHalParameters_l();
10109}
10110
Andy Hungee58e4a2023-07-07 13:47:37 -070010111void MmapThread::onFirstRef()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010112{
10113 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
10114}
10115
Andy Hungee58e4a2023-07-07 13:47:37 -070010116void MmapThread::disconnect()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010117{
Andy Hung8d31fd22023-06-26 19:20:57 -070010118 ActiveTracks<IAfMmapTrack> activeTracks;
Andy Hung3f49ebb2023-09-19 14:48:41 -070010119 audio_port_handle_t localPortId;
Eric Laurent331679c2018-04-16 17:03:16 -070010120 {
Andy Hung972bec12023-08-31 16:13:39 -070010121 audio_utils::lock_guard _l(mutex());
Andy Hung8d31fd22023-06-26 19:20:57 -070010122 for (const sp<IAfMmapTrack>& t : mActiveTracks) {
Eric Laurent331679c2018-04-16 17:03:16 -070010123 activeTracks.add(t);
10124 }
Andy Hung3f49ebb2023-09-19 14:48:41 -070010125 localPortId = mPortId;
Eric Laurent331679c2018-04-16 17:03:16 -070010126 }
Andy Hung8d31fd22023-06-26 19:20:57 -070010127 for (const sp<IAfMmapTrack>& t : activeTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010128 stop(t->portId());
10129 }
Phil Burk9fabbf82017-08-03 12:02:00 -070010130 // This will decrement references and may cause the destruction of this thread.
Eric Laurent6acd1d42017-01-04 14:23:29 -080010131 if (isOutput()) {
Andy Hung3f49ebb2023-09-19 14:48:41 -070010132 AudioSystem::releaseOutput(localPortId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010133 } else {
Andy Hung3f49ebb2023-09-19 14:48:41 -070010134 AudioSystem::releaseInput(localPortId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010135 }
10136}
10137
10138
Andy Hung8d672e02023-09-15 18:19:28 -070010139void MmapThread::configure_l(const audio_attributes_t* attr,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010140 audio_stream_type_t streamType __unused,
10141 audio_session_t sessionId,
10142 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010143 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010144 audio_port_handle_t portId)
10145{
10146 mAttr = *attr;
10147 mSessionId = sessionId;
10148 mCallback = callback;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010149 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010150 mPortId = portId;
10151}
10152
Andy Hungee58e4a2023-07-07 13:47:37 -070010153status_t MmapThread::createMmapBuffer(int32_t minSizeFrames,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010154 struct audio_mmap_buffer_info *info)
10155{
Andy Hung3f49ebb2023-09-19 14:48:41 -070010156 audio_utils::lock_guard l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010157 if (mHalStream == 0) {
10158 return NO_INIT;
10159 }
Eric Laurent18b57012017-02-13 16:23:52 -080010160 mStandby = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010161 return mHalStream->createMmapBuffer(minSizeFrames, info);
10162}
10163
Andy Hungee58e4a2023-07-07 13:47:37 -070010164status_t MmapThread::getMmapPosition(struct audio_mmap_position* position) const
Eric Laurent6acd1d42017-01-04 14:23:29 -080010165{
Andy Hung3f49ebb2023-09-19 14:48:41 -070010166 audio_utils::lock_guard l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010167 if (mHalStream == 0) {
10168 return NO_INIT;
10169 }
10170 return mHalStream->getMmapPosition(position);
10171}
10172
Andy Hungee58e4a2023-07-07 13:47:37 -070010173status_t MmapThread::exitStandby_l()
Eric Laurent331679c2018-04-16 17:03:16 -070010174{
Eric Laurentdda206a2022-07-08 17:28:35 +020010175 // The HAL must receive track metadata before starting the stream
10176 updateMetadata_l();
Eric Laurent331679c2018-04-16 17:03:16 -070010177 status_t ret = mHalStream->start();
10178 if (ret != NO_ERROR) {
10179 ALOGE("%s: error mHalStream->start() = %d for first track", __FUNCTION__, ret);
10180 return ret;
10181 }
Andy Hungcf10d742020-04-28 15:38:24 -070010182 if (mStandby) {
10183 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -070010184 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -070010185 mStandby = false;
10186 }
Eric Laurent331679c2018-04-16 17:03:16 -070010187 return NO_ERROR;
10188}
10189
Andy Hungee58e4a2023-07-07 13:47:37 -070010190status_t MmapThread::start(const AudioClient& client,
jiabind1f1cb62020-03-24 11:57:57 -070010191 const audio_attributes_t *attr,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010192 audio_port_handle_t *handle)
10193{
Andy Hung3f49ebb2023-09-19 14:48:41 -070010194 audio_utils::lock_guard l(mutex());
Eric Laurenta54f1282017-07-01 19:39:32 -070010195 ALOGV("%s clientUid %d mStandby %d mPortId %d *handle %d", __FUNCTION__,
Svet Ganov33761132021-05-13 22:51:08 +000010196 client.attributionSource.uid, mStandby, mPortId, *handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010197 if (mHalStream == 0) {
10198 return NO_INIT;
10199 }
10200
10201 status_t ret;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010202
Eric Laurentdda206a2022-07-08 17:28:35 +020010203 // For the first track, reuse portId and session allocated when the stream was opened.
Eric Laurenta54f1282017-07-01 19:39:32 -070010204 if (*handle == mPortId) {
Andy Hung3f49ebb2023-09-19 14:48:41 -070010205 acquireWakeLock_l();
Eric Laurentdda206a2022-07-08 17:28:35 +020010206 return NO_ERROR;
Eric Laurenta54f1282017-07-01 19:39:32 -070010207 }
10208
10209 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
10210
10211 audio_io_handle_t io = mId;
Andy Hung6cd79802023-07-19 16:56:19 -070010212 const AttributionSourceState adjAttributionSource = afutils::checkAttributionSourcePackage(
Atneya Nairf59db5c2023-05-10 21:37:41 -070010213 client.attributionSource);
10214
Andy Hung3f49ebb2023-09-19 14:48:41 -070010215 const auto localSessionId = mSessionId;
10216 auto localAttr = mAttr;
Eric Laurenta54f1282017-07-01 19:39:32 -070010217 if (isOutput()) {
10218 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
10219 config.sample_rate = mSampleRate;
10220 config.channel_mask = mChannelMask;
10221 config.format = mFormat;
Andy Hung3f49ebb2023-09-19 14:48:41 -070010222 audio_stream_type_t stream = streamType_l();
Eric Laurenta54f1282017-07-01 19:39:32 -070010223 audio_output_flags_t flags =
10224 (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010225 audio_port_handle_t deviceId = mDeviceId;
Kevin Rocard153f92d2018-12-18 18:33:28 -080010226 std::vector<audio_io_handle_t> secondaryOutputs;
Eric Laurentb0a7bc92022-04-05 15:06:08 +020010227 bool isSpatialized;
jiabinc658e452022-10-21 20:52:21 +000010228 bool isBitPerfect;
Andy Hung3f49ebb2023-09-19 14:48:41 -070010229 mutex().unlock();
10230 ret = AudioSystem::getOutputForAttr(&localAttr, &io,
10231 localSessionId,
Eric Laurenta54f1282017-07-01 19:39:32 -070010232 &stream,
Atneya Nairf59db5c2023-05-10 21:37:41 -070010233 adjAttributionSource,
Eric Laurenta54f1282017-07-01 19:39:32 -070010234 &config,
10235 flags,
10236 &deviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -080010237 &portId,
Eric Laurentb0a7bc92022-04-05 15:06:08 +020010238 &secondaryOutputs,
jiabinc658e452022-10-21 20:52:21 +000010239 &isSpatialized,
10240 &isBitPerfect);
Andy Hung3f49ebb2023-09-19 14:48:41 -070010241 mutex().lock();
10242 mAttr = localAttr;
Kevin Rocard153f92d2018-12-18 18:33:28 -080010243 ALOGD_IF(!secondaryOutputs.empty(),
10244 "MmapThread::start does not support secondary outputs, ignoring them");
Eric Laurent6acd1d42017-01-04 14:23:29 -080010245 } else {
Eric Laurenta54f1282017-07-01 19:39:32 -070010246 audio_config_base_t config;
10247 config.sample_rate = mSampleRate;
10248 config.channel_mask = mChannelMask;
10249 config.format = mFormat;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010250 audio_port_handle_t deviceId = mDeviceId;
Andy Hung3f49ebb2023-09-19 14:48:41 -070010251 mutex().unlock();
10252 ret = AudioSystem::getInputForAttr(&localAttr, &io,
Mikhail Naganov2996f672019-04-18 12:29:59 -070010253 RECORD_RIID_INVALID,
Andy Hung3f49ebb2023-09-19 14:48:41 -070010254 localSessionId,
Atneya Nairf59db5c2023-05-10 21:37:41 -070010255 adjAttributionSource,
Eric Laurenta54f1282017-07-01 19:39:32 -070010256 &config,
10257 AUDIO_INPUT_FLAG_MMAP_NOIRQ,
10258 &deviceId,
10259 &portId);
Andy Hung3f49ebb2023-09-19 14:48:41 -070010260 mutex().lock();
10261 // localAttr is const for getInputForAttr.
Eric Laurenta54f1282017-07-01 19:39:32 -070010262 }
10263 // APM should not chose a different input or output stream for the same set of attributes
10264 // and audo configuration
10265 if (ret != NO_ERROR || io != mId) {
10266 ALOGE("%s: error getting output or input from APM (error %d, io %d expected io %d)",
10267 __FUNCTION__, ret, io, mId);
10268 return BAD_VALUE;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010269 }
10270
10271 if (isOutput()) {
Andy Hung3f49ebb2023-09-19 14:48:41 -070010272 mutex().unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -070010273 ret = AudioSystem::startOutput(portId);
Andy Hung3f49ebb2023-09-19 14:48:41 -070010274 mutex().lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010275 } else {
jiabin09609032022-06-15 19:26:01 +000010276 {
10277 // Add the track record before starting input so that the silent status for the
10278 // client can be cached.
jiabin09609032022-06-15 19:26:01 +000010279 setClientSilencedState_l(portId, false /*silenced*/);
10280 }
Andy Hung3f49ebb2023-09-19 14:48:41 -070010281 mutex().unlock();
Eric Laurent4eb58f12018-12-07 16:41:02 -080010282 ret = AudioSystem::startInput(portId);
Andy Hung3f49ebb2023-09-19 14:48:41 -070010283 mutex().lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010284 }
10285
10286 // abort if start is rejected by audio policy manager
10287 if (ret != NO_ERROR) {
Phil Burk7f6b40d2017-02-09 13:18:38 -080010288 ALOGE("%s: error start rejected by AudioPolicyManager = %d", __FUNCTION__, ret);
Eric Tan39ec8d62018-07-24 09:49:29 -070010289 if (!mActiveTracks.isEmpty()) {
Andy Hungc5007f82023-08-29 14:26:09 -070010290 mutex().unlock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010291 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -070010292 AudioSystem::releaseOutput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010293 } else {
Eric Laurentfee19762018-01-29 18:44:13 -080010294 AudioSystem::releaseInput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010295 }
Andy Hungc5007f82023-08-29 14:26:09 -070010296 mutex().lock();
Eric Laurent18b57012017-02-13 16:23:52 -080010297 } else {
10298 mHalStream->stop();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010299 }
jiabin09609032022-06-15 19:26:01 +000010300 eraseClientSilencedState_l(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010301 return PERMISSION_DENIED;
10302 }
10303
Kevin Rocard1f564ac2018-03-29 13:53:10 -070010304 // Given that MmapThread::mAttr is mutable, should a MmapTrack have attributes ?
Andy Hung8d31fd22023-06-26 19:20:57 -070010305 sp<IAfMmapTrack> track = IAfMmapTrack::create(
10306 this, attr == nullptr ? mAttr : *attr, mSampleRate, mFormat,
Svet Ganov33761132021-05-13 22:51:08 +000010307 mChannelMask, mSessionId, isOutput(),
10308 client.attributionSource,
Philip P. Moltmannbda45752020-07-17 16:41:18 -070010309 IPCThreadState::self()->getCallingPid(), portId);
jiabin09609032022-06-15 19:26:01 +000010310 if (!isOutput()) {
10311 track->setSilenced_l(isClientSilenced_l(portId));
10312 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010313
Eric Laurent4eb58f12018-12-07 16:41:02 -080010314 if (isOutput()) {
10315 // force volume update when a new track is added
10316 mHalVolFloat = -1.0f;
10317 } else if (!track->isSilenced_l()) {
Andy Hung8d31fd22023-06-26 19:20:57 -070010318 for (const sp<IAfMmapTrack>& t : mActiveTracks) {
Andy Hung920f6572022-10-06 12:09:49 -070010319 if (t->isSilenced_l()
10320 && t->uid() != static_cast<uid_t>(client.attributionSource.uid)) {
Eric Laurent4eb58f12018-12-07 16:41:02 -080010321 t->invalidate();
Andy Hung920f6572022-10-06 12:09:49 -070010322 }
Eric Laurent4eb58f12018-12-07 16:41:02 -080010323 }
10324 }
10325
Eric Laurent6acd1d42017-01-04 14:23:29 -080010326 mActiveTracks.add(track);
Andy Hung116bc262023-06-20 18:56:17 -070010327 sp<IAfEffectChain> chain = getEffectChain_l(mSessionId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010328 if (chain != 0) {
Andy Hung3f49ebb2023-09-19 14:48:41 -070010329 chain->setStrategy(getStrategyForStream(streamType_l()));
Eric Laurent6acd1d42017-01-04 14:23:29 -080010330 chain->incTrackCnt();
10331 chain->incActiveTrackCnt();
10332 }
10333
Andy Hungc2b11cb2020-04-22 09:04:01 -070010334 track->logBeginInterval(patchSinksToString(&mPatch)); // log to MediaMetrics
Eric Laurent6acd1d42017-01-04 14:23:29 -080010335 *handle = portId;
Eric Laurentdda206a2022-07-08 17:28:35 +020010336
10337 if (mActiveTracks.size() == 1) {
10338 ret = exitStandby_l();
10339 }
10340
Eric Laurent6acd1d42017-01-04 14:23:29 -080010341 broadcast_l();
10342
Eric Laurentdda206a2022-07-08 17:28:35 +020010343 ALOGV("%s DONE status %d handle %d stream %p", __FUNCTION__, ret, *handle, mHalStream.get());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010344
Eric Laurentdda206a2022-07-08 17:28:35 +020010345 return ret;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010346}
10347
Andy Hungee58e4a2023-07-07 13:47:37 -070010348status_t MmapThread::stop(audio_port_handle_t handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010349{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010350 ALOGV("%s handle %d", __FUNCTION__, handle);
Andy Hung3f49ebb2023-09-19 14:48:41 -070010351 audio_utils::lock_guard l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010352
10353 if (mHalStream == 0) {
10354 return NO_INIT;
10355 }
10356
Eric Laurenta54f1282017-07-01 19:39:32 -070010357 if (handle == mPortId) {
Andy Hung3f49ebb2023-09-19 14:48:41 -070010358 releaseWakeLock_l();
Eric Laurenta54f1282017-07-01 19:39:32 -070010359 return NO_ERROR;
10360 }
10361
Andy Hung8d31fd22023-06-26 19:20:57 -070010362 sp<IAfMmapTrack> track;
10363 for (const sp<IAfMmapTrack>& t : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010364 if (handle == t->portId()) {
10365 track = t;
10366 break;
10367 }
10368 }
10369 if (track == 0) {
10370 return BAD_VALUE;
10371 }
10372
10373 mActiveTracks.remove(track);
jiabin09609032022-06-15 19:26:01 +000010374 eraseClientSilencedState_l(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010375
Andy Hungc5007f82023-08-29 14:26:09 -070010376 mutex().unlock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010377 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -070010378 AudioSystem::stopOutput(track->portId());
10379 AudioSystem::releaseOutput(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010380 } else {
Eric Laurentfee19762018-01-29 18:44:13 -080010381 AudioSystem::stopInput(track->portId());
10382 AudioSystem::releaseInput(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010383 }
Andy Hungc5007f82023-08-29 14:26:09 -070010384 mutex().lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010385
Andy Hung116bc262023-06-20 18:56:17 -070010386 sp<IAfEffectChain> chain = getEffectChain_l(track->sessionId());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010387 if (chain != 0) {
10388 chain->decActiveTrackCnt();
10389 chain->decTrackCnt();
10390 }
10391
Eric Laurentdda206a2022-07-08 17:28:35 +020010392 if (mActiveTracks.isEmpty()) {
10393 mHalStream->stop();
10394 }
10395
Eric Laurent6acd1d42017-01-04 14:23:29 -080010396 broadcast_l();
10397
Eric Laurent6acd1d42017-01-04 14:23:29 -080010398 return NO_ERROR;
10399}
10400
Andy Hungee58e4a2023-07-07 13:47:37 -070010401status_t MmapThread::standby()
Andy Hung3f49ebb2023-09-19 14:48:41 -070010402NO_THREAD_SAFETY_ANALYSIS // clang bug
Eric Laurent18b57012017-02-13 16:23:52 -080010403{
10404 ALOGV("%s", __FUNCTION__);
Atneya Nair97a73882023-10-30 20:26:21 -070010405 audio_utils::lock_guard l_{mutex()};
Eric Laurent18b57012017-02-13 16:23:52 -080010406
10407 if (mHalStream == 0) {
10408 return NO_INIT;
10409 }
Eric Tan39ec8d62018-07-24 09:49:29 -070010410 if (!mActiveTracks.isEmpty()) {
Eric Laurent18b57012017-02-13 16:23:52 -080010411 return INVALID_OPERATION;
10412 }
10413 mHalStream->standby();
Andy Hungcf10d742020-04-28 15:38:24 -070010414 if (!mStandby) {
10415 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -070010416 mThreadSnapshot.onEnd();
Andy Hungcf10d742020-04-28 15:38:24 -070010417 mStandby = true;
10418 }
Andy Hung3f49ebb2023-09-19 14:48:41 -070010419 releaseWakeLock_l();
Eric Laurent18b57012017-02-13 16:23:52 -080010420 return NO_ERROR;
10421}
10422
Andy Hungee58e4a2023-07-07 13:47:37 -070010423status_t MmapThread::reportData(const void* /*buffer*/, size_t /*frameCount*/) {
jiabinfc791ee2023-02-15 19:43:40 +000010424 // This is a stub implementation. The MmapPlaybackThread overrides this function.
10425 return INVALID_OPERATION;
10426}
10427
Andy Hungee58e4a2023-07-07 13:47:37 -070010428void MmapThread::readHalParameters_l()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010429{
10430 status_t result = mHalStream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
10431 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
10432 mFormat = mHALFormat;
10433 LOG_ALWAYS_FATAL_IF(!audio_is_linear_pcm(mFormat), "HAL format %#x is not linear pcm", mFormat);
10434 result = mHalStream->getFrameSize(&mFrameSize);
10435 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
Hayden Gomes1a89ab32020-06-12 11:05:47 -070010436 LOG_ALWAYS_FATAL_IF(mFrameSize <= 0, "Error frame size was %zu but must be greater than zero",
10437 mFrameSize);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010438 result = mHalStream->getBufferSize(&mBufferSize);
10439 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
10440 mFrameCount = mBufferSize / mFrameSize;
Andy Hungc2b11cb2020-04-22 09:04:01 -070010441
Andy Hungcf10d742020-04-28 15:38:24 -070010442 // TODO: make a readHalParameters call?
10443 mediametrics::LogItem item(mThreadMetrics.getMetricsId());
Andy Hungc2b11cb2020-04-22 09:04:01 -070010444 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
Andy Hung25a80ac2023-07-19 12:47:35 -070010445 .set(AMEDIAMETRICS_PROP_ENCODING, IAfThreadBase::formatToString(mFormat).c_str())
Andy Hungc2b11cb2020-04-22 09:04:01 -070010446 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
10447 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
10448 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
10449 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mFrameCount)
10450 /*
10451 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
10452 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELMASK,
10453 (int32_t)mHapticChannelMask)
10454 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELCOUNT,
10455 (int32_t)mHapticChannelCount)
10456 */
10457 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_ENCODING,
Andy Hung25a80ac2023-07-19 12:47:35 -070010458 IAfThreadBase::formatToString(mHALFormat).c_str())
Andy Hungc2b11cb2020-04-22 09:04:01 -070010459 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_FRAMECOUNT,
10460 (int32_t)mFrameCount) // sic - added HAL
10461 .record();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010462}
10463
Andy Hungee58e4a2023-07-07 13:47:37 -070010464bool MmapThread::threadLoop()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010465{
Andy Hungab65b182023-09-06 19:41:47 -070010466 {
10467 audio_utils::unique_lock _l(mutex());
10468 checkSilentMode_l();
10469 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010470
10471 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
10472
10473 while (!exitPending())
10474 {
Andy Hung116bc262023-06-20 18:56:17 -070010475 Vector<sp<IAfEffectChain>> effectChains;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010476
Andy Hung13850be2019-03-14 11:33:09 -070010477 { // under Thread lock
Andy Hungc5007f82023-08-29 14:26:09 -070010478 audio_utils::unique_lock _l(mutex());
Andy Hung13850be2019-03-14 11:33:09 -070010479
Eric Laurent6acd1d42017-01-04 14:23:29 -080010480 if (mSignalPending) {
10481 // A signal was raised while we were unlocked
10482 mSignalPending = false;
10483 } else {
10484 if (mConfigEvents.isEmpty()) {
10485 // we're about to wait, flush the binder command buffer
10486 IPCThreadState::self()->flushCommands();
10487
10488 if (exitPending()) {
10489 break;
10490 }
10491
Eric Laurent6acd1d42017-01-04 14:23:29 -080010492 // wait until we have something to do...
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +000010493 ALOGV("%s going to sleep", myName.c_str());
Andy Hungc5007f82023-08-29 14:26:09 -070010494 mWaitWorkCV.wait(_l);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +000010495 ALOGV("%s waking up", myName.c_str());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010496
10497 checkSilentMode_l();
10498
10499 continue;
10500 }
10501 }
10502
10503 processConfigEvents_l();
10504
10505 processVolume_l();
10506
10507 checkInvalidTracks_l();
10508
Andy Hungab65b182023-09-06 19:41:47 -070010509 mActiveTracks.updatePowerState_l(this);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010510
Kevin Rocard069c2712018-03-29 19:09:14 -070010511 updateMetadata_l();
10512
Eric Laurent6acd1d42017-01-04 14:23:29 -080010513 lockEffectChains_l(effectChains);
Andy Hung13850be2019-03-14 11:33:09 -070010514 } // release Thread lock
10515
Eric Laurent6acd1d42017-01-04 14:23:29 -080010516 for (size_t i = 0; i < effectChains.size(); i ++) {
Andy Hung13850be2019-03-14 11:33:09 -070010517 effectChains[i]->process_l(); // Thread is not locked, but effect chain is locked
Eric Laurent6acd1d42017-01-04 14:23:29 -080010518 }
Andy Hung13850be2019-03-14 11:33:09 -070010519
10520 // enable changes in effect chain, including moving to another thread.
Eric Laurent6acd1d42017-01-04 14:23:29 -080010521 unlockEffectChains(effectChains);
10522 // Effect chains will be actually deleted here if they were removed from
10523 // mEffectChains list during mixing or effects processing
10524 }
10525
10526 threadLoop_exit();
10527
10528 if (!mStandby) {
10529 threadLoop_standby();
10530 mStandby = true;
10531 }
10532
Eric Laurent6acd1d42017-01-04 14:23:29 -080010533 ALOGV("Thread %p type %d exiting", this, mType);
10534 return false;
10535}
10536
Andy Hungc5007f82023-08-29 14:26:09 -070010537// checkForNewParameter_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -070010538bool MmapThread::checkForNewParameter_l(const String8& keyValuePair,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010539 status_t& status)
10540{
10541 AudioParameter param = AudioParameter(keyValuePair);
10542 int value;
Eric Laurente6e9a482017-07-25 19:26:02 -070010543 bool sendToHal = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010544 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -070010545 LOG_FATAL("Should not happen set routing device in MmapThread");
Eric Laurent6acd1d42017-01-04 14:23:29 -080010546 }
Eric Laurente6e9a482017-07-25 19:26:02 -070010547 if (sendToHal) {
10548 status = mHalStream->setParameters(keyValuePair);
10549 } else {
10550 status = NO_ERROR;
10551 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010552
10553 return false;
10554}
10555
Andy Hungee58e4a2023-07-07 13:47:37 -070010556String8 MmapThread::getParameters(const String8& keys)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010557{
Andy Hung972bec12023-08-31 16:13:39 -070010558 audio_utils::lock_guard _l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010559 String8 out_s8;
10560 if (initCheck() == NO_ERROR && mHalStream->getParameters(keys, &out_s8) == OK) {
10561 return out_s8;
10562 }
Andy Hung920f6572022-10-06 12:09:49 -070010563 return {};
Eric Laurent6acd1d42017-01-04 14:23:29 -080010564}
10565
Andy Hungab65b182023-09-06 19:41:47 -070010566void MmapThread::ioConfigChanged_l(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -070010567 audio_port_handle_t portId __unused) {
Mikhail Naganov88536df2021-07-26 17:30:29 -070010568 sp<AudioIoDescriptor> desc;
10569 bool isInput = false;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010570 switch (event) {
10571 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -070010572 case AUDIO_INPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -080010573 case AUDIO_INPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -070010574 isInput = true;
10575 FALLTHROUGH_INTENDED;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010576 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -070010577 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -080010578 case AUDIO_OUTPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -070010579 desc = sp<AudioIoDescriptor>::make(mId, mPatch, isInput,
10580 mSampleRate, mFormat, mChannelMask, mFrameCount, mFrameCount);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010581 break;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010582 case AUDIO_INPUT_CLOSED:
10583 case AUDIO_OUTPUT_CLOSED:
10584 default:
Mikhail Naganov88536df2021-07-26 17:30:29 -070010585 desc = sp<AudioIoDescriptor>::make(mId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010586 break;
10587 }
Andy Hungab65b182023-09-06 19:41:47 -070010588 mAfThreadCallback->ioConfigChanged_l(event, desc, pid);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010589}
10590
Andy Hungee58e4a2023-07-07 13:47:37 -070010591status_t MmapThread::createAudioPatch_l(const struct audio_patch* patch,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010592 audio_patch_handle_t *handle)
Andy Hungc5007f82023-08-29 14:26:09 -070010593NO_THREAD_SAFETY_ANALYSIS // elease and re-acquire mutex()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010594{
10595 status_t status = NO_ERROR;
10596
10597 // store new device and send to effects
10598 audio_devices_t type = AUDIO_DEVICE_NONE;
10599 audio_port_handle_t deviceId;
jiabinc52b1ff2019-10-31 17:20:42 -070010600 AudioDeviceTypeAddrVector sinkDeviceTypeAddrs;
10601 AudioDeviceTypeAddr sourceDeviceTypeAddr;
10602 uint32_t numDevices = 0;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010603 if (isOutput()) {
10604 for (unsigned int i = 0; i < patch->num_sinks; i++) {
jiabinc52b1ff2019-10-31 17:20:42 -070010605 LOG_ALWAYS_FATAL_IF(popcount(patch->sinks[i].ext.device.type) > 1
10606 && !mAudioHwDev->supportsAudioPatches(),
10607 "Enumerated device type(%#x) must not be used "
10608 "as it does not support audio patches",
10609 patch->sinks[i].ext.device.type);
Mikhail Naganov55773032020-10-01 15:08:13 -070010610 type = static_cast<audio_devices_t>(type | patch->sinks[i].ext.device.type);
Andy Hung920f6572022-10-06 12:09:49 -070010611 sinkDeviceTypeAddrs.emplace_back(patch->sinks[i].ext.device.type,
10612 patch->sinks[i].ext.device.address);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010613 }
10614 deviceId = patch->sinks[0].id;
jiabinc52b1ff2019-10-31 17:20:42 -070010615 numDevices = mPatch.num_sinks;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010616 } else {
10617 type = patch->sources[0].ext.device.type;
10618 deviceId = patch->sources[0].id;
jiabinc52b1ff2019-10-31 17:20:42 -070010619 numDevices = mPatch.num_sources;
10620 sourceDeviceTypeAddr.mType = patch->sources[0].ext.device.type;
jiabin0a488932020-08-07 17:32:40 -070010621 sourceDeviceTypeAddr.setAddress(patch->sources[0].ext.device.address);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010622 }
10623
10624 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -080010625 if (isOutput()) {
10626 mEffectChains[i]->setDevices_l(sinkDeviceTypeAddrs);
10627 } else {
10628 mEffectChains[i]->setInputDevice_l(sourceDeviceTypeAddr);
10629 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010630 }
10631
jiabinc52b1ff2019-10-31 17:20:42 -070010632 if (!isOutput()) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010633 // store new source and send to effects
10634 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
10635 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
10636 for (size_t i = 0; i < mEffectChains.size(); i++) {
10637 mEffectChains[i]->setAudioSource_l(mAudioSource);
10638 }
10639 }
10640 }
10641
10642 if (mAudioHwDev->supportsAudioPatches()) {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010643 status = mHalDevice->createAudioPatch(patch->num_sources, patch->sources, patch->num_sinks,
10644 patch->sinks, handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010645 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010646 audio_port_config port;
10647 std::optional<audio_source_t> source;
10648 if (isOutput()) {
10649 port = patch->sinks[0];
Eric Laurent6acd1d42017-01-04 14:23:29 -080010650 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010651 port = patch->sources[0];
10652 source = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010653 }
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010654 status = mHalStream->legacyCreateAudioPatch(port, source, type);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010655 *handle = AUDIO_PATCH_HANDLE_NONE;
10656 }
10657
jiabinc52b1ff2019-10-31 17:20:42 -070010658 if (numDevices == 0 || mDeviceId != deviceId) {
10659 if (isOutput()) {
10660 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
10661 mOutDeviceTypeAddrs = sinkDeviceTypeAddrs;
jiabin0a957d32020-04-29 10:56:20 -070010662 checkSilentMode_l();
jiabinc52b1ff2019-10-31 17:20:42 -070010663 } else {
10664 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
10665 mInDeviceTypeAddr = sourceDeviceTypeAddr;
10666 }
Phil Burk7f6b40d2017-02-09 13:18:38 -080010667 sp<MmapStreamCallback> callback = mCallback.promote();
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010668 if (mDeviceId != deviceId && callback != 0) {
Andy Hungc5007f82023-08-29 14:26:09 -070010669 mutex().unlock();
Phil Burk7f6b40d2017-02-09 13:18:38 -080010670 callback->onRoutingChanged(deviceId);
Andy Hungc5007f82023-08-29 14:26:09 -070010671 mutex().lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010672 }
jiabinc52b1ff2019-10-31 17:20:42 -070010673 mPatch = *patch;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010674 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010675 }
Eric Laurentdda206a2022-07-08 17:28:35 +020010676 // Force meteadata update after a route change
10677 mActiveTracks.setHasChanged();
10678
Eric Laurent6acd1d42017-01-04 14:23:29 -080010679 return status;
10680}
10681
Andy Hungee58e4a2023-07-07 13:47:37 -070010682status_t MmapThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010683{
10684 status_t status = NO_ERROR;
10685
jiabinc52b1ff2019-10-31 17:20:42 -070010686 mPatch = audio_patch{};
10687 mOutDeviceTypeAddrs.clear();
10688 mInDeviceTypeAddr.reset();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010689
10690 bool supportsAudioPatches = mHalDevice->supportsAudioPatches(&supportsAudioPatches) == OK ?
10691 supportsAudioPatches : false;
10692
10693 if (supportsAudioPatches) {
10694 status = mHalDevice->releaseAudioPatch(handle);
10695 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010696 status = mHalStream->legacyReleaseAudioPatch();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010697 }
Eric Laurentdda206a2022-07-08 17:28:35 +020010698 // Force meteadata update after a route change
10699 mActiveTracks.setHasChanged();
10700
Eric Laurent6acd1d42017-01-04 14:23:29 -080010701 return status;
10702}
10703
Andy Hungee58e4a2023-07-07 13:47:37 -070010704void MmapThread::toAudioPortConfig(struct audio_port_config* config)
Andy Hung3f49ebb2023-09-19 14:48:41 -070010705NO_THREAD_SAFETY_ANALYSIS // mAudioHwDev handle access
Eric Laurent6acd1d42017-01-04 14:23:29 -080010706{
Mikhail Naganovdc769682018-05-04 15:34:08 -070010707 ThreadBase::toAudioPortConfig(config);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010708 if (isOutput()) {
10709 config->role = AUDIO_PORT_ROLE_SOURCE;
10710 config->ext.mix.hw_module = mAudioHwDev->handle();
10711 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
10712 } else {
10713 config->role = AUDIO_PORT_ROLE_SINK;
10714 config->ext.mix.hw_module = mAudioHwDev->handle();
10715 config->ext.mix.usecase.source = mAudioSource;
10716 }
10717}
10718
Andy Hungee58e4a2023-07-07 13:47:37 -070010719status_t MmapThread::addEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010720{
10721 audio_session_t session = chain->sessionId();
10722
10723 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
10724 // Attach all tracks with same session ID to this chain.
10725 // indicate all active tracks in the chain
Andy Hung8d31fd22023-06-26 19:20:57 -070010726 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010727 if (session == track->sessionId()) {
10728 chain->incTrackCnt();
10729 chain->incActiveTrackCnt();
10730 }
10731 }
10732
10733 chain->setThread(this);
10734 chain->setInBuffer(nullptr);
10735 chain->setOutBuffer(nullptr);
Shunkai Yaod125e402024-01-20 03:19:06 +000010736 chain->syncHalEffectsState_l();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010737
10738 mEffectChains.add(chain);
10739 checkSuspendOnAddEffectChain_l(chain);
10740 return NO_ERROR;
10741}
10742
Andy Hungee58e4a2023-07-07 13:47:37 -070010743size_t MmapThread::removeEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010744{
10745 audio_session_t session = chain->sessionId();
10746
10747 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
10748
10749 for (size_t i = 0; i < mEffectChains.size(); i++) {
10750 if (chain == mEffectChains[i]) {
10751 mEffectChains.removeAt(i);
10752 // detach all active tracks from the chain
10753 // detach all tracks with same session ID from this chain
Andy Hung8d31fd22023-06-26 19:20:57 -070010754 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010755 if (session == track->sessionId()) {
10756 chain->decActiveTrackCnt();
10757 chain->decTrackCnt();
10758 }
10759 }
10760 break;
10761 }
10762 }
10763 return mEffectChains.size();
10764}
10765
Andy Hungee58e4a2023-07-07 13:47:37 -070010766void MmapThread::threadLoop_standby()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010767{
10768 mHalStream->standby();
10769}
10770
Andy Hungee58e4a2023-07-07 13:47:37 -070010771void MmapThread::threadLoop_exit()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010772{
Phil Burk7dce7282017-09-27 13:51:41 -070010773 // Do not call callback->onTearDown() because it is redundant for thread exit
10774 // and because it can cause a recursive mutex lock on stop().
Eric Laurent6acd1d42017-01-04 14:23:29 -080010775}
10776
Andy Hungee58e4a2023-07-07 13:47:37 -070010777status_t MmapThread::setSyncEvent(const sp<SyncEvent>& /* event */)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010778{
10779 return BAD_VALUE;
10780}
10781
Andy Hungee58e4a2023-07-07 13:47:37 -070010782bool MmapThread::isValidSyncEvent(
10783 const sp<SyncEvent>& /* event */) const
Eric Laurent6acd1d42017-01-04 14:23:29 -080010784{
10785 return false;
10786}
10787
Andy Hungee58e4a2023-07-07 13:47:37 -070010788status_t MmapThread::checkEffectCompatibility_l(
Eric Laurent6acd1d42017-01-04 14:23:29 -080010789 const effect_descriptor_t *desc, audio_session_t sessionId)
10790{
10791 // No global effect sessions on mmap threads
Eric Laurent3f75a5b2019-11-12 15:55:51 -080010792 if (audio_is_global_session(sessionId)) {
10793 ALOGW("checkEffectCompatibility_l(): global effect %s on MMAP thread %s",
Eric Laurent6acd1d42017-01-04 14:23:29 -080010794 desc->name, mThreadName);
10795 return BAD_VALUE;
10796 }
10797
10798 if (!isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC)) {
10799 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on capture mmap thread",
10800 desc->name);
10801 return BAD_VALUE;
10802 }
10803 if (isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Glenn Kastend3bb6452016-12-05 18:14:37 -080010804 ALOGW("checkEffectCompatibility_l(): pre processing effect %s created on playback mmap "
10805 "thread", desc->name);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010806 return BAD_VALUE;
10807 }
10808
10809 // Only allow effects without processing load or latency
10810 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) != EFFECT_FLAG_NO_PROCESS) {
10811 return BAD_VALUE;
10812 }
10813
Andy Hung116bc262023-06-20 18:56:17 -070010814 if (IAfEffectModule::isHapticGenerator(&desc->type)) {
jiabineb3bda02020-06-30 14:07:03 -070010815 ALOGE("%s(): HapticGenerator is not supported for MmapThread", __func__);
10816 return BAD_VALUE;
10817 }
10818
Eric Laurent6acd1d42017-01-04 14:23:29 -080010819 return NO_ERROR;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010820}
10821
Andy Hungee58e4a2023-07-07 13:47:37 -070010822void MmapThread::checkInvalidTracks_l()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010823{
Eric Laurent039c24a2022-10-07 14:01:59 +020010824 sp<MmapStreamCallback> callback;
Andy Hung8d31fd22023-06-26 19:20:57 -070010825 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010826 if (track->isInvalid()) {
Eric Laurent039c24a2022-10-07 14:01:59 +020010827 callback = mCallback.promote();
10828 if (callback == nullptr && mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
10829 ALOGW("Could not notify MMAP stream tear down: no onRoutingChanged callback!");
10830 mNoCallbackWarningCount++;
10831 }
10832 break;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010833 }
10834 }
Eric Laurent039c24a2022-10-07 14:01:59 +020010835 if (callback != 0) {
Andy Hungc5007f82023-08-29 14:26:09 -070010836 mutex().unlock();
Eric Laurent039c24a2022-10-07 14:01:59 +020010837 callback->onRoutingChanged(AUDIO_PORT_HANDLE_NONE);
Andy Hungc5007f82023-08-29 14:26:09 -070010838 mutex().lock();
jiabindfa32482022-10-06 19:45:50 +000010839 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010840}
10841
Andy Hungee58e4a2023-07-07 13:47:37 -070010842void MmapThread::dumpInternals_l(int fd, const Vector<String16>& /* args */)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010843{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010844 dprintf(fd, " Attributes: content type %d usage %d source %d\n",
10845 mAttr.content_type, mAttr.usage, mAttr.source);
10846 dprintf(fd, " Session: %d port Id: %d\n", mSessionId, mPortId);
Eric Tan39ec8d62018-07-24 09:49:29 -070010847 if (mActiveTracks.isEmpty()) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010848 dprintf(fd, " No active clients\n");
10849 }
10850}
10851
Andy Hungee58e4a2023-07-07 13:47:37 -070010852void MmapThread::dumpTracks_l(int fd, const Vector<String16>& /* args */)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010853{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010854 String8 result;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010855 size_t numtracks = mActiveTracks.size();
Andy Hung2c6c3bb2017-06-16 14:01:45 -070010856 dprintf(fd, " %zu Tracks\n", numtracks);
10857 const char *prefix = " ";
Eric Laurent6acd1d42017-01-04 14:23:29 -080010858 if (numtracks) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -070010859 result.append(prefix);
Kevin Rocard5f2136e2018-05-11 22:03:00 -070010860 mActiveTracks[0]->appendDumpHeader(result);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010861 for (size_t i = 0; i < numtracks ; ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -070010862 sp<IAfMmapTrack> track = mActiveTracks[i];
Andy Hung2c6c3bb2017-06-16 14:01:45 -070010863 result.append(prefix);
10864 track->appendDump(result, true /* active */);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010865 }
10866 } else {
10867 dprintf(fd, "\n");
10868 }
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +000010869 write(fd, result.c_str(), result.size());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010870}
10871
Andy Hungee58e4a2023-07-07 13:47:37 -070010872/* static */
10873sp<IAfMmapPlaybackThread> IAfMmapPlaybackThread::create(
Andy Hung583043b2023-07-17 17:05:00 -070010874 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
Andy Hungee58e4a2023-07-07 13:47:37 -070010875 AudioHwDevice* hwDev, AudioStreamOut* output, bool systemReady) {
Andy Hung583043b2023-07-17 17:05:00 -070010876 return sp<MmapPlaybackThread>::make(afThreadCallback, id, hwDev, output, systemReady);
Andy Hungee58e4a2023-07-07 13:47:37 -070010877}
10878
10879MmapPlaybackThread::MmapPlaybackThread(
Andy Hung583043b2023-07-17 17:05:00 -070010880 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
jiabinc52b1ff2019-10-31 17:20:42 -070010881 AudioHwDevice *hwDev, AudioStreamOut *output, bool systemReady)
Andy Hung583043b2023-07-17 17:05:00 -070010882 : MmapThread(afThreadCallback, id, hwDev, output->stream, systemReady, true /* isOut */),
Eric Laurent6acd1d42017-01-04 14:23:29 -080010883 mStreamType(AUDIO_STREAM_MUSIC),
Phil Burk56ecf3e2018-03-12 15:38:17 -070010884 mOutput(output)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010885{
10886 snprintf(mThreadName, kThreadNameLength, "AudioMmapOut_%X", id);
10887 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Andy Hung583043b2023-07-17 17:05:00 -070010888 mMasterVolume = afThreadCallback->masterVolume_l();
10889 mMasterMute = afThreadCallback->masterMute_l();
Eric Laurent1f9b5e62023-07-03 18:14:07 +020010890
10891 for (int i = AUDIO_STREAM_MIN; i < AUDIO_STREAM_FOR_POLICY_CNT; ++i) {
10892 const audio_stream_type_t stream{static_cast<audio_stream_type_t>(i)};
10893 mStreamTypes[stream].volume = 0.0f;
Andy Hung583043b2023-07-17 17:05:00 -070010894 mStreamTypes[stream].mute = mAfThreadCallback->streamMute_l(stream);
Eric Laurent1f9b5e62023-07-03 18:14:07 +020010895 }
10896 // Audio patch and call assistant volume are always max
10897 mStreamTypes[AUDIO_STREAM_PATCH].volume = 1.0f;
10898 mStreamTypes[AUDIO_STREAM_PATCH].mute = false;
10899 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].volume = 1.0f;
10900 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].mute = false;
10901
Eric Laurent6acd1d42017-01-04 14:23:29 -080010902 if (mAudioHwDev) {
10903 if (mAudioHwDev->canSetMasterVolume()) {
10904 mMasterVolume = 1.0;
10905 }
10906
10907 if (mAudioHwDev->canSetMasterMute()) {
10908 mMasterMute = false;
10909 }
10910 }
10911}
10912
Andy Hungee58e4a2023-07-07 13:47:37 -070010913void MmapPlaybackThread::configure(const audio_attributes_t* attr,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010914 audio_stream_type_t streamType,
10915 audio_session_t sessionId,
10916 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010917 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010918 audio_port_handle_t portId)
10919{
Andy Hung8d672e02023-09-15 18:19:28 -070010920 audio_utils::lock_guard l(mutex());
10921 MmapThread::configure_l(attr, streamType, sessionId, callback, deviceId, portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010922 mStreamType = streamType;
10923}
10924
Andy Hungee58e4a2023-07-07 13:47:37 -070010925AudioStreamOut* MmapPlaybackThread::clearOutput()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010926{
Andy Hung972bec12023-08-31 16:13:39 -070010927 audio_utils::lock_guard _l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010928 AudioStreamOut *output = mOutput;
10929 mOutput = NULL;
10930 return output;
10931}
10932
Andy Hungee58e4a2023-07-07 13:47:37 -070010933void MmapPlaybackThread::setMasterVolume(float value)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010934{
Andy Hung972bec12023-08-31 16:13:39 -070010935 audio_utils::lock_guard _l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010936 // Don't apply master volume in SW if our HAL can do it for us.
10937 if (mAudioHwDev &&
10938 mAudioHwDev->canSetMasterVolume()) {
10939 mMasterVolume = 1.0;
10940 } else {
10941 mMasterVolume = value;
10942 }
10943}
10944
Andy Hungee58e4a2023-07-07 13:47:37 -070010945void MmapPlaybackThread::setMasterMute(bool muted)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010946{
Andy Hung972bec12023-08-31 16:13:39 -070010947 audio_utils::lock_guard _l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010948 // Don't apply master mute in SW if our HAL can do it for us.
10949 if (mAudioHwDev && mAudioHwDev->canSetMasterMute()) {
10950 mMasterMute = false;
10951 } else {
10952 mMasterMute = muted;
10953 }
10954}
10955
Andy Hungee58e4a2023-07-07 13:47:37 -070010956void MmapPlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010957{
Andy Hung972bec12023-08-31 16:13:39 -070010958 audio_utils::lock_guard _l(mutex());
Eric Laurent1f9b5e62023-07-03 18:14:07 +020010959 mStreamTypes[stream].volume = value;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010960 if (stream == mStreamType) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010961 broadcast_l();
10962 }
10963}
10964
Andy Hungee58e4a2023-07-07 13:47:37 -070010965float MmapPlaybackThread::streamVolume(audio_stream_type_t stream) const
Eric Laurent6acd1d42017-01-04 14:23:29 -080010966{
Andy Hung972bec12023-08-31 16:13:39 -070010967 audio_utils::lock_guard _l(mutex());
Eric Laurent1f9b5e62023-07-03 18:14:07 +020010968 return mStreamTypes[stream].volume;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010969}
10970
Andy Hungee58e4a2023-07-07 13:47:37 -070010971void MmapPlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010972{
Andy Hung972bec12023-08-31 16:13:39 -070010973 audio_utils::lock_guard _l(mutex());
Eric Laurent1f9b5e62023-07-03 18:14:07 +020010974 mStreamTypes[stream].mute = muted;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010975 if (stream == mStreamType) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010976 broadcast_l();
10977 }
10978}
10979
Andy Hungee58e4a2023-07-07 13:47:37 -070010980void MmapPlaybackThread::invalidateTracks(audio_stream_type_t streamType)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010981{
Andy Hung972bec12023-08-31 16:13:39 -070010982 audio_utils::lock_guard _l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010983 if (streamType == mStreamType) {
Andy Hung8d31fd22023-06-26 19:20:57 -070010984 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010985 track->invalidate();
10986 }
10987 broadcast_l();
10988 }
10989}
10990
Andy Hungee58e4a2023-07-07 13:47:37 -070010991void MmapPlaybackThread::invalidateTracks(std::set<audio_port_handle_t>& portIds)
jiabinc44b3462022-12-08 12:52:31 -080010992{
Andy Hung972bec12023-08-31 16:13:39 -070010993 audio_utils::lock_guard _l(mutex());
jiabinc44b3462022-12-08 12:52:31 -080010994 bool trackMatch = false;
Andy Hung8d31fd22023-06-26 19:20:57 -070010995 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
jiabinc44b3462022-12-08 12:52:31 -080010996 if (portIds.find(track->portId()) != portIds.end()) {
10997 track->invalidate();
10998 trackMatch = true;
10999 portIds.erase(track->portId());
11000 }
11001 if (portIds.empty()) {
11002 break;
11003 }
11004 }
11005 if (trackMatch) {
11006 broadcast_l();
11007 }
11008}
11009
Andy Hungee58e4a2023-07-07 13:47:37 -070011010void MmapPlaybackThread::processVolume_l()
Andy Hung920f6572022-10-06 12:09:49 -070011011NO_THREAD_SAFETY_ANALYSIS // access of track->processMuteEvent_l
Eric Laurent6acd1d42017-01-04 14:23:29 -080011012{
11013 float volume;
11014
Eric Laurent1f9b5e62023-07-03 18:14:07 +020011015 if (mMasterMute || streamMuted_l()) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080011016 volume = 0;
11017 } else {
Eric Laurent1f9b5e62023-07-03 18:14:07 +020011018 volume = mMasterVolume * streamVolume_l();
Eric Laurent6acd1d42017-01-04 14:23:29 -080011019 }
11020
11021 if (volume != mHalVolFloat) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080011022 // Convert volumes from float to 8.24
11023 uint32_t vol = (uint32_t)(volume * (1 << 24));
11024
11025 // Delegate volume control to effect in track effect chain if needed
11026 // only one effect chain can be present on DirectOutputThread, so if
11027 // there is one, the track is connected to it
11028 if (!mEffectChains.isEmpty()) {
Shunkai Yaof4847652024-01-12 00:25:20 +000011029 mEffectChains[0]->setVolume(&vol, &vol);
Eric Laurent6acd1d42017-01-04 14:23:29 -080011030 volume = (float)vol / (1 << 24);
11031 }
Eric Laurentdff774a2017-04-21 15:29:38 -070011032 // Try to use HW volume control and fall back to SW control if not implemented
Phil Burk56ecf3e2018-03-12 15:38:17 -070011033 if (mOutput->stream->setVolume(volume, volume) == NO_ERROR) {
11034 mHalVolFloat = volume; // HW volume control worked, so update value.
11035 mNoCallbackWarningCount = 0;
11036 } else {
Eric Laurentdff774a2017-04-21 15:29:38 -070011037 sp<MmapStreamCallback> callback = mCallback.promote();
11038 if (callback != 0) {
Phil Burk56ecf3e2018-03-12 15:38:17 -070011039 mHalVolFloat = volume; // SW volume control worked, so update value.
11040 mNoCallbackWarningCount = 0;
Andy Hungc5007f82023-08-29 14:26:09 -070011041 mutex().unlock();
Robert Wu4389ae62022-02-17 18:39:41 +000011042 callback->onVolumeChanged(volume);
Andy Hungc5007f82023-08-29 14:26:09 -070011043 mutex().lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080011044 } else {
Phil Burk56ecf3e2018-03-12 15:38:17 -070011045 if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
11046 ALOGW("Could not set MMAP stream volume: no volume callback!");
11047 mNoCallbackWarningCount++;
11048 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080011049 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080011050 }
Andy Hung8d31fd22023-06-26 19:20:57 -070011051 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Jasmine Chaeaa10e42021-05-11 10:11:14 +080011052 track->setMetadataHasChanged();
Andy Hung583043b2023-07-17 17:05:00 -070011053 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
Vlad Popaec1788e2022-08-04 11:23:30 +020011054 /*muteState=*/{mMasterMute,
Eric Laurent1f9b5e62023-07-03 18:14:07 +020011055 streamVolume_l() == 0.f,
11056 streamMuted_l(),
Vlad Popaec1788e2022-08-04 11:23:30 +020011057 // TODO(b/241533526): adjust logic to include mute from AppOps
11058 false /*muteFromPlaybackRestricted*/,
11059 false /*muteFromClientVolume*/,
11060 false /*muteFromVolumeShaper*/});
Jasmine Chaeaa10e42021-05-11 10:11:14 +080011061 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080011062 }
11063}
11064
Andy Hungee58e4a2023-07-07 13:47:37 -070011065ThreadBase::MetadataUpdate MmapPlaybackThread::updateMetadata_l()
Kevin Rocard069c2712018-03-29 19:09:14 -070011066{
Jasmine Chaeaa10e42021-05-11 10:11:14 +080011067 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
Vlad Popa7e81cea2023-01-19 16:34:16 +010011068 return {}; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -070011069 }
11070 StreamOutHalInterface::SourceMetadata metadata;
Andy Hung8d31fd22023-06-26 19:20:57 -070011071 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Kevin Rocard069c2712018-03-29 19:09:14 -070011072 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurent94579172020-11-20 18:41:04 +010011073 playback_track_metadata_v7_t trackMetadata;
11074 trackMetadata.base = {
Kevin Rocard069c2712018-03-29 19:09:14 -070011075 .usage = track->attributes().usage,
11076 .content_type = track->attributes().content_type,
11077 .gain = mHalVolFloat, // TODO: propagate from aaudio pre-mix volume
Eric Laurent94579172020-11-20 18:41:04 +010011078 };
11079 trackMetadata.channel_mask = track->channelMask(),
11080 strncpy(trackMetadata.tags, track->attributes().tags, AUDIO_ATTRIBUTES_TAGS_MAX_SIZE);
11081 metadata.tracks.push_back(trackMetadata);
Kevin Rocard069c2712018-03-29 19:09:14 -070011082 }
11083 mOutput->stream->updateSourceMetadata(metadata);
Vlad Popa7e81cea2023-01-19 16:34:16 +010011084
11085 MetadataUpdate change;
11086 change.playbackMetadataUpdate = metadata.tracks;
11087 return change;
11088};
Kevin Rocard069c2712018-03-29 19:09:14 -070011089
Andy Hungee58e4a2023-07-07 13:47:37 -070011090void MmapPlaybackThread::checkSilentMode_l()
Eric Laurent6acd1d42017-01-04 14:23:29 -080011091{
11092 if (!mMasterMute) {
11093 char value[PROPERTY_VALUE_MAX];
11094 if (property_get("ro.audio.silent", value, "0") > 0) {
11095 char *endptr;
11096 unsigned long ul = strtoul(value, &endptr, 0);
11097 if (*endptr == '\0' && ul != 0) {
11098 ALOGD("Silence is golden");
11099 // The setprop command will not allow a property to be changed after
11100 // the first time it is set, so we don't have to worry about un-muting.
11101 setMasterMute_l(true);
11102 }
11103 }
11104 }
11105}
11106
Andy Hungee58e4a2023-07-07 13:47:37 -070011107void MmapPlaybackThread::toAudioPortConfig(struct audio_port_config* config)
Mikhail Naganov32abc2b2018-05-24 12:57:11 -070011108{
11109 MmapThread::toAudioPortConfig(config);
11110 if (mOutput && mOutput->flags != AUDIO_OUTPUT_FLAG_NONE) {
11111 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
11112 config->flags.output = mOutput->flags;
11113 }
11114}
11115
Andy Hungee58e4a2023-07-07 13:47:37 -070011116status_t MmapPlaybackThread::getExternalPosition(uint64_t* position,
Andy Hung440901d2023-06-29 21:19:25 -070011117 int64_t* timeNanos) const
jiabinb7d8c5a2020-08-26 17:24:52 -070011118{
11119 if (mOutput == nullptr) {
11120 return NO_INIT;
11121 }
11122 struct timespec timestamp;
11123 status_t status = mOutput->getPresentationPosition(position, &timestamp);
11124 if (status == NO_ERROR) {
11125 *timeNanos = timestamp.tv_sec * NANOS_PER_SECOND + timestamp.tv_nsec;
11126 }
11127 return status;
11128}
11129
Andy Hungee58e4a2023-07-07 13:47:37 -070011130status_t MmapPlaybackThread::reportData(const void* buffer, size_t frameCount) {
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010011131 // Send to MelProcessor for sound dose measurement.
11132 auto processor = mMelProcessor.load();
11133 if (processor) {
11134 processor->process(buffer, frameCount * mFrameSize);
11135 }
11136
jiabinfc791ee2023-02-15 19:43:40 +000011137 return NO_ERROR;
11138}
11139
Andy Hungc5007f82023-08-29 14:26:09 -070011140// startMelComputation_l() must be called with AudioFlinger::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -070011141void MmapPlaybackThread::startMelComputation_l(
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010011142 const sp<audio_utils::MelProcessor>& processor)
11143{
11144 ALOGV("%s: starting mel processor for thread %d", __func__, id());
Vlad Popa1c2f7e12023-03-28 02:08:56 +020011145 mMelProcessor.store(processor);
11146 if (processor) {
11147 processor->resume();
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010011148 }
Vlad Popa1c2f7e12023-03-28 02:08:56 +020011149
11150 // no need to update output format for MMapPlaybackThread since it is
11151 // assigned constant for each thread
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010011152}
11153
Andy Hungc5007f82023-08-29 14:26:09 -070011154// stopMelComputation_l() must be called with AudioFlinger::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -070011155void MmapPlaybackThread::stopMelComputation_l()
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010011156{
Vlad Popa1c2f7e12023-03-28 02:08:56 +020011157 ALOGV("%s: pausing mel processor for thread %d", __func__, id());
11158 auto melProcessor = mMelProcessor.load();
11159 if (melProcessor != nullptr) {
11160 melProcessor->pause();
11161 }
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010011162}
11163
Andy Hungee58e4a2023-07-07 13:47:37 -070011164void MmapPlaybackThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent6acd1d42017-01-04 14:23:29 -080011165{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -070011166 MmapThread::dumpInternals_l(fd, args);
Eric Laurent6acd1d42017-01-04 14:23:29 -080011167
Glenn Kastend3bb6452016-12-05 18:14:37 -080011168 dprintf(fd, " Stream type: %d Stream volume: %f HAL volume: %f Stream mute %d\n",
Eric Laurent1f9b5e62023-07-03 18:14:07 +020011169 mStreamType, streamVolume_l(), mHalVolFloat, streamMuted_l());
Eric Laurent6acd1d42017-01-04 14:23:29 -080011170 dprintf(fd, " Master volume: %f Master mute %d\n", mMasterVolume, mMasterMute);
11171}
11172
Andy Hungee58e4a2023-07-07 13:47:37 -070011173/* static */
11174sp<IAfMmapCaptureThread> IAfMmapCaptureThread::create(
Andy Hung583043b2023-07-17 17:05:00 -070011175 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
Andy Hungee58e4a2023-07-07 13:47:37 -070011176 AudioHwDevice* hwDev, AudioStreamIn* input, bool systemReady) {
Andy Hung583043b2023-07-17 17:05:00 -070011177 return sp<MmapCaptureThread>::make(afThreadCallback, id, hwDev, input, systemReady);
Andy Hungee58e4a2023-07-07 13:47:37 -070011178}
11179
11180MmapCaptureThread::MmapCaptureThread(
Andy Hung583043b2023-07-17 17:05:00 -070011181 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
jiabinc52b1ff2019-10-31 17:20:42 -070011182 AudioHwDevice *hwDev, AudioStreamIn *input, bool systemReady)
Andy Hung583043b2023-07-17 17:05:00 -070011183 : MmapThread(afThreadCallback, id, hwDev, input->stream, systemReady, false /* isOut */),
Eric Laurent6acd1d42017-01-04 14:23:29 -080011184 mInput(input)
11185{
11186 snprintf(mThreadName, kThreadNameLength, "AudioMmapIn_%X", id);
11187 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
11188}
11189
Andy Hungee58e4a2023-07-07 13:47:37 -070011190status_t MmapCaptureThread::exitStandby_l()
Eric Laurent331679c2018-04-16 17:03:16 -070011191{
Phil Burkf054fc32018-12-06 09:45:59 -080011192 {
11193 // mInput might have been cleared by clearInput()
Phil Burkf054fc32018-12-06 09:45:59 -080011194 if (mInput != nullptr && mInput->stream != nullptr) {
11195 mInput->stream->setGain(1.0f);
11196 }
11197 }
Eric Laurentdda206a2022-07-08 17:28:35 +020011198 return MmapThread::exitStandby_l();
Eric Laurent331679c2018-04-16 17:03:16 -070011199}
11200
Andy Hungee58e4a2023-07-07 13:47:37 -070011201AudioStreamIn* MmapCaptureThread::clearInput()
Eric Laurent6acd1d42017-01-04 14:23:29 -080011202{
Andy Hung972bec12023-08-31 16:13:39 -070011203 audio_utils::lock_guard _l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080011204 AudioStreamIn *input = mInput;
11205 mInput = NULL;
11206 return input;
11207}
Kevin Rocard069c2712018-03-29 19:09:14 -070011208
Andy Hungee58e4a2023-07-07 13:47:37 -070011209void MmapCaptureThread::processVolume_l()
Eric Laurent331679c2018-04-16 17:03:16 -070011210{
11211 bool changed = false;
11212 bool silenced = false;
11213
11214 sp<MmapStreamCallback> callback = mCallback.promote();
11215 if (callback == 0) {
11216 if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
11217 ALOGW("Could not set MMAP stream silenced: no onStreamSilenced callback!");
11218 mNoCallbackWarningCount++;
11219 }
11220 }
11221
11222 // After a change occurred in track silenced state, mute capture in audio DSP if at least one
11223 // track is silenced and unmute otherwise
11224 for (size_t i = 0; i < mActiveTracks.size() && !silenced; i++) {
11225 if (!mActiveTracks[i]->getAndSetSilencedNotified_l()) {
11226 changed = true;
11227 silenced = mActiveTracks[i]->isSilenced_l();
11228 }
11229 }
11230
11231 if (changed) {
11232 mInput->stream->setGain(silenced ? 0.0f: 1.0f);
11233 }
11234}
11235
Andy Hungee58e4a2023-07-07 13:47:37 -070011236ThreadBase::MetadataUpdate MmapCaptureThread::updateMetadata_l()
Kevin Rocard069c2712018-03-29 19:09:14 -070011237{
Jasmine Chaeaa10e42021-05-11 10:11:14 +080011238 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
Vlad Popa7e81cea2023-01-19 16:34:16 +010011239 return {}; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -070011240 }
11241 StreamInHalInterface::SinkMetadata metadata;
Andy Hung8d31fd22023-06-26 19:20:57 -070011242 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Kevin Rocard069c2712018-03-29 19:09:14 -070011243 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurent94579172020-11-20 18:41:04 +010011244 record_track_metadata_v7_t trackMetadata;
11245 trackMetadata.base = {
Kevin Rocard069c2712018-03-29 19:09:14 -070011246 .source = track->attributes().source,
11247 .gain = 1, // capture tracks do not have volumes
Eric Laurent94579172020-11-20 18:41:04 +010011248 };
11249 trackMetadata.channel_mask = track->channelMask(),
11250 strncpy(trackMetadata.tags, track->attributes().tags, AUDIO_ATTRIBUTES_TAGS_MAX_SIZE);
11251 metadata.tracks.push_back(trackMetadata);
Kevin Rocard069c2712018-03-29 19:09:14 -070011252 }
11253 mInput->stream->updateSinkMetadata(metadata);
Vlad Popa7e81cea2023-01-19 16:34:16 +010011254 MetadataUpdate change;
11255 change.recordMetadataUpdate = metadata.tracks;
11256 return change;
Kevin Rocard069c2712018-03-29 19:09:14 -070011257}
11258
Andy Hungee58e4a2023-07-07 13:47:37 -070011259void MmapCaptureThread::setRecordSilenced(audio_port_handle_t portId, bool silenced)
Eric Laurent331679c2018-04-16 17:03:16 -070011260{
Andy Hung972bec12023-08-31 16:13:39 -070011261 audio_utils::lock_guard _l(mutex());
Eric Laurent331679c2018-04-16 17:03:16 -070011262 for (size_t i = 0; i < mActiveTracks.size() ; i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -070011263 if (mActiveTracks[i]->portId() == portId) {
Eric Laurent331679c2018-04-16 17:03:16 -070011264 mActiveTracks[i]->setSilenced_l(silenced);
11265 broadcast_l();
11266 }
11267 }
jiabin09609032022-06-15 19:26:01 +000011268 setClientSilencedIfExists_l(portId, silenced);
Eric Laurent331679c2018-04-16 17:03:16 -070011269}
11270
Andy Hungee58e4a2023-07-07 13:47:37 -070011271void MmapCaptureThread::toAudioPortConfig(struct audio_port_config* config)
Mikhail Naganov32abc2b2018-05-24 12:57:11 -070011272{
11273 MmapThread::toAudioPortConfig(config);
11274 if (mInput && mInput->flags != AUDIO_INPUT_FLAG_NONE) {
11275 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
11276 config->flags.input = mInput->flags;
11277 }
11278}
11279
Andy Hungee58e4a2023-07-07 13:47:37 -070011280status_t MmapCaptureThread::getExternalPosition(
Andy Hung440901d2023-06-29 21:19:25 -070011281 uint64_t* position, int64_t* timeNanos) const
jiabinb7d8c5a2020-08-26 17:24:52 -070011282{
11283 if (mInput == nullptr) {
11284 return NO_INIT;
11285 }
11286 return mInput->getCapturePosition((int64_t*)position, timeNanos);
11287}
11288
jiabinc658e452022-10-21 20:52:21 +000011289// ----------------------------------------------------------------------------
11290
Andy Hungee58e4a2023-07-07 13:47:37 -070011291/* static */
11292sp<IAfPlaybackThread> IAfPlaybackThread::createBitPerfectThread(
Andy Hung583043b2023-07-17 17:05:00 -070011293 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hungee58e4a2023-07-07 13:47:37 -070011294 AudioStreamOut* output, audio_io_handle_t id, bool systemReady) {
Andy Hung583043b2023-07-17 17:05:00 -070011295 return sp<BitPerfectThread>::make(afThreadCallback, output, id, systemReady);
Andy Hungee58e4a2023-07-07 13:47:37 -070011296}
11297
Andy Hung583043b2023-07-17 17:05:00 -070011298BitPerfectThread::BitPerfectThread(const sp<IAfThreadCallback> &afThreadCallback,
jiabinc658e452022-10-21 20:52:21 +000011299 AudioStreamOut *output, audio_io_handle_t id, bool systemReady)
Andy Hung583043b2023-07-17 17:05:00 -070011300 : MixerThread(afThreadCallback, output, id, systemReady, BIT_PERFECT) {}
jiabinc658e452022-10-21 20:52:21 +000011301
Andy Hungee58e4a2023-07-07 13:47:37 -070011302PlaybackThread::mixer_state BitPerfectThread::prepareTracks_l(
Andy Hung8d31fd22023-06-26 19:20:57 -070011303 Vector<sp<IAfTrack>>* tracksToRemove) {
jiabinc658e452022-10-21 20:52:21 +000011304 mixer_state result = MixerThread::prepareTracks_l(tracksToRemove);
11305 // If there is only one active track and it is bit-perfect, enable tee buffer.
jiabin76d94692022-12-15 21:51:21 +000011306 float volumeLeft = 1.0f;
11307 float volumeRight = 1.0f;
jiabinc658e452022-10-21 20:52:21 +000011308 if (mActiveTracks.size() == 1 && mActiveTracks[0]->isBitPerfect()) {
11309 const int trackId = mActiveTracks[0]->id();
11310 mAudioMixer->setParameter(
11311 trackId, AudioMixer::TRACK, AudioMixer::TEE_BUFFER, (void *)mSinkBuffer);
11312 mAudioMixer->setParameter(
11313 trackId, AudioMixer::TRACK, AudioMixer::TEE_BUFFER_FRAME_COUNT,
11314 (void *)(uintptr_t)mNormalFrameCount);
jiabin76d94692022-12-15 21:51:21 +000011315 mActiveTracks[0]->getFinalVolume(&volumeLeft, &volumeRight);
jiabinc658e452022-10-21 20:52:21 +000011316 mIsBitPerfect = true;
11317 } else {
11318 mIsBitPerfect = false;
11319 // No need to copy bit-perfect data directly to sink buffer given there are multiple tracks
11320 // active.
11321 for (const auto& track : mActiveTracks) {
11322 const int trackId = track->id();
11323 mAudioMixer->setParameter(
11324 trackId, AudioMixer::TRACK, AudioMixer::TEE_BUFFER, nullptr);
11325 }
11326 }
jiabin76d94692022-12-15 21:51:21 +000011327 if (mVolumeLeft != volumeLeft || mVolumeRight != volumeRight) {
11328 mVolumeLeft = volumeLeft;
11329 mVolumeRight = volumeRight;
11330 setVolumeForOutput_l(volumeLeft, volumeRight);
11331 }
jiabinc658e452022-10-21 20:52:21 +000011332 return result;
11333}
11334
Andy Hungee58e4a2023-07-07 13:47:37 -070011335void BitPerfectThread::threadLoop_mix() {
jiabinc658e452022-10-21 20:52:21 +000011336 MixerThread::threadLoop_mix();
11337 mHasDataCopiedToSinkBuffer = mIsBitPerfect;
11338}
11339
Glenn Kasten63238ef2015-03-02 15:50:29 -080011340} // namespace android