blob: 29df1d842f7af92ea91df3caa73aa9aa0aa1ea0c [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
Glenn Kasten153b9fe2013-07-15 11:23:36 -070023#include "Configuration.h"
Eric Laurent81784c32012-11-19 14:55:58 -080024#include <math.h>
25#include <fcntl.h>
Eric Tan7b651152018-07-13 10:17:19 -070026#include <memory>
Andy Hungb68f5eb2019-12-03 16:49:17 -080027#include <sstream>
Eric Tan7b651152018-07-13 10:17:19 -070028#include <string>
Glenn Kastenad8510a2015-02-17 16:24:07 -080029#include <linux/futex.h>
Eric Laurent81784c32012-11-19 14:55:58 -080030#include <sys/stat.h>
Glenn Kastenad8510a2015-02-17 16:24:07 -080031#include <sys/syscall.h>
Glenn Kastenc9a23672020-06-30 12:12:42 -070032#include <cutils/bitops.h>
Eric Laurent81784c32012-11-19 14:55:58 -080033#include <cutils/properties.h>
Vlad Popae8d99472022-06-30 16:02:48 +020034#include <binder/PersistableBundle.h>
jiabinc52b1ff2019-10-31 17:20:42 -070035#include <media/AudioContainers.h>
36#include <media/AudioDeviceTypeAddr.h>
Glenn Kasten1ab85ec2013-05-31 09:18:43 -070037#include <media/AudioParameter.h>
Andy Hungcd044842014-08-07 11:04:34 -070038#include <media/AudioResamplerPublic.h>
Andy Hung89816052017-01-11 17:08:23 -080039#include <media/RecordBufferConverter.h>
Mikhail Naganov913d06c2016-11-01 12:49:22 -070040#include <media/TypeConverter.h>
Eric Laurent81784c32012-11-19 14:55:58 -080041#include <utils/Log.h>
Alex Ray371eb972012-11-30 11:11:54 -080042#include <utils/Trace.h>
Eric Laurent81784c32012-11-19 14:55:58 -080043
44#include <private/media/AudioTrackShared.h>
Wei Jiaf2ae3e12016-10-27 17:10:59 -070045#include <private/android_filesystem_config.h>
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +010046#include <audio_utils/Balance.h>
Vlad Popab042ee62022-10-20 18:05:00 +020047#include <audio_utils/MelProcessor.h>
jiabinf6eb4c32020-02-25 14:06:25 -080048#include <audio_utils/Metadata.h>
jiabin245cdd92018-12-07 17:55:15 -080049#include <audio_utils/channels.h>
Glenn Kasten6bf707f2017-02-23 16:53:58 -080050#include <audio_utils/mono_blend.h>
Eric Laurent81784c32012-11-19 14:55:58 -080051#include <audio_utils/primitives.h>
Andy Hung98ef9782014-03-04 14:46:50 -080052#include <audio_utils/format.h>
Glenn Kastenc56f3422014-03-21 17:53:17 -070053#include <audio_utils/minifloat.h>
Hongwei Wang95e37682019-04-12 11:13:36 -070054#include <audio_utils/safe_math.h>
Mikhail Naganov9fe94012016-10-14 14:57:40 -070055#include <system/audio_effects/effect_aec.h>
Eric Laurentb3f315a2021-07-13 15:09:05 +020056#include <system/audio_effects/effect_downmix.h>
57#include <system/audio_effects/effect_ns.h>
Eric Laurent1c5e2e32021-08-18 18:50:28 +020058#include <system/audio_effects/effect_spatializer.h>
Mikhail Naganovcbc8f612016-10-11 18:05:13 -070059#include <system/audio.h>
Eric Laurent81784c32012-11-19 14:55:58 -080060
61// NBAIO implementations
Glenn Kasten6dbb5e32014-05-13 10:38:42 -070062#include <media/nbaio/AudioStreamInSource.h>
Eric Laurent81784c32012-11-19 14:55:58 -080063#include <media/nbaio/AudioStreamOutSink.h>
64#include <media/nbaio/MonoPipe.h>
65#include <media/nbaio/MonoPipeReader.h>
66#include <media/nbaio/Pipe.h>
67#include <media/nbaio/PipeReader.h>
68#include <media/nbaio/SourceAudioBufferProvider.h>
Wei Jia3f273d12015-11-24 09:06:49 -080069#include <mediautils/BatteryNotifier.h>
Andy Hungafc51db2022-04-08 17:33:40 -070070#include <mediautils/Process.h>
Eric Laurent81784c32012-11-19 14:55:58 -080071
Mikhail Naganov2996f672019-04-18 12:29:59 -070072#include <audiomanager/AudioManager.h>
Eric Laurent81784c32012-11-19 14:55:58 -080073#include <powermanager/PowerManager.h>
74
Kevin Rocard7588ff42018-01-08 11:11:30 -080075#include <media/audiohal/EffectsFactoryHalInterface.h>
Kevin Rocard069c2712018-03-29 19:09:14 -070076#include <media/audiohal/StreamHalInterface.h>
Kevin Rocard7588ff42018-01-08 11:11:30 -080077
Eric Laurent81784c32012-11-19 14:55:58 -080078#include "AudioFlinger.h"
Andy Hungee58e4a2023-07-07 13:47:37 -070079#include "Threads.h"
80
Andy Hungab7ef302018-05-15 19:35:29 -070081#include <mediautils/SchedulingPolicyService.h>
82#include <mediautils/ServiceUtilities.h>
Eric Laurent81784c32012-11-19 14:55:58 -080083
Eric Laurent81784c32012-11-19 14:55:58 -080084#ifdef ADD_BATTERY_DATA
85#include <media/IMediaPlayerService.h>
86#include <media/IMediaDeathNotifier.h>
87#endif
88
Eric Laurent81784c32012-11-19 14:55:58 -080089#ifdef DEBUG_CPU_USAGE
Eric Tan5b13ff82018-07-27 11:20:17 -070090#include <audio_utils/Statistics.h>
Eric Laurent81784c32012-11-19 14:55:58 -080091#include <cpustats/ThreadCpuUsage.h>
92#endif
93
Andy Hungd69d9f12023-05-23 17:36:46 -070094#include <fastpath/AutoPark.h>
Glenn Kastenc05b8d72016-03-24 09:48:17 -070095
Nicolas Rouletfe1e1442017-01-30 12:02:03 -080096#include <pthread.h>
Andy Hung0a51b5c2023-07-18 20:54:44 -070097#include <afutils/DumpTryLock.h>
Andy Hung0077d8c2023-05-24 11:53:47 -070098#include <afutils/TypedLogger.h>
Nicolas Rouletfe1e1442017-01-30 12:02:03 -080099
Eric Laurent81784c32012-11-19 14:55:58 -0800100// ----------------------------------------------------------------------------
101
102// Note: the following macro is used for extremely verbose logging message. In
103// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
104// 0; but one side effect of this is to turn all LOGV's as well. Some messages
105// are so verbose that we want to suppress them even when we have ALOG_ASSERT
106// turned on. Do not uncomment the #def below unless you really know what you
107// are doing and want to see all of the extremely verbose messages.
108//#define VERY_VERY_VERBOSE_LOGGING
109#ifdef VERY_VERY_VERBOSE_LOGGING
110#define ALOGVV ALOGV
111#else
112#define ALOGVV(a...) do { } while(0)
113#endif
114
Andy Hung6770c6f2015-04-07 13:43:36 -0700115// TODO: Move these macro/inlines to a header file.
Glenn Kasten49d00ad2014-07-21 11:22:03 -0700116#define max(a, b) ((a) > (b) ? (a) : (b))
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700117
Andy Hung6770c6f2015-04-07 13:43:36 -0700118template <typename T>
119static inline T min(const T& a, const T& b)
120{
121 return a < b ? a : b;
122}
Glenn Kasten49d00ad2014-07-21 11:22:03 -0700123
Eric Laurent81784c32012-11-19 14:55:58 -0800124namespace android {
125
Andy Hungee58e4a2023-07-07 13:47:37 -0700126using audioflinger::SyncEvent;
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -0700127using media::IEffectClient;
Svet Ganov33761132021-05-13 22:51:08 +0000128using content::AttributionSourceState;
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -0700129
Eric Laurent81784c32012-11-19 14:55:58 -0800130// retry counts for buffer fill timeout
131// 50 * ~20msecs = 1 second
132static const int8_t kMaxTrackRetries = 50;
133static const int8_t kMaxTrackStartupRetries = 50;
Andy Hung455982f2021-04-27 17:46:12 -0700134
Eric Laurent81784c32012-11-19 14:55:58 -0800135// allow less retry attempts on direct output thread.
136// direct outputs can be a scarce resource in audio hardware and should
137// be released as quickly as possible.
Andy Hung455982f2021-04-27 17:46:12 -0700138// Notes:
139// 1) The retry duration kMaxTrackRetriesDirectMs may be increased
140// in case the data write is bursty for the AudioTrack. The application
141// should endeavor to write at least once every kMaxTrackRetriesDirectMs
142// to prevent an underrun situation. If the data is bursty, then
143// the application can also throttle the data sent to be even.
144// 2) For compressed audio data, any data present in the AudioTrack buffer
145// will be sent and reset the retry count. This delivers data as
146// it arrives, with approximately kDirectMinSleepTimeUs = 10ms checking interval.
147// 3) For linear PCM or proportional PCM, we wait one period for a period's worth
148// of data to be available, then any remaining data is delivered.
149// This is required to ensure the last bit of data is delivered before underrun.
150//
151// Sleep time per cycle is kDirectMinSleepTimeUs for compressed tracks
152// or the size of the HAL period for proportional / linear PCM tracks.
153static const int32_t kMaxTrackRetriesDirectMs = 200;
Eric Laurent81784c32012-11-19 14:55:58 -0800154
155// don't warn about blocked writes or record buffer overflows more often than this
156static const nsecs_t kWarningThrottleNs = seconds(5);
157
158// RecordThread loop sleep time upon application overrun or audio HAL read error
159static const int kRecordThreadSleepUs = 5000;
160
Eric Laurent10351942014-05-08 18:49:52 -0700161// maximum time to wait in sendConfigEvent_l() for a status to be received
162static const nsecs_t kConfigEventTimeoutNs = seconds(2);
Eric Laurent81784c32012-11-19 14:55:58 -0800163
164// minimum sleep time for the mixer thread loop when tracks are active but in underrun
165static const uint32_t kMinThreadSleepTimeUs = 5000;
166// maximum divider applied to the active sleep time in the mixer thread loop
167static const uint32_t kMaxThreadSleepTimeShift = 2;
168
Andy Hung09a50072014-02-27 14:30:47 -0800169// minimum normal sink buffer size, expressed in milliseconds rather than frames
Glenn Kasteneb9487e2015-07-22 09:15:17 -0700170// FIXME This should be based on experimentally observed scheduling jitter
Andy Hung09a50072014-02-27 14:30:47 -0800171static const uint32_t kMinNormalSinkBufferSizeMs = 20;
172// maximum normal sink buffer size
173static const uint32_t kMaxNormalSinkBufferSizeMs = 24;
Eric Laurent81784c32012-11-19 14:55:58 -0800174
Glenn Kasteneb9487e2015-07-22 09:15:17 -0700175// minimum capture buffer size in milliseconds to _not_ need a fast capture thread
176// FIXME This should be based on experimentally observed scheduling jitter
177static const uint32_t kMinNormalCaptureBufferSizeMs = 12;
178
Eric Laurent972a1732013-09-04 09:42:59 -0700179// Offloaded output thread standby delay: allows track transition without going to standby
180static const nsecs_t kOffloadStandbyDelayNs = seconds(1);
181
Eric Laurent51716182016-02-29 18:00:56 -0800182// Direct output thread minimum sleep time in idle or active(underrun) state
183static const nsecs_t kDirectMinSleepTimeUs = 10000;
184
Brian Lindahl65e90012022-07-27 18:01:07 +0200185// Minimum amount of time between checking to see if the timestamp is advancing
186// for underrun detection. If we check too frequently, we may not detect a
187// timestamp update and will falsely detect underrun.
188static const nsecs_t kMinimumTimeBetweenTimestampChecksNs = 150 /* ms */ * 1000;
189
Glenn Kasten1b291842016-07-18 14:55:21 -0700190// The universal constant for ubiquitous 20ms value. The value of 20ms seems to provide a good
191// balance between power consumption and latency, and allows threads to be scheduled reliably
192// by the CFS scheduler.
193// FIXME Express other hardcoded references to 20ms with references to this constant and move
194// it appropriately.
195#define FMS_20 20
Eric Laurent51716182016-02-29 18:00:56 -0800196
Eric Laurent81784c32012-11-19 14:55:58 -0800197// Whether to use fast mixer
198static const enum {
199 FastMixer_Never, // never initialize or use: for debugging only
200 FastMixer_Always, // always initialize and use, even if not needed: for debugging only
201 // normal mixer multiplier is 1
202 FastMixer_Static, // initialize if needed, then use all the time if initialized,
203 // multiplier is calculated based on min & max normal mixer buffer size
204 FastMixer_Dynamic, // initialize if needed, then use dynamically depending on track load,
205 // multiplier is calculated based on min & max normal mixer buffer size
206 // FIXME for FastMixer_Dynamic:
207 // Supporting this option will require fixing HALs that can't handle large writes.
208 // For example, one HAL implementation returns an error from a large write,
209 // and another HAL implementation corrupts memory, possibly in the sample rate converter.
210 // We could either fix the HAL implementations, or provide a wrapper that breaks
211 // up large writes into smaller ones, and the wrapper would need to deal with scheduler.
212} kUseFastMixer = FastMixer_Static;
213
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700214// Whether to use fast capture
215static const enum {
216 FastCapture_Never, // never initialize or use: for debugging only
217 FastCapture_Always, // always initialize and use, even if not needed: for debugging only
218 FastCapture_Static, // initialize if needed, then use all the time if initialized
219} kUseFastCapture = FastCapture_Static;
220
Eric Laurent81784c32012-11-19 14:55:58 -0800221// Priorities for requestPriority
222static const int kPriorityAudioApp = 2;
223static const int kPriorityFastMixer = 3;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700224static const int kPriorityFastCapture = 3;
Eric Laurent81784c32012-11-19 14:55:58 -0800225
Glenn Kastenea38ee72016-04-18 11:08:01 -0700226// IAudioFlinger::createTrack() has an in/out parameter 'pFrameCount' for the total size of the
227// track buffer in shared memory. Zero on input means to use a default value. For fast tracks,
228// AudioFlinger derives the default from HAL buffer size and 'fast track multiplier'.
Glenn Kasten03490092014-05-27 12:30:54 -0700229
230// This is the default value, if not specified by property.
Glenn Kastenb5fed682013-12-03 09:06:43 -0800231static const int kFastTrackMultiplier = 2;
Eric Laurent81784c32012-11-19 14:55:58 -0800232
Glenn Kasten03490092014-05-27 12:30:54 -0700233// The minimum and maximum allowed values
234static const int kFastTrackMultiplierMin = 1;
235static const int kFastTrackMultiplierMax = 2;
236
237// The actual value to use, which can be specified per-device via property af.fast_track_multiplier.
238static int sFastTrackMultiplier = kFastTrackMultiplier;
239
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700240// See Thread::readOnlyHeap().
241// Initially this heap is used to allocate client buffers for "fast" AudioRecord.
242// Eventually it will be the single buffer that FastCapture writes into via HAL read(),
243// and that all "fast" AudioRecord clients read from. In either case, the size can be small.
Mikhail Naganov79a77822018-05-10 15:57:25 -0700244static const size_t kRecordThreadReadOnlyHeapSize = 0xD000;
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700245
Eric Laurent81784c32012-11-19 14:55:58 -0800246// ----------------------------------------------------------------------------
247
Andy Hungb68f5eb2019-12-03 16:49:17 -0800248// TODO: move all toString helpers to audio.h
249// under #ifdef __cplusplus #endif
250static std::string patchSinksToString(const struct audio_patch *patch)
251{
252 std::stringstream ss;
253 for (size_t i = 0; i < patch->num_sinks; ++i) {
Andy Hungc2b11cb2020-04-22 09:04:01 -0700254 if (i > 0) {
255 ss << "|";
256 }
Andy Hungb68f5eb2019-12-03 16:49:17 -0800257 ss << "(" << toString(patch->sinks[i].ext.device.type)
258 << ", " << patch->sinks[i].ext.device.address << ")";
259 }
260 return ss.str();
261}
262
263static std::string patchSourcesToString(const struct audio_patch *patch)
264{
265 std::stringstream ss;
266 for (size_t i = 0; i < patch->num_sources; ++i) {
Andy Hungc2b11cb2020-04-22 09:04:01 -0700267 if (i > 0) {
268 ss << "|";
269 }
Andy Hungb68f5eb2019-12-03 16:49:17 -0800270 ss << "(" << toString(patch->sources[i].ext.device.type)
271 << ", " << patch->sources[i].ext.device.address << ")";
272 }
273 return ss.str();
274}
275
Andy Hung4bd53e72022-11-17 17:21:45 -0800276static std::string toString(audio_latency_mode_t mode) {
277 // We convert to the AIDL type to print (eventually the legacy type will be removed).
Mikhail Naganovf53e1822022-12-18 02:48:14 +0000278 const auto result = legacy2aidl_audio_latency_mode_t_AudioLatencyMode(mode);
279 return result.has_value() ? media::audio::common::toString(*result) : "UNKNOWN";
Andy Hung4bd53e72022-11-17 17:21:45 -0800280}
281
282// Could be made a template, but other toString overloads for std::vector are confused.
283static std::string toString(const std::vector<audio_latency_mode_t>& elements) {
284 std::string s("{ ");
285 for (const auto& e : elements) {
286 s.append(toString(e));
287 s.append(" ");
288 }
289 s.append("}");
290 return s;
291}
292
Glenn Kasten03490092014-05-27 12:30:54 -0700293static pthread_once_t sFastTrackMultiplierOnce = PTHREAD_ONCE_INIT;
294
295static void sFastTrackMultiplierInit()
296{
297 char value[PROPERTY_VALUE_MAX];
298 if (property_get("af.fast_track_multiplier", value, NULL) > 0) {
299 char *endptr;
300 unsigned long ul = strtoul(value, &endptr, 0);
301 if (*endptr == '\0' && kFastTrackMultiplierMin <= ul && ul <= kFastTrackMultiplierMax) {
302 sFastTrackMultiplier = (int) ul;
303 }
304 }
305}
306
307// ----------------------------------------------------------------------------
308
Eric Laurent81784c32012-11-19 14:55:58 -0800309#ifdef ADD_BATTERY_DATA
310// To collect the amplifier usage
311static void addBatteryData(uint32_t params) {
312 sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService();
313 if (service == NULL) {
314 // it already logged
315 return;
316 }
317
318 service->addBatteryData(params);
319}
320#endif
321
Andy Hung3f0c9022016-01-15 17:49:46 -0800322// Track the CLOCK_BOOTTIME versus CLOCK_MONOTONIC timebase offset
323struct {
324 // call when you acquire a partial wakelock
325 void acquire(const sp<IBinder> &wakeLockToken) {
326 pthread_mutex_lock(&mLock);
327 if (wakeLockToken.get() == nullptr) {
328 adjustTimebaseOffset(&mBoottimeOffset, ExtendedTimestamp::TIMEBASE_BOOTTIME);
329 } else {
330 if (mCount == 0) {
331 adjustTimebaseOffset(&mBoottimeOffset, ExtendedTimestamp::TIMEBASE_BOOTTIME);
332 }
333 ++mCount;
334 }
335 pthread_mutex_unlock(&mLock);
336 }
337
338 // call when you release a partial wakelock.
339 void release(const sp<IBinder> &wakeLockToken) {
340 if (wakeLockToken.get() == nullptr) {
341 return;
342 }
343 pthread_mutex_lock(&mLock);
344 if (--mCount < 0) {
345 ALOGE("negative wakelock count");
346 mCount = 0;
347 }
348 pthread_mutex_unlock(&mLock);
349 }
350
351 // retrieves the boottime timebase offset from monotonic.
352 int64_t getBoottimeOffset() {
353 pthread_mutex_lock(&mLock);
354 int64_t boottimeOffset = mBoottimeOffset;
355 pthread_mutex_unlock(&mLock);
356 return boottimeOffset;
357 }
358
359 // Adjusts the timebase offset between TIMEBASE_MONOTONIC
360 // and the selected timebase.
361 // Currently only TIMEBASE_BOOTTIME is allowed.
362 //
363 // This only needs to be called upon acquiring the first partial wakelock
364 // after all other partial wakelocks are released.
365 //
366 // We do an empirical measurement of the offset rather than parsing
367 // /proc/timer_list since the latter is not a formal kernel ABI.
368 static void adjustTimebaseOffset(int64_t *offset, ExtendedTimestamp::Timebase timebase) {
369 int clockbase;
370 switch (timebase) {
371 case ExtendedTimestamp::TIMEBASE_BOOTTIME:
372 clockbase = SYSTEM_TIME_BOOTTIME;
373 break;
374 default:
375 LOG_ALWAYS_FATAL("invalid timebase %d", timebase);
376 break;
377 }
378 // try three times to get the clock offset, choose the one
379 // with the minimum gap in measurements.
380 const int tries = 3;
Andy Hung920f6572022-10-06 12:09:49 -0700381 nsecs_t bestGap = 0, measured = 0; // not required, initialized for clang-tidy
Andy Hung3f0c9022016-01-15 17:49:46 -0800382 for (int i = 0; i < tries; ++i) {
383 const nsecs_t tmono = systemTime(SYSTEM_TIME_MONOTONIC);
384 const nsecs_t tbase = systemTime(clockbase);
385 const nsecs_t tmono2 = systemTime(SYSTEM_TIME_MONOTONIC);
386 const nsecs_t gap = tmono2 - tmono;
387 if (i == 0 || gap < bestGap) {
388 bestGap = gap;
389 measured = tbase - ((tmono + tmono2) >> 1);
390 }
391 }
392
393 // to avoid micro-adjusting, we don't change the timebase
394 // unless it is significantly different.
395 //
396 // Assumption: It probably takes more than toleranceNs to
397 // suspend and resume the device.
398 static int64_t toleranceNs = 10000; // 10 us
399 if (llabs(*offset - measured) > toleranceNs) {
400 ALOGV("Adjusting timebase offset old: %lld new: %lld",
401 (long long)*offset, (long long)measured);
402 *offset = measured;
403 }
404 }
405
406 pthread_mutex_t mLock;
407 int32_t mCount;
408 int64_t mBoottimeOffset;
409} gBoottime = { PTHREAD_MUTEX_INITIALIZER, 0, 0 }; // static, so use POD initialization
Eric Laurent81784c32012-11-19 14:55:58 -0800410
411// ----------------------------------------------------------------------------
412// CPU Stats
413// ----------------------------------------------------------------------------
414
415class CpuStats {
416public:
417 CpuStats();
418 void sample(const String8 &title);
419#ifdef DEBUG_CPU_USAGE
420private:
421 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns
Andy Hung16698b82018-08-01 10:48:38 -0700422 audio_utils::Statistics<double> mWcStats; // statistics on thread CPU usage in wall clock ns
Eric Laurent81784c32012-11-19 14:55:58 -0800423
Andy Hung16698b82018-08-01 10:48:38 -0700424 audio_utils::Statistics<double> mHzStats; // statistics on thread CPU usage in cycles
Eric Laurent81784c32012-11-19 14:55:58 -0800425
426 int mCpuNum; // thread's current CPU number
427 int mCpukHz; // frequency of thread's current CPU in kHz
428#endif
429};
430
431CpuStats::CpuStats()
432#ifdef DEBUG_CPU_USAGE
433 : mCpuNum(-1), mCpukHz(-1)
434#endif
435{
436}
437
Glenn Kasten0f11b512014-01-31 16:18:54 -0800438void CpuStats::sample(const String8 &title
439#ifndef DEBUG_CPU_USAGE
440 __unused
441#endif
442 ) {
Eric Laurent81784c32012-11-19 14:55:58 -0800443#ifdef DEBUG_CPU_USAGE
444 // get current thread's delta CPU time in wall clock ns
445 double wcNs;
446 bool valid = mCpuUsage.sampleAndEnable(wcNs);
447
448 // record sample for wall clock statistics
449 if (valid) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700450 mWcStats.add(wcNs);
Eric Laurent81784c32012-11-19 14:55:58 -0800451 }
452
453 // get the current CPU number
454 int cpuNum = sched_getcpu();
455
456 // get the current CPU frequency in kHz
457 int cpukHz = mCpuUsage.getCpukHz(cpuNum);
458
459 // check if either CPU number or frequency changed
460 if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
461 mCpuNum = cpuNum;
462 mCpukHz = cpukHz;
463 // ignore sample for purposes of cycles
464 valid = false;
465 }
466
467 // if no change in CPU number or frequency, then record sample for cycle statistics
468 if (valid && mCpukHz > 0) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700469 const double cycles = wcNs * cpukHz * 0.000001;
470 mHzStats.add(cycles);
Eric Laurent81784c32012-11-19 14:55:58 -0800471 }
472
Eric Tan5b13ff82018-07-27 11:20:17 -0700473 const unsigned n = mWcStats.getN();
Eric Laurent81784c32012-11-19 14:55:58 -0800474 // mCpuUsage.elapsed() is expensive, so don't call it every loop
475 if ((n & 127) == 1) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700476 const long long elapsed = mCpuUsage.elapsed();
Eric Laurent81784c32012-11-19 14:55:58 -0800477 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700478 const double perLoop = elapsed / (double) n;
479 const double perLoop100 = perLoop * 0.01;
480 const double perLoop1k = perLoop * 0.001;
481 const double mean = mWcStats.getMean();
482 const double stddev = mWcStats.getStdDev();
483 const double minimum = mWcStats.getMin();
484 const double maximum = mWcStats.getMax();
485 const double meanCycles = mHzStats.getMean();
486 const double stddevCycles = mHzStats.getStdDev();
487 const double minCycles = mHzStats.getMin();
488 const double maxCycles = mHzStats.getMax();
Eric Laurent81784c32012-11-19 14:55:58 -0800489 mCpuUsage.resetElapsed();
490 mWcStats.reset();
491 mHzStats.reset();
492 ALOGD("CPU usage for %s over past %.1f secs\n"
493 " (%u mixer loops at %.1f mean ms per loop):\n"
494 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
495 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
496 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
497 title.string(),
498 elapsed * .000000001, n, perLoop * .000001,
499 mean * .001,
500 stddev * .001,
501 minimum * .001,
502 maximum * .001,
503 mean / perLoop100,
504 stddev / perLoop100,
505 minimum / perLoop100,
506 maximum / perLoop100,
507 meanCycles / perLoop1k,
508 stddevCycles / perLoop1k,
509 minCycles / perLoop1k,
510 maxCycles / perLoop1k);
511
512 }
513 }
514#endif
515};
516
517// ----------------------------------------------------------------------------
518// ThreadBase
519// ----------------------------------------------------------------------------
520
Glenn Kasten97b7b752014-09-28 13:04:24 -0700521// static
Andy Hungee58e4a2023-07-07 13:47:37 -0700522const char* ThreadBase::threadTypeToString(ThreadBase::type_t type)
Glenn Kasten97b7b752014-09-28 13:04:24 -0700523{
524 switch (type) {
525 case MIXER:
526 return "MIXER";
527 case DIRECT:
528 return "DIRECT";
529 case DUPLICATING:
530 return "DUPLICATING";
531 case RECORD:
532 return "RECORD";
533 case OFFLOAD:
534 return "OFFLOAD";
Andy Hungea840382020-05-05 21:50:17 -0700535 case MMAP_PLAYBACK:
536 return "MMAP_PLAYBACK";
537 case MMAP_CAPTURE:
538 return "MMAP_CAPTURE";
Eric Laurent1c5e2e32021-08-18 18:50:28 +0200539 case SPATIALIZER:
540 return "SPATIALIZER";
jiabinc658e452022-10-21 20:52:21 +0000541 case BIT_PERFECT:
542 return "BIT_PERFECT";
Glenn Kasten97b7b752014-09-28 13:04:24 -0700543 default:
544 return "unknown";
545 }
546}
547
Andy Hung583043b2023-07-17 17:05:00 -0700548ThreadBase::ThreadBase(const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
Andy Hungcf10d742020-04-28 15:38:24 -0700549 type_t type, bool systemReady, bool isOut)
Eric Laurent81784c32012-11-19 14:55:58 -0800550 : Thread(false /*canCallJava*/),
551 mType(type),
Andy Hung583043b2023-07-17 17:05:00 -0700552 mAfThreadCallback(afThreadCallback),
Andy Hungcf10d742020-04-28 15:38:24 -0700553 mThreadMetrics(std::string(AMEDIAMETRICS_KEY_PREFIX_AUDIO_THREAD) + std::to_string(id),
554 isOut),
555 mIsOut(isOut),
Glenn Kasten70949c42013-08-06 07:40:12 -0700556 // mSampleRate, mFrameCount, mChannelMask, mChannelCount, mFrameSize, mFormat, mBufferSize
Glenn Kastendeca2ae2014-02-07 10:25:56 -0800557 // are set by PlaybackThread::readOutputParameters_l() or
558 // RecordThread::readInputParameters_l()
Eric Laurentfd477972013-10-25 18:10:40 -0700559 //FIXME: mStandby should be true here. Is this some kind of hack?
jiabinc52b1ff2019-10-31 17:20:42 -0700560 mStandby(false),
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700561 mAudioSource(AUDIO_SOURCE_DEFAULT), mId(id),
Eric Laurent81784c32012-11-19 14:55:58 -0800562 // mName will be set by concrete (non-virtual) subclass
Eric Laurent72e3f392015-05-20 14:43:50 -0700563 mDeathRecipient(new PMDeathRecipient(this)),
Eric Laurent6acd1d42017-01-04 14:23:29 -0800564 mSystemReady(systemReady),
565 mSignalPending(false)
Eric Laurent81784c32012-11-19 14:55:58 -0800566{
Andy Hungcf10d742020-04-28 15:38:24 -0700567 mThreadMetrics.logConstructor(getpid(), threadTypeToString(type), id);
Eric Laurent296fb132015-05-01 11:38:42 -0700568 memset(&mPatch, 0, sizeof(struct audio_patch));
Eric Laurent81784c32012-11-19 14:55:58 -0800569}
570
Andy Hungee58e4a2023-07-07 13:47:37 -0700571ThreadBase::~ThreadBase()
Eric Laurent81784c32012-11-19 14:55:58 -0800572{
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700573 // mConfigEvents should be empty, but just in case it isn't, free the memory it owns
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700574 mConfigEvents.clear();
575
Eric Laurent81784c32012-11-19 14:55:58 -0800576 // do not lock the mutex in destructor
577 releaseWakeLock_l();
578 if (mPowerManager != 0) {
Marco Nelissen06b46062014-11-14 07:58:25 -0800579 sp<IBinder> binder = IInterface::asBinder(mPowerManager);
Eric Laurent81784c32012-11-19 14:55:58 -0800580 binder->unlinkToDeath(mDeathRecipient);
581 }
Andy Hungd0979812019-02-21 15:51:44 -0800582
583 sendStatistics(true /* force */);
Eric Laurent81784c32012-11-19 14:55:58 -0800584}
585
Andy Hungee58e4a2023-07-07 13:47:37 -0700586status_t ThreadBase::readyToRun()
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700587{
588 status_t status = initCheck();
589 if (status == NO_ERROR) {
Glenn Kasten1bfe09a2017-02-21 13:05:56 -0800590 ALOGI("AudioFlinger's thread %p tid=%d ready to run", this, getTid());
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700591 } else {
592 ALOGE("No working audio driver found.");
593 }
594 return status;
595}
596
Andy Hungee58e4a2023-07-07 13:47:37 -0700597void ThreadBase::exit()
Eric Laurent81784c32012-11-19 14:55:58 -0800598{
599 ALOGV("ThreadBase::exit");
600 // do any cleanup required for exit to succeed
601 preExit();
602 {
603 // This lock prevents the following race in thread (uniprocessor for illustration):
604 // if (!exitPending()) {
605 // // context switch from here to exit()
606 // // exit() calls requestExit(), what exitPending() observes
607 // // exit() calls signal(), which is dropped since no waiters
608 // // context switch back from exit() to here
609 // mWaitWorkCV.wait(...);
610 // // now thread is hung
611 // }
612 AutoMutex lock(mLock);
613 requestExit();
614 mWaitWorkCV.broadcast();
615 }
616 // When Thread::requestExitAndWait is made virtual and this method is renamed to
617 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
618 requestExitAndWait();
619}
620
Andy Hungee58e4a2023-07-07 13:47:37 -0700621status_t ThreadBase::setParameters(const String8& keyValuePairs)
Eric Laurent81784c32012-11-19 14:55:58 -0800622{
Eric Laurent81784c32012-11-19 14:55:58 -0800623 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
624 Mutex::Autolock _l(mLock);
625
Eric Laurent10351942014-05-08 18:49:52 -0700626 return sendSetParameterConfigEvent_l(keyValuePairs);
627}
628
629// sendConfigEvent_l() must be called with ThreadBase::mLock held
630// Can temporarily release the lock if waiting for a reply from processConfigEvents_l().
Andy Hungee58e4a2023-07-07 13:47:37 -0700631status_t ThreadBase::sendConfigEvent_l(sp<ConfigEvent>& event)
Andy Hung920f6572022-10-06 12:09:49 -0700632NO_THREAD_SAFETY_ANALYSIS // condition variable
Eric Laurent10351942014-05-08 18:49:52 -0700633{
634 status_t status = NO_ERROR;
635
Eric Laurent72e3f392015-05-20 14:43:50 -0700636 if (event->mRequiresSystemReady && !mSystemReady) {
637 event->mWaitStatus = false;
638 mPendingConfigEvents.add(event);
639 return status;
640 }
Eric Laurent10351942014-05-08 18:49:52 -0700641 mConfigEvents.add(event);
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700642 ALOGV("sendConfigEvent_l() num events %zu event %d", mConfigEvents.size(), event->mType);
Eric Laurent81784c32012-11-19 14:55:58 -0800643 mWaitWorkCV.signal();
Eric Laurent10351942014-05-08 18:49:52 -0700644 mLock.unlock();
645 {
646 Mutex::Autolock _l(event->mLock);
647 while (event->mWaitStatus) {
648 if (event->mCond.waitRelative(event->mLock, kConfigEventTimeoutNs) != NO_ERROR) {
649 event->mStatus = TIMED_OUT;
650 event->mWaitStatus = false;
651 }
652 }
653 status = event->mStatus;
Eric Laurent81784c32012-11-19 14:55:58 -0800654 }
Eric Laurent10351942014-05-08 18:49:52 -0700655 mLock.lock();
Eric Laurent81784c32012-11-19 14:55:58 -0800656 return status;
657}
658
Andy Hungee58e4a2023-07-07 13:47:37 -0700659void ThreadBase::sendIoConfigEvent(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -0700660 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -0800661{
662 Mutex::Autolock _l(mLock);
Eric Laurent09f1ed22019-04-24 17:45:17 -0700663 sendIoConfigEvent_l(event, pid, portId);
Eric Laurent81784c32012-11-19 14:55:58 -0800664}
665
666// sendIoConfigEvent_l() must be called with ThreadBase::mLock held
Andy Hungee58e4a2023-07-07 13:47:37 -0700667void ThreadBase::sendIoConfigEvent_l(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -0700668 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -0800669{
Andy Hungd0979812019-02-21 15:51:44 -0800670 // The audio statistics history is exponentially weighted to forget events
671 // about five or more seconds in the past. In order to have
672 // crisper statistics for mediametrics, we reset the statistics on
673 // an IoConfigEvent, to reflect different properties for a new device.
674 mIoJitterMs.reset();
675 mLatencyMs.reset();
676 mProcessTimeMs.reset();
Robert Wu06db0a32021-08-10 19:05:34 +0000677 mMonopipePipeDepthStats.reset();
Dean Wheatley12473e92021-03-18 23:00:55 +1100678 mTimestampVerifier.discontinuity(mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS);
Andy Hungd0979812019-02-21 15:51:44 -0800679
Eric Laurent09f1ed22019-04-24 17:45:17 -0700680 sp<ConfigEvent> configEvent = (ConfigEvent *)new IoConfigEvent(event, pid, portId);
Eric Laurent10351942014-05-08 18:49:52 -0700681 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800682}
683
Andy Hungee58e4a2023-07-07 13:47:37 -0700684void ThreadBase::sendPrioConfigEvent(pid_t pid, pid_t tid, int32_t prio, bool forApp)
Eric Laurent72e3f392015-05-20 14:43:50 -0700685{
686 Mutex::Autolock _l(mLock);
Mikhail Naganov83f04272017-02-07 10:45:09 -0800687 sendPrioConfigEvent_l(pid, tid, prio, forApp);
Eric Laurent72e3f392015-05-20 14:43:50 -0700688}
689
Eric Laurent81784c32012-11-19 14:55:58 -0800690// sendPrioConfigEvent_l() must be called with ThreadBase::mLock held
Andy Hungee58e4a2023-07-07 13:47:37 -0700691void ThreadBase::sendPrioConfigEvent_l(
Mikhail Naganov83f04272017-02-07 10:45:09 -0800692 pid_t pid, pid_t tid, int32_t prio, bool forApp)
Eric Laurent81784c32012-11-19 14:55:58 -0800693{
Mikhail Naganov83f04272017-02-07 10:45:09 -0800694 sp<ConfigEvent> configEvent = (ConfigEvent *)new PrioConfigEvent(pid, tid, prio, forApp);
Eric Laurent10351942014-05-08 18:49:52 -0700695 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800696}
697
Eric Laurent10351942014-05-08 18:49:52 -0700698// sendSetParameterConfigEvent_l() must be called with ThreadBase::mLock held
Andy Hungee58e4a2023-07-07 13:47:37 -0700699status_t ThreadBase::sendSetParameterConfigEvent_l(const String8& keyValuePair)
Eric Laurent81784c32012-11-19 14:55:58 -0800700{
Andy Hung2ddee192015-12-18 17:34:44 -0800701 sp<ConfigEvent> configEvent;
702 AudioParameter param(keyValuePair);
703 int value;
Mikhail Naganov00260b52016-10-13 12:54:24 -0700704 if (param.getInt(String8(AudioParameter::keyMonoOutput), value) == NO_ERROR) {
Andy Hung2ddee192015-12-18 17:34:44 -0800705 setMasterMono_l(value != 0);
706 if (param.size() == 1) {
707 return NO_ERROR; // should be a solo parameter - we don't pass down
708 }
Mikhail Naganov00260b52016-10-13 12:54:24 -0700709 param.remove(String8(AudioParameter::keyMonoOutput));
Andy Hung2ddee192015-12-18 17:34:44 -0800710 configEvent = new SetParameterConfigEvent(param.toString());
711 } else {
712 configEvent = new SetParameterConfigEvent(keyValuePair);
713 }
Eric Laurent10351942014-05-08 18:49:52 -0700714 return sendConfigEvent_l(configEvent);
Glenn Kastenf7773312013-08-13 16:00:42 -0700715}
716
Andy Hungee58e4a2023-07-07 13:47:37 -0700717status_t ThreadBase::sendCreateAudioPatchConfigEvent(
Eric Laurent1c333e22014-05-20 10:48:17 -0700718 const struct audio_patch *patch,
719 audio_patch_handle_t *handle)
720{
721 Mutex::Autolock _l(mLock);
722 sp<ConfigEvent> configEvent = (ConfigEvent *)new CreateAudioPatchConfigEvent(*patch, *handle);
723 status_t status = sendConfigEvent_l(configEvent);
724 if (status == NO_ERROR) {
725 CreateAudioPatchConfigEventData *data =
726 (CreateAudioPatchConfigEventData *)configEvent->mData.get();
727 *handle = data->mHandle;
728 }
729 return status;
730}
731
Andy Hungee58e4a2023-07-07 13:47:37 -0700732status_t ThreadBase::sendReleaseAudioPatchConfigEvent(
Eric Laurent1c333e22014-05-20 10:48:17 -0700733 const audio_patch_handle_t handle)
734{
735 Mutex::Autolock _l(mLock);
736 sp<ConfigEvent> configEvent = (ConfigEvent *)new ReleaseAudioPatchConfigEvent(handle);
737 return sendConfigEvent_l(configEvent);
738}
739
Andy Hungee58e4a2023-07-07 13:47:37 -0700740status_t ThreadBase::sendUpdateOutDeviceConfigEvent(
jiabinc52b1ff2019-10-31 17:20:42 -0700741 const DeviceDescriptorBaseVector& outDevices)
742{
743 if (type() != RECORD) {
744 // The update out device operation is only for record thread.
745 return INVALID_OPERATION;
746 }
747 Mutex::Autolock _l(mLock);
748 sp<ConfigEvent> configEvent = (ConfigEvent *)new UpdateOutDevicesConfigEvent(outDevices);
749 return sendConfigEvent_l(configEvent);
750}
751
Andy Hungee58e4a2023-07-07 13:47:37 -0700752void ThreadBase::sendResizeBufferConfigEvent_l(int32_t maxSharedAudioHistoryMs)
Eric Laurentec376dc2021-04-08 20:41:22 +0200753{
754 ALOG_ASSERT(type() == RECORD, "sendResizeBufferConfigEvent_l() called on non record thread");
755 sp<ConfigEvent> configEvent =
756 (ConfigEvent *)new ResizeBufferConfigEvent(maxSharedAudioHistoryMs);
757 sendConfigEvent_l(configEvent);
758}
Eric Laurent1c333e22014-05-20 10:48:17 -0700759
Andy Hungee58e4a2023-07-07 13:47:37 -0700760void ThreadBase::sendCheckOutputStageEffectsEvent()
Eric Laurentb3f315a2021-07-13 15:09:05 +0200761{
762 Mutex::Autolock _l(mLock);
763 sendCheckOutputStageEffectsEvent_l();
764}
765
Andy Hungee58e4a2023-07-07 13:47:37 -0700766void ThreadBase::sendCheckOutputStageEffectsEvent_l()
Eric Laurentb3f315a2021-07-13 15:09:05 +0200767{
768 sp<ConfigEvent> configEvent =
769 (ConfigEvent *)new CheckOutputStageEffectsEvent();
770 sendConfigEvent_l(configEvent);
771}
772
Andy Hungee58e4a2023-07-07 13:47:37 -0700773void ThreadBase::sendHalLatencyModesChangedEvent_l()
Eric Laurent68a40a82022-05-03 18:15:04 +0200774{
775 sp<ConfigEvent> configEvent = sp<HalLatencyModesChangedEvent>::make();
776 sendConfigEvent_l(configEvent);
777}
778
Glenn Kasten2cfbf882013-08-14 13:12:11 -0700779// post condition: mConfigEvents.isEmpty()
Andy Hungee58e4a2023-07-07 13:47:37 -0700780void ThreadBase::processConfigEvents_l()
Glenn Kastenf7773312013-08-13 16:00:42 -0700781{
Eric Laurent10351942014-05-08 18:49:52 -0700782 bool configChanged = false;
783
Eric Laurent81784c32012-11-19 14:55:58 -0800784 while (!mConfigEvents.isEmpty()) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700785 ALOGV("processConfigEvents_l() remaining events %zu", mConfigEvents.size());
Eric Laurent10351942014-05-08 18:49:52 -0700786 sp<ConfigEvent> event = mConfigEvents[0];
Eric Laurent81784c32012-11-19 14:55:58 -0800787 mConfigEvents.removeAt(0);
Eric Laurent10351942014-05-08 18:49:52 -0700788 switch (event->mType) {
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700789 case CFG_EVENT_PRIO: {
Eric Laurent10351942014-05-08 18:49:52 -0700790 PrioConfigEventData *data = (PrioConfigEventData *)event->mData.get();
791 // FIXME Need to understand why this has to be done asynchronously
Mikhail Naganov83f04272017-02-07 10:45:09 -0800792 int err = requestPriority(data->mPid, data->mTid, data->mPrio, data->mForApp,
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700793 true /*asynchronous*/);
794 if (err != 0) {
795 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Eric Laurent10351942014-05-08 18:49:52 -0700796 data->mPrio, data->mPid, data->mTid, err);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700797 }
798 } break;
799 case CFG_EVENT_IO: {
Eric Laurent10351942014-05-08 18:49:52 -0700800 IoConfigEventData *data = (IoConfigEventData *)event->mData.get();
Eric Laurent09f1ed22019-04-24 17:45:17 -0700801 ioConfigChanged(data->mEvent, data->mPid, data->mPortId);
Eric Laurent10351942014-05-08 18:49:52 -0700802 } break;
803 case CFG_EVENT_SET_PARAMETER: {
804 SetParameterConfigEventData *data = (SetParameterConfigEventData *)event->mData.get();
805 if (checkForNewParameter_l(data->mKeyValuePairs, event->mStatus)) {
806 configChanged = true;
Andy Hung293558a2017-03-21 12:19:20 -0700807 mLocalLog.log("CFG_EVENT_SET_PARAMETER: (%s) configuration changed",
808 data->mKeyValuePairs.string());
Glenn Kastend5418eb2013-08-14 13:11:06 -0700809 }
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700810 } break;
Eric Laurent1c333e22014-05-20 10:48:17 -0700811 case CFG_EVENT_CREATE_AUDIO_PATCH: {
jiabinc52b1ff2019-10-31 17:20:42 -0700812 const DeviceTypeSet oldDevices = getDeviceTypes();
Eric Laurent1c333e22014-05-20 10:48:17 -0700813 CreateAudioPatchConfigEventData *data =
814 (CreateAudioPatchConfigEventData *)event->mData.get();
815 event->mStatus = createAudioPatch_l(&data->mPatch, &data->mHandle);
jiabinc52b1ff2019-10-31 17:20:42 -0700816 const DeviceTypeSet newDevices = getDeviceTypes();
Eric Laurent52568142022-10-28 11:23:28 +0200817 configChanged = oldDevices != newDevices;
jiabinc52b1ff2019-10-31 17:20:42 -0700818 mLocalLog.log("CFG_EVENT_CREATE_AUDIO_PATCH: old device %s (%s) new device %s (%s)",
819 dumpDeviceTypes(oldDevices).c_str(), toString(oldDevices).c_str(),
820 dumpDeviceTypes(newDevices).c_str(), toString(newDevices).c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -0700821 } break;
822 case CFG_EVENT_RELEASE_AUDIO_PATCH: {
jiabinc52b1ff2019-10-31 17:20:42 -0700823 const DeviceTypeSet oldDevices = getDeviceTypes();
Eric Laurent1c333e22014-05-20 10:48:17 -0700824 ReleaseAudioPatchConfigEventData *data =
825 (ReleaseAudioPatchConfigEventData *)event->mData.get();
826 event->mStatus = releaseAudioPatch_l(data->mHandle);
jiabinc52b1ff2019-10-31 17:20:42 -0700827 const DeviceTypeSet newDevices = getDeviceTypes();
Eric Laurent52568142022-10-28 11:23:28 +0200828 configChanged = oldDevices != newDevices;
jiabinc52b1ff2019-10-31 17:20:42 -0700829 mLocalLog.log("CFG_EVENT_RELEASE_AUDIO_PATCH: old device %s (%s) new device %s (%s)",
830 dumpDeviceTypes(oldDevices).c_str(), toString(oldDevices).c_str(),
831 dumpDeviceTypes(newDevices).c_str(), toString(newDevices).c_str());
832 } break;
833 case CFG_EVENT_UPDATE_OUT_DEVICE: {
834 UpdateOutDevicesConfigEventData *data =
835 (UpdateOutDevicesConfigEventData *)event->mData.get();
836 updateOutDevices(data->mOutDevices);
Eric Laurent1c333e22014-05-20 10:48:17 -0700837 } break;
Eric Laurentec376dc2021-04-08 20:41:22 +0200838 case CFG_EVENT_RESIZE_BUFFER: {
839 ResizeBufferConfigEventData *data =
840 (ResizeBufferConfigEventData *)event->mData.get();
841 resizeInputBuffer_l(data->mMaxSharedAudioHistoryMs);
842 } break;
Eric Laurentb3f315a2021-07-13 15:09:05 +0200843
844 case CFG_EVENT_CHECK_OUTPUT_STAGE_EFFECTS: {
845 setCheckOutputStageEffects();
846 } break;
847
Eric Laurent68a40a82022-05-03 18:15:04 +0200848 case CFG_EVENT_HAL_LATENCY_MODES_CHANGED: {
849 onHalLatencyModesChanged_l();
850 } break;
851
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700852 default:
Eric Laurent10351942014-05-08 18:49:52 -0700853 ALOG_ASSERT(false, "processConfigEvents_l() unknown event type %d", event->mType);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700854 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800855 }
Eric Laurent10351942014-05-08 18:49:52 -0700856 {
857 Mutex::Autolock _l(event->mLock);
858 if (event->mWaitStatus) {
859 event->mWaitStatus = false;
860 event->mCond.signal();
861 }
862 }
863 ALOGV_IF(mConfigEvents.isEmpty(), "processConfigEvents_l() DONE thread %p", this);
864 }
865
866 if (configChanged) {
867 cacheParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800868 }
Eric Laurent81784c32012-11-19 14:55:58 -0800869}
870
Marco Nelissenb2208842014-02-07 14:00:50 -0800871String8 channelMaskToString(audio_channel_mask_t mask, bool output) {
872 String8 s;
Glenn Kastene1635ec2015-06-08 15:46:49 -0700873 const audio_channel_representation_t representation =
874 audio_channel_mask_get_representation(mask);
Andy Hungf98ec8d2015-05-19 12:53:24 -0700875
876 switch (representation) {
jiabin245cdd92018-12-07 17:55:15 -0800877 // Travel all single bit channel mask to convert channel mask to string.
Andy Hungf98ec8d2015-05-19 12:53:24 -0700878 case AUDIO_CHANNEL_REPRESENTATION_POSITION: {
879 if (output) {
880 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT) s.append("front-left, ");
881 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT) s.append("front-right, ");
882 if (mask & AUDIO_CHANNEL_OUT_FRONT_CENTER) s.append("front-center, ");
Andy Hungfba71252021-05-07 11:58:32 -0700883 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY) s.append("low-frequency, ");
Andy Hungf98ec8d2015-05-19 12:53:24 -0700884 if (mask & AUDIO_CHANNEL_OUT_BACK_LEFT) s.append("back-left, ");
885 if (mask & AUDIO_CHANNEL_OUT_BACK_RIGHT) s.append("back-right, ");
886 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT_OF_CENTER) s.append("front-left-of-center, ");
887 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT_OF_CENTER) s.append("front-right-of-center, ");
888 if (mask & AUDIO_CHANNEL_OUT_BACK_CENTER) s.append("back-center, ");
889 if (mask & AUDIO_CHANNEL_OUT_SIDE_LEFT) s.append("side-left, ");
890 if (mask & AUDIO_CHANNEL_OUT_SIDE_RIGHT) s.append("side-right, ");
891 if (mask & AUDIO_CHANNEL_OUT_TOP_CENTER) s.append("top-center ,");
892 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_LEFT) s.append("top-front-left, ");
893 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_CENTER) s.append("top-front-center, ");
894 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_RIGHT) s.append("top-front-right, ");
895 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_LEFT) s.append("top-back-left, ");
Andy Hungae81b4c2021-05-07 08:54:28 -0700896 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_CENTER) s.append("top-back-center, ");
897 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_RIGHT) s.append("top-back-right, ");
898 if (mask & AUDIO_CHANNEL_OUT_TOP_SIDE_LEFT) s.append("top-side-left, ");
899 if (mask & AUDIO_CHANNEL_OUT_TOP_SIDE_RIGHT) s.append("top-side-right, ");
900 if (mask & AUDIO_CHANNEL_OUT_BOTTOM_FRONT_LEFT) s.append("bottom-front-left, ");
901 if (mask & AUDIO_CHANNEL_OUT_BOTTOM_FRONT_CENTER) s.append("bottom-front-center, ");
902 if (mask & AUDIO_CHANNEL_OUT_BOTTOM_FRONT_RIGHT) s.append("bottom-front-right, ");
Andy Hungfba71252021-05-07 11:58:32 -0700903 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY_2) s.append("low-frequency-2, ");
Andy Hungae81b4c2021-05-07 08:54:28 -0700904 if (mask & AUDIO_CHANNEL_OUT_HAPTIC_B) s.append("haptic-B, ");
905 if (mask & AUDIO_CHANNEL_OUT_HAPTIC_A) s.append("haptic-A, ");
Andy Hungf98ec8d2015-05-19 12:53:24 -0700906 if (mask & ~AUDIO_CHANNEL_OUT_ALL) s.append("unknown, ");
907 } else {
908 if (mask & AUDIO_CHANNEL_IN_LEFT) s.append("left, ");
909 if (mask & AUDIO_CHANNEL_IN_RIGHT) s.append("right, ");
910 if (mask & AUDIO_CHANNEL_IN_FRONT) s.append("front, ");
911 if (mask & AUDIO_CHANNEL_IN_BACK) s.append("back, ");
912 if (mask & AUDIO_CHANNEL_IN_LEFT_PROCESSED) s.append("left-processed, ");
913 if (mask & AUDIO_CHANNEL_IN_RIGHT_PROCESSED) s.append("right-processed, ");
914 if (mask & AUDIO_CHANNEL_IN_FRONT_PROCESSED) s.append("front-processed, ");
915 if (mask & AUDIO_CHANNEL_IN_BACK_PROCESSED) s.append("back-processed, ");
916 if (mask & AUDIO_CHANNEL_IN_PRESSURE) s.append("pressure, ");
917 if (mask & AUDIO_CHANNEL_IN_X_AXIS) s.append("X, ");
918 if (mask & AUDIO_CHANNEL_IN_Y_AXIS) s.append("Y, ");
919 if (mask & AUDIO_CHANNEL_IN_Z_AXIS) s.append("Z, ");
Mikhail Naganovc9948492018-05-10 17:25:28 -0700920 if (mask & AUDIO_CHANNEL_IN_BACK_LEFT) s.append("back-left, ");
921 if (mask & AUDIO_CHANNEL_IN_BACK_RIGHT) s.append("back-right, ");
922 if (mask & AUDIO_CHANNEL_IN_CENTER) s.append("center, ");
Andy Hungfba71252021-05-07 11:58:32 -0700923 if (mask & AUDIO_CHANNEL_IN_LOW_FREQUENCY) s.append("low-frequency, ");
Andy Hungae81b4c2021-05-07 08:54:28 -0700924 if (mask & AUDIO_CHANNEL_IN_TOP_LEFT) s.append("top-left, ");
925 if (mask & AUDIO_CHANNEL_IN_TOP_RIGHT) s.append("top-right, ");
Andy Hungf98ec8d2015-05-19 12:53:24 -0700926 if (mask & AUDIO_CHANNEL_IN_VOICE_UPLINK) s.append("voice-uplink, ");
927 if (mask & AUDIO_CHANNEL_IN_VOICE_DNLINK) s.append("voice-dnlink, ");
928 if (mask & ~AUDIO_CHANNEL_IN_ALL) s.append("unknown, ");
929 }
930 const int len = s.length();
931 if (len > 2) {
Glenn Kasten57c4e6f2016-03-18 14:54:07 -0700932 (void) s.lockBuffer(len); // needed?
Andy Hungf98ec8d2015-05-19 12:53:24 -0700933 s.unlockBuffer(len - 2); // remove trailing ", "
934 }
935 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -0800936 }
Andy Hungf98ec8d2015-05-19 12:53:24 -0700937 case AUDIO_CHANNEL_REPRESENTATION_INDEX:
938 s.appendFormat("index mask, bits:%#x", audio_channel_mask_get_bits(mask));
939 return s;
940 default:
941 s.appendFormat("unknown mask, representation:%d bits:%#x",
942 representation, audio_channel_mask_get_bits(mask));
943 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -0800944 }
Marco Nelissenb2208842014-02-07 14:00:50 -0800945}
946
Andy Hungee58e4a2023-07-07 13:47:37 -0700947void ThreadBase::dump(int fd, const Vector<String16>& args)
Andy Hung920f6572022-10-06 12:09:49 -0700948NO_THREAD_SAFETY_ANALYSIS // conditional try lock
Eric Laurent81784c32012-11-19 14:55:58 -0800949{
Glenn Kasten1bfe09a2017-02-21 13:05:56 -0800950 dprintf(fd, "\n%s thread %p, name %s, tid %d, type %d (%s):\n", isOutput() ? "Output" : "Input",
951 this, mThreadName, getTid(), type(), threadTypeToString(type()));
952
Andy Hung0a51b5c2023-07-18 20:54:44 -0700953 const bool locked = afutils::dumpTryLock(mLock);
Eric Laurent81784c32012-11-19 14:55:58 -0800954 if (!locked) {
Glenn Kasten1bfe09a2017-02-21 13:05:56 -0800955 dprintf(fd, " Thread may be deadlocked\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800956 }
957
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -0700958 dumpBase_l(fd, args);
959 dumpInternals_l(fd, args);
960 dumpTracks_l(fd, args);
961 dumpEffectChains_l(fd, args);
962
963 if (locked) {
964 mLock.unlock();
965 }
966
967 dprintf(fd, " Local log:\n");
968 mLocalLog.dump(fd, " " /* prefix */, 40 /* lines */);
Andy Hungafc51db2022-04-08 17:33:40 -0700969
970 // --all does the statistics
971 bool dumpAll = false;
972 for (const auto &arg : args) {
973 if (arg == String16("--all")) {
974 dumpAll = true;
975 }
976 }
977 if (dumpAll || type() == SPATIALIZER) {
Andy Hung44d648b2022-04-08 17:33:40 -0700978 const std::string sched = mThreadSnapshot.toString();
Andy Hungafc51db2022-04-08 17:33:40 -0700979 if (!sched.empty()) {
980 (void)write(fd, sched.c_str(), sched.size());
981 }
982 }
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -0700983}
984
Andy Hungee58e4a2023-07-07 13:47:37 -0700985void ThreadBase::dumpBase_l(int fd, const Vector<String16>& /* args */)
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -0700986{
Elliott Hughes87cebad2014-05-22 10:14:43 -0700987 dprintf(fd, " I/O handle: %d\n", mId);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700988 dprintf(fd, " Standby: %s\n", mStandby ? "yes" : "no");
Glenn Kasten97b7b752014-09-28 13:04:24 -0700989 dprintf(fd, " Sample rate: %u Hz\n", mSampleRate);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700990 dprintf(fd, " HAL frame count: %zu\n", mFrameCount);
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700991 dprintf(fd, " HAL format: 0x%x (%s)\n", mHALFormat, formatToString(mHALFormat).c_str());
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700992 dprintf(fd, " HAL buffer size: %zu bytes\n", mBufferSize);
Glenn Kasten97b7b752014-09-28 13:04:24 -0700993 dprintf(fd, " Channel count: %u\n", mChannelCount);
994 dprintf(fd, " Channel mask: 0x%08x (%s)\n", mChannelMask,
Marco Nelissenb2208842014-02-07 14:00:50 -0800995 channelMaskToString(mChannelMask, mType != RECORD).string());
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700996 dprintf(fd, " Processing format: 0x%x (%s)\n", mFormat, formatToString(mFormat).c_str());
Glenn Kastenf87c2f52015-08-21 08:03:57 -0700997 dprintf(fd, " Processing frame size: %zu bytes\n", mFrameSize);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700998 dprintf(fd, " Pending config events:");
Marco Nelissenb2208842014-02-07 14:00:50 -0800999 size_t numConfig = mConfigEvents.size();
1000 if (numConfig) {
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001001 const size_t SIZE = 256;
1002 char buffer[SIZE];
Marco Nelissenb2208842014-02-07 14:00:50 -08001003 for (size_t i = 0; i < numConfig; i++) {
1004 mConfigEvents[i]->dump(buffer, SIZE);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001005 dprintf(fd, "\n %s", buffer);
Marco Nelissenb2208842014-02-07 14:00:50 -08001006 }
Elliott Hughes87cebad2014-05-22 10:14:43 -07001007 dprintf(fd, "\n");
Marco Nelissenb2208842014-02-07 14:00:50 -08001008 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07001009 dprintf(fd, " none\n");
Eric Laurent81784c32012-11-19 14:55:58 -08001010 }
Andy Hung293558a2017-03-21 12:19:20 -07001011 // Note: output device may be used by capture threads for effects such as AEC.
jiabinc52b1ff2019-10-31 17:20:42 -07001012 dprintf(fd, " Output devices: %s (%s)\n",
1013 dumpDeviceTypes(outDeviceTypes()).c_str(), toString(outDeviceTypes()).c_str());
1014 dprintf(fd, " Input device: %#x (%s)\n",
1015 inDeviceType(), toString(inDeviceType()).c_str());
Andy Hung9b181952019-02-25 14:53:36 -08001016 dprintf(fd, " Audio source: %d (%s)\n", mAudioSource, toString(mAudioSource).c_str());
Eric Laurent81784c32012-11-19 14:55:58 -08001017
Andy Hung2e2c0bb2018-06-11 19:13:11 -07001018 // Dump timestamp statistics for the Thread types that support it.
1019 if (mType == RECORD
1020 || mType == MIXER
1021 || mType == DUPLICATING
Andy Hungf3234512018-07-03 14:51:47 -07001022 || mType == DIRECT
Andy Hung4b7f54f2022-04-28 17:45:28 -07001023 || mType == OFFLOAD
1024 || mType == SPATIALIZER) {
Andy Hung2e2c0bb2018-06-11 19:13:11 -07001025 dprintf(fd, " Timestamp stats: %s\n", mTimestampVerifier.toString().c_str());
Andy Hungc8fddf32018-08-08 18:32:37 -07001026 dprintf(fd, " Timestamp corrected: %s\n", isTimestampCorrectionEnabled() ? "yes" : "no");
Andy Hung2e2c0bb2018-06-11 19:13:11 -07001027 }
1028
Andy Hung446f4df2019-02-21 12:26:41 -08001029 if (mLastIoBeginNs > 0) { // MMAP may not set this
1030 dprintf(fd, " Last %s occurred (msecs): %lld\n",
1031 isOutput() ? "write" : "read",
1032 (long long) (systemTime() - mLastIoBeginNs) / NANOS_PER_MILLISECOND);
1033 }
1034
1035 if (mProcessTimeMs.getN() > 0) {
1036 dprintf(fd, " Process time ms stats: %s\n", mProcessTimeMs.toString().c_str());
1037 }
1038
1039 if (mIoJitterMs.getN() > 0) {
1040 dprintf(fd, " Hal %s jitter ms stats: %s\n",
1041 isOutput() ? "write" : "read",
1042 mIoJitterMs.toString().c_str());
1043 }
1044
Andy Hunge6c37112019-02-26 17:38:10 -08001045 if (mLatencyMs.getN() > 0) {
1046 dprintf(fd, " Threadloop %s latency stats: %s\n",
1047 isOutput() ? "write" : "read",
1048 mLatencyMs.toString().c_str());
1049 }
Robert Wu06db0a32021-08-10 19:05:34 +00001050
1051 if (mMonopipePipeDepthStats.getN() > 0) {
1052 dprintf(fd, " Monopipe %s pipe depth stats: %s\n",
1053 isOutput() ? "write" : "read",
1054 mMonopipePipeDepthStats.toString().c_str());
1055 }
Eric Laurent81784c32012-11-19 14:55:58 -08001056}
1057
Andy Hungee58e4a2023-07-07 13:47:37 -07001058void ThreadBase::dumpEffectChains_l(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -08001059{
1060 const size_t SIZE = 256;
1061 char buffer[SIZE];
Eric Laurent81784c32012-11-19 14:55:58 -08001062
Marco Nelissenb2208842014-02-07 14:00:50 -08001063 size_t numEffectChains = mEffectChains.size();
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +00001064 snprintf(buffer, SIZE, " %zu Effect Chains\n", numEffectChains);
Eric Laurent81784c32012-11-19 14:55:58 -08001065 write(fd, buffer, strlen(buffer));
1066
Marco Nelissenb2208842014-02-07 14:00:50 -08001067 for (size_t i = 0; i < numEffectChains; ++i) {
Andy Hung116bc262023-06-20 18:56:17 -07001068 sp<IAfEffectChain> chain = mEffectChains[i];
Eric Laurent81784c32012-11-19 14:55:58 -08001069 if (chain != 0) {
1070 chain->dump(fd, args);
1071 }
1072 }
1073}
1074
Andy Hungee58e4a2023-07-07 13:47:37 -07001075void ThreadBase::acquireWakeLock()
Eric Laurent81784c32012-11-19 14:55:58 -08001076{
1077 Mutex::Autolock _l(mLock);
Andy Hungdae27702016-10-31 14:01:16 -07001078 acquireWakeLock_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001079}
1080
Andy Hungee58e4a2023-07-07 13:47:37 -07001081String16 ThreadBase::getWakeLockTag()
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001082{
1083 switch (mType) {
Glenn Kastenbcb14862015-03-05 17:11:21 -08001084 case MIXER:
1085 return String16("AudioMix");
1086 case DIRECT:
1087 return String16("AudioDirectOut");
1088 case DUPLICATING:
1089 return String16("AudioDup");
1090 case RECORD:
1091 return String16("AudioIn");
1092 case OFFLOAD:
1093 return String16("AudioOffload");
Andy Hungea840382020-05-05 21:50:17 -07001094 case MMAP_PLAYBACK:
1095 return String16("MmapPlayback");
1096 case MMAP_CAPTURE:
1097 return String16("MmapCapture");
Eric Laurent1c5e2e32021-08-18 18:50:28 +02001098 case SPATIALIZER:
1099 return String16("AudioSpatial");
Glenn Kastenbcb14862015-03-05 17:11:21 -08001100 default:
1101 ALOG_ASSERT(false);
1102 return String16("AudioUnknown");
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001103 }
1104}
1105
Andy Hungee58e4a2023-07-07 13:47:37 -07001106void ThreadBase::acquireWakeLock_l()
Eric Laurent81784c32012-11-19 14:55:58 -08001107{
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001108 getPowerManager_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001109 if (mPowerManager != 0) {
1110 sp<IBinder> binder = new BBinder();
Andy Hungdae27702016-10-31 14:01:16 -07001111 // Uses AID_AUDIOSERVER for wakelock. updateWakeLockUids_l() updates with client uids.
Chris Ye6597d732020-02-28 22:38:25 -08001112 binder::Status status = mPowerManager->acquireWakeLockAsync(binder,
1113 POWERMANAGER_PARTIAL_WAKE_LOCK,
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001114 getWakeLockTag(),
Marco Nelissendcb346b2015-09-09 10:47:29 -07001115 String16("audioserver"),
Chris Ye6597d732020-02-28 22:38:25 -08001116 {} /* workSource */,
1117 {} /* historyTag */);
1118 if (status.isOk()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001119 mWakeLockToken = binder;
1120 }
Chris Ye6597d732020-02-28 22:38:25 -08001121 ALOGV("acquireWakeLock_l() %s status %d", mThreadName, status.exceptionCode());
Eric Laurent81784c32012-11-19 14:55:58 -08001122 }
Wei Jia3f273d12015-11-24 09:06:49 -08001123
Andy Hung3f0c9022016-01-15 17:49:46 -08001124 gBoottime.acquire(mWakeLockToken);
Andy Hung818e7a32016-02-16 18:08:07 -08001125 mTimestamp.mTimebaseOffset[ExtendedTimestamp::TIMEBASE_BOOTTIME] =
1126 gBoottime.getBoottimeOffset();
Eric Laurent81784c32012-11-19 14:55:58 -08001127}
1128
Andy Hungee58e4a2023-07-07 13:47:37 -07001129void ThreadBase::releaseWakeLock()
Eric Laurent81784c32012-11-19 14:55:58 -08001130{
1131 Mutex::Autolock _l(mLock);
1132 releaseWakeLock_l();
1133}
1134
Andy Hungee58e4a2023-07-07 13:47:37 -07001135void ThreadBase::releaseWakeLock_l()
Eric Laurent81784c32012-11-19 14:55:58 -08001136{
Andy Hung3f0c9022016-01-15 17:49:46 -08001137 gBoottime.release(mWakeLockToken);
Eric Laurent81784c32012-11-19 14:55:58 -08001138 if (mWakeLockToken != 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -08001139 ALOGV("releaseWakeLock_l() %s", mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08001140 if (mPowerManager != 0) {
Chris Ye6597d732020-02-28 22:38:25 -08001141 mPowerManager->releaseWakeLockAsync(mWakeLockToken, 0);
Eric Laurent81784c32012-11-19 14:55:58 -08001142 }
1143 mWakeLockToken.clear();
1144 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001145}
1146
Andy Hungee58e4a2023-07-07 13:47:37 -07001147void ThreadBase::getPowerManager_l() {
Eric Laurent72e3f392015-05-20 14:43:50 -07001148 if (mSystemReady && mPowerManager == 0) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001149 // use checkService() to avoid blocking if power service is not up yet
1150 sp<IBinder> binder =
1151 defaultServiceManager()->checkService(String16("power"));
1152 if (binder == 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -08001153 ALOGW("Thread %s cannot connect to the power manager service", mThreadName);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001154 } else {
Chris Ye6597d732020-02-28 22:38:25 -08001155 mPowerManager = interface_cast<os::IPowerManager>(binder);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001156 binder->linkToDeath(mDeathRecipient);
1157 }
1158 }
1159}
1160
Andy Hungee58e4a2023-07-07 13:47:37 -07001161void ThreadBase::updateWakeLockUids_l(const SortedVector<uid_t>& uids) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001162 getPowerManager_l();
Andy Hungdae27702016-10-31 14:01:16 -07001163
1164#if !LOG_NDEBUG
1165 std::stringstream s;
Andy Hungd01b0f12016-11-07 16:10:30 -08001166 for (uid_t uid : uids) {
Andy Hungdae27702016-10-31 14:01:16 -07001167 s << uid << " ";
1168 }
1169 ALOGD("updateWakeLockUids_l %s uids:%s", mThreadName, s.str().c_str());
1170#endif
1171
Andy Hung438e7572015-12-14 15:51:17 -08001172 if (mWakeLockToken == NULL) { // token may be NULL if AudioFlinger::systemReady() not called.
1173 if (mSystemReady) {
1174 ALOGE("no wake lock to update, but system ready!");
1175 } else {
1176 ALOGW("no wake lock to update, system not ready yet");
1177 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001178 return;
1179 }
1180 if (mPowerManager != 0) {
Andy Hung1f12a8a2016-11-07 16:10:30 -08001181 std::vector<int> uidsAsInt(uids.begin(), uids.end()); // powermanager expects uids as ints
Chris Ye6597d732020-02-28 22:38:25 -08001182 binder::Status status = mPowerManager->updateWakeLockUidsAsync(
1183 mWakeLockToken, uidsAsInt);
1184 ALOGV("updateWakeLockUids_l() %s status %d", mThreadName, status.exceptionCode());
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001185 }
1186}
1187
Andy Hungee58e4a2023-07-07 13:47:37 -07001188void ThreadBase::clearPowerManager()
Eric Laurent81784c32012-11-19 14:55:58 -08001189{
1190 Mutex::Autolock _l(mLock);
1191 releaseWakeLock_l();
1192 mPowerManager.clear();
1193}
1194
Andy Hungee58e4a2023-07-07 13:47:37 -07001195void ThreadBase::updateOutDevices(
jiabinc52b1ff2019-10-31 17:20:42 -07001196 const DeviceDescriptorBaseVector& outDevices __unused)
1197{
1198 ALOGE("%s should only be called in RecordThread", __func__);
1199}
1200
Andy Hungee58e4a2023-07-07 13:47:37 -07001201void ThreadBase::resizeInputBuffer_l(int32_t /* maxSharedAudioHistoryMs */)
Eric Laurentec376dc2021-04-08 20:41:22 +02001202{
1203 ALOGE("%s should only be called in RecordThread", __func__);
1204}
1205
Andy Hungee58e4a2023-07-07 13:47:37 -07001206void ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& /* who */)
Eric Laurent81784c32012-11-19 14:55:58 -08001207{
1208 sp<ThreadBase> thread = mThread.promote();
1209 if (thread != 0) {
1210 thread->clearPowerManager();
1211 }
1212 ALOGW("power manager service died !!!");
1213}
1214
Andy Hungee58e4a2023-07-07 13:47:37 -07001215void ThreadBase::setEffectSuspended_l(
Glenn Kastend848eb42016-03-08 13:42:11 -08001216 const effect_uuid_t *type, bool suspend, audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001217{
Andy Hung116bc262023-06-20 18:56:17 -07001218 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08001219 if (chain != 0) {
1220 if (type != NULL) {
1221 chain->setEffectSuspended_l(type, suspend);
1222 } else {
1223 chain->setEffectSuspendedAll_l(suspend);
1224 }
1225 }
1226
1227 updateSuspendedSessions_l(type, suspend, sessionId);
1228}
1229
Andy Hungee58e4a2023-07-07 13:47:37 -07001230void ThreadBase::checkSuspendOnAddEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08001231{
1232 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
1233 if (index < 0) {
1234 return;
1235 }
1236
1237 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
1238 mSuspendedSessions.valueAt(index);
1239
1240 for (size_t i = 0; i < sessionEffects.size(); i++) {
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07001241 const sp<SuspendedSessionDesc>& desc = sessionEffects.valueAt(i);
Eric Laurent81784c32012-11-19 14:55:58 -08001242 for (int j = 0; j < desc->mRefCount; j++) {
Andy Hung116bc262023-06-20 18:56:17 -07001243 if (sessionEffects.keyAt(i) == IAfEffectChain::kKeyForSuspendAll) {
Eric Laurent81784c32012-11-19 14:55:58 -08001244 chain->setEffectSuspendedAll_l(true);
1245 } else {
1246 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
1247 desc->mType.timeLow);
1248 chain->setEffectSuspended_l(&desc->mType, true);
1249 }
1250 }
1251 }
1252}
1253
Andy Hungee58e4a2023-07-07 13:47:37 -07001254void ThreadBase::updateSuspendedSessions_l(const effect_uuid_t* type,
Eric Laurent81784c32012-11-19 14:55:58 -08001255 bool suspend,
Glenn Kastend848eb42016-03-08 13:42:11 -08001256 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001257{
1258 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
1259
1260 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1261
1262 if (suspend) {
1263 if (index >= 0) {
1264 sessionEffects = mSuspendedSessions.valueAt(index);
1265 } else {
1266 mSuspendedSessions.add(sessionId, sessionEffects);
1267 }
1268 } else {
1269 if (index < 0) {
1270 return;
1271 }
1272 sessionEffects = mSuspendedSessions.valueAt(index);
1273 }
1274
1275
Andy Hung116bc262023-06-20 18:56:17 -07001276 int key = IAfEffectChain::kKeyForSuspendAll;
Eric Laurent81784c32012-11-19 14:55:58 -08001277 if (type != NULL) {
1278 key = type->timeLow;
1279 }
1280 index = sessionEffects.indexOfKey(key);
1281
1282 sp<SuspendedSessionDesc> desc;
1283 if (suspend) {
1284 if (index >= 0) {
1285 desc = sessionEffects.valueAt(index);
1286 } else {
1287 desc = new SuspendedSessionDesc();
1288 if (type != NULL) {
1289 desc->mType = *type;
1290 }
1291 sessionEffects.add(key, desc);
1292 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
1293 }
1294 desc->mRefCount++;
1295 } else {
1296 if (index < 0) {
1297 return;
1298 }
1299 desc = sessionEffects.valueAt(index);
1300 if (--desc->mRefCount == 0) {
1301 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
1302 sessionEffects.removeItemsAt(index);
1303 if (sessionEffects.isEmpty()) {
1304 ALOGV("updateSuspendedSessions_l() restore removing session %d",
1305 sessionId);
1306 mSuspendedSessions.removeItem(sessionId);
1307 }
1308 }
1309 }
1310 if (!sessionEffects.isEmpty()) {
1311 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1312 }
1313}
1314
Andy Hungee58e4a2023-07-07 13:47:37 -07001315void ThreadBase::checkSuspendOnEffectEnabled(bool enabled,
Eric Laurent6b446ce2019-12-13 10:56:31 -08001316 audio_session_t sessionId,
Andy Hung920f6572022-10-06 12:09:49 -07001317 bool threadLocked)
1318NO_THREAD_SAFETY_ANALYSIS // manual locking
1319{
Eric Laurent6b446ce2019-12-13 10:56:31 -08001320 if (!threadLocked) {
1321 mLock.lock();
1322 }
Eric Laurent81784c32012-11-19 14:55:58 -08001323
Eric Laurent81784c32012-11-19 14:55:58 -08001324 if (mType != RECORD) {
1325 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1326 // another session. This gives the priority to well behaved effect control panels
1327 // and applications not using global effects.
1328 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
1329 // global effects
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001330 if (!audio_is_global_session(sessionId)) {
Eric Laurent81784c32012-11-19 14:55:58 -08001331 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1332 }
1333 }
1334
Eric Laurent6b446ce2019-12-13 10:56:31 -08001335 if (!threadLocked) {
1336 mLock.unlock();
Eric Laurent81784c32012-11-19 14:55:58 -08001337 }
1338}
1339
Eric Laurent4c415062016-06-17 16:14:16 -07001340// checkEffectCompatibility_l() must be called with ThreadBase::mLock held
Andy Hungee58e4a2023-07-07 13:47:37 -07001341status_t RecordThread::checkEffectCompatibility_l(
Eric Laurent4c415062016-06-17 16:14:16 -07001342 const effect_descriptor_t *desc, audio_session_t sessionId)
1343{
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001344 // No global output effect sessions on record threads
1345 if (sessionId == AUDIO_SESSION_OUTPUT_MIX
1346 || sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Eric Laurent4c415062016-06-17 16:14:16 -07001347 ALOGW("checkEffectCompatibility_l(): global effect %s on record thread %s",
1348 desc->name, mThreadName);
1349 return BAD_VALUE;
1350 }
1351 // only pre processing effects on record thread
1352 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC) {
1353 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on record thread %s",
1354 desc->name, mThreadName);
1355 return BAD_VALUE;
1356 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001357
1358 // always allow effects without processing load or latency
1359 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1360 return NO_ERROR;
1361 }
1362
Eric Laurent4c415062016-06-17 16:14:16 -07001363 audio_input_flags_t flags = mInput->flags;
1364 if (hasFastCapture() || (flags & AUDIO_INPUT_FLAG_FAST)) {
1365 if (flags & AUDIO_INPUT_FLAG_RAW) {
1366 ALOGW("checkEffectCompatibility_l(): effect %s on record thread %s in raw mode",
1367 desc->name, mThreadName);
1368 return BAD_VALUE;
1369 }
1370 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1371 ALOGW("checkEffectCompatibility_l(): non HW effect %s on record thread %s in fast mode",
1372 desc->name, mThreadName);
1373 return BAD_VALUE;
1374 }
1375 }
jiabineb3bda02020-06-30 14:07:03 -07001376
Andy Hung116bc262023-06-20 18:56:17 -07001377 if (IAfEffectModule::isHapticGenerator(&desc->type)) {
jiabineb3bda02020-06-30 14:07:03 -07001378 ALOGE("%s(): HapticGenerator is not supported in RecordThread", __func__);
1379 return BAD_VALUE;
1380 }
Eric Laurent4c415062016-06-17 16:14:16 -07001381 return NO_ERROR;
1382}
1383
1384// checkEffectCompatibility_l() must be called with ThreadBase::mLock held
Andy Hungee58e4a2023-07-07 13:47:37 -07001385status_t PlaybackThread::checkEffectCompatibility_l(
Eric Laurent4c415062016-06-17 16:14:16 -07001386 const effect_descriptor_t *desc, audio_session_t sessionId)
1387{
1388 // no preprocessing on playback threads
1389 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001390 ALOGW("%s: pre processing effect %s created on playback"
1391 " thread %s", __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001392 return BAD_VALUE;
1393 }
1394
Eric Laurent3e4de772017-07-16 16:55:08 -07001395 // always allow effects without processing load or latency
1396 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1397 return NO_ERROR;
1398 }
1399
Andy Hung116bc262023-06-20 18:56:17 -07001400 if (IAfEffectModule::isHapticGenerator(&desc->type) && mHapticChannelCount == 0) {
jiabineb3bda02020-06-30 14:07:03 -07001401 ALOGW("%s: thread doesn't support haptic playback while the effect is HapticGenerator",
1402 __func__);
1403 return BAD_VALUE;
1404 }
1405
Eric Laurentf690c462021-09-17 14:47:03 +02001406 if (memcmp(&desc->type, FX_IID_SPATIALIZER, sizeof(effect_uuid_t)) == 0
1407 && mType != SPATIALIZER) {
1408 ALOGW("%s: attempt to create a spatializer effect on a thread of type %d",
1409 __func__, mType);
1410 return BAD_VALUE;
1411 }
1412
Eric Laurent4c415062016-06-17 16:14:16 -07001413 switch (mType) {
1414 case MIXER: {
Eric Laurent4c415062016-06-17 16:14:16 -07001415 audio_output_flags_t flags = mOutput->flags;
1416 if (hasFastMixer() || (flags & AUDIO_OUTPUT_FLAG_FAST)) {
1417 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1418 // global effects are applied only to non fast tracks if they are SW
1419 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1420 break;
1421 }
1422 } else if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1423 // only post processing on output stage session
1424 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001425 ALOGW("%s: non post processing effect %s not allowed on output stage session",
1426 __func__, desc->name);
Eric Laurent4c415062016-06-17 16:14:16 -07001427 return BAD_VALUE;
1428 }
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001429 } else if (sessionId == AUDIO_SESSION_DEVICE) {
1430 // only post processing on output stage session
1431 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001432 ALOGW("%s: non post processing effect %s not allowed on device session",
1433 __func__, desc->name);
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001434 return BAD_VALUE;
1435 }
Eric Laurent4c415062016-06-17 16:14:16 -07001436 } else {
1437 // no restriction on effects applied on non fast tracks
1438 if ((hasAudioSession_l(sessionId) & ThreadBase::FAST_SESSION) == 0) {
1439 break;
1440 }
1441 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001442
Eric Laurent4c415062016-06-17 16:14:16 -07001443 if (flags & AUDIO_OUTPUT_FLAG_RAW) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001444 ALOGW("%s: effect %s on playback thread in raw mode", __func__, desc->name);
Eric Laurent4c415062016-06-17 16:14:16 -07001445 return BAD_VALUE;
1446 }
1447 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001448 ALOGW("%s: non HW effect %s on playback thread in fast mode",
1449 __func__, desc->name);
Eric Laurent4c415062016-06-17 16:14:16 -07001450 return BAD_VALUE;
1451 }
1452 }
1453 } break;
1454 case OFFLOAD:
Jean-Michel Trivi773ee952016-07-11 16:53:18 -07001455 // nothing actionable on offload threads, if the effect:
1456 // - is offloadable: the effect can be created
1457 // - is NOT offloadable: the effect should still be created, but EffectHandle::enable()
1458 // will take care of invalidating the tracks of the thread
Eric Laurent4c415062016-06-17 16:14:16 -07001459 break;
1460 case DIRECT:
1461 // Reject any effect on Direct output threads for now, since the format of
1462 // mSinkBuffer is not guaranteed to be compatible with effect processing (PCM 16 stereo).
Eric Laurentb62d0362021-10-26 17:40:18 +02001463 ALOGW("%s: effect %s on DIRECT output thread %s",
1464 __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001465 return BAD_VALUE;
1466 case DUPLICATING:
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001467 if (audio_is_global_session(sessionId)) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001468 ALOGW("%s: global effect %s on DUPLICATING thread %s",
1469 __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001470 return BAD_VALUE;
1471 }
1472 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001473 ALOGW("%s: post processing effect %s on DUPLICATING thread %s",
1474 __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001475 return BAD_VALUE;
1476 }
1477 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) != 0) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001478 ALOGW("%s: HW tunneled effect %s on DUPLICATING thread %s",
1479 __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001480 return BAD_VALUE;
1481 }
1482 break;
Eric Laurent1c5e2e32021-08-18 18:50:28 +02001483 case SPATIALIZER:
Eric Laurentb62d0362021-10-26 17:40:18 +02001484 // Global effects (AUDIO_SESSION_OUTPUT_MIX) are not supported on spatializer mixer
1485 // as there is no common accumulation buffer for sptialized and non sptialized tracks.
1486 // Post processing effects (AUDIO_SESSION_OUTPUT_STAGE or AUDIO_SESSION_DEVICE)
1487 // are supported and added after the spatializer.
1488 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1489 ALOGW("%s: global effect %s not supported on spatializer thread %s",
1490 __func__, desc->name, mThreadName);
Eric Laurentb3f315a2021-07-13 15:09:05 +02001491 return BAD_VALUE;
Eric Laurentb62d0362021-10-26 17:40:18 +02001492 } else if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1493 // only post processing , downmixer or spatializer effects on output stage session
1494 if (memcmp(&desc->type, FX_IID_SPATIALIZER, sizeof(effect_uuid_t)) == 0
1495 || memcmp(&desc->type, EFFECT_UIID_DOWNMIX, sizeof(effect_uuid_t)) == 0) {
1496 break;
1497 }
1498 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
1499 ALOGW("%s: non post processing effect %s not allowed on output stage session",
1500 __func__, desc->name);
1501 return BAD_VALUE;
1502 }
1503 } else if (sessionId == AUDIO_SESSION_DEVICE) {
1504 // only post processing on output stage session
1505 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
1506 ALOGW("%s: non post processing effect %s not allowed on device session",
1507 __func__, desc->name);
1508 return BAD_VALUE;
1509 }
Eric Laurentb3f315a2021-07-13 15:09:05 +02001510 }
1511 break;
jiabinc658e452022-10-21 20:52:21 +00001512 case BIT_PERFECT:
1513 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) != 0) {
1514 // Allow HW accelerated effects of tunnel type
1515 break;
1516 }
1517 // As bit-perfect tracks will not be allowed to apply audio effect that will touch the audio
1518 // data, effects will not be allowed on 1) global effects (AUDIO_SESSION_OUTPUT_MIX),
1519 // 2) post-processing effects (AUDIO_SESSION_OUTPUT_STAGE or AUDIO_SESSION_DEVICE) and
1520 // 3) there is any bit-perfect track with the given session id.
1521 if (sessionId == AUDIO_SESSION_OUTPUT_MIX || sessionId == AUDIO_SESSION_OUTPUT_STAGE ||
1522 sessionId == AUDIO_SESSION_DEVICE) {
1523 ALOGW("%s: effect %s not supported on bit-perfect thread %s",
1524 __func__, desc->name, mThreadName);
1525 return BAD_VALUE;
1526 } else if ((hasAudioSession_l(sessionId) & ThreadBase::BIT_PERFECT_SESSION) != 0) {
1527 ALOGW("%s: effect %s not supported as there is a bit-perfect track with session as %d",
1528 __func__, desc->name, sessionId);
1529 return BAD_VALUE;
1530 }
1531 break;
Eric Laurent4c415062016-06-17 16:14:16 -07001532 default:
1533 LOG_ALWAYS_FATAL("checkEffectCompatibility_l(): wrong thread type %d", mType);
1534 }
1535
1536 return NO_ERROR;
1537}
1538
Eric Laurent81784c32012-11-19 14:55:58 -08001539// ThreadBase::createEffect_l() must be called with AudioFlinger::mLock held
Andy Hungee58e4a2023-07-07 13:47:37 -07001540sp<IAfEffectHandle> ThreadBase::createEffect_l(
Andy Hung88035ac2023-06-27 17:05:02 -07001541 const sp<Client>& client,
Eric Laurent81784c32012-11-19 14:55:58 -08001542 const sp<IEffectClient>& effectClient,
1543 int32_t priority,
Glenn Kastend848eb42016-03-08 13:42:11 -08001544 audio_session_t sessionId,
Eric Laurent81784c32012-11-19 14:55:58 -08001545 effect_descriptor_t *desc,
1546 int *enabled,
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001547 status_t *status,
Eric Laurent2fe0acd2020-03-13 14:30:46 -07001548 bool pinned,
Eric Laurentde8caf42021-08-11 17:19:25 +02001549 bool probe,
1550 bool notifyFramesProcessed)
Eric Laurent81784c32012-11-19 14:55:58 -08001551{
Andy Hung116bc262023-06-20 18:56:17 -07001552 sp<IAfEffectModule> effect;
1553 sp<IAfEffectHandle> handle;
Eric Laurent81784c32012-11-19 14:55:58 -08001554 status_t lStatus;
Andy Hung116bc262023-06-20 18:56:17 -07001555 sp<IAfEffectChain> chain;
Eric Laurent81784c32012-11-19 14:55:58 -08001556 bool chainCreated = false;
1557 bool effectCreated = false;
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001558 audio_unique_id_t effectId = AUDIO_UNIQUE_ID_USE_UNSPECIFIED;
Eric Laurent81784c32012-11-19 14:55:58 -08001559
1560 lStatus = initCheck();
1561 if (lStatus != NO_ERROR) {
1562 ALOGW("createEffect_l() Audio driver not initialized.");
1563 goto Exit;
1564 }
1565
Eric Laurent81784c32012-11-19 14:55:58 -08001566 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
1567
1568 { // scope for mLock
1569 Mutex::Autolock _l(mLock);
1570
Eric Laurent4c415062016-06-17 16:14:16 -07001571 lStatus = checkEffectCompatibility_l(desc, sessionId);
Eric Laurent2fe0acd2020-03-13 14:30:46 -07001572 if (probe || lStatus != NO_ERROR) {
Eric Laurent4c415062016-06-17 16:14:16 -07001573 goto Exit;
1574 }
1575
Eric Laurent81784c32012-11-19 14:55:58 -08001576 // check for existing effect chain with the requested audio session
1577 chain = getEffectChain_l(sessionId);
1578 if (chain == 0) {
1579 // create a new chain for this session
1580 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
Andy Hung116bc262023-06-20 18:56:17 -07001581 chain = IAfEffectChain::create(this, sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08001582 addEffectChain_l(chain);
1583 chain->setStrategy(getStrategyForSession_l(sessionId));
1584 chainCreated = true;
1585 } else {
1586 effect = chain->getEffectFromDesc_l(desc);
1587 }
1588
1589 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
1590
1591 if (effect == 0) {
Andy Hung583043b2023-07-17 17:05:00 -07001592 effectId = mAfThreadCallback->nextUniqueId(AUDIO_UNIQUE_ID_USE_EFFECT);
Eric Laurent81784c32012-11-19 14:55:58 -08001593 // create a new effect module if none present in the chain
Eric Laurent6b446ce2019-12-13 10:56:31 -08001594 lStatus = chain->createEffect_l(effect, desc, effectId, sessionId, pinned);
Eric Laurent81784c32012-11-19 14:55:58 -08001595 if (lStatus != NO_ERROR) {
1596 goto Exit;
1597 }
1598 effectCreated = true;
1599
jiabinc52b1ff2019-10-31 17:20:42 -07001600 // FIXME: use vector of device and address when effect interface is ready.
jiabin8f278ee2019-11-11 12:16:27 -08001601 effect->setDevices(outDeviceTypeAddrs());
1602 effect->setInputDevice(inDeviceTypeAddr());
Andy Hung583043b2023-07-17 17:05:00 -07001603 effect->setMode(mAfThreadCallback->getMode());
Eric Laurent81784c32012-11-19 14:55:58 -08001604 effect->setAudioSource(mAudioSource);
1605 }
jiabin1319f5a2021-03-30 22:21:24 +00001606 if (effect->isHapticGenerator()) {
1607 // TODO(b/184194057): Use the vibrator information from the vibrator that will be used
1608 // for the HapticGenerator.
Lais Andradebc3f37a2021-07-02 00:13:19 +01001609 const std::optional<media::AudioVibratorInfo> defaultVibratorInfo =
Andy Hung583043b2023-07-17 17:05:00 -07001610 std::move(mAfThreadCallback->getDefaultVibratorInfo_l());
Lais Andradebc3f37a2021-07-02 00:13:19 +01001611 if (defaultVibratorInfo) {
jiabin1319f5a2021-03-30 22:21:24 +00001612 // Only set the vibrator info when it is a valid one.
Lais Andradebc3f37a2021-07-02 00:13:19 +01001613 effect->setVibratorInfo(*defaultVibratorInfo);
jiabin1319f5a2021-03-30 22:21:24 +00001614 }
1615 }
Eric Laurent81784c32012-11-19 14:55:58 -08001616 // create effect handle and connect it to effect module
Andy Hung116bc262023-06-20 18:56:17 -07001617 handle = IAfEffectHandle::create(
1618 effect, client, effectClient, priority, notifyFramesProcessed);
Glenn Kastene75da402013-11-20 13:54:52 -08001619 lStatus = handle->initCheck();
1620 if (lStatus == OK) {
1621 lStatus = effect->addHandle(handle.get());
Eric Laurentb3f315a2021-07-13 15:09:05 +02001622 sendCheckOutputStageEffectsEvent_l();
Glenn Kastene75da402013-11-20 13:54:52 -08001623 }
Eric Laurent81784c32012-11-19 14:55:58 -08001624 if (enabled != NULL) {
1625 *enabled = (int)effect->isEnabled();
1626 }
1627 }
1628
1629Exit:
Eric Laurent2fe0acd2020-03-13 14:30:46 -07001630 if (!probe && lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurent81784c32012-11-19 14:55:58 -08001631 Mutex::Autolock _l(mLock);
1632 if (effectCreated) {
1633 chain->removeEffect_l(effect);
1634 }
Eric Laurent81784c32012-11-19 14:55:58 -08001635 if (chainCreated) {
1636 removeEffectChain_l(chain);
1637 }
haobo101735295ff7b0d2017-03-17 17:44:03 +08001638 // handle must be cleared by caller to avoid deadlock.
Eric Laurent81784c32012-11-19 14:55:58 -08001639 }
1640
Glenn Kasten9156ef32013-08-06 15:39:08 -07001641 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001642 return handle;
1643}
1644
Andy Hungee58e4a2023-07-07 13:47:37 -07001645void ThreadBase::disconnectEffectHandle(IAfEffectHandle* handle,
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001646 bool unpinIfLast)
1647{
1648 bool remove = false;
Andy Hung116bc262023-06-20 18:56:17 -07001649 sp<IAfEffectModule> effect;
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001650 {
1651 Mutex::Autolock _l(mLock);
Andy Hung116bc262023-06-20 18:56:17 -07001652 sp<IAfEffectBase> effectBase = handle->effect().promote();
Eric Laurent41709552019-12-16 19:34:05 -08001653 if (effectBase == nullptr) {
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001654 return;
1655 }
Eric Laurentb82e6b72019-11-22 17:25:04 -08001656 effect = effectBase->asEffectModule();
1657 if (effect == nullptr) {
1658 return;
1659 }
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001660 // restore suspended effects if the disconnected handle was enabled and the last one.
1661 remove = (effect->removeHandle(handle) == 0) && (!effect->isPinned() || unpinIfLast);
1662 if (remove) {
1663 removeEffect_l(effect, true);
1664 }
Eric Laurentb3f315a2021-07-13 15:09:05 +02001665 sendCheckOutputStageEffectsEvent_l();
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001666 }
1667 if (remove) {
Andy Hung583043b2023-07-17 17:05:00 -07001668 mAfThreadCallback->updateOrphanEffectChains(effect);
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001669 if (handle->enabled()) {
Eric Laurent6b446ce2019-12-13 10:56:31 -08001670 effect->checkSuspendOnEffectEnabled(false, false /*threadLocked*/);
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001671 }
1672 }
1673}
1674
Andy Hungee58e4a2023-07-07 13:47:37 -07001675void ThreadBase::onEffectEnable(const sp<IAfEffectModule>& effect) {
Andy Hungea840382020-05-05 21:50:17 -07001676 if (isOffloadOrMmap()) {
Eric Laurent6b446ce2019-12-13 10:56:31 -08001677 Mutex::Autolock _l(mLock);
1678 broadcast_l();
1679 }
1680 if (!effect->isOffloadable()) {
1681 if (mType == ThreadBase::OFFLOAD) {
1682 PlaybackThread *t = (PlaybackThread *)this;
1683 t->invalidateTracks(AUDIO_STREAM_MUSIC);
1684 }
1685 if (effect->sessionId() == AUDIO_SESSION_OUTPUT_MIX) {
Andy Hung583043b2023-07-17 17:05:00 -07001686 mAfThreadCallback->onNonOffloadableGlobalEffectEnable();
Eric Laurent6b446ce2019-12-13 10:56:31 -08001687 }
1688 }
1689}
1690
Andy Hungee58e4a2023-07-07 13:47:37 -07001691void ThreadBase::onEffectDisable() {
Andy Hungea840382020-05-05 21:50:17 -07001692 if (isOffloadOrMmap()) {
Eric Laurent6b446ce2019-12-13 10:56:31 -08001693 Mutex::Autolock _l(mLock);
1694 broadcast_l();
1695 }
1696}
1697
Andy Hungee58e4a2023-07-07 13:47:37 -07001698sp<IAfEffectModule> ThreadBase::getEffect(audio_session_t sessionId,
Andy Hung440901d2023-06-29 21:19:25 -07001699 int effectId) const
Eric Laurent81784c32012-11-19 14:55:58 -08001700{
1701 Mutex::Autolock _l(mLock);
1702 return getEffect_l(sessionId, effectId);
1703}
1704
Andy Hungee58e4a2023-07-07 13:47:37 -07001705sp<IAfEffectModule> ThreadBase::getEffect_l(audio_session_t sessionId,
Andy Hung440901d2023-06-29 21:19:25 -07001706 int effectId) const
Eric Laurent81784c32012-11-19 14:55:58 -08001707{
Andy Hung116bc262023-06-20 18:56:17 -07001708 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08001709 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
1710}
1711
Andy Hungee58e4a2023-07-07 13:47:37 -07001712std::vector<int> ThreadBase::getEffectIds_l(audio_session_t sessionId) const
Eric Laurent6c796322019-04-09 14:13:17 -07001713{
Andy Hung116bc262023-06-20 18:56:17 -07001714 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent6c796322019-04-09 14:13:17 -07001715 return chain != nullptr ? chain->getEffectIds() : std::vector<int>{};
1716}
1717
Eric Laurent81784c32012-11-19 14:55:58 -08001718// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
1719// PlaybackThread::mLock held
Andy Hungee58e4a2023-07-07 13:47:37 -07001720status_t ThreadBase::addEffect_l(const sp<IAfEffectModule>& effect)
Eric Laurent81784c32012-11-19 14:55:58 -08001721{
1722 // check for existing effect chain with the requested audio session
Glenn Kastend848eb42016-03-08 13:42:11 -08001723 audio_session_t sessionId = effect->sessionId();
Andy Hung116bc262023-06-20 18:56:17 -07001724 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08001725 bool chainCreated = false;
1726
Eric Laurent5baf2af2013-09-12 17:37:00 -07001727 ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(),
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001728 "addEffect_l() on offloaded thread %p: effect %s does not support offload flags %#x",
Eric Laurent5baf2af2013-09-12 17:37:00 -07001729 this, effect->desc().name, effect->desc().flags);
1730
Eric Laurent81784c32012-11-19 14:55:58 -08001731 if (chain == 0) {
1732 // create a new chain for this session
1733 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
Andy Hung116bc262023-06-20 18:56:17 -07001734 chain = IAfEffectChain::create(this, sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08001735 addEffectChain_l(chain);
1736 chain->setStrategy(getStrategyForSession_l(sessionId));
1737 chainCreated = true;
1738 }
1739 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
1740
1741 if (chain->getEffectFromId_l(effect->id()) != 0) {
1742 ALOGW("addEffect_l() %p effect %s already present in chain %p",
1743 this, effect->desc().name, chain.get());
1744 return BAD_VALUE;
1745 }
1746
Eric Laurent5baf2af2013-09-12 17:37:00 -07001747 effect->setOffloaded(mType == OFFLOAD, mId);
1748
Eric Laurent81784c32012-11-19 14:55:58 -08001749 status_t status = chain->addEffect_l(effect);
1750 if (status != NO_ERROR) {
1751 if (chainCreated) {
1752 removeEffectChain_l(chain);
1753 }
1754 return status;
1755 }
1756
jiabin8f278ee2019-11-11 12:16:27 -08001757 effect->setDevices(outDeviceTypeAddrs());
1758 effect->setInputDevice(inDeviceTypeAddr());
Andy Hung583043b2023-07-17 17:05:00 -07001759 effect->setMode(mAfThreadCallback->getMode());
Eric Laurent81784c32012-11-19 14:55:58 -08001760 effect->setAudioSource(mAudioSource);
Eric Laurentd8365c52017-07-16 15:27:05 -07001761
Eric Laurent81784c32012-11-19 14:55:58 -08001762 return NO_ERROR;
1763}
1764
Andy Hungee58e4a2023-07-07 13:47:37 -07001765void ThreadBase::removeEffect_l(const sp<IAfEffectModule>& effect, bool release) {
Eric Laurent81784c32012-11-19 14:55:58 -08001766
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001767 ALOGV("%s %p effect %p", __FUNCTION__, this, effect.get());
Eric Laurent81784c32012-11-19 14:55:58 -08001768 effect_descriptor_t desc = effect->desc();
1769 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
1770 detachAuxEffect_l(effect->id());
1771 }
1772
Andy Hung116bc262023-06-20 18:56:17 -07001773 sp<IAfEffectChain> chain = effect->getCallback()->chain().promote();
Eric Laurent81784c32012-11-19 14:55:58 -08001774 if (chain != 0) {
1775 // remove effect chain if removing last effect
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001776 if (chain->removeEffect_l(effect, release) == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08001777 removeEffectChain_l(chain);
1778 }
1779 } else {
1780 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
1781 }
1782}
1783
Andy Hungee58e4a2023-07-07 13:47:37 -07001784void ThreadBase::lockEffectChains_l(
Andy Hung116bc262023-06-20 18:56:17 -07001785 Vector<sp<IAfEffectChain>>& effectChains)
Andy Hung920f6572022-10-06 12:09:49 -07001786NO_THREAD_SAFETY_ANALYSIS // calls EffectChain::lock()
Eric Laurent81784c32012-11-19 14:55:58 -08001787{
1788 effectChains = mEffectChains;
1789 for (size_t i = 0; i < mEffectChains.size(); i++) {
1790 mEffectChains[i]->lock();
1791 }
1792}
1793
Andy Hungee58e4a2023-07-07 13:47:37 -07001794void ThreadBase::unlockEffectChains(
Andy Hung116bc262023-06-20 18:56:17 -07001795 const Vector<sp<IAfEffectChain>>& effectChains)
Andy Hung920f6572022-10-06 12:09:49 -07001796NO_THREAD_SAFETY_ANALYSIS // calls EffectChain::unlock()
Eric Laurent81784c32012-11-19 14:55:58 -08001797{
1798 for (size_t i = 0; i < effectChains.size(); i++) {
1799 effectChains[i]->unlock();
1800 }
1801}
1802
Andy Hungee58e4a2023-07-07 13:47:37 -07001803sp<IAfEffectChain> ThreadBase::getEffectChain(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08001804{
1805 Mutex::Autolock _l(mLock);
1806 return getEffectChain_l(sessionId);
1807}
1808
Andy Hungee58e4a2023-07-07 13:47:37 -07001809sp<IAfEffectChain> ThreadBase::getEffectChain_l(audio_session_t sessionId)
Glenn Kastend848eb42016-03-08 13:42:11 -08001810 const
Eric Laurent81784c32012-11-19 14:55:58 -08001811{
1812 size_t size = mEffectChains.size();
1813 for (size_t i = 0; i < size; i++) {
1814 if (mEffectChains[i]->sessionId() == sessionId) {
1815 return mEffectChains[i];
1816 }
1817 }
1818 return 0;
1819}
1820
Andy Hungee58e4a2023-07-07 13:47:37 -07001821void ThreadBase::setMode(audio_mode_t mode)
Eric Laurent81784c32012-11-19 14:55:58 -08001822{
1823 Mutex::Autolock _l(mLock);
1824 size_t size = mEffectChains.size();
1825 for (size_t i = 0; i < size; i++) {
1826 mEffectChains[i]->setMode_l(mode);
1827 }
1828}
1829
Andy Hungee58e4a2023-07-07 13:47:37 -07001830void ThreadBase::toAudioPortConfig(struct audio_port_config* config)
Eric Laurent83b88082014-06-20 18:31:16 -07001831{
1832 config->type = AUDIO_PORT_TYPE_MIX;
1833 config->ext.mix.handle = mId;
1834 config->sample_rate = mSampleRate;
1835 config->format = mFormat;
1836 config->channel_mask = mChannelMask;
1837 config->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
1838 AUDIO_PORT_CONFIG_FORMAT;
1839}
1840
Andy Hungee58e4a2023-07-07 13:47:37 -07001841void ThreadBase::systemReady()
Eric Laurent72e3f392015-05-20 14:43:50 -07001842{
1843 Mutex::Autolock _l(mLock);
1844 if (mSystemReady) {
1845 return;
1846 }
1847 mSystemReady = true;
1848
1849 for (size_t i = 0; i < mPendingConfigEvents.size(); i++) {
1850 sendConfigEvent_l(mPendingConfigEvents.editItemAt(i));
1851 }
1852 mPendingConfigEvents.clear();
1853}
1854
Andy Hungdae27702016-10-31 14:01:16 -07001855template <typename T>
Andy Hungee58e4a2023-07-07 13:47:37 -07001856ssize_t ThreadBase::ActiveTracks<T>::add(const sp<T>& track) {
Andy Hungdae27702016-10-31 14:01:16 -07001857 ssize_t index = mActiveTracks.indexOf(track);
1858 if (index >= 0) {
1859 ALOGW("ActiveTracks<T>::add track %p already there", track.get());
1860 return index;
1861 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001862 logTrack("add", track);
Andy Hungdae27702016-10-31 14:01:16 -07001863 mActiveTracksGeneration++;
1864 mLatestActiveTrack = track;
Atneya Nair166663a2023-06-27 19:16:24 -07001865 track->beginBatteryAttribution();
Kevin Rocard069c2712018-03-29 19:09:14 -07001866 mHasChanged = true;
Andy Hungdae27702016-10-31 14:01:16 -07001867 return mActiveTracks.add(track);
1868}
1869
1870template <typename T>
Andy Hungee58e4a2023-07-07 13:47:37 -07001871ssize_t ThreadBase::ActiveTracks<T>::remove(const sp<T>& track) {
Andy Hungdae27702016-10-31 14:01:16 -07001872 ssize_t index = mActiveTracks.remove(track);
1873 if (index < 0) {
1874 ALOGW("ActiveTracks<T>::remove nonexistent track %p", track.get());
1875 return index;
1876 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001877 logTrack("remove", track);
Andy Hungdae27702016-10-31 14:01:16 -07001878 mActiveTracksGeneration++;
Atneya Nair166663a2023-06-27 19:16:24 -07001879 track->endBatteryAttribution();
Andy Hungdae27702016-10-31 14:01:16 -07001880 // mLatestActiveTrack is not cleared even if is the same as track.
Kevin Rocard069c2712018-03-29 19:09:14 -07001881 mHasChanged = true;
Andy Hung8946a282018-04-19 20:04:56 -07001882#ifdef TEE_SINK
1883 track->dumpTee(-1 /* fd */, "_REMOVE");
1884#endif
Andy Hungc2b11cb2020-04-22 09:04:01 -07001885 track->logEndInterval(); // log to MediaMetrics
Andy Hungdae27702016-10-31 14:01:16 -07001886 return index;
1887}
1888
1889template <typename T>
Andy Hungee58e4a2023-07-07 13:47:37 -07001890void ThreadBase::ActiveTracks<T>::clear() {
Andy Hungdae27702016-10-31 14:01:16 -07001891 for (const sp<T> &track : mActiveTracks) {
Atneya Nair166663a2023-06-27 19:16:24 -07001892 track->endBatteryAttribution();
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001893 logTrack("clear", track);
Andy Hungdae27702016-10-31 14:01:16 -07001894 }
1895 mLastActiveTracksGeneration = mActiveTracksGeneration;
Kevin Rocard069c2712018-03-29 19:09:14 -07001896 if (!mActiveTracks.empty()) { mHasChanged = true; }
Andy Hungdae27702016-10-31 14:01:16 -07001897 mActiveTracks.clear();
1898 mLatestActiveTrack.clear();
Andy Hungdae27702016-10-31 14:01:16 -07001899}
1900
1901template <typename T>
Andy Hungee58e4a2023-07-07 13:47:37 -07001902void ThreadBase::ActiveTracks<T>::updatePowerState(
Andy Hung920f6572022-10-06 12:09:49 -07001903 const sp<ThreadBase>& thread, bool force) {
Andy Hungdae27702016-10-31 14:01:16 -07001904 // Updates ActiveTracks client uids to the thread wakelock.
1905 if (mActiveTracksGeneration != mLastActiveTracksGeneration || force) {
1906 thread->updateWakeLockUids_l(getWakeLockUids());
1907 mLastActiveTracksGeneration = mActiveTracksGeneration;
1908 }
Andy Hungdae27702016-10-31 14:01:16 -07001909}
Eric Laurent83b88082014-06-20 18:31:16 -07001910
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001911template <typename T>
Andy Hungee58e4a2023-07-07 13:47:37 -07001912bool ThreadBase::ActiveTracks<T>::readAndClearHasChanged() {
Jasmine Chaeaa10e42021-05-11 10:11:14 +08001913 bool hasChanged = mHasChanged;
Kevin Rocard069c2712018-03-29 19:09:14 -07001914 mHasChanged = false;
Jasmine Chaeaa10e42021-05-11 10:11:14 +08001915
1916 for (const sp<T> &track : mActiveTracks) {
1917 // Do not short-circuit as all hasChanged states must be reset
1918 // as all the metadata are going to be sent
1919 hasChanged |= track->readAndClearHasChanged();
1920 }
Kevin Rocard069c2712018-03-29 19:09:14 -07001921 return hasChanged;
1922}
1923
1924template <typename T>
Andy Hungee58e4a2023-07-07 13:47:37 -07001925void ThreadBase::ActiveTracks<T>::logTrack(
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001926 const char *funcName, const sp<T> &track) const {
1927 if (mLocalLog != nullptr) {
1928 String8 result;
1929 track->appendDump(result, false /* active */);
1930 mLocalLog->log("AT::%-10s(%p) %s", funcName, track.get(), result.string());
1931 }
1932}
1933
Andy Hungee58e4a2023-07-07 13:47:37 -07001934void ThreadBase::broadcast_l()
Eric Laurent6acd1d42017-01-04 14:23:29 -08001935{
1936 // Thread could be blocked waiting for async
1937 // so signal it to handle state changes immediately
1938 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
1939 // be lost so we also flag to prevent it blocking on mWaitWorkCV
1940 mSignalPending = true;
1941 mWaitWorkCV.broadcast();
1942}
1943
Andy Hungd0979812019-02-21 15:51:44 -08001944// Call only from threadLoop() or when it is idle.
1945// Do not call from high performance code as this may do binder rpc to the MediaMetrics service.
Andy Hungee58e4a2023-07-07 13:47:37 -07001946void ThreadBase::sendStatistics(bool force)
Andy Hungd0979812019-02-21 15:51:44 -08001947{
1948 // Do not log if we have no stats.
1949 // We choose the timestamp verifier because it is the most likely item to be present.
1950 const int64_t nstats = mTimestampVerifier.getN() - mLastRecordedTimestampVerifierN;
1951 if (nstats == 0) {
1952 return;
1953 }
1954
1955 // Don't log more frequently than once per 12 hours.
1956 // We use BOOTTIME to include suspend time.
1957 const int64_t timeNs = systemTime(SYSTEM_TIME_BOOTTIME);
1958 const int64_t sinceNs = timeNs - mLastRecordedTimeNs; // ok if mLastRecordedTimeNs = 0
1959 if (!force && sinceNs <= 12 * NANOS_PER_HOUR) {
1960 return;
1961 }
1962
1963 mLastRecordedTimestampVerifierN = mTimestampVerifier.getN();
1964 mLastRecordedTimeNs = timeNs;
1965
Ray Essickf27e9872019-12-07 06:28:46 -08001966 std::unique_ptr<mediametrics::Item> item(mediametrics::Item::create("audiothread"));
Andy Hungd0979812019-02-21 15:51:44 -08001967
1968#define MM_PREFIX "android.media.audiothread." // avoid cut-n-paste errors.
1969
1970 // thread configuration
1971 item->setInt32(MM_PREFIX "id", (int32_t)mId); // IO handle
1972 // item->setInt32(MM_PREFIX "portId", (int32_t)mPortId);
1973 item->setCString(MM_PREFIX "type", threadTypeToString(mType));
1974 item->setInt32(MM_PREFIX "sampleRate", (int32_t)mSampleRate);
1975 item->setInt64(MM_PREFIX "channelMask", (int64_t)mChannelMask);
1976 item->setCString(MM_PREFIX "encoding", toString(mFormat).c_str());
1977 item->setInt32(MM_PREFIX "frameCount", (int32_t)mFrameCount);
jiabinc52b1ff2019-10-31 17:20:42 -07001978 item->setCString(MM_PREFIX "outDevice", toString(outDeviceTypes()).c_str());
1979 item->setCString(MM_PREFIX "inDevice", toString(inDeviceType()).c_str());
Andy Hungd0979812019-02-21 15:51:44 -08001980
1981 // thread statistics
1982 if (mIoJitterMs.getN() > 0) {
1983 item->setDouble(MM_PREFIX "ioJitterMs.mean", mIoJitterMs.getMean());
1984 item->setDouble(MM_PREFIX "ioJitterMs.std", mIoJitterMs.getStdDev());
1985 }
1986 if (mProcessTimeMs.getN() > 0) {
1987 item->setDouble(MM_PREFIX "processTimeMs.mean", mProcessTimeMs.getMean());
1988 item->setDouble(MM_PREFIX "processTimeMs.std", mProcessTimeMs.getStdDev());
1989 }
1990 const auto tsjitter = mTimestampVerifier.getJitterMs();
1991 if (tsjitter.getN() > 0) {
1992 item->setDouble(MM_PREFIX "timestampJitterMs.mean", tsjitter.getMean());
1993 item->setDouble(MM_PREFIX "timestampJitterMs.std", tsjitter.getStdDev());
1994 }
1995 if (mLatencyMs.getN() > 0) {
1996 item->setDouble(MM_PREFIX "latencyMs.mean", mLatencyMs.getMean());
1997 item->setDouble(MM_PREFIX "latencyMs.std", mLatencyMs.getStdDev());
1998 }
Robert Wu06db0a32021-08-10 19:05:34 +00001999 if (mMonopipePipeDepthStats.getN() > 0) {
2000 item->setDouble(MM_PREFIX "monopipePipeDepthStats.mean",
2001 mMonopipePipeDepthStats.getMean());
2002 item->setDouble(MM_PREFIX "monopipePipeDepthStats.std",
2003 mMonopipePipeDepthStats.getStdDev());
2004 }
Andy Hungd0979812019-02-21 15:51:44 -08002005
2006 item->selfrecord();
2007}
2008
Andy Hungee58e4a2023-07-07 13:47:37 -07002009product_strategy_t ThreadBase::getStrategyForStream(audio_stream_type_t stream) const
Eric Laurentd66d7a12021-07-13 13:35:32 +02002010{
Andy Hung583043b2023-07-17 17:05:00 -07002011 if (!mAfThreadCallback->isAudioPolicyReady()) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02002012 return PRODUCT_STRATEGY_NONE;
2013 }
2014 return AudioSystem::getStrategyForStream(stream);
2015}
2016
Vlad Popa6fbbfbf2023-02-22 15:05:43 +01002017// startMelComputation_l() must be called with AudioFlinger::mLock held
Andy Hungee58e4a2023-07-07 13:47:37 -07002018void ThreadBase::startMelComputation_l(
Vlad Popa6fbbfbf2023-02-22 15:05:43 +01002019 const sp<audio_utils::MelProcessor>& /*processor*/)
2020{
2021 // Do nothing
2022 ALOGW("%s: ThreadBase does not support CSD", __func__);
2023}
2024
2025// stopMelComputation_l() must be called with AudioFlinger::mLock held
Andy Hungee58e4a2023-07-07 13:47:37 -07002026void ThreadBase::stopMelComputation_l()
Vlad Popa6fbbfbf2023-02-22 15:05:43 +01002027{
2028 // Do nothing
2029 ALOGW("%s: ThreadBase does not support CSD", __func__);
2030}
2031
Eric Laurent81784c32012-11-19 14:55:58 -08002032// ----------------------------------------------------------------------------
2033// Playback
2034// ----------------------------------------------------------------------------
2035
Andy Hung583043b2023-07-17 17:05:00 -07002036PlaybackThread::PlaybackThread(const sp<IAfThreadCallback>& afThreadCallback,
Eric Laurent81784c32012-11-19 14:55:58 -08002037 AudioStreamOut* output,
2038 audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -07002039 type_t type,
Eric Laurentf1f22e72021-07-13 14:04:14 +02002040 bool systemReady,
2041 audio_config_base_t *mixerConfig)
Andy Hung583043b2023-07-17 17:05:00 -07002042 : ThreadBase(afThreadCallback, id, type, systemReady, true /* isOut */),
Andy Hung2098f272014-02-27 14:00:06 -08002043 mNormalFrameCount(0), mSinkBuffer(NULL),
Eric Laurent1c5e2e32021-08-18 18:50:28 +02002044 mMixerBufferEnabled(AudioFlinger::kEnableExtendedPrecision || type == SPATIALIZER),
Andy Hung69aed5f2014-02-25 17:24:40 -08002045 mMixerBuffer(NULL),
2046 mMixerBufferSize(0),
2047 mMixerBufferFormat(AUDIO_FORMAT_INVALID),
2048 mMixerBufferValid(false),
Eric Laurent1c5e2e32021-08-18 18:50:28 +02002049 mEffectBufferEnabled(AudioFlinger::kEnableExtendedPrecision || type == SPATIALIZER),
Andy Hung98ef9782014-03-04 14:46:50 -08002050 mEffectBuffer(NULL),
2051 mEffectBufferSize(0),
2052 mEffectBufferFormat(AUDIO_FORMAT_INVALID),
2053 mEffectBufferValid(false),
Glenn Kastenc1fac192013-08-06 07:41:36 -07002054 mSuspended(0), mBytesWritten(0),
Andy Hungc54b1ff2016-02-23 14:07:07 -08002055 mFramesWritten(0),
Andy Hung238fa3d2016-07-28 10:53:22 -07002056 mSuspendedFrames(0),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002057 mActiveTracks(&this->mLocalLog),
Eric Laurent81784c32012-11-19 14:55:58 -08002058 // mStreamTypes[] initialized in constructor body
Andy Hung1bc088a2018-02-09 15:57:31 -08002059 mTracks(type == MIXER),
Eric Laurent81784c32012-11-19 14:55:58 -08002060 mOutput(output),
Andy Hung446f4df2019-02-21 12:26:41 -08002061 mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
Eric Laurent81784c32012-11-19 14:55:58 -08002062 mMixerStatus(MIXER_IDLE),
2063 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002064 mStandbyDelayNs(AudioFlinger::mStandbyTimeInNsecs),
Eric Laurentbfb1b832013-01-07 09:53:42 -08002065 mBytesRemaining(0),
2066 mCurrentWriteLength(0),
2067 mUseAsyncWrite(false),
Eric Laurent3b4529e2013-09-05 18:09:19 -07002068 mWriteAckSequence(0),
2069 mDrainSequence(0),
Eric Laurent81784c32012-11-19 14:55:58 -08002070 mScreenState(AudioFlinger::mScreenState),
2071 // index 0 is reserved for normal mixer's submix
Glenn Kastendc2c50b2016-04-21 08:13:14 -07002072 mFastTrackAvailMask(((1 << FastMixerState::sMaxFastTracks) - 1) & ~1),
Eric Laurent7c29ec92017-09-20 17:54:22 -07002073 mHwSupportsPause(false), mHwPaused(false), mFlushPending(false),
Eric Laurent74c38dc2020-12-23 18:19:44 +01002074 mLeftVolFloat(-1.0), mRightVolFloat(-1.0),
Brian Lindahl65e90012022-07-27 18:01:07 +02002075 mDownStreamPatch{},
Eric Laurentb0463942022-12-20 16:31:10 +01002076 mIsTimestampAdvancing(kMinimumTimeBetweenTimestampChecksNs)
Eric Laurent81784c32012-11-19 14:55:58 -08002077{
Glenn Kastend7dca052015-03-05 16:05:54 -08002078 snprintf(mThreadName, kThreadNameLength, "AudioOut_%X", id);
Andy Hung583043b2023-07-17 17:05:00 -07002079 mNBLogWriter = afThreadCallback->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08002080
2081 // Assumes constructor is called by AudioFlinger with it's mLock held, but
2082 // it would be safer to explicitly pass initial masterVolume/masterMute as
2083 // parameter.
2084 //
2085 // If the HAL we are using has support for master volume or master mute,
2086 // then do not attenuate or mute during mixing (just leave the volume at 1.0
2087 // and the mute set to false).
Andy Hung583043b2023-07-17 17:05:00 -07002088 mMasterVolume = afThreadCallback->masterVolume_l();
2089 mMasterMute = afThreadCallback->masterMute_l();
George Burgess IV5e4d86f2020-02-18 12:55:36 -08002090 if (mOutput->audioHwDev) {
Eric Laurent81784c32012-11-19 14:55:58 -08002091 if (mOutput->audioHwDev->canSetMasterVolume()) {
2092 mMasterVolume = 1.0;
2093 }
2094
2095 if (mOutput->audioHwDev->canSetMasterMute()) {
2096 mMasterMute = false;
2097 }
Andy Hungc8fddf32018-08-08 18:32:37 -07002098 mIsMsdDevice = strcmp(
2099 mOutput->audioHwDev->moduleName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002100 }
2101
Eric Laurentf1f22e72021-07-13 14:04:14 +02002102 if (mixerConfig != nullptr && mixerConfig->channel_mask != AUDIO_CHANNEL_NONE) {
2103 mMixerChannelMask = mixerConfig->channel_mask;
2104 }
2105
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002106 readOutputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002107
Eric Laurent1c5e2e32021-08-18 18:50:28 +02002108 if (mType != SPATIALIZER
Eric Laurentb3f315a2021-07-13 15:09:05 +02002109 && mMixerChannelMask != mChannelMask) {
2110 LOG_ALWAYS_FATAL("HAL channel mask %#x does not match mixer channel mask %#x",
2111 mChannelMask, mMixerChannelMask);
2112 }
2113
Andy Hungc8fddf32018-08-08 18:32:37 -07002114 // TODO: We may also match on address as well as device type for
2115 // AUDIO_DEVICE_OUT_BUS, AUDIO_DEVICE_OUT_ALL_A2DP, AUDIO_DEVICE_OUT_REMOTE_SUBMIX
Dean Wheatleyf8726f02019-12-02 14:12:01 +11002116 if (type == MIXER || type == DIRECT || type == OFFLOAD) {
jiabinc52b1ff2019-10-31 17:20:42 -07002117 // TODO: This property should be ensure that only contains one single device type.
2118 mTimestampCorrectedDevice = (audio_devices_t)property_get_int64(
2119 "audio.timestamp.corrected_output_device",
Andy Hungc8fddf32018-08-08 18:32:37 -07002120 (int64_t)(mIsMsdDevice ? AUDIO_DEVICE_OUT_BUS // turn on by default for MSD
2121 : AUDIO_DEVICE_NONE));
2122 }
2123
Mikhail Naganovf33115d2020-09-25 23:03:05 +00002124 for (int i = AUDIO_STREAM_MIN; i < AUDIO_STREAM_FOR_POLICY_CNT; ++i) {
2125 const audio_stream_type_t stream{static_cast<audio_stream_type_t>(i)};
Eric Laurent98e38192018-02-15 18:31:53 -08002126 mStreamTypes[stream].volume = 0.0f;
Andy Hung583043b2023-07-17 17:05:00 -07002127 mStreamTypes[stream].mute = mAfThreadCallback->streamMute_l(stream);
Eric Laurent81784c32012-11-19 14:55:58 -08002128 }
Eric Laurent35f8c7c2020-02-08 11:42:35 -08002129 // Audio patch and call assistant volume are always max
Eric Laurent98e38192018-02-15 18:31:53 -08002130 mStreamTypes[AUDIO_STREAM_PATCH].volume = 1.0f;
2131 mStreamTypes[AUDIO_STREAM_PATCH].mute = false;
Eric Laurent35f8c7c2020-02-08 11:42:35 -08002132 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].volume = 1.0f;
2133 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].mute = false;
Eric Laurent81784c32012-11-19 14:55:58 -08002134}
2135
Andy Hungee58e4a2023-07-07 13:47:37 -07002136PlaybackThread::~PlaybackThread()
Eric Laurent81784c32012-11-19 14:55:58 -08002137{
Andy Hung583043b2023-07-17 17:05:00 -07002138 mAfThreadCallback->unregisterWriter(mNBLogWriter);
Andy Hung010a1a12014-03-13 13:57:33 -07002139 free(mSinkBuffer);
Andy Hung69aed5f2014-02-25 17:24:40 -08002140 free(mMixerBuffer);
Andy Hung98ef9782014-03-04 14:46:50 -08002141 free(mEffectBuffer);
Eric Laurentb62d0362021-10-26 17:40:18 +02002142 free(mPostSpatializerBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08002143}
2144
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002145// Thread virtuals
2146
Andy Hungee58e4a2023-07-07 13:47:37 -07002147void PlaybackThread::onFirstRef()
Eric Laurent81784c32012-11-19 14:55:58 -08002148{
Jasmine Chaeaa10e42021-05-11 10:11:14 +08002149 if (!isStreamInitialized()) {
jiabinf6eb4c32020-02-25 14:06:25 -08002150 ALOGE("The stream is not open yet"); // This should not happen.
2151 } else {
Mikhail Naganovaec565e2023-02-22 16:31:28 -08002152 // Callbacks take strong or weak pointers as a parameter.
2153 // Since PlaybackThread passes itself as a callback handler, it can only
2154 // be done outside of the constructor. Creating weak and especially strong
2155 // pointers to a refcounted object in its own constructor is strongly
2156 // discouraged, see comments in system/core/libutils/include/utils/RefBase.h.
2157 // Even if a function takes a weak pointer, it is possible that it will
2158 // need to convert it to a strong pointer down the line.
2159 if (mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING &&
2160 mOutput->stream->setCallback(this) == OK) {
2161 mUseAsyncWrite = true;
Andy Hungee58e4a2023-07-07 13:47:37 -07002162 mCallbackThread = sp<AsyncCallbackThread>::make(this);
Mikhail Naganovaec565e2023-02-22 16:31:28 -08002163 }
2164
jiabinf6eb4c32020-02-25 14:06:25 -08002165 if (mOutput->stream->setEventCallback(this) != OK) {
jiabinf1a36052020-08-19 14:33:31 -07002166 ALOGD("Failed to add event callback");
jiabinf6eb4c32020-02-25 14:06:25 -08002167 }
2168 }
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002169 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
Andy Hung44d648b2022-04-08 17:33:40 -07002170 mThreadSnapshot.setTid(getTid());
Eric Laurent81784c32012-11-19 14:55:58 -08002171}
2172
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002173// ThreadBase virtuals
Andy Hungee58e4a2023-07-07 13:47:37 -07002174void PlaybackThread::preExit()
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002175{
2176 ALOGV(" preExit()");
Ytai Ben-Tsvi7e0183f2022-02-04 10:49:54 -08002177 status_t result = mOutput->stream->exit();
2178 ALOGE_IF(result != OK, "Error when calling exit(): %d", result);
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002179}
2180
Andy Hungee58e4a2023-07-07 13:47:37 -07002181void PlaybackThread::dumpTracks_l(int fd, const Vector<String16>& /* args */)
Eric Laurent81784c32012-11-19 14:55:58 -08002182{
Eric Laurent81784c32012-11-19 14:55:58 -08002183 String8 result;
2184
Marco Nelissenb2208842014-02-07 14:00:50 -08002185 result.appendFormat(" Stream volumes in dB: ");
Eric Laurent81784c32012-11-19 14:55:58 -08002186 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
2187 const stream_type_t *st = &mStreamTypes[i];
2188 if (i > 0) {
2189 result.appendFormat(", ");
2190 }
2191 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
2192 if (st->mute) {
2193 result.append("M");
2194 }
2195 }
2196 result.append("\n");
2197 write(fd, result.string(), result.length());
2198 result.clear();
2199
Eric Laurent81784c32012-11-19 14:55:58 -08002200 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
2201 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
Elliott Hughes87cebad2014-05-22 10:14:43 -07002202 dprintf(fd, " Normal mixer raw underrun counters: partial=%u empty=%u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08002203 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Marco Nelissenb2208842014-02-07 14:00:50 -08002204
2205 size_t numtracks = mTracks.size();
2206 size_t numactive = mActiveTracks.size();
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002207 dprintf(fd, " %zu Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08002208 size_t numactiveseen = 0;
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002209 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08002210 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002211 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002212 result.append(prefix);
Andy Hungf6ab58d2018-05-25 12:50:39 -07002213 mTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08002214 for (size_t i = 0; i < numtracks; ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07002215 sp<IAfTrack> track = mTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08002216 if (track != 0) {
2217 bool active = mActiveTracks.indexOf(track) >= 0;
2218 if (active) {
2219 numactiveseen++;
2220 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002221 result.append(prefix);
2222 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08002223 }
2224 }
2225 } else {
2226 result.append("\n");
2227 }
2228 if (numactiveseen != numactive) {
2229 // some tracks in the active list were not in the tracks list
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002230 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08002231 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002232 result.append(prefix);
Andy Hungf6ab58d2018-05-25 12:50:39 -07002233 mActiveTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08002234 for (size_t i = 0; i < numactive; ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07002235 sp<IAfTrack> track = mActiveTracks[i];
Andy Hungdae27702016-10-31 14:01:16 -07002236 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002237 result.append(prefix);
2238 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08002239 }
2240 }
2241 }
2242
2243 write(fd, result.string(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08002244}
2245
Andy Hungee58e4a2023-07-07 13:47:37 -07002246void PlaybackThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -08002247{
Andy Hung04cb8f72020-03-20 13:44:33 -07002248 dprintf(fd, " Master volume: %f\n", mMasterVolume);
Mikhail Naganovdfb411f2018-09-11 13:39:56 -07002249 dprintf(fd, " Master mute: %s\n", mMasterMute ? "on" : "off");
Eric Laurentf1f22e72021-07-13 14:04:14 +02002250 dprintf(fd, " Mixer channel Mask: %#x (%s)\n",
2251 mMixerChannelMask, channelMaskToString(mMixerChannelMask, true /* output */).c_str());
jiabin245cdd92018-12-07 17:55:15 -08002252 if (mHapticChannelMask != AUDIO_CHANNEL_NONE) {
2253 dprintf(fd, " Haptic channel mask: %#x (%s)\n", mHapticChannelMask,
2254 channelMaskToString(mHapticChannelMask, true /* output */).c_str());
2255 }
Elliott Hughes87cebad2014-05-22 10:14:43 -07002256 dprintf(fd, " Normal frame count: %zu\n", mNormalFrameCount);
Elliott Hughes87cebad2014-05-22 10:14:43 -07002257 dprintf(fd, " Total writes: %d\n", mNumWrites);
2258 dprintf(fd, " Delayed writes: %d\n", mNumDelayedWrites);
2259 dprintf(fd, " Blocked in write: %s\n", mInWrite ? "yes" : "no");
2260 dprintf(fd, " Suspend count: %d\n", mSuspended);
2261 dprintf(fd, " Sink buffer : %p\n", mSinkBuffer);
2262 dprintf(fd, " Mixer buffer: %p\n", mMixerBuffer);
2263 dprintf(fd, " Effect buffer: %p\n", mEffectBuffer);
2264 dprintf(fd, " Fast track availMask=%#x\n", mFastTrackAvailMask);
Eric Laurent42537be2016-01-08 17:16:42 -08002265 dprintf(fd, " Standby delay ns=%lld\n", (long long)mStandbyDelayNs);
Glenn Kasten97b7b752014-09-28 13:04:24 -07002266 AudioStreamOut *output = mOutput;
2267 audio_output_flags_t flags = output != NULL ? output->flags : AUDIO_OUTPUT_FLAG_NONE;
Mikhail Naganov913d06c2016-11-01 12:49:22 -07002268 dprintf(fd, " AudioStreamOut: %p flags %#x (%s)\n",
Andy Hung9b181952019-02-25 14:53:36 -08002269 output, flags, toString(flags).c_str());
Andy Hungb54c8542016-09-21 12:55:15 -07002270 dprintf(fd, " Frames written: %lld\n", (long long)mFramesWritten);
2271 dprintf(fd, " Suspended frames: %lld\n", (long long)mSuspendedFrames);
2272 if (mPipeSink.get() != nullptr) {
2273 dprintf(fd, " PipeSink frames written: %lld\n", (long long)mPipeSink->framesWritten());
2274 }
2275 if (output != nullptr) {
2276 dprintf(fd, " Hal stream dump:\n");
Andy Hung61589a42021-06-16 09:37:53 -07002277 (void)output->stream->dump(fd, args);
Andy Hungb54c8542016-09-21 12:55:15 -07002278 }
Eric Laurent81784c32012-11-19 14:55:58 -08002279}
2280
Eric Laurent81784c32012-11-19 14:55:58 -08002281// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
Andy Hungee58e4a2023-07-07 13:47:37 -07002282sp<IAfTrack> PlaybackThread::createTrack_l(
Andy Hung88035ac2023-06-27 17:05:02 -07002283 const sp<Client>& client,
Eric Laurent81784c32012-11-19 14:55:58 -08002284 audio_stream_type_t streamType,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07002285 const audio_attributes_t& attr,
Eric Laurent21da6472017-11-09 16:29:26 -08002286 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08002287 audio_format_t format,
2288 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08002289 size_t *pFrameCount,
Eric Laurent21da6472017-11-09 16:29:26 -08002290 size_t *pNotificationFrameCount,
2291 uint32_t notificationsPerBuffer,
2292 float speed,
Eric Laurent81784c32012-11-19 14:55:58 -08002293 const sp<IMemory>& sharedBuffer,
Glenn Kastend848eb42016-03-08 13:42:11 -08002294 audio_session_t sessionId,
Eric Laurent05067782016-06-01 18:27:28 -07002295 audio_output_flags_t *flags,
Eric Laurent09f1ed22019-04-24 17:45:17 -07002296 pid_t creatorPid,
Svet Ganov33761132021-05-13 22:51:08 +00002297 const AttributionSourceState& attributionSource,
Eric Laurent81784c32012-11-19 14:55:58 -08002298 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002299 status_t *status,
jiabinf6eb4c32020-02-25 14:06:25 -08002300 audio_port_handle_t portId,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02002301 const sp<media::IAudioTrackCallback>& callback,
jiabinc658e452022-10-21 20:52:21 +00002302 bool isSpatialized,
2303 bool isBitPerfect)
Eric Laurent81784c32012-11-19 14:55:58 -08002304{
Glenn Kasten74935e42013-12-19 08:56:45 -08002305 size_t frameCount = *pFrameCount;
Eric Laurent21da6472017-11-09 16:29:26 -08002306 size_t notificationFrameCount = *pNotificationFrameCount;
Andy Hung8d31fd22023-06-26 19:20:57 -07002307 sp<IAfTrack> track;
Eric Laurent81784c32012-11-19 14:55:58 -08002308 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07002309 audio_output_flags_t outputFlags = mOutput->flags;
Eric Laurent21da6472017-11-09 16:29:26 -08002310 audio_output_flags_t requestedFlags = *flags;
Eric Laurent9b11c022018-06-06 19:19:22 -07002311 uint32_t sampleRate;
2312
2313 if (sharedBuffer != 0 && checkIMemory(sharedBuffer) != NO_ERROR) {
2314 lStatus = BAD_VALUE;
2315 goto Exit;
2316 }
Eric Laurent21da6472017-11-09 16:29:26 -08002317
2318 if (*pSampleRate == 0) {
2319 *pSampleRate = mSampleRate;
2320 }
Eric Laurent9b11c022018-06-06 19:19:22 -07002321 sampleRate = *pSampleRate;
Eric Laurent05067782016-06-01 18:27:28 -07002322
2323 // special case for FAST flag considered OK if fast mixer is present
2324 if (hasFastMixer()) {
2325 outputFlags = (audio_output_flags_t)(outputFlags | AUDIO_OUTPUT_FLAG_FAST);
2326 }
2327
2328 // Check if requested flags are compatible with output stream flags
2329 if ((*flags & outputFlags) != *flags) {
2330 ALOGW("createTrack_l(): mismatch between requested flags (%08x) and output flags (%08x)",
2331 *flags, outputFlags);
2332 *flags = (audio_output_flags_t)(*flags & outputFlags);
2333 }
Eric Laurent81784c32012-11-19 14:55:58 -08002334
jiabinc658e452022-10-21 20:52:21 +00002335 if (isBitPerfect) {
Andy Hung116bc262023-06-20 18:56:17 -07002336 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
jiabinc658e452022-10-21 20:52:21 +00002337 if (chain.get() != nullptr) {
2338 // Bit-perfect is required according to the configuration and preferred mixer
2339 // attributes, but it is not in the output flag from the client's request. Explicitly
2340 // adding bit-perfect flag to check the compatibility
2341 audio_output_flags_t flagsToCheck =
2342 (audio_output_flags_t)(*flags & AUDIO_OUTPUT_FLAG_BIT_PERFECT);
2343 chain->checkOutputFlagCompatibility(&flagsToCheck);
2344 if ((flagsToCheck & AUDIO_OUTPUT_FLAG_BIT_PERFECT) == AUDIO_OUTPUT_FLAG_NONE) {
2345 ALOGE("%s cannot create track as there is data-processing effect attached to "
2346 "given session id(%d)", __func__, sessionId);
2347 lStatus = BAD_VALUE;
2348 goto Exit;
2349 }
2350 *flags = flagsToCheck;
2351 }
2352 }
2353
Eric Laurent81784c32012-11-19 14:55:58 -08002354 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07002355 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
Eric Laurent81784c32012-11-19 14:55:58 -08002356 if (
Eric Laurent81784c32012-11-19 14:55:58 -08002357 // PCM data
2358 audio_is_linear_pcm(format) &&
Andy Hung1f439e12015-05-19 12:57:41 -07002359 // TODO: extract as a data library function that checks that a computationally
2360 // expensive downmixer is not required: isFastOutputChannelConversion()
jiabin245cdd92018-12-07 17:55:15 -08002361 (channelMask == (mChannelMask | mHapticChannelMask) ||
Andy Hung1f439e12015-05-19 12:57:41 -07002362 mChannelMask != AUDIO_CHANNEL_OUT_STEREO ||
2363 (channelMask == AUDIO_CHANNEL_OUT_MONO
2364 /* && mChannelMask == AUDIO_CHANNEL_OUT_STEREO */)) &&
Eric Laurent81784c32012-11-19 14:55:58 -08002365 // hardware sample rate
2366 (sampleRate == mSampleRate) &&
Eric Laurent81784c32012-11-19 14:55:58 -08002367 // normal mixer has an associated fast mixer
2368 hasFastMixer() &&
2369 // there are sufficient fast track slots available
2370 (mFastTrackAvailMask != 0)
2371 // FIXME test that MixerThread for this fast track has a capable output HAL
2372 // FIXME add a permission test also?
2373 ) {
Andy Hunge0a269a2016-03-23 15:13:42 -07002374 // static tracks can have any nonzero framecount, streaming tracks check against minimum.
2375 if (sharedBuffer == 0) {
Glenn Kasten03490092014-05-27 12:30:54 -07002376 // read the fast track multiplier property the first time it is needed
2377 int ok = pthread_once(&sFastTrackMultiplierOnce, sFastTrackMultiplierInit);
2378 if (ok != 0) {
2379 ALOGE("%s pthread_once failed: %d", __func__, ok);
2380 }
Andy Hunge0a269a2016-03-23 15:13:42 -07002381 frameCount = max(frameCount, mFrameCount * sFastTrackMultiplier); // incl framecount 0
Eric Laurent81784c32012-11-19 14:55:58 -08002382 }
Eric Laurent4c415062016-06-17 16:14:16 -07002383
2384 // check compatibility with audio effects.
2385 { // scope for mLock
2386 Mutex::Autolock _l(mLock);
Andy Hungd3bb0ad2016-10-11 17:16:43 -07002387 for (audio_session_t session : {
Eric Laurent3f75a5b2019-11-12 15:55:51 -08002388 AUDIO_SESSION_DEVICE,
Andy Hungd3bb0ad2016-10-11 17:16:43 -07002389 AUDIO_SESSION_OUTPUT_STAGE,
2390 AUDIO_SESSION_OUTPUT_MIX,
2391 sessionId,
2392 }) {
Andy Hung116bc262023-06-20 18:56:17 -07002393 sp<IAfEffectChain> chain = getEffectChain_l(session);
Andy Hungd3bb0ad2016-10-11 17:16:43 -07002394 if (chain.get() != nullptr) {
2395 audio_output_flags_t old = *flags;
2396 chain->checkOutputFlagCompatibility(flags);
2397 if (old != *flags) {
2398 ALOGV("AUDIO_OUTPUT_FLAGS denied by effect, session=%d old=%#x new=%#x",
2399 (int)session, (int)old, (int)*flags);
2400 }
Eric Laurent4c415062016-06-17 16:14:16 -07002401 }
2402 }
2403 }
Eric Laurent122f7e72016-06-29 11:53:29 -07002404 ALOGV_IF((*flags & AUDIO_OUTPUT_FLAG_FAST) != 0,
Eric Laurent4c415062016-06-17 16:14:16 -07002405 "AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
2406 frameCount, mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08002407 } else {
Robert Wu4c7bb7d2021-08-12 18:50:13 +00002408 ALOGD("AUDIO_OUTPUT_FLAG_FAST denied: sharedBuffer=%p frameCount=%zu "
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002409 "mFrameCount=%zu format=%#x mFormat=%#x isLinear=%d channelMask=%#x "
Andy Hung6146c082014-03-18 11:56:15 -07002410 "sampleRate=%u mSampleRate=%u "
Eric Laurent81784c32012-11-19 14:55:58 -08002411 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
Glenn Kastend79072e2016-01-06 08:41:20 -08002412 sharedBuffer.get(), frameCount, mFrameCount, format, mFormat,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07002413 audio_is_linear_pcm(format), channelMask, sampleRate,
2414 mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
Eric Laurent4c415062016-06-17 16:14:16 -07002415 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_FAST);
Andy Hung0e48d252015-01-26 11:43:15 -08002416 }
2417 }
Eric Laurent21da6472017-11-09 16:29:26 -08002418
2419 if (!audio_has_proportional_frames(format)) {
2420 if (sharedBuffer != 0) {
2421 // Same comment as below about ignoring frameCount parameter for set()
2422 frameCount = sharedBuffer->size();
2423 } else if (frameCount == 0) {
2424 frameCount = mNormalFrameCount;
2425 }
2426 if (notificationFrameCount != frameCount) {
2427 notificationFrameCount = frameCount;
2428 }
2429 } else if (sharedBuffer != 0) {
2430 // FIXME: Ensure client side memory buffers need
2431 // not have additional alignment beyond sample
2432 // (e.g. 16 bit stereo accessed as 32 bit frame).
2433 size_t alignment = audio_bytes_per_sample(format);
2434 if (alignment & 1) {
2435 // for AUDIO_FORMAT_PCM_24_BIT_PACKED (not exposed through Java).
2436 alignment = 1;
2437 }
2438 uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
2439 size_t frameSize = channelCount * audio_bytes_per_sample(format);
2440 if (channelCount > 1) {
2441 // More than 2 channels does not require stronger alignment than stereo
2442 alignment <<= 1;
2443 }
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07002444 if (((uintptr_t)sharedBuffer->unsecurePointer() & (alignment - 1)) != 0) {
Eric Laurent21da6472017-11-09 16:29:26 -08002445 ALOGE("Invalid buffer alignment: address %p, channel count %u",
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07002446 sharedBuffer->unsecurePointer(), channelCount);
Eric Laurent21da6472017-11-09 16:29:26 -08002447 lStatus = BAD_VALUE;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002448 goto Exit;
2449 }
Eric Laurent21da6472017-11-09 16:29:26 -08002450
2451 // When initializing a shared buffer AudioTrack via constructors,
2452 // there's no frameCount parameter.
2453 // But when initializing a shared buffer AudioTrack via set(),
2454 // there _is_ a frameCount parameter. We silently ignore it.
2455 frameCount = sharedBuffer->size() / frameSize;
2456 } else {
2457 size_t minFrameCount = 0;
2458 // For fast tracks we try to respect the application's request for notifications per buffer.
2459 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
2460 if (notificationsPerBuffer > 0) {
2461 // Avoid possible arithmetic overflow during multiplication.
2462 if (notificationsPerBuffer > SIZE_MAX / mFrameCount) {
2463 ALOGE("Requested notificationPerBuffer=%u ignored for HAL frameCount=%zu",
2464 notificationsPerBuffer, mFrameCount);
2465 } else {
2466 minFrameCount = mFrameCount * notificationsPerBuffer;
2467 }
2468 }
2469 } else {
2470 // For normal PCM streaming tracks, update minimum frame count.
2471 // Buffer depth is forced to be at least 2 x the normal mixer frame count and
2472 // cover audio hardware latency.
2473 // This is probably too conservative, but legacy application code may depend on it.
2474 // If you change this calculation, also review the start threshold which is related.
2475 uint32_t latencyMs = latency_l();
2476 if (latencyMs == 0) {
2477 ALOGE("Error when retrieving output stream latency");
2478 lStatus = UNKNOWN_ERROR;
2479 goto Exit;
2480 }
2481
2482 minFrameCount = AudioSystem::calculateMinFrameCount(latencyMs, mNormalFrameCount,
2483 mSampleRate, sampleRate, speed /*, 0 mNotificationsPerBufferReq*/);
2484
Eric Laurent81784c32012-11-19 14:55:58 -08002485 }
Eric Laurent21da6472017-11-09 16:29:26 -08002486 if (frameCount < minFrameCount) {
Eric Laurent81784c32012-11-19 14:55:58 -08002487 frameCount = minFrameCount;
2488 }
Eric Laurent81784c32012-11-19 14:55:58 -08002489 }
Eric Laurent21da6472017-11-09 16:29:26 -08002490
2491 // Make sure that application is notified with sufficient margin before underrun.
2492 // The client can divide the AudioTrack buffer into sub-buffers,
2493 // and expresses its desire to server as the notification frame count.
2494 if (sharedBuffer == 0 && audio_is_linear_pcm(format)) {
2495 size_t maxNotificationFrames;
2496 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
2497 // notify every HAL buffer, regardless of the size of the track buffer
2498 maxNotificationFrames = mFrameCount;
2499 } else {
Andy Hungfa117802019-04-12 13:50:39 -07002500 // Triple buffer the notification period for a triple buffered mixer period;
2501 // otherwise, double buffering for the notification period is fine.
2502 //
2503 // TODO: This should be moved to AudioTrack to modify the notification period
2504 // on AudioTrack::setBufferSizeInFrames() changes.
2505 const int nBuffering =
2506 (uint64_t{frameCount} * mSampleRate)
2507 / (uint64_t{mNormalFrameCount} * sampleRate) == 3 ? 3 : 2;
2508
Eric Laurent21da6472017-11-09 16:29:26 -08002509 maxNotificationFrames = frameCount / nBuffering;
2510 // If client requested a fast track but this was denied, then use the smaller maximum.
2511 if (requestedFlags & AUDIO_OUTPUT_FLAG_FAST) {
2512 size_t maxNotificationFramesFastDenied = FMS_20 * sampleRate / 1000;
2513 if (maxNotificationFrames > maxNotificationFramesFastDenied) {
2514 maxNotificationFrames = maxNotificationFramesFastDenied;
2515 }
2516 }
2517 }
2518 if (notificationFrameCount == 0 || notificationFrameCount > maxNotificationFrames) {
2519 if (notificationFrameCount == 0) {
2520 ALOGD("Client defaulted notificationFrames to %zu for frameCount %zu",
2521 maxNotificationFrames, frameCount);
2522 } else {
2523 ALOGW("Client adjusted notificationFrames from %zu to %zu for frameCount %zu",
2524 notificationFrameCount, maxNotificationFrames, frameCount);
2525 }
2526 notificationFrameCount = maxNotificationFrames;
2527 }
2528 }
2529
Glenn Kasten74935e42013-12-19 08:56:45 -08002530 *pFrameCount = frameCount;
Eric Laurent21da6472017-11-09 16:29:26 -08002531 *pNotificationFrameCount = notificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08002532
Glenn Kastenc3df8382014-03-13 15:05:25 -07002533 switch (mType) {
jiabinc658e452022-10-21 20:52:21 +00002534 case BIT_PERFECT:
2535 if (isBitPerfect) {
2536 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
2537 ALOGE("%s, bad parameter when request streaming bit-perfect, sampleRate=%u, "
2538 "format=%#x, channelMask=%#x, mSampleRate=%u, mFormat=%#x, mChannelMask=%#x",
2539 __func__, sampleRate, format, channelMask, mSampleRate, mFormat,
2540 mChannelMask);
2541 lStatus = BAD_VALUE;
2542 goto Exit;
2543 }
2544 }
2545 break;
Glenn Kastenc3df8382014-03-13 15:05:25 -07002546
2547 case DIRECT:
Phil Burkfdb3c072016-02-09 10:47:02 -08002548 if (audio_is_linear_pcm(format)) { // TODO maybe use audio_has_proportional_frames()?
Eric Laurent81784c32012-11-19 14:55:58 -08002549 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002550 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
2551 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08002552 sampleRate, format, channelMask, mOutput, mFormat);
2553 lStatus = BAD_VALUE;
2554 goto Exit;
2555 }
2556 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002557 break;
2558
2559 case OFFLOAD:
Eric Laurentbfb1b832013-01-07 09:53:42 -08002560 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002561 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
2562 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002563 sampleRate, format, channelMask, mOutput, mFormat);
2564 lStatus = BAD_VALUE;
2565 goto Exit;
2566 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002567 break;
2568
2569 default:
Glenn Kasten993fa062014-05-02 11:14:34 -07002570 if (!audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002571 ALOGE("createTrack_l() Bad parameter: format %#x \""
2572 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002573 format, mOutput, mFormat);
2574 lStatus = BAD_VALUE;
2575 goto Exit;
2576 }
Andy Hungcd044842014-08-07 11:04:34 -07002577 if (sampleRate > mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Eric Laurent81784c32012-11-19 14:55:58 -08002578 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
2579 lStatus = BAD_VALUE;
2580 goto Exit;
2581 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002582 break;
2583
Eric Laurent81784c32012-11-19 14:55:58 -08002584 }
2585
2586 lStatus = initCheck();
2587 if (lStatus != NO_ERROR) {
Glenn Kasten15e57982013-09-24 11:52:37 -07002588 ALOGE("createTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08002589 goto Exit;
2590 }
2591
2592 { // scope for mLock
2593 Mutex::Autolock _l(mLock);
2594
2595 // all tracks in same audio session must share the same routing strategy otherwise
2596 // conflicts will happen when tracks are moved from one output to another by audio policy
2597 // manager
Eric Laurentd66d7a12021-07-13 13:35:32 +02002598 product_strategy_t strategy = getStrategyForStream(streamType);
Eric Laurent81784c32012-11-19 14:55:58 -08002599 for (size_t i = 0; i < mTracks.size(); ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07002600 sp<IAfTrack> t = mTracks[i];
Eric Laurent83b88082014-06-20 18:31:16 -07002601 if (t != 0 && t->isExternalTrack()) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02002602 product_strategy_t actual = getStrategyForStream(t->streamType());
Eric Laurent81784c32012-11-19 14:55:58 -08002603 if (sessionId == t->sessionId() && strategy != actual) {
2604 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
2605 strategy, actual);
2606 lStatus = BAD_VALUE;
2607 goto Exit;
2608 }
2609 }
2610 }
2611
yucliuc9c49cd2020-07-13 16:25:21 -07002612 // Set DIRECT flag if current thread is DirectOutputThread. This can
2613 // happen when the playback is rerouted to direct output thread by
2614 // dynamic audio policy.
2615 // Do NOT report the flag changes back to client, since the client
2616 // doesn't explicitly request a direct flag.
2617 audio_output_flags_t trackFlags = *flags;
2618 if (mType == DIRECT) {
2619 trackFlags = static_cast<audio_output_flags_t>(trackFlags | AUDIO_OUTPUT_FLAG_DIRECT);
2620 }
2621
Andy Hung8d31fd22023-06-26 19:20:57 -07002622 track = IAfTrack::create(this, client, streamType, attr, sampleRate, format,
Andy Hung8fe68032017-06-05 16:17:51 -07002623 channelMask, frameCount,
2624 nullptr /* buffer */, (size_t)0 /* bufferSize */, sharedBuffer,
Svet Ganov33761132021-05-13 22:51:08 +00002625 sessionId, creatorPid, attributionSource, trackFlags,
Andy Hung8d31fd22023-06-26 19:20:57 -07002626 IAfTrackBase::TYPE_DEFAULT, portId, SIZE_MAX /*frameCountToBeReady*/,
jiabinc658e452022-10-21 20:52:21 +00002627 speed, isSpatialized, isBitPerfect);
Glenn Kasten03003332013-08-06 15:40:54 -07002628
Glenn Kasten03003332013-08-06 15:40:54 -07002629 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
2630 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08002631 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08002632 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08002633 goto Exit;
2634 }
2635 mTracks.add(track);
jiabinf6eb4c32020-02-25 14:06:25 -08002636 {
2637 Mutex::Autolock _atCbL(mAudioTrackCbLock);
2638 if (callback.get() != nullptr) {
jiabin18a4b1c2020-09-17 11:40:42 -07002639 mAudioTrackCallbacks.emplace(track, callback);
jiabinf6eb4c32020-02-25 14:06:25 -08002640 }
2641 }
Eric Laurent81784c32012-11-19 14:55:58 -08002642
Andy Hung116bc262023-06-20 18:56:17 -07002643 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08002644 if (chain != 0) {
2645 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
2646 track->setMainBuffer(chain->inBuffer());
Eric Laurentd66d7a12021-07-13 13:35:32 +02002647 chain->setStrategy(getStrategyForStream(track->streamType()));
Eric Laurent81784c32012-11-19 14:55:58 -08002648 chain->incTrackCnt();
2649 }
2650
Eric Laurent05067782016-06-01 18:27:28 -07002651 if ((*flags & AUDIO_OUTPUT_FLAG_FAST) && (tid != -1)) {
Eric Laurent81784c32012-11-19 14:55:58 -08002652 pid_t callingPid = IPCThreadState::self()->getCallingPid();
2653 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
2654 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07002655 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08002656 }
2657 }
2658
2659 lStatus = NO_ERROR;
2660
2661Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07002662 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08002663 return track;
2664}
2665
Andy Hung1bc088a2018-02-09 15:57:31 -08002666template<typename T>
Andy Hungee58e4a2023-07-07 13:47:37 -07002667ssize_t PlaybackThread::Tracks<T>::remove(const sp<T>& track)
Andy Hung1bc088a2018-02-09 15:57:31 -08002668{
Andy Hungc0691382018-09-12 18:01:57 -07002669 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08002670 const ssize_t index = mTracks.remove(track);
2671 if (index >= 0) {
Andy Hungc0691382018-09-12 18:01:57 -07002672 if (mSaveDeletedTrackIds) {
Andy Hung1bc088a2018-02-09 15:57:31 -08002673 // We can't directly access mAudioMixer since the caller may be outside of threadLoop.
Andy Hungc0691382018-09-12 18:01:57 -07002674 // Instead, we add to mDeletedTrackIds which is solely used for mAudioMixer update,
Andy Hung1bc088a2018-02-09 15:57:31 -08002675 // to be handled when MixerThread::prepareTracks_l() next changes mAudioMixer.
Andy Hungc0691382018-09-12 18:01:57 -07002676 mDeletedTrackIds.emplace(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08002677 }
Andy Hung1bc088a2018-02-09 15:57:31 -08002678 }
2679 return index;
2680}
2681
Andy Hungee58e4a2023-07-07 13:47:37 -07002682uint32_t PlaybackThread::correctLatency_l(uint32_t latency) const
Eric Laurent81784c32012-11-19 14:55:58 -08002683{
2684 return latency;
2685}
2686
Andy Hungee58e4a2023-07-07 13:47:37 -07002687uint32_t PlaybackThread::latency() const
Eric Laurent81784c32012-11-19 14:55:58 -08002688{
2689 Mutex::Autolock _l(mLock);
2690 return latency_l();
2691}
Andy Hungee58e4a2023-07-07 13:47:37 -07002692uint32_t PlaybackThread::latency_l() const
Eric Laurent81784c32012-11-19 14:55:58 -08002693{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002694 uint32_t latency;
2695 if (initCheck() == NO_ERROR && mOutput->stream->getLatency(&latency) == OK) {
2696 return correctLatency_l(latency);
Eric Laurent81784c32012-11-19 14:55:58 -08002697 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002698 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002699}
2700
Andy Hungee58e4a2023-07-07 13:47:37 -07002701void PlaybackThread::setMasterVolume(float value)
Eric Laurent81784c32012-11-19 14:55:58 -08002702{
2703 Mutex::Autolock _l(mLock);
2704 // Don't apply master volume in SW if our HAL can do it for us.
2705 if (mOutput && mOutput->audioHwDev &&
2706 mOutput->audioHwDev->canSetMasterVolume()) {
2707 mMasterVolume = 1.0;
2708 } else {
2709 mMasterVolume = value;
2710 }
2711}
2712
Andy Hungee58e4a2023-07-07 13:47:37 -07002713void PlaybackThread::setMasterBalance(float balance)
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01002714{
2715 mMasterBalance.store(balance);
2716}
2717
Andy Hungee58e4a2023-07-07 13:47:37 -07002718void PlaybackThread::setMasterMute(bool muted)
Eric Laurent81784c32012-11-19 14:55:58 -08002719{
Eric Laurent6acd1d42017-01-04 14:23:29 -08002720 if (isDuplicating()) {
2721 return;
2722 }
Eric Laurent81784c32012-11-19 14:55:58 -08002723 Mutex::Autolock _l(mLock);
2724 // Don't apply master mute in SW if our HAL can do it for us.
2725 if (mOutput && mOutput->audioHwDev &&
2726 mOutput->audioHwDev->canSetMasterMute()) {
2727 mMasterMute = false;
2728 } else {
2729 mMasterMute = muted;
2730 }
2731}
2732
Andy Hungee58e4a2023-07-07 13:47:37 -07002733void PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
Eric Laurent81784c32012-11-19 14:55:58 -08002734{
2735 Mutex::Autolock _l(mLock);
2736 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002737 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002738}
2739
Andy Hungee58e4a2023-07-07 13:47:37 -07002740void PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
Eric Laurent81784c32012-11-19 14:55:58 -08002741{
2742 Mutex::Autolock _l(mLock);
2743 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002744 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002745}
2746
Andy Hungee58e4a2023-07-07 13:47:37 -07002747float PlaybackThread::streamVolume(audio_stream_type_t stream) const
Eric Laurent81784c32012-11-19 14:55:58 -08002748{
2749 Mutex::Autolock _l(mLock);
2750 return mStreamTypes[stream].volume;
2751}
2752
Andy Hungee58e4a2023-07-07 13:47:37 -07002753void PlaybackThread::setVolumeForOutput_l(float left, float right) const
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09002754{
2755 mOutput->stream->setVolume(left, right);
2756}
2757
Eric Laurent81784c32012-11-19 14:55:58 -08002758// addTrack_l() must be called with ThreadBase::mLock held
Andy Hungee58e4a2023-07-07 13:47:37 -07002759status_t PlaybackThread::addTrack_l(const sp<IAfTrack>& track)
Andy Hung920f6572022-10-06 12:09:49 -07002760NO_THREAD_SAFETY_ANALYSIS // release and re-acquire mLock
Eric Laurent81784c32012-11-19 14:55:58 -08002761{
2762 status_t status = ALREADY_EXISTS;
2763
Eric Laurent81784c32012-11-19 14:55:58 -08002764 if (mActiveTracks.indexOf(track) < 0) {
2765 // the track is newly added, make sure it fills up all its
2766 // buffers before playing. This is to ensure the client will
2767 // effectively get the latency it requested.
Eric Laurent83b88082014-06-20 18:31:16 -07002768 if (track->isExternalTrack()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07002769 IAfTrackBase::track_state state = track->state();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002770 mLock.unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002771 status = AudioSystem::startOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002772 mLock.lock();
2773 // abort track was stopped/paused while we released the lock
Andy Hung8d31fd22023-06-26 19:20:57 -07002774 if (state != track->state()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002775 if (status == NO_ERROR) {
2776 mLock.unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002777 AudioSystem::stopOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002778 mLock.lock();
2779 }
2780 return INVALID_OPERATION;
2781 }
2782 // abort if start is rejected by audio policy manager
2783 if (status != NO_ERROR) {
jiabina84c3d32022-12-02 18:59:55 +00002784 // Do not replace the error if it is DEAD_OBJECT. When this happens, it indicates
2785 // current playback thread is reopened, which may happen when clients set preferred
2786 // mixer configuration. Returning DEAD_OBJECT will make the client restore track
2787 // immediately.
2788 return status == DEAD_OBJECT ? status : PERMISSION_DENIED;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002789 }
2790#ifdef ADD_BATTERY_DATA
2791 // to track the speaker usage
2792 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
2793#endif
Eric Laurent09f1ed22019-04-24 17:45:17 -07002794 sendIoConfigEvent_l(AUDIO_CLIENT_STARTED, track->creatorPid(), track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002795 }
2796
Eric Laurent51716182016-02-29 18:00:56 -08002797 // set retry count for buffer fill
2798 if (track->isOffloaded()) {
Eric Laurente93cc032016-05-05 10:15:10 -07002799 if (track->isStopping_1()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07002800 track->retryCount() = kMaxTrackStopRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07002801 } else {
Andy Hung8d31fd22023-06-26 19:20:57 -07002802 track->retryCount() = kMaxTrackStartupRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07002803 }
Andy Hung8d31fd22023-06-26 19:20:57 -07002804 track->fillingStatus() = mStandby ? IAfTrack::FS_FILLING : IAfTrack::FS_FILLED;
Eric Laurent51716182016-02-29 18:00:56 -08002805 } else {
Andy Hung8d31fd22023-06-26 19:20:57 -07002806 track->retryCount() = kMaxTrackStartupRetries;
2807 track->fillingStatus() =
2808 track->sharedBuffer() != 0 ? IAfTrack::FS_FILLED : IAfTrack::FS_FILLING;
Eric Laurent51716182016-02-29 18:00:56 -08002809 }
2810
Andy Hung116bc262023-06-20 18:56:17 -07002811 sp<IAfEffectChain> chain = getEffectChain_l(track->sessionId());
jiabineb3bda02020-06-30 14:07:03 -07002812 if (mHapticChannelMask != AUDIO_CHANNEL_NONE
2813 && ((track->channelMask() & AUDIO_CHANNEL_HAPTIC_ALL) != AUDIO_CHANNEL_NONE
2814 || (chain != nullptr && chain->containsHapticGeneratingEffect_l()))) {
jiabin57303cc2018-12-18 15:45:57 -08002815 // Unlock due to VibratorService will lock for this call and will
2816 // call Tracks.mute/unmute which also require thread's lock.
2817 mLock.unlock();
Simon Bowden62823412022-10-17 14:52:26 +00002818 const os::HapticScale intensity = AudioFlinger::onExternalVibrationStart(
jiabin57303cc2018-12-18 15:45:57 -08002819 track->getExternalVibration());
Lais Andradebc3f37a2021-07-02 00:13:19 +01002820 std::optional<media::AudioVibratorInfo> vibratorInfo;
2821 {
2822 // TODO(b/184194780): Use the vibrator information from the vibrator that will be
2823 // used to play this track.
Andy Hung583043b2023-07-17 17:05:00 -07002824 Mutex::Autolock _l(mAfThreadCallback->mutex());
2825 vibratorInfo = std::move(mAfThreadCallback->getDefaultVibratorInfo_l());
Lais Andradebc3f37a2021-07-02 00:13:19 +01002826 }
jiabin57303cc2018-12-18 15:45:57 -08002827 mLock.lock();
Simon Bowden62823412022-10-17 14:52:26 +00002828 track->setHapticIntensity(intensity);
Lais Andradebc3f37a2021-07-02 00:13:19 +01002829 if (vibratorInfo) {
2830 track->setHapticMaxAmplitude(vibratorInfo->maxAmplitude);
2831 }
2832
jiabin57303cc2018-12-18 15:45:57 -08002833 // Haptic playback should be enabled by vibrator service.
2834 if (track->getHapticPlaybackEnabled()) {
2835 // Disable haptic playback of all active track to ensure only
2836 // one track playing haptic if current track should play haptic.
2837 for (const auto &t : mActiveTracks) {
2838 t->setHapticPlaybackEnabled(false);
2839 }
jiabin245cdd92018-12-07 17:55:15 -08002840 }
jiabine70bc7f2020-06-30 22:07:55 -07002841
2842 // Set haptic intensity for effect
2843 if (chain != nullptr) {
2844 chain->setHapticIntensity_l(track->id(), intensity);
2845 }
jiabin245cdd92018-12-07 17:55:15 -08002846 }
2847
Andy Hung8d31fd22023-06-26 19:20:57 -07002848 track->setResetDone(false);
Andy Hung59de4262021-06-14 10:53:54 -07002849 track->resetPresentationComplete();
Eric Laurent81784c32012-11-19 14:55:58 -08002850 mActiveTracks.add(track);
Eric Laurentd0107bc2013-06-11 14:38:48 -07002851 if (chain != 0) {
2852 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
2853 track->sessionId());
2854 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08002855 }
2856
Andy Hungc2b11cb2020-04-22 09:04:01 -07002857 track->logBeginInterval(patchSinksToString(&mPatch)); // log to MediaMetrics
Eric Laurent81784c32012-11-19 14:55:58 -08002858 status = NO_ERROR;
2859 }
2860
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08002861 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002862 return status;
2863}
2864
Andy Hungee58e4a2023-07-07 13:47:37 -07002865bool PlaybackThread::destroyTrack_l(const sp<IAfTrack>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002866{
Eric Laurentbfb1b832013-01-07 09:53:42 -08002867 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08002868 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002869 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
Andy Hung8d31fd22023-06-26 19:20:57 -07002870 track->setState(IAfTrackBase::STOPPED);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002871 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08002872 removeTrack_l(track);
Eric Laurentab5cdba2014-06-09 17:22:27 -07002873 } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) {
Andy Hung916987e2023-03-20 19:08:16 -07002874 if (track->isPausePending()) {
2875 track->pauseAck();
2876 }
Andy Hung8d31fd22023-06-26 19:20:57 -07002877 track->setState(IAfTrackBase::STOPPING_1);
Eric Laurent81784c32012-11-19 14:55:58 -08002878 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002879
2880 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08002881}
2882
Andy Hungee58e4a2023-07-07 13:47:37 -07002883void PlaybackThread::removeTrack_l(const sp<IAfTrack>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002884{
2885 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Andy Hung2148bf02016-11-28 19:01:02 -08002886
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002887 String8 result;
2888 track->appendDump(result, false /* active */);
2889 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.string());
Andy Hung2148bf02016-11-28 19:01:02 -08002890
Eric Laurent81784c32012-11-19 14:55:58 -08002891 mTracks.remove(track);
jiabin18a4b1c2020-09-17 11:40:42 -07002892 {
2893 Mutex::Autolock _atCbL(mAudioTrackCbLock);
2894 mAudioTrackCallbacks.erase(track);
2895 }
Eric Laurent81784c32012-11-19 14:55:58 -08002896 if (track->isFastTrack()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07002897 int index = track->fastIndex();
Glenn Kastendc2c50b2016-04-21 08:13:14 -07002898 ALOG_ASSERT(0 < index && index < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08002899 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
2900 mFastTrackAvailMask |= 1 << index;
2901 // redundant as track is about to be destroyed, for dumpsys only
Andy Hung8d31fd22023-06-26 19:20:57 -07002902 track->fastIndex() = -1;
Eric Laurent81784c32012-11-19 14:55:58 -08002903 }
Andy Hung116bc262023-06-20 18:56:17 -07002904 sp<IAfEffectChain> chain = getEffectChain_l(track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08002905 if (chain != 0) {
2906 chain->decTrackCnt();
2907 }
2908}
2909
Andy Hungee58e4a2023-07-07 13:47:37 -07002910String8 PlaybackThread::getParameters(const String8& keys)
Eric Laurent81784c32012-11-19 14:55:58 -08002911{
Eric Laurent81784c32012-11-19 14:55:58 -08002912 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002913 String8 out_s8;
2914 if (initCheck() == NO_ERROR && mOutput->stream->getParameters(keys, &out_s8) == OK) {
2915 return out_s8;
Eric Laurent81784c32012-11-19 14:55:58 -08002916 }
Andy Hung920f6572022-10-06 12:09:49 -07002917 return {};
Eric Laurent81784c32012-11-19 14:55:58 -08002918}
2919
Andy Hungee58e4a2023-07-07 13:47:37 -07002920status_t DirectOutputThread::selectPresentation(int presentationId, int programId) {
Mikhail Naganovac917ac2018-11-28 14:03:52 -08002921 Mutex::Autolock _l(mLock);
Jasmine Chaeaa10e42021-05-11 10:11:14 +08002922 if (!isStreamInitialized()) {
Mikhail Naganovac917ac2018-11-28 14:03:52 -08002923 return NO_INIT;
2924 }
2925 return mOutput->stream->selectPresentation(presentationId, programId);
2926}
2927
Andy Hungee58e4a2023-07-07 13:47:37 -07002928void PlaybackThread::ioConfigChanged(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -07002929 audio_port_handle_t portId) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002930 ALOGV("PlaybackThread::ioConfigChanged, thread %p, event %d", this, event);
Mikhail Naganov88536df2021-07-26 17:30:29 -07002931 sp<AudioIoDescriptor> desc;
2932 const struct audio_patch patch = isMsdDevice() ? mDownStreamPatch : mPatch;
Eric Laurent81784c32012-11-19 14:55:58 -08002933 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002934 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07002935 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07002936 case AUDIO_OUTPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07002937 desc = sp<AudioIoDescriptor>::make(mId, patch, false /*isInput*/,
2938 mSampleRate, mFormat, mChannelMask,
2939 // FIXME AudioFlinger::frameCount(audio_io_handle_t) instead of mNormalFrameCount?
2940 mNormalFrameCount, mFrameCount, latency_l());
Eric Laurent81784c32012-11-19 14:55:58 -08002941 break;
Eric Laurent09f1ed22019-04-24 17:45:17 -07002942 case AUDIO_CLIENT_STARTED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07002943 desc = sp<AudioIoDescriptor>::make(mId, patch, portId);
Eric Laurent09f1ed22019-04-24 17:45:17 -07002944 break;
Eric Laurent73e26b62015-04-27 16:55:58 -07002945 case AUDIO_OUTPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08002946 default:
Mikhail Naganov88536df2021-07-26 17:30:29 -07002947 desc = sp<AudioIoDescriptor>::make(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08002948 break;
2949 }
Andy Hung583043b2023-07-17 17:05:00 -07002950 mAfThreadCallback->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08002951}
2952
Andy Hungee58e4a2023-07-07 13:47:37 -07002953void PlaybackThread::onWriteReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002954{
Eric Laurent3b4529e2013-09-05 18:09:19 -07002955 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002956}
2957
Andy Hungee58e4a2023-07-07 13:47:37 -07002958void PlaybackThread::onDrainReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002959{
Eric Laurent3b4529e2013-09-05 18:09:19 -07002960 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002961}
2962
Andy Hungee58e4a2023-07-07 13:47:37 -07002963void PlaybackThread::onError()
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002964{
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002965 mCallbackThread->setAsyncError();
2966}
2967
Andy Hungee58e4a2023-07-07 13:47:37 -07002968void PlaybackThread::onCodecFormatChanged(
jiabinf6eb4c32020-02-25 14:06:25 -08002969 const std::basic_string<uint8_t>& metadataBs)
2970{
Andy Hungee58e4a2023-07-07 13:47:37 -07002971 const auto weakPointerThis = wp<PlaybackThread>::fromExisting(this);
Kuowei Li9e2f6162022-11-23 16:25:26 +08002972 std::thread([this, metadataBs, weakPointerThis]() {
Andy Hungee58e4a2023-07-07 13:47:37 -07002973 const sp<PlaybackThread> playbackThread = weakPointerThis.promote();
Kuowei Li9e2f6162022-11-23 16:25:26 +08002974 if (playbackThread == nullptr) {
2975 ALOGW("PlaybackThread was destroyed, skip codec format change event");
2976 return;
2977 }
2978
jiabinf6eb4c32020-02-25 14:06:25 -08002979 audio_utils::metadata::Data metadata =
2980 audio_utils::metadata::dataFromByteString(metadataBs);
2981 if (metadata.empty()) {
2982 ALOGW("Can not transform the buffer to audio metadata, %s, %d",
2983 reinterpret_cast<char*>(const_cast<uint8_t*>(metadataBs.data())),
2984 (int)metadataBs.size());
2985 return;
2986 }
2987
2988 audio_utils::metadata::ByteString metaDataStr =
2989 audio_utils::metadata::byteStringFromData(metadata);
2990 std::vector metadataVec(metaDataStr.begin(), metaDataStr.end());
2991 Mutex::Autolock _l(mAudioTrackCbLock);
jiabin18a4b1c2020-09-17 11:40:42 -07002992 for (const auto& callbackPair : mAudioTrackCallbacks) {
2993 callbackPair.second->onCodecFormatChanged(metadataVec);
jiabinf6eb4c32020-02-25 14:06:25 -08002994 }
2995 }).detach();
2996}
2997
Andy Hungee58e4a2023-07-07 13:47:37 -07002998void PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002999{
3000 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003001 // reject out of sequence requests
3002 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
3003 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003004 mWaitWorkCV.signal();
3005 }
3006}
3007
Andy Hungee58e4a2023-07-07 13:47:37 -07003008void PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08003009{
3010 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003011 // reject out of sequence requests
3012 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
Andy Hungf3234512018-07-03 14:51:47 -07003013 // Register discontinuity when HW drain is completed because that can cause
3014 // the timestamp frame position to reset to 0 for direct and offload threads.
3015 // (Out of sequence requests are ignored, since the discontinuity would be handled
3016 // elsewhere, e.g. in flush).
Dean Wheatley12473e92021-03-18 23:00:55 +11003017 mTimestampVerifier.discontinuity(mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003018 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003019 mWaitWorkCV.signal();
3020 }
3021}
3022
Andy Hungee58e4a2023-07-07 13:47:37 -07003023void PlaybackThread::readOutputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08003024{
Glenn Kastenadad3d72014-02-21 14:51:43 -08003025 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Mikhail Naganov560637e2021-03-31 22:40:13 +00003026 const audio_config_base_t audioConfig = mOutput->getAudioProperties();
3027 mSampleRate = audioConfig.sample_rate;
3028 mChannelMask = audioConfig.channel_mask;
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003029 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08003030 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003031 }
Andy Hungee58e4a2023-07-07 13:47:37 -07003032 if (hasMixer() && !AudioFlinger::isValidPcmSinkChannelMask(mChannelMask)) {
Andy Hung9a592762014-07-21 21:56:01 -07003033 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output",
3034 mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003035 }
Eric Laurentf1f22e72021-07-13 14:04:14 +02003036
3037 if (mMixerChannelMask == AUDIO_CHANNEL_NONE) {
3038 mMixerChannelMask = mChannelMask;
3039 }
3040
Andy Hunge5412692014-05-16 11:25:07 -07003041 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01003042 mBalance.setChannelMask(mChannelMask);
Phil Burkca5e6142015-07-14 09:42:29 -07003043
Eric Laurentf1f22e72021-07-13 14:04:14 +02003044 uint32_t mixerChannelCount = audio_channel_count_from_out_mask(mMixerChannelMask);
3045
Phil Burkca5e6142015-07-14 09:42:29 -07003046 // Get actual HAL format.
Mikhail Naganov560637e2021-03-31 22:40:13 +00003047 status_t result = mOutput->stream->getAudioProperties(nullptr, nullptr, &mHALFormat);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003048 LOG_ALWAYS_FATAL_IF(result != OK, "Error when retrieving output stream format: %d", result);
Phil Burkca5e6142015-07-14 09:42:29 -07003049 // Get format from the shim, which will be different than the HAL format
3050 // if playing compressed audio over HDMI passthrough.
Mikhail Naganov560637e2021-03-31 22:40:13 +00003051 mFormat = audioConfig.format;
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003052 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08003053 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003054 }
Andy Hungee58e4a2023-07-07 13:47:37 -07003055 if (hasMixer() && !AudioFlinger::isValidPcmSinkFormat(mFormat)) {
Andy Hung6146c082014-03-18 11:56:15 -07003056 LOG_FATAL("HAL format %#x not supported for mixed output",
3057 mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003058 }
Phil Burk062e67a2015-02-11 13:40:50 -08003059 mFrameSize = mOutput->getFrameSize();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003060 result = mOutput->stream->getBufferSize(&mBufferSize);
3061 LOG_ALWAYS_FATAL_IF(result != OK,
3062 "Error when retrieving output stream buffer size: %d", result);
Glenn Kasten70949c42013-08-06 07:40:12 -07003063 mFrameCount = mBufferSize / mFrameSize;
Eric Laurentb3f315a2021-07-13 15:09:05 +02003064 if (hasMixer() && (mFrameCount & 15)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003065 ALOGW("HAL output buffer size is %zu frames but AudioMixer requires multiples of 16 frames",
Eric Laurent81784c32012-11-19 14:55:58 -08003066 mFrameCount);
3067 }
3068
Eric Laurentd1f69b02014-12-15 14:33:13 -08003069 mHwSupportsPause = false;
3070 if (mOutput->flags & AUDIO_OUTPUT_FLAG_DIRECT) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003071 bool supportsPause = false, supportsResume = false;
3072 if (mOutput->stream->supportsPauseAndResume(&supportsPause, &supportsResume) == OK) {
3073 if (supportsPause && supportsResume) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08003074 mHwSupportsPause = true;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003075 } else if (supportsPause) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08003076 ALOGW("direct output implements pause but not resume");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003077 } else if (supportsResume) {
3078 ALOGW("direct output implements resume but not pause");
Eric Laurentd1f69b02014-12-15 14:33:13 -08003079 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08003080 }
3081 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07003082 if (!mHwSupportsPause && mOutput->flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) {
3083 LOG_ALWAYS_FATAL("HW_AV_SYNC requested but HAL does not implement pause and resume");
3084 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08003085
Andy Hungfbfc3952015-01-15 13:33:51 -08003086 if (mType == DUPLICATING && mMixerBufferEnabled && mEffectBufferEnabled) {
3087 // For best precision, we use float instead of the associated output
3088 // device format (typically PCM 16 bit).
3089
3090 mFormat = AUDIO_FORMAT_PCM_FLOAT;
3091 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
3092 mBufferSize = mFrameSize * mFrameCount;
3093
3094 // TODO: We currently use the associated output device channel mask and sample rate.
3095 // (1) Perhaps use the ORed channel mask of all downstream MixerThreads
3096 // (if a valid mask) to avoid premature downmix.
3097 // (2) Perhaps use the maximum sample rate of all downstream MixerThreads
3098 // instead of the output device sample rate to avoid loss of high frequency information.
3099 // This may need to be updated as MixerThread/OutputTracks are added and not here.
3100 }
3101
Andy Hung09a50072014-02-27 14:30:47 -08003102 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08003103 double multiplier = 1.0;
Andy Hungd3639922022-04-28 18:00:49 -07003104 // Note: mType == SPATIALIZER does not support FastMixer.
Eric Laurent81784c32012-11-19 14:55:58 -08003105 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
3106 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08003107 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
3108 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Haynes Mathew George227a14b2016-05-09 12:45:48 -07003109
Eric Laurent81784c32012-11-19 14:55:58 -08003110 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
3111 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
3112 maxNormalFrameCount = maxNormalFrameCount & ~15;
3113 if (maxNormalFrameCount < minNormalFrameCount) {
3114 maxNormalFrameCount = minNormalFrameCount;
3115 }
3116 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
3117 if (multiplier <= 1.0) {
3118 multiplier = 1.0;
3119 } else if (multiplier <= 2.0) {
3120 if (2 * mFrameCount <= maxNormalFrameCount) {
3121 multiplier = 2.0;
3122 } else {
3123 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
3124 }
3125 } else {
Haynes Mathew George227a14b2016-05-09 12:45:48 -07003126 multiplier = floor(multiplier);
Eric Laurent81784c32012-11-19 14:55:58 -08003127 }
3128 }
3129 mNormalFrameCount = multiplier * mFrameCount;
3130 // round up to nearest 16 frames to satisfy AudioMixer
Eric Laurentb3f315a2021-07-13 15:09:05 +02003131 if (hasMixer()) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07003132 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
3133 }
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003134 ALOGI("HAL output buffer size %zu frames, normal sink buffer size %zu frames", mFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08003135 mNormalFrameCount);
3136
Andy Hung08fb1742015-05-31 23:22:10 -07003137 // Check if we want to throttle the processing to no more than 2x normal rate
3138 mThreadThrottle = property_get_bool("af.thread.throttle", true /* default_value */);
Andy Hung40eb1a12015-06-18 13:42:02 -07003139 mThreadThrottleTimeMs = 0;
3140 mThreadThrottleEndMs = 0;
Andy Hung08fb1742015-05-31 23:22:10 -07003141 mHalfBufferMs = mNormalFrameCount * 1000 / (2 * mSampleRate);
3142
Andy Hung010a1a12014-03-13 13:57:33 -07003143 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
3144 // Originally this was int16_t[] array, need to remove legacy implications.
3145 free(mSinkBuffer);
3146 mSinkBuffer = NULL;
Eric Laurent39095982021-08-24 18:29:27 +02003147
Andy Hung5b10a202014-03-13 13:59:29 -07003148 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
3149 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
3150 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07003151 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08003152
Andy Hung69aed5f2014-02-25 17:24:40 -08003153 // We resize the mMixerBuffer according to the requirements of the sink buffer which
3154 // drives the output.
3155 free(mMixerBuffer);
3156 mMixerBuffer = NULL;
3157 if (mMixerBufferEnabled) {
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01003158 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // no longer valid: AUDIO_FORMAT_PCM_16_BIT.
Eric Laurentf1f22e72021-07-13 14:04:14 +02003159 mMixerBufferSize = mNormalFrameCount * mixerChannelCount
Andy Hung69aed5f2014-02-25 17:24:40 -08003160 * audio_bytes_per_sample(mMixerBufferFormat);
3161 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
3162 }
Andy Hung98ef9782014-03-04 14:46:50 -08003163 free(mEffectBuffer);
3164 mEffectBuffer = NULL;
3165 if (mEffectBufferEnabled) {
Andy Hung319587b2023-05-23 14:01:03 -07003166 mEffectBufferFormat = AUDIO_FORMAT_PCM_FLOAT;
Eric Laurentf1f22e72021-07-13 14:04:14 +02003167 mEffectBufferSize = mNormalFrameCount * mixerChannelCount
Andy Hung98ef9782014-03-04 14:46:50 -08003168 * audio_bytes_per_sample(mEffectBufferFormat);
3169 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
3170 }
Andy Hung69aed5f2014-02-25 17:24:40 -08003171
Eric Laurentb62d0362021-10-26 17:40:18 +02003172 if (mType == SPATIALIZER) {
3173 free(mPostSpatializerBuffer);
3174 mPostSpatializerBuffer = nullptr;
3175 mPostSpatializerBufferSize = mNormalFrameCount * mChannelCount
3176 * audio_bytes_per_sample(mEffectBufferFormat);
3177 (void)posix_memalign(&mPostSpatializerBuffer, 32, mPostSpatializerBufferSize);
3178 }
3179
Mikhail Naganov55773032020-10-01 15:08:13 -07003180 mHapticChannelMask = static_cast<audio_channel_mask_t>(mChannelMask & AUDIO_CHANNEL_HAPTIC_ALL);
3181 mChannelMask = static_cast<audio_channel_mask_t>(mChannelMask & ~mHapticChannelMask);
jiabin245cdd92018-12-07 17:55:15 -08003182 mHapticChannelCount = audio_channel_count_from_out_mask(mHapticChannelMask);
3183 mChannelCount -= mHapticChannelCount;
Eric Laurentf1f22e72021-07-13 14:04:14 +02003184 mMixerChannelMask = static_cast<audio_channel_mask_t>(mMixerChannelMask & ~mHapticChannelMask);
jiabin245cdd92018-12-07 17:55:15 -08003185
Eric Laurent81784c32012-11-19 14:55:58 -08003186 // force reconfiguration of effect chains and engines to take new buffer size and audio
3187 // parameters into account
Glenn Kastendeca2ae2014-02-07 10:25:56 -08003188 // Note that mLock is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08003189 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
3190 // matter.
3191 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
Andy Hung116bc262023-06-20 18:56:17 -07003192 Vector<sp<IAfEffectChain>> effectChains = mEffectChains;
Eric Laurent81784c32012-11-19 14:55:58 -08003193 for (size_t i = 0; i < effectChains.size(); i ++) {
Andy Hung583043b2023-07-17 17:05:00 -07003194 mAfThreadCallback->moveEffectChain_l(effectChains[i]->sessionId(),
Eric Laurent6c796322019-04-09 14:13:17 -07003195 this/* srcThread */, this/* dstThread */);
Eric Laurent81784c32012-11-19 14:55:58 -08003196 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08003197
George Burgess IV5e4d86f2020-02-18 12:55:36 -08003198 audio_output_flags_t flags = mOutput->flags;
Andy Hungcf10d742020-04-28 15:38:24 -07003199 mediametrics::LogItem item(mThreadMetrics.getMetricsId()); // TODO: method in ThreadMetrics?
Andy Hungb68f5eb2019-12-03 16:49:17 -08003200 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
3201 .set(AMEDIAMETRICS_PROP_ENCODING, formatToString(mFormat).c_str())
3202 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
3203 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
3204 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
3205 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mNormalFrameCount)
3206 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
3207 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELMASK,
3208 (int32_t)mHapticChannelMask)
3209 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELCOUNT,
3210 (int32_t)mHapticChannelCount)
3211 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_ENCODING,
3212 formatToString(mHALFormat).c_str())
3213 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_FRAMECOUNT,
3214 (int32_t)mFrameCount) // sic - added HAL
3215 ;
3216 uint32_t latencyMs;
3217 if (mOutput->stream->getLatency(&latencyMs) == NO_ERROR) {
3218 item.set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_LATENCYMS, (double)latencyMs);
3219 }
3220 item.record();
Eric Laurent81784c32012-11-19 14:55:58 -08003221}
3222
Andy Hungee58e4a2023-07-07 13:47:37 -07003223ThreadBase::MetadataUpdate PlaybackThread::updateMetadata_l()
Kevin Rocard069c2712018-03-29 19:09:14 -07003224{
Jasmine Chaeaa10e42021-05-11 10:11:14 +08003225 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
Vlad Popa7e81cea2023-01-19 16:34:16 +01003226 return {}; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -07003227 }
3228 StreamOutHalInterface::SourceMetadata metadata;
Kevin Rocard12381092018-04-11 09:19:59 -07003229 auto backInserter = std::back_inserter(metadata.tracks);
Andy Hung8d31fd22023-06-26 19:20:57 -07003230 for (const sp<IAfTrack>& track : mActiveTracks) {
Kevin Rocard069c2712018-03-29 19:09:14 -07003231 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurent49e39282022-06-24 18:42:45 +02003232 track->copyMetadataTo(backInserter);
Kevin Rocard069c2712018-03-29 19:09:14 -07003233 }
Kevin Rocard12381092018-04-11 09:19:59 -07003234 sendMetadataToBackend_l(metadata);
Vlad Popa7e81cea2023-01-19 16:34:16 +01003235 MetadataUpdate change;
3236 change.playbackMetadataUpdate = metadata.tracks;
3237 return change;
Kevin Rocard80ee2722018-04-11 15:53:48 +00003238}
Kevin Rocardc86a7f72018-04-03 09:00:09 -07003239
Andy Hungee58e4a2023-07-07 13:47:37 -07003240void PlaybackThread::sendMetadataToBackend_l(
Kevin Rocard12381092018-04-11 09:19:59 -07003241 const StreamOutHalInterface::SourceMetadata& metadata)
3242{
3243 mOutput->stream->updateSourceMetadata(metadata);
3244};
3245
Andy Hungee58e4a2023-07-07 13:47:37 -07003246status_t PlaybackThread::getRenderPosition(
Andy Hung440901d2023-06-29 21:19:25 -07003247 uint32_t* halFrames, uint32_t* dspFrames) const
Eric Laurent81784c32012-11-19 14:55:58 -08003248{
3249 if (halFrames == NULL || dspFrames == NULL) {
3250 return BAD_VALUE;
3251 }
3252 Mutex::Autolock _l(mLock);
3253 if (initCheck() != NO_ERROR) {
3254 return INVALID_OPERATION;
3255 }
Andy Hung818e7a32016-02-16 18:08:07 -08003256 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08003257 *halFrames = framesWritten;
3258
3259 if (isSuspended()) {
3260 // return an estimation of rendered frames when the output is suspended
3261 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08003262 *dspFrames = (uint32_t)
3263 (framesWritten >= (int64_t)latencyFrames ? framesWritten - latencyFrames : 0);
Eric Laurent81784c32012-11-19 14:55:58 -08003264 return NO_ERROR;
3265 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003266 status_t status;
3267 uint32_t frames;
Phil Burk062e67a2015-02-11 13:40:50 -08003268 status = mOutput->getRenderPosition(&frames);
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003269 *dspFrames = (size_t)frames;
3270 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08003271 }
3272}
3273
Andy Hungee58e4a2023-07-07 13:47:37 -07003274product_strategy_t PlaybackThread::getStrategyForSession_l(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08003275{
3276 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
3277 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
3278 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02003279 return getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurent81784c32012-11-19 14:55:58 -08003280 }
3281 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003282 sp<IAfTrack> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08003283 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02003284 return getStrategyForStream(track->streamType());
Eric Laurent81784c32012-11-19 14:55:58 -08003285 }
3286 }
Eric Laurentd66d7a12021-07-13 13:35:32 +02003287 return getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurent81784c32012-11-19 14:55:58 -08003288}
3289
3290
Andy Hungee58e4a2023-07-07 13:47:37 -07003291AudioStreamOut* PlaybackThread::getOutput() const
Eric Laurent81784c32012-11-19 14:55:58 -08003292{
3293 Mutex::Autolock _l(mLock);
3294 return mOutput;
3295}
3296
Andy Hungee58e4a2023-07-07 13:47:37 -07003297AudioStreamOut* PlaybackThread::clearOutput()
Eric Laurent81784c32012-11-19 14:55:58 -08003298{
3299 Mutex::Autolock _l(mLock);
3300 AudioStreamOut *output = mOutput;
3301 mOutput = NULL;
3302 // FIXME FastMixer might also have a raw ptr to mOutputSink;
3303 // must push a NULL and wait for ack
3304 mOutputSink.clear();
3305 mPipeSink.clear();
3306 mNormalSink.clear();
3307 return output;
3308}
3309
3310// this method must always be called either with ThreadBase mLock held or inside the thread loop
Andy Hungee58e4a2023-07-07 13:47:37 -07003311sp<StreamHalInterface> PlaybackThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08003312{
3313 if (mOutput == NULL) {
3314 return NULL;
3315 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003316 return mOutput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08003317}
3318
Andy Hungee58e4a2023-07-07 13:47:37 -07003319uint32_t PlaybackThread::activeSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08003320{
3321 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
3322}
3323
Andy Hungee58e4a2023-07-07 13:47:37 -07003324status_t PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
Eric Laurent81784c32012-11-19 14:55:58 -08003325{
3326 if (!isValidSyncEvent(event)) {
3327 return BAD_VALUE;
3328 }
3329
3330 Mutex::Autolock _l(mLock);
3331
3332 for (size_t i = 0; i < mTracks.size(); ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003333 sp<IAfTrack> track = mTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08003334 if (event->triggerSession() == track->sessionId()) {
3335 (void) track->setSyncEvent(event);
3336 return NO_ERROR;
3337 }
3338 }
3339
3340 return NAME_NOT_FOUND;
3341}
3342
Andy Hungee58e4a2023-07-07 13:47:37 -07003343bool PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
Eric Laurent81784c32012-11-19 14:55:58 -08003344{
3345 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
3346}
3347
Andy Hungee58e4a2023-07-07 13:47:37 -07003348void PlaybackThread::threadLoop_removeTracks(
Andy Hung8d31fd22023-06-26 19:20:57 -07003349 [[maybe_unused]] const Vector<sp<IAfTrack>>& tracksToRemove)
Eric Laurent81784c32012-11-19 14:55:58 -08003350{
Andy Hungfe726a62018-09-27 15:17:25 -07003351 // Miscellaneous track cleanup when removed from the active list,
3352 // called without Thread lock but synchronized with threadLoop processing.
Eric Laurentbfb1b832013-01-07 09:53:42 -08003353#ifdef ADD_BATTERY_DATA
Andy Hungfe726a62018-09-27 15:17:25 -07003354 for (const auto& track : tracksToRemove) {
3355 if (track->isExternalTrack()) {
3356 // to track the speaker usage
3357 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Eric Laurent81784c32012-11-19 14:55:58 -08003358 }
3359 }
Andy Hungfe726a62018-09-27 15:17:25 -07003360#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003361}
3362
Andy Hungee58e4a2023-07-07 13:47:37 -07003363void PlaybackThread::checkSilentMode_l()
Eric Laurent81784c32012-11-19 14:55:58 -08003364{
3365 if (!mMasterMute) {
3366 char value[PROPERTY_VALUE_MAX];
jiabin0a957d32020-04-29 10:56:20 -07003367 if (mOutDeviceTypeAddrs.empty()) {
3368 ALOGD("ro.audio.silent is ignored since no output device is set");
3369 return;
3370 }
jiabinc52b1ff2019-10-31 17:20:42 -07003371 if (isSingleDeviceType(outDeviceTypes(), AUDIO_DEVICE_OUT_REMOTE_SUBMIX)) {
Jean-Michel Trivi32f37c22016-03-31 16:00:32 -07003372 ALOGD("ro.audio.silent will be ignored for threads on AUDIO_DEVICE_OUT_REMOTE_SUBMIX");
3373 return;
3374 }
Eric Laurent81784c32012-11-19 14:55:58 -08003375 if (property_get("ro.audio.silent", value, "0") > 0) {
3376 char *endptr;
3377 unsigned long ul = strtoul(value, &endptr, 0);
3378 if (*endptr == '\0' && ul != 0) {
3379 ALOGD("Silence is golden");
3380 // The setprop command will not allow a property to be changed after
3381 // the first time it is set, so we don't have to worry about un-muting.
3382 setMasterMute_l(true);
3383 }
3384 }
3385 }
3386}
3387
3388// shared by MIXER and DIRECT, overridden by DUPLICATING
Andy Hungee58e4a2023-07-07 13:47:37 -07003389ssize_t PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08003390{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07003391 LOG_HIST_TS();
Eric Laurent81784c32012-11-19 14:55:58 -08003392 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003393 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07003394 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08003395
3396 // If an NBAIO sink is present, use it to write the normal mixer's submix
3397 if (mNormalSink != 0) {
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003398
Andy Hung010a1a12014-03-13 13:57:33 -07003399 const size_t count = mBytesRemaining / mFrameSize;
3400
Simon Wilson2d590962012-11-29 15:18:50 -08003401 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08003402 // update the setpoint when AudioFlinger::mScreenState changes
3403 uint32_t screenState = AudioFlinger::mScreenState;
3404 if (screenState != mScreenState) {
3405 mScreenState = screenState;
3406 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
3407 if (pipe != NULL) {
3408 pipe->setAvgFrames((mScreenState & 1) ?
3409 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
3410 }
3411 }
Andy Hung010a1a12014-03-13 13:57:33 -07003412 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08003413 ATRACE_END();
Vlad Popab042ee62022-10-20 18:05:00 +02003414
Eric Laurent81784c32012-11-19 14:55:58 -08003415 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07003416 bytesWritten = framesWritten * mFrameSize;
Andy Hung58e32872022-11-15 16:12:24 -08003417
Andy Hung8946a282018-04-19 20:04:56 -07003418#ifdef TEE_SINK
3419 mTee.write((char *)mSinkBuffer + offset, framesWritten);
3420#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003421 } else {
3422 bytesWritten = framesWritten;
3423 }
3424 // otherwise use the HAL / AudioStreamOut directly
3425 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003426 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07003427
Eric Laurentbfb1b832013-01-07 09:53:42 -08003428 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003429 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
3430 mWriteAckSequence += 2;
3431 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003432 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003433 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003434 }
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07003435 ATRACE_BEGIN("write");
Glenn Kasten767094d2013-08-23 13:51:43 -07003436 // FIXME We should have an implementation of timestamps for direct output threads.
3437 // They are used e.g for multichannel PCM playback over HDMI.
Phil Burk062e67a2015-02-11 13:40:50 -08003438 bytesWritten = mOutput->write((char *)mSinkBuffer + offset, mBytesRemaining);
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07003439 ATRACE_END();
Eric Laurent51716182016-02-29 18:00:56 -08003440
Eric Laurentbfb1b832013-01-07 09:53:42 -08003441 if (mUseAsyncWrite &&
3442 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
3443 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07003444 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003445 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003446 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003447 }
Eric Laurent81784c32012-11-19 14:55:58 -08003448 }
3449
Eric Laurent81784c32012-11-19 14:55:58 -08003450 mNumWrites++;
3451 mInWrite = false;
Andy Hungcf10d742020-04-28 15:38:24 -07003452 if (mStandby) {
3453 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07003454 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -07003455 mStandby = false;
3456 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003457 return bytesWritten;
3458}
3459
Vlad Popa6fbbfbf2023-02-22 15:05:43 +01003460// startMelComputation_l() must be called with AudioFlinger::mLock held
Andy Hungee58e4a2023-07-07 13:47:37 -07003461void PlaybackThread::startMelComputation_l(
Vlad Popaf09e93f2022-10-31 16:27:12 +01003462 const sp<audio_utils::MelProcessor>& processor)
Vlad Popab042ee62022-10-20 18:05:00 +02003463{
Vlad Popa3c7a2662023-02-14 20:09:47 +01003464 auto outputSink = static_cast<AudioStreamOutSink*>(mOutputSink.get());
Vlad Popa1a0c3ab2023-03-17 01:07:01 +01003465 if (outputSink != nullptr) {
3466 outputSink->startMelComputation(processor);
3467 }
Vlad Popab042ee62022-10-20 18:05:00 +02003468}
3469
Vlad Popa6fbbfbf2023-02-22 15:05:43 +01003470// stopMelComputation_l() must be called with AudioFlinger::mLock held
Andy Hungee58e4a2023-07-07 13:47:37 -07003471void PlaybackThread::stopMelComputation_l()
Vlad Popa3c7a2662023-02-14 20:09:47 +01003472{
3473 auto outputSink = static_cast<AudioStreamOutSink*>(mOutputSink.get());
Vlad Popa1a0c3ab2023-03-17 01:07:01 +01003474 if (outputSink != nullptr) {
3475 outputSink->stopMelComputation();
3476 }
Vlad Popab042ee62022-10-20 18:05:00 +02003477}
3478
Andy Hungee58e4a2023-07-07 13:47:37 -07003479void PlaybackThread::threadLoop_drain()
Eric Laurentbfb1b832013-01-07 09:53:42 -08003480{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003481 bool supportsDrain = false;
3482 if (mOutput->stream->supportsDrain(&supportsDrain) == OK && supportsDrain) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003483 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
3484 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003485 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
3486 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003487 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003488 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003489 }
Mikhail Naganovcbc8f612016-10-11 18:05:13 -07003490 status_t result = mOutput->stream->drain(mMixerStatus == MIXER_DRAIN_TRACK);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003491 ALOGE_IF(result != OK, "Error when draining stream: %d", result);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003492 }
3493}
3494
Andy Hungee58e4a2023-07-07 13:47:37 -07003495void PlaybackThread::threadLoop_exit()
Eric Laurentbfb1b832013-01-07 09:53:42 -08003496{
Eric Laurent275e8e92014-11-30 15:14:47 -08003497 {
3498 Mutex::Autolock _l(mLock);
3499 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003500 sp<IAfTrack> track = mTracks[i];
Eric Laurent275e8e92014-11-30 15:14:47 -08003501 track->invalidate();
3502 }
Andy Hungdae27702016-10-31 14:01:16 -07003503 // Clear ActiveTracks to update BatteryNotifier in case active tracks remain.
3504 // After we exit there are no more track changes sent to BatteryNotifier
3505 // because that requires an active threadLoop.
3506 // TODO: should we decActiveTrackCnt() of the cleared track effect chain?
3507 mActiveTracks.clear();
Eric Laurent275e8e92014-11-30 15:14:47 -08003508 }
Eric Laurent81784c32012-11-19 14:55:58 -08003509}
3510
3511/*
3512The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08003513 - mSinkBufferSize from frame count * frame size
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003514 - mActiveSleepTimeUs from activeSleepTimeUs()
3515 - mIdleSleepTimeUs from idleSleepTimeUs()
Eric Laurent42537be2016-01-08 17:16:42 -08003516 - mStandbyDelayNs from mActiveSleepTimeUs (DIRECT only) or forced to at least
3517 kDefaultStandbyTimeInNsecs when connected to an A2DP device.
Eric Laurent81784c32012-11-19 14:55:58 -08003518 - maxPeriod from frame count and sample rate (MIXER only)
3519
3520The parameters that affect these derived values are:
3521 - frame count
3522 - frame size
3523 - sample rate
3524 - device type: A2DP or not
3525 - device latency
3526 - format: PCM or not
3527 - active sleep time
3528 - idle sleep time
3529*/
3530
Andy Hungee58e4a2023-07-07 13:47:37 -07003531void PlaybackThread::cacheParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08003532{
Andy Hung25c2dac2014-02-27 14:56:00 -08003533 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003534 mActiveSleepTimeUs = activeSleepTimeUs();
3535 mIdleSleepTimeUs = idleSleepTimeUs();
Eric Laurent42537be2016-01-08 17:16:42 -08003536
Eric Laurent52568142022-10-28 11:23:28 +02003537 mStandbyDelayNs = AudioFlinger::mStandbyTimeInNsecs;
Carter Hsu0ca47c22023-06-02 18:01:45 +08003538
Eric Laurent42537be2016-01-08 17:16:42 -08003539 // make sure standby delay is not too short when connected to an A2DP sink to avoid
3540 // truncating audio when going to standby.
jiabinc52b1ff2019-10-31 17:20:42 -07003541 if (!Intersection(outDeviceTypes(), getAudioDeviceOutAllA2dpSet()).empty()) {
Eric Laurent42537be2016-01-08 17:16:42 -08003542 if (mStandbyDelayNs < kDefaultStandbyTimeInNsecs) {
3543 mStandbyDelayNs = kDefaultStandbyTimeInNsecs;
3544 }
3545 }
Eric Laurent81784c32012-11-19 14:55:58 -08003546}
3547
Andy Hungee58e4a2023-07-07 13:47:37 -07003548bool PlaybackThread::invalidateTracks_l(audio_stream_type_t streamType)
Eric Laurent81784c32012-11-19 14:55:58 -08003549{
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003550 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %zu",
Eric Laurent81784c32012-11-19 14:55:58 -08003551 this, streamType, mTracks.size());
Eric Laurent13084622016-05-17 10:51:49 -07003552 bool trackMatch = false;
Eric Laurent81784c32012-11-19 14:55:58 -08003553 size_t size = mTracks.size();
3554 for (size_t i = 0; i < size; i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003555 sp<IAfTrack> t = mTracks[i];
Eric Laurentd60560a2015-04-10 11:31:20 -07003556 if (t->streamType() == streamType && t->isExternalTrack()) {
Glenn Kasten5736c352012-12-04 12:12:34 -08003557 t->invalidate();
Eric Laurent13084622016-05-17 10:51:49 -07003558 trackMatch = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003559 }
3560 }
Eric Laurent13084622016-05-17 10:51:49 -07003561 return trackMatch;
Eric Laurent81784c32012-11-19 14:55:58 -08003562}
3563
Andy Hungee58e4a2023-07-07 13:47:37 -07003564void PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
Haynes Mathew George05317d22016-05-03 16:34:26 -07003565{
3566 Mutex::Autolock _l(mLock);
3567 invalidateTracks_l(streamType);
3568}
3569
Andy Hungee58e4a2023-07-07 13:47:37 -07003570void PlaybackThread::invalidateTracks(std::set<audio_port_handle_t>& portIds) {
jiabinc44b3462022-12-08 12:52:31 -08003571 Mutex::Autolock _l(mLock);
3572 invalidateTracks_l(portIds);
3573}
3574
Andy Hungee58e4a2023-07-07 13:47:37 -07003575bool PlaybackThread::invalidateTracks_l(std::set<audio_port_handle_t>& portIds) {
jiabinc44b3462022-12-08 12:52:31 -08003576 bool trackMatch = false;
3577 const size_t size = mTracks.size();
3578 for (size_t i = 0; i < size; i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003579 sp<IAfTrack> t = mTracks[i];
jiabinc44b3462022-12-08 12:52:31 -08003580 if (t->isExternalTrack() && portIds.find(t->portId()) != portIds.end()) {
3581 t->invalidate();
3582 portIds.erase(t->portId());
3583 trackMatch = true;
3584 }
3585 if (portIds.empty()) {
3586 break;
3587 }
3588 }
3589 return trackMatch;
3590}
3591
jiabinf042b9b2021-05-07 23:46:28 +00003592// getTrackById_l must be called with holding thread lock
Andy Hungee58e4a2023-07-07 13:47:37 -07003593IAfTrack* PlaybackThread::getTrackById_l(
jiabinf042b9b2021-05-07 23:46:28 +00003594 audio_port_handle_t trackPortId) {
3595 for (size_t i = 0; i < mTracks.size(); i++) {
3596 if (mTracks[i]->portId() == trackPortId) {
3597 return mTracks[i].get();
3598 }
3599 }
3600 return nullptr;
3601}
3602
Andy Hungee58e4a2023-07-07 13:47:37 -07003603status_t PlaybackThread::addEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08003604{
Glenn Kastend848eb42016-03-08 13:42:11 -08003605 audio_session_t session = chain->sessionId();
Mikhail Naganov022b9952017-01-04 16:36:51 -08003606 sp<EffectBufferHalInterface> halInBuffer, halOutBuffer;
Andy Hung319587b2023-05-23 14:01:03 -07003607 float *buffer = nullptr; // only used for non global sessions
Eric Laurentb62d0362021-10-26 17:40:18 +02003608
Andy Hungd3639922022-04-28 18:00:49 -07003609 if (mType == SPATIALIZER) {
Eric Laurentb62d0362021-10-26 17:40:18 +02003610 if (!audio_is_global_session(session)) {
3611 // player sessions on a spatializer output will use a dedicated input buffer and
3612 // will either output multi channel to mEffectBuffer if the track is spatilaized
3613 // or stereo to mPostSpatializerBuffer if not spatialized.
3614 uint32_t channelMask;
3615 bool isSessionSpatialized =
3616 (hasAudioSession_l(session) & ThreadBase::SPATIALIZED_SESSION) != 0;
3617 if (isSessionSpatialized) {
3618 channelMask = mMixerChannelMask;
3619 } else {
3620 channelMask = mChannelMask;
3621 }
Eric Laurentf1f22e72021-07-13 14:04:14 +02003622 size_t numSamples = mNormalFrameCount
Eric Laurentb62d0362021-10-26 17:40:18 +02003623 * (audio_channel_count_from_out_mask(channelMask) + mHapticChannelCount);
Andy Hung583043b2023-07-17 17:05:00 -07003624 status_t result = mAfThreadCallback->getEffectsFactoryHal()->allocateBuffer(
Andy Hung319587b2023-05-23 14:01:03 -07003625 numSamples * sizeof(float),
Mikhail Naganov022b9952017-01-04 16:36:51 -08003626 &halInBuffer);
3627 if (result != OK) return result;
Eric Laurentb62d0362021-10-26 17:40:18 +02003628
Andy Hung583043b2023-07-17 17:05:00 -07003629 result = mAfThreadCallback->getEffectsFactoryHal()->mirrorBuffer(
Eric Laurentb62d0362021-10-26 17:40:18 +02003630 isSessionSpatialized ? mEffectBuffer : mPostSpatializerBuffer,
3631 isSessionSpatialized ? mEffectBufferSize : mPostSpatializerBufferSize,
3632 &halOutBuffer);
3633 if (result != OK) return result;
3634
Shunkai Yao44bdbad2023-01-14 05:11:58 +00003635 buffer = halInBuffer ? halInBuffer->audioBuffer()->f32 : buffer;
Andy Hung26836922023-05-22 17:31:57 -07003636
Mikhail Naganov022b9952017-01-04 16:36:51 -08003637 ALOGV("addEffectChain_l() creating new input buffer %p session %d",
3638 buffer, session);
Eric Laurentb62d0362021-10-26 17:40:18 +02003639 } else {
3640 // A global session on a SPATIALIZER thread is either OUTPUT_STAGE or DEVICE
3641 // - OUTPUT_STAGE session uses the mEffectBuffer as input buffer and
3642 // mPostSpatializerBuffer as output buffer
3643 // - DEVICE session uses the mPostSpatializerBuffer as input and output buffer.
Andy Hung583043b2023-07-17 17:05:00 -07003644 status_t result = mAfThreadCallback->getEffectsFactoryHal()->mirrorBuffer(
Eric Laurentb62d0362021-10-26 17:40:18 +02003645 mEffectBuffer, mEffectBufferSize, &halInBuffer);
3646 if (result != OK) return result;
Andy Hung583043b2023-07-17 17:05:00 -07003647 result = mAfThreadCallback->getEffectsFactoryHal()->mirrorBuffer(
Eric Laurentb62d0362021-10-26 17:40:18 +02003648 mPostSpatializerBuffer, mPostSpatializerBufferSize, &halOutBuffer);
3649 if (result != OK) return result;
Eric Laurent81784c32012-11-19 14:55:58 -08003650
Eric Laurentb62d0362021-10-26 17:40:18 +02003651 if (session == AUDIO_SESSION_DEVICE) {
3652 halInBuffer = halOutBuffer;
3653 }
3654 }
3655 } else {
Andy Hung583043b2023-07-17 17:05:00 -07003656 status_t result = mAfThreadCallback->getEffectsFactoryHal()->mirrorBuffer(
Eric Laurentb62d0362021-10-26 17:40:18 +02003657 mEffectBufferEnabled ? mEffectBuffer : mSinkBuffer,
3658 mEffectBufferEnabled ? mEffectBufferSize : mSinkBufferSize,
3659 &halInBuffer);
3660 if (result != OK) return result;
3661 halOutBuffer = halInBuffer;
3662 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
3663 if (!audio_is_global_session(session)) {
Andy Hung319587b2023-05-23 14:01:03 -07003664 buffer = halInBuffer ? reinterpret_cast<float*>(halInBuffer->externalData())
Shunkai Yao44bdbad2023-01-14 05:11:58 +00003665 : buffer;
Eric Laurentb62d0362021-10-26 17:40:18 +02003666 // Only one effect chain can be present in direct output thread and it uses
3667 // the sink buffer as input
3668 if (mType != DIRECT) {
3669 size_t numSamples = mNormalFrameCount
3670 * (audio_channel_count_from_out_mask(mMixerChannelMask)
3671 + mHapticChannelCount);
Andy Hung583043b2023-07-17 17:05:00 -07003672 const status_t allocateStatus =
3673 mAfThreadCallback->getEffectsFactoryHal()->allocateBuffer(
Andy Hung319587b2023-05-23 14:01:03 -07003674 numSamples * sizeof(float),
Eric Laurentb62d0362021-10-26 17:40:18 +02003675 &halInBuffer);
Andy Hung920f6572022-10-06 12:09:49 -07003676 if (allocateStatus != OK) return allocateStatus;
Andy Hung26836922023-05-22 17:31:57 -07003677
Shunkai Yao44bdbad2023-01-14 05:11:58 +00003678 buffer = halInBuffer ? halInBuffer->audioBuffer()->f32 : buffer;
Eric Laurentb62d0362021-10-26 17:40:18 +02003679 ALOGV("addEffectChain_l() creating new input buffer %p session %d",
3680 buffer, session);
3681 }
3682 }
3683 }
3684
3685 if (!audio_is_global_session(session)) {
Eric Laurent81784c32012-11-19 14:55:58 -08003686 // Attach all tracks with same session ID to this chain.
3687 for (size_t i = 0; i < mTracks.size(); ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003688 sp<IAfTrack> track = mTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08003689 if (session == track->sessionId()) {
Eric Laurentb62d0362021-10-26 17:40:18 +02003690 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p",
3691 track.get(), buffer);
Eric Laurent81784c32012-11-19 14:55:58 -08003692 track->setMainBuffer(buffer);
3693 chain->incTrackCnt();
3694 }
3695 }
3696
3697 // indicate all active tracks in the chain
Andy Hung8d31fd22023-06-26 19:20:57 -07003698 for (const sp<IAfTrack>& track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08003699 if (session == track->sessionId()) {
Eric Laurentb62d0362021-10-26 17:40:18 +02003700 ALOGV("addEffectChain_l() activating track %p on session %d",
3701 track.get(), session);
Eric Laurent81784c32012-11-19 14:55:58 -08003702 chain->incActiveTrackCnt();
3703 }
3704 }
3705 }
Eric Laurentb62d0362021-10-26 17:40:18 +02003706
Eric Laurentaaa44472014-09-12 17:41:50 -07003707 chain->setThread(this);
Mikhail Naganov022b9952017-01-04 16:36:51 -08003708 chain->setInBuffer(halInBuffer);
3709 chain->setOutBuffer(halOutBuffer);
Eric Laurent3f75a5b2019-11-12 15:55:51 -08003710 // Effect chain for session AUDIO_SESSION_DEVICE is inserted at end of effect
3711 // chains list in order to be processed last as it contains output device effects.
3712 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted just before to apply post
3713 // processing effects specific to an output stream before effects applied to all streams
3714 // routed to a given device.
Eric Laurent81784c32012-11-19 14:55:58 -08003715 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
3716 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Glenn Kastend848eb42016-03-08 13:42:11 -08003717 // after track specific effects and before output stage.
Eric Laurent81784c32012-11-19 14:55:58 -08003718 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
Glenn Kastend848eb42016-03-08 13:42:11 -08003719 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX.
Eric Laurent81784c32012-11-19 14:55:58 -08003720 // Effect chain for other sessions are inserted at beginning of effect
3721 // chains list to be processed before output mix effects. Relative order between other
Glenn Kastend848eb42016-03-08 13:42:11 -08003722 // sessions is not important.
3723 static_assert(AUDIO_SESSION_OUTPUT_MIX == 0 &&
Eric Laurent3f75a5b2019-11-12 15:55:51 -08003724 AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX &&
3725 AUDIO_SESSION_DEVICE < AUDIO_SESSION_OUTPUT_STAGE,
Glenn Kastend848eb42016-03-08 13:42:11 -08003726 "audio_session_t constants misdefined");
Eric Laurent81784c32012-11-19 14:55:58 -08003727 size_t size = mEffectChains.size();
3728 size_t i = 0;
3729 for (i = 0; i < size; i++) {
3730 if (mEffectChains[i]->sessionId() < session) {
3731 break;
3732 }
3733 }
3734 mEffectChains.insertAt(chain, i);
3735 checkSuspendOnAddEffectChain_l(chain);
3736
3737 return NO_ERROR;
3738}
3739
Andy Hungee58e4a2023-07-07 13:47:37 -07003740size_t PlaybackThread::removeEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08003741{
Glenn Kastend848eb42016-03-08 13:42:11 -08003742 audio_session_t session = chain->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08003743
3744 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
3745
3746 for (size_t i = 0; i < mEffectChains.size(); i++) {
3747 if (chain == mEffectChains[i]) {
3748 mEffectChains.removeAt(i);
3749 // detach all active tracks from the chain
Andy Hung8d31fd22023-06-26 19:20:57 -07003750 for (const sp<IAfTrack>& track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08003751 if (session == track->sessionId()) {
3752 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
3753 chain.get(), session);
3754 chain->decActiveTrackCnt();
3755 }
3756 }
3757
3758 // detach all tracks with same session ID from this chain
Andy Hung920f6572022-10-06 12:09:49 -07003759 for (size_t j = 0; j < mTracks.size(); ++j) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003760 sp<IAfTrack> track = mTracks[j];
Eric Laurent81784c32012-11-19 14:55:58 -08003761 if (session == track->sessionId()) {
Andy Hung319587b2023-05-23 14:01:03 -07003762 track->setMainBuffer(reinterpret_cast<float*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08003763 chain->decTrackCnt();
3764 }
3765 }
3766 break;
3767 }
3768 }
3769 return mEffectChains.size();
3770}
3771
Andy Hungee58e4a2023-07-07 13:47:37 -07003772status_t PlaybackThread::attachAuxEffect(
Andy Hung8d31fd22023-06-26 19:20:57 -07003773 const sp<IAfTrack>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003774{
3775 Mutex::Autolock _l(mLock);
3776 return attachAuxEffect_l(track, EffectId);
3777}
3778
Andy Hungee58e4a2023-07-07 13:47:37 -07003779status_t PlaybackThread::attachAuxEffect_l(
Andy Hung8d31fd22023-06-26 19:20:57 -07003780 const sp<IAfTrack>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003781{
3782 status_t status = NO_ERROR;
3783
3784 if (EffectId == 0) {
3785 track->setAuxBuffer(0, NULL);
3786 } else {
3787 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
Andy Hung116bc262023-06-20 18:56:17 -07003788 sp<IAfEffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Eric Laurent81784c32012-11-19 14:55:58 -08003789 if (effect != 0) {
3790 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
3791 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
3792 } else {
3793 status = INVALID_OPERATION;
3794 }
3795 } else {
3796 status = BAD_VALUE;
3797 }
3798 }
3799 return status;
3800}
3801
Andy Hungee58e4a2023-07-07 13:47:37 -07003802void PlaybackThread::detachAuxEffect_l(int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003803{
3804 for (size_t i = 0; i < mTracks.size(); ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003805 sp<IAfTrack> track = mTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08003806 if (track->auxEffectId() == effectId) {
3807 attachAuxEffect_l(track, 0);
3808 }
3809 }
3810}
3811
Andy Hungee58e4a2023-07-07 13:47:37 -07003812bool PlaybackThread::threadLoop()
Andy Hung920f6572022-10-06 12:09:49 -07003813NO_THREAD_SAFETY_ANALYSIS // manual locking of AudioFlinger
Eric Laurent81784c32012-11-19 14:55:58 -08003814{
Andy Hung78d8d952023-05-30 18:10:23 -07003815 aflog::setThreadWriter(mNBLogWriter.get());
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003816
Andy Hung8d31fd22023-06-26 19:20:57 -07003817 Vector<sp<IAfTrack>> tracksToRemove;
Eric Laurent81784c32012-11-19 14:55:58 -08003818
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003819 mStandbyTimeNs = systemTime();
Andy Hung446f4df2019-02-21 12:26:41 -08003820 int64_t lastLoopCountWritten = -2; // never matches "previous" loop, when loopCount = 0.
Eric Laurent81784c32012-11-19 14:55:58 -08003821
3822 // MIXER
3823 nsecs_t lastWarning = 0;
3824
3825 // DUPLICATING
3826 // FIXME could this be made local to while loop?
3827 writeFrames = 0;
3828
3829 cacheParameters_l();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003830 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003831
Andy Hungd3639922022-04-28 18:00:49 -07003832 if (mType == MIXER || mType == SPATIALIZER) {
Eric Laurent81784c32012-11-19 14:55:58 -08003833 sleepTimeShift = 0;
3834 }
3835
3836 CpuStats cpuStats;
3837 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
3838
3839 acquireWakeLock();
3840
Glenn Kasteneef598c2017-04-03 14:41:13 -07003841 // mNBLogWriter logging APIs can only be called by a single thread, typically the
3842 // thread associated with this PlaybackThread.
3843 // If you want to share the mNBLogWriter with other threads (for example, binder threads)
3844 // then all such threads must agree to hold a common mutex before logging.
Glenn Kasten9e58b552013-01-18 15:09:48 -08003845 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
3846 // and then that string will be logged at the next convenient opportunity.
Glenn Kasteneef598c2017-04-03 14:41:13 -07003847 // See reference to logString below.
Glenn Kasten9e58b552013-01-18 15:09:48 -08003848 const char *logString = NULL;
3849
rago1bb90822017-05-02 18:31:48 -07003850 // Estimated time for next buffer to be written to hal. This is used only on
3851 // suspended mode (for now) to help schedule the wait time until next iteration.
3852 nsecs_t timeLoopNextNs = 0;
3853
Eric Laurent664539d2013-09-23 18:24:31 -07003854 checkSilentMode_l();
Glenn Kasteneef598c2017-04-03 14:41:13 -07003855
Andy Hung2dbffc22018-08-08 18:50:41 -07003856 audio_patch_handle_t lastDownstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Andy Hungf3234512018-07-03 14:51:47 -07003857
Eric Laurentb3f315a2021-07-13 15:09:05 +02003858 sendCheckOutputStageEffectsEvent();
3859
Andy Hung446f4df2019-02-21 12:26:41 -08003860 // loopCount is used for statistics and diagnostics.
3861 for (int64_t loopCount = 0; !exitPending(); ++loopCount)
Eric Laurent81784c32012-11-19 14:55:58 -08003862 {
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08003863 // Log merge requests are performed during AudioFlinger binder transactions, but
3864 // that does not cover audio playback. It's requested here for that reason.
Andy Hung583043b2023-07-17 17:05:00 -07003865 mAfThreadCallback->requestLogMerge();
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08003866
Eric Laurent81784c32012-11-19 14:55:58 -08003867 cpuStats.sample(myName);
3868
Andy Hung116bc262023-06-20 18:56:17 -07003869 Vector<sp<IAfEffectChain>> effectChains;
Andy Hung6e6a2e62019-04-30 16:38:41 -07003870 audio_session_t activeHapticSessionId = AUDIO_SESSION_NONE;
Eric Laurentb62d0362021-10-26 17:40:18 +02003871 bool isHapticSessionSpatialized = false;
Andy Hung8d31fd22023-06-26 19:20:57 -07003872 std::vector<sp<IAfTrack>> activeTracks;
Eric Laurent81784c32012-11-19 14:55:58 -08003873
Andy Hung2dbffc22018-08-08 18:50:41 -07003874 // If the device is AUDIO_DEVICE_OUT_BUS, check for downstream latency.
3875 //
jiabinc52b1ff2019-10-31 17:20:42 -07003876 // Note: we access outDeviceTypes() outside of mLock.
3877 if (isMsdDevice() && outDeviceTypes().count(AUDIO_DEVICE_OUT_BUS) != 0) {
Andy Hung2dbffc22018-08-08 18:50:41 -07003878 // Here, we try for the AF lock, but do not block on it as the latency
3879 // is more informational.
Andy Hung583043b2023-07-17 17:05:00 -07003880 if (mAfThreadCallback->mutex().tryLock() == NO_ERROR) {
Andy Hungb6692eb2023-07-13 16:52:46 -07003881 std::vector<SoftwarePatch> swPatches;
Andy Hung920f6572022-10-06 12:09:49 -07003882 double latencyMs = 0.; // not required; initialized for clang-tidy
Andy Hung2dbffc22018-08-08 18:50:41 -07003883 status_t status = INVALID_OPERATION;
3884 audio_patch_handle_t downstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Andy Hung583043b2023-07-17 17:05:00 -07003885 if (mAfThreadCallback->getPatchPanel()->getDownstreamSoftwarePatches(
Andy Hungb6692eb2023-07-13 16:52:46 -07003886 id(), &swPatches) == OK
Andy Hung2dbffc22018-08-08 18:50:41 -07003887 && swPatches.size() > 0) {
3888 status = swPatches[0].getLatencyMs_l(&latencyMs);
3889 downstreamPatchHandle = swPatches[0].getPatchHandle();
3890 }
3891 if (downstreamPatchHandle != lastDownstreamPatchHandle) {
Dean Wheatley30d28422018-11-06 10:27:40 +11003892 mDownstreamLatencyStatMs.reset();
Andy Hung2dbffc22018-08-08 18:50:41 -07003893 lastDownstreamPatchHandle = downstreamPatchHandle;
3894 }
3895 if (status == OK) {
3896 // verify downstream latency (we assume a max reasonable
Mikhail Naganov6aa0a312018-11-09 11:00:01 -08003897 // latency of 5 seconds).
3898 const double minLatency = 0., maxLatency = 5000.;
3899 if (latencyMs >= minLatency && latencyMs <= maxLatency) {
Dean Wheatley56a583e2020-05-08 15:12:17 +10003900 ALOGVV("new downstream latency %lf ms", latencyMs);
Andy Hung2dbffc22018-08-08 18:50:41 -07003901 } else {
3902 ALOGD("out of range downstream latency %lf ms", latencyMs);
Andy Hung920f6572022-10-06 12:09:49 -07003903 latencyMs = std::clamp(latencyMs, minLatency, maxLatency);
Andy Hung2dbffc22018-08-08 18:50:41 -07003904 }
Dean Wheatley30d28422018-11-06 10:27:40 +11003905 mDownstreamLatencyStatMs.add(latencyMs);
Andy Hung2dbffc22018-08-08 18:50:41 -07003906 }
Andy Hung583043b2023-07-17 17:05:00 -07003907 mAfThreadCallback->mutex().unlock();
Andy Hung2dbffc22018-08-08 18:50:41 -07003908 }
3909 } else {
3910 if (lastDownstreamPatchHandle != AUDIO_PATCH_HANDLE_NONE) {
3911 // our device is no longer AUDIO_DEVICE_OUT_BUS, reset patch handle and stats.
Dean Wheatley30d28422018-11-06 10:27:40 +11003912 mDownstreamLatencyStatMs.reset();
Andy Hung2dbffc22018-08-08 18:50:41 -07003913 lastDownstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
3914 }
3915 }
3916
Eric Laurentb3f315a2021-07-13 15:09:05 +02003917 if (mCheckOutputStageEffects.exchange(false)) {
3918 checkOutputStageEffects();
3919 }
3920
Vlad Popa7e81cea2023-01-19 16:34:16 +01003921 MetadataUpdate metadataUpdate;
Eric Laurent81784c32012-11-19 14:55:58 -08003922 { // scope for mLock
3923
3924 Mutex::Autolock _l(mLock);
3925
Eric Laurent021cf962014-05-13 10:18:14 -07003926 processConfigEvents_l();
Eric Laurentb3f315a2021-07-13 15:09:05 +02003927 if (mCheckOutputStageEffects.load()) {
3928 continue;
3929 }
Eric Laurent10351942014-05-08 18:49:52 -07003930
Glenn Kasteneef598c2017-04-03 14:41:13 -07003931 // See comment at declaration of logString for why this is done under mLock
Glenn Kasten9e58b552013-01-18 15:09:48 -08003932 if (logString != NULL) {
3933 mNBLogWriter->logTimestamp();
3934 mNBLogWriter->log(logString);
3935 logString = NULL;
3936 }
3937
Dean Wheatley12473e92021-03-18 23:00:55 +11003938 collectTimestamps_l();
Andy Hungc8fddf32018-08-08 18:32:37 -07003939
Eric Laurent81784c32012-11-19 14:55:58 -08003940 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003941 if (mSignalPending) {
3942 // A signal was raised while we were unlocked
3943 mSignalPending = false;
3944 } else if (waitingAsyncCallback_l()) {
3945 if (exitPending()) {
3946 break;
3947 }
Marco Nelissen078538c2015-05-12 09:17:57 -07003948 bool released = false;
Eric Laurent64667972016-03-30 18:19:46 -07003949 if (!keepWakeLock()) {
Marco Nelissen078538c2015-05-12 09:17:57 -07003950 releaseWakeLock_l();
3951 released = true;
3952 }
Andy Hung10cbff12017-02-21 17:30:14 -08003953
3954 const int64_t waitNs = computeWaitTimeNs_l();
3955 ALOGV("wait async completion (wait time: %lld)", (long long)waitNs);
3956 status_t status = mWaitWorkCV.waitRelative(mLock, waitNs);
3957 if (status == TIMED_OUT) {
3958 mSignalPending = true; // if timeout recheck everything
3959 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003960 ALOGV("async completion/wake");
Marco Nelissen078538c2015-05-12 09:17:57 -07003961 if (released) {
3962 acquireWakeLock_l();
3963 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003964 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3965 mSleepTimeUs = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07003966
3967 continue;
3968 }
Eric Tan39ec8d62018-07-24 09:49:29 -07003969 if ((mActiveTracks.isEmpty() && systemTime() > mStandbyTimeNs) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08003970 isSuspended()) {
3971 // put audio hardware into standby after short delay
3972 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003973
3974 threadLoop_standby();
3975
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07003976 // This is where we go into standby
3977 if (!mStandby) {
3978 LOG_AUDIO_STATE();
Andy Hungcf10d742020-04-28 15:38:24 -07003979 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07003980 mThreadSnapshot.onEnd();
Eric Laurent19952e12023-04-20 10:08:29 +02003981 setStandby_l();
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07003982 }
Andy Hungd0979812019-02-21 15:51:44 -08003983 sendStatistics(false /* force */);
Eric Laurent81784c32012-11-19 14:55:58 -08003984 }
3985
Eric Tan39ec8d62018-07-24 09:49:29 -07003986 if (mActiveTracks.isEmpty() && mConfigEvents.isEmpty()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003987 // we're about to wait, flush the binder command buffer
3988 IPCThreadState::self()->flushCommands();
3989
3990 clearOutputTracks();
3991
3992 if (exitPending()) {
3993 break;
3994 }
3995
3996 releaseWakeLock_l();
3997 // wait until we have something to do...
3998 ALOGV("%s going to sleep", myName.string());
3999 mWaitWorkCV.wait(mLock);
4000 ALOGV("%s waking up", myName.string());
4001 acquireWakeLock_l();
4002
4003 mMixerStatus = MIXER_IDLE;
4004 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
4005 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004006 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08004007 checkSilentMode_l();
4008
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004009 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
4010 mSleepTimeUs = mIdleSleepTimeUs;
Andy Hungd3639922022-04-28 18:00:49 -07004011 if (mType == MIXER || mType == SPATIALIZER) {
Eric Laurent81784c32012-11-19 14:55:58 -08004012 sleepTimeShift = 0;
4013 }
4014
4015 continue;
4016 }
4017 }
Eric Laurent81784c32012-11-19 14:55:58 -08004018 // mMixerStatusIgnoringFastTracks is also updated internally
4019 mMixerStatus = prepareTracks_l(&tracksToRemove);
4020
Andy Hungdae27702016-10-31 14:01:16 -07004021 mActiveTracks.updatePowerState(this);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08004022
Vlad Popa7e81cea2023-01-19 16:34:16 +01004023 metadataUpdate = updateMetadata_l();
Kevin Rocard069c2712018-03-29 19:09:14 -07004024
Eric Laurent81784c32012-11-19 14:55:58 -08004025 // prevent any changes in effect chain list and in each effect chain
4026 // during mixing and effect process as the audio buffers could be deleted
4027 // or modified if an effect is created or deleted
4028 lockEffectChains_l(effectChains);
Andy Hung6e6a2e62019-04-30 16:38:41 -07004029
4030 // Determine which session to pick up haptic data.
4031 // This must be done under the same lock as prepareTracks_l().
jiabineb3bda02020-06-30 14:07:03 -07004032 // The haptic data from the effect is at a higher priority than the one from track.
Andy Hung6e6a2e62019-04-30 16:38:41 -07004033 // TODO: Write haptic data directly to sink buffer when mixing.
Eric Laurentb62d0362021-10-26 17:40:18 +02004034 if (mHapticChannelCount > 0) {
Andy Hung6e6a2e62019-04-30 16:38:41 -07004035 for (const auto& track : mActiveTracks) {
Andy Hung116bc262023-06-20 18:56:17 -07004036 sp<IAfEffectChain> effectChain = getEffectChain_l(track->sessionId());
Eric Laurentb62d0362021-10-26 17:40:18 +02004037 if (effectChain != nullptr
4038 && effectChain->containsHapticGeneratingEffect_l()) {
jiabineb3bda02020-06-30 14:07:03 -07004039 activeHapticSessionId = track->sessionId();
Eric Laurentb62d0362021-10-26 17:40:18 +02004040 isHapticSessionSpatialized =
Eric Laurentb0a7bc92022-04-05 15:06:08 +02004041 mType == SPATIALIZER && track->isSpatialized();
jiabineb3bda02020-06-30 14:07:03 -07004042 break;
4043 }
Eric Laurentb62d0362021-10-26 17:40:18 +02004044 if (activeHapticSessionId == AUDIO_SESSION_NONE
4045 && track->getHapticPlaybackEnabled()) {
Andy Hung6e6a2e62019-04-30 16:38:41 -07004046 activeHapticSessionId = track->sessionId();
Eric Laurentb62d0362021-10-26 17:40:18 +02004047 isHapticSessionSpatialized =
Eric Laurentb0a7bc92022-04-05 15:06:08 +02004048 mType == SPATIALIZER && track->isSpatialized();
Andy Hung6e6a2e62019-04-30 16:38:41 -07004049 }
4050 }
4051 }
4052
Andy Hungc1646382019-04-30 16:12:10 -07004053 // Acquire a local copy of active tracks with lock (release w/o lock).
4054 //
4055 // Control methods on the track acquire the ThreadBase lock (e.g. start()
4056 // stop(), pause(), etc.), but the threadLoop is entitled to call audio
4057 // data / buffer methods on tracks from activeTracks without the ThreadBase lock.
4058 activeTracks.insert(activeTracks.end(), mActiveTracks.begin(), mActiveTracks.end());
Eric Laurent68a40a82022-05-03 18:15:04 +02004059
4060 setHalLatencyMode_l();
Eric Laurent19952e12023-04-20 10:08:29 +02004061
Jiabin Huangfb476842022-12-06 03:18:10 +00004062 for (const auto &track : mActiveTracks ) {
jiabin7434e812023-06-27 18:22:35 +00004063 track->updateTeePatches_l();
Jiabin Huangfb476842022-12-06 03:18:10 +00004064 }
4065
Eric Laurent19952e12023-04-20 10:08:29 +02004066 // signal actual start of output stream when the render position reported by the kernel
4067 // starts moving.
Eric Laurent4edbd8c2023-05-22 17:00:24 +02004068 if (!mHalStarted && ((isSuspended() && (mBytesWritten != 0)) || (!mStandby
4069 && (mKernelPositionOnStandby
4070 != mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL])))) {
Eric Laurent19952e12023-04-20 10:08:29 +02004071 mHalStarted = true;
4072 mWaitHalStartCV.broadcast();
4073 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -08004074 } // mLock scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08004075
Eric Laurentbfb1b832013-01-07 09:53:42 -08004076 if (mBytesRemaining == 0) {
4077 mCurrentWriteLength = 0;
4078 if (mMixerStatus == MIXER_TRACKS_READY) {
4079 // threadLoop_mix() sets mCurrentWriteLength
4080 threadLoop_mix();
4081 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
4082 && (mMixerStatus != MIXER_DRAIN_ALL)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004083 // threadLoop_sleepTime sets mSleepTimeUs to 0 if data
Eric Laurentbfb1b832013-01-07 09:53:42 -08004084 // must be written to HAL
4085 threadLoop_sleepTime();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004086 if (mSleepTimeUs == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08004087 mCurrentWriteLength = mSinkBufferSize;
Andy Hungc1646382019-04-30 16:12:10 -07004088
4089 // Tally underrun frames as we are inserting 0s here.
4090 for (const auto& track : activeTracks) {
Andy Hung8d31fd22023-06-26 19:20:57 -07004091 if (track->fillingStatus() == IAfTrack::FS_ACTIVE
Andy Hunge2e830f2019-12-03 12:54:46 -08004092 && !track->isStopped()
4093 && !track->isPaused()
4094 && !track->isTerminated()) {
4095 ALOGV("%s: track(%d) %s underrun due to thread sleep of %zu frames",
4096 __func__, track->id(), track->getTrackStateAsString(),
4097 mNormalFrameCount);
Andy Hung8d31fd22023-06-26 19:20:57 -07004098 track->audioTrackServerProxy()->tallyUnderrunFrames(
4099 mNormalFrameCount);
Andy Hungc1646382019-04-30 16:12:10 -07004100 }
4101 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004102 }
4103 }
Andy Hung98ef9782014-03-04 14:46:50 -08004104 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004105 // mMixerBuffer with data if mMixerBufferValid is true and mSleepTimeUs == 0.
Andy Hung98ef9782014-03-04 14:46:50 -08004106 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
jiabinc658e452022-10-21 20:52:21 +00004107 // or mSinkBuffer (if there are no effects and there is no data already copied to
4108 // mSinkBuffer).
Andy Hung98ef9782014-03-04 14:46:50 -08004109 //
4110 // This is done pre-effects computation; if effects change to
4111 // support higher precision, this needs to move.
4112 //
4113 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004114 // TODO use mSleepTimeUs == 0 as an additional condition.
Eric Laurent39095982021-08-24 18:29:27 +02004115 uint32_t mixerChannelCount = mEffectBufferValid ?
4116 audio_channel_count_from_out_mask(mMixerChannelMask) : mChannelCount;
jiabinc658e452022-10-21 20:52:21 +00004117 if (mMixerBufferValid && (mEffectBufferValid || !mHasDataCopiedToSinkBuffer)) {
Andy Hung98ef9782014-03-04 14:46:50 -08004118 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
4119 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
4120
David Li88ee0902022-06-22 10:01:21 +08004121 // Apply mono blending and balancing if the effect buffer is not valid. Otherwise,
4122 // do these processes after effects are applied.
4123 if (!mEffectBufferValid) {
4124 // mono blend occurs for mixer threads only (not direct or offloaded)
4125 // and is handled here if we're going directly to the sink.
4126 if (requireMonoBlend()) {
4127 mono_blend(mMixerBuffer, mMixerBufferFormat, mChannelCount,
4128 mNormalFrameCount, true /*limit*/);
4129 }
Andy Hung2ddee192015-12-18 17:34:44 -08004130
David Li88ee0902022-06-22 10:01:21 +08004131 if (!hasFastMixer()) {
4132 // Balance must take effect after mono conversion.
4133 // We do it here if there is no FastMixer.
4134 // mBalance detects zero balance within the class for speed
4135 // (not needed here).
4136 mBalance.setBalance(mMasterBalance.load());
4137 mBalance.process((float *)mMixerBuffer, mNormalFrameCount);
4138 }
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01004139 }
4140
Andy Hung98ef9782014-03-04 14:46:50 -08004141 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
Eric Laurent39095982021-08-24 18:29:27 +02004142 mNormalFrameCount * (mixerChannelCount + mHapticChannelCount));
jiabin245cdd92018-12-07 17:55:15 -08004143
4144 // If we're going directly to the sink and there are haptic channels,
4145 // we should adjust channels as the sample data is partially interleaved
4146 // in this case.
4147 if (!mEffectBufferValid && mHapticChannelCount > 0) {
4148 adjust_channels_non_destructive(buffer, mChannelCount, buffer,
4149 mChannelCount + mHapticChannelCount,
4150 audio_bytes_per_sample(format),
4151 audio_bytes_per_frame(mChannelCount, format) * mNormalFrameCount);
4152 }
Andy Hung98ef9782014-03-04 14:46:50 -08004153 }
4154
Eric Laurentbfb1b832013-01-07 09:53:42 -08004155 mBytesRemaining = mCurrentWriteLength;
4156 if (isSuspended()) {
Andy Hung238fa3d2016-07-28 10:53:22 -07004157 // Simulate write to HAL when suspended (e.g. BT SCO phone call).
4158 mSleepTimeUs = suspendSleepTimeUs(); // assumes full buffer.
4159 const size_t framesRemaining = mBytesRemaining / mFrameSize;
4160 mBytesWritten += mBytesRemaining;
4161 mFramesWritten += framesRemaining;
4162 mSuspendedFrames += framesRemaining; // to adjust kernel HAL position
Eric Laurentbfb1b832013-01-07 09:53:42 -08004163 mBytesRemaining = 0;
4164 }
Eric Laurent81784c32012-11-19 14:55:58 -08004165
Eric Laurentbfb1b832013-01-07 09:53:42 -08004166 // only process effects if we're going to write
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004167 if (mSleepTimeUs == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004168 for (size_t i = 0; i < effectChains.size(); i ++) {
4169 effectChains[i]->process_l();
jiabin47affe52019-04-04 18:02:07 -07004170 // TODO: Write haptic data directly to sink buffer when mixing.
Andy Hung6e6a2e62019-04-30 16:38:41 -07004171 if (activeHapticSessionId != AUDIO_SESSION_NONE
4172 && activeHapticSessionId == effectChains[i]->sessionId()) {
jiabin47affe52019-04-04 18:02:07 -07004173 // Haptic data is active in this case, copy it directly from
4174 // in buffer to out buffer.
Eric Laurentb62d0362021-10-26 17:40:18 +02004175 uint32_t hapticSessionChannelCount = mEffectBufferValid ?
4176 audio_channel_count_from_out_mask(mMixerChannelMask) :
4177 mChannelCount;
4178 if (mType == SPATIALIZER && !isHapticSessionSpatialized) {
4179 hapticSessionChannelCount = mChannelCount;
4180 }
4181
jiabin47affe52019-04-04 18:02:07 -07004182 const size_t audioBufferSize = mNormalFrameCount
Eric Laurentb62d0362021-10-26 17:40:18 +02004183 * audio_bytes_per_frame(hapticSessionChannelCount,
Andy Hung319587b2023-05-23 14:01:03 -07004184 AUDIO_FORMAT_PCM_FLOAT);
jiabin47affe52019-04-04 18:02:07 -07004185 memcpy_by_audio_format(
4186 (uint8_t*)effectChains[i]->outBuffer() + audioBufferSize,
Andy Hung319587b2023-05-23 14:01:03 -07004187 AUDIO_FORMAT_PCM_FLOAT,
jiabin47affe52019-04-04 18:02:07 -07004188 (const uint8_t*)effectChains[i]->inBuffer() + audioBufferSize,
Andy Hung319587b2023-05-23 14:01:03 -07004189 AUDIO_FORMAT_PCM_FLOAT, mNormalFrameCount * mHapticChannelCount);
jiabin47affe52019-04-04 18:02:07 -07004190 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004191 }
Eric Laurent81784c32012-11-19 14:55:58 -08004192 }
4193 }
Eric Laurent59fe0102013-09-27 18:48:26 -07004194 // Process effect chains for offloaded thread even if no audio
4195 // was read from audio track: process only updates effect state
4196 // and thus does have to be synchronized with audio writes but may have
4197 // to be called while waiting for async write callback
4198 if (mType == OFFLOAD) {
4199 for (size_t i = 0; i < effectChains.size(); i ++) {
4200 effectChains[i]->process_l();
4201 }
4202 }
Eric Laurent81784c32012-11-19 14:55:58 -08004203
Andy Hung98ef9782014-03-04 14:46:50 -08004204 // Only if the Effects buffer is enabled and there is data in the
4205 // Effects buffer (buffer valid), we need to
4206 // copy into the sink buffer.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004207 // TODO use mSleepTimeUs == 0 as an additional condition.
jiabinc658e452022-10-21 20:52:21 +00004208 if (mEffectBufferValid && !mHasDataCopiedToSinkBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08004209 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
Eric Laurentb62d0362021-10-26 17:40:18 +02004210 void *effectBuffer = (mType == SPATIALIZER) ? mPostSpatializerBuffer : mEffectBuffer;
Andy Hung2ddee192015-12-18 17:34:44 -08004211 if (requireMonoBlend()) {
Eric Laurentb62d0362021-10-26 17:40:18 +02004212 mono_blend(effectBuffer, mEffectBufferFormat, mChannelCount, mNormalFrameCount,
Glenn Kasten03c48d52016-01-27 17:25:17 -08004213 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08004214 }
4215
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01004216 if (!hasFastMixer()) {
4217 // Balance must take effect after mono conversion.
4218 // We do it here if there is no FastMixer.
4219 // mBalance detects zero balance within the class for speed (not needed here).
4220 mBalance.setBalance(mMasterBalance.load());
Eric Laurentb62d0362021-10-26 17:40:18 +02004221 mBalance.process((float *)effectBuffer, mNormalFrameCount);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01004222 }
4223
Eric Laurentb62d0362021-10-26 17:40:18 +02004224 // for SPATIALIZER thread, Move haptics channels from mEffectBuffer to
4225 // mPostSpatializerBuffer if the haptics track is spatialized.
4226 // Otherwise, the haptics channels are already in mPostSpatializerBuffer.
4227 // For other thread types, the haptics channels are already in mEffectBuffer.
4228 if (mType == SPATIALIZER && isHapticSessionSpatialized) {
4229 const size_t srcBufferSize = mNormalFrameCount *
4230 audio_bytes_per_frame(audio_channel_count_from_out_mask(mMixerChannelMask),
4231 mEffectBufferFormat);
4232 const size_t dstBufferSize = mNormalFrameCount
4233 * audio_bytes_per_frame(mChannelCount, mEffectBufferFormat);
4234
4235 memcpy_by_audio_format((uint8_t*)mPostSpatializerBuffer + dstBufferSize,
4236 mEffectBufferFormat,
4237 (uint8_t*)mEffectBuffer + srcBufferSize,
4238 mEffectBufferFormat,
4239 mNormalFrameCount * mHapticChannelCount);
Eric Laurent39095982021-08-24 18:29:27 +02004240 }
Atneya Nairba9a1072022-09-19 17:51:37 -07004241 const size_t framesToCopy = mNormalFrameCount * (mChannelCount + mHapticChannelCount);
4242 if (mFormat == AUDIO_FORMAT_PCM_FLOAT &&
4243 mEffectBufferFormat == AUDIO_FORMAT_PCM_FLOAT) {
4244 // Clamp PCM float values more than this distance from 0 to insulate
4245 // a HAL which doesn't handle NaN correctly.
4246 static constexpr float HAL_FLOAT_SAMPLE_LIMIT = 2.0f;
4247 memcpy_to_float_from_float_with_clamping(static_cast<float*>(mSinkBuffer),
4248 static_cast<const float*>(effectBuffer),
4249 framesToCopy, HAL_FLOAT_SAMPLE_LIMIT /* absMax */);
4250 } else {
4251 memcpy_by_audio_format(mSinkBuffer, mFormat,
4252 effectBuffer, mEffectBufferFormat, framesToCopy);
4253 }
jiabin245cdd92018-12-07 17:55:15 -08004254 // The sample data is partially interleaved when haptic channels exist,
4255 // we need to adjust channels here.
4256 if (mHapticChannelCount > 0) {
4257 adjust_channels_non_destructive(mSinkBuffer, mChannelCount, mSinkBuffer,
4258 mChannelCount + mHapticChannelCount,
4259 audio_bytes_per_sample(mFormat),
4260 audio_bytes_per_frame(mChannelCount, mFormat) * mNormalFrameCount);
4261 }
Andy Hung98ef9782014-03-04 14:46:50 -08004262 }
4263
Eric Laurent81784c32012-11-19 14:55:58 -08004264 // enable changes in effect chain
4265 unlockEffectChains(effectChains);
4266
Vlad Popafce10862023-02-03 10:37:07 +01004267 if (!metadataUpdate.playbackMetadataUpdate.empty()) {
Andy Hung583043b2023-07-17 17:05:00 -07004268 mAfThreadCallback->getMelReporter()->updateMetadataForCsd(id(),
Vlad Popafce10862023-02-03 10:37:07 +01004269 metadataUpdate.playbackMetadataUpdate);
4270 }
4271
Eric Laurentbfb1b832013-01-07 09:53:42 -08004272 if (!waitingAsyncCallback()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004273 // mSleepTimeUs == 0 means we must write to audio hardware
4274 if (mSleepTimeUs == 0) {
Andy Hung08fb1742015-05-31 23:22:10 -07004275 ssize_t ret = 0;
Andy Hung446f4df2019-02-21 12:26:41 -08004276 // writePeriodNs is updated >= 0 when ret > 0.
4277 int64_t writePeriodNs = -1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004278 if (mBytesRemaining) {
Andy Hung69488c42016-05-16 18:43:33 -07004279 // FIXME rewrite to reduce number of system calls
Andy Hung446f4df2019-02-21 12:26:41 -08004280 const int64_t lastIoBeginNs = systemTime();
Andy Hung08fb1742015-05-31 23:22:10 -07004281 ret = threadLoop_write();
Andy Hung446f4df2019-02-21 12:26:41 -08004282 const int64_t lastIoEndNs = systemTime();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004283 if (ret < 0) {
4284 mBytesRemaining = 0;
Andy Hung446f4df2019-02-21 12:26:41 -08004285 } else if (ret > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004286 mBytesWritten += ret;
4287 mBytesRemaining -= ret;
Andy Hung446f4df2019-02-21 12:26:41 -08004288 const int64_t frames = ret / mFrameSize;
4289 mFramesWritten += frames;
4290
4291 writePeriodNs = lastIoEndNs - mLastIoEndNs;
4292 // process information relating to write time.
4293 if (audio_has_proportional_frames(mFormat)) {
4294 // we are in a continuous mixing cycle
4295 if (mMixerStatus == MIXER_TRACKS_READY &&
4296 loopCount == lastLoopCountWritten + 1) {
4297
4298 const double jitterMs =
4299 TimestampVerifier<int64_t, int64_t>::computeJitterMs(
4300 {frames, writePeriodNs},
4301 {0, 0} /* lastTimestamp */, mSampleRate);
4302 const double processMs =
4303 (lastIoBeginNs - mLastIoEndNs) * 1e-6;
4304
4305 Mutex::Autolock _l(mLock);
4306 mIoJitterMs.add(jitterMs);
4307 mProcessTimeMs.add(processMs);
Robert Wu06db0a32021-08-10 19:05:34 +00004308
4309 if (mPipeSink.get() != nullptr) {
4310 // Using the Monopipe availableToWrite, we estimate the current
4311 // buffer size.
4312 MonoPipe* monoPipe = static_cast<MonoPipe*>(mPipeSink.get());
4313 const ssize_t
4314 availableToWrite = mPipeSink->availableToWrite();
4315 const size_t pipeFrames = monoPipe->maxFrames();
4316 const size_t
4317 remainingFrames = pipeFrames - max(availableToWrite, 0);
4318 mMonopipePipeDepthStats.add(remainingFrames);
4319 }
Andy Hung446f4df2019-02-21 12:26:41 -08004320 }
4321
4322 // write blocked detection
4323 const int64_t deltaWriteNs = lastIoEndNs - lastIoBeginNs;
Andy Hungd3639922022-04-28 18:00:49 -07004324 if ((mType == MIXER || mType == SPATIALIZER)
4325 && deltaWriteNs > maxPeriod) {
Andy Hung446f4df2019-02-21 12:26:41 -08004326 mNumDelayedWrites++;
4327 if ((lastIoEndNs - lastWarning) > kWarningThrottleNs) {
4328 ATRACE_NAME("underrun");
4329 ALOGW("write blocked for %lld msecs, "
4330 "%d delayed writes, thread %d",
4331 (long long)deltaWriteNs / NANOS_PER_MILLISECOND,
4332 mNumDelayedWrites, mId);
4333 lastWarning = lastIoEndNs;
4334 }
4335 }
4336 }
4337 // update timing info.
4338 mLastIoBeginNs = lastIoBeginNs;
4339 mLastIoEndNs = lastIoEndNs;
4340 lastLoopCountWritten = loopCount;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004341 }
4342 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
4343 (mMixerStatus == MIXER_DRAIN_ALL)) {
4344 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08004345 }
Andy Hungd3639922022-04-28 18:00:49 -07004346 if ((mType == MIXER || mType == SPATIALIZER) && !mStandby) {
Andy Hung08fb1742015-05-31 23:22:10 -07004347
4348 if (mThreadThrottle
4349 && mMixerStatus == MIXER_TRACKS_READY // we are mixing (active tracks)
Andy Hung446f4df2019-02-21 12:26:41 -08004350 && writePeriodNs > 0) { // we have write period info
Andy Hung08fb1742015-05-31 23:22:10 -07004351 // Limit MixerThread data processing to no more than twice the
4352 // expected processing rate.
4353 //
4354 // This helps prevent underruns with NuPlayer and other applications
4355 // which may set up buffers that are close to the minimum size, or use
4356 // deep buffers, and rely on a double-buffering sleep strategy to fill.
4357 //
4358 // The throttle smooths out sudden large data drains from the device,
4359 // e.g. when it comes out of standby, which often causes problems with
4360 // (1) mixer threads without a fast mixer (which has its own warm-up)
4361 // (2) minimum buffer sized tracks (even if the track is full,
4362 // the app won't fill fast enough to handle the sudden draw).
Haynes Mathew Georgef92b2172016-05-09 11:34:15 -07004363 //
4364 // Total time spent in last processing cycle equals time spent in
4365 // 1. threadLoop_write, as well as time spent in
4366 // 2. threadLoop_mix (significant for heavy mixing, especially
4367 // on low tier processors)
Andy Hung08fb1742015-05-31 23:22:10 -07004368
Andy Hung446f4df2019-02-21 12:26:41 -08004369 // it's OK if deltaMs is an overestimate.
4370
4371 const int32_t deltaMs = writePeriodNs / NANOS_PER_MILLISECOND;
Ivan Lozanoe02bc542017-10-26 09:51:54 -07004372
Ivan Lozanoea04d392017-11-07 14:37:07 -08004373 const int32_t throttleMs = (int32_t)mHalfBufferMs - deltaMs;
Andy Hung08fb1742015-05-31 23:22:10 -07004374 if ((signed)mHalfBufferMs >= throttleMs && throttleMs > 0) {
Andy Hungcf10d742020-04-28 15:38:24 -07004375 mThreadMetrics.logThrottleMs((double)throttleMs);
Andy Hungb68f5eb2019-12-03 16:49:17 -08004376
Andy Hung08fb1742015-05-31 23:22:10 -07004377 usleep(throttleMs * 1000);
Andy Hung40eb1a12015-06-18 13:42:02 -07004378 // notify of throttle start on verbose log
4379 ALOGV_IF(mThreadThrottleEndMs == mThreadThrottleTimeMs,
4380 "mixer(%p) throttle begin:"
4381 " ret(%zd) deltaMs(%d) requires sleep %d ms",
Andy Hung08fb1742015-05-31 23:22:10 -07004382 this, ret, deltaMs, throttleMs);
Andy Hung40eb1a12015-06-18 13:42:02 -07004383 mThreadThrottleTimeMs += throttleMs;
Andy Hung0a31ddd2016-07-06 19:10:29 -07004384 // Throttle must be attributed to the previous mixer loop's write time
4385 // to allow back-to-back throttling.
Andy Hung446f4df2019-02-21 12:26:41 -08004386 // This also ensures proper timing statistics.
4387 mLastIoEndNs = systemTime(); // we fetch the write end time again.
Andy Hung40eb1a12015-06-18 13:42:02 -07004388 } else {
4389 uint32_t diff = mThreadThrottleTimeMs - mThreadThrottleEndMs;
4390 if (diff > 0) {
4391 // notify of throttle end on debug log
Andy Hung3ea004d2016-05-05 16:48:37 -07004392 // but prevent spamming for bluetooth
jiabinc52b1ff2019-10-31 17:20:42 -07004393 ALOGD_IF(!isSingleDeviceType(
4394 outDeviceTypes(), audio_is_a2dp_out_device) &&
4395 !isSingleDeviceType(
4396 outDeviceTypes(), audio_is_hearing_aid_out_device),
Andy Hung3ea004d2016-05-05 16:48:37 -07004397 "mixer(%p) throttle end: throttle time(%u)", this, diff);
Andy Hung40eb1a12015-06-18 13:42:02 -07004398 mThreadThrottleEndMs = mThreadThrottleTimeMs;
4399 }
Andy Hung08fb1742015-05-31 23:22:10 -07004400 }
4401 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004402 }
Eric Laurent81784c32012-11-19 14:55:58 -08004403
Eric Laurentbfb1b832013-01-07 09:53:42 -08004404 } else {
Glenn Kastene7754022014-10-31 12:11:26 -07004405 ATRACE_BEGIN("sleep");
Eric Laurente93cc032016-05-05 10:15:10 -07004406 Mutex::Autolock _l(mLock);
rago1bb90822017-05-02 18:31:48 -07004407 // suspended requires accurate metering of sleep time.
4408 if (isSuspended()) {
4409 // advance by expected sleepTime
4410 timeLoopNextNs += microseconds((nsecs_t)mSleepTimeUs);
4411 const nsecs_t nowNs = systemTime();
4412
4413 // compute expected next time vs current time.
4414 // (negative deltas are treated as delays).
4415 nsecs_t deltaNs = timeLoopNextNs - nowNs;
4416 if (deltaNs < -kMaxNextBufferDelayNs) {
4417 // Delays longer than the max allowed trigger a reset.
4418 ALOGV("DelayNs: %lld, resetting timeLoopNextNs", (long long) deltaNs);
4419 deltaNs = microseconds((nsecs_t)mSleepTimeUs);
4420 timeLoopNextNs = nowNs + deltaNs;
4421 } else if (deltaNs < 0) {
4422 // Delays within the max delay allowed: zero the delta/sleepTime
4423 // to help the system catch up in the next iteration(s)
4424 ALOGV("DelayNs: %lld, catching-up", (long long) deltaNs);
4425 deltaNs = 0;
4426 }
4427 // update sleep time (which is >= 0)
4428 mSleepTimeUs = deltaNs / 1000;
4429 }
Eric Laurente93cc032016-05-05 10:15:10 -07004430 if (!mSignalPending && mConfigEvents.isEmpty() && !exitPending()) {
4431 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)mSleepTimeUs));
Eric Laurent51716182016-02-29 18:00:56 -08004432 }
Glenn Kastene7754022014-10-31 12:11:26 -07004433 ATRACE_END();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004434 }
Eric Laurent81784c32012-11-19 14:55:58 -08004435 }
4436
4437 // Finally let go of removed track(s), without the lock held
4438 // since we can't guarantee the destructors won't acquire that
4439 // same lock. This will also mutate and push a new fast mixer state.
4440 threadLoop_removeTracks(tracksToRemove);
4441 tracksToRemove.clear();
4442
4443 // FIXME I don't understand the need for this here;
4444 // it was in the original code but maybe the
4445 // assignment in saveOutputTracks() makes this unnecessary?
4446 clearOutputTracks();
4447
4448 // Effect chains will be actually deleted here if they were removed from
4449 // mEffectChains list during mixing or effects processing
4450 effectChains.clear();
4451
4452 // FIXME Note that the above .clear() is no longer necessary since effectChains
4453 // is now local to this block, but will keep it for now (at least until merge done).
4454 }
4455
Eric Laurentbfb1b832013-01-07 09:53:42 -08004456 threadLoop_exit();
4457
Eric Laurentcf817a22014-08-04 20:36:31 -07004458 if (!mStandby) {
4459 threadLoop_standby();
Eric Laurent19952e12023-04-20 10:08:29 +02004460 setStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08004461 }
4462
4463 releaseWakeLock();
4464
4465 ALOGV("Thread %p type %d exiting", this, mType);
4466 return false;
4467}
4468
Andy Hungee58e4a2023-07-07 13:47:37 -07004469void PlaybackThread::collectTimestamps_l()
Dean Wheatley12473e92021-03-18 23:00:55 +11004470{
Dean Wheatley12473e92021-03-18 23:00:55 +11004471 if (mStandby) {
4472 mTimestampVerifier.discontinuity(discontinuityForStandbyOrFlush());
4473 return;
4474 } else if (mHwPaused) {
4475 mTimestampVerifier.discontinuity(mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS);
4476 return;
4477 }
4478
4479 // Gather the framesReleased counters for all active tracks,
4480 // and associate with the sink frames written out. We need
4481 // this to convert the sink timestamp to the track timestamp.
4482 bool kernelLocationUpdate = false;
4483 ExtendedTimestamp timestamp; // use private copy to fetch
4484
4485 // Always query HAL timestamp and update timestamp verifier. In standby or pause,
4486 // HAL may be draining some small duration buffered data for fade out.
4487 if (threadloop_getHalTimestamp_l(&timestamp) == OK) {
4488 mTimestampVerifier.add(timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL],
4489 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4490 mSampleRate);
4491
4492 if (isTimestampCorrectionEnabled()) {
4493 ALOGVV("TS_BEFORE: %d %lld %lld", id(),
4494 (long long)timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4495 (long long)timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]);
4496 auto correctedTimestamp = mTimestampVerifier.getLastCorrectedTimestamp();
4497 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4498 = correctedTimestamp.mFrames;
4499 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]
4500 = correctedTimestamp.mTimeNs;
4501 ALOGVV("TS_AFTER: %d %lld %lld", id(),
4502 (long long)timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4503 (long long)timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]);
4504
4505 // Note: Downstream latency only added if timestamp correction enabled.
4506 if (mDownstreamLatencyStatMs.getN() > 0) { // we have latency info.
4507 const int64_t newPosition =
4508 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4509 - int64_t(mDownstreamLatencyStatMs.getMean() * mSampleRate * 1e-3);
4510 // prevent retrograde
4511 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = max(
4512 newPosition,
4513 (mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4514 - mSuspendedFrames));
4515 }
4516 }
4517
4518 // We always fetch the timestamp here because often the downstream
4519 // sink will block while writing.
4520
4521 // We keep track of the last valid kernel position in case we are in underrun
4522 // and the normal mixer period is the same as the fast mixer period, or there
4523 // is some error from the HAL.
4524 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
4525 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
4526 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
4527 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
4528 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4529
4530 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
4531 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER];
4532 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
4533 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER];
4534 }
4535
4536 if (timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
4537 kernelLocationUpdate = true;
4538 } else {
4539 ALOGVV("getTimestamp error - no valid kernel position");
4540 }
4541
4542 // copy over kernel info
4543 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] =
4544 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4545 + mSuspendedFrames; // add frames discarded when suspended
4546 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] =
4547 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4548 } else {
4549 mTimestampVerifier.error();
4550 }
4551
4552 // mFramesWritten for non-offloaded tracks are contiguous
4553 // even after standby() is called. This is useful for the track frame
4554 // to sink frame mapping.
4555 bool serverLocationUpdate = false;
4556 if (mFramesWritten != mLastFramesWritten) {
4557 serverLocationUpdate = true;
4558 mLastFramesWritten = mFramesWritten;
4559 }
4560 // Only update timestamps if there is a meaningful change.
4561 // Either the kernel timestamp must be valid or we have written something.
4562 if (kernelLocationUpdate || serverLocationUpdate) {
4563 if (serverLocationUpdate) {
4564 // use the time before we called the HAL write - it is a bit more accurate
4565 // to when the server last read data than the current time here.
4566 //
4567 // If we haven't written anything, mLastIoBeginNs will be -1
4568 // and we use systemTime().
4569 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] = mFramesWritten;
4570 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = mLastIoBeginNs == -1
4571 ? systemTime() : mLastIoBeginNs;
4572 }
4573
Andy Hung8d31fd22023-06-26 19:20:57 -07004574 for (const sp<IAfTrack>& t : mActiveTracks) {
Dean Wheatley12473e92021-03-18 23:00:55 +11004575 if (!t->isFastTrack()) {
4576 t->updateTrackFrameInfo(
Andy Hung8d31fd22023-06-26 19:20:57 -07004577 t->audioTrackServerProxy()->framesReleased(),
Dean Wheatley12473e92021-03-18 23:00:55 +11004578 mFramesWritten,
4579 mSampleRate,
4580 mTimestamp);
4581 }
4582 }
4583 }
4584
4585 if (audio_has_proportional_frames(mFormat)) {
4586 const double latencyMs = mTimestamp.getOutputServerLatencyMs(mSampleRate);
4587 if (latencyMs != 0.) { // note 0. means timestamp is empty.
4588 mLatencyMs.add(latencyMs);
4589 }
4590 }
4591#if 0
4592 // logFormat example
4593 if (z % 100 == 0) {
4594 timespec ts;
4595 clock_gettime(CLOCK_MONOTONIC, &ts);
4596 LOGT("This is an integer %d, this is a float %f, this is my "
4597 "pid %p %% %s %t", 42, 3.14, "and this is a timestamp", ts);
4598 LOGT("A deceptive null-terminated string %\0");
4599 }
4600 ++z;
4601#endif
4602}
4603
Eric Laurentbfb1b832013-01-07 09:53:42 -08004604// removeTracks_l() must be called with ThreadBase::mLock held
Andy Hungee58e4a2023-07-07 13:47:37 -07004605void PlaybackThread::removeTracks_l(const Vector<sp<IAfTrack>>& tracksToRemove)
Andy Hung920f6572022-10-06 12:09:49 -07004606NO_THREAD_SAFETY_ANALYSIS // release and re-acquire mLock
Eric Laurentbfb1b832013-01-07 09:53:42 -08004607{
Andy Hungfe726a62018-09-27 15:17:25 -07004608 for (const auto& track : tracksToRemove) {
4609 mActiveTracks.remove(track);
4610 ALOGV("%s(%d): removing track on session %d", __func__, track->id(), track->sessionId());
Andy Hung116bc262023-06-20 18:56:17 -07004611 sp<IAfEffectChain> chain = getEffectChain_l(track->sessionId());
Andy Hungfe726a62018-09-27 15:17:25 -07004612 if (chain != 0) {
4613 ALOGV("%s(%d): stopping track on chain %p for session Id: %d",
4614 __func__, track->id(), chain.get(), track->sessionId());
4615 chain->decActiveTrackCnt();
4616 }
4617 // If an external client track, inform APM we're no longer active, and remove if needed.
4618 // We do this under lock so that the state is consistent if the Track is destroyed.
4619 if (track->isExternalTrack()) {
4620 AudioSystem::stopOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08004621 if (track->isTerminated()) {
Andy Hungfe726a62018-09-27 15:17:25 -07004622 AudioSystem::releaseOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08004623 }
4624 }
Andy Hungfe726a62018-09-27 15:17:25 -07004625 if (track->isTerminated()) {
4626 // remove from our tracks vector
4627 removeTrack_l(track);
4628 }
jiabineb3bda02020-06-30 14:07:03 -07004629 if (mHapticChannelCount > 0 &&
4630 ((track->channelMask() & AUDIO_CHANNEL_HAPTIC_ALL) != AUDIO_CHANNEL_NONE
4631 || (chain != nullptr && chain->containsHapticGeneratingEffect_l()))) {
jiabin57303cc2018-12-18 15:45:57 -08004632 mLock.unlock();
4633 // Unlock due to VibratorService will lock for this call and will
4634 // call Tracks.mute/unmute which also require thread's lock.
4635 AudioFlinger::onExternalVibrationStop(track->getExternalVibration());
4636 mLock.lock();
jiabine70bc7f2020-06-30 22:07:55 -07004637
4638 // When the track is stop, set the haptic intensity as MUTE
4639 // for the HapticGenerator effect.
4640 if (chain != nullptr) {
Simon Bowden62823412022-10-17 14:52:26 +00004641 chain->setHapticIntensity_l(track->id(), os::HapticScale::MUTE);
jiabine70bc7f2020-06-30 22:07:55 -07004642 }
jiabin245cdd92018-12-07 17:55:15 -08004643 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004644 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004645}
Eric Laurent81784c32012-11-19 14:55:58 -08004646
Andy Hungee58e4a2023-07-07 13:47:37 -07004647status_t PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
Eric Laurentaccc1472013-09-20 09:36:34 -07004648{
4649 if (mNormalSink != 0) {
Andy Hung818e7a32016-02-16 18:08:07 -08004650 ExtendedTimestamp ets;
4651 status_t status = mNormalSink->getTimestamp(ets);
4652 if (status == NO_ERROR) {
4653 status = ets.getBestTimestamp(&timestamp);
4654 }
4655 return status;
Eric Laurentaccc1472013-09-20 09:36:34 -07004656 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004657 if ((mType == OFFLOAD || mType == DIRECT) && mOutput != NULL) {
Dean Wheatley12473e92021-03-18 23:00:55 +11004658 collectTimestamps_l();
4659 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] <= 0) {
4660 return INVALID_OPERATION;
Eric Laurentaccc1472013-09-20 09:36:34 -07004661 }
Dean Wheatley12473e92021-03-18 23:00:55 +11004662 timestamp.mPosition = mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
4663 const int64_t timeNs = mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4664 timestamp.mTime.tv_sec = timeNs / NANOS_PER_SECOND;
4665 timestamp.mTime.tv_nsec = timeNs - (timestamp.mTime.tv_sec * NANOS_PER_SECOND);
4666 return NO_ERROR;
Eric Laurentaccc1472013-09-20 09:36:34 -07004667 }
4668 return INVALID_OPERATION;
4669}
Eric Laurent1c333e22014-05-20 10:48:17 -07004670
Eric Laurenteab90452019-06-24 15:17:46 -07004671// For dedicated VoIP outputs, let the HAL apply the stream volume. Track volume is
4672// still applied by the mixer.
4673// All tracks attached to a mixer with flag VOIP_RX are tied to the same
4674// stream type STREAM_VOICE_CALL so this will only change the HAL volume once even
4675// if more than one track are active
Andy Hungee58e4a2023-07-07 13:47:37 -07004676status_t PlaybackThread::handleVoipVolume_l(float* volume)
Eric Laurenteab90452019-06-24 15:17:46 -07004677{
4678 status_t result = NO_ERROR;
4679 if ((mOutput->flags & AUDIO_OUTPUT_FLAG_VOIP_RX) != 0) {
4680 if (*volume != mLeftVolFloat) {
4681 result = mOutput->stream->setVolume(*volume, *volume);
Alex Leungc5dedb22023-05-10 08:00:50 -07004682 // HAL can return INVALID_OPERATION if operation is not supported.
4683 ALOGE_IF(result != OK && result != INVALID_OPERATION,
Eric Laurenteab90452019-06-24 15:17:46 -07004684 "Error when setting output stream volume: %d", result);
4685 if (result == NO_ERROR) {
4686 mLeftVolFloat = *volume;
4687 }
4688 }
4689 // if stream volume was successfully sent to the HAL, mLeftVolFloat == v here and we
4690 // remove stream volume contribution from software volume.
4691 if (mLeftVolFloat == *volume) {
4692 *volume = 1.0f;
4693 }
4694 }
4695 return result;
4696}
4697
Andy Hungee58e4a2023-07-07 13:47:37 -07004698status_t MixerThread::createAudioPatch_l(const struct audio_patch* patch,
Eric Laurent054d9d32015-04-24 08:48:48 -07004699 audio_patch_handle_t *handle)
4700{
Andy Hungf60abce2016-08-26 11:37:54 -07004701 status_t status;
4702 if (property_get_bool("af.patch_park", false /* default_value */)) {
4703 // Park FastMixer to avoid potential DOS issues with writing to the HAL
4704 // or if HAL does not properly lock against access.
4705 AutoPark<FastMixer> park(mFastMixer);
4706 status = PlaybackThread::createAudioPatch_l(patch, handle);
4707 } else {
4708 status = PlaybackThread::createAudioPatch_l(patch, handle);
4709 }
Eric Laurentb0463942022-12-20 16:31:10 +01004710
4711 updateHalSupportedLatencyModes_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07004712 return status;
4713}
4714
Andy Hungee58e4a2023-07-07 13:47:37 -07004715status_t PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
Eric Laurent1c333e22014-05-20 10:48:17 -07004716 audio_patch_handle_t *handle)
4717{
4718 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07004719
4720 // store new device and send to effects
4721 audio_devices_t type = AUDIO_DEVICE_NONE;
jiabinc52b1ff2019-10-31 17:20:42 -07004722 AudioDeviceTypeAddrVector deviceTypeAddrs;
Eric Laurent054d9d32015-04-24 08:48:48 -07004723 for (unsigned int i = 0; i < patch->num_sinks; i++) {
jiabinc52b1ff2019-10-31 17:20:42 -07004724 LOG_ALWAYS_FATAL_IF(popcount(patch->sinks[i].ext.device.type) > 1
4725 && !mOutput->audioHwDev->supportsAudioPatches(),
4726 "Enumerated device type(%#x) must not be used "
4727 "as it does not support audio patches",
4728 patch->sinks[i].ext.device.type);
Mikhail Naganov55773032020-10-01 15:08:13 -07004729 type = static_cast<audio_devices_t>(type | patch->sinks[i].ext.device.type);
Andy Hung920f6572022-10-06 12:09:49 -07004730 deviceTypeAddrs.emplace_back(patch->sinks[i].ext.device.type,
4731 patch->sinks[i].ext.device.address);
Eric Laurent054d9d32015-04-24 08:48:48 -07004732 }
4733
François Gaffie0c280aa2018-07-25 10:02:15 +02004734 audio_port_handle_t sinkPortId = patch->sinks[0].id;
Eric Laurent054d9d32015-04-24 08:48:48 -07004735#ifdef ADD_BATTERY_DATA
4736 // when changing the audio output device, call addBatteryData to notify
4737 // the change
jiabinc52b1ff2019-10-31 17:20:42 -07004738 if (outDeviceTypes() != deviceTypes) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004739 uint32_t params = 0;
4740 // check whether speaker is on
jiabinc52b1ff2019-10-31 17:20:42 -07004741 if (deviceTypes.count(AUDIO_DEVICE_OUT_SPEAKER) > 0) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004742 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent1c333e22014-05-20 10:48:17 -07004743 }
4744
Eric Laurent054d9d32015-04-24 08:48:48 -07004745 // check if any other device (except speaker) is on
jiabinc52b1ff2019-10-31 17:20:42 -07004746 if (!isSingleDeviceType(deviceTypes, AUDIO_DEVICE_OUT_SPEAKER)) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004747 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
4748 }
4749
4750 if (params != 0) {
4751 addBatteryData(params);
4752 }
4753 }
4754#endif
4755
4756 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08004757 mEffectChains[i]->setDevices_l(deviceTypeAddrs);
Eric Laurent054d9d32015-04-24 08:48:48 -07004758 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07004759
jiabinc52b1ff2019-10-31 17:20:42 -07004760 // mPatch.num_sinks is not set when the thread is created so that
4761 // the first patch creation triggers an ioConfigChanged callback
4762 bool configChanged = (mPatch.num_sinks == 0) ||
4763 (mPatch.sinks[0].id != sinkPortId);
Eric Laurent296fb132015-05-01 11:38:42 -07004764 mPatch = *patch;
jiabinc52b1ff2019-10-31 17:20:42 -07004765 mOutDeviceTypeAddrs = deviceTypeAddrs;
jiabin0a957d32020-04-29 10:56:20 -07004766 checkSilentMode_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07004767
Mikhail Naganov9ee05402016-10-13 15:58:17 -07004768 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07004769 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
4770 status = hwDevice->createAudioPatch(patch->num_sources,
4771 patch->sources,
4772 patch->num_sinks,
4773 patch->sinks,
4774 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07004775 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08004776 status = mOutput->stream->legacyCreateAudioPatch(patch->sinks[0], std::nullopt, type);
Eric Laurent054d9d32015-04-24 08:48:48 -07004777 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07004778 }
Andy Hungc2b11cb2020-04-22 09:04:01 -07004779 const std::string patchSinksAsString = patchSinksToString(patch);
Andy Hungcf10d742020-04-28 15:38:24 -07004780
4781 mThreadMetrics.logEndInterval();
Andy Hungea840382020-05-05 21:50:17 -07004782 mThreadMetrics.logCreatePatch(/* inDevices */ {}, patchSinksAsString);
Andy Hungcf10d742020-04-28 15:38:24 -07004783 mThreadMetrics.logBeginInterval();
Andy Hungc2b11cb2020-04-22 09:04:01 -07004784 // also dispatch to active AudioTracks for MediaMetrics
4785 for (const auto &track : mActiveTracks) {
4786 track->logEndInterval();
4787 track->logBeginInterval(patchSinksAsString);
4788 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08004789
Eric Laurente8726fe2015-06-26 09:39:24 -07004790 if (configChanged) {
4791 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
4792 }
Vlad Popa7e81cea2023-01-19 16:34:16 +01004793 // Force metadata update after a route change
Eric Laurentdda206a2022-07-08 17:28:35 +02004794 mActiveTracks.setHasChanged();
4795
Eric Laurent1c333e22014-05-20 10:48:17 -07004796 return status;
4797}
4798
Andy Hungee58e4a2023-07-07 13:47:37 -07004799status_t MixerThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
Eric Laurent054d9d32015-04-24 08:48:48 -07004800{
Andy Hungf60abce2016-08-26 11:37:54 -07004801 status_t status;
4802 if (property_get_bool("af.patch_park", false /* default_value */)) {
4803 // Park FastMixer to avoid potential DOS issues with writing to the HAL
4804 // or if HAL does not properly lock against access.
4805 AutoPark<FastMixer> park(mFastMixer);
4806 status = PlaybackThread::releaseAudioPatch_l(handle);
4807 } else {
4808 status = PlaybackThread::releaseAudioPatch_l(handle);
4809 }
Eric Laurent054d9d32015-04-24 08:48:48 -07004810 return status;
4811}
4812
Andy Hungee58e4a2023-07-07 13:47:37 -07004813status_t PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004814{
4815 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07004816
jiabinc52b1ff2019-10-31 17:20:42 -07004817 mPatch = audio_patch{};
4818 mOutDeviceTypeAddrs.clear();
Eric Laurent054d9d32015-04-24 08:48:48 -07004819
Mikhail Naganov9ee05402016-10-13 15:58:17 -07004820 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07004821 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
4822 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07004823 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08004824 status = mOutput->stream->legacyReleaseAudioPatch();
Eric Laurent1c333e22014-05-20 10:48:17 -07004825 }
Eric Laurentdda206a2022-07-08 17:28:35 +02004826 // Force meteadata update after a route change
4827 mActiveTracks.setHasChanged();
4828
Eric Laurent1c333e22014-05-20 10:48:17 -07004829 return status;
4830}
4831
Andy Hungee58e4a2023-07-07 13:47:37 -07004832void PlaybackThread::addPatchTrack(const sp<IAfPatchTrack>& track)
Eric Laurent83b88082014-06-20 18:31:16 -07004833{
4834 Mutex::Autolock _l(mLock);
4835 mTracks.add(track);
4836}
4837
Andy Hungee58e4a2023-07-07 13:47:37 -07004838void PlaybackThread::deletePatchTrack(const sp<IAfPatchTrack>& track)
Eric Laurent83b88082014-06-20 18:31:16 -07004839{
4840 Mutex::Autolock _l(mLock);
4841 destroyTrack_l(track);
4842}
4843
Andy Hungee58e4a2023-07-07 13:47:37 -07004844void PlaybackThread::toAudioPortConfig(struct audio_port_config* config)
Eric Laurent83b88082014-06-20 18:31:16 -07004845{
Mikhail Naganovdc769682018-05-04 15:34:08 -07004846 ThreadBase::toAudioPortConfig(config);
Eric Laurent83b88082014-06-20 18:31:16 -07004847 config->role = AUDIO_PORT_ROLE_SOURCE;
4848 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
4849 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07004850 if (mOutput && mOutput->flags != AUDIO_OUTPUT_FLAG_NONE) {
4851 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
4852 config->flags.output = mOutput->flags;
4853 }
Eric Laurent83b88082014-06-20 18:31:16 -07004854}
4855
Eric Laurent81784c32012-11-19 14:55:58 -08004856// ----------------------------------------------------------------------------
4857
Andy Hungee58e4a2023-07-07 13:47:37 -07004858/* static */
4859sp<IAfPlaybackThread> IAfPlaybackThread::createMixerThread(
Andy Hung583043b2023-07-17 17:05:00 -07004860 const sp<IAfThreadCallback>& afThreadCallback, AudioStreamOut* output,
Andy Hungee58e4a2023-07-07 13:47:37 -07004861 audio_io_handle_t id, bool systemReady, type_t type, audio_config_base_t* mixerConfig) {
Andy Hung583043b2023-07-17 17:05:00 -07004862 return sp<MixerThread>::make(afThreadCallback, output, id, systemReady, type, mixerConfig);
Andy Hungee58e4a2023-07-07 13:47:37 -07004863}
4864
Andy Hung583043b2023-07-17 17:05:00 -07004865MixerThread::MixerThread(const sp<IAfThreadCallback>& afThreadCallback, AudioStreamOut* output,
Eric Laurentf1f22e72021-07-13 14:04:14 +02004866 audio_io_handle_t id, bool systemReady, type_t type, audio_config_base_t *mixerConfig)
Andy Hung583043b2023-07-17 17:05:00 -07004867 : PlaybackThread(afThreadCallback, output, id, type, systemReady, mixerConfig),
Eric Laurent81784c32012-11-19 14:55:58 -08004868 // mAudioMixer below
4869 // mFastMixer below
Eric Laurentb0463942022-12-20 16:31:10 +01004870 mBluetoothLatencyModesEnabled(false),
Andy Hung2ddee192015-12-18 17:34:44 -08004871 mFastMixerFutex(0),
4872 mMasterMono(false)
Eric Laurent81784c32012-11-19 14:55:58 -08004873 // mOutputSink below
4874 // mPipeSink below
4875 // mNormalSink below
4876{
Andy Hung583043b2023-07-17 17:05:00 -07004877 setMasterBalance(afThreadCallback->getMasterBalance_l());
jiabinc52b1ff2019-10-31 17:20:42 -07004878 ALOGV("MixerThread() id=%d type=%d", id, type);
Glenn Kasten49f36ba2017-12-06 13:02:02 -08004879 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%#x, mFrameSize=%zu, "
Glenn Kastenc42e9b42016-03-21 11:35:03 -07004880 "mFrameCount=%zu, mNormalFrameCount=%zu",
Eric Laurent81784c32012-11-19 14:55:58 -08004881 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
4882 mNormalFrameCount);
4883 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
4884
Andy Hungfbfc3952015-01-15 13:33:51 -08004885 if (type == DUPLICATING) {
4886 // The Duplicating thread uses the AudioMixer and delivers data to OutputTracks
4887 // (downstream MixerThreads) in DuplicatingThread::threadLoop_write().
4888 // Do not create or use mFastMixer, mOutputSink, mPipeSink, or mNormalSink.
4889 return;
4890 }
Eric Laurent81784c32012-11-19 14:55:58 -08004891 // create an NBAIO sink for the HAL output stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07004892 mOutputSink = new AudioStreamOutSink(output->stream);
Eric Laurent81784c32012-11-19 14:55:58 -08004893 size_t numCounterOffers = 0;
jiabin245cdd92018-12-07 17:55:15 -08004894 const NBAIO_Format offers[1] = {Format_from_SR_C(
4895 mSampleRate, mChannelCount + mHapticChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07004896#if !LOG_NDEBUG
4897 ssize_t index =
4898#else
4899 (void)
4900#endif
4901 mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08004902 ALOG_ASSERT(index == 0);
4903
4904 // initialize fast mixer depending on configuration
4905 bool initFastMixer;
jiabinc658e452022-10-21 20:52:21 +00004906 if (mType == SPATIALIZER || mType == BIT_PERFECT) {
Eric Laurent81784c32012-11-19 14:55:58 -08004907 initFastMixer = false;
Eric Laurentb62d0362021-10-26 17:40:18 +02004908 } else {
4909 switch (kUseFastMixer) {
4910 case FastMixer_Never:
4911 initFastMixer = false;
4912 break;
4913 case FastMixer_Always:
4914 initFastMixer = true;
4915 break;
4916 case FastMixer_Static:
4917 case FastMixer_Dynamic:
4918 initFastMixer = mFrameCount < mNormalFrameCount;
4919 break;
4920 }
4921 ALOGW_IF(initFastMixer == false && mFrameCount < mNormalFrameCount,
4922 "FastMixer is preferred for this sink as frameCount %zu is less than threshold %zu",
4923 mFrameCount, mNormalFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08004924 }
4925 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07004926 audio_format_t fastMixerFormat;
4927 if (mMixerBufferEnabled && mEffectBufferEnabled) {
4928 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
4929 } else {
4930 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
4931 }
4932 if (mFormat != fastMixerFormat) {
4933 // change our Sink format to accept our intermediate precision
4934 mFormat = fastMixerFormat;
4935 free(mSinkBuffer);
jiabin245cdd92018-12-07 17:55:15 -08004936 mFrameSize = audio_bytes_per_frame(mChannelCount + mHapticChannelCount, mFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07004937 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
4938 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
4939 }
Eric Laurent81784c32012-11-19 14:55:58 -08004940
4941 // create a MonoPipe to connect our submix to FastMixer
4942 NBAIO_Format format = mOutputSink->format();
Andy Hung8946a282018-04-19 20:04:56 -07004943
Andy Hung1258c1a2014-05-23 21:22:17 -07004944 // adjust format to match that of the Fast Mixer
Glenn Kasten49f36ba2017-12-06 13:02:02 -08004945 ALOGV("format changed from %#x to %#x", format.mFormat, fastMixerFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07004946 format.mFormat = fastMixerFormat;
4947 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
4948
Eric Laurent81784c32012-11-19 14:55:58 -08004949 // This pipe depth compensates for scheduling latency of the normal mixer thread.
4950 // When it wakes up after a maximum latency, it runs a few cycles quickly before
4951 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
4952 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
Andy Hung920f6572022-10-06 12:09:49 -07004953 const NBAIO_Format offersFast[1] = {format};
4954 size_t numCounterOffersFast = 0;
Andy Hung8946a282018-04-19 20:04:56 -07004955#if !LOG_NDEBUG
Eric Laurent1e28aaa2023-04-16 19:34:23 +02004956 index =
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07004957#else
4958 (void)
4959#endif
Andy Hung920f6572022-10-06 12:09:49 -07004960 monoPipe->negotiate(offersFast, std::size(offersFast),
4961 nullptr /* counterOffers */, numCounterOffersFast);
Eric Laurent81784c32012-11-19 14:55:58 -08004962 ALOG_ASSERT(index == 0);
4963 monoPipe->setAvgFrames((mScreenState & 1) ?
4964 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
4965 mPipeSink = monoPipe;
4966
Eric Laurent81784c32012-11-19 14:55:58 -08004967 // create fast mixer and configure it initially with just one fast track for our submix
Andy Hung8946a282018-04-19 20:04:56 -07004968 mFastMixer = new FastMixer(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08004969 FastMixerStateQueue *sq = mFastMixer->sq();
4970#ifdef STATE_QUEUE_DUMP
4971 sq->setObserverDump(&mStateQueueObserverDump);
4972 sq->setMutatorDump(&mStateQueueMutatorDump);
4973#endif
4974 FastMixerState *state = sq->begin();
4975 FastTrack *fastTrack = &state->mFastTracks[0];
4976 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
4977 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
4978 fastTrack->mVolumeProvider = NULL;
Mikhail Naganov55773032020-10-01 15:08:13 -07004979 fastTrack->mChannelMask = static_cast<audio_channel_mask_t>(
4980 mChannelMask | mHapticChannelMask); // mPipeSink channel mask for
4981 // audio to FastMixer
Andy Hunge8a1ced2014-05-09 15:02:21 -07004982 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
jiabin245cdd92018-12-07 17:55:15 -08004983 fastTrack->mHapticPlaybackEnabled = mHapticChannelMask != AUDIO_CHANNEL_NONE;
jiabine70bc7f2020-06-30 22:07:55 -07004984 fastTrack->mHapticIntensity = os::HapticScale::NONE;
Lais Andradebc3f37a2021-07-02 00:13:19 +01004985 fastTrack->mHapticMaxAmplitude = NAN;
Eric Laurent81784c32012-11-19 14:55:58 -08004986 fastTrack->mGeneration++;
4987 state->mFastTracksGen++;
4988 state->mTrackMask = 1;
4989 // fast mixer will use the HAL output sink
4990 state->mOutputSink = mOutputSink.get();
4991 state->mOutputSinkGen++;
4992 state->mFrameCount = mFrameCount;
jiabin245cdd92018-12-07 17:55:15 -08004993 // specify sink channel mask when haptic channel mask present as it can not
4994 // be calculated directly from channel count
4995 state->mSinkChannelMask = mHapticChannelMask == AUDIO_CHANNEL_NONE
Mikhail Naganov55773032020-10-01 15:08:13 -07004996 ? AUDIO_CHANNEL_NONE
4997 : static_cast<audio_channel_mask_t>(mChannelMask | mHapticChannelMask);
Eric Laurent81784c32012-11-19 14:55:58 -08004998 state->mCommand = FastMixerState::COLD_IDLE;
4999 // already done in constructor initialization list
5000 //mFastMixerFutex = 0;
5001 state->mColdFutexAddr = &mFastMixerFutex;
5002 state->mColdGen++;
5003 state->mDumpState = &mFastMixerDumpState;
Andy Hung583043b2023-07-17 17:05:00 -07005004 mFastMixerNBLogWriter = afThreadCallback->newWriter_l(kFastMixerLogSize, "FastMixer");
Glenn Kasten9e58b552013-01-18 15:09:48 -08005005 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08005006 sq->end();
5007 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
5008
Eric Tan0513b5d2018-09-17 10:32:48 -07005009 NBLog::thread_info_t info;
5010 info.id = mId;
5011 info.type = NBLog::FASTMIXER;
5012 mFastMixerNBLogWriter->log<NBLog::EVENT_THREAD_INFO>(info);
5013
Eric Laurent81784c32012-11-19 14:55:58 -08005014 // start the fast mixer
5015 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
5016 pid_t tid = mFastMixer->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07005017 sendPrioConfigEvent(getpid(), tid, kPriorityFastMixer, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08005018 stream()->setHalThreadPriority(kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08005019
5020#ifdef AUDIO_WATCHDOG
5021 // create and start the watchdog
5022 mAudioWatchdog = new AudioWatchdog();
5023 mAudioWatchdog->setDump(&mAudioWatchdogDump);
5024 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
5025 tid = mAudioWatchdog->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07005026 sendPrioConfigEvent(getpid(), tid, kPriorityFastMixer, false /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08005027#endif
Andy Hung8946a282018-04-19 20:04:56 -07005028 } else {
5029#ifdef TEE_SINK
5030 // Only use the MixerThread tee if there is no FastMixer.
5031 mTee.set(mOutputSink->format(), NBAIO_Tee::TEE_FLAG_OUTPUT_THREAD);
5032 mTee.setId(std::string("_") + std::to_string(mId) + "_M");
5033#endif
Eric Laurent81784c32012-11-19 14:55:58 -08005034 }
5035
5036 switch (kUseFastMixer) {
5037 case FastMixer_Never:
5038 case FastMixer_Dynamic:
5039 mNormalSink = mOutputSink;
5040 break;
5041 case FastMixer_Always:
5042 mNormalSink = mPipeSink;
5043 break;
5044 case FastMixer_Static:
5045 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
5046 break;
5047 }
5048}
5049
Andy Hungee58e4a2023-07-07 13:47:37 -07005050MixerThread::~MixerThread()
Eric Laurent81784c32012-11-19 14:55:58 -08005051{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005052 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005053 FastMixerStateQueue *sq = mFastMixer->sq();
5054 FastMixerState *state = sq->begin();
5055 if (state->mCommand == FastMixerState::COLD_IDLE) {
5056 int32_t old = android_atomic_inc(&mFastMixerFutex);
5057 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07005058 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08005059 }
5060 }
5061 state->mCommand = FastMixerState::EXIT;
5062 sq->end();
5063 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
5064 mFastMixer->join();
5065 // Though the fast mixer thread has exited, it's state queue is still valid.
5066 // We'll use that extract the final state which contains one remaining fast track
5067 // corresponding to our sub-mix.
5068 state = sq->begin();
5069 ALOG_ASSERT(state->mTrackMask == 1);
5070 FastTrack *fastTrack = &state->mFastTracks[0];
5071 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
5072 delete fastTrack->mBufferProvider;
5073 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005074 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08005075#ifdef AUDIO_WATCHDOG
5076 if (mAudioWatchdog != 0) {
5077 mAudioWatchdog->requestExit();
5078 mAudioWatchdog->requestExitAndWait();
5079 mAudioWatchdog.clear();
5080 }
5081#endif
5082 }
Andy Hung583043b2023-07-17 17:05:00 -07005083 mAfThreadCallback->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08005084 delete mAudioMixer;
5085}
5086
Andy Hungee58e4a2023-07-07 13:47:37 -07005087void MixerThread::onFirstRef() {
Eric Laurentb0463942022-12-20 16:31:10 +01005088 PlaybackThread::onFirstRef();
5089
5090 Mutex::Autolock _l(mLock);
5091 if (mOutput != nullptr && mOutput->stream != nullptr) {
5092 status_t status = mOutput->stream->setLatencyModeCallback(this);
5093 if (status != INVALID_OPERATION) {
5094 updateHalSupportedLatencyModes_l();
5095 }
5096 // Default to enabled if the HAL supports it. This can be changed by Audioflinger after
5097 // the thread construction according to AudioFlinger::mBluetoothLatencyModesEnabled
5098 mBluetoothLatencyModesEnabled.store(
5099 mOutput->audioHwDev->supportsBluetoothVariableLatency());
5100 }
5101}
Eric Laurent81784c32012-11-19 14:55:58 -08005102
Andy Hungee58e4a2023-07-07 13:47:37 -07005103uint32_t MixerThread::correctLatency_l(uint32_t latency) const
Eric Laurent81784c32012-11-19 14:55:58 -08005104{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005105 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005106 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
5107 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
5108 }
5109 return latency;
5110}
5111
Andy Hungee58e4a2023-07-07 13:47:37 -07005112ssize_t MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08005113{
5114 // FIXME we should only do one push per cycle; confirm this is true
5115 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005116 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005117 FastMixerStateQueue *sq = mFastMixer->sq();
5118 FastMixerState *state = sq->begin();
5119 if (state->mCommand != FastMixerState::MIX_WRITE &&
5120 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
5121 if (state->mCommand == FastMixerState::COLD_IDLE) {
Eric Laurenta2ab4502015-09-09 12:25:51 -07005122
5123 // FIXME workaround for first HAL write being CPU bound on some devices
5124 ATRACE_BEGIN("write");
5125 mOutput->write((char *)mSinkBuffer, 0);
5126 ATRACE_END();
5127
Eric Laurent81784c32012-11-19 14:55:58 -08005128 int32_t old = android_atomic_inc(&mFastMixerFutex);
5129 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07005130 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08005131 }
5132#ifdef AUDIO_WATCHDOG
5133 if (mAudioWatchdog != 0) {
5134 mAudioWatchdog->resume();
5135 }
5136#endif
5137 }
5138 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kastend797a9d2015-03-02 14:19:25 -08005139#ifdef FAST_THREAD_STATISTICS
Andy Hung583043b2023-07-17 17:05:00 -07005140 mFastMixerDumpState.increaseSamplingN(mAfThreadCallback->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08005141 FastThreadDumpState::kSamplingNforLowRamDevice : FastThreadDumpState::kSamplingN);
Glenn Kastend797a9d2015-03-02 14:19:25 -08005142#endif
Eric Laurent81784c32012-11-19 14:55:58 -08005143 sq->end();
5144 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
5145 if (kUseFastMixer == FastMixer_Dynamic) {
5146 mNormalSink = mPipeSink;
5147 }
5148 } else {
5149 sq->end(false /*didModify*/);
5150 }
5151 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005152 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08005153}
5154
Andy Hungee58e4a2023-07-07 13:47:37 -07005155void MixerThread::threadLoop_standby()
Eric Laurent81784c32012-11-19 14:55:58 -08005156{
5157 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005158 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005159 FastMixerStateQueue *sq = mFastMixer->sq();
5160 FastMixerState *state = sq->begin();
5161 if (!(state->mCommand & FastMixerState::IDLE)) {
Andy Hung2148bf02016-11-28 19:01:02 -08005162 // Report any frames trapped in the Monopipe
5163 MonoPipe *monoPipe = (MonoPipe *)mPipeSink.get();
5164 const long long pipeFrames = monoPipe->maxFrames() - monoPipe->availableToWrite();
5165 mLocalLog.log("threadLoop_standby: framesWritten:%lld suspendedFrames:%lld "
5166 "monoPipeWritten:%lld monoPipeLeft:%lld",
5167 (long long)mFramesWritten, (long long)mSuspendedFrames,
5168 (long long)mPipeSink->framesWritten(), pipeFrames);
5169 mLocalLog.log("threadLoop_standby: %s", mTimestamp.toString().c_str());
5170
Eric Laurent81784c32012-11-19 14:55:58 -08005171 state->mCommand = FastMixerState::COLD_IDLE;
5172 state->mColdFutexAddr = &mFastMixerFutex;
5173 state->mColdGen++;
5174 mFastMixerFutex = 0;
5175 sq->end();
5176 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
5177 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
5178 if (kUseFastMixer == FastMixer_Dynamic) {
5179 mNormalSink = mOutputSink;
5180 }
5181#ifdef AUDIO_WATCHDOG
5182 if (mAudioWatchdog != 0) {
5183 mAudioWatchdog->pause();
5184 }
5185#endif
5186 } else {
5187 sq->end(false /*didModify*/);
5188 }
5189 }
5190 PlaybackThread::threadLoop_standby();
5191}
5192
Andy Hungee58e4a2023-07-07 13:47:37 -07005193bool PlaybackThread::waitingAsyncCallback_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08005194{
5195 return false;
5196}
5197
Andy Hungee58e4a2023-07-07 13:47:37 -07005198bool PlaybackThread::shouldStandby_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08005199{
5200 return !mStandby;
5201}
5202
Andy Hungee58e4a2023-07-07 13:47:37 -07005203bool PlaybackThread::waitingAsyncCallback()
Eric Laurentbfb1b832013-01-07 09:53:42 -08005204{
5205 Mutex::Autolock _l(mLock);
5206 return waitingAsyncCallback_l();
5207}
5208
Eric Laurent81784c32012-11-19 14:55:58 -08005209// shared by MIXER and DIRECT, overridden by DUPLICATING
Andy Hungee58e4a2023-07-07 13:47:37 -07005210void PlaybackThread::threadLoop_standby()
Eric Laurent81784c32012-11-19 14:55:58 -08005211{
5212 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
Phil Burk062e67a2015-02-11 13:40:50 -08005213 mOutput->standby();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005214 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005215 // discard any pending drain or write ack by incrementing sequence
5216 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
5217 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005218 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005219 mCallbackThread->setWriteBlocked(mWriteAckSequence);
5220 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005221 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08005222 mHwPaused = false;
Eric Laurent68a40a82022-05-03 18:15:04 +02005223 setHalLatencyMode_l();
Eric Laurent81784c32012-11-19 14:55:58 -08005224}
5225
Andy Hungee58e4a2023-07-07 13:47:37 -07005226void PlaybackThread::onAddNewTrack_l()
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08005227{
5228 ALOGV("signal playback thread");
5229 broadcast_l();
5230}
5231
Andy Hungee58e4a2023-07-07 13:47:37 -07005232void PlaybackThread::onAsyncError()
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005233{
5234 for (int i = AUDIO_STREAM_SYSTEM; i < (int)AUDIO_STREAM_CNT; i++) {
5235 invalidateTracks((audio_stream_type_t)i);
5236 }
5237}
5238
Andy Hungee58e4a2023-07-07 13:47:37 -07005239void MixerThread::threadLoop_mix()
Eric Laurent81784c32012-11-19 14:55:58 -08005240{
Eric Laurent81784c32012-11-19 14:55:58 -08005241 // mix buffers...
Glenn Kastend79072e2016-01-06 08:41:20 -08005242 mAudioMixer->process();
Andy Hung25c2dac2014-02-27 14:56:00 -08005243 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005244 // increase sleep time progressively when application underrun condition clears.
5245 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
5246 // that a steady state of alternating ready/not ready conditions keeps the sleep time
5247 // such that we would underrun the audio HAL.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005248 if ((mSleepTimeUs == 0) && (sleepTimeShift > 0)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005249 sleepTimeShift--;
5250 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005251 mSleepTimeUs = 0;
5252 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08005253 //TODO: delay standby when effects have a tail
Glenn Kasten4c053ea2014-09-28 14:41:07 -07005254
Eric Laurent81784c32012-11-19 14:55:58 -08005255}
5256
Andy Hungee58e4a2023-07-07 13:47:37 -07005257void MixerThread::threadLoop_sleepTime()
Eric Laurent81784c32012-11-19 14:55:58 -08005258{
5259 // If no tracks are ready, sleep once for the duration of an output
5260 // buffer size, then write 0s to the output
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005261 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005262 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Andy Hung06d13222018-05-03 20:13:31 -07005263 if (mPipeSink.get() != nullptr && mPipeSink == mNormalSink) {
5264 // Using the Monopipe availableToWrite, we estimate the
5265 // sleep time to retry for more data (before we underrun).
5266 MonoPipe *monoPipe = static_cast<MonoPipe *>(mPipeSink.get());
5267 const ssize_t availableToWrite = mPipeSink->availableToWrite();
5268 const size_t pipeFrames = monoPipe->maxFrames();
5269 const size_t framesLeft = pipeFrames - max(availableToWrite, 0);
5270 // HAL_framecount <= framesDelay ~ framesLeft / 2 <= Normal_Mixer_framecount
5271 const size_t framesDelay = std::min(
5272 mNormalFrameCount, max(framesLeft / 2, mFrameCount));
5273 ALOGV("pipeFrames:%zu framesLeft:%zu framesDelay:%zu",
5274 pipeFrames, framesLeft, framesDelay);
5275 mSleepTimeUs = framesDelay * MICROS_PER_SECOND / mSampleRate;
5276 } else {
5277 mSleepTimeUs = mActiveSleepTimeUs >> sleepTimeShift;
5278 if (mSleepTimeUs < kMinThreadSleepTimeUs) {
5279 mSleepTimeUs = kMinThreadSleepTimeUs;
5280 }
5281 // reduce sleep time in case of consecutive application underruns to avoid
5282 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
5283 // duration we would end up writing less data than needed by the audio HAL if
5284 // the condition persists.
5285 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
5286 sleepTimeShift++;
5287 }
Eric Laurent81784c32012-11-19 14:55:58 -08005288 }
5289 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005290 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005291 }
5292 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08005293 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
5294 // before effects processing or output.
5295 if (mMixerBufferValid) {
5296 memset(mMixerBuffer, 0, mMixerBufferSize);
Eric Laurent39095982021-08-24 18:29:27 +02005297 if (mType == SPATIALIZER) {
5298 memset(mSinkBuffer, 0, mSinkBufferSize);
5299 }
Andy Hung98ef9782014-03-04 14:46:50 -08005300 } else {
5301 memset(mSinkBuffer, 0, mSinkBufferSize);
5302 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005303 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005304 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
5305 "anticipated start");
5306 }
5307 // TODO add standby time extension fct of effect tail
5308}
5309
5310// prepareTracks_l() must be called with ThreadBase::mLock held
Andy Hungee58e4a2023-07-07 13:47:37 -07005311PlaybackThread::mixer_state MixerThread::prepareTracks_l(
Andy Hung8d31fd22023-06-26 19:20:57 -07005312 Vector<sp<IAfTrack>>* tracksToRemove)
Eric Laurent81784c32012-11-19 14:55:58 -08005313{
Andy Hungc0691382018-09-12 18:01:57 -07005314 // clean up deleted track ids in AudioMixer before allocating new tracks
5315 (void)mTracks.processDeletedTrackIds([this](int trackId) {
5316 // for each trackId, destroy it in the AudioMixer
5317 if (mAudioMixer->exists(trackId)) {
5318 mAudioMixer->destroy(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08005319 }
5320 });
Andy Hungc0691382018-09-12 18:01:57 -07005321 mTracks.clearDeletedTrackIds();
Eric Laurent81784c32012-11-19 14:55:58 -08005322
5323 mixer_state mixerStatus = MIXER_IDLE;
5324 // find out which tracks need to be processed
5325 size_t count = mActiveTracks.size();
5326 size_t mixedTracks = 0;
5327 size_t tracksWithEffect = 0;
5328 // counts only _active_ fast tracks
5329 size_t fastTracks = 0;
5330 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
5331
5332 float masterVolume = mMasterVolume;
5333 bool masterMute = mMasterMute;
5334
5335 if (masterMute) {
5336 masterVolume = 0;
5337 }
5338 // Delegate master volume control to effect in output mix effect chain if needed
Andy Hung116bc262023-06-20 18:56:17 -07005339 sp<IAfEffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Eric Laurent81784c32012-11-19 14:55:58 -08005340 if (chain != 0) {
5341 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
5342 chain->setVolume_l(&v, &v);
5343 masterVolume = (float)((v + (1 << 23)) >> 24);
5344 chain.clear();
5345 }
5346
5347 // prepare a new state to push
5348 FastMixerStateQueue *sq = NULL;
5349 FastMixerState *state = NULL;
5350 bool didModify = false;
5351 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Andy Hungf2285312017-02-14 18:31:59 -08005352 bool coldIdle = false;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005353 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005354 sq = mFastMixer->sq();
5355 state = sq->begin();
Andy Hungf2285312017-02-14 18:31:59 -08005356 coldIdle = state->mCommand == FastMixerState::COLD_IDLE;
Eric Laurent81784c32012-11-19 14:55:58 -08005357 }
5358
Andy Hung69aed5f2014-02-25 17:24:40 -08005359 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08005360 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08005361
Andy Hungbd3b2b02018-05-21 10:53:11 -07005362 // DeferredOperations handles statistics after setting mixerStatus.
5363 class DeferredOperations {
5364 public:
Andy Hungea840382020-05-05 21:50:17 -07005365 DeferredOperations(mixer_state *mixerStatus, ThreadMetrics *threadMetrics)
5366 : mMixerStatus(mixerStatus)
5367 , mThreadMetrics(threadMetrics) {}
Andy Hungbd3b2b02018-05-21 10:53:11 -07005368
5369 // when leaving scope, tally frames properly.
5370 ~DeferredOperations() {
5371 // Tally underrun frames only if we are actually mixing (MIXER_TRACKS_READY)
5372 // because that is when the underrun occurs.
5373 // We do not distinguish between FastTracks and NormalTracks here.
Andy Hungea840382020-05-05 21:50:17 -07005374 size_t maxUnderrunFrames = 0;
Andy Hungb68f5eb2019-12-03 16:49:17 -08005375 if (*mMixerStatus == MIXER_TRACKS_READY && mUnderrunFrames.size() > 0) {
Andy Hungbd3b2b02018-05-21 10:53:11 -07005376 for (const auto &underrun : mUnderrunFrames) {
Andy Hungc2b11cb2020-04-22 09:04:01 -07005377 underrun.first->tallyUnderrunFrames(underrun.second);
Andy Hungea840382020-05-05 21:50:17 -07005378 maxUnderrunFrames = max(underrun.second, maxUnderrunFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07005379 }
5380 }
Andy Hungea840382020-05-05 21:50:17 -07005381 // send the max underrun frames for this mixer period
5382 mThreadMetrics->logUnderrunFrames(maxUnderrunFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07005383 }
5384
5385 // tallyUnderrunFrames() is called to update the track counters
5386 // with the number of underrun frames for a particular mixer period.
5387 // We defer tallying until we know the final mixer status.
Andy Hung8d31fd22023-06-26 19:20:57 -07005388 void tallyUnderrunFrames(const sp<IAfTrack>& track, size_t underrunFrames) {
Andy Hungbd3b2b02018-05-21 10:53:11 -07005389 mUnderrunFrames.emplace_back(track, underrunFrames);
5390 }
5391
5392 private:
5393 const mixer_state * const mMixerStatus;
Andy Hungea840382020-05-05 21:50:17 -07005394 ThreadMetrics * const mThreadMetrics;
Andy Hung8d31fd22023-06-26 19:20:57 -07005395 std::vector<std::pair<sp<IAfTrack>, size_t>> mUnderrunFrames;
Andy Hungea840382020-05-05 21:50:17 -07005396 } deferredOperations(&mixerStatus, &mThreadMetrics);
Andy Hungb68f5eb2019-12-03 16:49:17 -08005397 // implicit nested scope for variable capture
Andy Hungbd3b2b02018-05-21 10:53:11 -07005398
jiabin245cdd92018-12-07 17:55:15 -08005399 bool noFastHapticTrack = true;
Eric Laurent81784c32012-11-19 14:55:58 -08005400 for (size_t i=0 ; i<count ; i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07005401 const sp<IAfTrack> t = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08005402
5403 // this const just means the local variable doesn't change
Andy Hung8d31fd22023-06-26 19:20:57 -07005404 IAfTrack* const track = t.get();
Eric Laurent81784c32012-11-19 14:55:58 -08005405
5406 // process fast tracks
5407 if (track->isFastTrack()) {
Andy Hungae22b482019-05-09 15:38:55 -07005408 LOG_ALWAYS_FATAL_IF(mFastMixer.get() == nullptr,
5409 "%s(%d): FastTrack(%d) present without FastMixer",
5410 __func__, id(), track->id());
5411
jiabin245cdd92018-12-07 17:55:15 -08005412 if (track->getHapticPlaybackEnabled()) {
5413 noFastHapticTrack = false;
5414 }
Eric Laurent81784c32012-11-19 14:55:58 -08005415
5416 // It's theoretically possible (though unlikely) for a fast track to be created
5417 // and then removed within the same normal mix cycle. This is not a problem, as
5418 // the track never becomes active so it's fast mixer slot is never touched.
5419 // The converse, of removing an (active) track and then creating a new track
5420 // at the identical fast mixer slot within the same normal mix cycle,
5421 // is impossible because the slot isn't marked available until the end of each cycle.
Andy Hung8d31fd22023-06-26 19:20:57 -07005422 int j = track->fastIndex();
Glenn Kastendc2c50b2016-04-21 08:13:14 -07005423 ALOG_ASSERT(0 < j && j < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08005424 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
5425 FastTrack *fastTrack = &state->mFastTracks[j];
5426
5427 // Determine whether the track is currently in underrun condition,
5428 // and whether it had a recent underrun.
5429 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
5430 FastTrackUnderruns underruns = ftDump->mUnderruns;
5431 uint32_t recentFull = (underruns.mBitFields.mFull -
Andy Hung8d31fd22023-06-26 19:20:57 -07005432 track->fastTrackUnderruns().mBitFields.mFull) & UNDERRUN_MASK;
Eric Laurent81784c32012-11-19 14:55:58 -08005433 uint32_t recentPartial = (underruns.mBitFields.mPartial -
Andy Hung8d31fd22023-06-26 19:20:57 -07005434 track->fastTrackUnderruns().mBitFields.mPartial) & UNDERRUN_MASK;
Eric Laurent81784c32012-11-19 14:55:58 -08005435 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
Andy Hung8d31fd22023-06-26 19:20:57 -07005436 track->fastTrackUnderruns().mBitFields.mEmpty) & UNDERRUN_MASK;
Eric Laurent81784c32012-11-19 14:55:58 -08005437 uint32_t recentUnderruns = recentPartial + recentEmpty;
Andy Hung8d31fd22023-06-26 19:20:57 -07005438 track->fastTrackUnderruns() = underruns;
Eric Laurent81784c32012-11-19 14:55:58 -08005439 // don't count underruns that occur while stopping or pausing
5440 // or stopped which can occur when flush() is called while active
Andy Hungbd3b2b02018-05-21 10:53:11 -07005441 size_t underrunFrames = 0;
Glenn Kasten82aaf942013-07-17 16:05:07 -07005442 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
5443 recentUnderruns > 0) {
5444 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
Andy Hungbd3b2b02018-05-21 10:53:11 -07005445 underrunFrames = recentUnderruns * mFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08005446 }
Andy Hungbd3b2b02018-05-21 10:53:11 -07005447 // Immediately account for FastTrack underruns.
Andy Hung8d31fd22023-06-26 19:20:57 -07005448 track->audioTrackServerProxy()->tallyUnderrunFrames(underrunFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08005449
5450 // This is similar to the state machine for normal tracks,
5451 // with a few modifications for fast tracks.
5452 bool isActive = true;
Andy Hung8d31fd22023-06-26 19:20:57 -07005453 switch (track->state()) {
5454 case IAfTrackBase::STOPPING_1:
Eric Laurent81784c32012-11-19 14:55:58 -08005455 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08005456 if (recentUnderruns > 0 || track->isTerminated()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07005457 track->setState(IAfTrackBase::STOPPING_2);
Eric Laurent81784c32012-11-19 14:55:58 -08005458 }
5459 break;
Andy Hung8d31fd22023-06-26 19:20:57 -07005460 case IAfTrackBase::PAUSING:
Eric Laurent81784c32012-11-19 14:55:58 -08005461 // ramp down is not yet implemented
5462 track->setPaused();
5463 break;
Andy Hung8d31fd22023-06-26 19:20:57 -07005464 case IAfTrackBase::RESUMING:
Eric Laurent81784c32012-11-19 14:55:58 -08005465 // ramp up is not yet implemented
Andy Hung8d31fd22023-06-26 19:20:57 -07005466 track->setState(IAfTrackBase::ACTIVE);
Eric Laurent81784c32012-11-19 14:55:58 -08005467 break;
Andy Hung8d31fd22023-06-26 19:20:57 -07005468 case IAfTrackBase::ACTIVE:
Eric Laurent81784c32012-11-19 14:55:58 -08005469 if (recentFull > 0 || recentPartial > 0) {
5470 // track has provided at least some frames recently: reset retry count
Andy Hung8d31fd22023-06-26 19:20:57 -07005471 track->retryCount() = kMaxTrackRetries;
Eric Laurent81784c32012-11-19 14:55:58 -08005472 }
5473 if (recentUnderruns == 0) {
5474 // no recent underruns: stay active
5475 break;
5476 }
5477 // there has recently been an underrun of some kind
5478 if (track->sharedBuffer() == 0) {
5479 // were any of the recent underruns "empty" (no frames available)?
5480 if (recentEmpty == 0) {
5481 // no, then ignore the partial underruns as they are allowed indefinitely
5482 break;
5483 }
5484 // there has recently been an "empty" underrun: decrement the retry counter
Andy Hung8d31fd22023-06-26 19:20:57 -07005485 if (--(track->retryCount()) > 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005486 break;
5487 }
5488 // indicate to client process that the track was disabled because of underrun;
5489 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08005490 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08005491 // remove from active list, but state remains ACTIVE [confusing but true]
5492 isActive = false;
5493 break;
5494 }
Chih-Hung Hsieh2b487032018-09-13 14:16:02 -07005495 FALLTHROUGH_INTENDED;
Andy Hung8d31fd22023-06-26 19:20:57 -07005496 case IAfTrackBase::STOPPING_2:
5497 case IAfTrackBase::PAUSED:
5498 case IAfTrackBase::STOPPED:
5499 case IAfTrackBase::FLUSHED: // flush() while active
Eric Laurent81784c32012-11-19 14:55:58 -08005500 // Check for presentation complete if track is inactive
5501 // We have consumed all the buffers of this track.
5502 // This would be incomplete if we auto-paused on underrun
5503 {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005504 uint32_t latency = 0;
5505 status_t result = mOutput->stream->getLatency(&latency);
5506 ALOGE_IF(result != OK,
5507 "Error when retrieving output stream latency: %d", result);
5508 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08005509 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005510 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
5511 // track stays in active list until presentation is complete
5512 break;
5513 }
5514 }
5515 if (track->isStopping_2()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07005516 track->setState(IAfTrackBase::STOPPED);
Eric Laurent81784c32012-11-19 14:55:58 -08005517 }
5518 if (track->isStopped()) {
5519 // Can't reset directly, as fast mixer is still polling this track
5520 // track->reset();
5521 // So instead mark this track as needing to be reset after push with ack
5522 resetMask |= 1 << i;
5523 }
5524 isActive = false;
5525 break;
Andy Hung8d31fd22023-06-26 19:20:57 -07005526 case IAfTrackBase::IDLE:
Eric Laurent81784c32012-11-19 14:55:58 -08005527 default:
Andy Hung8d31fd22023-06-26 19:20:57 -07005528 LOG_ALWAYS_FATAL("unexpected track state %d", (int)track->state());
Eric Laurent81784c32012-11-19 14:55:58 -08005529 }
5530
5531 if (isActive) {
5532 // was it previously inactive?
5533 if (!(state->mTrackMask & (1 << j))) {
Andy Hung8d31fd22023-06-26 19:20:57 -07005534 ExtendedAudioBufferProvider *eabp = track->asExtendedAudioBufferProvider();
5535 VolumeProvider *vp = track->asVolumeProvider();
Eric Laurent81784c32012-11-19 14:55:58 -08005536 fastTrack->mBufferProvider = eabp;
5537 fastTrack->mVolumeProvider = vp;
Andy Hung8d31fd22023-06-26 19:20:57 -07005538 fastTrack->mChannelMask = track->channelMask();
5539 fastTrack->mFormat = track->format();
jiabin245cdd92018-12-07 17:55:15 -08005540 fastTrack->mHapticPlaybackEnabled = track->getHapticPlaybackEnabled();
jiabin77270b82018-12-18 15:41:29 -08005541 fastTrack->mHapticIntensity = track->getHapticIntensity();
Lais Andradebc3f37a2021-07-02 00:13:19 +01005542 fastTrack->mHapticMaxAmplitude = track->getHapticMaxAmplitude();
Eric Laurent81784c32012-11-19 14:55:58 -08005543 fastTrack->mGeneration++;
5544 state->mTrackMask |= 1 << j;
5545 didModify = true;
5546 // no acknowledgement required for newly active tracks
5547 }
Andy Hung8d31fd22023-06-26 19:20:57 -07005548 sp<AudioTrackServerProxy> proxy = track->audioTrackServerProxy();
Eric Laurenteab90452019-06-24 15:17:46 -07005549 float volume;
5550 if (track->isPlaybackRestricted() || mStreamTypes[track->streamType()].mute) {
5551 volume = 0.f;
5552 } else {
5553 volume = masterVolume * mStreamTypes[track->streamType()].volume;
5554 }
5555
5556 handleVoipVolume_l(&volume);
5557
Eric Laurent81784c32012-11-19 14:55:58 -08005558 // cache the combined master volume and stream type volume for fast mixer; this
5559 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005560 const float vh = track->getVolumeHandler()->getVolume(
Eric Laurenteab90452019-06-24 15:17:46 -07005561 proxy->framesReleased()).first;
5562 volume *= vh;
Andy Hung8d31fd22023-06-26 19:20:57 -07005563 track->setCachedVolume(volume);
Kevin Rocard12381092018-04-11 09:19:59 -07005564 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Vlad Popae2f5aef2022-07-25 16:00:20 +02005565 float vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
5566 float vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
5567
Andy Hung583043b2023-07-17 17:05:00 -07005568 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
Vlad Popae2f5aef2022-07-25 16:00:20 +02005569 /*muteState=*/{masterVolume == 0.f,
5570 mStreamTypes[track->streamType()].volume == 0.f,
5571 mStreamTypes[track->streamType()].mute,
5572 track->isPlaybackRestricted(),
Vlad Popa436c9172022-08-02 15:25:08 +02005573 vlf == 0.f && vrf == 0.f,
5574 vh == 0.f});
Vlad Popae2f5aef2022-07-25 16:00:20 +02005575
5576 vlf *= volume;
5577 vrf *= volume;
Eric Laurenteab90452019-06-24 15:17:46 -07005578
jiabin76d94692022-12-15 21:51:21 +00005579 track->setFinalVolume(vlf, vrf);
Eric Laurent81784c32012-11-19 14:55:58 -08005580 ++fastTracks;
5581 } else {
5582 // was it previously active?
5583 if (state->mTrackMask & (1 << j)) {
5584 fastTrack->mBufferProvider = NULL;
5585 fastTrack->mGeneration++;
5586 state->mTrackMask &= ~(1 << j);
5587 didModify = true;
5588 // If any fast tracks were removed, we must wait for acknowledgement
5589 // because we're about to decrement the last sp<> on those tracks.
5590 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
5591 } else {
Glenn Kastenbf848af2017-12-22 11:55:01 -08005592 // ALOGW rather than LOG_ALWAYS_FATAL because it seems there are cases where an
5593 // AudioTrack may start (which may not be with a start() but with a write()
5594 // after underrun) and immediately paused or released. In that case the
5595 // FastTrack state hasn't had time to update.
5596 // TODO Remove the ALOGW when this theory is confirmed.
5597 ALOGW("fast track %d should have been active; "
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08005598 "mState=%d, mTrackMask=%#x, recentUnderruns=%u, isShared=%d",
Andy Hung8d31fd22023-06-26 19:20:57 -07005599 j, (int)track->state(), state->mTrackMask, recentUnderruns,
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08005600 track->sharedBuffer() != 0);
Glenn Kastenbf848af2017-12-22 11:55:01 -08005601 // Since the FastMixer state already has the track inactive, do nothing here.
Eric Laurent81784c32012-11-19 14:55:58 -08005602 }
5603 tracksToRemove->add(track);
5604 // Avoids a misleading display in dumpsys
Andy Hung8d31fd22023-06-26 19:20:57 -07005605 track->fastTrackUnderruns().mBitFields.mMostRecent = UNDERRUN_FULL;
Eric Laurent81784c32012-11-19 14:55:58 -08005606 }
jiabin245cdd92018-12-07 17:55:15 -08005607 if (fastTrack->mHapticPlaybackEnabled != track->getHapticPlaybackEnabled()) {
5608 fastTrack->mHapticPlaybackEnabled = track->getHapticPlaybackEnabled();
5609 didModify = true;
5610 }
Eric Laurent81784c32012-11-19 14:55:58 -08005611 continue;
5612 }
5613
5614 { // local variable scope to avoid goto warning
5615
5616 audio_track_cblk_t* cblk = track->cblk();
5617
5618 // The first time a track is added we wait
5619 // for all its buffers to be filled before processing it
Andy Hungc0691382018-09-12 18:01:57 -07005620 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08005621
5622 // if an active track doesn't exist in the AudioMixer, create it.
Andy Hungc0691382018-09-12 18:01:57 -07005623 // use the trackId as the AudioMixer name.
5624 if (!mAudioMixer->exists(trackId)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08005625 status_t status = mAudioMixer->create(
Andy Hungc0691382018-09-12 18:01:57 -07005626 trackId,
Andy Hung8d31fd22023-06-26 19:20:57 -07005627 track->channelMask(),
5628 track->format(),
5629 track->sessionId());
Andy Hung1bc088a2018-02-09 15:57:31 -08005630 if (status != OK) {
Andy Hungc0691382018-09-12 18:01:57 -07005631 ALOGW("%s(): AudioMixer cannot create track(%d)"
5632 " mask %#x, format %#x, sessionId %d",
5633 __func__, trackId,
Andy Hung8d31fd22023-06-26 19:20:57 -07005634 track->channelMask(), track->format(), track->sessionId());
Andy Hung1bc088a2018-02-09 15:57:31 -08005635 tracksToRemove->add(track);
5636 track->invalidate(); // consider it dead.
5637 continue;
5638 }
5639 }
5640
Eric Laurent81784c32012-11-19 14:55:58 -08005641 // make sure that we have enough frames to mix one full buffer.
5642 // enforce this condition only once to enable draining the buffer in case the client
5643 // app does not call stop() and relies on underrun to stop:
5644 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
5645 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005646 size_t desiredFrames;
Andy Hung8d31fd22023-06-26 19:20:57 -07005647 const uint32_t sampleRate = track->audioTrackServerProxy()->getSampleRate();
5648 const AudioPlaybackRate playbackRate = track->audioTrackServerProxy()->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07005649
5650 desiredFrames = sourceFramesNeededWithTimestretch(
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07005651 sampleRate, mNormalFrameCount, mSampleRate, playbackRate.mSpeed);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005652 // TODO: ONLY USED FOR LEGACY RESAMPLERS, remove when they are removed.
5653 // add frames already consumed but not yet released by the resampler
5654 // because mAudioTrackServerProxy->framesReady() will include these frames
Andy Hungc0691382018-09-12 18:01:57 -07005655 desiredFrames += mAudioMixer->getUnreleasedFrames(trackId);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005656
Eric Laurent81784c32012-11-19 14:55:58 -08005657 uint32_t minFrames = 1;
5658 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
5659 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005660 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08005661 }
Eric Laurent13e4c962013-12-20 17:36:01 -08005662
5663 size_t framesReady = track->framesReady();
Glenn Kastene7754022014-10-31 12:11:26 -07005664 if (ATRACE_ENABLED()) {
5665 // I wish we had formatted trace names
Andy Hung1bc088a2018-02-09 15:57:31 -08005666 std::string traceName("nRdy");
Andy Hungc0691382018-09-12 18:01:57 -07005667 traceName += std::to_string(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08005668 ATRACE_INT(traceName.c_str(), framesReady);
Glenn Kastene7754022014-10-31 12:11:26 -07005669 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005670 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08005671 !track->isPaused() && !track->isTerminated())
5672 {
Andy Hungc0691382018-09-12 18:01:57 -07005673 ALOGVV("track(%d) s=%08x [OK] on thread %p", trackId, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08005674
5675 mixedTracks++;
5676
Andy Hung69aed5f2014-02-25 17:24:40 -08005677 // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
5678 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08005679 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08005680 if (track->mainBuffer() != mSinkBuffer &&
5681 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08005682 if (mEffectBufferEnabled) {
5683 mEffectBufferValid = true; // Later can set directly.
5684 }
Eric Laurent81784c32012-11-19 14:55:58 -08005685 chain = getEffectChain_l(track->sessionId());
5686 // Delegate volume control to effect in track effect chain if needed
5687 if (chain != 0) {
5688 tracksWithEffect++;
5689 } else {
Andy Hungc0691382018-09-12 18:01:57 -07005690 ALOGW("prepareTracks_l(): track(%d) attached to effect but no chain found on "
Eric Laurent81784c32012-11-19 14:55:58 -08005691 "session %d",
Andy Hungc0691382018-09-12 18:01:57 -07005692 trackId, track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08005693 }
5694 }
5695
5696
5697 int param = AudioMixer::VOLUME;
Andy Hung8d31fd22023-06-26 19:20:57 -07005698 if (track->fillingStatus() == IAfTrack::FS_FILLED) {
Eric Laurent81784c32012-11-19 14:55:58 -08005699 // no ramp for the first volume setting
Andy Hung8d31fd22023-06-26 19:20:57 -07005700 track->fillingStatus() = IAfTrack::FS_ACTIVE;
5701 if (track->state() == IAfTrackBase::RESUMING) {
5702 track->setState(IAfTrackBase::ACTIVE);
Revathi Uddaraju453bcb52017-08-14 14:19:40 +08005703 // If a new track is paused immediately after start, do not ramp on resume.
5704 if (cblk->mServer != 0) {
5705 param = AudioMixer::RAMP_VOLUME;
5706 }
Eric Laurent81784c32012-11-19 14:55:58 -08005707 }
Andy Hungc0691382018-09-12 18:01:57 -07005708 mAudioMixer->setParameter(trackId, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Eric Laurent7c29ec92017-09-20 17:54:22 -07005709 mLeftVolFloat = -1.0;
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005710 // FIXME should not make a decision based on mServer
5711 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005712 // If the track is stopped before the first frame was mixed,
5713 // do not apply ramp
5714 param = AudioMixer::RAMP_VOLUME;
5715 }
5716
5717 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07005718 uint32_t vl, vr; // in U8.24 integer format
5719 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Eric Laurent7c29ec92017-09-20 17:54:22 -07005720 // read original volumes with volume control
Eric Laurenteab90452019-06-24 15:17:46 -07005721 float v = masterVolume * mStreamTypes[track->streamType()].volume;
Andy Hung333ab962019-05-28 20:23:35 -07005722 // Always fetch volumeshaper volume to ensure state is updated.
Andy Hung8d31fd22023-06-26 19:20:57 -07005723 const sp<AudioTrackServerProxy> proxy = track->audioTrackServerProxy();
Andy Hung333ab962019-05-28 20:23:35 -07005724 const float vh = track->getVolumeHandler()->getVolume(
Andy Hung8d31fd22023-06-26 19:20:57 -07005725 track->audioTrackServerProxy()->framesReleased()).first;
Eric Laurent7c29ec92017-09-20 17:54:22 -07005726
Eric Laurenteab90452019-06-24 15:17:46 -07005727 if (mStreamTypes[track->streamType()].mute || track->isPlaybackRestricted()) {
5728 v = 0;
5729 }
5730
5731 handleVoipVolume_l(&v);
5732
5733 if (track->isPausing()) {
Andy Hung6be49402014-05-30 10:42:03 -07005734 vl = vr = 0;
5735 vlf = vrf = vaf = 0.;
Eric Laurenteab90452019-06-24 15:17:46 -07005736 track->setPaused();
Eric Laurent81784c32012-11-19 14:55:58 -08005737 } else {
Glenn Kastenc56f3422014-03-21 17:53:17 -07005738 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07005739 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
5740 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08005741 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07005742 if (vlf > GAIN_FLOAT_UNITY) {
5743 ALOGV("Track left volume out of range: %.3g", vlf);
5744 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08005745 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07005746 if (vrf > GAIN_FLOAT_UNITY) {
5747 ALOGV("Track right volume out of range: %.3g", vrf);
5748 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08005749 }
Vlad Popae2f5aef2022-07-25 16:00:20 +02005750
Andy Hung583043b2023-07-17 17:05:00 -07005751 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
Vlad Popae2f5aef2022-07-25 16:00:20 +02005752 /*muteState=*/{masterVolume == 0.f,
5753 mStreamTypes[track->streamType()].volume == 0.f,
5754 mStreamTypes[track->streamType()].mute,
5755 track->isPlaybackRestricted(),
Vlad Popa436c9172022-08-02 15:25:08 +02005756 vlf == 0.f && vrf == 0.f,
5757 vh == 0.f});
Vlad Popae2f5aef2022-07-25 16:00:20 +02005758
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005759 // now apply the master volume and stream type volume and shaper volume
5760 vlf *= v * vh;
5761 vrf *= v * vh;
Eric Laurent81784c32012-11-19 14:55:58 -08005762 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07005763 // then derive vl and vr as U8.24 versions for the effect chain
5764 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
5765 vl = (uint32_t) (scaleto8_24 * vlf);
5766 vr = (uint32_t) (scaleto8_24 * vrf);
5767 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08005768 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08005769 // send level comes from shared memory and so may be corrupt
5770 if (sendLevel > MAX_GAIN_INT) {
5771 ALOGV("Track send level out of range: %04X", sendLevel);
5772 sendLevel = MAX_GAIN_INT;
5773 }
Andy Hung6be49402014-05-30 10:42:03 -07005774 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
5775 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08005776 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005777
jiabin76d94692022-12-15 21:51:21 +00005778 track->setFinalVolume(vrf, vlf);
Kevin Rocard12381092018-04-11 09:19:59 -07005779
Eric Laurent81784c32012-11-19 14:55:58 -08005780 // Delegate volume control to effect in track effect chain if needed
5781 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
5782 // Do not ramp volume if volume is controlled by effect
5783 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08005784 // Update remaining floating point volume levels
5785 vlf = (float)vl / (1 << 24);
5786 vrf = (float)vr / (1 << 24);
Andy Hung8d31fd22023-06-26 19:20:57 -07005787 track->setHasVolumeController(true);
Eric Laurent81784c32012-11-19 14:55:58 -08005788 } else {
5789 // force no volume ramp when volume controller was just disabled or removed
5790 // from effect chain to avoid volume spike
Andy Hung8d31fd22023-06-26 19:20:57 -07005791 if (track->hasVolumeController()) {
Eric Laurent81784c32012-11-19 14:55:58 -08005792 param = AudioMixer::VOLUME;
5793 }
Andy Hung8d31fd22023-06-26 19:20:57 -07005794 track->setHasVolumeController(false);
Eric Laurent81784c32012-11-19 14:55:58 -08005795 }
5796
Eric Laurent81784c32012-11-19 14:55:58 -08005797 // XXX: these things DON'T need to be done each time
Andy Hung8d31fd22023-06-26 19:20:57 -07005798 mAudioMixer->setBufferProvider(trackId, track->asExtendedAudioBufferProvider());
Andy Hungc0691382018-09-12 18:01:57 -07005799 mAudioMixer->enable(trackId);
Eric Laurent81784c32012-11-19 14:55:58 -08005800
Andy Hungc0691382018-09-12 18:01:57 -07005801 mAudioMixer->setParameter(trackId, param, AudioMixer::VOLUME0, &vlf);
5802 mAudioMixer->setParameter(trackId, param, AudioMixer::VOLUME1, &vrf);
5803 mAudioMixer->setParameter(trackId, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08005804 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005805 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005806 AudioMixer::TRACK,
5807 AudioMixer::FORMAT, (void *)track->format());
5808 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005809 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005810 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00005811 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Eric Laurent39095982021-08-24 18:29:27 +02005812
Eric Laurentb0a7bc92022-04-05 15:06:08 +02005813 if (mType == SPATIALIZER && !track->isSpatialized()) {
Eric Laurent39095982021-08-24 18:29:27 +02005814 mAudioMixer->setParameter(
5815 trackId,
5816 AudioMixer::TRACK,
5817 AudioMixer::MIXER_CHANNEL_MASK,
5818 (void *)(uintptr_t)(mChannelMask | mHapticChannelMask));
5819 } else {
5820 mAudioMixer->setParameter(
5821 trackId,
5822 AudioMixer::TRACK,
5823 AudioMixer::MIXER_CHANNEL_MASK,
5824 (void *)(uintptr_t)(mMixerChannelMask | mHapticChannelMask));
5825 }
5826
Glenn Kastene3aa6592012-12-04 12:22:46 -08005827 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07005828 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Andy Hung333ab962019-05-28 20:23:35 -07005829 uint32_t reqSampleRate = proxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08005830 if (reqSampleRate == 0) {
5831 reqSampleRate = mSampleRate;
5832 } else if (reqSampleRate > maxSampleRate) {
5833 reqSampleRate = maxSampleRate;
5834 }
Eric Laurent81784c32012-11-19 14:55:58 -08005835 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005836 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005837 AudioMixer::RESAMPLE,
5838 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00005839 (void *)(uintptr_t)reqSampleRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005840
Andy Hung8edb8dc2015-03-26 19:13:55 -07005841 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005842 trackId,
Andy Hung8edb8dc2015-03-26 19:13:55 -07005843 AudioMixer::TIMESTRETCH,
5844 AudioMixer::PLAYBACK_RATE,
Andy Hung920f6572022-10-06 12:09:49 -07005845 // cast away constness for this generic API.
5846 const_cast<void *>(reinterpret_cast<const void *>(&playbackRate)));
Andy Hung8edb8dc2015-03-26 19:13:55 -07005847
Andy Hung69aed5f2014-02-25 17:24:40 -08005848 /*
5849 * Select the appropriate output buffer for the track.
5850 *
Andy Hung98ef9782014-03-04 14:46:50 -08005851 * Tracks with effects go into their own effects chain buffer
5852 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08005853 *
5854 * Other tracks can use mMixerBuffer for higher precision
5855 * channel accumulation. If this buffer is enabled
5856 * (mMixerBufferEnabled true), then selected tracks will accumulate
5857 * into it.
5858 *
5859 */
5860 if (mMixerBufferEnabled
5861 && (track->mainBuffer() == mSinkBuffer
5862 || track->mainBuffer() == mMixerBuffer)) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02005863 if (mType == SPATIALIZER && !track->isSpatialized()) {
Eric Laurent39095982021-08-24 18:29:27 +02005864 mAudioMixer->setParameter(
5865 trackId,
5866 AudioMixer::TRACK,
Eric Laurentb62d0362021-10-26 17:40:18 +02005867 AudioMixer::MIXER_FORMAT, (void *)mEffectBufferFormat);
Eric Laurent39095982021-08-24 18:29:27 +02005868 mAudioMixer->setParameter(
5869 trackId,
5870 AudioMixer::TRACK,
Eric Laurentb62d0362021-10-26 17:40:18 +02005871 AudioMixer::MAIN_BUFFER, (void *)mPostSpatializerBuffer);
Eric Laurent39095982021-08-24 18:29:27 +02005872 } else {
5873 mAudioMixer->setParameter(
5874 trackId,
5875 AudioMixer::TRACK,
5876 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
5877 mAudioMixer->setParameter(
5878 trackId,
5879 AudioMixer::TRACK,
5880 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
5881 // TODO: override track->mainBuffer()?
5882 mMixerBufferValid = true;
5883 }
Andy Hung69aed5f2014-02-25 17:24:40 -08005884 } else {
5885 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005886 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08005887 AudioMixer::TRACK,
Andy Hung319587b2023-05-23 14:01:03 -07005888 AudioMixer::MIXER_FORMAT, (void *)AUDIO_FORMAT_PCM_FLOAT);
Andy Hung69aed5f2014-02-25 17:24:40 -08005889 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005890 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08005891 AudioMixer::TRACK,
5892 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
5893 }
Eric Laurent81784c32012-11-19 14:55:58 -08005894 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005895 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005896 AudioMixer::TRACK,
5897 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
jiabin245cdd92018-12-07 17:55:15 -08005898 mAudioMixer->setParameter(
5899 trackId,
5900 AudioMixer::TRACK,
5901 AudioMixer::HAPTIC_ENABLED, (void *)(uintptr_t)track->getHapticPlaybackEnabled());
jiabin77270b82018-12-18 15:41:29 -08005902 mAudioMixer->setParameter(
5903 trackId,
5904 AudioMixer::TRACK,
5905 AudioMixer::HAPTIC_INTENSITY, (void *)(uintptr_t)track->getHapticIntensity());
Andy Hung8d31fd22023-06-26 19:20:57 -07005906 const float hapticMaxAmplitude = track->getHapticMaxAmplitude();
Lais Andradebc3f37a2021-07-02 00:13:19 +01005907 mAudioMixer->setParameter(
5908 trackId,
5909 AudioMixer::TRACK,
Andy Hung8d31fd22023-06-26 19:20:57 -07005910 AudioMixer::HAPTIC_MAX_AMPLITUDE, (void *)&hapticMaxAmplitude);
Eric Laurent81784c32012-11-19 14:55:58 -08005911
5912 // reset retry count
Andy Hung8d31fd22023-06-26 19:20:57 -07005913 track->retryCount() = kMaxTrackRetries;
Eric Laurent81784c32012-11-19 14:55:58 -08005914
5915 // If one track is ready, set the mixer ready if:
5916 // - the mixer was not ready during previous round OR
5917 // - no other track is not ready
5918 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
5919 mixerStatus != MIXER_TRACKS_ENABLED) {
5920 mixerStatus = MIXER_TRACKS_READY;
5921 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08005922
5923 // Enable the next few lines to instrument a test for underrun log handling.
5924 // TODO: Remove when we have a better way of testing the underrun log.
5925#if 0
5926 static int i;
5927 if ((++i & 0xf) == 0) {
5928 deferredOperations.tallyUnderrunFrames(track, 10 /* underrunFrames */);
5929 }
5930#endif
Eric Laurent81784c32012-11-19 14:55:58 -08005931 } else {
Andy Hungbd3b2b02018-05-21 10:53:11 -07005932 size_t underrunFrames = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005933 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Andy Hungb68f5eb2019-12-03 16:49:17 -08005934 ALOGV("track(%d) underrun, track state %s framesReady(%zu) < framesDesired(%zd)",
5935 trackId, track->getTrackStateAsString(), framesReady, desiredFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07005936 underrunFrames = desiredFrames;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005937 }
Andy Hungbd3b2b02018-05-21 10:53:11 -07005938 deferredOperations.tallyUnderrunFrames(track, underrunFrames);
Phil Burk2812d9e2016-01-04 10:34:30 -08005939
Eric Laurent81784c32012-11-19 14:55:58 -08005940 // clear effect chain input buffer if an active track underruns to avoid sending
5941 // previous audio buffer again to effects
5942 chain = getEffectChain_l(track->sessionId());
5943 if (chain != 0) {
5944 chain->clearInputBuffer();
5945 }
5946
Andy Hungc0691382018-09-12 18:01:57 -07005947 ALOGVV("track(%d) s=%08x [NOT READY] on thread %p", trackId, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08005948 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
5949 track->isStopped() || track->isPaused()) {
5950 // We have consumed all the buffers of this track.
5951 // Remove it from the list of active tracks.
5952 // TODO: use actual buffer filling status instead of latency when available from
5953 // audio HAL
5954 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08005955 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005956 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
5957 if (track->isStopped()) {
5958 track->reset();
5959 }
5960 tracksToRemove->add(track);
5961 }
5962 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08005963 // No buffers for this track. Give it a few chances to
5964 // fill a buffer, then remove it from active list.
Andy Hung8d31fd22023-06-26 19:20:57 -07005965 if (--(track->retryCount()) <= 0) {
Andy Hungc0691382018-09-12 18:01:57 -07005966 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p",
5967 trackId, this);
Eric Laurent81784c32012-11-19 14:55:58 -08005968 tracksToRemove->add(track);
5969 // indicate to client process that the track was disabled because of underrun;
5970 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08005971 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08005972 // If one track is not ready, mark the mixer also not ready if:
5973 // - the mixer was ready during previous round OR
5974 // - no other track is ready
5975 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
5976 mixerStatus != MIXER_TRACKS_READY) {
5977 mixerStatus = MIXER_TRACKS_ENABLED;
5978 }
5979 }
Andy Hungc0691382018-09-12 18:01:57 -07005980 mAudioMixer->disable(trackId);
Eric Laurent81784c32012-11-19 14:55:58 -08005981 }
5982
5983 } // local variable scope to avoid goto warning
Eric Laurent81784c32012-11-19 14:55:58 -08005984
5985 }
5986
jiabin245cdd92018-12-07 17:55:15 -08005987 if (mHapticChannelMask != AUDIO_CHANNEL_NONE && sq != NULL) {
5988 // When there is no fast track playing haptic and FastMixer exists,
5989 // enabling the first FastTrack, which provides mixed data from normal
5990 // tracks, to play haptic data.
5991 FastTrack *fastTrack = &state->mFastTracks[0];
5992 if (fastTrack->mHapticPlaybackEnabled != noFastHapticTrack) {
5993 fastTrack->mHapticPlaybackEnabled = noFastHapticTrack;
5994 didModify = true;
5995 }
5996 }
5997
Eric Laurent81784c32012-11-19 14:55:58 -08005998 // Push the new FastMixer state if necessary
Jing Mike537412f2023-03-12 11:01:47 +08005999 [[maybe_unused]] bool pauseAudioWatchdog = false;
Eric Laurent81784c32012-11-19 14:55:58 -08006000 if (didModify) {
6001 state->mFastTracksGen++;
6002 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
6003 if (kUseFastMixer == FastMixer_Dynamic &&
6004 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
6005 state->mCommand = FastMixerState::COLD_IDLE;
6006 state->mColdFutexAddr = &mFastMixerFutex;
6007 state->mColdGen++;
6008 mFastMixerFutex = 0;
6009 if (kUseFastMixer == FastMixer_Dynamic) {
6010 mNormalSink = mOutputSink;
6011 }
6012 // If we go into cold idle, need to wait for acknowledgement
6013 // so that fast mixer stops doing I/O.
6014 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
6015 pauseAudioWatchdog = true;
6016 }
Eric Laurent81784c32012-11-19 14:55:58 -08006017 }
6018 if (sq != NULL) {
6019 sq->end(didModify);
Andy Hungf2285312017-02-14 18:31:59 -08006020 // No need to block if the FastMixer is in COLD_IDLE as the FastThread
6021 // is not active. (We BLOCK_UNTIL_ACKED when entering COLD_IDLE
6022 // when bringing the output sink into standby.)
6023 //
6024 // We will get the latest FastMixer state when we come out of COLD_IDLE.
6025 //
6026 // This occurs with BT suspend when we idle the FastMixer with
6027 // active tracks, which may be added or removed.
6028 sq->push(coldIdle ? FastMixerStateQueue::BLOCK_NEVER : block);
Eric Laurent81784c32012-11-19 14:55:58 -08006029 }
6030#ifdef AUDIO_WATCHDOG
6031 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
6032 mAudioWatchdog->pause();
6033 }
6034#endif
6035
6036 // Now perform the deferred reset on fast tracks that have stopped
6037 while (resetMask != 0) {
6038 size_t i = __builtin_ctz(resetMask);
6039 ALOG_ASSERT(i < count);
6040 resetMask &= ~(1 << i);
Andy Hung8d31fd22023-06-26 19:20:57 -07006041 sp<IAfTrack> track = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08006042 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
6043 track->reset();
6044 }
6045
Andy Hung80d03d22018-04-10 10:32:11 -07006046 // Track destruction may occur outside of threadLoop once it is removed from active tracks.
6047 // Ensure the AudioMixer doesn't have a raw "buffer provider" pointer to the track if
6048 // it ceases to be active, to allow safe removal from the AudioMixer at the start
6049 // of prepareTracks_l(); this releases any outstanding buffer back to the track.
6050 // See also the implementation of destroyTrack_l().
6051 for (const auto &track : *tracksToRemove) {
Andy Hungc0691382018-09-12 18:01:57 -07006052 const int trackId = track->id();
6053 if (mAudioMixer->exists(trackId)) { // Normal tracks here, fast tracks in FastMixer.
6054 mAudioMixer->setBufferProvider(trackId, nullptr /* bufferProvider */);
Andy Hung80d03d22018-04-10 10:32:11 -07006055 }
6056 }
6057
Eric Laurent81784c32012-11-19 14:55:58 -08006058 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08006059 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08006060
Eric Laurentb3f315a2021-07-13 15:09:05 +02006061 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0 ||
6062 getEffectChain_l(AUDIO_SESSION_OUTPUT_STAGE) != 0) {
Eric Laurent97d547d2014-09-02 14:45:53 -07006063 mEffectBufferValid = true;
Marco Nelissenac302142014-10-20 13:15:38 -07006064 }
6065
6066 if (mEffectBufferValid) {
Marco Nelissen57088b52014-10-17 16:39:39 -07006067 // as long as there are effects we should clear the effects buffer, to avoid
6068 // passing a non-clean buffer to the effect chain
6069 memset(mEffectBuffer, 0, mEffectBufferSize);
Eric Laurentb62d0362021-10-26 17:40:18 +02006070 if (mType == SPATIALIZER) {
6071 memset(mPostSpatializerBuffer, 0, mPostSpatializerBufferSize);
6072 }
Eric Laurent97d547d2014-09-02 14:45:53 -07006073 }
Andy Hung69aed5f2014-02-25 17:24:40 -08006074 // sink or mix buffer must be cleared if all tracks are connected to an
6075 // effect chain as in this case the mixer will not write to the sink or mix buffer
6076 // and track effects will accumulate into it
Eric Laurent39095982021-08-24 18:29:27 +02006077 // always clear sink buffer for spatializer output as the output of the spatializer
6078 // effect will be accumulated into it
6079 if ((mBytesRemaining == 0) && (((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
6080 (mixedTracks == 0 && fastTracks > 0)) || (mType == SPATIALIZER))) {
Eric Laurent81784c32012-11-19 14:55:58 -08006081 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08006082 if (mMixerBufferValid) {
6083 memset(mMixerBuffer, 0, mMixerBufferSize);
6084 // TODO: In testing, mSinkBuffer below need not be cleared because
6085 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
6086 // after mixing.
6087 //
6088 // To enforce this guarantee:
6089 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
6090 // (mixedTracks == 0 && fastTracks > 0))
6091 // must imply MIXER_TRACKS_READY.
6092 // Later, we may clear buffers regardless, and skip much of this logic.
6093 }
Andy Hung98ef9782014-03-04 14:46:50 -08006094 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07006095 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08006096 }
6097
6098 // if any fast tracks, then status is ready
6099 mMixerStatusIgnoringFastTracks = mixerStatus;
6100 if (fastTracks > 0) {
6101 mixerStatus = MIXER_TRACKS_READY;
6102 }
6103 return mixerStatus;
6104}
6105
Eric Laurentad7dd962016-09-22 12:38:37 -07006106// trackCountForUid_l() must be called with ThreadBase::mLock held
Andy Hungee58e4a2023-07-07 13:47:37 -07006107uint32_t PlaybackThread::trackCountForUid_l(uid_t uid) const
Eric Laurentad7dd962016-09-22 12:38:37 -07006108{
6109 uint32_t trackCount = 0;
6110 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hung1f12a8a2016-11-07 16:10:30 -08006111 if (mTracks[i]->uid() == uid) {
Eric Laurentad7dd962016-09-22 12:38:37 -07006112 trackCount++;
6113 }
6114 }
6115 return trackCount;
6116}
6117
Andy Hungee58e4a2023-07-07 13:47:37 -07006118bool PlaybackThread::IsTimestampAdvancing::check(AudioStreamOut* output)
ziyangch8f194f12021-12-01 13:48:04 -08006119{
Brian Lindahl65e90012022-07-27 18:01:07 +02006120 // Check the timestamp to see if it's advancing once every 150ms. If we check too frequently, we
6121 // could falsely detect that the frame position has stalled due to underrun because we haven't
6122 // given the Audio HAL enough time to update.
6123 const nsecs_t nowNs = systemTime();
6124 if (nowNs - mPreviousNs < mMinimumTimeBetweenChecksNs) {
6125 return mLatchedValue;
6126 }
6127 mPreviousNs = nowNs;
6128 mLatchedValue = false;
6129 // Determine if the presentation position is still advancing.
ziyangch8f194f12021-12-01 13:48:04 -08006130 uint64_t position = 0;
6131 struct timespec unused;
Brian Lindahl65e90012022-07-27 18:01:07 +02006132 const status_t ret = output->getPresentationPosition(&position, &unused);
ziyangch8f194f12021-12-01 13:48:04 -08006133 if (ret == NO_ERROR) {
Brian Lindahl65e90012022-07-27 18:01:07 +02006134 if (position != mPreviousPosition) {
6135 mPreviousPosition = position;
6136 mLatchedValue = true;
ziyangch8f194f12021-12-01 13:48:04 -08006137 }
6138 }
Brian Lindahl65e90012022-07-27 18:01:07 +02006139 return mLatchedValue;
6140}
6141
Andy Hungee58e4a2023-07-07 13:47:37 -07006142void PlaybackThread::IsTimestampAdvancing::clear()
Brian Lindahl65e90012022-07-27 18:01:07 +02006143{
6144 mLatchedValue = true;
6145 mPreviousPosition = 0;
6146 mPreviousNs = 0;
ziyangch8f194f12021-12-01 13:48:04 -08006147}
6148
Andy Hung1bc088a2018-02-09 15:57:31 -08006149// isTrackAllowed_l() must be called with ThreadBase::mLock held
Andy Hungee58e4a2023-07-07 13:47:37 -07006150bool MixerThread::isTrackAllowed_l(
Andy Hung1bc088a2018-02-09 15:57:31 -08006151 audio_channel_mask_t channelMask, audio_format_t format,
6152 audio_session_t sessionId, uid_t uid) const
Eric Laurent81784c32012-11-19 14:55:58 -08006153{
Andy Hung1bc088a2018-02-09 15:57:31 -08006154 if (!PlaybackThread::isTrackAllowed_l(channelMask, format, sessionId, uid)) {
6155 return false;
Eric Laurentad7dd962016-09-22 12:38:37 -07006156 }
Andy Hung1bc088a2018-02-09 15:57:31 -08006157 // Check validity as we don't call AudioMixer::create() here.
Mikhail Naganov7ad7a252019-07-30 14:42:32 -07006158 if (!mAudioMixer->isValidFormat(format)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08006159 ALOGW("%s: invalid format: %#x", __func__, format);
6160 return false;
6161 }
Mikhail Naganov7ad7a252019-07-30 14:42:32 -07006162 if (!mAudioMixer->isValidChannelMask(channelMask)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08006163 ALOGW("%s: invalid channelMask: %#x", __func__, channelMask);
6164 return false;
6165 }
6166 return true;
Eric Laurent81784c32012-11-19 14:55:58 -08006167}
6168
Eric Laurent10351942014-05-08 18:49:52 -07006169// checkForNewParameter_l() must be called with ThreadBase::mLock held
Andy Hungee58e4a2023-07-07 13:47:37 -07006170bool MixerThread::checkForNewParameter_l(const String8& keyValuePair,
Eric Laurent10351942014-05-08 18:49:52 -07006171 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08006172{
Eric Laurent81784c32012-11-19 14:55:58 -08006173 bool reconfig = false;
Eric Laurent10351942014-05-08 18:49:52 -07006174 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006175
Glenn Kastenc05b8d72016-03-24 09:48:17 -07006176 AutoPark<FastMixer> park(mFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08006177
Eric Laurent10351942014-05-08 18:49:52 -07006178 AudioParameter param = AudioParameter(keyValuePair);
6179 int value;
6180 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
6181 reconfig = true;
6182 }
6183 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hungee58e4a2023-07-07 13:47:37 -07006184 if (!AudioFlinger::isValidPcmSinkFormat(static_cast<audio_format_t>(value))) {
Eric Laurent10351942014-05-08 18:49:52 -07006185 status = BAD_VALUE;
6186 } else {
6187 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08006188 reconfig = true;
6189 }
Eric Laurent10351942014-05-08 18:49:52 -07006190 }
6191 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hungee58e4a2023-07-07 13:47:37 -07006192 if (!AudioFlinger::isValidPcmSinkChannelMask(static_cast<audio_channel_mask_t>(value))) {
Eric Laurent10351942014-05-08 18:49:52 -07006193 status = BAD_VALUE;
6194 } else {
6195 // no need to save value, since it's constant
6196 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006197 }
Eric Laurent10351942014-05-08 18:49:52 -07006198 }
6199 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6200 // do not accept frame count changes if tracks are open as the track buffer
6201 // size depends on frame count and correct behavior would not be guaranteed
6202 // if frame count is changed after track creation
6203 if (!mTracks.isEmpty()) {
6204 status = INVALID_OPERATION;
6205 } else {
6206 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006207 }
Eric Laurent10351942014-05-08 18:49:52 -07006208 }
6209 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07006210 LOG_FATAL("Should not set routing device in MixerThread");
Eric Laurent10351942014-05-08 18:49:52 -07006211 }
Eric Laurent81784c32012-11-19 14:55:58 -08006212
Eric Laurent10351942014-05-08 18:49:52 -07006213 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006214 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07006215 if (!mStandby && status == INVALID_OPERATION) {
Andy Hungdda7aed2023-03-27 15:53:06 -07006216 ALOGW("%s: setParameters failed with keyValuePair %s, entering standby",
6217 __func__, keyValuePair.c_str());
Phil Burk062e67a2015-02-11 13:40:50 -08006218 mOutput->standby();
Andy Hungdda7aed2023-03-27 15:53:06 -07006219 mThreadMetrics.logEndInterval();
6220 mThreadSnapshot.onEnd();
6221 setStandby_l();
Eric Laurent10351942014-05-08 18:49:52 -07006222 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006223 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent81784c32012-11-19 14:55:58 -08006224 }
Eric Laurent10351942014-05-08 18:49:52 -07006225 if (status == NO_ERROR && reconfig) {
6226 readOutputParameters_l();
6227 delete mAudioMixer;
6228 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
Andy Hung1bc088a2018-02-09 15:57:31 -08006229 for (const auto &track : mTracks) {
Andy Hungc0691382018-09-12 18:01:57 -07006230 const int trackId = track->id();
Andy Hung920f6572022-10-06 12:09:49 -07006231 const status_t createStatus = mAudioMixer->create(
Andy Hungc0691382018-09-12 18:01:57 -07006232 trackId,
Andy Hung8d31fd22023-06-26 19:20:57 -07006233 track->channelMask(),
6234 track->format(),
6235 track->sessionId());
Andy Hung920f6572022-10-06 12:09:49 -07006236 ALOGW_IF(createStatus != NO_ERROR,
Andy Hungc0691382018-09-12 18:01:57 -07006237 "%s(): AudioMixer cannot create track(%d)"
6238 " mask %#x, format %#x, sessionId %d",
Andy Hung1bc088a2018-02-09 15:57:31 -08006239 __func__,
Andy Hung8d31fd22023-06-26 19:20:57 -07006240 trackId, track->channelMask(), track->format(), track->sessionId());
Eric Laurent10351942014-05-08 18:49:52 -07006241 }
Eric Laurent73e26b62015-04-27 16:55:58 -07006242 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07006243 }
Eric Laurent81784c32012-11-19 14:55:58 -08006244 }
6245
Dean Wheatley68918102021-03-19 22:09:19 +11006246 return reconfig;
Eric Laurent81784c32012-11-19 14:55:58 -08006247}
6248
6249
Andy Hungee58e4a2023-07-07 13:47:37 -07006250void MixerThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -08006251{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07006252 PlaybackThread::dumpInternals_l(fd, args);
Andy Hung40eb1a12015-06-18 13:42:02 -07006253 dprintf(fd, " Thread throttle time (msecs): %u\n", mThreadThrottleTimeMs);
Andy Hung8ed196a2018-01-05 13:21:11 -08006254 dprintf(fd, " AudioMixer tracks: %s\n", mAudioMixer->trackNames().c_str());
Andy Hung2ddee192015-12-18 17:34:44 -08006255 dprintf(fd, " Master mono: %s\n", mMasterMono ? "on" : "off");
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006256 dprintf(fd, " Master balance: %f (%s)\n", mMasterBalance.load(),
6257 (hasFastMixer() ? std::to_string(mFastMixer->getMasterBalance())
6258 : mBalance.toString()).c_str());
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006259 if (hasFastMixer()) {
6260 dprintf(fd, " FastMixer thread %p tid=%d", mFastMixer.get(), mFastMixer->getTid());
6261
6262 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
6263 // while we are dumping it. It may be inconsistent, but it won't mutate!
6264 // This is a large object so we place it on the heap.
6265 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
Eric Tan2942a4e2018-09-12 17:41:27 -07006266 const std::unique_ptr<FastMixerDumpState> copy =
6267 std::make_unique<FastMixerDumpState>(mFastMixerDumpState);
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006268 copy->dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08006269
6270#ifdef STATE_QUEUE_DUMP
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006271 // Similar for state queue
6272 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
6273 observerCopy.dump(fd);
6274 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
6275 mutatorCopy.dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08006276#endif
6277
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006278#ifdef AUDIO_WATCHDOG
6279 if (mAudioWatchdog != 0) {
6280 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
6281 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
6282 wdCopy.dump(fd);
6283 }
6284#endif
6285
6286 } else {
6287 dprintf(fd, " No FastMixer\n");
6288 }
Eric Laurent90cea102023-05-15 15:08:27 +02006289
6290 dprintf(fd, "Bluetooth latency modes are %senabled\n",
6291 mBluetoothLatencyModesEnabled ? "" : "not ");
6292 dprintf(fd, "HAL does %ssupport Bluetooth latency modes\n", mOutput != nullptr &&
6293 mOutput->audioHwDev->supportsBluetoothVariableLatency() ? "" : "not ");
6294 dprintf(fd, "Supported latency modes: %s\n", toString(mSupportedLatencyModes).c_str());
Eric Laurent81784c32012-11-19 14:55:58 -08006295}
6296
Andy Hungee58e4a2023-07-07 13:47:37 -07006297uint32_t MixerThread::idleSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08006298{
6299 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
6300}
6301
Andy Hungee58e4a2023-07-07 13:47:37 -07006302uint32_t MixerThread::suspendSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08006303{
6304 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
6305}
6306
Andy Hungee58e4a2023-07-07 13:47:37 -07006307void MixerThread::cacheParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08006308{
6309 PlaybackThread::cacheParameters_l();
6310
6311 // FIXME: Relaxed timing because of a certain device that can't meet latency
6312 // Should be reduced to 2x after the vendor fixes the driver issue
6313 // increase threshold again due to low power audio mode. The way this warning
6314 // threshold is calculated and its usefulness should be reconsidered anyway.
6315 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
6316}
6317
Andy Hungee58e4a2023-07-07 13:47:37 -07006318void MixerThread::onHalLatencyModesChanged_l() {
Andy Hung583043b2023-07-17 17:05:00 -07006319 mAfThreadCallback->onSupportedLatencyModesChanged(mId, mSupportedLatencyModes);
Eric Laurentb0463942022-12-20 16:31:10 +01006320}
6321
Andy Hungee58e4a2023-07-07 13:47:37 -07006322void MixerThread::setHalLatencyMode_l() {
Eric Laurentb0463942022-12-20 16:31:10 +01006323 // Only handle latency mode if:
6324 // - mBluetoothLatencyModesEnabled is true
6325 // - the HAL supports latency modes
6326 // - the selected device is Bluetooth LE or A2DP
6327 if (!mBluetoothLatencyModesEnabled.load() || mSupportedLatencyModes.empty()) {
6328 return;
6329 }
6330 if (mOutDeviceTypeAddrs.size() != 1
6331 || !(audio_is_a2dp_out_device(mOutDeviceTypeAddrs[0].mType)
6332 || audio_is_ble_out_device(mOutDeviceTypeAddrs[0].mType))) {
6333 return;
6334 }
6335
6336 audio_latency_mode_t latencyMode = AUDIO_LATENCY_MODE_FREE;
6337 if (mSupportedLatencyModes.size() == 1) {
6338 // If the HAL only support one latency mode currently, confirm the choice
6339 latencyMode = mSupportedLatencyModes[0];
6340 } else if (mSupportedLatencyModes.size() > 1) {
6341 // Request low latency if:
6342 // - At least one active track is either:
6343 // - a fast track with gaming usage or
6344 // - a track with acessibility usage
6345 for (const auto& track : mActiveTracks) {
6346 if ((track->isFastTrack() && track->attributes().usage == AUDIO_USAGE_GAME)
6347 || track->attributes().usage == AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY) {
6348 latencyMode = AUDIO_LATENCY_MODE_LOW;
6349 break;
6350 }
6351 }
6352 }
6353
6354 if (latencyMode != mSetLatencyMode) {
6355 status_t status = mOutput->stream->setLatencyMode(latencyMode);
6356 ALOGD("%s: thread(%d) setLatencyMode(%s) returned %d",
6357 __func__, mId, toString(latencyMode).c_str(), status);
6358 if (status == NO_ERROR) {
6359 mSetLatencyMode = latencyMode;
6360 }
6361 }
6362}
6363
Andy Hungee58e4a2023-07-07 13:47:37 -07006364void MixerThread::updateHalSupportedLatencyModes_l() {
Eric Laurentb0463942022-12-20 16:31:10 +01006365
6366 if (mOutput == nullptr || mOutput->stream == nullptr) {
6367 return;
6368 }
6369 std::vector<audio_latency_mode_t> latencyModes;
6370 const status_t status = mOutput->stream->getRecommendedLatencyModes(&latencyModes);
6371 if (status != NO_ERROR) {
6372 latencyModes.clear();
6373 }
6374 if (latencyModes != mSupportedLatencyModes) {
6375 ALOGD("%s: thread(%d) status %d supported latency modes: %s",
6376 __func__, mId, status, toString(latencyModes).c_str());
6377 mSupportedLatencyModes.swap(latencyModes);
6378 sendHalLatencyModesChangedEvent_l();
6379 }
6380}
6381
Andy Hungee58e4a2023-07-07 13:47:37 -07006382status_t MixerThread::getSupportedLatencyModes(
Eric Laurentb0463942022-12-20 16:31:10 +01006383 std::vector<audio_latency_mode_t>* modes) {
6384 if (modes == nullptr) {
6385 return BAD_VALUE;
6386 }
6387 Mutex::Autolock _l(mLock);
6388 *modes = mSupportedLatencyModes;
6389 return NO_ERROR;
6390}
6391
Andy Hungee58e4a2023-07-07 13:47:37 -07006392void MixerThread::onRecommendedLatencyModeChanged(
Eric Laurentb0463942022-12-20 16:31:10 +01006393 std::vector<audio_latency_mode_t> modes) {
6394 Mutex::Autolock _l(mLock);
6395 if (modes != mSupportedLatencyModes) {
6396 ALOGD("%s: thread(%d) supported latency modes: %s",
6397 __func__, mId, toString(modes).c_str());
6398 mSupportedLatencyModes.swap(modes);
6399 sendHalLatencyModesChangedEvent_l();
6400 }
6401}
6402
Andy Hungee58e4a2023-07-07 13:47:37 -07006403status_t MixerThread::setBluetoothVariableLatencyEnabled(bool enabled) {
Eric Laurentb0463942022-12-20 16:31:10 +01006404 if (mOutput == nullptr || mOutput->audioHwDev == nullptr
6405 || !mOutput->audioHwDev->supportsBluetoothVariableLatency()) {
6406 return INVALID_OPERATION;
6407 }
6408 mBluetoothLatencyModesEnabled.store(enabled);
6409 return NO_ERROR;
6410}
6411
Eric Laurent81784c32012-11-19 14:55:58 -08006412// ----------------------------------------------------------------------------
6413
Andy Hungee58e4a2023-07-07 13:47:37 -07006414/* static */
6415sp<IAfPlaybackThread> IAfPlaybackThread::createDirectOutputThread(
Andy Hung583043b2023-07-17 17:05:00 -07006416 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hungee58e4a2023-07-07 13:47:37 -07006417 AudioStreamOut* output, audio_io_handle_t id, bool systemReady,
6418 const audio_offload_info_t& offloadInfo) {
6419 return sp<DirectOutputThread>::make(
Andy Hung583043b2023-07-17 17:05:00 -07006420 afThreadCallback, output, id, systemReady, offloadInfo);
Andy Hungee58e4a2023-07-07 13:47:37 -07006421}
6422
Andy Hung583043b2023-07-17 17:05:00 -07006423DirectOutputThread::DirectOutputThread(const sp<IAfThreadCallback>& afThreadCallback,
Gareth Fennb18c1a32022-10-05 13:42:36 -07006424 AudioStreamOut* output, audio_io_handle_t id, ThreadBase::type_t type, bool systemReady,
6425 const audio_offload_info_t& offloadInfo)
Andy Hung583043b2023-07-17 17:05:00 -07006426 : PlaybackThread(afThreadCallback, output, id, type, systemReady)
Gareth Fennb18c1a32022-10-05 13:42:36 -07006427 , mOffloadInfo(offloadInfo)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006428{
Andy Hung583043b2023-07-17 17:05:00 -07006429 setMasterBalance(afThreadCallback->getMasterBalance_l());
Eric Laurentbfb1b832013-01-07 09:53:42 -08006430}
6431
Andy Hungee58e4a2023-07-07 13:47:37 -07006432DirectOutputThread::~DirectOutputThread()
Eric Laurent81784c32012-11-19 14:55:58 -08006433{
6434}
6435
Andy Hungee58e4a2023-07-07 13:47:37 -07006436void DirectOutputThread::dumpInternals_l(int fd, const Vector<String16>& args)
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006437{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07006438 PlaybackThread::dumpInternals_l(fd, args);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006439 dprintf(fd, " Master balance: %f Left: %f Right: %f\n",
6440 mMasterBalance.load(), mMasterBalanceLeft, mMasterBalanceRight);
6441}
6442
Andy Hungee58e4a2023-07-07 13:47:37 -07006443void DirectOutputThread::setMasterBalance(float balance)
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006444{
6445 Mutex::Autolock _l(mLock);
6446 if (mMasterBalance != balance) {
6447 mMasterBalance.store(balance);
6448 mBalance.computeStereoBalance(balance, &mMasterBalanceLeft, &mMasterBalanceRight);
6449 broadcast_l();
6450 }
6451}
6452
Andy Hungee58e4a2023-07-07 13:47:37 -07006453void DirectOutputThread::processVolume_l(IAfTrack* track, bool lastTrack)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006454{
Eric Laurentbfb1b832013-01-07 09:53:42 -08006455 float left, right;
6456
Andy Hung333ab962019-05-28 20:23:35 -07006457 // Ensure volumeshaper state always advances even when muted.
Andy Hung8d31fd22023-06-26 19:20:57 -07006458 const sp<AudioTrackServerProxy> proxy = track->audioTrackServerProxy();
Andy Hung398ffa22022-12-13 19:19:53 -08006459
6460 const size_t framesReleased = proxy->framesReleased();
6461 const int64_t frames = mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
6462 const int64_t time = mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
6463
6464 ALOGV("%s: Direct/Offload bufferConsumed:%zu timestamp frames:%lld time:%lld",
6465 __func__, framesReleased, (long long)frames, (long long)time);
6466
6467 const int64_t volumeShaperFrames =
6468 mMonotonicFrameCounter.updateAndGetMonotonicFrameCount(frames, time);
6469 const auto [shaperVolume, shaperActive] =
6470 track->getVolumeHandler()->getVolume(volumeShaperFrames);
Andy Hung333ab962019-05-28 20:23:35 -07006471 mVolumeShaperActive = shaperActive;
6472
Vlad Popae2f5aef2022-07-25 16:00:20 +02006473 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
6474 left = float_from_gain(gain_minifloat_unpack_left(vlr));
6475 right = float_from_gain(gain_minifloat_unpack_right(vlr));
6476
6477 const bool clientVolumeMute = (left == 0.f && right == 0.f);
6478
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08006479 if (mMasterMute || mStreamTypes[track->streamType()].mute || track->isPlaybackRestricted()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08006480 left = right = 0;
6481 } else {
6482 float typeVolume = mStreamTypes[track->streamType()].volume;
Andy Hung333ab962019-05-28 20:23:35 -07006483 const float v = mMasterVolume * typeVolume * shaperVolume;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08006484
Glenn Kastenc56f3422014-03-21 17:53:17 -07006485 if (left > GAIN_FLOAT_UNITY) {
6486 left = GAIN_FLOAT_UNITY;
6487 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07006488 if (right > GAIN_FLOAT_UNITY) {
6489 right = GAIN_FLOAT_UNITY;
6490 }
zhangjincheng86cb3bc2023-01-16 17:17:38 +08006491 left *= v;
6492 right *= v;
Andy Hung583043b2023-07-17 17:05:00 -07006493 if (mAfThreadCallback->getMode() != AUDIO_MODE_IN_COMMUNICATION
zhangjincheng86cb3bc2023-01-16 17:17:38 +08006494 || audio_channel_count_from_out_mask(mChannelMask) > 1) {
6495 left *= mMasterBalanceLeft; // DirectOutputThread balance applied as track volume
6496 right *= mMasterBalanceRight;
6497 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006498 }
6499
Andy Hung583043b2023-07-17 17:05:00 -07006500 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
Vlad Popae8d99472022-06-30 16:02:48 +02006501 /*muteState=*/{mMasterMute,
6502 mStreamTypes[track->streamType()].volume == 0.f,
6503 mStreamTypes[track->streamType()].mute,
Vlad Popae2f5aef2022-07-25 16:00:20 +02006504 track->isPlaybackRestricted(),
Vlad Popa436c9172022-08-02 15:25:08 +02006505 clientVolumeMute,
6506 shaperVolume == 0.f});
Vlad Popae8d99472022-06-30 16:02:48 +02006507
Eric Laurentbfb1b832013-01-07 09:53:42 -08006508 if (lastTrack) {
jiabin76d94692022-12-15 21:51:21 +00006509 track->setFinalVolume(left, right);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006510 if (left != mLeftVolFloat || right != mRightVolFloat) {
6511 mLeftVolFloat = left;
6512 mRightVolFloat = right;
6513
Eric Laurentbfb1b832013-01-07 09:53:42 -08006514 // Delegate volume control to effect in track effect chain if needed
6515 // only one effect chain can be present on DirectOutputThread, so if
6516 // there is one, the track is connected to it
6517 if (!mEffectChains.isEmpty()) {
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09006518 // if effect chain exists, volume is handled by it.
6519 // Convert volumes from float to 8.24
6520 uint32_t vl = (uint32_t)(left * (1 << 24));
6521 uint32_t vr = (uint32_t)(right * (1 << 24));
6522 // Direct/Offload effect chains set output volume in setVolume_l().
6523 (void)mEffectChains[0]->setVolume_l(&vl, &vr);
6524 } else {
6525 // otherwise we directly set the volume.
6526 setVolumeForOutput_l(left, right);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006527 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006528 }
6529 }
6530}
6531
Andy Hungee58e4a2023-07-07 13:47:37 -07006532void DirectOutputThread::onAddNewTrack_l()
Phil Burk43b4dcc2015-06-09 16:53:44 -07006533{
Andy Hung8d31fd22023-06-26 19:20:57 -07006534 sp<IAfTrack> previousTrack = mPreviousTrack.promote();
6535 sp<IAfTrack> latestTrack = mActiveTracks.getLatest();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006536
Eric Laurent0f0631e2015-07-06 18:01:25 -07006537 if (previousTrack != 0 && latestTrack != 0) {
6538 if (mType == DIRECT) {
6539 if (previousTrack.get() != latestTrack.get()) {
6540 mFlushPending = true;
6541 }
6542 } else /* mType == OFFLOAD */ {
Dean Wheatley0f51fd02022-08-31 16:41:40 +10006543 if (previousTrack->sessionId() != latestTrack->sessionId() ||
6544 previousTrack->isFlushPending()) {
Eric Laurent0f0631e2015-07-06 18:01:25 -07006545 mFlushPending = true;
6546 }
6547 }
Revathi Uddaraju20413a92016-10-13 17:16:14 +08006548 } else if (previousTrack == 0) {
6549 // there could be an old track added back during track transition for direct
6550 // output, so always issues flush to flush data of the previous track if it
6551 // was already destroyed with HAL paused, then flush can resume the playback
6552 mFlushPending = true;
Phil Burk43b4dcc2015-06-09 16:53:44 -07006553 }
6554 PlaybackThread::onAddNewTrack_l();
6555}
Eric Laurentbfb1b832013-01-07 09:53:42 -08006556
Andy Hungee58e4a2023-07-07 13:47:37 -07006557PlaybackThread::mixer_state DirectOutputThread::prepareTracks_l(
Andy Hung8d31fd22023-06-26 19:20:57 -07006558 Vector<sp<IAfTrack>>* tracksToRemove
Eric Laurent81784c32012-11-19 14:55:58 -08006559)
6560{
Eric Laurentd595b7c2013-04-03 17:27:56 -07006561 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08006562 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006563 bool doHwPause = false;
6564 bool doHwResume = false;
Eric Laurent81784c32012-11-19 14:55:58 -08006565
6566 // find out which tracks need to be processed
Andy Hung8d31fd22023-06-26 19:20:57 -07006567 for (const sp<IAfTrack>& t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08006568 if (t->isInvalid()) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07006569 ALOGW("An invalidated track shouldn't be in active list");
Eric Laurent5850c4c2016-11-10 13:04:31 -08006570 tracksToRemove->add(t);
Phil Burk43b4dcc2015-06-09 16:53:44 -07006571 continue;
6572 }
6573
Andy Hung8d31fd22023-06-26 19:20:57 -07006574 IAfTrack* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006575#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurent81784c32012-11-19 14:55:58 -08006576 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006577#endif
Eric Laurentfd477972013-10-25 18:10:40 -07006578 // Only consider last track started for volume and mixer state control.
6579 // In theory an older track could underrun and restart after the new one starts
6580 // but as we only care about the transition phase between two tracks on a
6581 // direct output, it is not a problem to ignore the underrun case.
Andy Hung8d31fd22023-06-26 19:20:57 -07006582 sp<IAfTrack> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08006583 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08006584
Kuowei Li23666472021-01-20 10:23:25 +08006585 if (track->isPausePending()) {
6586 track->pauseAck();
6587 // It is possible a track might have been flushed or stopped.
6588 // Other operations such as flush pending might occur on the next prepare.
6589 if (track->isPausing()) {
6590 track->setPaused();
6591 }
6592 // Always perform pause, as an immediate flush will change
6593 // the pause state to be no longer isPausing().
Phil Burk6fc2a7c2015-04-30 16:08:10 -07006594 if (mHwSupportsPause && last && !mHwPaused) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006595 doHwPause = true;
6596 mHwPaused = true;
6597 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08006598 } else if (track->isFlushPending()) {
6599 track->flushAck();
6600 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07006601 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006602 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07006603 } else if (track->isResumePending()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006604 track->resumeAck();
Eric Laurent3df841a2016-07-15 15:15:40 -07006605 if (last) {
6606 mLeftVolFloat = mRightVolFloat = -1.0;
6607 if (mHwPaused) {
6608 doHwResume = true;
6609 mHwPaused = false;
6610 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08006611 }
6612 }
6613
Eric Laurent81784c32012-11-19 14:55:58 -08006614 // The first time a track is added we wait
Phil Burk99adee32014-12-10 16:46:30 -08006615 // for all its buffers to be filled before processing it.
6616 // Allow draining the buffer in case the client
6617 // app does not call stop() and relies on underrun to stop:
Andy Hung8d31fd22023-06-26 19:20:57 -07006618 // hence the test on (track->retryCount() > 1).
6619 // If track->retryCount() <= 1 then track is about to be disabled, paused, removed,
Andy Hung455982f2021-04-27 17:46:12 -07006620 // so we accept any nonzero amount of data delivered by the AudioTrack (which will
6621 // reset the retry counter).
Phil Burkca5e6142015-07-14 09:42:29 -07006622 // Do not use a high threshold for compressed audio.
Andy Hung455982f2021-04-27 17:46:12 -07006623
6624 // target retry count that we will use is based on the time we wait for retries.
6625 const int32_t targetRetryCount = kMaxTrackRetriesDirectMs * 1000 / mActiveSleepTimeUs;
6626 // the retry threshold is when we accept any size for PCM data. This is slightly
6627 // smaller than the retry count so we can push small bits of data without a glitch.
6628 const int32_t retryThreshold = targetRetryCount > 2 ? targetRetryCount - 1 : 1;
Eric Laurent81784c32012-11-19 14:55:58 -08006629 uint32_t minFrames;
Phil Burk99adee32014-12-10 16:46:30 -08006630 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
Andy Hung8d31fd22023-06-26 19:20:57 -07006631 && (track->retryCount() > retryThreshold) && audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006632 minFrames = mNormalFrameCount;
6633 } else {
6634 minFrames = 1;
6635 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006636
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07006637 const size_t framesReady = track->framesReady();
6638 const int trackId = track->id();
6639 if (ATRACE_ENABLED()) {
6640 std::string traceName("nRdy");
6641 traceName += std::to_string(trackId);
6642 ATRACE_INT(traceName.c_str(), framesReady);
6643 }
6644 if ((framesReady >= minFrames) && track->isReady() && !track->isPaused() &&
Eric Laurentab5cdba2014-06-09 17:22:27 -07006645 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08006646 {
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07006647 ALOGVV("track(%d) s=%08x [OK]", trackId, cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08006648
Andy Hung8d31fd22023-06-26 19:20:57 -07006649 if (track->fillingStatus() == IAfTrack::FS_FILLED) {
6650 track->fillingStatus() = IAfTrack::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07006651 if (last) {
6652 // make sure processVolume_l() will apply new volume even if 0
6653 mLeftVolFloat = mRightVolFloat = -1.0;
6654 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08006655 if (!mHwSupportsPause) {
6656 track->resumeAck();
Eric Laurent81784c32012-11-19 14:55:58 -08006657 }
6658 }
6659
6660 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08006661 processVolume_l(track, last);
6662 if (last) {
Andy Hung8d31fd22023-06-26 19:20:57 -07006663 sp<IAfTrack> previousTrack = mPreviousTrack.promote();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006664 if (previousTrack != 0) {
6665 if (track != previousTrack.get()) {
6666 // Flush any data still being written from last track
6667 mBytesRemaining = 0;
Eric Laurent0f0631e2015-07-06 18:01:25 -07006668 // Invalidate previous track to force a seek when resuming.
6669 previousTrack->invalidate();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006670 }
6671 }
6672 mPreviousTrack = track;
6673
Eric Laurentd595b7c2013-04-03 17:27:56 -07006674 // reset retry count
Andy Hung8d31fd22023-06-26 19:20:57 -07006675 track->retryCount() = targetRetryCount;
Eric Laurent5850c4c2016-11-10 13:04:31 -08006676 mActiveTrack = t;
Eric Laurentd595b7c2013-04-03 17:27:56 -07006677 mixerStatus = MIXER_TRACKS_READY;
Eric Laurent5cff4032015-05-26 13:49:58 -07006678 if (mHwPaused) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08006679 doHwResume = true;
6680 mHwPaused = false;
6681 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07006682 }
Eric Laurent81784c32012-11-19 14:55:58 -08006683 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07006684 // clear effect chain input buffer if the last active track started underruns
6685 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07006686 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08006687 mEffectChains[0]->clearInputBuffer();
6688 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07006689 if (track->isStopping_1()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07006690 track->setState(IAfTrackBase::STOPPING_2);
Eric Laurentb369caf2015-03-30 20:51:47 -07006691 if (last && mHwPaused) {
6692 doHwResume = true;
6693 mHwPaused = false;
6694 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07006695 }
6696 if ((track->sharedBuffer() != 0) || track->isStopped() ||
6697 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08006698 // We have consumed all the buffers of this track.
6699 // Remove it from the list of active tracks.
Atneya Nair0cae0432022-05-10 18:12:12 -04006700 bool presComplete = false;
Eric Laurentfd477972013-10-25 18:10:40 -07006701 if (mStandby || !last ||
Atneya Nair0cae0432022-05-10 18:12:12 -04006702 (presComplete = track->presentationComplete(latency_l())) ||
Jindong32dc26e2019-11-11 18:10:01 +08006703 track->isPaused() || mHwPaused) {
Atneya Nair0cae0432022-05-10 18:12:12 -04006704 if (presComplete) {
6705 mOutput->presentationComplete();
6706 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07006707 if (track->isStopping_2()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07006708 track->setState(IAfTrackBase::STOPPED);
Eric Laurentab5cdba2014-06-09 17:22:27 -07006709 }
Eric Laurent81784c32012-11-19 14:55:58 -08006710 if (track->isStopped()) {
6711 track->reset();
6712 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07006713 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08006714 }
6715 } else {
6716 // No buffers for this track. Give it a few chances to
6717 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07006718 // Only consider last track started for mixer state control
Brian Lindahl65e90012022-07-27 18:01:07 +02006719 bool isTimestampAdvancing = mIsTimestampAdvancing.check(mOutput);
Gareth Fennb18c1a32022-10-05 13:42:36 -07006720 if (!isTunerStream() // tuner streams remain active in underrun
Andy Hung8d31fd22023-06-26 19:20:57 -07006721 && --(track->retryCount()) <= 0) {
Brian Lindahl65e90012022-07-27 18:01:07 +02006722 if (isTimestampAdvancing) { // HAL is still playing audio, give us more time.
Andy Hung8d31fd22023-06-26 19:20:57 -07006723 track->retryCount() = kMaxTrackRetriesOffload;
ziyangch8f194f12021-12-01 13:48:04 -08006724 } else {
6725 ALOGV("BUFFER TIMEOUT: remove track(%d) from active list", trackId);
6726 tracksToRemove->add(track);
6727 // indicate to client process that the track was disabled because of
6728 // underrun; it will then automatically call start() when data is available
6729 track->disable();
6730 // only do hw pause when track is going to be removed due to BUFFER TIMEOUT.
6731 // unlike mixerthread, HAL can be paused for direct output
6732 ALOGW("pause because of UNDERRUN, framesReady = %zu,"
6733 "minFrames = %u, mFormat = %#x",
6734 framesReady, minFrames, mFormat);
6735 if (last && mHwSupportsPause && !mHwPaused && !mStandby) {
6736 doHwPause = true;
6737 mHwPaused = true;
6738 }
Eric Laurent0f7b5f22014-12-19 10:43:21 -08006739 }
Haynes Mathew George5c6daae2017-01-24 20:06:05 -08006740 } else if (last) {
6741 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurent81784c32012-11-19 14:55:58 -08006742 }
6743 }
6744 }
6745 }
6746
Eric Laurentd1f69b02014-12-15 14:33:13 -08006747 // if an active track did not command a flush, check for pending flush on stopped tracks
Phil Burk43b4dcc2015-06-09 16:53:44 -07006748 if (!mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006749 for (size_t i = 0; i < mTracks.size(); i++) {
6750 if (mTracks[i]->isFlushPending()) {
6751 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006752 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006753 }
6754 }
6755 }
6756
6757 // make sure the pause/flush/resume sequence is executed in the right order.
6758 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
6759 // before flush and then resume HW. This can happen in case of pause/flush/resume
6760 // if resume is received before pause is executed.
6761 if (mHwSupportsPause && !mStandby &&
Phil Burk43b4dcc2015-06-09 16:53:44 -07006762 (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006763 status_t result = mOutput->stream->pause();
6764 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Gareth Fenncd1e1622022-10-05 11:45:45 -07006765 doHwResume = !doHwPause; // resume if pause is due to flush.
Eric Laurentd1f69b02014-12-15 14:33:13 -08006766 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07006767 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006768 flushHw_l();
6769 }
6770 if (mHwSupportsPause && !mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006771 status_t result = mOutput->stream->resume();
6772 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08006773 }
Eric Laurent81784c32012-11-19 14:55:58 -08006774 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08006775 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08006776
6777 return mixerStatus;
6778}
6779
Andy Hungee58e4a2023-07-07 13:47:37 -07006780void DirectOutputThread::threadLoop_mix()
Eric Laurent81784c32012-11-19 14:55:58 -08006781{
Eric Laurent81784c32012-11-19 14:55:58 -08006782 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08006783 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08006784 // output audio to hardware
6785 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07006786 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08006787 buffer.frameCount = frameCount;
Phil Burk062e67a2015-02-11 13:40:50 -08006788 status_t status = mActiveTrack->getNextBuffer(&buffer);
6789 if (status != NO_ERROR || buffer.raw == NULL) {
Eric Laurent51716182016-02-29 18:00:56 -08006790 // no need to pad with 0 for compressed audio
6791 if (audio_has_proportional_frames(mFormat)) {
6792 memset(curBuf, 0, frameCount * mFrameSize);
6793 }
Eric Laurent81784c32012-11-19 14:55:58 -08006794 break;
6795 }
6796 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
6797 frameCount -= buffer.frameCount;
6798 curBuf += buffer.frameCount * mFrameSize;
6799 mActiveTrack->releaseBuffer(&buffer);
6800 }
Andy Hung2098f272014-02-27 14:00:06 -08006801 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006802 mSleepTimeUs = 0;
6803 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08006804 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08006805}
6806
Andy Hungee58e4a2023-07-07 13:47:37 -07006807void DirectOutputThread::threadLoop_sleepTime()
Eric Laurent81784c32012-11-19 14:55:58 -08006808{
Eric Laurentd1f69b02014-12-15 14:33:13 -08006809 // do not write to HAL when paused
Eric Laurent0f7b5f22014-12-19 10:43:21 -08006810 if (mHwPaused || (usesHwAvSync() && mStandby)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006811 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006812 return;
6813 }
Andy Hung85ba3332021-04-27 17:40:26 -07006814 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
6815 mSleepTimeUs = mActiveSleepTimeUs;
6816 } else {
6817 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006818 }
Andy Hung85ba3332021-04-27 17:40:26 -07006819 // Note: In S or later, we do not write zeroes for
6820 // linear or proportional PCM direct tracks in underrun.
Eric Laurent81784c32012-11-19 14:55:58 -08006821}
6822
Andy Hungee58e4a2023-07-07 13:47:37 -07006823void DirectOutputThread::threadLoop_exit()
Eric Laurentd1f69b02014-12-15 14:33:13 -08006824{
6825 {
6826 Mutex::Autolock _l(mLock);
Eric Laurentd1f69b02014-12-15 14:33:13 -08006827 for (size_t i = 0; i < mTracks.size(); i++) {
6828 if (mTracks[i]->isFlushPending()) {
6829 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006830 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006831 }
6832 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07006833 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006834 flushHw_l();
6835 }
6836 }
6837 PlaybackThread::threadLoop_exit();
6838}
6839
6840// must be called with thread mutex locked
Andy Hungee58e4a2023-07-07 13:47:37 -07006841bool DirectOutputThread::shouldStandby_l()
Eric Laurentd1f69b02014-12-15 14:33:13 -08006842{
6843 bool trackPaused = false;
Eric Laurentb369caf2015-03-30 20:51:47 -07006844 bool trackStopped = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006845
6846 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
6847 // after a timeout and we will enter standby then.
6848 if (mTracks.size() > 0) {
6849 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
Eric Laurentb369caf2015-03-30 20:51:47 -07006850 trackStopped = mTracks[mTracks.size() - 1]->isStopped() ||
Andy Hung8d31fd22023-06-26 19:20:57 -07006851 mTracks[mTracks.size() - 1]->state() == IAfTrackBase::IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006852 }
6853
Eric Laurent5cff4032015-05-26 13:49:58 -07006854 return !mStandby && !(trackPaused || (mHwPaused && !trackStopped));
Eric Laurentd1f69b02014-12-15 14:33:13 -08006855}
6856
Eric Laurent10351942014-05-08 18:49:52 -07006857// checkForNewParameter_l() must be called with ThreadBase::mLock held
Andy Hungee58e4a2023-07-07 13:47:37 -07006858bool DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
Eric Laurent10351942014-05-08 18:49:52 -07006859 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08006860{
6861 bool reconfig = false;
Eric Laurent10351942014-05-08 18:49:52 -07006862 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006863
Eric Laurent10351942014-05-08 18:49:52 -07006864 AudioParameter param = AudioParameter(keyValuePair);
6865 int value;
6866 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07006867 LOG_FATAL("Should not set routing device in DirectOutputThread");
Eric Laurent81784c32012-11-19 14:55:58 -08006868 }
Eric Laurent10351942014-05-08 18:49:52 -07006869 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6870 // do not accept frame count changes if tracks are open as the track buffer
6871 // size depends on frame count and correct behavior would not be garantied
6872 // if frame count is changed after track creation
6873 if (!mTracks.isEmpty()) {
6874 status = INVALID_OPERATION;
6875 } else {
6876 reconfig = true;
6877 }
6878 }
6879 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006880 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07006881 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08006882 mOutput->standby();
Andy Hungcf10d742020-04-28 15:38:24 -07006883 if (!mStandby) {
6884 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07006885 mThreadSnapshot.onEnd();
Eric Laurent19952e12023-04-20 10:08:29 +02006886 setStandby_l();
Andy Hungcf10d742020-04-28 15:38:24 -07006887 }
Eric Laurent10351942014-05-08 18:49:52 -07006888 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006889 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07006890 }
6891 if (status == NO_ERROR && reconfig) {
6892 readOutputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07006893 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07006894 }
6895 }
6896
Dean Wheatley68918102021-03-19 22:09:19 +11006897 return reconfig;
Eric Laurent81784c32012-11-19 14:55:58 -08006898}
6899
Andy Hungee58e4a2023-07-07 13:47:37 -07006900uint32_t DirectOutputThread::activeSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08006901{
6902 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08006903 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006904 time = PlaybackThread::activeSleepTimeUs();
6905 } else {
Eric Laurent51716182016-02-29 18:00:56 -08006906 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006907 }
6908 return time;
6909}
6910
Andy Hungee58e4a2023-07-07 13:47:37 -07006911uint32_t DirectOutputThread::idleSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08006912{
6913 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08006914 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006915 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
6916 } else {
Eric Laurent51716182016-02-29 18:00:56 -08006917 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006918 }
6919 return time;
6920}
6921
Andy Hungee58e4a2023-07-07 13:47:37 -07006922uint32_t DirectOutputThread::suspendSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08006923{
6924 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08006925 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006926 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
6927 } else {
Eric Laurent51716182016-02-29 18:00:56 -08006928 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006929 }
6930 return time;
6931}
6932
Andy Hungee58e4a2023-07-07 13:47:37 -07006933void DirectOutputThread::cacheParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08006934{
6935 PlaybackThread::cacheParameters_l();
6936
6937 // use shorter standby delay as on normal output to release
6938 // hardware resources as soon as possible
Eric Laurentb369caf2015-03-30 20:51:47 -07006939 // no delay on outputs with HW A/V sync
6940 if (usesHwAvSync()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006941 mStandbyDelayNs = 0;
Phil Burkfdb3c072016-02-09 10:47:02 -08006942 } else if ((mType == OFFLOAD) && !audio_has_proportional_frames(mFormat)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006943 mStandbyDelayNs = kOffloadStandbyDelayNs;
Eric Laurent5cff4032015-05-26 13:49:58 -07006944 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006945 mStandbyDelayNs = microseconds(mActiveSleepTimeUs*2);
Eric Laurent972a1732013-09-04 09:42:59 -07006946 }
Eric Laurent81784c32012-11-19 14:55:58 -08006947}
6948
Andy Hungee58e4a2023-07-07 13:47:37 -07006949void DirectOutputThread::flushHw_l()
Eric Laurente659ef42014-09-29 13:06:46 -07006950{
ziyangch8f194f12021-12-01 13:48:04 -08006951 PlaybackThread::flushHw_l();
Phil Burk062e67a2015-02-11 13:40:50 -08006952 mOutput->flush();
Eric Laurentd1f69b02014-12-15 14:33:13 -08006953 mHwPaused = false;
Phil Burk43b4dcc2015-06-09 16:53:44 -07006954 mFlushPending = false;
Dean Wheatley12473e92021-03-18 23:00:55 +11006955 mTimestampVerifier.discontinuity(discontinuityForStandbyOrFlush());
Sampath Shetty999f0e82020-01-15 10:19:06 +11006956 mTimestamp.clear();
Andy Hung398ffa22022-12-13 19:19:53 -08006957 mMonotonicFrameCounter.onFlush();
Eric Laurente659ef42014-09-29 13:06:46 -07006958}
6959
Andy Hungee58e4a2023-07-07 13:47:37 -07006960int64_t DirectOutputThread::computeWaitTimeNs_l() const {
Andy Hung10cbff12017-02-21 17:30:14 -08006961 // If a VolumeShaper is active, we must wake up periodically to update volume.
6962 const int64_t NS_PER_MS = 1000000;
6963 return mVolumeShaperActive ?
6964 kMinNormalSinkBufferSizeMs * NS_PER_MS : PlaybackThread::computeWaitTimeNs_l();
6965}
6966
Eric Laurent81784c32012-11-19 14:55:58 -08006967// ----------------------------------------------------------------------------
6968
Andy Hungee58e4a2023-07-07 13:47:37 -07006969AsyncCallbackThread::AsyncCallbackThread(
6970 const wp<PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006971 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07006972 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07006973 mWriteAckSequence(0),
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006974 mDrainSequence(0),
6975 mAsyncError(false)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006976{
6977}
6978
Andy Hungee58e4a2023-07-07 13:47:37 -07006979void AsyncCallbackThread::onFirstRef()
Eric Laurentbfb1b832013-01-07 09:53:42 -08006980{
6981 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
6982}
6983
Andy Hungee58e4a2023-07-07 13:47:37 -07006984bool AsyncCallbackThread::threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08006985{
6986 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07006987 uint32_t writeAckSequence;
6988 uint32_t drainSequence;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006989 bool asyncError;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006990
6991 {
6992 Mutex::Autolock _l(mLock);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08006993 while (!((mWriteAckSequence & 1) ||
6994 (mDrainSequence & 1) ||
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006995 mAsyncError ||
Haynes Mathew George24a325d2013-12-03 21:26:02 -08006996 exitPending())) {
6997 mWaitWorkCV.wait(mLock);
6998 }
6999
Eric Laurentbfb1b832013-01-07 09:53:42 -08007000 if (exitPending()) {
7001 break;
7002 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07007003 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
7004 mWriteAckSequence, mDrainSequence);
7005 writeAckSequence = mWriteAckSequence;
7006 mWriteAckSequence &= ~1;
7007 drainSequence = mDrainSequence;
7008 mDrainSequence &= ~1;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007009 asyncError = mAsyncError;
7010 mAsyncError = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007011 }
7012 {
Andy Hungee58e4a2023-07-07 13:47:37 -07007013 const sp<PlaybackThread> playbackThread = mPlaybackThread.promote();
Eric Laurent4de95592013-09-26 15:28:21 -07007014 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07007015 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07007016 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007017 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07007018 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07007019 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007020 }
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007021 if (asyncError) {
7022 playbackThread->onAsyncError();
7023 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007024 }
7025 }
7026 }
7027 return false;
7028}
7029
Andy Hungee58e4a2023-07-07 13:47:37 -07007030void AsyncCallbackThread::exit()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007031{
7032 ALOGV("AsyncCallbackThread::exit");
7033 Mutex::Autolock _l(mLock);
7034 requestExit();
7035 mWaitWorkCV.broadcast();
7036}
7037
Andy Hungee58e4a2023-07-07 13:47:37 -07007038void AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08007039{
7040 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07007041 // bit 0 is cleared
7042 mWriteAckSequence = sequence << 1;
7043}
7044
Andy Hungee58e4a2023-07-07 13:47:37 -07007045void AsyncCallbackThread::resetWriteBlocked()
Eric Laurent3b4529e2013-09-05 18:09:19 -07007046{
7047 Mutex::Autolock _l(mLock);
7048 // ignore unexpected callbacks
7049 if (mWriteAckSequence & 2) {
7050 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007051 mWaitWorkCV.signal();
7052 }
7053}
7054
Andy Hungee58e4a2023-07-07 13:47:37 -07007055void AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08007056{
7057 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07007058 // bit 0 is cleared
7059 mDrainSequence = sequence << 1;
7060}
7061
Andy Hungee58e4a2023-07-07 13:47:37 -07007062void AsyncCallbackThread::resetDraining()
Eric Laurent3b4529e2013-09-05 18:09:19 -07007063{
7064 Mutex::Autolock _l(mLock);
7065 // ignore unexpected callbacks
7066 if (mDrainSequence & 2) {
7067 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007068 mWaitWorkCV.signal();
7069 }
7070}
7071
Andy Hungee58e4a2023-07-07 13:47:37 -07007072void AsyncCallbackThread::setAsyncError()
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007073{
7074 Mutex::Autolock _l(mLock);
7075 mAsyncError = true;
7076 mWaitWorkCV.signal();
7077}
7078
Eric Laurentbfb1b832013-01-07 09:53:42 -08007079
7080// ----------------------------------------------------------------------------
Andy Hungee58e4a2023-07-07 13:47:37 -07007081
7082/* static */
7083sp<IAfPlaybackThread> IAfPlaybackThread::createOffloadThread(
Andy Hung583043b2023-07-17 17:05:00 -07007084 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hungee58e4a2023-07-07 13:47:37 -07007085 AudioStreamOut* output, audio_io_handle_t id, bool systemReady,
7086 const audio_offload_info_t& offloadInfo) {
Andy Hung583043b2023-07-17 17:05:00 -07007087 return sp<OffloadThread>::make(afThreadCallback, output, id, systemReady, offloadInfo);
Andy Hungee58e4a2023-07-07 13:47:37 -07007088}
7089
Andy Hung583043b2023-07-17 17:05:00 -07007090OffloadThread::OffloadThread(const sp<IAfThreadCallback>& afThreadCallback,
Gareth Fennb18c1a32022-10-05 13:42:36 -07007091 AudioStreamOut* output, audio_io_handle_t id, bool systemReady,
7092 const audio_offload_info_t& offloadInfo)
Andy Hung583043b2023-07-17 17:05:00 -07007093 : DirectOutputThread(afThreadCallback, output, id, OFFLOAD, systemReady, offloadInfo),
ziyangch8f194f12021-12-01 13:48:04 -08007094 mPausedWriteLength(0), mPausedBytesRemaining(0), mKeepWakeLock(true)
Eric Laurentbfb1b832013-01-07 09:53:42 -08007095{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07007096 //FIXME: mStandby should be set to true by ThreadBase constructo
Eric Laurentfd477972013-10-25 18:10:40 -07007097 mStandby = true;
Eric Laurent64667972016-03-30 18:19:46 -07007098 mKeepWakeLock = property_get_bool("ro.audio.offload_wakelock", true /* default_value */);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007099}
7100
Andy Hungee58e4a2023-07-07 13:47:37 -07007101void OffloadThread::threadLoop_exit()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007102{
7103 if (mFlushPending || mHwPaused) {
7104 // If a flush is pending or track was paused, just discard buffered data
7105 flushHw_l();
7106 } else {
7107 mMixerStatus = MIXER_DRAIN_ALL;
7108 threadLoop_drain();
7109 }
Uday Gupta56604aa2014-05-13 11:19:17 -07007110 if (mUseAsyncWrite) {
7111 ALOG_ASSERT(mCallbackThread != 0);
7112 mCallbackThread->exit();
7113 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007114 PlaybackThread::threadLoop_exit();
7115}
7116
Andy Hungee58e4a2023-07-07 13:47:37 -07007117PlaybackThread::mixer_state OffloadThread::prepareTracks_l(
Andy Hung8d31fd22023-06-26 19:20:57 -07007118 Vector<sp<IAfTrack>>* tracksToRemove
Eric Laurentbfb1b832013-01-07 09:53:42 -08007119)
7120{
Eric Laurentbfb1b832013-01-07 09:53:42 -08007121 size_t count = mActiveTracks.size();
7122
7123 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07007124 bool doHwPause = false;
7125 bool doHwResume = false;
7126
Glenn Kastenc42e9b42016-03-21 11:35:03 -07007127 ALOGV("OffloadThread::prepareTracks_l active tracks %zu", count);
Eric Laurentede6c3b2013-09-19 14:37:46 -07007128
Eric Laurentbfb1b832013-01-07 09:53:42 -08007129 // find out which tracks need to be processed
Andy Hung8d31fd22023-06-26 19:20:57 -07007130 for (const sp<IAfTrack>& t : mActiveTracks) {
7131 IAfTrack* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07007132#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurentbfb1b832013-01-07 09:53:42 -08007133 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07007134#endif
Eric Laurentfd477972013-10-25 18:10:40 -07007135 // Only consider last track started for volume and mixer state control.
7136 // In theory an older track could underrun and restart after the new one starts
7137 // but as we only care about the transition phase between two tracks on a
7138 // direct output, it is not a problem to ignore the underrun case.
Andy Hung8d31fd22023-06-26 19:20:57 -07007139 sp<IAfTrack> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08007140 bool last = l.get() == track;
Eric Laurentfd477972013-10-25 18:10:40 -07007141
Haynes Mathew George7844f672014-01-15 12:32:55 -08007142 if (track->isInvalid()) {
7143 ALOGW("An invalidated track shouldn't be in active list");
7144 tracksToRemove->add(track);
7145 continue;
7146 }
7147
Andy Hung8d31fd22023-06-26 19:20:57 -07007148 if (track->state() == IAfTrackBase::IDLE) {
Haynes Mathew George7844f672014-01-15 12:32:55 -08007149 ALOGW("An idle track shouldn't be in active list");
7150 continue;
7151 }
7152
Kuowei Li23666472021-01-20 10:23:25 +08007153 if (track->isPausePending()) {
7154 track->pauseAck();
7155 // It is possible a track might have been flushed or stopped.
7156 // Other operations such as flush pending might occur on the next prepare.
7157 if (track->isPausing()) {
7158 track->setPaused();
7159 }
7160 // Always perform pause if last, as an immediate flush will change
7161 // the pause state to be no longer isPausing().
Eric Laurentbfb1b832013-01-07 09:53:42 -08007162 if (last) {
Eric Laurent5cff4032015-05-26 13:49:58 -07007163 if (mHwSupportsPause && !mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07007164 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007165 mHwPaused = true;
7166 }
7167 // If we were part way through writing the mixbuffer to
7168 // the HAL we must save this until we resume
7169 // BUG - this will be wrong if a different track is made active,
7170 // in that case we want to discard the pending data in the
7171 // mixbuffer and tell the client to present it again when the
7172 // track is resumed
7173 mPausedWriteLength = mCurrentWriteLength;
7174 mPausedBytesRemaining = mBytesRemaining;
7175 mBytesRemaining = 0; // stop writing
7176 }
7177 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08007178 } else if (track->isFlushPending()) {
Eric Laurente93cc032016-05-05 10:15:10 -07007179 if (track->isStopping_1()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07007180 track->retryCount() = kMaxTrackStopRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07007181 } else {
Andy Hung8d31fd22023-06-26 19:20:57 -07007182 track->retryCount() = kMaxTrackRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07007183 }
Haynes Mathew George7844f672014-01-15 12:32:55 -08007184 track->flushAck();
7185 if (last) {
7186 mFlushPending = true;
7187 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08007188 } else if (track->isResumePending()){
7189 track->resumeAck();
7190 if (last) {
7191 if (mPausedBytesRemaining) {
7192 // Need to continue write that was interrupted
7193 mCurrentWriteLength = mPausedWriteLength;
7194 mBytesRemaining = mPausedBytesRemaining;
7195 mPausedBytesRemaining = 0;
7196 }
7197 if (mHwPaused) {
7198 doHwResume = true;
7199 mHwPaused = false;
7200 // threadLoop_mix() will handle the case that we need to
7201 // resume an interrupted write
7202 }
7203 // enable write to audio HAL
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007204 mSleepTimeUs = 0;
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08007205
Eric Laurent3df841a2016-07-15 15:15:40 -07007206 mLeftVolFloat = mRightVolFloat = -1.0;
7207
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08007208 // Do not handle new data in this iteration even if track->framesReady()
7209 mixerStatus = MIXER_TRACKS_ENABLED;
7210 }
7211 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07007212 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Andy Hungc0691382018-09-12 18:01:57 -07007213 ALOGVV("OffloadThread: track(%d) s=%08x [OK]", track->id(), cblk->mServer);
Andy Hung8d31fd22023-06-26 19:20:57 -07007214 if (track->fillingStatus() == IAfTrack::FS_FILLED) {
7215 track->fillingStatus() = IAfTrack::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07007216 if (last) {
7217 // make sure processVolume_l() will apply new volume even if 0
7218 mLeftVolFloat = mRightVolFloat = -1.0;
7219 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007220 }
7221
7222 if (last) {
Andy Hung8d31fd22023-06-26 19:20:57 -07007223 sp<IAfTrack> previousTrack = mPreviousTrack.promote();
Eric Laurentd7e59222013-11-15 12:02:28 -08007224 if (previousTrack != 0) {
7225 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08007226 // Flush any data still being written from last track
7227 mBytesRemaining = 0;
7228 if (mPausedBytesRemaining) {
7229 // Last track was paused so we also need to flush saved
7230 // mixbuffer state and invalidate track so that it will
7231 // re-submit that unwritten data when it is next resumed
7232 mPausedBytesRemaining = 0;
7233 // Invalidate is a bit drastic - would be more efficient
7234 // to have a flag to tell client that some of the
7235 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08007236 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08007237 }
7238 // flush data already sent to the DSP if changing audio session as audio
7239 // comes from a different source. Also invalidate previous track to force a
7240 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08007241 if (previousTrack->sessionId() != track->sessionId()) {
7242 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08007243 }
7244 }
7245 }
7246 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007247 // reset retry count
Eric Laurente93cc032016-05-05 10:15:10 -07007248 if (track->isStopping_1()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07007249 track->retryCount() = kMaxTrackStopRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07007250 } else {
Andy Hung8d31fd22023-06-26 19:20:57 -07007251 track->retryCount() = kMaxTrackRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07007252 }
Eric Laurent5850c4c2016-11-10 13:04:31 -08007253 mActiveTrack = t;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007254 mixerStatus = MIXER_TRACKS_READY;
7255 }
7256 } else {
Andy Hungc0691382018-09-12 18:01:57 -07007257 ALOGVV("OffloadThread: track(%d) s=%08x [NOT READY]", track->id(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007258 if (track->isStopping_1()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07007259 if (--(track->retryCount()) <= 0) {
Eric Laurente93cc032016-05-05 10:15:10 -07007260 // Hardware buffer can hold a large amount of audio so we must
7261 // wait for all current track's data to drain before we say
7262 // that the track is stopped.
7263 if (mBytesRemaining == 0) {
7264 // Only start draining when all data in mixbuffer
7265 // has been written
7266 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
Andy Hung8d31fd22023-06-26 19:20:57 -07007267 track->setState(IAfTrackBase::STOPPING_2);
7268 // so presentation completes after
Eric Laurente93cc032016-05-05 10:15:10 -07007269 // drain do not drain if no data was ever sent to HAL (mStandby == true)
7270 if (last && !mStandby) {
7271 // do not modify drain sequence if we are already draining. This happens
7272 // when resuming from pause after drain.
7273 if ((mDrainSequence & 1) == 0) {
7274 mSleepTimeUs = 0;
7275 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
7276 mixerStatus = MIXER_DRAIN_TRACK;
7277 mDrainSequence += 2;
7278 }
7279 if (mHwPaused) {
7280 // It is possible to move from PAUSED to STOPPING_1 without
7281 // a resume so we must ensure hardware is running
7282 doHwResume = true;
7283 mHwPaused = false;
7284 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007285 }
7286 }
Eric Laurente93cc032016-05-05 10:15:10 -07007287 } else if (last) {
Andy Hung8d31fd22023-06-26 19:20:57 -07007288 ALOGV("stopping1 underrun retries left %d", track->retryCount());
Eric Laurente93cc032016-05-05 10:15:10 -07007289 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007290 }
7291 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07007292 // Drain has completed or we are in standby, signal presentation complete
7293 if (!(mDrainSequence & 1) || !last || mStandby) {
Andy Hung8d31fd22023-06-26 19:20:57 -07007294 track->setState(IAfTrackBase::STOPPED);
Atneya Nair0cae0432022-05-10 18:12:12 -04007295 mOutput->presentationComplete();
7296 track->presentationComplete(latency_l()); // always returns true
Eric Laurentbfb1b832013-01-07 09:53:42 -08007297 track->reset();
7298 tracksToRemove->add(track);
Dean Wheatley12473e92021-03-18 23:00:55 +11007299 // OFFLOADED stop resets frame counts.
Andy Hungf3234512018-07-03 14:51:47 -07007300 if (!mUseAsyncWrite) {
7301 // If we don't get explicit drain notification we must
7302 // register discontinuity regardless of whether this is
7303 // the previous (!last) or the upcoming (last) track
7304 // to avoid skipping the discontinuity.
Dean Wheatley12473e92021-03-18 23:00:55 +11007305 mTimestampVerifier.discontinuity(
7306 mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Andy Hungf3234512018-07-03 14:51:47 -07007307 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007308 }
7309 } else {
7310 // No buffers for this track. Give it a few chances to
7311 // fill a buffer, then remove it from active list.
Brian Lindahl65e90012022-07-27 18:01:07 +02007312 bool isTimestampAdvancing = mIsTimestampAdvancing.check(mOutput);
Gareth Fennb18c1a32022-10-05 13:42:36 -07007313 if (!isTunerStream() // tuner streams remain active in underrun
Andy Hung8d31fd22023-06-26 19:20:57 -07007314 && --(track->retryCount()) <= 0) {
Brian Lindahl65e90012022-07-27 18:01:07 +02007315 if (isTimestampAdvancing) { // HAL is still playing audio, give us more time.
Andy Hung8d31fd22023-06-26 19:20:57 -07007316 track->retryCount() = kMaxTrackRetriesOffload;
Andy Hungf8044752016-07-27 14:58:11 -07007317 } else {
Andy Hungc0691382018-09-12 18:01:57 -07007318 ALOGV("OffloadThread: BUFFER TIMEOUT: remove track(%d) from active list",
7319 track->id());
Andy Hungf8044752016-07-27 14:58:11 -07007320 tracksToRemove->add(track);
Glenn Kastend3bb6452016-12-05 18:14:37 -08007321 // tell client process that the track was disabled because of underrun;
Andy Hungf8044752016-07-27 14:58:11 -07007322 // it will then automatically call start() when data is available
7323 track->disable();
7324 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007325 } else if (last){
7326 mixerStatus = MIXER_TRACKS_ENABLED;
7327 }
7328 }
7329 }
7330 // compute volume for this track
Wenfeng Sun79458332019-05-29 20:12:43 +08007331 if (track->isReady()) { // check ready to prevent premature start.
7332 processVolume_l(track, last);
7333 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007334 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007335
Eric Laurentea0fade2013-10-04 16:23:48 -07007336 // make sure the pause/flush/resume sequence is executed in the right order.
7337 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
7338 // before flush and then resume HW. This can happen in case of pause/flush/resume
7339 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07007340 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007341 status_t result = mOutput->stream->pause();
7342 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Gareth Fenncd1e1622022-10-05 11:45:45 -07007343 doHwResume = !doHwPause; // resume if pause is due to flush.
Eric Laurent972a1732013-09-04 09:42:59 -07007344 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007345 if (mFlushPending) {
7346 flushHw_l();
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007347 }
Eric Laurentfd477972013-10-25 18:10:40 -07007348 if (!mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007349 status_t result = mOutput->stream->resume();
7350 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07007351 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007352
Eric Laurentbfb1b832013-01-07 09:53:42 -08007353 // remove all the tracks that need to be...
7354 removeTracks_l(*tracksToRemove);
7355
7356 return mixerStatus;
7357}
7358
Eric Laurentbfb1b832013-01-07 09:53:42 -08007359// must be called with thread mutex locked
Andy Hungee58e4a2023-07-07 13:47:37 -07007360bool OffloadThread::waitingAsyncCallback_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007361{
Eric Laurent3b4529e2013-09-05 18:09:19 -07007362 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
7363 mWriteAckSequence, mDrainSequence);
7364 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08007365 return true;
7366 }
7367 return false;
7368}
7369
Andy Hungee58e4a2023-07-07 13:47:37 -07007370bool OffloadThread::waitingAsyncCallback()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007371{
7372 Mutex::Autolock _l(mLock);
7373 return waitingAsyncCallback_l();
7374}
7375
Andy Hungee58e4a2023-07-07 13:47:37 -07007376void OffloadThread::flushHw_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007377{
Eric Laurente659ef42014-09-29 13:06:46 -07007378 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08007379 // Flush anything still waiting in the mixbuffer
7380 mCurrentWriteLength = 0;
7381 mBytesRemaining = 0;
7382 mPausedWriteLength = 0;
7383 mPausedBytesRemaining = 0;
Eric Laurent3eaf66b2016-04-01 14:44:17 -07007384 // reset bytes written count to reflect that DSP buffers are empty after flush.
7385 mBytesWritten = 0;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08007386
Eric Laurentbfb1b832013-01-07 09:53:42 -08007387 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07007388 // discard any pending drain or write ack by incrementing sequence
7389 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
7390 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007391 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07007392 mCallbackThread->setWriteBlocked(mWriteAckSequence);
7393 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007394 }
7395}
7396
Andy Hungee58e4a2023-07-07 13:47:37 -07007397void OffloadThread::invalidateTracks(audio_stream_type_t streamType)
Haynes Mathew George05317d22016-05-03 16:34:26 -07007398{
7399 Mutex::Autolock _l(mLock);
Eric Laurent13084622016-05-17 10:51:49 -07007400 if (PlaybackThread::invalidateTracks_l(streamType)) {
7401 mFlushPending = true;
7402 }
Haynes Mathew George05317d22016-05-03 16:34:26 -07007403}
7404
Andy Hungee58e4a2023-07-07 13:47:37 -07007405void OffloadThread::invalidateTracks(std::set<audio_port_handle_t>& portIds) {
jiabinc44b3462022-12-08 12:52:31 -08007406 Mutex::Autolock _l(mLock);
7407 if (PlaybackThread::invalidateTracks_l(portIds)) {
7408 mFlushPending = true;
7409 }
7410}
7411
Eric Laurentbfb1b832013-01-07 09:53:42 -08007412// ----------------------------------------------------------------------------
7413
Andy Hungee58e4a2023-07-07 13:47:37 -07007414/* static */
7415sp<IAfDuplicatingThread> IAfDuplicatingThread::create(
Andy Hung583043b2023-07-17 17:05:00 -07007416 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hungee58e4a2023-07-07 13:47:37 -07007417 IAfPlaybackThread* mainThread, audio_io_handle_t id, bool systemReady) {
Andy Hung583043b2023-07-17 17:05:00 -07007418 return sp<DuplicatingThread>::make(afThreadCallback, mainThread, id, systemReady);
Andy Hungee58e4a2023-07-07 13:47:37 -07007419}
7420
Andy Hung583043b2023-07-17 17:05:00 -07007421DuplicatingThread::DuplicatingThread(const sp<IAfThreadCallback>& afThreadCallback,
Andy Hung87c693c2023-07-06 20:56:16 -07007422 IAfPlaybackThread* mainThread, audio_io_handle_t id, bool systemReady)
Andy Hung583043b2023-07-17 17:05:00 -07007423 : MixerThread(afThreadCallback, mainThread->getOutput(), id,
Eric Laurent72e3f392015-05-20 14:43:50 -07007424 systemReady, DUPLICATING),
Eric Laurent81784c32012-11-19 14:55:58 -08007425 mWaitTimeMs(UINT_MAX)
7426{
7427 addOutputTrack(mainThread);
7428}
7429
Andy Hungee58e4a2023-07-07 13:47:37 -07007430DuplicatingThread::~DuplicatingThread()
Eric Laurent81784c32012-11-19 14:55:58 -08007431{
7432 for (size_t i = 0; i < mOutputTracks.size(); i++) {
7433 mOutputTracks[i]->destroy();
7434 }
7435}
7436
Andy Hungee58e4a2023-07-07 13:47:37 -07007437void DuplicatingThread::threadLoop_mix()
Eric Laurent81784c32012-11-19 14:55:58 -08007438{
7439 // mix buffers...
Andy Hung920f6572022-10-06 12:09:49 -07007440 if (outputsReady()) {
Glenn Kastend79072e2016-01-06 08:41:20 -08007441 mAudioMixer->process();
Eric Laurent81784c32012-11-19 14:55:58 -08007442 } else {
Eric Laurent02b57082014-11-07 17:28:28 -08007443 if (mMixerBufferValid) {
7444 memset(mMixerBuffer, 0, mMixerBufferSize);
7445 } else {
7446 memset(mSinkBuffer, 0, mSinkBufferSize);
7447 }
Eric Laurent81784c32012-11-19 14:55:58 -08007448 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007449 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007450 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08007451 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007452 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08007453}
7454
Andy Hungee58e4a2023-07-07 13:47:37 -07007455void DuplicatingThread::threadLoop_sleepTime()
Eric Laurent81784c32012-11-19 14:55:58 -08007456{
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007457 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08007458 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007459 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007460 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007461 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007462 }
7463 } else if (mBytesWritten != 0) {
7464 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
7465 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08007466 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08007467 } else {
7468 // flush remaining overflow buffers in output tracks
7469 writeFrames = 0;
7470 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007471 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007472 }
7473}
7474
Andy Hungee58e4a2023-07-07 13:47:37 -07007475ssize_t DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08007476{
7477 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hung1c86ebe2018-05-29 20:29:08 -07007478 const ssize_t actualWritten = outputTracks[i]->write(mSinkBuffer, writeFrames);
7479
7480 // Consider the first OutputTrack for timestamp and frame counting.
7481
7482 // The threadLoop() generally assumes writing a full sink buffer size at a time.
7483 // Here, we correct for writeFrames of 0 (a stop) or underruns because
7484 // we always claim success.
7485 if (i == 0) {
7486 const ssize_t correction = mSinkBufferSize / mFrameSize - actualWritten;
7487 ALOGD_IF(correction != 0 && writeFrames != 0,
7488 "%s: writeFrames:%u actualWritten:%zd correction:%zd mFramesWritten:%lld",
7489 __func__, writeFrames, actualWritten, correction, (long long)mFramesWritten);
7490 mFramesWritten -= correction;
7491 }
7492
7493 // TODO: Report correction for the other output tracks and show in the dump.
Eric Laurent81784c32012-11-19 14:55:58 -08007494 }
Andy Hungcf10d742020-04-28 15:38:24 -07007495 if (mStandby) {
7496 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07007497 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -07007498 mStandby = false;
7499 }
Andy Hung25c2dac2014-02-27 14:56:00 -08007500 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08007501}
7502
Andy Hungee58e4a2023-07-07 13:47:37 -07007503void DuplicatingThread::threadLoop_standby()
Eric Laurent81784c32012-11-19 14:55:58 -08007504{
7505 // DuplicatingThread implements standby by stopping all tracks
7506 for (size_t i = 0; i < outputTracks.size(); i++) {
7507 outputTracks[i]->stop();
7508 }
7509}
7510
Andy Hungee58e4a2023-07-07 13:47:37 -07007511void DuplicatingThread::dumpInternals_l(int fd, const Vector<String16>& args)
Andy Hung1bc088a2018-02-09 15:57:31 -08007512{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07007513 MixerThread::dumpInternals_l(fd, args);
Andy Hung1bc088a2018-02-09 15:57:31 -08007514
7515 std::stringstream ss;
7516 const size_t numTracks = mOutputTracks.size();
7517 ss << " " << numTracks << " OutputTracks";
7518 if (numTracks > 0) {
7519 ss << ":";
7520 for (const auto &track : mOutputTracks) {
Andy Hung87c693c2023-07-06 20:56:16 -07007521 const auto thread = track->thread().promote();
Andy Hungc0691382018-09-12 18:01:57 -07007522 ss << " (" << track->id() << " : ";
Andy Hung1bc088a2018-02-09 15:57:31 -08007523 if (thread.get() != nullptr) {
7524 ss << thread.get() << ", " << thread->id();
7525 } else {
7526 ss << "null";
7527 }
7528 ss << ")";
7529 }
7530 }
7531 ss << "\n";
7532 std::string result = ss.str();
7533 write(fd, result.c_str(), result.size());
7534}
7535
Andy Hungee58e4a2023-07-07 13:47:37 -07007536void DuplicatingThread::saveOutputTracks()
Eric Laurent81784c32012-11-19 14:55:58 -08007537{
7538 outputTracks = mOutputTracks;
7539}
7540
Andy Hungee58e4a2023-07-07 13:47:37 -07007541void DuplicatingThread::clearOutputTracks()
Eric Laurent81784c32012-11-19 14:55:58 -08007542{
7543 outputTracks.clear();
7544}
7545
Andy Hungee58e4a2023-07-07 13:47:37 -07007546void DuplicatingThread::addOutputTrack(IAfPlaybackThread* thread)
Eric Laurent81784c32012-11-19 14:55:58 -08007547{
7548 Mutex::Autolock _l(mLock);
Andy Hungc25b84a2015-01-14 19:04:10 -08007549 // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
7550 // Adjust for thread->sampleRate() to determine minimum buffer frame count.
7551 // Then triple buffer because Threads do not run synchronously and may not be clock locked.
7552 const size_t frameCount =
7553 3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
7554 // TODO: Consider asynchronous sample rate conversion to handle clock disparity
7555 // from different OutputTracks and their associated MixerThreads (e.g. one may
7556 // nearly empty and the other may be dropping data).
7557
Svet Ganov33761132021-05-13 22:51:08 +00007558 // TODO b/182392769: use attribution source util, move to server edge
7559 AttributionSourceState attributionSource = AttributionSourceState();
7560 attributionSource.uid = VALUE_OR_FATAL(legacy2aidl_uid_t_int32_t(
Philip P. Moltmannbda45752020-07-17 16:41:18 -07007561 IPCThreadState::self()->getCallingUid()));
Svet Ganov33761132021-05-13 22:51:08 +00007562 attributionSource.pid = VALUE_OR_FATAL(legacy2aidl_pid_t_int32_t(
Philip P. Moltmannbda45752020-07-17 16:41:18 -07007563 IPCThreadState::self()->getCallingPid()));
Svet Ganov33761132021-05-13 22:51:08 +00007564 attributionSource.token = sp<BBinder>::make();
Andy Hung8d31fd22023-06-26 19:20:57 -07007565 sp<IAfOutputTrack> outputTrack = IAfOutputTrack::create(thread,
Eric Laurent81784c32012-11-19 14:55:58 -08007566 this,
7567 mSampleRate,
Andy Hungc25b84a2015-01-14 19:04:10 -08007568 mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08007569 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08007570 frameCount,
Svet Ganov33761132021-05-13 22:51:08 +00007571 attributionSource);
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07007572 status_t status = outputTrack != 0 ? outputTrack->initCheck() : (status_t) NO_MEMORY;
7573 if (status != NO_ERROR) {
7574 ALOGE("addOutputTrack() initCheck failed %d", status);
7575 return;
Eric Laurent81784c32012-11-19 14:55:58 -08007576 }
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07007577 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
7578 mOutputTracks.add(outputTrack);
7579 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
7580 updateWaitTime_l();
Eric Laurent81784c32012-11-19 14:55:58 -08007581}
7582
Andy Hungee58e4a2023-07-07 13:47:37 -07007583void DuplicatingThread::removeOutputTrack(IAfPlaybackThread* thread)
Eric Laurent81784c32012-11-19 14:55:58 -08007584{
7585 Mutex::Autolock _l(mLock);
7586 for (size_t i = 0; i < mOutputTracks.size(); i++) {
7587 if (mOutputTracks[i]->thread() == thread) {
7588 mOutputTracks[i]->destroy();
7589 mOutputTracks.removeAt(i);
7590 updateWaitTime_l();
Eric Laurentf6870ae2015-05-08 10:50:03 -07007591 if (thread->getOutput() == mOutput) {
7592 mOutput = NULL;
7593 }
Eric Laurent81784c32012-11-19 14:55:58 -08007594 return;
7595 }
7596 }
Eric Laurentf6870ae2015-05-08 10:50:03 -07007597 ALOGV("removeOutputTrack(): unknown thread: %p", thread);
Eric Laurent81784c32012-11-19 14:55:58 -08007598}
7599
7600// caller must hold mLock
Andy Hungee58e4a2023-07-07 13:47:37 -07007601void DuplicatingThread::updateWaitTime_l()
Eric Laurent81784c32012-11-19 14:55:58 -08007602{
7603 mWaitTimeMs = UINT_MAX;
7604 for (size_t i = 0; i < mOutputTracks.size(); i++) {
Andy Hung87c693c2023-07-06 20:56:16 -07007605 const auto strong = mOutputTracks[i]->thread().promote();
Eric Laurent81784c32012-11-19 14:55:58 -08007606 if (strong != 0) {
7607 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
7608 if (waitTimeMs < mWaitTimeMs) {
7609 mWaitTimeMs = waitTimeMs;
7610 }
7611 }
7612 }
7613}
7614
Andy Hungee58e4a2023-07-07 13:47:37 -07007615bool DuplicatingThread::outputsReady()
Eric Laurent81784c32012-11-19 14:55:58 -08007616{
7617 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hung87c693c2023-07-06 20:56:16 -07007618 const auto thread = outputTracks[i]->thread().promote();
Eric Laurent81784c32012-11-19 14:55:58 -08007619 if (thread == 0) {
7620 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
7621 outputTracks[i].get());
7622 return false;
7623 }
Andy Hung87c693c2023-07-06 20:56:16 -07007624 IAfPlaybackThread* const playbackThread = thread->asIAfPlaybackThread().get();
Eric Laurent81784c32012-11-19 14:55:58 -08007625 // see note at standby() declaration
Andy Hung440901d2023-06-29 21:19:25 -07007626 if (playbackThread->inStandby() && !playbackThread->isSuspended()) {
Eric Laurent81784c32012-11-19 14:55:58 -08007627 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
7628 thread.get());
7629 return false;
7630 }
7631 }
7632 return true;
7633}
7634
Andy Hungee58e4a2023-07-07 13:47:37 -07007635void DuplicatingThread::sendMetadataToBackend_l(
Kevin Rocard12381092018-04-11 09:19:59 -07007636 const StreamOutHalInterface::SourceMetadata& metadata)
Kevin Rocard069c2712018-03-29 19:09:14 -07007637{
Kevin Rocard12381092018-04-11 09:19:59 -07007638 for (auto& outputTrack : outputTracks) { // not mOutputTracks
7639 outputTrack->setMetadatas(metadata.tracks);
7640 }
Kevin Rocard069c2712018-03-29 19:09:14 -07007641}
7642
Andy Hungee58e4a2023-07-07 13:47:37 -07007643uint32_t DuplicatingThread::activeSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08007644{
7645 return (mWaitTimeMs * 1000) / 2;
7646}
7647
Andy Hungee58e4a2023-07-07 13:47:37 -07007648void DuplicatingThread::cacheParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08007649{
7650 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
7651 updateWaitTime_l();
7652
7653 MixerThread::cacheParameters_l();
7654}
7655
Eric Laurentb3f315a2021-07-13 15:09:05 +02007656// ----------------------------------------------------------------------------
7657
Andy Hungee58e4a2023-07-07 13:47:37 -07007658/* static */
7659sp<IAfPlaybackThread> IAfPlaybackThread::createSpatializerThread(
Andy Hung583043b2023-07-17 17:05:00 -07007660 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hungee58e4a2023-07-07 13:47:37 -07007661 AudioStreamOut* output,
7662 audio_io_handle_t id,
7663 bool systemReady,
7664 audio_config_base_t* mixerConfig) {
Andy Hung583043b2023-07-17 17:05:00 -07007665 return sp<SpatializerThread>::make(afThreadCallback, output, id, systemReady, mixerConfig);
Andy Hungee58e4a2023-07-07 13:47:37 -07007666}
7667
Andy Hung583043b2023-07-17 17:05:00 -07007668SpatializerThread::SpatializerThread(const sp<IAfThreadCallback>& afThreadCallback,
Eric Laurentb3f315a2021-07-13 15:09:05 +02007669 AudioStreamOut* output,
7670 audio_io_handle_t id,
7671 bool systemReady,
7672 audio_config_base_t *mixerConfig)
Andy Hung583043b2023-07-17 17:05:00 -07007673 : MixerThread(afThreadCallback, output, id, systemReady, SPATIALIZER, mixerConfig)
Eric Laurentb3f315a2021-07-13 15:09:05 +02007674{
7675}
7676
Andy Hungee58e4a2023-07-07 13:47:37 -07007677void SpatializerThread::onFirstRef() {
Eric Laurentb0463942022-12-20 16:31:10 +01007678 MixerThread::onFirstRef();
Andy Hungfeb4e5c2022-10-17 19:10:02 -07007679
Andy Hung41ccf7f2022-12-14 14:25:49 -08007680 const pid_t tid = getTid();
7681 if (tid == -1) {
7682 // Unusual: PlaybackThread::onFirstRef() should set the threadLoop running.
7683 ALOGW("%s: Cannot update Spatializer mixer thread priority, not running", __func__);
7684 } else {
7685 const int priorityBoost = requestSpatializerPriority(getpid(), tid);
7686 if (priorityBoost > 0) {
Andy Hungfeb4e5c2022-10-17 19:10:02 -07007687 stream()->setHalThreadPriority(priorityBoost);
7688 }
7689 }
Eric Laurent68a40a82022-05-03 18:15:04 +02007690}
7691
Andy Hungee58e4a2023-07-07 13:47:37 -07007692void SpatializerThread::setHalLatencyMode_l() {
Eric Laurent68a40a82022-05-03 18:15:04 +02007693 // if mSupportedLatencyModes is empty, the HAL stream does not support
7694 // latency mode control and we can exit.
7695 if (mSupportedLatencyModes.empty()) {
7696 return;
7697 }
7698 audio_latency_mode_t latencyMode = AUDIO_LATENCY_MODE_FREE;
7699 if (mSupportedLatencyModes.size() == 1) {
7700 // If the HAL only support one latency mode currently, confirm the choice
7701 latencyMode = mSupportedLatencyModes[0];
7702 } else if (mSupportedLatencyModes.size() > 1) {
7703 // Request low latency if:
7704 // - The low latency mode is requested by the spatializer controller
7705 // (mRequestedLatencyMode = AUDIO_LATENCY_MODE_LOW)
7706 // AND
7707 // - At least one active track is spatialized
7708 bool hasSpatializedActiveTrack = false;
7709 for (const auto& track : mActiveTracks) {
7710 if (track->isSpatialized()) {
7711 hasSpatializedActiveTrack = true;
7712 break;
7713 }
7714 }
7715 if (hasSpatializedActiveTrack && mRequestedLatencyMode == AUDIO_LATENCY_MODE_LOW) {
7716 latencyMode = AUDIO_LATENCY_MODE_LOW;
7717 }
7718 }
7719
7720 if (latencyMode != mSetLatencyMode) {
7721 status_t status = mOutput->stream->setLatencyMode(latencyMode);
Andy Hung4bd53e72022-11-17 17:21:45 -08007722 ALOGD("%s: thread(%d) setLatencyMode(%s) returned %d",
7723 __func__, mId, toString(latencyMode).c_str(), status);
Eric Laurent68a40a82022-05-03 18:15:04 +02007724 if (status == NO_ERROR) {
7725 mSetLatencyMode = latencyMode;
7726 }
7727 }
7728}
7729
Andy Hungee58e4a2023-07-07 13:47:37 -07007730status_t SpatializerThread::setRequestedLatencyMode(audio_latency_mode_t mode) {
Eric Laurent68a40a82022-05-03 18:15:04 +02007731 if (mode != AUDIO_LATENCY_MODE_LOW && mode != AUDIO_LATENCY_MODE_FREE) {
7732 return BAD_VALUE;
7733 }
7734 Mutex::Autolock _l(mLock);
7735 mRequestedLatencyMode = mode;
7736 return NO_ERROR;
7737}
7738
Andy Hungee58e4a2023-07-07 13:47:37 -07007739void SpatializerThread::checkOutputStageEffects()
Eric Laurentb3f315a2021-07-13 15:09:05 +02007740{
7741 bool hasVirtualizer = false;
7742 bool hasDownMixer = false;
Andy Hung116bc262023-06-20 18:56:17 -07007743 sp<IAfEffectHandle> finalDownMixer;
Eric Laurentb3f315a2021-07-13 15:09:05 +02007744 {
7745 Mutex::Autolock _l(mLock);
Andy Hung116bc262023-06-20 18:56:17 -07007746 sp<IAfEffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_STAGE);
Eric Laurentb3f315a2021-07-13 15:09:05 +02007747 if (chain != 0) {
Eric Laurent1c5e2e32021-08-18 18:50:28 +02007748 hasVirtualizer = chain->getEffectFromType_l(FX_IID_SPATIALIZER) != nullptr;
Eric Laurentb3f315a2021-07-13 15:09:05 +02007749 hasDownMixer = chain->getEffectFromType_l(EFFECT_UIID_DOWNMIX) != nullptr;
7750 }
7751
7752 finalDownMixer = mFinalDownMixer;
7753 mFinalDownMixer.clear();
7754 }
7755
7756 if (hasVirtualizer) {
7757 if (finalDownMixer != nullptr) {
7758 int32_t ret;
Andy Hung116bc262023-06-20 18:56:17 -07007759 finalDownMixer->asIEffect()->disable(&ret);
Eric Laurentb3f315a2021-07-13 15:09:05 +02007760 }
7761 finalDownMixer.clear();
7762 } else if (!hasDownMixer) {
7763 std::vector<effect_descriptor_t> descriptors;
Andy Hung583043b2023-07-17 17:05:00 -07007764 status_t status = mAfThreadCallback->getEffectsFactoryHal()->getDescriptors(
Eric Laurentb3f315a2021-07-13 15:09:05 +02007765 EFFECT_UIID_DOWNMIX, &descriptors);
7766 if (status != NO_ERROR) {
7767 return;
7768 }
7769 ALOG_ASSERT(!descriptors.empty(),
7770 "%s getDescriptors() returned no error but empty list", __func__);
7771
7772 finalDownMixer = createEffect_l(nullptr /*client*/, nullptr /*effectClient*/,
7773 0 /*priority*/, AUDIO_SESSION_OUTPUT_STAGE, &descriptors[0], nullptr /*enabled*/,
Eric Laurentde8caf42021-08-11 17:19:25 +02007774 &status, false /*pinned*/, false /*probe*/, false /*notifyFramesProcessed*/);
Eric Laurentb3f315a2021-07-13 15:09:05 +02007775
7776 if (finalDownMixer == nullptr || (status != NO_ERROR && status != ALREADY_EXISTS)) {
7777 ALOGW("%s error creating downmixer %d", __func__, status);
7778 finalDownMixer.clear();
7779 } else {
7780 int32_t ret;
Andy Hung116bc262023-06-20 18:56:17 -07007781 finalDownMixer->asIEffect()->enable(&ret);
Eric Laurentb3f315a2021-07-13 15:09:05 +02007782 }
7783 }
7784
7785 {
7786 Mutex::Autolock _l(mLock);
7787 mFinalDownMixer = finalDownMixer;
7788 }
7789}
7790
Eric Laurent81784c32012-11-19 14:55:58 -08007791// ----------------------------------------------------------------------------
7792// Record
7793// ----------------------------------------------------------------------------
7794
Andy Hung583043b2023-07-17 17:05:00 -07007795sp<IAfRecordThread> IAfRecordThread::create(const sp<IAfThreadCallback>& afThreadCallback,
Andy Hung87c693c2023-07-06 20:56:16 -07007796 AudioStreamIn* input,
7797 audio_io_handle_t id,
7798 bool systemReady) {
Andy Hung583043b2023-07-17 17:05:00 -07007799 return sp<RecordThread>::make(afThreadCallback, input, id, systemReady);
Andy Hung87c693c2023-07-06 20:56:16 -07007800}
7801
Andy Hung583043b2023-07-17 17:05:00 -07007802RecordThread::RecordThread(const sp<IAfThreadCallback>& afThreadCallback,
Eric Laurent81784c32012-11-19 14:55:58 -08007803 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08007804 audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -07007805 bool systemReady
Glenn Kasten46909e72013-02-26 09:20:22 -08007806 ) :
Andy Hung583043b2023-07-17 17:05:00 -07007807 ThreadBase(afThreadCallback, id, RECORD, systemReady, false /* isOut */),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007808 mInput(input),
Mikhail Naganov2534b382019-09-25 13:05:02 -07007809 mSource(mInput),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007810 mActiveTracks(&this->mLocalLog),
7811 mRsmpInBuffer(NULL),
Glenn Kasten1b291842016-07-18 14:55:21 -07007812 // mRsmpInFrames, mRsmpInFramesP2, and mRsmpInFramesOA are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007813 mRsmpInRear(0)
Glenn Kastenb880f5e2014-05-07 08:43:45 -07007814 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
7815 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007816 // mFastCapture below
7817 , mFastCaptureFutex(0)
7818 // mInputSource
7819 // mPipeSink
7820 // mPipeSource
7821 , mPipeFramesP2(0)
7822 // mPipeMemory
7823 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07007824 , mFastTrackAvail(false)
Eric Laurentd8365c52017-07-16 15:27:05 -07007825 , mBtNrecSuspended(false)
Eric Laurent81784c32012-11-19 14:55:58 -08007826{
Glenn Kastend7dca052015-03-05 16:05:54 -08007827 snprintf(mThreadName, kThreadNameLength, "AudioIn_%X", id);
Andy Hung583043b2023-07-17 17:05:00 -07007828 mNBLogWriter = afThreadCallback->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08007829
George Burgess IVa8f90c12020-05-14 11:27:19 -07007830 if (mInput->audioHwDev != nullptr) {
Andy Hungc8fddf32018-08-08 18:32:37 -07007831 mIsMsdDevice = strcmp(
7832 mInput->audioHwDev->moduleName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0;
7833 }
7834
Glenn Kastendeca2ae2014-02-07 10:25:56 -08007835 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007836
Andy Hungc8fddf32018-08-08 18:32:37 -07007837 // TODO: We may also match on address as well as device type for
7838 // AUDIO_DEVICE_IN_BUS, AUDIO_DEVICE_IN_BLUETOOTH_A2DP, AUDIO_DEVICE_IN_REMOTE_SUBMIX
jiabinc52b1ff2019-10-31 17:20:42 -07007839 // TODO: This property should be ensure that only contains one single device type.
7840 mTimestampCorrectedDevice = (audio_devices_t)property_get_int64(
7841 "audio.timestamp.corrected_input_device",
Andy Hungc8fddf32018-08-08 18:32:37 -07007842 (int64_t)(mIsMsdDevice ? AUDIO_DEVICE_IN_BUS // turn on by default for MSD
7843 : AUDIO_DEVICE_NONE));
7844
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007845 // create an NBAIO source for the HAL input stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07007846 mInputSource = new AudioStreamInSource(input->stream);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007847 size_t numCounterOffers = 0;
7848 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07007849#if !LOG_NDEBUG
Jing Mike537412f2023-03-12 11:01:47 +08007850 [[maybe_unused]] ssize_t index =
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07007851#else
7852 (void)
7853#endif
7854 mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007855 ALOG_ASSERT(index == 0);
7856
7857 // initialize fast capture depending on configuration
7858 bool initFastCapture;
7859 switch (kUseFastCapture) {
7860 case FastCapture_Never:
7861 initFastCapture = false;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007862 ALOGV("%p kUseFastCapture = Never, initFastCapture = false", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007863 break;
7864 case FastCapture_Always:
7865 initFastCapture = true;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007866 ALOGV("%p kUseFastCapture = Always, initFastCapture = true", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007867 break;
7868 case FastCapture_Static:
Sampath6fac2332022-12-16 17:34:37 +11007869 initFastCapture = !mIsMsdDevice // Disable fast capture for MSD BUS devices.
7870 && (mFrameCount * 1000) / mSampleRate < kMinNormalCaptureBufferSizeMs;
7871 ALOGV("%p kUseFastCapture = Static, (%lld * 1000) / %u vs %u, initFastCapture = %d "
7872 "mIsMsdDevice = %d", this, (long long)mFrameCount, mSampleRate,
7873 kMinNormalCaptureBufferSizeMs, initFastCapture, mIsMsdDevice);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007874 break;
7875 // case FastCapture_Dynamic:
7876 }
7877
7878 if (initFastCapture) {
Glenn Kastend198b852015-03-16 14:55:53 -07007879 // create a Pipe for FastCapture to write to, and for us and fast tracks to read from
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007880 NBAIO_Format format = mInputSource->format();
Glenn Kasten1b291842016-07-18 14:55:21 -07007881 // quadruple-buffering of 20 ms each; this ensures we can sleep for 20ms in RecordThread
7882 size_t pipeFramesP2 = roundup(4 * FMS_20 * mSampleRate / 1000);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007883 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007884 void *pipeBuffer = nullptr;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007885 const sp<MemoryDealer> roHeap(readOnlyHeap());
7886 sp<IMemory> pipeMemory;
7887 if ((roHeap == 0) ||
7888 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07007889 (pipeBuffer = pipeMemory->unsecurePointer()) == nullptr) {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007890 ALOGE("not enough memory for pipe buffer size=%zu; "
7891 "roHeap=%p, pipeMemory=%p, pipeBuffer=%p; roHeapSize: %lld",
7892 pipeSize, roHeap.get(), pipeMemory.get(), pipeBuffer,
7893 (long long)kRecordThreadReadOnlyHeapSize);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007894 goto failed;
7895 }
7896 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
7897 memset(pipeBuffer, 0, pipeSize);
7898 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
Andy Hung920f6572022-10-06 12:09:49 -07007899 const NBAIO_Format offersFast[1] = {format};
7900 size_t numCounterOffersFast = 0;
Eric Laurent1e28aaa2023-04-16 19:34:23 +02007901 [[maybe_unused]] ssize_t index2 = pipe->negotiate(offersFast, std::size(offersFast),
Andy Hung920f6572022-10-06 12:09:49 -07007902 nullptr /* counterOffers */, numCounterOffersFast);
Eric Laurent1e28aaa2023-04-16 19:34:23 +02007903 ALOG_ASSERT(index2 == 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007904 mPipeSink = pipe;
7905 PipeReader *pipeReader = new PipeReader(*pipe);
Andy Hung920f6572022-10-06 12:09:49 -07007906 numCounterOffersFast = 0;
Eric Laurent1e28aaa2023-04-16 19:34:23 +02007907 index2 = pipeReader->negotiate(offersFast, std::size(offersFast),
Andy Hung920f6572022-10-06 12:09:49 -07007908 nullptr /* counterOffers */, numCounterOffersFast);
Eric Laurent1e28aaa2023-04-16 19:34:23 +02007909 ALOG_ASSERT(index2 == 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007910 mPipeSource = pipeReader;
7911 mPipeFramesP2 = pipeFramesP2;
7912 mPipeMemory = pipeMemory;
7913
7914 // create fast capture
7915 mFastCapture = new FastCapture();
7916 FastCaptureStateQueue *sq = mFastCapture->sq();
7917#ifdef STATE_QUEUE_DUMP
7918 // FIXME
7919#endif
7920 FastCaptureState *state = sq->begin();
7921 state->mCblk = NULL;
7922 state->mInputSource = mInputSource.get();
7923 state->mInputSourceGen++;
7924 state->mPipeSink = pipe;
7925 state->mPipeSinkGen++;
7926 state->mFrameCount = mFrameCount;
7927 state->mCommand = FastCaptureState::COLD_IDLE;
7928 // already done in constructor initialization list
7929 //mFastCaptureFutex = 0;
7930 state->mColdFutexAddr = &mFastCaptureFutex;
7931 state->mColdGen++;
7932 state->mDumpState = &mFastCaptureDumpState;
7933#ifdef TEE_SINK
7934 // FIXME
7935#endif
Andy Hung583043b2023-07-17 17:05:00 -07007936 mFastCaptureNBLogWriter =
7937 afThreadCallback->newWriter_l(kFastCaptureLogSize, "FastCapture");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007938 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
7939 sq->end();
7940 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
7941
7942 // start the fast capture
7943 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
7944 pid_t tid = mFastCapture->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07007945 sendPrioConfigEvent(getpid(), tid, kPriorityFastCapture, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08007946 stream()->setHalThreadPriority(kPriorityFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007947#ifdef AUDIO_WATCHDOG
7948 // FIXME
7949#endif
7950
Glenn Kasten6e6704c2014-07-03 10:20:00 -07007951 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007952 }
Andy Hung8946a282018-04-19 20:04:56 -07007953#ifdef TEE_SINK
7954 mTee.set(mInputSource->format(), NBAIO_Tee::TEE_FLAG_INPUT_THREAD);
7955 mTee.setId(std::string("_") + std::to_string(mId) + "_C");
7956#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007957failed: ;
7958
7959 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08007960}
7961
Andy Hungee58e4a2023-07-07 13:47:37 -07007962RecordThread::~RecordThread()
Eric Laurent81784c32012-11-19 14:55:58 -08007963{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007964 if (mFastCapture != 0) {
7965 FastCaptureStateQueue *sq = mFastCapture->sq();
7966 FastCaptureState *state = sq->begin();
7967 if (state->mCommand == FastCaptureState::COLD_IDLE) {
7968 int32_t old = android_atomic_inc(&mFastCaptureFutex);
7969 if (old == -1) {
7970 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
7971 }
7972 }
7973 state->mCommand = FastCaptureState::EXIT;
7974 sq->end();
7975 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
7976 mFastCapture->join();
7977 mFastCapture.clear();
7978 }
Andy Hung583043b2023-07-17 17:05:00 -07007979 mAfThreadCallback->unregisterWriter(mFastCaptureNBLogWriter);
7980 mAfThreadCallback->unregisterWriter(mNBLogWriter);
Andy Hung57446612015-04-19 23:56:46 -07007981 free(mRsmpInBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08007982}
7983
Andy Hungee58e4a2023-07-07 13:47:37 -07007984void RecordThread::onFirstRef()
Eric Laurent81784c32012-11-19 14:55:58 -08007985{
Glenn Kastend7dca052015-03-05 16:05:54 -08007986 run(mThreadName, PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08007987}
7988
Andy Hungee58e4a2023-07-07 13:47:37 -07007989void RecordThread::preExit()
Eric Laurent555530a2017-02-07 18:17:24 -08007990{
7991 ALOGV(" preExit()");
7992 Mutex::Autolock _l(mLock);
7993 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07007994 sp<IAfRecordTrack> track = mTracks[i];
Eric Laurent555530a2017-02-07 18:17:24 -08007995 track->invalidate();
7996 }
7997 mActiveTracks.clear();
7998 mStartStopCond.broadcast();
7999}
8000
Andy Hungee58e4a2023-07-07 13:47:37 -07008001bool RecordThread::threadLoop()
Eric Laurent81784c32012-11-19 14:55:58 -08008002{
Eric Laurent81784c32012-11-19 14:55:58 -08008003 nsecs_t lastWarning = 0;
8004
8005 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08008006
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008007reacquire_wakelock:
Andy Hung8d31fd22023-06-26 19:20:57 -07008008 sp<IAfRecordTrack> activeTrack;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008009 {
8010 Mutex::Autolock _l(mLock);
Andy Hungdae27702016-10-31 14:01:16 -07008011 acquireWakeLock_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008012 }
8013
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008014 // used to request a deferred sleep, to be executed later while mutex is unlocked
8015 uint32_t sleepUs = 0;
8016
Andy Hung446f4df2019-02-21 12:26:41 -08008017 int64_t lastLoopCountRead = -2; // never matches "previous" loop, when loopCount = 0.
8018
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008019 // loop while there is work to do
Andy Hung446f4df2019-02-21 12:26:41 -08008020 for (int64_t loopCount = 0;; ++loopCount) { // loopCount used for statistics tracking
Andy Hung116bc262023-06-20 18:56:17 -07008021 Vector<sp<IAfEffectChain>> effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07008022
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008023 // activeTracks accumulates a copy of a subset of mActiveTracks
Andy Hung8d31fd22023-06-26 19:20:57 -07008024 Vector<sp<IAfRecordTrack>> activeTracks;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008025
Glenn Kasten735f45f2014-08-18 15:51:59 -07008026 // reference to the (first and only) active fast track
Andy Hung8d31fd22023-06-26 19:20:57 -07008027 sp<IAfRecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07008028
Glenn Kasten735f45f2014-08-18 15:51:59 -07008029 // reference to a fast track which is about to be removed
Andy Hung8d31fd22023-06-26 19:20:57 -07008030 sp<IAfRecordTrack> fastTrackToRemove;
Glenn Kasten735f45f2014-08-18 15:51:59 -07008031
Eric Laurent33403f02020-05-29 18:35:06 -07008032 bool silenceFastCapture = false;
8033
Eric Laurent81784c32012-11-19 14:55:58 -08008034 { // scope for mLock
8035 Mutex::Autolock _l(mLock);
Eric Laurent000a4192014-01-29 15:17:32 -08008036
Eric Laurent021cf962014-05-13 10:18:14 -07008037 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008038
Eric Laurent000a4192014-01-29 15:17:32 -08008039 // check exitPending here because checkForNewParameters_l() and
8040 // checkForNewParameters_l() can temporarily release mLock
8041 if (exitPending()) {
8042 break;
8043 }
8044
Eric Laurent5c25d562016-07-13 17:17:45 -07008045 // sleep with mutex unlocked
8046 if (sleepUs > 0) {
Glenn Kastenf9715e42016-07-13 14:02:03 -07008047 ATRACE_BEGIN("sleepC");
Eric Laurent5c25d562016-07-13 17:17:45 -07008048 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)sleepUs));
8049 ATRACE_END();
8050 sleepUs = 0;
8051 continue;
8052 }
8053
Glenn Kasten2b806402013-11-20 16:37:38 -08008054 // if no active track(s), then standby and release wakelock
8055 size_t size = mActiveTracks.size();
8056 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07008057 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07008058 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08008059 releaseWakeLock_l();
8060 ALOGV("RecordThread: loop stopping");
8061 // go to sleep
8062 mWaitWorkCV.wait(mLock);
8063 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008064 goto reacquire_wakelock;
8065 }
8066
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008067 bool doBroadcast = false;
Eric Laurent5c25d562016-07-13 17:17:45 -07008068 bool allStopped = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008069 for (size_t i = 0; i < size; ) {
Glenn Kasten9e982352013-08-14 14:39:50 -07008070
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008071 activeTrack = mActiveTracks[i];
8072 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07008073 if (activeTrack->isFastTrack()) {
8074 ALOG_ASSERT(fastTrackToRemove == 0);
8075 fastTrackToRemove = activeTrack;
8076 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008077 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08008078 mActiveTracks.remove(activeTrack);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008079 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07008080 continue;
8081 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008082
Andy Hung8d31fd22023-06-26 19:20:57 -07008083 IAfTrackBase::track_state activeTrackState = activeTrack->state();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008084 switch (activeTrackState) {
8085
Andy Hung8d31fd22023-06-26 19:20:57 -07008086 case IAfTrackBase::PAUSING:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008087 mActiveTracks.remove(activeTrack);
Andy Hung8d31fd22023-06-26 19:20:57 -07008088 activeTrack->setState(IAfTrackBase::PAUSED);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008089 doBroadcast = true;
8090 size--;
8091 continue;
8092
Andy Hung8d31fd22023-06-26 19:20:57 -07008093 case IAfTrackBase::STARTING_1:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008094 sleepUs = 10000;
8095 i++;
Eric Laurent5c25d562016-07-13 17:17:45 -07008096 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008097 continue;
8098
Andy Hung8d31fd22023-06-26 19:20:57 -07008099 case IAfTrackBase::STARTING_2:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008100 doBroadcast = true;
Andy Hungcf10d742020-04-28 15:38:24 -07008101 if (mStandby) {
8102 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07008103 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -07008104 mStandby = false;
8105 }
Andy Hung8d31fd22023-06-26 19:20:57 -07008106 activeTrack->setState(IAfTrackBase::ACTIVE);
Eric Laurent5c25d562016-07-13 17:17:45 -07008107 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008108 break;
8109
Andy Hung8d31fd22023-06-26 19:20:57 -07008110 case IAfTrackBase::ACTIVE:
Eric Laurent5c25d562016-07-13 17:17:45 -07008111 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008112 break;
8113
Andy Hung8d31fd22023-06-26 19:20:57 -07008114 case IAfTrackBase::IDLE: // cannot be on ActiveTracks if idle
8115 case IAfTrackBase::PAUSED: // cannot be on ActiveTracks if paused
8116 case IAfTrackBase::STOPPED: // cannot be on ActiveTracks if destroyed/terminated
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008117 default:
Andy Hungce685402018-10-05 17:23:27 -07008118 LOG_ALWAYS_FATAL("%s: Unexpected active track state:%d, id:%d, tracks:%zu",
8119 __func__, activeTrackState, activeTrack->id(), size);
Glenn Kasten9e982352013-08-14 14:39:50 -07008120 }
Glenn Kasten9e982352013-08-14 14:39:50 -07008121
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008122 if (activeTrack->isFastTrack()) {
8123 ALOG_ASSERT(!mFastTrackAvail);
8124 ALOG_ASSERT(fastTrack == 0);
Eric Laurent33403f02020-05-29 18:35:06 -07008125 // if the active fast track is silenced either:
8126 // 1) silence the whole capture from fast capture buffer if this is
8127 // the only active track
8128 // 2) invalidate this track: this will cause the client to reconnect and possibly
8129 // be invalidated again until unsilenced
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008130 bool invalidate = false;
Eric Laurent33403f02020-05-29 18:35:06 -07008131 if (activeTrack->isSilenced()) {
8132 if (size > 1) {
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008133 invalidate = true;
Eric Laurent33403f02020-05-29 18:35:06 -07008134 } else {
8135 silenceFastCapture = true;
8136 }
8137 }
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008138 // Invalidate fast tracks if access to audio history is required as this is not
8139 // possible with fast tracks. Once the fast track has been invalidated, no new
8140 // fast track will be created until mMaxSharedAudioHistoryMs is cleared.
8141 if (mMaxSharedAudioHistoryMs != 0) {
8142 invalidate = true;
8143 }
8144 if (invalidate) {
8145 activeTrack->invalidate();
8146 ALOG_ASSERT(fastTrackToRemove == 0);
8147 fastTrackToRemove = activeTrack;
8148 removeTrack_l(activeTrack);
8149 mActiveTracks.remove(activeTrack);
8150 size--;
8151 continue;
8152 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008153 fastTrack = activeTrack;
8154 }
Eric Laurent33403f02020-05-29 18:35:06 -07008155
8156 activeTracks.add(activeTrack);
8157 i++;
8158
Glenn Kasten9e982352013-08-14 14:39:50 -07008159 }
Eric Laurent5c25d562016-07-13 17:17:45 -07008160
Andy Hungdae27702016-10-31 14:01:16 -07008161 mActiveTracks.updatePowerState(this);
8162
Kevin Rocard069c2712018-03-29 19:09:14 -07008163 updateMetadata_l();
8164
Eric Laurent5c25d562016-07-13 17:17:45 -07008165 if (allStopped) {
8166 standbyIfNotAlreadyInStandby();
8167 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008168 if (doBroadcast) {
8169 mStartStopCond.broadcast();
8170 }
8171
8172 // sleep if there are no active tracks to process
Eric Tan39ec8d62018-07-24 09:49:29 -07008173 if (activeTracks.isEmpty()) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008174 if (sleepUs == 0) {
8175 sleepUs = kRecordThreadSleepUs;
8176 }
8177 continue;
8178 }
8179 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07008180
Eric Laurent81784c32012-11-19 14:55:58 -08008181 lockEffectChains_l(effectChains);
8182 }
8183
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008184 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07008185
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008186 size_t size = effectChains.size();
8187 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008188 // thread mutex is not locked, but effect chain is locked
8189 effectChains[i]->process_l();
8190 }
8191
Glenn Kasten735f45f2014-08-18 15:51:59 -07008192 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008193 if (mFastCapture != 0) {
8194 FastCaptureStateQueue *sq = mFastCapture->sq();
8195 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07008196 bool didModify = false;
8197 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008198 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
8199 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
8200 if (state->mCommand == FastCaptureState::COLD_IDLE) {
8201 int32_t old = android_atomic_inc(&mFastCaptureFutex);
8202 if (old == -1) {
8203 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
8204 }
8205 }
8206 state->mCommand = FastCaptureState::READ_WRITE;
8207#if 0 // FIXME
Andy Hung583043b2023-07-17 17:05:00 -07008208 mFastCaptureDumpState.increaseSamplingN(mAfThreadCallback->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08008209 FastThreadDumpState::kSamplingNforLowRamDevice :
8210 FastThreadDumpState::kSamplingN);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008211#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07008212 didModify = true;
8213 }
8214 audio_track_cblk_t *cblkOld = state->mCblk;
8215 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
8216 if (cblkNew != cblkOld) {
8217 state->mCblk = cblkNew;
8218 // block until acked if removing a fast track
8219 if (cblkOld != NULL) {
8220 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
8221 }
8222 didModify = true;
8223 }
jiabin01c8f562018-07-19 17:47:28 -07008224 AudioBufferProvider* abp = (fastTrack != 0 && fastTrack->isPatchTrack()) ?
8225 reinterpret_cast<AudioBufferProvider*>(fastTrack.get()) : nullptr;
8226 if (state->mFastPatchRecordBufferProvider != abp) {
8227 state->mFastPatchRecordBufferProvider = abp;
8228 state->mFastPatchRecordFormat = fastTrack == 0 ?
8229 AUDIO_FORMAT_INVALID : fastTrack->format();
8230 didModify = true;
8231 }
Eric Laurent33403f02020-05-29 18:35:06 -07008232 if (state->mSilenceCapture != silenceFastCapture) {
8233 state->mSilenceCapture = silenceFastCapture;
8234 didModify = true;
8235 }
Glenn Kasten735f45f2014-08-18 15:51:59 -07008236 sq->end(didModify);
8237 if (didModify) {
8238 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008239#if 0
8240 if (kUseFastCapture == FastCapture_Dynamic) {
8241 mNormalSource = mPipeSource;
8242 }
8243#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008244 }
8245 }
8246
Glenn Kasten735f45f2014-08-18 15:51:59 -07008247 // now run the fast track destructor with thread mutex unlocked
8248 fastTrackToRemove.clear();
8249
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008250 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
8251 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
8252 // slow, then this RecordThread will overrun by not calling HAL read often enough.
8253 // If destination is non-contiguous, first read past the nominal end of buffer, then
8254 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008255
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008256 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Andy Hung920f6572022-10-06 12:09:49 -07008257 ssize_t framesRead = 0; // not needed, remove clang-tidy warning.
Andy Hung446f4df2019-02-21 12:26:41 -08008258 const int64_t lastIoBeginNs = systemTime(); // start IO timing
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008259
8260 // If an NBAIO source is present, use it to read the normal capture's data
8261 if (mPipeSource != 0) {
Andy Hung156317a2018-08-02 11:49:29 -07008262 size_t framesToRead = min(mRsmpInFramesOA - rear, mRsmpInFramesP2 / 2);
Andy Hungd5b638f2018-04-30 13:56:10 -07008263
8264 // The audio fifo read() returns OVERRUN on overflow, and advances the read pointer
8265 // to the full buffer point (clearing the overflow condition). Upon OVERRUN error,
8266 // we immediately retry the read() to get data and prevent another overflow.
8267 for (int retries = 0; retries <= 2; ++retries) {
8268 ALOGW_IF(retries > 0, "overrun on read from pipe, retry #%d", retries);
8269 framesRead = mPipeSource->read((uint8_t*)mRsmpInBuffer + rear * mFrameSize,
8270 framesToRead);
8271 if (framesRead != OVERRUN) break;
8272 }
8273
Andy Hung7a3dc6b2018-05-01 16:39:51 -07008274 const ssize_t availableToRead = mPipeSource->availableToRead();
8275 if (availableToRead >= 0) {
Robert Wu06db0a32021-08-10 19:05:34 +00008276 mMonopipePipeDepthStats.add(availableToRead);
Glenn Kastena2f59b32020-08-03 16:37:24 -07008277 // PipeSource is the primary clock. It is up to the AudioRecord client to keep up.
Andy Hung7a3dc6b2018-05-01 16:39:51 -07008278 LOG_ALWAYS_FATAL_IF((size_t)availableToRead > mPipeFramesP2,
8279 "more frames to read than fifo size, %zd > %zu",
8280 availableToRead, mPipeFramesP2);
8281 const size_t pipeFramesFree = mPipeFramesP2 - availableToRead;
8282 const size_t sleepFrames = min(pipeFramesFree, mRsmpInFramesP2) / 2;
8283 ALOGVV("mPipeFramesP2:%zu mRsmpInFramesP2:%zu sleepFrames:%zu availableToRead:%zd",
8284 mPipeFramesP2, mRsmpInFramesP2, sleepFrames, availableToRead);
Glenn Kasten1b291842016-07-18 14:55:21 -07008285 sleepUs = (sleepFrames * 1000000LL) / mSampleRate;
8286 }
8287 if (framesRead < 0) {
8288 status_t status = (status_t) framesRead;
8289 switch (status) {
8290 case OVERRUN:
8291 ALOGW("overrun on read from pipe");
8292 framesRead = 0;
8293 break;
8294 case NEGOTIATE:
8295 ALOGE("re-negotiation is needed");
8296 framesRead = -1; // Will cause an attempt to recover.
8297 break;
8298 default:
8299 ALOGE("unknown error %d on read from pipe", status);
8300 break;
8301 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008302 }
8303 // otherwise use the HAL / AudioStreamIn directly
8304 } else {
Glenn Kastenec6a7032016-03-14 07:40:23 -07008305 ATRACE_BEGIN("read");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008306 size_t bytesRead;
Mikhail Naganov2534b382019-09-25 13:05:02 -07008307 status_t result = mSource->read(
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008308 (uint8_t*)mRsmpInBuffer + rear * mFrameSize, mBufferSize, &bytesRead);
Glenn Kastenec6a7032016-03-14 07:40:23 -07008309 ATRACE_END();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008310 if (result < 0) {
8311 framesRead = result;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008312 } else {
8313 framesRead = bytesRead / mFrameSize;
8314 }
8315 }
8316
Andy Hung446f4df2019-02-21 12:26:41 -08008317 const int64_t lastIoEndNs = systemTime(); // end IO timing
8318
Andy Hung3f0c9022016-01-15 17:49:46 -08008319 // Update server timestamp with server stats
8320 // systemTime() is optional if the hardware supports timestamps.
Andy Hung743f6402020-06-03 13:17:04 -07008321 if (framesRead >= 0) {
8322 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += framesRead;
8323 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = lastIoEndNs;
8324 }
Andy Hung3f0c9022016-01-15 17:49:46 -08008325
8326 // Update server timestamp with kernel stats
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008327 if (mPipeSource.get() == nullptr /* don't obtain for FastCapture, could block */) {
Andy Hung3f0c9022016-01-15 17:49:46 -08008328 int64_t position, time;
Andy Hung2e2c0bb2018-06-11 19:13:11 -07008329 if (mStandby) {
Dean Wheatley12473e92021-03-18 23:00:55 +11008330 mTimestampVerifier.discontinuity(audio_is_linear_pcm(mFormat) ?
8331 mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS :
8332 mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Mikhail Naganov2534b382019-09-25 13:05:02 -07008333 } else if (mSource->getCapturePosition(&position, &time) == NO_ERROR
Andy Hungc8fddf32018-08-08 18:32:37 -07008334 && time > mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]) {
8335
8336 mTimestampVerifier.add(position, time, mSampleRate);
8337
8338 // Correct timestamps
8339 if (isTimestampCorrectionEnabled()) {
Dean Wheatley56a583e2020-05-08 15:12:17 +10008340 ALOGVV("TS_BEFORE: %d %lld %lld",
Andy Hungc8fddf32018-08-08 18:32:37 -07008341 id(), (long long)time, (long long)position);
8342 auto correctedTimestamp = mTimestampVerifier.getLastCorrectedTimestamp();
8343 position = correctedTimestamp.mFrames;
8344 time = correctedTimestamp.mTimeNs;
Dean Wheatley56a583e2020-05-08 15:12:17 +10008345 ALOGVV("TS_AFTER: %d %lld %lld",
Andy Hungc8fddf32018-08-08 18:32:37 -07008346 id(), (long long)time, (long long)position);
8347 }
8348
Andy Hung3f0c9022016-01-15 17:49:46 -08008349 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = position;
8350 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] = time;
8351 // Note: In general record buffers should tend to be empty in
8352 // a properly running pipeline.
8353 //
8354 // Also, it is not advantageous to call get_presentation_position during the read
8355 // as the read obtains a lock, preventing the timestamp call from executing.
Andy Hung2e2c0bb2018-06-11 19:13:11 -07008356 } else {
8357 mTimestampVerifier.error();
Andy Hung3f0c9022016-01-15 17:49:46 -08008358 }
8359 }
Andy Hunge6c37112019-02-26 17:38:10 -08008360
8361 // From the timestamp, input read latency is negative output write latency.
8362 const audio_input_flags_t flags = mInput != NULL ? mInput->flags : AUDIO_INPUT_FLAG_NONE;
Andy Hung8d31fd22023-06-26 19:20:57 -07008363 const double latencyMs = IAfRecordTrack::checkServerLatencySupported(mFormat, flags)
Andy Hunge6c37112019-02-26 17:38:10 -08008364 ? - mTimestamp.getOutputServerLatencyMs(mSampleRate) : 0.;
8365 if (latencyMs != 0.) { // note 0. means timestamp is empty.
8366 mLatencyMs.add(latencyMs);
8367 }
8368
Andy Hung3f0c9022016-01-15 17:49:46 -08008369 // Use this to track timestamp information
8370 // ALOGD("%s", mTimestamp.toString().c_str());
8371
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008372 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07008373 ALOGE("read failed: framesRead=%zd", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008374 // Force input into standby so that it tries to recover at next read attempt
8375 inputStandBy();
8376 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008377 }
8378 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008379 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008380 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008381 ALOG_ASSERT(framesRead > 0);
Andy Hung6427e442018-08-09 12:51:02 -07008382 mFramesRead += framesRead;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008383
Andy Hung8946a282018-04-19 20:04:56 -07008384#ifdef TEE_SINK
8385 (void)mTee.write((uint8_t*)mRsmpInBuffer + rear * mFrameSize, framesRead);
8386#endif
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008387 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008388 {
8389 size_t part1 = mRsmpInFramesP2 - rear;
8390 if ((size_t) framesRead > part1) {
Andy Hung57446612015-04-19 23:56:46 -07008391 memcpy(mRsmpInBuffer, (uint8_t*)mRsmpInBuffer + mRsmpInFramesP2 * mFrameSize,
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008392 (framesRead - part1) * mFrameSize);
8393 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008394 }
Dean Wheatleyfd56e812020-11-06 22:32:21 +11008395 mRsmpInRear = audio_utils::safe_add_overflow(mRsmpInRear, (int32_t)framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008396
8397 size = activeTracks.size();
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008398
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008399 // loop over each active track
8400 for (size_t i = 0; i < size; i++) {
8401 activeTrack = activeTracks[i];
8402
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008403 // skip fast tracks, as those are handled directly by FastCapture
8404 if (activeTrack->isFastTrack()) {
8405 continue;
8406 }
8407
Andy Hung73c02e42015-03-29 01:13:58 -07008408 // TODO: This code probably should be moved to RecordTrack.
Andy Hung97a893e2015-03-29 01:03:07 -07008409 // TODO: Update the activeTrack buffer converter in case of reconfigure.
8410
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008411 enum {
8412 OVERRUN_UNKNOWN,
8413 OVERRUN_TRUE,
8414 OVERRUN_FALSE
8415 } overrun = OVERRUN_UNKNOWN;
8416
8417 // loop over getNextBuffer to handle circular sink
8418 for (;;) {
8419
Andy Hung8d31fd22023-06-26 19:20:57 -07008420 activeTrack->sinkBuffer().frameCount = ~0;
8421 status_t status = activeTrack->getNextBuffer(&activeTrack->sinkBuffer());
8422 size_t framesOut = activeTrack->sinkBuffer().frameCount;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008423 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
8424
Andy Hung73c02e42015-03-29 01:13:58 -07008425 // check available frames and handle overrun conditions
8426 // if the record track isn't draining fast enough.
8427 bool hasOverrun;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008428 size_t framesIn;
Andy Hung8d31fd22023-06-26 19:20:57 -07008429 activeTrack->resamplerBufferProvider()->sync(&framesIn, &hasOverrun);
Andy Hung73c02e42015-03-29 01:13:58 -07008430 if (hasOverrun) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008431 overrun = OVERRUN_TRUE;
8432 }
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08008433 if (framesOut == 0 || framesIn == 0) {
8434 break;
8435 }
8436
Andy Hung6770c6f2015-04-07 13:43:36 -07008437 // Don't allow framesOut to be larger than what is possible with resampling
8438 // from framesIn.
8439 // This isn't strictly necessary but helps limit buffer resizing in
8440 // RecordBufferConverter. TODO: remove when no longer needed.
8441 framesOut = min(framesOut,
8442 destinationFramesPossible(
Andy Hung8d31fd22023-06-26 19:20:57 -07008443 framesIn, mSampleRate, activeTrack->sampleRate()));
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008444
8445 if (activeTrack->isDirect()) {
Daniel Van Veen9e2376e2018-09-27 14:37:58 +10008446 // No RecordBufferConverter used for direct streams. Pass
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008447 // straight from RecordThread buffer to RecordTrack buffer.
8448 AudioBufferProvider::Buffer buffer;
8449 buffer.frameCount = framesOut;
Andy Hung920f6572022-10-06 12:09:49 -07008450 const status_t getNextBufferStatus =
Andy Hung8d31fd22023-06-26 19:20:57 -07008451 activeTrack->resamplerBufferProvider()->getNextBuffer(&buffer);
Andy Hung920f6572022-10-06 12:09:49 -07008452 if (getNextBufferStatus == OK && buffer.frameCount != 0) {
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008453 ALOGV_IF(buffer.frameCount != framesOut,
8454 "%s() read less than expected (%zu vs %zu)",
8455 __func__, buffer.frameCount, framesOut);
8456 framesOut = buffer.frameCount;
Andy Hung8d31fd22023-06-26 19:20:57 -07008457 memcpy(activeTrack->sinkBuffer().raw,
8458 buffer.raw, buffer.frameCount * mFrameSize);
8459 activeTrack->resamplerBufferProvider()->releaseBuffer(&buffer);
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008460 } else {
8461 framesOut = 0;
8462 ALOGE("%s() cannot fill request, status: %d, frameCount: %zu",
Andy Hung920f6572022-10-06 12:09:49 -07008463 __func__, getNextBufferStatus, buffer.frameCount);
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008464 }
8465 } else {
8466 // process frames from the RecordThread buffer provider to the RecordTrack
8467 // buffer
Andy Hung8d31fd22023-06-26 19:20:57 -07008468 framesOut = activeTrack->recordBufferConverter()->convert(
8469 activeTrack->sinkBuffer().raw,
8470 activeTrack->resamplerBufferProvider(),
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008471 framesOut);
8472 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008473
8474 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
8475 overrun = OVERRUN_FALSE;
8476 }
8477
Andy Hung93bb5732023-05-04 21:16:34 -07008478 // MediaSyncEvent handling: Synchronize AudioRecord to AudioTrack completion.
8479 const ssize_t framesToDrop =
Andy Hung8d31fd22023-06-26 19:20:57 -07008480 activeTrack->synchronizedRecordState().updateRecordFrames(framesOut);
Andy Hung93bb5732023-05-04 21:16:34 -07008481 if (framesToDrop == 0) {
8482 // no sync event, process normally, otherwise ignore.
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008483 if (framesOut > 0) {
Andy Hung8d31fd22023-06-26 19:20:57 -07008484 activeTrack->sinkBuffer().frameCount = framesOut;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008485 // Sanitize before releasing if the track has no access to the source data
8486 // An idle UID receives silence from non virtual devices until active
8487 if (activeTrack->isSilenced()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07008488 memset(activeTrack->sinkBuffer().raw,
8489 0, framesOut * activeTrack->frameSize());
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008490 }
Andy Hung8d31fd22023-06-26 19:20:57 -07008491 activeTrack->releaseBuffer(&activeTrack->sinkBuffer());
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008492 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008493 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008494 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008495 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008496 }
8497 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008498
8499 switch (overrun) {
8500 case OVERRUN_TRUE:
8501 // client isn't retrieving buffers fast enough
8502 if (!activeTrack->setOverflow()) {
8503 nsecs_t now = systemTime();
8504 // FIXME should lastWarning per track?
8505 if ((now - lastWarning) > kWarningThrottleNs) {
8506 ALOGW("RecordThread: buffer overflow");
8507 lastWarning = now;
8508 }
8509 }
8510 break;
8511 case OVERRUN_FALSE:
8512 activeTrack->clearOverflow();
8513 break;
8514 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008515 break;
8516 }
8517
Andy Hung3f0c9022016-01-15 17:49:46 -08008518 // update frame information and push timestamp out
8519 activeTrack->updateTrackFrameInfo(
Andy Hung8d31fd22023-06-26 19:20:57 -07008520 activeTrack->serverProxy()->framesReleased(),
Andy Hung3f0c9022016-01-15 17:49:46 -08008521 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER],
8522 mSampleRate, mTimestamp);
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008523 }
8524
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008525unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08008526 // enable changes in effect chain
8527 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07008528 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurentcccbc762019-04-05 14:20:05 -07008529 if (audio_has_proportional_frames(mFormat)
8530 && loopCount == lastLoopCountRead + 1) {
8531 const int64_t readPeriodNs = lastIoEndNs - mLastIoEndNs;
8532 const double jitterMs =
8533 TimestampVerifier<int64_t, int64_t>::computeJitterMs(
8534 {framesRead, readPeriodNs},
8535 {0, 0} /* lastTimestamp */, mSampleRate);
8536 const double processMs = (lastIoBeginNs - mLastIoEndNs) * 1e-6;
8537
8538 Mutex::Autolock _l(mLock);
8539 mIoJitterMs.add(jitterMs);
8540 mProcessTimeMs.add(processMs);
8541 }
8542 // update timing info.
8543 mLastIoBeginNs = lastIoBeginNs;
8544 mLastIoEndNs = lastIoEndNs;
8545 lastLoopCountRead = loopCount;
Eric Laurent81784c32012-11-19 14:55:58 -08008546 }
8547
Glenn Kasten93e471f2013-08-19 08:40:07 -07008548 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08008549
8550 {
8551 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07008552 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07008553 sp<IAfRecordTrack> track = mTracks[i];
Eric Laurent9a54bc22013-09-09 09:08:44 -07008554 track->invalidate();
8555 }
Glenn Kasten2b806402013-11-20 16:37:38 -08008556 mActiveTracks.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08008557 mStartStopCond.broadcast();
8558 }
8559
8560 releaseWakeLock();
8561
8562 ALOGV("RecordThread %p exiting", this);
8563 return false;
8564}
8565
Andy Hungee58e4a2023-07-07 13:47:37 -07008566void RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08008567{
8568 if (!mStandby) {
8569 inputStandBy();
Andy Hungcf10d742020-04-28 15:38:24 -07008570 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07008571 mThreadSnapshot.onEnd();
Eric Laurent81784c32012-11-19 14:55:58 -08008572 mStandby = true;
8573 }
8574}
8575
Andy Hungee58e4a2023-07-07 13:47:37 -07008576void RecordThread::inputStandBy()
Eric Laurent81784c32012-11-19 14:55:58 -08008577{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008578 // Idle the fast capture if it's currently running
8579 if (mFastCapture != 0) {
8580 FastCaptureStateQueue *sq = mFastCapture->sq();
8581 FastCaptureState *state = sq->begin();
8582 if (!(state->mCommand & FastCaptureState::IDLE)) {
8583 state->mCommand = FastCaptureState::COLD_IDLE;
8584 state->mColdFutexAddr = &mFastCaptureFutex;
8585 state->mColdGen++;
8586 mFastCaptureFutex = 0;
8587 sq->end();
8588 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
8589 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
8590#if 0
8591 if (kUseFastCapture == FastCapture_Dynamic) {
8592 // FIXME
8593 }
8594#endif
8595#ifdef AUDIO_WATCHDOG
8596 // FIXME
8597#endif
8598 } else {
8599 sq->end(false /*didModify*/);
8600 }
8601 }
Mikhail Naganov2534b382019-09-25 13:05:02 -07008602 status_t result = mSource->standby();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008603 ALOGE_IF(result != OK, "Error when putting input stream into standby: %d", result);
Andy Hungad6d52d2016-07-18 13:42:03 -07008604
8605 // If going into standby, flush the pipe source.
8606 if (mPipeSource.get() != nullptr) {
8607 const ssize_t flushed = mPipeSource->flush();
8608 if (flushed > 0) {
8609 ALOGV("Input standby flushed PipeSource %zd frames", flushed);
8610 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += flushed;
8611 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
8612 }
8613 }
Eric Laurent81784c32012-11-19 14:55:58 -08008614}
8615
Glenn Kasten05997e22014-03-13 15:08:33 -07008616// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held
Andy Hungee58e4a2023-07-07 13:47:37 -07008617sp<IAfRecordTrack> RecordThread::createRecordTrack_l(
Andy Hung88035ac2023-06-27 17:05:02 -07008618 const sp<Client>& client,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07008619 const audio_attributes_t& attr,
Eric Laurentf14db3c2017-12-08 14:20:36 -08008620 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08008621 audio_format_t format,
8622 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08008623 size_t *pFrameCount,
Glenn Kastend848eb42016-03-08 13:42:11 -08008624 audio_session_t sessionId,
Eric Laurentf14db3c2017-12-08 14:20:36 -08008625 size_t *pNotificationFrameCount,
Eric Laurent09f1ed22019-04-24 17:45:17 -07008626 pid_t creatorPid,
Svet Ganov33761132021-05-13 22:51:08 +00008627 const AttributionSourceState& attributionSource,
Eric Laurent05067782016-06-01 18:27:28 -07008628 audio_input_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08008629 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08008630 status_t *status,
Eric Laurentec376dc2021-04-08 20:41:22 +02008631 audio_port_handle_t portId,
8632 int32_t maxSharedAudioHistoryMs)
Eric Laurent81784c32012-11-19 14:55:58 -08008633{
Glenn Kasten74935e42013-12-19 08:56:45 -08008634 size_t frameCount = *pFrameCount;
Eric Laurentf14db3c2017-12-08 14:20:36 -08008635 size_t notificationFrameCount = *pNotificationFrameCount;
Andy Hung8d31fd22023-06-26 19:20:57 -07008636 sp<IAfRecordTrack> track;
Eric Laurent81784c32012-11-19 14:55:58 -08008637 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07008638 audio_input_flags_t inputFlags = mInput->flags;
Eric Laurentf14db3c2017-12-08 14:20:36 -08008639 audio_input_flags_t requestedFlags = *flags;
8640 uint32_t sampleRate;
8641
8642 lStatus = initCheck();
8643 if (lStatus != NO_ERROR) {
8644 ALOGE("createRecordTrack_l() audio driver not initialized");
8645 goto Exit;
8646 }
8647
Mikhail Naganovce9f2652018-07-16 11:09:24 -07008648 if (!audio_is_linear_pcm(mFormat) && (*flags & AUDIO_INPUT_FLAG_DIRECT) == 0) {
8649 ALOGE("createRecordTrack_l() on an encoded stream requires AUDIO_INPUT_FLAG_DIRECT");
8650 lStatus = BAD_VALUE;
8651 goto Exit;
8652 }
8653
Eric Laurentec376dc2021-04-08 20:41:22 +02008654 if (maxSharedAudioHistoryMs != 0) {
Eric Laurent9ff3e532022-11-10 16:04:44 +01008655 if (!captureHotwordAllowed(attributionSource)) {
Eric Laurentec376dc2021-04-08 20:41:22 +02008656 lStatus = PERMISSION_DENIED;
8657 goto Exit;
8658 }
Eric Laurentec376dc2021-04-08 20:41:22 +02008659 if (maxSharedAudioHistoryMs < 0
8660 || maxSharedAudioHistoryMs > AudioFlinger::kMaxSharedAudioHistoryMs) {
8661 lStatus = BAD_VALUE;
8662 goto Exit;
8663 }
8664 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08008665 if (*pSampleRate == 0) {
8666 *pSampleRate = mSampleRate;
8667 }
8668 sampleRate = *pSampleRate;
Eric Laurent05067782016-06-01 18:27:28 -07008669
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008670 // special case for FAST flag considered OK if fast capture is present and access to
8671 // audio history is not required
8672 if (hasFastCapture() && mMaxSharedAudioHistoryMs == 0) {
Eric Laurent05067782016-06-01 18:27:28 -07008673 inputFlags = (audio_input_flags_t)(inputFlags | AUDIO_INPUT_FLAG_FAST);
8674 }
8675
Eric Laurentf14db3c2017-12-08 14:20:36 -08008676 // Check if requested flags are compatible with input stream flags
Eric Laurent05067782016-06-01 18:27:28 -07008677 if ((*flags & inputFlags) != *flags) {
8678 ALOGW("createRecordTrack_l(): mismatch between requested flags (%08x) and"
8679 " input flags (%08x)",
8680 *flags, inputFlags);
8681 *flags = (audio_input_flags_t)(*flags & inputFlags);
8682 }
Eric Laurent81784c32012-11-19 14:55:58 -08008683
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008684 // client expresses a preference for FAST and no access to audio history,
8685 // but we get the final say
8686 if (*flags & AUDIO_INPUT_FLAG_FAST && maxSharedAudioHistoryMs == 0) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07008687 if (
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07008688 // we formerly checked for a callback handler (non-0 tid),
8689 // but that is no longer required for TRANSFER_OBTAIN mode
jiabinb00edc32021-08-16 16:27:54 +00008690 // No need to match hardware format, format conversion will be done in client side.
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07008691 //
Phil Burk7ed66a12019-04-18 13:20:30 -07008692 // Frame count is not specified (0), or is less than or equal the pipe depth.
8693 // It is OK to provide a higher capacity than requested.
8694 // We will force it to mPipeFramesP2 below.
8695 (frameCount <= mPipeFramesP2) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07008696 // PCM data
8697 audio_is_linear_pcm(format) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08008698 // hardware channel mask
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008699 (channelMask == mChannelMask) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08008700 // hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07008701 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07008702 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008703 hasFastCapture() &&
8704 // there are sufficient fast track slots available
8705 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07008706 ) {
Eric Laurent4c415062016-06-17 16:14:16 -07008707 // check compatibility with audio effects.
8708 Mutex::Autolock _l(mLock);
8709 // Do not accept FAST flag if the session has software effects
Andy Hung116bc262023-06-20 18:56:17 -07008710 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent4c415062016-06-17 16:14:16 -07008711 if (chain != 0) {
Andy Hungd3bb0ad2016-10-11 17:16:43 -07008712 audio_input_flags_t old = *flags;
8713 chain->checkInputFlagCompatibility(flags);
8714 if (old != *flags) {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008715 ALOGV("%p AUDIO_INPUT_FLAGS denied by effect old=%#x new=%#x",
8716 this, (int)old, (int)*flags);
Eric Laurent4c415062016-06-17 16:14:16 -07008717 }
8718 }
Eric Laurent122f7e72016-06-29 11:53:29 -07008719 ALOGV_IF((*flags & AUDIO_INPUT_FLAG_FAST) != 0,
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008720 "%p AUDIO_INPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
8721 this, frameCount, mFrameCount);
Glenn Kasten90e58b12013-07-31 16:16:02 -07008722 } else {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008723 ALOGV("%p AUDIO_INPUT_FLAG_FAST denied: frameCount=%zu mFrameCount=%zu mPipeFramesP2=%zu "
8724 "format=%#x isLinear=%d mFormat=%#x channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008725 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008726 this, frameCount, mFrameCount, mPipeFramesP2,
8727 format, audio_is_linear_pcm(format), mFormat, channelMask, sampleRate, mSampleRate,
Glenn Kasten74105912014-07-03 12:28:53 -07008728 hasFastCapture(), tid, mFastTrackAvail);
Eric Laurent05067782016-06-01 18:27:28 -07008729 *flags = (audio_input_flags_t)(*flags & ~AUDIO_INPUT_FLAG_FAST);
Glenn Kasten74105912014-07-03 12:28:53 -07008730 }
8731 }
8732
Eric Laurentf14db3c2017-12-08 14:20:36 -08008733 // If FAST or RAW flags were corrected, ask caller to request new input from audio policy
8734 if ((*flags & AUDIO_INPUT_FLAG_FAST) !=
8735 (requestedFlags & AUDIO_INPUT_FLAG_FAST)) {
8736 *flags = (audio_input_flags_t) (*flags & ~(AUDIO_INPUT_FLAG_FAST | AUDIO_INPUT_FLAG_RAW));
8737 lStatus = BAD_TYPE;
8738 goto Exit;
8739 }
8740
Glenn Kasten74105912014-07-03 12:28:53 -07008741 // compute track buffer size in frames, and suggest the notification frame count
Eric Laurent05067782016-06-01 18:27:28 -07008742 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten74105912014-07-03 12:28:53 -07008743 // fast track: frame count is exactly the pipe depth
8744 frameCount = mPipeFramesP2;
8745 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
Eric Laurentf14db3c2017-12-08 14:20:36 -08008746 notificationFrameCount = mFrameCount;
Glenn Kasten74105912014-07-03 12:28:53 -07008747 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07008748 // not fast track: max notification period is resampled equivalent of one HAL buffer time
8749 // or 20 ms if there is a fast capture
8750 // TODO This could be a roundupRatio inline, and const
8751 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
8752 * sampleRate + mSampleRate - 1) / mSampleRate;
8753 // minimum number of notification periods is at least kMinNotifications,
8754 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
8755 static const size_t kMinNotifications = 3;
8756 static const uint32_t kMinMs = 30;
8757 // TODO This could be a roundupRatio inline
8758 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
8759 // TODO This could be a roundupRatio inline
8760 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
8761 maxNotificationFrames;
8762 const size_t minFrameCount = maxNotificationFrames *
8763 max(kMinNotifications, minNotificationsByMs);
8764 frameCount = max(frameCount, minFrameCount);
Eric Laurentf14db3c2017-12-08 14:20:36 -08008765 if (notificationFrameCount == 0 || notificationFrameCount > maxNotificationFrames) {
8766 notificationFrameCount = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07008767 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07008768 }
Glenn Kasten74935e42013-12-19 08:56:45 -08008769 *pFrameCount = frameCount;
Eric Laurentf14db3c2017-12-08 14:20:36 -08008770 *pNotificationFrameCount = notificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08008771
8772 { // scope for mLock
8773 Mutex::Autolock _l(mLock);
Eric Laurent2407ce32021-04-26 14:56:03 +02008774 int32_t startFrames = -1;
Eric Laurentec376dc2021-04-08 20:41:22 +02008775 if (!mSharedAudioPackageName.empty()
Eric Laurent9ff3e532022-11-10 16:04:44 +01008776 && mSharedAudioPackageName == attributionSource.packageName
Eric Laurentec376dc2021-04-08 20:41:22 +02008777 && mSharedAudioSessionId == sessionId
Eric Laurent9ff3e532022-11-10 16:04:44 +01008778 && captureHotwordAllowed(attributionSource)) {
Eric Laurent2407ce32021-04-26 14:56:03 +02008779 startFrames = mSharedAudioStartFrames;
Eric Laurentec376dc2021-04-08 20:41:22 +02008780 }
Eric Laurent81784c32012-11-19 14:55:58 -08008781
Andy Hung8d31fd22023-06-26 19:20:57 -07008782 track = IAfRecordTrack::create(this, client, attr, sampleRate,
Andy Hung8fe68032017-06-05 16:17:51 -07008783 format, channelMask, frameCount,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07008784 nullptr /* buffer */, (size_t)0 /* bufferSize */, sessionId, creatorPid,
Andy Hung8d31fd22023-06-26 19:20:57 -07008785 attributionSource, *flags, IAfTrackBase::TYPE_DEFAULT, portId,
Svet Ganov33761132021-05-13 22:51:08 +00008786 startFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08008787
Glenn Kasten03003332013-08-06 15:40:54 -07008788 lStatus = track->initCheck();
8789 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07008790 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08008791 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08008792 goto Exit;
8793 }
8794 mTracks.add(track);
8795
Eric Laurent05067782016-06-01 18:27:28 -07008796 if ((*flags & AUDIO_INPUT_FLAG_FAST) && (tid != -1)) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07008797 pid_t callingPid = IPCThreadState::self()->getCallingPid();
8798 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
8799 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07008800 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Glenn Kasten90e58b12013-07-31 16:16:02 -07008801 }
Eric Laurentec376dc2021-04-08 20:41:22 +02008802
8803 if (maxSharedAudioHistoryMs != 0) {
8804 sendResizeBufferConfigEvent_l(maxSharedAudioHistoryMs);
8805 }
Eric Laurent81784c32012-11-19 14:55:58 -08008806 }
Glenn Kasten05997e22014-03-13 15:08:33 -07008807
Eric Laurent81784c32012-11-19 14:55:58 -08008808 lStatus = NO_ERROR;
8809
8810Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07008811 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08008812 return track;
8813}
8814
Andy Hungee58e4a2023-07-07 13:47:37 -07008815status_t RecordThread::start(IAfRecordTrack* recordTrack,
Eric Laurent81784c32012-11-19 14:55:58 -08008816 AudioSystem::sync_event_t event,
Glenn Kastend848eb42016-03-08 13:42:11 -08008817 audio_session_t triggerSession)
Eric Laurent81784c32012-11-19 14:55:58 -08008818{
8819 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
8820 sp<ThreadBase> strongMe = this;
8821 status_t status = NO_ERROR;
8822
8823 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08008824 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08008825 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Andy Hung8d31fd22023-06-26 19:20:57 -07008826 recordTrack->synchronizedRecordState().startRecording(
Andy Hung583043b2023-07-17 17:05:00 -07008827 mAfThreadCallback->createSyncEvent(
Andy Hung93bb5732023-05-04 21:16:34 -07008828 event, triggerSession,
8829 recordTrack->sessionId(), syncStartEventCallback, recordTrack));
Eric Laurent81784c32012-11-19 14:55:58 -08008830 }
8831
8832 {
Glenn Kasten47c20702013-08-13 15:37:35 -07008833 // This section is a rendezvous between binder thread executing start() and RecordThread
Eric Laurent81784c32012-11-19 14:55:58 -08008834 AutoMutex lock(mLock);
Andy Hungce685402018-10-05 17:23:27 -07008835 if (recordTrack->isInvalid()) {
8836 recordTrack->clearSyncStartEvent();
Eric Laurentd52a28c2020-08-21 17:10:39 -07008837 ALOGW("%s track %d: invalidated before startInput", __func__, recordTrack->portId());
8838 return DEAD_OBJECT;
Andy Hungce685402018-10-05 17:23:27 -07008839 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008840 if (mActiveTracks.indexOf(recordTrack) >= 0) {
Andy Hung8d31fd22023-06-26 19:20:57 -07008841 if (recordTrack->state() == IAfTrackBase::PAUSING) {
Andy Hungce685402018-10-05 17:23:27 -07008842 // We haven't stopped yet (moved to PAUSED and not in mActiveTracks)
8843 // so no need to startInput().
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008844 ALOGV("active record track PAUSING -> ACTIVE");
Andy Hung8d31fd22023-06-26 19:20:57 -07008845 recordTrack->setState(IAfTrackBase::ACTIVE);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008846 } else {
Andy Hung8d31fd22023-06-26 19:20:57 -07008847 ALOGV("active record track state %d", (int)recordTrack->state());
Eric Laurent81784c32012-11-19 14:55:58 -08008848 }
8849 return status;
8850 }
8851
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08008852 // TODO consider other ways of handling this, such as changing the state to :STARTING and
8853 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
8854 // or using a separate command thread
Andy Hung8d31fd22023-06-26 19:20:57 -07008855 recordTrack->setState(IAfTrackBase::STARTING_1);
Glenn Kasten2b806402013-11-20 16:37:38 -08008856 mActiveTracks.add(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07008857 if (recordTrack->isExternalTrack()) {
8858 mLock.unlock();
Eric Laurent4eb58f12018-12-07 16:41:02 -08008859 status = AudioSystem::startInput(recordTrack->portId());
Eric Laurent83b88082014-06-20 18:31:16 -07008860 mLock.lock();
Andy Hungce685402018-10-05 17:23:27 -07008861 if (recordTrack->isInvalid()) {
8862 recordTrack->clearSyncStartEvent();
Andy Hung8d31fd22023-06-26 19:20:57 -07008863 if (status == NO_ERROR && recordTrack->state() == IAfTrackBase::STARTING_1) {
8864 recordTrack->setState(IAfTrackBase::STARTING_2);
Andy Hungce685402018-10-05 17:23:27 -07008865 // STARTING_2 forces destroy to call stopInput.
8866 }
Eric Laurentd52a28c2020-08-21 17:10:39 -07008867 ALOGW("%s track %d: invalidated after startInput", __func__, recordTrack->portId());
8868 return DEAD_OBJECT;
Andy Hungce685402018-10-05 17:23:27 -07008869 }
Andy Hung8d31fd22023-06-26 19:20:57 -07008870 if (recordTrack->state() != IAfTrackBase::STARTING_1) {
Andy Hungce685402018-10-05 17:23:27 -07008871 ALOGW("%s(%d): unsynchronized mState:%d change",
Andy Hung8d31fd22023-06-26 19:20:57 -07008872 __func__, recordTrack->id(), (int)recordTrack->state());
Andy Hungce685402018-10-05 17:23:27 -07008873 // Someone else has changed state, let them take over,
8874 // leave mState in the new state.
8875 recordTrack->clearSyncStartEvent();
8876 return INVALID_OPERATION;
8877 }
8878 // we're ok, but perhaps startInput has failed
Eric Laurent83b88082014-06-20 18:31:16 -07008879 if (status != NO_ERROR) {
Andy Hungce685402018-10-05 17:23:27 -07008880 ALOGW("%s(%d): startInput failed, status %d",
8881 __func__, recordTrack->id(), status);
8882 // We are in ActiveTracks if STARTING_1 and valid, so remove from ActiveTracks,
8883 // leave in STARTING_1, so destroy() will not call stopInput.
Eric Laurent83b88082014-06-20 18:31:16 -07008884 mActiveTracks.remove(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07008885 recordTrack->clearSyncStartEvent();
Eric Laurent83b88082014-06-20 18:31:16 -07008886 return status;
8887 }
Eric Laurent09f1ed22019-04-24 17:45:17 -07008888 sendIoConfigEvent_l(
8889 AUDIO_CLIENT_STARTED, recordTrack->creatorPid(), recordTrack->portId());
Eric Laurent81784c32012-11-19 14:55:58 -08008890 }
Andy Hungc2b11cb2020-04-22 09:04:01 -07008891
8892 recordTrack->logBeginInterval(patchSourcesToString(&mPatch)); // log to MediaMetrics
8893
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008894 // Catch up with current buffer indices if thread is already running.
8895 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
8896 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
8897 // see previously buffered data before it called start(), but with greater risk of overrun.
8898
Andy Hung8d31fd22023-06-26 19:20:57 -07008899 recordTrack->resamplerBufferProvider()->reset();
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008900 if (!recordTrack->isDirect()) {
8901 // clear any converter state as new data will be discontinuous
Andy Hung8d31fd22023-06-26 19:20:57 -07008902 recordTrack->recordBufferConverter()->reset();
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008903 }
Andy Hung8d31fd22023-06-26 19:20:57 -07008904 recordTrack->setState(IAfTrackBase::STARTING_2);
Eric Laurent81784c32012-11-19 14:55:58 -08008905 // signal thread to start
Eric Laurent81784c32012-11-19 14:55:58 -08008906 mWaitWorkCV.broadcast();
Eric Laurent81784c32012-11-19 14:55:58 -08008907 return status;
8908 }
Eric Laurent81784c32012-11-19 14:55:58 -08008909}
8910
Andy Hungee58e4a2023-07-07 13:47:37 -07008911void RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
Eric Laurent81784c32012-11-19 14:55:58 -08008912{
Andy Hungee58e4a2023-07-07 13:47:37 -07008913 const sp<SyncEvent> strongEvent = event.promote();
Eric Laurent81784c32012-11-19 14:55:58 -08008914
8915 if (strongEvent != 0) {
Andy Hungd29af632023-06-23 19:27:19 -07008916 sp<IAfTrackBase> ptr =
8917 std::any_cast<const wp<IAfTrackBase>>(strongEvent->cookie()).promote();
8918 if (ptr != nullptr) {
Andy Hung99b1ba62023-07-14 11:00:08 -07008919 // TODO(b/291317898) handleSyncStartEvent is in IAfTrackBase not IAfRecordTrack.
Andy Hungd29af632023-06-23 19:27:19 -07008920 ptr->handleSyncStartEvent(strongEvent);
Eric Laurent8ea16e42014-02-20 16:26:11 -08008921 }
Eric Laurent81784c32012-11-19 14:55:58 -08008922 }
8923}
8924
Andy Hungee58e4a2023-07-07 13:47:37 -07008925bool RecordThread::stop(IAfRecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08008926 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07008927 AutoMutex _l(mLock);
Andy Hungce685402018-10-05 17:23:27 -07008928 // if we're invalid, we can't be on the ActiveTracks.
Andy Hung8d31fd22023-06-26 19:20:57 -07008929 if (mActiveTracks.indexOf(recordTrack) < 0 || recordTrack->state() == IAfTrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08008930 return false;
8931 }
Glenn Kasten47c20702013-08-13 15:37:35 -07008932 // note that threadLoop may still be processing the track at this point [without lock]
Andy Hung8d31fd22023-06-26 19:20:57 -07008933 recordTrack->setState(IAfTrackBase::PAUSING);
Andy Hungce685402018-10-05 17:23:27 -07008934
Andy Hungabfab202019-03-07 19:45:54 -08008935 // NOTE: Waiting here is important to keep stop synchronous.
8936 // This is needed for proper patchRecord peer release.
Andy Hung8d31fd22023-06-26 19:20:57 -07008937 while (recordTrack->state() == IAfTrackBase::PAUSING && !recordTrack->isInvalid()) {
Andy Hungce685402018-10-05 17:23:27 -07008938 mWaitWorkCV.broadcast(); // signal thread to stop
8939 mStartStopCond.wait(mLock);
Eric Laurent81784c32012-11-19 14:55:58 -08008940 }
Andy Hungce685402018-10-05 17:23:27 -07008941
Andy Hung8d31fd22023-06-26 19:20:57 -07008942 if (recordTrack->state() == IAfTrackBase::PAUSED) { // successful stop
Eric Laurent81784c32012-11-19 14:55:58 -08008943 ALOGV("Record stopped OK");
8944 return true;
8945 }
Andy Hungce685402018-10-05 17:23:27 -07008946
8947 // don't handle anything - we've been invalidated or restarted and in a different state
8948 ALOGW_IF("%s(%d): unsynchronized stop, state: %d",
Andy Hung8d31fd22023-06-26 19:20:57 -07008949 __func__, recordTrack->id(), recordTrack->state());
Eric Laurent81784c32012-11-19 14:55:58 -08008950 return false;
8951}
8952
Andy Hungee58e4a2023-07-07 13:47:37 -07008953bool RecordThread::isValidSyncEvent(const sp<SyncEvent>& /* event */) const
Eric Laurent81784c32012-11-19 14:55:58 -08008954{
8955 return false;
8956}
8957
Andy Hungee58e4a2023-07-07 13:47:37 -07008958status_t RecordThread::setSyncEvent(const sp<SyncEvent>& /* event */)
Eric Laurent81784c32012-11-19 14:55:58 -08008959{
8960#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
8961 if (!isValidSyncEvent(event)) {
8962 return BAD_VALUE;
8963 }
8964
Glenn Kastend848eb42016-03-08 13:42:11 -08008965 audio_session_t eventSession = event->triggerSession();
Eric Laurent81784c32012-11-19 14:55:58 -08008966 status_t ret = NAME_NOT_FOUND;
8967
8968 Mutex::Autolock _l(mLock);
8969
8970 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07008971 sp<IAfRecordTrack> track = mTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08008972 if (eventSession == track->sessionId()) {
8973 (void) track->setSyncEvent(event);
8974 ret = NO_ERROR;
8975 }
8976 }
8977 return ret;
8978#else
8979 return BAD_VALUE;
8980#endif
8981}
8982
Andy Hungee58e4a2023-07-07 13:47:37 -07008983status_t RecordThread::getActiveMicrophones(
Andy Hung87c693c2023-07-06 20:56:16 -07008984 std::vector<media::MicrophoneInfoFw>* activeMicrophones) const
jiabin653cc0a2018-01-17 17:54:10 -08008985{
8986 ALOGV("RecordThread::getActiveMicrophones");
8987 AutoMutex _l(mLock);
Jasmine Chaeaa10e42021-05-11 10:11:14 +08008988 if (!isStreamInitialized()) {
Paul McLean8a661a32021-04-12 10:21:42 -06008989 return NO_INIT;
8990 }
jiabin9ff780e2018-03-19 18:19:52 -07008991 status_t status = mInput->stream->getActiveMicrophones(activeMicrophones);
8992 return status;
jiabin653cc0a2018-01-17 17:54:10 -08008993}
8994
Andy Hungee58e4a2023-07-07 13:47:37 -07008995status_t RecordThread::setPreferredMicrophoneDirection(
Paul McLean12340082019-03-19 09:35:05 -06008996 audio_microphone_direction_t direction)
Paul McLean03a6e6a2018-12-04 10:54:13 -07008997{
Paul McLean12340082019-03-19 09:35:05 -06008998 ALOGV("setPreferredMicrophoneDirection(%d)", direction);
Paul McLean03a6e6a2018-12-04 10:54:13 -07008999 AutoMutex _l(mLock);
Jasmine Chaeaa10e42021-05-11 10:11:14 +08009000 if (!isStreamInitialized()) {
Paul McLean8a661a32021-04-12 10:21:42 -06009001 return NO_INIT;
9002 }
Paul McLean12340082019-03-19 09:35:05 -06009003 return mInput->stream->setPreferredMicrophoneDirection(direction);
Paul McLean03a6e6a2018-12-04 10:54:13 -07009004}
9005
Andy Hungee58e4a2023-07-07 13:47:37 -07009006status_t RecordThread::setPreferredMicrophoneFieldDimension(float zoom)
Paul McLean03a6e6a2018-12-04 10:54:13 -07009007{
Paul McLean12340082019-03-19 09:35:05 -06009008 ALOGV("setPreferredMicrophoneFieldDimension(%f)", zoom);
Paul McLean03a6e6a2018-12-04 10:54:13 -07009009 AutoMutex _l(mLock);
Jasmine Chaeaa10e42021-05-11 10:11:14 +08009010 if (!isStreamInitialized()) {
Paul McLean8a661a32021-04-12 10:21:42 -06009011 return NO_INIT;
9012 }
Paul McLean12340082019-03-19 09:35:05 -06009013 return mInput->stream->setPreferredMicrophoneFieldDimension(zoom);
Paul McLean03a6e6a2018-12-04 10:54:13 -07009014}
9015
Andy Hungee58e4a2023-07-07 13:47:37 -07009016status_t RecordThread::shareAudioHistory(
Eric Laurentec376dc2021-04-08 20:41:22 +02009017 const std::string& sharedAudioPackageName, audio_session_t sharedSessionId,
9018 int64_t sharedAudioStartMs) {
9019 AutoMutex _l(mLock);
9020 return shareAudioHistory_l(sharedAudioPackageName, sharedSessionId, sharedAudioStartMs);
9021}
9022
Andy Hungee58e4a2023-07-07 13:47:37 -07009023status_t RecordThread::shareAudioHistory_l(
Eric Laurentec376dc2021-04-08 20:41:22 +02009024 const std::string& sharedAudioPackageName, audio_session_t sharedSessionId,
9025 int64_t sharedAudioStartMs) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009026
Eric Laurentec376dc2021-04-08 20:41:22 +02009027 if ((hasAudioSession_l(sharedSessionId) & ThreadBase::TRACK_SESSION) == 0) {
9028 return BAD_VALUE;
9029 }
Eric Laurent2407ce32021-04-26 14:56:03 +02009030
9031 if (sharedAudioStartMs < 0
9032 || sharedAudioStartMs > INT64_MAX / mSampleRate) {
Eric Laurentec376dc2021-04-08 20:41:22 +02009033 return BAD_VALUE;
9034 }
9035
Eric Laurent2407ce32021-04-26 14:56:03 +02009036 // Current implementation of the input resampling buffer wraps around indexes at 32 bit.
9037 // As we cannot detect more than one wraparound, only accept values up current write position
9038 // after one wraparound
9039 // We assume recent wraparounds on mRsmpInRear only given it is unlikely that the requesting
9040 // app waits several hours after the start time was computed.
Eric Laurent92d0a322021-07-16 15:32:33 +02009041 int64_t sharedAudioStartFrames = sharedAudioStartMs * mSampleRate / 1000;
Eric Laurent2407ce32021-04-26 14:56:03 +02009042 const int32_t sharedOffset = audio_utils::safe_sub_overflow(mRsmpInRear,
9043 (int32_t)sharedAudioStartFrames);
Eric Laurent92d0a322021-07-16 15:32:33 +02009044 // Bring the start frame position within the input buffer to match the documented
9045 // "best effort" behavior of the API.
9046 if (sharedOffset < 0) {
9047 sharedAudioStartFrames = mRsmpInRear;
Andy Hung920f6572022-10-06 12:09:49 -07009048 } else if (sharedOffset > static_cast<signed>(mRsmpInFrames)) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009049 sharedAudioStartFrames =
9050 audio_utils::safe_sub_overflow(mRsmpInRear, (int32_t)mRsmpInFrames);
Eric Laurent2407ce32021-04-26 14:56:03 +02009051 }
9052
Eric Laurentec376dc2021-04-08 20:41:22 +02009053 mSharedAudioPackageName = sharedAudioPackageName;
9054 if (mSharedAudioPackageName.empty()) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009055 resetAudioHistory_l();
Eric Laurentec376dc2021-04-08 20:41:22 +02009056 } else {
9057 mSharedAudioSessionId = sharedSessionId;
Eric Laurent2407ce32021-04-26 14:56:03 +02009058 mSharedAudioStartFrames = (int32_t)sharedAudioStartFrames;
Eric Laurentec376dc2021-04-08 20:41:22 +02009059 }
9060 return NO_ERROR;
9061}
9062
Andy Hungee58e4a2023-07-07 13:47:37 -07009063void RecordThread::resetAudioHistory_l() {
Eric Laurent92d0a322021-07-16 15:32:33 +02009064 mSharedAudioSessionId = AUDIO_SESSION_NONE;
9065 mSharedAudioStartFrames = -1;
9066 mSharedAudioPackageName = "";
9067}
9068
Andy Hungee58e4a2023-07-07 13:47:37 -07009069ThreadBase::MetadataUpdate RecordThread::updateMetadata_l()
Kevin Rocard069c2712018-03-29 19:09:14 -07009070{
Jasmine Chaeaa10e42021-05-11 10:11:14 +08009071 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
Vlad Popa7e81cea2023-01-19 16:34:16 +01009072 return {}; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -07009073 }
9074 StreamInHalInterface::SinkMetadata metadata;
Eric Laurent78b07302022-10-07 16:20:34 +02009075 auto backInserter = std::back_inserter(metadata.tracks);
Andy Hung8d31fd22023-06-26 19:20:57 -07009076 for (const sp<IAfRecordTrack>& track : mActiveTracks) {
Eric Laurent78b07302022-10-07 16:20:34 +02009077 track->copyMetadataTo(backInserter);
Kevin Rocard069c2712018-03-29 19:09:14 -07009078 }
9079 mInput->stream->updateSinkMetadata(metadata);
Vlad Popa7e81cea2023-01-19 16:34:16 +01009080 MetadataUpdate change;
9081 change.recordMetadataUpdate = metadata.tracks;
9082 return change;
Kevin Rocard069c2712018-03-29 19:09:14 -07009083}
9084
Eric Laurent81784c32012-11-19 14:55:58 -08009085// destroyTrack_l() must be called with ThreadBase::mLock held
Andy Hungee58e4a2023-07-07 13:47:37 -07009086void RecordThread::destroyTrack_l(const sp<IAfRecordTrack>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08009087{
Eric Laurentbfb1b832013-01-07 09:53:42 -08009088 track->terminate();
Andy Hung8d31fd22023-06-26 19:20:57 -07009089 track->setState(IAfTrackBase::STOPPED);
Eric Laurentec376dc2021-04-08 20:41:22 +02009090
Eric Laurent81784c32012-11-19 14:55:58 -08009091 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08009092 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08009093 removeTrack_l(track);
9094 }
9095}
9096
Andy Hungee58e4a2023-07-07 13:47:37 -07009097void RecordThread::removeTrack_l(const sp<IAfRecordTrack>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08009098{
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009099 String8 result;
9100 track->appendDump(result, false /* active */);
9101 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.string());
9102
Eric Laurent81784c32012-11-19 14:55:58 -08009103 mTracks.remove(track);
9104 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07009105 if (track->isFastTrack()) {
9106 ALOG_ASSERT(!mFastTrackAvail);
9107 mFastTrackAvail = true;
9108 }
Eric Laurent81784c32012-11-19 14:55:58 -08009109}
9110
Andy Hungee58e4a2023-07-07 13:47:37 -07009111void RecordThread::dumpInternals_l(int fd, const Vector<String16>& /* args */)
Eric Laurent81784c32012-11-19 14:55:58 -08009112{
Mikhail Naganov913d06c2016-11-01 12:49:22 -07009113 AudioStreamIn *input = mInput;
9114 audio_input_flags_t flags = input != NULL ? input->flags : AUDIO_INPUT_FLAG_NONE;
9115 dprintf(fd, " AudioStreamIn: %p flags %#x (%s)\n",
Andy Hung9b181952019-02-25 14:53:36 -08009116 input, flags, toString(flags).c_str());
Andy Hung6427e442018-08-09 12:51:02 -07009117 dprintf(fd, " Frames read: %lld\n", (long long)mFramesRead);
Eric Tan39ec8d62018-07-24 09:49:29 -07009118 if (mActiveTracks.isEmpty()) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07009119 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08009120 }
Andy Hungbfa64962017-06-12 14:43:19 -07009121
9122 if (input != nullptr) {
9123 dprintf(fd, " Hal stream dump:\n");
9124 (void)input->stream->dump(fd);
9125 }
9126
Glenn Kasten6e6704c2014-07-03 10:20:00 -07009127 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07009128 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Glenn Kasten17c9c992015-03-02 15:53:01 -08009129
Glenn Kasten2f90c512015-12-02 11:40:09 -08009130 // Make a non-atomic copy of fast capture dump state so it won't change underneath us
9131 // while we are dumping it. It may be inconsistent, but it won't mutate!
9132 // This is a large object so we place it on the heap.
9133 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
Eric Tan2942a4e2018-09-12 17:41:27 -07009134 const std::unique_ptr<FastCaptureDumpState> copy =
9135 std::make_unique<FastCaptureDumpState>(mFastCaptureDumpState);
Glenn Kasten2f90c512015-12-02 11:40:09 -08009136 copy->dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08009137}
9138
Andy Hungee58e4a2023-07-07 13:47:37 -07009139void RecordThread::dumpTracks_l(int fd, const Vector<String16>& /* args */)
Eric Laurent81784c32012-11-19 14:55:58 -08009140{
Eric Laurent81784c32012-11-19 14:55:58 -08009141 String8 result;
Marco Nelissenb2208842014-02-07 14:00:50 -08009142 size_t numtracks = mTracks.size();
9143 size_t numactive = mActiveTracks.size();
9144 size_t numactiveseen = 0;
Glenn Kastenc42e9b42016-03-21 11:35:03 -07009145 dprintf(fd, " %zu Tracks", numtracks);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009146 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08009147 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07009148 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009149 result.append(prefix);
Andy Hung000adb52018-06-01 15:43:26 -07009150 mTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08009151 for (size_t i = 0; i < numtracks ; ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07009152 sp<IAfRecordTrack> track = mTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08009153 if (track != 0) {
9154 bool active = mActiveTracks.indexOf(track) >= 0;
9155 if (active) {
9156 numactiveseen++;
9157 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009158 result.append(prefix);
9159 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08009160 }
Eric Laurent81784c32012-11-19 14:55:58 -08009161 }
Marco Nelissenb2208842014-02-07 14:00:50 -08009162 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07009163 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08009164 }
9165
Marco Nelissenb2208842014-02-07 14:00:50 -08009166 if (numactiveseen != numactive) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009167 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08009168 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009169 result.append(prefix);
Andy Hung000adb52018-06-01 15:43:26 -07009170 mActiveTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08009171 for (size_t i = 0; i < numactive; ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07009172 sp<IAfRecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08009173 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009174 result.append(prefix);
9175 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08009176 }
Glenn Kasten2b806402013-11-20 16:37:38 -08009177 }
Eric Laurent81784c32012-11-19 14:55:58 -08009178
9179 }
9180 write(fd, result.string(), result.size());
9181}
9182
Andy Hungee58e4a2023-07-07 13:47:37 -07009183void RecordThread::setRecordSilenced(audio_port_handle_t portId, bool silenced)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08009184{
9185 Mutex::Autolock _l(mLock);
9186 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07009187 sp<IAfRecordTrack> track = mTracks[i];
Eric Laurent5ada82e2019-08-29 17:53:54 -07009188 if (track != 0 && track->portId() == portId) {
Svet Ganovf4ddfef2018-01-16 07:37:58 -08009189 track->setSilenced(silenced);
9190 }
9191 }
9192}
Andy Hung73c02e42015-03-29 01:13:58 -07009193
Andy Hung8d31fd22023-06-26 19:20:57 -07009194void ResamplerBufferProvider::reset()
Andy Hung73c02e42015-03-29 01:13:58 -07009195{
Andy Hung87c693c2023-07-06 20:56:16 -07009196 const auto threadBase = mRecordTrack->thread().promote();
Andy Hungee58e4a2023-07-07 13:47:37 -07009197 auto* const recordThread = static_cast<RecordThread *>(threadBase->asIAfRecordThread().get());
Andy Hung73c02e42015-03-29 01:13:58 -07009198 mRsmpInUnrel = 0;
Eric Laurentec376dc2021-04-08 20:41:22 +02009199 const int32_t rear = recordThread->mRsmpInRear;
9200 ssize_t deltaFrames = 0;
Eric Laurent2407ce32021-04-26 14:56:03 +02009201 if (mRecordTrack->startFrames() >= 0) {
9202 int32_t startFrames = mRecordTrack->startFrames();
9203 // Accept a recent wraparound of mRsmpInRear
9204 if (startFrames <= rear) {
9205 deltaFrames = rear - startFrames;
9206 } else {
9207 deltaFrames = (int32_t)((int64_t)rear + UINT32_MAX + 1 - startFrames);
Eric Laurentec376dc2021-04-08 20:41:22 +02009208 }
Eric Laurentec376dc2021-04-08 20:41:22 +02009209 // start frame cannot be further in the past than start of resampling buffer
9210 if ((size_t) deltaFrames > recordThread->mRsmpInFrames) {
9211 deltaFrames = recordThread->mRsmpInFrames;
9212 }
9213 }
9214 mRsmpInFront = audio_utils::safe_sub_overflow(rear, static_cast<int32_t>(deltaFrames));
Andy Hung73c02e42015-03-29 01:13:58 -07009215}
9216
Andy Hung8d31fd22023-06-26 19:20:57 -07009217void ResamplerBufferProvider::sync(
Andy Hung73c02e42015-03-29 01:13:58 -07009218 size_t *framesAvailable, bool *hasOverrun)
9219{
Andy Hung87c693c2023-07-06 20:56:16 -07009220 const auto threadBase = mRecordTrack->thread().promote();
Andy Hungee58e4a2023-07-07 13:47:37 -07009221 auto* const recordThread = static_cast<RecordThread *>(threadBase->asIAfRecordThread().get());
Andy Hung73c02e42015-03-29 01:13:58 -07009222 const int32_t rear = recordThread->mRsmpInRear;
9223 const int32_t front = mRsmpInFront;
Hongwei Wang95e37682019-04-12 11:13:36 -07009224 const ssize_t filled = audio_utils::safe_sub_overflow(rear, front);
Andy Hung73c02e42015-03-29 01:13:58 -07009225
9226 size_t framesIn;
9227 bool overrun = false;
9228 if (filled < 0) {
9229 // should not happen, but treat like a massive overrun and re-sync
9230 framesIn = 0;
9231 mRsmpInFront = rear;
9232 overrun = true;
9233 } else if ((size_t) filled <= recordThread->mRsmpInFrames) {
9234 framesIn = (size_t) filled;
9235 } else {
9236 // client is not keeping up with server, but give it latest data
9237 framesIn = recordThread->mRsmpInFrames;
Hongwei Wang95e37682019-04-12 11:13:36 -07009238 mRsmpInFront = /* front = */ audio_utils::safe_sub_overflow(
9239 rear, static_cast<int32_t>(framesIn));
Andy Hung73c02e42015-03-29 01:13:58 -07009240 overrun = true;
9241 }
9242 if (framesAvailable != NULL) {
9243 *framesAvailable = framesIn;
9244 }
9245 if (hasOverrun != NULL) {
9246 *hasOverrun = overrun;
9247 }
9248}
9249
Eric Laurent81784c32012-11-19 14:55:58 -08009250// AudioBufferProvider interface
Andy Hung8d31fd22023-06-26 19:20:57 -07009251status_t ResamplerBufferProvider::getNextBuffer(
Glenn Kastend79072e2016-01-06 08:41:20 -08009252 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08009253{
Andy Hung87c693c2023-07-06 20:56:16 -07009254 const auto threadBase = mRecordTrack->thread().promote();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009255 if (threadBase == 0) {
9256 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08009257 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009258 return NOT_ENOUGH_DATA;
9259 }
Andy Hungee58e4a2023-07-07 13:47:37 -07009260 auto* const recordThread = static_cast<RecordThread *>(threadBase->asIAfRecordThread().get());
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009261 int32_t rear = recordThread->mRsmpInRear;
Andy Hung73c02e42015-03-29 01:13:58 -07009262 int32_t front = mRsmpInFront;
Hongwei Wang95e37682019-04-12 11:13:36 -07009263 ssize_t filled = audio_utils::safe_sub_overflow(rear, front);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009264 // FIXME should not be P2 (don't want to increase latency)
9265 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08009266 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07009267 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009268
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009269 front &= recordThread->mRsmpInFramesP2 - 1;
9270 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07009271 if (part1 > (size_t) filled) {
9272 part1 = filled;
9273 }
9274 size_t ask = buffer->frameCount;
9275 ALOG_ASSERT(ask > 0);
9276 if (part1 > ask) {
9277 part1 = ask;
9278 }
9279 if (part1 == 0) {
Andy Hung73c02e42015-03-29 01:13:58 -07009280 // out of data is fine since the resampler will return a short-count.
Glenn Kasten85948432013-08-19 12:09:05 -07009281 buffer->raw = NULL;
9282 buffer->frameCount = 0;
Andy Hung73c02e42015-03-29 01:13:58 -07009283 mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07009284 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08009285 }
9286
Andy Hung57446612015-04-19 23:56:46 -07009287 buffer->raw = (uint8_t*)recordThread->mRsmpInBuffer + front * recordThread->mFrameSize;
Glenn Kasten85948432013-08-19 12:09:05 -07009288 buffer->frameCount = part1;
Andy Hung73c02e42015-03-29 01:13:58 -07009289 mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08009290 return NO_ERROR;
9291}
9292
9293// AudioBufferProvider interface
Andy Hung8d31fd22023-06-26 19:20:57 -07009294void ResamplerBufferProvider::releaseBuffer(
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009295 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08009296{
Hongwei Wang95e37682019-04-12 11:13:36 -07009297 int32_t stepCount = static_cast<int32_t>(buffer->frameCount);
Glenn Kasten85948432013-08-19 12:09:05 -07009298 if (stepCount == 0) {
9299 return;
9300 }
Eric Laurent1e28aaa2023-04-16 19:34:23 +02009301 ALOG_ASSERT(stepCount <= (int32_t)mRsmpInUnrel);
Andy Hung73c02e42015-03-29 01:13:58 -07009302 mRsmpInUnrel -= stepCount;
Hongwei Wang95e37682019-04-12 11:13:36 -07009303 mRsmpInFront = audio_utils::safe_add_overflow(mRsmpInFront, stepCount);
Glenn Kasten85948432013-08-19 12:09:05 -07009304 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08009305 buffer->frameCount = 0;
9306}
9307
Andy Hungee58e4a2023-07-07 13:47:37 -07009308void RecordThread::checkBtNrec()
Eric Laurentd8365c52017-07-16 15:27:05 -07009309{
9310 Mutex::Autolock _l(mLock);
9311 checkBtNrec_l();
9312}
9313
Andy Hungee58e4a2023-07-07 13:47:37 -07009314void RecordThread::checkBtNrec_l()
Eric Laurentd8365c52017-07-16 15:27:05 -07009315{
9316 // disable AEC and NS if the device is a BT SCO headset supporting those
9317 // pre processings
jiabinc52b1ff2019-10-31 17:20:42 -07009318 bool suspend = audio_is_bluetooth_sco_device(inDeviceType()) &&
Andy Hung583043b2023-07-17 17:05:00 -07009319 mAfThreadCallback->btNrecIsOff();
Eric Laurentd8365c52017-07-16 15:27:05 -07009320 if (mBtNrecSuspended.exchange(suspend) != suspend) {
9321 for (size_t i = 0; i < mEffectChains.size(); i++) {
9322 setEffectSuspended_l(FX_IID_AEC, suspend, mEffectChains[i]->sessionId());
9323 setEffectSuspended_l(FX_IID_NS, suspend, mEffectChains[i]->sessionId());
9324 }
9325 }
9326}
9327
Andy Hung97a893e2015-03-29 01:03:07 -07009328
Andy Hungee58e4a2023-07-07 13:47:37 -07009329bool RecordThread::checkForNewParameter_l(const String8& keyValuePair,
Eric Laurent10351942014-05-08 18:49:52 -07009330 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08009331{
9332 bool reconfig = false;
9333
Eric Laurent10351942014-05-08 18:49:52 -07009334 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08009335
Eric Laurent10351942014-05-08 18:49:52 -07009336 audio_format_t reqFormat = mFormat;
9337 uint32_t samplingRate = mSampleRate;
Glenn Kastene1635ec2015-06-08 15:46:49 -07009338 // 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 +08009339 [[maybe_unused]] audio_channel_mask_t channelMask =
9340 audio_channel_in_mask_from_count(mChannelCount);
Eric Laurent10351942014-05-08 18:49:52 -07009341
9342 AudioParameter param = AudioParameter(keyValuePair);
9343 int value;
Haynes Mathew George9ce67b52015-09-30 11:40:47 -07009344
9345 // scope for AutoPark extends to end of method
9346 AutoPark<FastCapture> park(mFastCapture);
9347
Eric Laurent10351942014-05-08 18:49:52 -07009348 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
9349 // channel count change can be requested. Do we mandate the first client defines the
9350 // HAL sampling rate and channel count or do we allow changes on the fly?
9351 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
9352 samplingRate = value;
9353 reconfig = true;
9354 }
9355 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung97a893e2015-03-29 01:03:07 -07009356 if (!audio_is_linear_pcm((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07009357 status = BAD_VALUE;
9358 } else {
9359 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08009360 reconfig = true;
9361 }
Eric Laurent10351942014-05-08 18:49:52 -07009362 }
9363 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
9364 audio_channel_mask_t mask = (audio_channel_mask_t) value;
Andy Hungd330ee42015-04-20 13:23:41 -07009365 if (!audio_is_input_channel(mask) ||
Andy Hung936845a2021-06-08 00:09:06 -07009366 audio_channel_count_from_in_mask(mask) > FCC_LIMIT) {
Eric Laurent10351942014-05-08 18:49:52 -07009367 status = BAD_VALUE;
9368 } else {
9369 channelMask = mask;
9370 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08009371 }
Eric Laurent10351942014-05-08 18:49:52 -07009372 }
9373 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
9374 // do not accept frame count changes if tracks are open as the track buffer
9375 // size depends on frame count and correct behavior would not be guaranteed
9376 // if frame count is changed after track creation
9377 if (mActiveTracks.size() > 0) {
9378 status = INVALID_OPERATION;
9379 } else {
9380 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08009381 }
Eric Laurent10351942014-05-08 18:49:52 -07009382 }
9383 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07009384 LOG_FATAL("Should not set routing device in RecordThread");
Eric Laurent10351942014-05-08 18:49:52 -07009385 }
9386 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
9387 mAudioSource != (audio_source_t)value) {
jiabinc52b1ff2019-10-31 17:20:42 -07009388 LOG_FATAL("Should not set audio source in RecordThread");
Eric Laurent10351942014-05-08 18:49:52 -07009389 }
Glenn Kastene198c362013-08-13 09:13:36 -07009390
Eric Laurent10351942014-05-08 18:49:52 -07009391 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009392 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07009393 if (status == INVALID_OPERATION) {
9394 inputStandBy();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009395 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07009396 }
9397 if (reconfig) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009398 if (status == BAD_VALUE) {
Mikhail Naganov560637e2021-03-31 22:40:13 +00009399 audio_config_base_t config = AUDIO_CONFIG_BASE_INITIALIZER;
9400 if (mInput->stream->getAudioProperties(&config) == OK &&
9401 audio_is_linear_pcm(config.format) && audio_is_linear_pcm(reqFormat) &&
9402 config.sample_rate <= (AUDIO_RESAMPLER_DOWN_RATIO_MAX * samplingRate) &&
Andy Hung936845a2021-06-08 00:09:06 -07009403 audio_channel_count_from_in_mask(config.channel_mask) <= FCC_LIMIT) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009404 status = NO_ERROR;
9405 }
Eric Laurent81784c32012-11-19 14:55:58 -08009406 }
Eric Laurent10351942014-05-08 18:49:52 -07009407 if (status == NO_ERROR) {
9408 readInputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07009409 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08009410 }
9411 }
Eric Laurent81784c32012-11-19 14:55:58 -08009412 }
Eric Laurent10351942014-05-08 18:49:52 -07009413
Eric Laurent81784c32012-11-19 14:55:58 -08009414 return reconfig;
9415}
9416
Andy Hungee58e4a2023-07-07 13:47:37 -07009417String8 RecordThread::getParameters(const String8& keys)
Eric Laurent81784c32012-11-19 14:55:58 -08009418{
Eric Laurent81784c32012-11-19 14:55:58 -08009419 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009420 if (initCheck() == NO_ERROR) {
9421 String8 out_s8;
9422 if (mInput->stream->getParameters(keys, &out_s8) == OK) {
9423 return out_s8;
9424 }
Eric Laurent81784c32012-11-19 14:55:58 -08009425 }
Andy Hung920f6572022-10-06 12:09:49 -07009426 return {};
Eric Laurent81784c32012-11-19 14:55:58 -08009427}
9428
Andy Hungee58e4a2023-07-07 13:47:37 -07009429void RecordThread::ioConfigChanged(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -07009430 audio_port_handle_t portId) {
Mikhail Naganov88536df2021-07-26 17:30:29 -07009431 sp<AudioIoDescriptor> desc;
Eric Laurent81784c32012-11-19 14:55:58 -08009432 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07009433 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07009434 case AUDIO_INPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07009435 case AUDIO_INPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07009436 desc = sp<AudioIoDescriptor>::make(mId, mPatch, true /*isInput*/,
9437 mSampleRate, mFormat, mChannelMask, mFrameCount, mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08009438 break;
Eric Laurent09f1ed22019-04-24 17:45:17 -07009439 case AUDIO_CLIENT_STARTED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07009440 desc = sp<AudioIoDescriptor>::make(mId, mPatch, portId);
Eric Laurent09f1ed22019-04-24 17:45:17 -07009441 break;
Eric Laurent73e26b62015-04-27 16:55:58 -07009442 case AUDIO_INPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08009443 default:
Mikhail Naganov88536df2021-07-26 17:30:29 -07009444 desc = sp<AudioIoDescriptor>::make(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08009445 break;
9446 }
Andy Hung583043b2023-07-17 17:05:00 -07009447 mAfThreadCallback->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08009448}
9449
Andy Hungee58e4a2023-07-07 13:47:37 -07009450void RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08009451{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009452 status_t result = mInput->stream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
9453 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
Andy Hung463be252014-07-10 16:56:07 -07009454 mFormat = mHALFormat;
Mikhail Naganovce9f2652018-07-16 11:09:24 -07009455 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
9456 if (audio_is_linear_pcm(mFormat)) {
Andy Hung936845a2021-06-08 00:09:06 -07009457 LOG_ALWAYS_FATAL_IF(mChannelCount > FCC_LIMIT, "HAL channel count %d > %d",
9458 mChannelCount, FCC_LIMIT);
Mikhail Naganovce9f2652018-07-16 11:09:24 -07009459 } else {
Andy Hung936845a2021-06-08 00:09:06 -07009460 // Can have more that FCC_LIMIT channels in encoded streams.
Mikhail Naganovce9f2652018-07-16 11:09:24 -07009461 ALOGI("HAL format %#x is not linear pcm", mFormat);
9462 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009463 result = mInput->stream->getFrameSize(&mFrameSize);
9464 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
Hayden Gomes1a89ab32020-06-12 11:05:47 -07009465 LOG_ALWAYS_FATAL_IF(mFrameSize <= 0, "Error frame size was %zu but must be greater than zero",
9466 mFrameSize);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009467 result = mInput->stream->getBufferSize(&mBufferSize);
9468 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
Glenn Kasten548efc92012-11-29 08:48:51 -08009469 mFrameCount = mBufferSize / mFrameSize;
Hayden Gomes1a89ab32020-06-12 11:05:47 -07009470 ALOGV("%p RecordThread params: mChannelCount=%u, mFormat=%#x, mFrameSize=%zu, "
9471 "mBufferSize=%zu, mFrameCount=%zu",
9472 this, mChannelCount, mFormat, mFrameSize, mBufferSize, mFrameCount);
Glenn Kasten49d00ad2014-07-21 11:22:03 -07009473
Eric Laurentec376dc2021-04-08 20:41:22 +02009474 // mRsmpInFrames must be 0 before calling resizeInputBuffer_l for the first time
9475 mRsmpInFrames = 0;
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009476 resizeInputBuffer_l(0 /*maxSharedAudioHistoryMs*/);
Eric Laurent81784c32012-11-19 14:55:58 -08009477
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08009478 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
9479 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Andy Hungea840382020-05-05 21:50:17 -07009480
9481 audio_input_flags_t flags = mInput->flags;
9482 mediametrics::LogItem item(mThreadMetrics.getMetricsId());
9483 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
9484 .set(AMEDIAMETRICS_PROP_ENCODING, formatToString(mFormat).c_str())
9485 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
9486 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
9487 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
9488 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
9489 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mFrameCount)
9490 .record();
Eric Laurent81784c32012-11-19 14:55:58 -08009491}
9492
Andy Hungee58e4a2023-07-07 13:47:37 -07009493uint32_t RecordThread::getInputFramesLost() const
Eric Laurent81784c32012-11-19 14:55:58 -08009494{
9495 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009496 uint32_t result;
9497 if (initCheck() == NO_ERROR && mInput->stream->getInputFramesLost(&result) == OK) {
9498 return result;
Eric Laurent81784c32012-11-19 14:55:58 -08009499 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009500 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08009501}
9502
Andy Hungee58e4a2023-07-07 13:47:37 -07009503KeyedVector<audio_session_t, bool> RecordThread::sessionIds() const
Eric Laurent81784c32012-11-19 14:55:58 -08009504{
Glenn Kastend848eb42016-03-08 13:42:11 -08009505 KeyedVector<audio_session_t, bool> ids;
Eric Laurent81784c32012-11-19 14:55:58 -08009506 Mutex::Autolock _l(mLock);
9507 for (size_t j = 0; j < mTracks.size(); ++j) {
Andy Hung8d31fd22023-06-26 19:20:57 -07009508 sp<IAfRecordTrack> track = mTracks[j];
Glenn Kastend848eb42016-03-08 13:42:11 -08009509 audio_session_t sessionId = track->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08009510 if (ids.indexOfKey(sessionId) < 0) {
9511 ids.add(sessionId, true);
9512 }
9513 }
9514 return ids;
9515}
9516
Andy Hungee58e4a2023-07-07 13:47:37 -07009517AudioStreamIn* RecordThread::clearInput()
Eric Laurent81784c32012-11-19 14:55:58 -08009518{
9519 Mutex::Autolock _l(mLock);
9520 AudioStreamIn *input = mInput;
9521 mInput = NULL;
9522 return input;
9523}
9524
9525// this method must always be called either with ThreadBase mLock held or inside the thread loop
Andy Hungee58e4a2023-07-07 13:47:37 -07009526sp<StreamHalInterface> RecordThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08009527{
9528 if (mInput == NULL) {
9529 return NULL;
9530 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009531 return mInput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08009532}
9533
Andy Hungee58e4a2023-07-07 13:47:37 -07009534status_t RecordThread::addEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08009535{
Eric Laurent81784c32012-11-19 14:55:58 -08009536 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurentaaa44472014-09-12 17:41:50 -07009537 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08009538 chain->setInBuffer(NULL);
9539 chain->setOutBuffer(NULL);
9540
9541 checkSuspendOnAddEffectChain_l(chain);
9542
Eric Laurent1b928682014-10-02 19:41:47 -07009543 // make sure enabled pre processing effects state is communicated to the HAL as we
9544 // just moved them to a new input stream.
9545 chain->syncHalEffectsState();
9546
Eric Laurent81784c32012-11-19 14:55:58 -08009547 mEffectChains.add(chain);
9548
9549 return NO_ERROR;
9550}
9551
Andy Hungee58e4a2023-07-07 13:47:37 -07009552size_t RecordThread::removeEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08009553{
9554 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
Eric Laurentb20cf7d2019-04-05 19:37:34 -07009555
9556 for (size_t i = 0; i < mEffectChains.size(); i++) {
9557 if (chain == mEffectChains[i]) {
9558 mEffectChains.removeAt(i);
9559 break;
9560 }
Eric Laurent81784c32012-11-19 14:55:58 -08009561 }
Eric Laurentb20cf7d2019-04-05 19:37:34 -07009562 return mEffectChains.size();
Eric Laurent81784c32012-11-19 14:55:58 -08009563}
9564
Andy Hungee58e4a2023-07-07 13:47:37 -07009565status_t RecordThread::createAudioPatch_l(const struct audio_patch* patch,
Eric Laurent1c333e22014-05-20 10:48:17 -07009566 audio_patch_handle_t *handle)
9567{
9568 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07009569
9570 // store new device and send to effects
jiabinc52b1ff2019-10-31 17:20:42 -07009571 mInDeviceTypeAddr.mType = patch->sources[0].ext.device.type;
jiabin0a488932020-08-07 17:32:40 -07009572 mInDeviceTypeAddr.setAddress(patch->sources[0].ext.device.address);
François Gaffie0c280aa2018-07-25 10:02:15 +02009573 audio_port_handle_t deviceId = patch->sources[0].id;
Eric Laurent054d9d32015-04-24 08:48:48 -07009574 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08009575 mEffectChains[i]->setInputDevice_l(inDeviceTypeAddr());
Eric Laurent054d9d32015-04-24 08:48:48 -07009576 }
9577
Eric Laurentd8365c52017-07-16 15:27:05 -07009578 checkBtNrec_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07009579
9580 // store new source and send to effects
9581 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
9582 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent1c333e22014-05-20 10:48:17 -07009583 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent054d9d32015-04-24 08:48:48 -07009584 mEffectChains[i]->setAudioSource_l(mAudioSource);
Eric Laurent1c333e22014-05-20 10:48:17 -07009585 }
Eric Laurent054d9d32015-04-24 08:48:48 -07009586 }
Eric Laurent1c333e22014-05-20 10:48:17 -07009587
Mikhail Naganov9ee05402016-10-13 15:58:17 -07009588 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07009589 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
9590 status = hwDevice->createAudioPatch(patch->num_sources,
9591 patch->sources,
9592 patch->num_sinks,
9593 patch->sinks,
9594 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07009595 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08009596 status = mInput->stream->legacyCreateAudioPatch(patch->sources[0],
9597 patch->sinks[0].ext.mix.usecase.source,
9598 patch->sources[0].ext.device.type);
Eric Laurent054d9d32015-04-24 08:48:48 -07009599 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07009600 }
Eric Laurent054d9d32015-04-24 08:48:48 -07009601
jiabinc52b1ff2019-10-31 17:20:42 -07009602 if ((mPatch.num_sources == 0) || (mPatch.sources[0].id != deviceId)) {
Eric Laurente8726fe2015-06-26 09:39:24 -07009603 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
jiabinc52b1ff2019-10-31 17:20:42 -07009604 mPatch = *patch;
Eric Laurente8726fe2015-06-26 09:39:24 -07009605 }
Eric Laurent296fb132015-05-01 11:38:42 -07009606
Andy Hungc2b11cb2020-04-22 09:04:01 -07009607 const std::string pathSourcesAsString = patchSourcesToString(patch);
Andy Hungcf10d742020-04-28 15:38:24 -07009608 mThreadMetrics.logEndInterval();
Andy Hungea840382020-05-05 21:50:17 -07009609 mThreadMetrics.logCreatePatch(pathSourcesAsString, /* outDevices */ {});
Andy Hungcf10d742020-04-28 15:38:24 -07009610 mThreadMetrics.logBeginInterval();
Andy Hungc2b11cb2020-04-22 09:04:01 -07009611 // also dispatch to active AudioRecords
9612 for (const auto &track : mActiveTracks) {
9613 track->logEndInterval();
9614 track->logBeginInterval(pathSourcesAsString);
9615 }
Eric Laurentdda206a2022-07-08 17:28:35 +02009616 // Force meteadata update after a route change
9617 mActiveTracks.setHasChanged();
9618
Eric Laurent1c333e22014-05-20 10:48:17 -07009619 return status;
9620}
9621
Andy Hungee58e4a2023-07-07 13:47:37 -07009622status_t RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
Eric Laurent1c333e22014-05-20 10:48:17 -07009623{
9624 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07009625
jiabinc52b1ff2019-10-31 17:20:42 -07009626 mPatch = audio_patch{};
9627 mInDeviceTypeAddr.reset();
Eric Laurent054d9d32015-04-24 08:48:48 -07009628
Mikhail Naganov9ee05402016-10-13 15:58:17 -07009629 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07009630 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
9631 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07009632 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08009633 status = mInput->stream->legacyReleaseAudioPatch();
Eric Laurent1c333e22014-05-20 10:48:17 -07009634 }
Eric Laurentdda206a2022-07-08 17:28:35 +02009635 // Force meteadata update after a route change
9636 mActiveTracks.setHasChanged();
9637
Eric Laurent1c333e22014-05-20 10:48:17 -07009638 return status;
9639}
9640
Andy Hungee58e4a2023-07-07 13:47:37 -07009641void RecordThread::updateOutDevices(const DeviceDescriptorBaseVector& outDevices)
jiabinc52b1ff2019-10-31 17:20:42 -07009642{
wendy lin56aa82b2020-12-02 15:19:55 +08009643 Mutex::Autolock _l(mLock);
jiabinc52b1ff2019-10-31 17:20:42 -07009644 mOutDevices = outDevices;
9645 mOutDeviceTypeAddrs = deviceTypeAddrsFromDescriptors(mOutDevices);
9646 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08009647 mEffectChains[i]->setDevices_l(outDeviceTypeAddrs());
jiabinc52b1ff2019-10-31 17:20:42 -07009648 }
9649}
9650
Andy Hungee58e4a2023-07-07 13:47:37 -07009651int32_t RecordThread::getOldestFront_l()
Eric Laurentec376dc2021-04-08 20:41:22 +02009652{
9653 if (mTracks.size() == 0) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009654 return mRsmpInRear;
Eric Laurentec376dc2021-04-08 20:41:22 +02009655 }
Eric Laurent2407ce32021-04-26 14:56:03 +02009656 int32_t oldestFront = mRsmpInRear;
9657 int32_t maxFilled = 0;
Eric Laurentec376dc2021-04-08 20:41:22 +02009658 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07009659 int32_t front = mTracks[i]->resamplerBufferProvider()->getFront();
Eric Laurent2407ce32021-04-26 14:56:03 +02009660 int32_t filled;
Eric Laurent92d0a322021-07-16 15:32:33 +02009661 (void)__builtin_sub_overflow(mRsmpInRear, front, &filled);
Eric Laurent2407ce32021-04-26 14:56:03 +02009662 if (filled > maxFilled) {
9663 oldestFront = front;
9664 maxFilled = filled;
9665 }
Eric Laurentec376dc2021-04-08 20:41:22 +02009666 }
Andy Hung920f6572022-10-06 12:09:49 -07009667 if (maxFilled > static_cast<signed>(mRsmpInFrames)) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009668 (void)__builtin_sub_overflow(mRsmpInRear, mRsmpInFrames, &oldestFront);
9669 }
Eric Laurent2407ce32021-04-26 14:56:03 +02009670 return oldestFront;
Eric Laurentec376dc2021-04-08 20:41:22 +02009671}
9672
Andy Hungee58e4a2023-07-07 13:47:37 -07009673void RecordThread::updateFronts_l(int32_t offset)
Eric Laurentec376dc2021-04-08 20:41:22 +02009674{
9675 if (offset == 0) {
9676 return;
9677 }
9678 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07009679 int32_t front = mTracks[i]->resamplerBufferProvider()->getFront();
Eric Laurentec376dc2021-04-08 20:41:22 +02009680 front = audio_utils::safe_sub_overflow(front, offset);
Andy Hung8d31fd22023-06-26 19:20:57 -07009681 mTracks[i]->resamplerBufferProvider()->setFront(front);
Eric Laurentec376dc2021-04-08 20:41:22 +02009682 }
9683}
9684
Andy Hungee58e4a2023-07-07 13:47:37 -07009685void RecordThread::resizeInputBuffer_l(int32_t maxSharedAudioHistoryMs)
Eric Laurentec376dc2021-04-08 20:41:22 +02009686{
9687 // This is the formula for calculating the temporary buffer size.
9688 // With 7 HAL buffers, we can guarantee ability to down-sample the input by ratio of 6:1 to
9689 // 1 full output buffer, regardless of the alignment of the available input.
9690 // The value is somewhat arbitrary, and could probably be even larger.
9691 // A larger value should allow more old data to be read after a track calls start(),
9692 // without increasing latency.
9693 //
9694 // Note this is independent of the maximum downsampling ratio permitted for capture.
9695 size_t minRsmpInFrames = mFrameCount * 7;
9696
9697 // maxSharedAudioHistoryMs != 0 indicates a request to possibly make some part of the audio
9698 // capture history available to another client using the same session ID:
9699 // dimension the resampler input buffer accordingly.
9700
9701 // Get oldest client read position: getOldestFront_l() must be called before altering
9702 // mRsmpInRear, or mRsmpInFrames
9703 int32_t previousFront = getOldestFront_l();
9704 size_t previousRsmpInFramesP2 = mRsmpInFramesP2;
9705 int32_t previousRear = mRsmpInRear;
9706 mRsmpInRear = 0;
9707
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009708 ALOG_ASSERT(maxSharedAudioHistoryMs >= 0
Andy Hungee58e4a2023-07-07 13:47:37 -07009709 && maxSharedAudioHistoryMs <= kMaxSharedAudioHistoryMs,
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009710 "resizeInputBuffer_l() called with invalid max shared history %d",
9711 maxSharedAudioHistoryMs);
Eric Laurentec376dc2021-04-08 20:41:22 +02009712 if (maxSharedAudioHistoryMs != 0) {
9713 // resizeInputBuffer_l should never be called with a non zero shared history if the
9714 // buffer was not already allocated
9715 ALOG_ASSERT(mRsmpInBuffer != nullptr && mRsmpInFrames != 0,
9716 "resizeInputBuffer_l() called with shared history and unallocated buffer");
9717 size_t rsmpInFrames = (size_t)maxSharedAudioHistoryMs * mSampleRate / 1000;
9718 // never reduce resampler input buffer size
Eric Laurent92d0a322021-07-16 15:32:33 +02009719 if (rsmpInFrames <= mRsmpInFrames) {
Eric Laurentec376dc2021-04-08 20:41:22 +02009720 return;
9721 }
9722 mRsmpInFrames = rsmpInFrames;
9723 }
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009724 mMaxSharedAudioHistoryMs = maxSharedAudioHistoryMs;
Eric Laurentec376dc2021-04-08 20:41:22 +02009725 // Note: mRsmpInFrames is 0 when called with maxSharedAudioHistoryMs equals to 0 so it is always
9726 // initialized
9727 if (mRsmpInFrames < minRsmpInFrames) {
9728 mRsmpInFrames = minRsmpInFrames;
9729 }
9730 mRsmpInFramesP2 = roundup(mRsmpInFrames);
9731
9732 // TODO optimize audio capture buffer sizes ...
9733 // Here we calculate the size of the sliding buffer used as a source
9734 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
9735 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
9736 // be better to have it derived from the pipe depth in the long term.
9737 // The current value is higher than necessary. However it should not add to latency.
9738
9739 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
9740 mRsmpInFramesOA = mRsmpInFramesP2 + mFrameCount - 1;
9741
9742 void *rsmpInBuffer;
9743 (void)posix_memalign(&rsmpInBuffer, 32, mRsmpInFramesOA * mFrameSize);
9744 // if posix_memalign fails, will segv here.
9745 memset(rsmpInBuffer, 0, mRsmpInFramesOA * mFrameSize);
9746
9747 // Copy audio history if any from old buffer before freeing it
9748 if (previousRear != 0) {
9749 ALOG_ASSERT(mRsmpInBuffer != nullptr,
9750 "resizeInputBuffer_l() called with null buffer but frames already read from HAL");
9751
9752 ssize_t unread = audio_utils::safe_sub_overflow(previousRear, previousFront);
9753 previousFront &= previousRsmpInFramesP2 - 1;
9754 size_t part1 = previousRsmpInFramesP2 - previousFront;
9755 if (part1 > (size_t) unread) {
9756 part1 = unread;
9757 }
9758 if (part1 != 0) {
9759 memcpy(rsmpInBuffer, (const uint8_t*)mRsmpInBuffer + previousFront * mFrameSize,
9760 part1 * mFrameSize);
9761 mRsmpInRear = part1;
9762 part1 = unread - part1;
9763 if (part1 != 0) {
9764 memcpy((uint8_t*)rsmpInBuffer + mRsmpInRear * mFrameSize,
9765 (const uint8_t*)mRsmpInBuffer, part1 * mFrameSize);
9766 mRsmpInRear += part1;
9767 }
9768 }
9769 // Update front for all clients according to new rear
9770 updateFronts_l(audio_utils::safe_sub_overflow(previousRear, mRsmpInRear));
9771 } else {
9772 mRsmpInRear = 0;
9773 }
9774 free(mRsmpInBuffer);
9775 mRsmpInBuffer = rsmpInBuffer;
9776}
9777
Andy Hungee58e4a2023-07-07 13:47:37 -07009778void RecordThread::addPatchTrack(const sp<IAfPatchRecord>& record)
Eric Laurent83b88082014-06-20 18:31:16 -07009779{
9780 Mutex::Autolock _l(mLock);
9781 mTracks.add(record);
Mikhail Naganov2534b382019-09-25 13:05:02 -07009782 if (record->getSource()) {
9783 mSource = record->getSource();
9784 }
Eric Laurent83b88082014-06-20 18:31:16 -07009785}
9786
Andy Hungee58e4a2023-07-07 13:47:37 -07009787void RecordThread::deletePatchTrack(const sp<IAfPatchRecord>& record)
Eric Laurent83b88082014-06-20 18:31:16 -07009788{
9789 Mutex::Autolock _l(mLock);
Mikhail Naganov2534b382019-09-25 13:05:02 -07009790 if (mSource == record->getSource()) {
9791 mSource = mInput;
9792 }
Eric Laurent83b88082014-06-20 18:31:16 -07009793 destroyTrack_l(record);
9794}
9795
Andy Hungee58e4a2023-07-07 13:47:37 -07009796void RecordThread::toAudioPortConfig(struct audio_port_config* config)
Eric Laurent83b88082014-06-20 18:31:16 -07009797{
Mikhail Naganovdc769682018-05-04 15:34:08 -07009798 ThreadBase::toAudioPortConfig(config);
Eric Laurent83b88082014-06-20 18:31:16 -07009799 config->role = AUDIO_PORT_ROLE_SINK;
9800 config->ext.mix.hw_module = mInput->audioHwDev->handle();
9801 config->ext.mix.usecase.source = mAudioSource;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07009802 if (mInput && mInput->flags != AUDIO_INPUT_FLAG_NONE) {
9803 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
9804 config->flags.input = mInput->flags;
9805 }
Eric Laurent83b88082014-06-20 18:31:16 -07009806}
Eric Laurent1c333e22014-05-20 10:48:17 -07009807
Eric Laurent6acd1d42017-01-04 14:23:29 -08009808// ----------------------------------------------------------------------------
9809// Mmap
9810// ----------------------------------------------------------------------------
9811
Andy Hung7aa7d102023-07-07 15:58:48 -07009812// Mmap stream control interface implementation. Each MmapThreadHandle controls one
9813// MmapPlaybackThread or MmapCaptureThread instance.
9814class MmapThreadHandle : public MmapStreamInterface {
9815public:
9816 explicit MmapThreadHandle(const sp<IAfMmapThread>& thread);
9817 ~MmapThreadHandle() override;
9818
9819 // MmapStreamInterface virtuals
9820 status_t createMmapBuffer(int32_t minSizeFrames,
9821 struct audio_mmap_buffer_info* info) final;
9822 status_t getMmapPosition(struct audio_mmap_position* position) final;
9823 status_t getExternalPosition(uint64_t* position, int64_t* timeNanos) final;
9824 status_t start(const AudioClient& client,
9825 const audio_attributes_t* attr, audio_port_handle_t* handle) final;
9826 status_t stop(audio_port_handle_t handle) final;
9827 status_t standby() final;
9828 status_t reportData(const void* buffer, size_t frameCount) final;
9829private:
9830 const sp<IAfMmapThread> mThread;
9831};
9832
9833/* static */
9834sp<MmapStreamInterface> IAfMmapThread::createMmapStreamInterfaceAdapter(
9835 const sp<IAfMmapThread>& mmapThread) {
9836 return sp<MmapThreadHandle>::make(mmapThread);
9837}
9838
9839MmapThreadHandle::MmapThreadHandle(const sp<IAfMmapThread>& thread)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009840 : mThread(thread)
9841{
Phil Burk9fabbf82017-08-03 12:02:00 -07009842 assert(thread != 0); // thread must start non-null and stay non-null
Eric Laurent6acd1d42017-01-04 14:23:29 -08009843}
9844
Andy Hung7aa7d102023-07-07 15:58:48 -07009845// MmapStreamInterface could be directly implemented by MmapThread excepting this
9846// special handling on adapter dtor.
9847MmapThreadHandle::~MmapThreadHandle()
Eric Laurent6acd1d42017-01-04 14:23:29 -08009848{
Phil Burk9fabbf82017-08-03 12:02:00 -07009849 mThread->disconnect();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009850}
9851
Andy Hung7aa7d102023-07-07 15:58:48 -07009852status_t MmapThreadHandle::createMmapBuffer(int32_t minSizeFrames,
Eric Laurent6acd1d42017-01-04 14:23:29 -08009853 struct audio_mmap_buffer_info *info)
9854{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009855 return mThread->createMmapBuffer(minSizeFrames, info);
9856}
9857
Andy Hung7aa7d102023-07-07 15:58:48 -07009858status_t MmapThreadHandle::getMmapPosition(struct audio_mmap_position* position)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009859{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009860 return mThread->getMmapPosition(position);
9861}
9862
Andy Hung7aa7d102023-07-07 15:58:48 -07009863status_t MmapThreadHandle::getExternalPosition(uint64_t* position,
jiabinb7d8c5a2020-08-26 17:24:52 -07009864 int64_t *timeNanos) {
9865 return mThread->getExternalPosition(position, timeNanos);
9866}
9867
Andy Hung7aa7d102023-07-07 15:58:48 -07009868status_t MmapThreadHandle::start(const AudioClient& client,
jiabind1f1cb62020-03-24 11:57:57 -07009869 const audio_attributes_t *attr, audio_port_handle_t *handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009870{
jiabind1f1cb62020-03-24 11:57:57 -07009871 return mThread->start(client, attr, handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009872}
9873
Andy Hung7aa7d102023-07-07 15:58:48 -07009874status_t MmapThreadHandle::stop(audio_port_handle_t handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009875{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009876 return mThread->stop(handle);
9877}
9878
Andy Hung7aa7d102023-07-07 15:58:48 -07009879status_t MmapThreadHandle::standby()
Eric Laurent18b57012017-02-13 16:23:52 -08009880{
Eric Laurent18b57012017-02-13 16:23:52 -08009881 return mThread->standby();
9882}
9883
Andy Hung7aa7d102023-07-07 15:58:48 -07009884status_t MmapThreadHandle::reportData(const void* buffer, size_t frameCount)
9885{
jiabinfc791ee2023-02-15 19:43:40 +00009886 return mThread->reportData(buffer, frameCount);
9887}
9888
Eric Laurent6acd1d42017-01-04 14:23:29 -08009889
Andy Hungee58e4a2023-07-07 13:47:37 -07009890MmapThread::MmapThread(
Andy Hung583043b2023-07-17 17:05:00 -07009891 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
Andy Hung920f6572022-10-06 12:09:49 -07009892 AudioHwDevice *hwDev, const sp<StreamHalInterface>& stream, bool systemReady, bool isOut)
Andy Hung583043b2023-07-17 17:05:00 -07009893 : ThreadBase(afThreadCallback, id, (isOut ? MMAP_PLAYBACK : MMAP_CAPTURE), systemReady, isOut),
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009894 mSessionId(AUDIO_SESSION_NONE),
François Gaffie0c280aa2018-07-25 10:02:15 +02009895 mPortId(AUDIO_PORT_HANDLE_NONE),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009896 mHalStream(stream), mHalDevice(hwDev->hwDevice()), mAudioHwDev(hwDev),
Eric Laurent67f97292018-04-20 18:05:41 -07009897 mActiveTracks(&this->mLocalLog),
9898 mHalVolFloat(-1.0f), // Initialize to illegal value so it always gets set properly later.
9899 mNoCallbackWarningCount(0)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009900{
Eric Laurent18b57012017-02-13 16:23:52 -08009901 mStandby = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009902 readHalParameters_l();
9903}
9904
Andy Hungee58e4a2023-07-07 13:47:37 -07009905void MmapThread::onFirstRef()
Eric Laurent6acd1d42017-01-04 14:23:29 -08009906{
9907 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
9908}
9909
Andy Hungee58e4a2023-07-07 13:47:37 -07009910void MmapThread::disconnect()
Eric Laurent6acd1d42017-01-04 14:23:29 -08009911{
Andy Hung8d31fd22023-06-26 19:20:57 -07009912 ActiveTracks<IAfMmapTrack> activeTracks;
Eric Laurent331679c2018-04-16 17:03:16 -07009913 {
9914 Mutex::Autolock _l(mLock);
Andy Hung8d31fd22023-06-26 19:20:57 -07009915 for (const sp<IAfMmapTrack>& t : mActiveTracks) {
Eric Laurent331679c2018-04-16 17:03:16 -07009916 activeTracks.add(t);
9917 }
9918 }
Andy Hung8d31fd22023-06-26 19:20:57 -07009919 for (const sp<IAfMmapTrack>& t : activeTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08009920 stop(t->portId());
9921 }
Phil Burk9fabbf82017-08-03 12:02:00 -07009922 // This will decrement references and may cause the destruction of this thread.
Eric Laurent6acd1d42017-01-04 14:23:29 -08009923 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07009924 AudioSystem::releaseOutput(mPortId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009925 } else {
Eric Laurentfee19762018-01-29 18:44:13 -08009926 AudioSystem::releaseInput(mPortId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009927 }
9928}
9929
9930
Andy Hungee58e4a2023-07-07 13:47:37 -07009931void MmapThread::configure(const audio_attributes_t* attr,
Eric Laurent6acd1d42017-01-04 14:23:29 -08009932 audio_stream_type_t streamType __unused,
9933 audio_session_t sessionId,
9934 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009935 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -08009936 audio_port_handle_t portId)
9937{
9938 mAttr = *attr;
9939 mSessionId = sessionId;
9940 mCallback = callback;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009941 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009942 mPortId = portId;
9943}
9944
Andy Hungee58e4a2023-07-07 13:47:37 -07009945status_t MmapThread::createMmapBuffer(int32_t minSizeFrames,
Eric Laurent6acd1d42017-01-04 14:23:29 -08009946 struct audio_mmap_buffer_info *info)
9947{
9948 if (mHalStream == 0) {
9949 return NO_INIT;
9950 }
Eric Laurent18b57012017-02-13 16:23:52 -08009951 mStandby = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009952 return mHalStream->createMmapBuffer(minSizeFrames, info);
9953}
9954
Andy Hungee58e4a2023-07-07 13:47:37 -07009955status_t MmapThread::getMmapPosition(struct audio_mmap_position* position) const
Eric Laurent6acd1d42017-01-04 14:23:29 -08009956{
9957 if (mHalStream == 0) {
9958 return NO_INIT;
9959 }
9960 return mHalStream->getMmapPosition(position);
9961}
9962
Andy Hungee58e4a2023-07-07 13:47:37 -07009963status_t MmapThread::exitStandby_l()
Eric Laurent331679c2018-04-16 17:03:16 -07009964{
Eric Laurentdda206a2022-07-08 17:28:35 +02009965 // The HAL must receive track metadata before starting the stream
9966 updateMetadata_l();
Eric Laurent331679c2018-04-16 17:03:16 -07009967 status_t ret = mHalStream->start();
9968 if (ret != NO_ERROR) {
9969 ALOGE("%s: error mHalStream->start() = %d for first track", __FUNCTION__, ret);
9970 return ret;
9971 }
Andy Hungcf10d742020-04-28 15:38:24 -07009972 if (mStandby) {
9973 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07009974 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -07009975 mStandby = false;
9976 }
Eric Laurent331679c2018-04-16 17:03:16 -07009977 return NO_ERROR;
9978}
9979
Andy Hungee58e4a2023-07-07 13:47:37 -07009980status_t MmapThread::start(const AudioClient& client,
jiabind1f1cb62020-03-24 11:57:57 -07009981 const audio_attributes_t *attr,
Eric Laurent6acd1d42017-01-04 14:23:29 -08009982 audio_port_handle_t *handle)
9983{
Eric Laurenta54f1282017-07-01 19:39:32 -07009984 ALOGV("%s clientUid %d mStandby %d mPortId %d *handle %d", __FUNCTION__,
Svet Ganov33761132021-05-13 22:51:08 +00009985 client.attributionSource.uid, mStandby, mPortId, *handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009986 if (mHalStream == 0) {
9987 return NO_INIT;
9988 }
9989
9990 status_t ret;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009991
Eric Laurentdda206a2022-07-08 17:28:35 +02009992 // For the first track, reuse portId and session allocated when the stream was opened.
Eric Laurenta54f1282017-07-01 19:39:32 -07009993 if (*handle == mPortId) {
Eric Laurentdda206a2022-07-08 17:28:35 +02009994 acquireWakeLock();
9995 return NO_ERROR;
Eric Laurenta54f1282017-07-01 19:39:32 -07009996 }
9997
9998 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
9999
10000 audio_io_handle_t io = mId;
Atneya Nairf59db5c2023-05-10 21:37:41 -070010001 AttributionSourceState adjAttributionSource = AudioFlinger::checkAttributionSourcePackage(
10002 client.attributionSource);
10003
Eric Laurenta54f1282017-07-01 19:39:32 -070010004 if (isOutput()) {
10005 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
10006 config.sample_rate = mSampleRate;
10007 config.channel_mask = mChannelMask;
10008 config.format = mFormat;
10009 audio_stream_type_t stream = streamType();
10010 audio_output_flags_t flags =
10011 (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010012 audio_port_handle_t deviceId = mDeviceId;
Kevin Rocard153f92d2018-12-18 18:33:28 -080010013 std::vector<audio_io_handle_t> secondaryOutputs;
Eric Laurentb0a7bc92022-04-05 15:06:08 +020010014 bool isSpatialized;
jiabinc658e452022-10-21 20:52:21 +000010015 bool isBitPerfect;
Eric Laurenta54f1282017-07-01 19:39:32 -070010016 ret = AudioSystem::getOutputForAttr(&mAttr, &io,
10017 mSessionId,
10018 &stream,
Atneya Nairf59db5c2023-05-10 21:37:41 -070010019 adjAttributionSource,
Eric Laurenta54f1282017-07-01 19:39:32 -070010020 &config,
10021 flags,
10022 &deviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -080010023 &portId,
Eric Laurentb0a7bc92022-04-05 15:06:08 +020010024 &secondaryOutputs,
jiabinc658e452022-10-21 20:52:21 +000010025 &isSpatialized,
10026 &isBitPerfect);
Kevin Rocard153f92d2018-12-18 18:33:28 -080010027 ALOGD_IF(!secondaryOutputs.empty(),
10028 "MmapThread::start does not support secondary outputs, ignoring them");
Eric Laurent6acd1d42017-01-04 14:23:29 -080010029 } else {
Eric Laurenta54f1282017-07-01 19:39:32 -070010030 audio_config_base_t config;
10031 config.sample_rate = mSampleRate;
10032 config.channel_mask = mChannelMask;
10033 config.format = mFormat;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010034 audio_port_handle_t deviceId = mDeviceId;
Eric Laurenta54f1282017-07-01 19:39:32 -070010035 ret = AudioSystem::getInputForAttr(&mAttr, &io,
Mikhail Naganov2996f672019-04-18 12:29:59 -070010036 RECORD_RIID_INVALID,
Eric Laurenta54f1282017-07-01 19:39:32 -070010037 mSessionId,
Atneya Nairf59db5c2023-05-10 21:37:41 -070010038 adjAttributionSource,
Eric Laurenta54f1282017-07-01 19:39:32 -070010039 &config,
10040 AUDIO_INPUT_FLAG_MMAP_NOIRQ,
10041 &deviceId,
10042 &portId);
10043 }
10044 // APM should not chose a different input or output stream for the same set of attributes
10045 // and audo configuration
10046 if (ret != NO_ERROR || io != mId) {
10047 ALOGE("%s: error getting output or input from APM (error %d, io %d expected io %d)",
10048 __FUNCTION__, ret, io, mId);
10049 return BAD_VALUE;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010050 }
10051
10052 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -070010053 ret = AudioSystem::startOutput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010054 } else {
jiabin09609032022-06-15 19:26:01 +000010055 {
10056 // Add the track record before starting input so that the silent status for the
10057 // client can be cached.
10058 Mutex::Autolock _l(mLock);
10059 setClientSilencedState_l(portId, false /*silenced*/);
10060 }
Eric Laurent4eb58f12018-12-07 16:41:02 -080010061 ret = AudioSystem::startInput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010062 }
10063
Eric Laurent331679c2018-04-16 17:03:16 -070010064 Mutex::Autolock _l(mLock);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010065 // abort if start is rejected by audio policy manager
10066 if (ret != NO_ERROR) {
Phil Burk7f6b40d2017-02-09 13:18:38 -080010067 ALOGE("%s: error start rejected by AudioPolicyManager = %d", __FUNCTION__, ret);
Eric Tan39ec8d62018-07-24 09:49:29 -070010068 if (!mActiveTracks.isEmpty()) {
Eric Laurent331679c2018-04-16 17:03:16 -070010069 mLock.unlock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010070 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -070010071 AudioSystem::releaseOutput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010072 } else {
Eric Laurentfee19762018-01-29 18:44:13 -080010073 AudioSystem::releaseInput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010074 }
Eric Laurent331679c2018-04-16 17:03:16 -070010075 mLock.lock();
Eric Laurent18b57012017-02-13 16:23:52 -080010076 } else {
10077 mHalStream->stop();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010078 }
jiabin09609032022-06-15 19:26:01 +000010079 eraseClientSilencedState_l(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010080 return PERMISSION_DENIED;
10081 }
10082
Kevin Rocard1f564ac2018-03-29 13:53:10 -070010083 // Given that MmapThread::mAttr is mutable, should a MmapTrack have attributes ?
Andy Hung8d31fd22023-06-26 19:20:57 -070010084 sp<IAfMmapTrack> track = IAfMmapTrack::create(
10085 this, attr == nullptr ? mAttr : *attr, mSampleRate, mFormat,
Svet Ganov33761132021-05-13 22:51:08 +000010086 mChannelMask, mSessionId, isOutput(),
10087 client.attributionSource,
Philip P. Moltmannbda45752020-07-17 16:41:18 -070010088 IPCThreadState::self()->getCallingPid(), portId);
jiabin09609032022-06-15 19:26:01 +000010089 if (!isOutput()) {
10090 track->setSilenced_l(isClientSilenced_l(portId));
10091 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010092
Eric Laurent4eb58f12018-12-07 16:41:02 -080010093 if (isOutput()) {
10094 // force volume update when a new track is added
10095 mHalVolFloat = -1.0f;
10096 } else if (!track->isSilenced_l()) {
Andy Hung8d31fd22023-06-26 19:20:57 -070010097 for (const sp<IAfMmapTrack>& t : mActiveTracks) {
Andy Hung920f6572022-10-06 12:09:49 -070010098 if (t->isSilenced_l()
10099 && t->uid() != static_cast<uid_t>(client.attributionSource.uid)) {
Eric Laurent4eb58f12018-12-07 16:41:02 -080010100 t->invalidate();
Andy Hung920f6572022-10-06 12:09:49 -070010101 }
Eric Laurent4eb58f12018-12-07 16:41:02 -080010102 }
10103 }
10104
Eric Laurent6acd1d42017-01-04 14:23:29 -080010105 mActiveTracks.add(track);
Andy Hung116bc262023-06-20 18:56:17 -070010106 sp<IAfEffectChain> chain = getEffectChain_l(mSessionId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010107 if (chain != 0) {
Eric Laurentd66d7a12021-07-13 13:35:32 +020010108 chain->setStrategy(getStrategyForStream(streamType()));
Eric Laurent6acd1d42017-01-04 14:23:29 -080010109 chain->incTrackCnt();
10110 chain->incActiveTrackCnt();
10111 }
10112
Andy Hungc2b11cb2020-04-22 09:04:01 -070010113 track->logBeginInterval(patchSinksToString(&mPatch)); // log to MediaMetrics
Eric Laurent6acd1d42017-01-04 14:23:29 -080010114 *handle = portId;
Eric Laurentdda206a2022-07-08 17:28:35 +020010115
10116 if (mActiveTracks.size() == 1) {
10117 ret = exitStandby_l();
10118 }
10119
Eric Laurent6acd1d42017-01-04 14:23:29 -080010120 broadcast_l();
10121
Eric Laurentdda206a2022-07-08 17:28:35 +020010122 ALOGV("%s DONE status %d handle %d stream %p", __FUNCTION__, ret, *handle, mHalStream.get());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010123
Eric Laurentdda206a2022-07-08 17:28:35 +020010124 return ret;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010125}
10126
Andy Hungee58e4a2023-07-07 13:47:37 -070010127status_t MmapThread::stop(audio_port_handle_t handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010128{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010129 ALOGV("%s handle %d", __FUNCTION__, handle);
10130
10131 if (mHalStream == 0) {
10132 return NO_INIT;
10133 }
10134
Eric Laurenta54f1282017-07-01 19:39:32 -070010135 if (handle == mPortId) {
Phil Burk98ab4082020-09-25 21:46:34 +000010136 releaseWakeLock();
Eric Laurenta54f1282017-07-01 19:39:32 -070010137 return NO_ERROR;
10138 }
10139
Eric Laurent331679c2018-04-16 17:03:16 -070010140 Mutex::Autolock _l(mLock);
10141
Andy Hung8d31fd22023-06-26 19:20:57 -070010142 sp<IAfMmapTrack> track;
10143 for (const sp<IAfMmapTrack>& t : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010144 if (handle == t->portId()) {
10145 track = t;
10146 break;
10147 }
10148 }
10149 if (track == 0) {
10150 return BAD_VALUE;
10151 }
10152
10153 mActiveTracks.remove(track);
jiabin09609032022-06-15 19:26:01 +000010154 eraseClientSilencedState_l(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010155
Eric Laurent331679c2018-04-16 17:03:16 -070010156 mLock.unlock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010157 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -070010158 AudioSystem::stopOutput(track->portId());
10159 AudioSystem::releaseOutput(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010160 } else {
Eric Laurentfee19762018-01-29 18:44:13 -080010161 AudioSystem::stopInput(track->portId());
10162 AudioSystem::releaseInput(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010163 }
Eric Laurent331679c2018-04-16 17:03:16 -070010164 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010165
Andy Hung116bc262023-06-20 18:56:17 -070010166 sp<IAfEffectChain> chain = getEffectChain_l(track->sessionId());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010167 if (chain != 0) {
10168 chain->decActiveTrackCnt();
10169 chain->decTrackCnt();
10170 }
10171
Eric Laurentdda206a2022-07-08 17:28:35 +020010172 if (mActiveTracks.isEmpty()) {
10173 mHalStream->stop();
10174 }
10175
Eric Laurent6acd1d42017-01-04 14:23:29 -080010176 broadcast_l();
10177
Eric Laurent6acd1d42017-01-04 14:23:29 -080010178 return NO_ERROR;
10179}
10180
Andy Hungee58e4a2023-07-07 13:47:37 -070010181status_t MmapThread::standby()
Eric Laurent18b57012017-02-13 16:23:52 -080010182{
10183 ALOGV("%s", __FUNCTION__);
10184
10185 if (mHalStream == 0) {
10186 return NO_INIT;
10187 }
Eric Tan39ec8d62018-07-24 09:49:29 -070010188 if (!mActiveTracks.isEmpty()) {
Eric Laurent18b57012017-02-13 16:23:52 -080010189 return INVALID_OPERATION;
10190 }
10191 mHalStream->standby();
Andy Hungcf10d742020-04-28 15:38:24 -070010192 if (!mStandby) {
10193 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -070010194 mThreadSnapshot.onEnd();
Andy Hungcf10d742020-04-28 15:38:24 -070010195 mStandby = true;
10196 }
Eric Laurent18b57012017-02-13 16:23:52 -080010197 releaseWakeLock();
10198 return NO_ERROR;
10199}
10200
Andy Hungee58e4a2023-07-07 13:47:37 -070010201status_t MmapThread::reportData(const void* /*buffer*/, size_t /*frameCount*/) {
jiabinfc791ee2023-02-15 19:43:40 +000010202 // This is a stub implementation. The MmapPlaybackThread overrides this function.
10203 return INVALID_OPERATION;
10204}
10205
Andy Hungee58e4a2023-07-07 13:47:37 -070010206void MmapThread::readHalParameters_l()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010207{
10208 status_t result = mHalStream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
10209 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
10210 mFormat = mHALFormat;
10211 LOG_ALWAYS_FATAL_IF(!audio_is_linear_pcm(mFormat), "HAL format %#x is not linear pcm", mFormat);
10212 result = mHalStream->getFrameSize(&mFrameSize);
10213 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
Hayden Gomes1a89ab32020-06-12 11:05:47 -070010214 LOG_ALWAYS_FATAL_IF(mFrameSize <= 0, "Error frame size was %zu but must be greater than zero",
10215 mFrameSize);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010216 result = mHalStream->getBufferSize(&mBufferSize);
10217 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
10218 mFrameCount = mBufferSize / mFrameSize;
Andy Hungc2b11cb2020-04-22 09:04:01 -070010219
Andy Hungcf10d742020-04-28 15:38:24 -070010220 // TODO: make a readHalParameters call?
10221 mediametrics::LogItem item(mThreadMetrics.getMetricsId());
Andy Hungc2b11cb2020-04-22 09:04:01 -070010222 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
10223 .set(AMEDIAMETRICS_PROP_ENCODING, formatToString(mFormat).c_str())
10224 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
10225 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
10226 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
10227 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mFrameCount)
10228 /*
10229 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
10230 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELMASK,
10231 (int32_t)mHapticChannelMask)
10232 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELCOUNT,
10233 (int32_t)mHapticChannelCount)
10234 */
10235 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_ENCODING,
10236 formatToString(mHALFormat).c_str())
10237 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_FRAMECOUNT,
10238 (int32_t)mFrameCount) // sic - added HAL
10239 .record();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010240}
10241
Andy Hungee58e4a2023-07-07 13:47:37 -070010242bool MmapThread::threadLoop()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010243{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010244 checkSilentMode_l();
10245
10246 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
10247
10248 while (!exitPending())
10249 {
Andy Hung116bc262023-06-20 18:56:17 -070010250 Vector<sp<IAfEffectChain>> effectChains;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010251
Andy Hung13850be2019-03-14 11:33:09 -070010252 { // under Thread lock
10253 Mutex::Autolock _l(mLock);
10254
Eric Laurent6acd1d42017-01-04 14:23:29 -080010255 if (mSignalPending) {
10256 // A signal was raised while we were unlocked
10257 mSignalPending = false;
10258 } else {
10259 if (mConfigEvents.isEmpty()) {
10260 // we're about to wait, flush the binder command buffer
10261 IPCThreadState::self()->flushCommands();
10262
10263 if (exitPending()) {
10264 break;
10265 }
10266
Eric Laurent6acd1d42017-01-04 14:23:29 -080010267 // wait until we have something to do...
10268 ALOGV("%s going to sleep", myName.string());
10269 mWaitWorkCV.wait(mLock);
10270 ALOGV("%s waking up", myName.string());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010271
10272 checkSilentMode_l();
10273
10274 continue;
10275 }
10276 }
10277
10278 processConfigEvents_l();
10279
10280 processVolume_l();
10281
10282 checkInvalidTracks_l();
10283
10284 mActiveTracks.updatePowerState(this);
10285
Kevin Rocard069c2712018-03-29 19:09:14 -070010286 updateMetadata_l();
10287
Eric Laurent6acd1d42017-01-04 14:23:29 -080010288 lockEffectChains_l(effectChains);
Andy Hung13850be2019-03-14 11:33:09 -070010289 } // release Thread lock
10290
Eric Laurent6acd1d42017-01-04 14:23:29 -080010291 for (size_t i = 0; i < effectChains.size(); i ++) {
Andy Hung13850be2019-03-14 11:33:09 -070010292 effectChains[i]->process_l(); // Thread is not locked, but effect chain is locked
Eric Laurent6acd1d42017-01-04 14:23:29 -080010293 }
Andy Hung13850be2019-03-14 11:33:09 -070010294
10295 // enable changes in effect chain, including moving to another thread.
Eric Laurent6acd1d42017-01-04 14:23:29 -080010296 unlockEffectChains(effectChains);
10297 // Effect chains will be actually deleted here if they were removed from
10298 // mEffectChains list during mixing or effects processing
10299 }
10300
10301 threadLoop_exit();
10302
10303 if (!mStandby) {
10304 threadLoop_standby();
10305 mStandby = true;
10306 }
10307
Eric Laurent6acd1d42017-01-04 14:23:29 -080010308 ALOGV("Thread %p type %d exiting", this, mType);
10309 return false;
10310}
10311
10312// checkForNewParameter_l() must be called with ThreadBase::mLock held
Andy Hungee58e4a2023-07-07 13:47:37 -070010313bool MmapThread::checkForNewParameter_l(const String8& keyValuePair,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010314 status_t& status)
10315{
10316 AudioParameter param = AudioParameter(keyValuePair);
10317 int value;
Eric Laurente6e9a482017-07-25 19:26:02 -070010318 bool sendToHal = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010319 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -070010320 LOG_FATAL("Should not happen set routing device in MmapThread");
Eric Laurent6acd1d42017-01-04 14:23:29 -080010321 }
Eric Laurente6e9a482017-07-25 19:26:02 -070010322 if (sendToHal) {
10323 status = mHalStream->setParameters(keyValuePair);
10324 } else {
10325 status = NO_ERROR;
10326 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010327
10328 return false;
10329}
10330
Andy Hungee58e4a2023-07-07 13:47:37 -070010331String8 MmapThread::getParameters(const String8& keys)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010332{
10333 Mutex::Autolock _l(mLock);
10334 String8 out_s8;
10335 if (initCheck() == NO_ERROR && mHalStream->getParameters(keys, &out_s8) == OK) {
10336 return out_s8;
10337 }
Andy Hung920f6572022-10-06 12:09:49 -070010338 return {};
Eric Laurent6acd1d42017-01-04 14:23:29 -080010339}
10340
Andy Hungee58e4a2023-07-07 13:47:37 -070010341void MmapThread::ioConfigChanged(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -070010342 audio_port_handle_t portId __unused) {
Mikhail Naganov88536df2021-07-26 17:30:29 -070010343 sp<AudioIoDescriptor> desc;
10344 bool isInput = false;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010345 switch (event) {
10346 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -070010347 case AUDIO_INPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -080010348 case AUDIO_INPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -070010349 isInput = true;
10350 FALLTHROUGH_INTENDED;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010351 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -070010352 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -080010353 case AUDIO_OUTPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -070010354 desc = sp<AudioIoDescriptor>::make(mId, mPatch, isInput,
10355 mSampleRate, mFormat, mChannelMask, mFrameCount, mFrameCount);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010356 break;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010357 case AUDIO_INPUT_CLOSED:
10358 case AUDIO_OUTPUT_CLOSED:
10359 default:
Mikhail Naganov88536df2021-07-26 17:30:29 -070010360 desc = sp<AudioIoDescriptor>::make(mId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010361 break;
10362 }
Andy Hung583043b2023-07-17 17:05:00 -070010363 mAfThreadCallback->ioConfigChanged(event, desc, pid);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010364}
10365
Andy Hungee58e4a2023-07-07 13:47:37 -070010366status_t MmapThread::createAudioPatch_l(const struct audio_patch* patch,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010367 audio_patch_handle_t *handle)
Andy Hung920f6572022-10-06 12:09:49 -070010368NO_THREAD_SAFETY_ANALYSIS // elease and re-acquire mLock
Eric Laurent6acd1d42017-01-04 14:23:29 -080010369{
10370 status_t status = NO_ERROR;
10371
10372 // store new device and send to effects
10373 audio_devices_t type = AUDIO_DEVICE_NONE;
10374 audio_port_handle_t deviceId;
jiabinc52b1ff2019-10-31 17:20:42 -070010375 AudioDeviceTypeAddrVector sinkDeviceTypeAddrs;
10376 AudioDeviceTypeAddr sourceDeviceTypeAddr;
10377 uint32_t numDevices = 0;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010378 if (isOutput()) {
10379 for (unsigned int i = 0; i < patch->num_sinks; i++) {
jiabinc52b1ff2019-10-31 17:20:42 -070010380 LOG_ALWAYS_FATAL_IF(popcount(patch->sinks[i].ext.device.type) > 1
10381 && !mAudioHwDev->supportsAudioPatches(),
10382 "Enumerated device type(%#x) must not be used "
10383 "as it does not support audio patches",
10384 patch->sinks[i].ext.device.type);
Mikhail Naganov55773032020-10-01 15:08:13 -070010385 type = static_cast<audio_devices_t>(type | patch->sinks[i].ext.device.type);
Andy Hung920f6572022-10-06 12:09:49 -070010386 sinkDeviceTypeAddrs.emplace_back(patch->sinks[i].ext.device.type,
10387 patch->sinks[i].ext.device.address);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010388 }
10389 deviceId = patch->sinks[0].id;
jiabinc52b1ff2019-10-31 17:20:42 -070010390 numDevices = mPatch.num_sinks;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010391 } else {
10392 type = patch->sources[0].ext.device.type;
10393 deviceId = patch->sources[0].id;
jiabinc52b1ff2019-10-31 17:20:42 -070010394 numDevices = mPatch.num_sources;
10395 sourceDeviceTypeAddr.mType = patch->sources[0].ext.device.type;
jiabin0a488932020-08-07 17:32:40 -070010396 sourceDeviceTypeAddr.setAddress(patch->sources[0].ext.device.address);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010397 }
10398
10399 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -080010400 if (isOutput()) {
10401 mEffectChains[i]->setDevices_l(sinkDeviceTypeAddrs);
10402 } else {
10403 mEffectChains[i]->setInputDevice_l(sourceDeviceTypeAddr);
10404 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010405 }
10406
jiabinc52b1ff2019-10-31 17:20:42 -070010407 if (!isOutput()) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010408 // store new source and send to effects
10409 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
10410 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
10411 for (size_t i = 0; i < mEffectChains.size(); i++) {
10412 mEffectChains[i]->setAudioSource_l(mAudioSource);
10413 }
10414 }
10415 }
10416
10417 if (mAudioHwDev->supportsAudioPatches()) {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010418 status = mHalDevice->createAudioPatch(patch->num_sources, patch->sources, patch->num_sinks,
10419 patch->sinks, handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010420 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010421 audio_port_config port;
10422 std::optional<audio_source_t> source;
10423 if (isOutput()) {
10424 port = patch->sinks[0];
Eric Laurent6acd1d42017-01-04 14:23:29 -080010425 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010426 port = patch->sources[0];
10427 source = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010428 }
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010429 status = mHalStream->legacyCreateAudioPatch(port, source, type);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010430 *handle = AUDIO_PATCH_HANDLE_NONE;
10431 }
10432
jiabinc52b1ff2019-10-31 17:20:42 -070010433 if (numDevices == 0 || mDeviceId != deviceId) {
10434 if (isOutput()) {
10435 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
10436 mOutDeviceTypeAddrs = sinkDeviceTypeAddrs;
jiabin0a957d32020-04-29 10:56:20 -070010437 checkSilentMode_l();
jiabinc52b1ff2019-10-31 17:20:42 -070010438 } else {
10439 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
10440 mInDeviceTypeAddr = sourceDeviceTypeAddr;
10441 }
Phil Burk7f6b40d2017-02-09 13:18:38 -080010442 sp<MmapStreamCallback> callback = mCallback.promote();
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010443 if (mDeviceId != deviceId && callback != 0) {
Eric Laurent734046e2018-04-16 14:50:52 -070010444 mLock.unlock();
Phil Burk7f6b40d2017-02-09 13:18:38 -080010445 callback->onRoutingChanged(deviceId);
Eric Laurent734046e2018-04-16 14:50:52 -070010446 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010447 }
jiabinc52b1ff2019-10-31 17:20:42 -070010448 mPatch = *patch;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010449 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010450 }
Eric Laurentdda206a2022-07-08 17:28:35 +020010451 // Force meteadata update after a route change
10452 mActiveTracks.setHasChanged();
10453
Eric Laurent6acd1d42017-01-04 14:23:29 -080010454 return status;
10455}
10456
Andy Hungee58e4a2023-07-07 13:47:37 -070010457status_t MmapThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010458{
10459 status_t status = NO_ERROR;
10460
jiabinc52b1ff2019-10-31 17:20:42 -070010461 mPatch = audio_patch{};
10462 mOutDeviceTypeAddrs.clear();
10463 mInDeviceTypeAddr.reset();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010464
10465 bool supportsAudioPatches = mHalDevice->supportsAudioPatches(&supportsAudioPatches) == OK ?
10466 supportsAudioPatches : false;
10467
10468 if (supportsAudioPatches) {
10469 status = mHalDevice->releaseAudioPatch(handle);
10470 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010471 status = mHalStream->legacyReleaseAudioPatch();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010472 }
Eric Laurentdda206a2022-07-08 17:28:35 +020010473 // Force meteadata update after a route change
10474 mActiveTracks.setHasChanged();
10475
Eric Laurent6acd1d42017-01-04 14:23:29 -080010476 return status;
10477}
10478
Andy Hungee58e4a2023-07-07 13:47:37 -070010479void MmapThread::toAudioPortConfig(struct audio_port_config* config)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010480{
Mikhail Naganovdc769682018-05-04 15:34:08 -070010481 ThreadBase::toAudioPortConfig(config);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010482 if (isOutput()) {
10483 config->role = AUDIO_PORT_ROLE_SOURCE;
10484 config->ext.mix.hw_module = mAudioHwDev->handle();
10485 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
10486 } else {
10487 config->role = AUDIO_PORT_ROLE_SINK;
10488 config->ext.mix.hw_module = mAudioHwDev->handle();
10489 config->ext.mix.usecase.source = mAudioSource;
10490 }
10491}
10492
Andy Hungee58e4a2023-07-07 13:47:37 -070010493status_t MmapThread::addEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010494{
10495 audio_session_t session = chain->sessionId();
10496
10497 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
10498 // Attach all tracks with same session ID to this chain.
10499 // indicate all active tracks in the chain
Andy Hung8d31fd22023-06-26 19:20:57 -070010500 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010501 if (session == track->sessionId()) {
10502 chain->incTrackCnt();
10503 chain->incActiveTrackCnt();
10504 }
10505 }
10506
10507 chain->setThread(this);
10508 chain->setInBuffer(nullptr);
10509 chain->setOutBuffer(nullptr);
10510 chain->syncHalEffectsState();
10511
10512 mEffectChains.add(chain);
10513 checkSuspendOnAddEffectChain_l(chain);
10514 return NO_ERROR;
10515}
10516
Andy Hungee58e4a2023-07-07 13:47:37 -070010517size_t MmapThread::removeEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010518{
10519 audio_session_t session = chain->sessionId();
10520
10521 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
10522
10523 for (size_t i = 0; i < mEffectChains.size(); i++) {
10524 if (chain == mEffectChains[i]) {
10525 mEffectChains.removeAt(i);
10526 // detach all active tracks from the chain
10527 // detach all tracks with same session ID from this chain
Andy Hung8d31fd22023-06-26 19:20:57 -070010528 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010529 if (session == track->sessionId()) {
10530 chain->decActiveTrackCnt();
10531 chain->decTrackCnt();
10532 }
10533 }
10534 break;
10535 }
10536 }
10537 return mEffectChains.size();
10538}
10539
Andy Hungee58e4a2023-07-07 13:47:37 -070010540void MmapThread::threadLoop_standby()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010541{
10542 mHalStream->standby();
10543}
10544
Andy Hungee58e4a2023-07-07 13:47:37 -070010545void MmapThread::threadLoop_exit()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010546{
Phil Burk7dce7282017-09-27 13:51:41 -070010547 // Do not call callback->onTearDown() because it is redundant for thread exit
10548 // and because it can cause a recursive mutex lock on stop().
Eric Laurent6acd1d42017-01-04 14:23:29 -080010549}
10550
Andy Hungee58e4a2023-07-07 13:47:37 -070010551status_t MmapThread::setSyncEvent(const sp<SyncEvent>& /* event */)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010552{
10553 return BAD_VALUE;
10554}
10555
Andy Hungee58e4a2023-07-07 13:47:37 -070010556bool MmapThread::isValidSyncEvent(
10557 const sp<SyncEvent>& /* event */) const
Eric Laurent6acd1d42017-01-04 14:23:29 -080010558{
10559 return false;
10560}
10561
Andy Hungee58e4a2023-07-07 13:47:37 -070010562status_t MmapThread::checkEffectCompatibility_l(
Eric Laurent6acd1d42017-01-04 14:23:29 -080010563 const effect_descriptor_t *desc, audio_session_t sessionId)
10564{
10565 // No global effect sessions on mmap threads
Eric Laurent3f75a5b2019-11-12 15:55:51 -080010566 if (audio_is_global_session(sessionId)) {
10567 ALOGW("checkEffectCompatibility_l(): global effect %s on MMAP thread %s",
Eric Laurent6acd1d42017-01-04 14:23:29 -080010568 desc->name, mThreadName);
10569 return BAD_VALUE;
10570 }
10571
10572 if (!isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC)) {
10573 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on capture mmap thread",
10574 desc->name);
10575 return BAD_VALUE;
10576 }
10577 if (isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Glenn Kastend3bb6452016-12-05 18:14:37 -080010578 ALOGW("checkEffectCompatibility_l(): pre processing effect %s created on playback mmap "
10579 "thread", desc->name);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010580 return BAD_VALUE;
10581 }
10582
10583 // Only allow effects without processing load or latency
10584 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) != EFFECT_FLAG_NO_PROCESS) {
10585 return BAD_VALUE;
10586 }
10587
Andy Hung116bc262023-06-20 18:56:17 -070010588 if (IAfEffectModule::isHapticGenerator(&desc->type)) {
jiabineb3bda02020-06-30 14:07:03 -070010589 ALOGE("%s(): HapticGenerator is not supported for MmapThread", __func__);
10590 return BAD_VALUE;
10591 }
10592
Eric Laurent6acd1d42017-01-04 14:23:29 -080010593 return NO_ERROR;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010594}
10595
Andy Hungee58e4a2023-07-07 13:47:37 -070010596void MmapThread::checkInvalidTracks_l()
Andy Hung920f6572022-10-06 12:09:49 -070010597NO_THREAD_SAFETY_ANALYSIS // release and re-acquire mLock
Eric Laurent6acd1d42017-01-04 14:23:29 -080010598{
Eric Laurent039c24a2022-10-07 14:01:59 +020010599 sp<MmapStreamCallback> callback;
Andy Hung8d31fd22023-06-26 19:20:57 -070010600 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010601 if (track->isInvalid()) {
Eric Laurent039c24a2022-10-07 14:01:59 +020010602 callback = mCallback.promote();
10603 if (callback == nullptr && mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
10604 ALOGW("Could not notify MMAP stream tear down: no onRoutingChanged callback!");
10605 mNoCallbackWarningCount++;
10606 }
10607 break;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010608 }
10609 }
Eric Laurent039c24a2022-10-07 14:01:59 +020010610 if (callback != 0) {
10611 mLock.unlock();
10612 callback->onRoutingChanged(AUDIO_PORT_HANDLE_NONE);
10613 mLock.lock();
jiabindfa32482022-10-06 19:45:50 +000010614 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010615}
10616
Andy Hungee58e4a2023-07-07 13:47:37 -070010617void MmapThread::dumpInternals_l(int fd, const Vector<String16>& /* args */)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010618{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010619 dprintf(fd, " Attributes: content type %d usage %d source %d\n",
10620 mAttr.content_type, mAttr.usage, mAttr.source);
10621 dprintf(fd, " Session: %d port Id: %d\n", mSessionId, mPortId);
Eric Tan39ec8d62018-07-24 09:49:29 -070010622 if (mActiveTracks.isEmpty()) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010623 dprintf(fd, " No active clients\n");
10624 }
10625}
10626
Andy Hungee58e4a2023-07-07 13:47:37 -070010627void MmapThread::dumpTracks_l(int fd, const Vector<String16>& /* args */)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010628{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010629 String8 result;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010630 size_t numtracks = mActiveTracks.size();
Andy Hung2c6c3bb2017-06-16 14:01:45 -070010631 dprintf(fd, " %zu Tracks\n", numtracks);
10632 const char *prefix = " ";
Eric Laurent6acd1d42017-01-04 14:23:29 -080010633 if (numtracks) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -070010634 result.append(prefix);
Kevin Rocard5f2136e2018-05-11 22:03:00 -070010635 mActiveTracks[0]->appendDumpHeader(result);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010636 for (size_t i = 0; i < numtracks ; ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -070010637 sp<IAfMmapTrack> track = mActiveTracks[i];
Andy Hung2c6c3bb2017-06-16 14:01:45 -070010638 result.append(prefix);
10639 track->appendDump(result, true /* active */);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010640 }
10641 } else {
10642 dprintf(fd, "\n");
10643 }
10644 write(fd, result.string(), result.size());
10645}
10646
Andy Hungee58e4a2023-07-07 13:47:37 -070010647/* static */
10648sp<IAfMmapPlaybackThread> IAfMmapPlaybackThread::create(
Andy Hung583043b2023-07-17 17:05:00 -070010649 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
Andy Hungee58e4a2023-07-07 13:47:37 -070010650 AudioHwDevice* hwDev, AudioStreamOut* output, bool systemReady) {
Andy Hung583043b2023-07-17 17:05:00 -070010651 return sp<MmapPlaybackThread>::make(afThreadCallback, id, hwDev, output, systemReady);
Andy Hungee58e4a2023-07-07 13:47:37 -070010652}
10653
10654MmapPlaybackThread::MmapPlaybackThread(
Andy Hung583043b2023-07-17 17:05:00 -070010655 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
jiabinc52b1ff2019-10-31 17:20:42 -070010656 AudioHwDevice *hwDev, AudioStreamOut *output, bool systemReady)
Andy Hung583043b2023-07-17 17:05:00 -070010657 : MmapThread(afThreadCallback, id, hwDev, output->stream, systemReady, true /* isOut */),
Eric Laurent6acd1d42017-01-04 14:23:29 -080010658 mStreamType(AUDIO_STREAM_MUSIC),
Phil Burk56ecf3e2018-03-12 15:38:17 -070010659 mOutput(output)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010660{
10661 snprintf(mThreadName, kThreadNameLength, "AudioMmapOut_%X", id);
10662 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Andy Hung583043b2023-07-17 17:05:00 -070010663 mMasterVolume = afThreadCallback->masterVolume_l();
10664 mMasterMute = afThreadCallback->masterMute_l();
Eric Laurent1f9b5e62023-07-03 18:14:07 +020010665
10666 for (int i = AUDIO_STREAM_MIN; i < AUDIO_STREAM_FOR_POLICY_CNT; ++i) {
10667 const audio_stream_type_t stream{static_cast<audio_stream_type_t>(i)};
10668 mStreamTypes[stream].volume = 0.0f;
Andy Hung583043b2023-07-17 17:05:00 -070010669 mStreamTypes[stream].mute = mAfThreadCallback->streamMute_l(stream);
Eric Laurent1f9b5e62023-07-03 18:14:07 +020010670 }
10671 // Audio patch and call assistant volume are always max
10672 mStreamTypes[AUDIO_STREAM_PATCH].volume = 1.0f;
10673 mStreamTypes[AUDIO_STREAM_PATCH].mute = false;
10674 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].volume = 1.0f;
10675 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].mute = false;
10676
Eric Laurent6acd1d42017-01-04 14:23:29 -080010677 if (mAudioHwDev) {
10678 if (mAudioHwDev->canSetMasterVolume()) {
10679 mMasterVolume = 1.0;
10680 }
10681
10682 if (mAudioHwDev->canSetMasterMute()) {
10683 mMasterMute = false;
10684 }
10685 }
10686}
10687
Andy Hungee58e4a2023-07-07 13:47:37 -070010688void MmapPlaybackThread::configure(const audio_attributes_t* attr,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010689 audio_stream_type_t streamType,
10690 audio_session_t sessionId,
10691 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010692 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010693 audio_port_handle_t portId)
10694{
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010695 MmapThread::configure(attr, streamType, sessionId, callback, deviceId, portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010696 mStreamType = streamType;
10697}
10698
Andy Hungee58e4a2023-07-07 13:47:37 -070010699AudioStreamOut* MmapPlaybackThread::clearOutput()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010700{
10701 Mutex::Autolock _l(mLock);
10702 AudioStreamOut *output = mOutput;
10703 mOutput = NULL;
10704 return output;
10705}
10706
Andy Hungee58e4a2023-07-07 13:47:37 -070010707void MmapPlaybackThread::setMasterVolume(float value)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010708{
10709 Mutex::Autolock _l(mLock);
10710 // Don't apply master volume in SW if our HAL can do it for us.
10711 if (mAudioHwDev &&
10712 mAudioHwDev->canSetMasterVolume()) {
10713 mMasterVolume = 1.0;
10714 } else {
10715 mMasterVolume = value;
10716 }
10717}
10718
Andy Hungee58e4a2023-07-07 13:47:37 -070010719void MmapPlaybackThread::setMasterMute(bool muted)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010720{
10721 Mutex::Autolock _l(mLock);
10722 // Don't apply master mute in SW if our HAL can do it for us.
10723 if (mAudioHwDev && mAudioHwDev->canSetMasterMute()) {
10724 mMasterMute = false;
10725 } else {
10726 mMasterMute = muted;
10727 }
10728}
10729
Andy Hungee58e4a2023-07-07 13:47:37 -070010730void MmapPlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010731{
10732 Mutex::Autolock _l(mLock);
Eric Laurent1f9b5e62023-07-03 18:14:07 +020010733 mStreamTypes[stream].volume = value;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010734 if (stream == mStreamType) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010735 broadcast_l();
10736 }
10737}
10738
Andy Hungee58e4a2023-07-07 13:47:37 -070010739float MmapPlaybackThread::streamVolume(audio_stream_type_t stream) const
Eric Laurent6acd1d42017-01-04 14:23:29 -080010740{
10741 Mutex::Autolock _l(mLock);
Eric Laurent1f9b5e62023-07-03 18:14:07 +020010742 return mStreamTypes[stream].volume;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010743}
10744
Andy Hungee58e4a2023-07-07 13:47:37 -070010745void MmapPlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010746{
10747 Mutex::Autolock _l(mLock);
Eric Laurent1f9b5e62023-07-03 18:14:07 +020010748 mStreamTypes[stream].mute = muted;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010749 if (stream == mStreamType) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010750 broadcast_l();
10751 }
10752}
10753
Andy Hungee58e4a2023-07-07 13:47:37 -070010754void MmapPlaybackThread::invalidateTracks(audio_stream_type_t streamType)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010755{
10756 Mutex::Autolock _l(mLock);
10757 if (streamType == mStreamType) {
Andy Hung8d31fd22023-06-26 19:20:57 -070010758 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010759 track->invalidate();
10760 }
10761 broadcast_l();
10762 }
10763}
10764
Andy Hungee58e4a2023-07-07 13:47:37 -070010765void MmapPlaybackThread::invalidateTracks(std::set<audio_port_handle_t>& portIds)
jiabinc44b3462022-12-08 12:52:31 -080010766{
10767 Mutex::Autolock _l(mLock);
10768 bool trackMatch = false;
Andy Hung8d31fd22023-06-26 19:20:57 -070010769 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
jiabinc44b3462022-12-08 12:52:31 -080010770 if (portIds.find(track->portId()) != portIds.end()) {
10771 track->invalidate();
10772 trackMatch = true;
10773 portIds.erase(track->portId());
10774 }
10775 if (portIds.empty()) {
10776 break;
10777 }
10778 }
10779 if (trackMatch) {
10780 broadcast_l();
10781 }
10782}
10783
Andy Hungee58e4a2023-07-07 13:47:37 -070010784void MmapPlaybackThread::processVolume_l()
Andy Hung920f6572022-10-06 12:09:49 -070010785NO_THREAD_SAFETY_ANALYSIS // access of track->processMuteEvent_l
Eric Laurent6acd1d42017-01-04 14:23:29 -080010786{
10787 float volume;
10788
Eric Laurent1f9b5e62023-07-03 18:14:07 +020010789 if (mMasterMute || streamMuted_l()) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010790 volume = 0;
10791 } else {
Eric Laurent1f9b5e62023-07-03 18:14:07 +020010792 volume = mMasterVolume * streamVolume_l();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010793 }
10794
10795 if (volume != mHalVolFloat) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010796 // Convert volumes from float to 8.24
10797 uint32_t vol = (uint32_t)(volume * (1 << 24));
10798
10799 // Delegate volume control to effect in track effect chain if needed
10800 // only one effect chain can be present on DirectOutputThread, so if
10801 // there is one, the track is connected to it
10802 if (!mEffectChains.isEmpty()) {
10803 mEffectChains[0]->setVolume_l(&vol, &vol);
10804 volume = (float)vol / (1 << 24);
10805 }
Eric Laurentdff774a2017-04-21 15:29:38 -070010806 // Try to use HW volume control and fall back to SW control if not implemented
Phil Burk56ecf3e2018-03-12 15:38:17 -070010807 if (mOutput->stream->setVolume(volume, volume) == NO_ERROR) {
10808 mHalVolFloat = volume; // HW volume control worked, so update value.
10809 mNoCallbackWarningCount = 0;
10810 } else {
Eric Laurentdff774a2017-04-21 15:29:38 -070010811 sp<MmapStreamCallback> callback = mCallback.promote();
10812 if (callback != 0) {
Phil Burk56ecf3e2018-03-12 15:38:17 -070010813 mHalVolFloat = volume; // SW volume control worked, so update value.
10814 mNoCallbackWarningCount = 0;
Eric Laurent734046e2018-04-16 14:50:52 -070010815 mLock.unlock();
Robert Wu4389ae62022-02-17 18:39:41 +000010816 callback->onVolumeChanged(volume);
Eric Laurent734046e2018-04-16 14:50:52 -070010817 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010818 } else {
Phil Burk56ecf3e2018-03-12 15:38:17 -070010819 if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
10820 ALOGW("Could not set MMAP stream volume: no volume callback!");
10821 mNoCallbackWarningCount++;
10822 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010823 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010824 }
Andy Hung8d31fd22023-06-26 19:20:57 -070010825 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Jasmine Chaeaa10e42021-05-11 10:11:14 +080010826 track->setMetadataHasChanged();
Andy Hung583043b2023-07-17 17:05:00 -070010827 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
Vlad Popaec1788e2022-08-04 11:23:30 +020010828 /*muteState=*/{mMasterMute,
Eric Laurent1f9b5e62023-07-03 18:14:07 +020010829 streamVolume_l() == 0.f,
10830 streamMuted_l(),
Vlad Popaec1788e2022-08-04 11:23:30 +020010831 // TODO(b/241533526): adjust logic to include mute from AppOps
10832 false /*muteFromPlaybackRestricted*/,
10833 false /*muteFromClientVolume*/,
10834 false /*muteFromVolumeShaper*/});
Jasmine Chaeaa10e42021-05-11 10:11:14 +080010835 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010836 }
10837}
10838
Andy Hungee58e4a2023-07-07 13:47:37 -070010839ThreadBase::MetadataUpdate MmapPlaybackThread::updateMetadata_l()
Kevin Rocard069c2712018-03-29 19:09:14 -070010840{
Jasmine Chaeaa10e42021-05-11 10:11:14 +080010841 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
Vlad Popa7e81cea2023-01-19 16:34:16 +010010842 return {}; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -070010843 }
10844 StreamOutHalInterface::SourceMetadata metadata;
Andy Hung8d31fd22023-06-26 19:20:57 -070010845 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Kevin Rocard069c2712018-03-29 19:09:14 -070010846 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurent94579172020-11-20 18:41:04 +010010847 playback_track_metadata_v7_t trackMetadata;
10848 trackMetadata.base = {
Kevin Rocard069c2712018-03-29 19:09:14 -070010849 .usage = track->attributes().usage,
10850 .content_type = track->attributes().content_type,
10851 .gain = mHalVolFloat, // TODO: propagate from aaudio pre-mix volume
Eric Laurent94579172020-11-20 18:41:04 +010010852 };
10853 trackMetadata.channel_mask = track->channelMask(),
10854 strncpy(trackMetadata.tags, track->attributes().tags, AUDIO_ATTRIBUTES_TAGS_MAX_SIZE);
10855 metadata.tracks.push_back(trackMetadata);
Kevin Rocard069c2712018-03-29 19:09:14 -070010856 }
10857 mOutput->stream->updateSourceMetadata(metadata);
Vlad Popa7e81cea2023-01-19 16:34:16 +010010858
10859 MetadataUpdate change;
10860 change.playbackMetadataUpdate = metadata.tracks;
10861 return change;
10862};
Kevin Rocard069c2712018-03-29 19:09:14 -070010863
Andy Hungee58e4a2023-07-07 13:47:37 -070010864void MmapPlaybackThread::checkSilentMode_l()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010865{
10866 if (!mMasterMute) {
10867 char value[PROPERTY_VALUE_MAX];
10868 if (property_get("ro.audio.silent", value, "0") > 0) {
10869 char *endptr;
10870 unsigned long ul = strtoul(value, &endptr, 0);
10871 if (*endptr == '\0' && ul != 0) {
10872 ALOGD("Silence is golden");
10873 // The setprop command will not allow a property to be changed after
10874 // the first time it is set, so we don't have to worry about un-muting.
10875 setMasterMute_l(true);
10876 }
10877 }
10878 }
10879}
10880
Andy Hungee58e4a2023-07-07 13:47:37 -070010881void MmapPlaybackThread::toAudioPortConfig(struct audio_port_config* config)
Mikhail Naganov32abc2b2018-05-24 12:57:11 -070010882{
10883 MmapThread::toAudioPortConfig(config);
10884 if (mOutput && mOutput->flags != AUDIO_OUTPUT_FLAG_NONE) {
10885 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
10886 config->flags.output = mOutput->flags;
10887 }
10888}
10889
Andy Hungee58e4a2023-07-07 13:47:37 -070010890status_t MmapPlaybackThread::getExternalPosition(uint64_t* position,
Andy Hung440901d2023-06-29 21:19:25 -070010891 int64_t* timeNanos) const
jiabinb7d8c5a2020-08-26 17:24:52 -070010892{
10893 if (mOutput == nullptr) {
10894 return NO_INIT;
10895 }
10896 struct timespec timestamp;
10897 status_t status = mOutput->getPresentationPosition(position, &timestamp);
10898 if (status == NO_ERROR) {
10899 *timeNanos = timestamp.tv_sec * NANOS_PER_SECOND + timestamp.tv_nsec;
10900 }
10901 return status;
10902}
10903
Andy Hungee58e4a2023-07-07 13:47:37 -070010904status_t MmapPlaybackThread::reportData(const void* buffer, size_t frameCount) {
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010010905 // Send to MelProcessor for sound dose measurement.
10906 auto processor = mMelProcessor.load();
10907 if (processor) {
10908 processor->process(buffer, frameCount * mFrameSize);
10909 }
10910
jiabinfc791ee2023-02-15 19:43:40 +000010911 return NO_ERROR;
10912}
10913
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010010914// startMelComputation_l() must be called with AudioFlinger::mLock held
Andy Hungee58e4a2023-07-07 13:47:37 -070010915void MmapPlaybackThread::startMelComputation_l(
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010010916 const sp<audio_utils::MelProcessor>& processor)
10917{
10918 ALOGV("%s: starting mel processor for thread %d", __func__, id());
Vlad Popa1c2f7e12023-03-28 02:08:56 +020010919 mMelProcessor.store(processor);
10920 if (processor) {
10921 processor->resume();
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010010922 }
Vlad Popa1c2f7e12023-03-28 02:08:56 +020010923
10924 // no need to update output format for MMapPlaybackThread since it is
10925 // assigned constant for each thread
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010010926}
10927
10928// stopMelComputation_l() must be called with AudioFlinger::mLock held
Andy Hungee58e4a2023-07-07 13:47:37 -070010929void MmapPlaybackThread::stopMelComputation_l()
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010010930{
Vlad Popa1c2f7e12023-03-28 02:08:56 +020010931 ALOGV("%s: pausing mel processor for thread %d", __func__, id());
10932 auto melProcessor = mMelProcessor.load();
10933 if (melProcessor != nullptr) {
10934 melProcessor->pause();
10935 }
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010010936}
10937
Andy Hungee58e4a2023-07-07 13:47:37 -070010938void MmapPlaybackThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010939{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -070010940 MmapThread::dumpInternals_l(fd, args);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010941
Glenn Kastend3bb6452016-12-05 18:14:37 -080010942 dprintf(fd, " Stream type: %d Stream volume: %f HAL volume: %f Stream mute %d\n",
Eric Laurent1f9b5e62023-07-03 18:14:07 +020010943 mStreamType, streamVolume_l(), mHalVolFloat, streamMuted_l());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010944 dprintf(fd, " Master volume: %f Master mute %d\n", mMasterVolume, mMasterMute);
10945}
10946
Andy Hungee58e4a2023-07-07 13:47:37 -070010947/* static */
10948sp<IAfMmapCaptureThread> IAfMmapCaptureThread::create(
Andy Hung583043b2023-07-17 17:05:00 -070010949 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
Andy Hungee58e4a2023-07-07 13:47:37 -070010950 AudioHwDevice* hwDev, AudioStreamIn* input, bool systemReady) {
Andy Hung583043b2023-07-17 17:05:00 -070010951 return sp<MmapCaptureThread>::make(afThreadCallback, id, hwDev, input, systemReady);
Andy Hungee58e4a2023-07-07 13:47:37 -070010952}
10953
10954MmapCaptureThread::MmapCaptureThread(
Andy Hung583043b2023-07-17 17:05:00 -070010955 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
jiabinc52b1ff2019-10-31 17:20:42 -070010956 AudioHwDevice *hwDev, AudioStreamIn *input, bool systemReady)
Andy Hung583043b2023-07-17 17:05:00 -070010957 : MmapThread(afThreadCallback, id, hwDev, input->stream, systemReady, false /* isOut */),
Eric Laurent6acd1d42017-01-04 14:23:29 -080010958 mInput(input)
10959{
10960 snprintf(mThreadName, kThreadNameLength, "AudioMmapIn_%X", id);
10961 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
10962}
10963
Andy Hungee58e4a2023-07-07 13:47:37 -070010964status_t MmapCaptureThread::exitStandby_l()
Eric Laurent331679c2018-04-16 17:03:16 -070010965{
Phil Burkf054fc32018-12-06 09:45:59 -080010966 {
10967 // mInput might have been cleared by clearInput()
Phil Burkf054fc32018-12-06 09:45:59 -080010968 if (mInput != nullptr && mInput->stream != nullptr) {
10969 mInput->stream->setGain(1.0f);
10970 }
10971 }
Eric Laurentdda206a2022-07-08 17:28:35 +020010972 return MmapThread::exitStandby_l();
Eric Laurent331679c2018-04-16 17:03:16 -070010973}
10974
Andy Hungee58e4a2023-07-07 13:47:37 -070010975AudioStreamIn* MmapCaptureThread::clearInput()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010976{
10977 Mutex::Autolock _l(mLock);
10978 AudioStreamIn *input = mInput;
10979 mInput = NULL;
10980 return input;
10981}
Kevin Rocard069c2712018-03-29 19:09:14 -070010982
Andy Hungee58e4a2023-07-07 13:47:37 -070010983void MmapCaptureThread::processVolume_l()
Eric Laurent331679c2018-04-16 17:03:16 -070010984{
10985 bool changed = false;
10986 bool silenced = false;
10987
10988 sp<MmapStreamCallback> callback = mCallback.promote();
10989 if (callback == 0) {
10990 if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
10991 ALOGW("Could not set MMAP stream silenced: no onStreamSilenced callback!");
10992 mNoCallbackWarningCount++;
10993 }
10994 }
10995
10996 // After a change occurred in track silenced state, mute capture in audio DSP if at least one
10997 // track is silenced and unmute otherwise
10998 for (size_t i = 0; i < mActiveTracks.size() && !silenced; i++) {
10999 if (!mActiveTracks[i]->getAndSetSilencedNotified_l()) {
11000 changed = true;
11001 silenced = mActiveTracks[i]->isSilenced_l();
11002 }
11003 }
11004
11005 if (changed) {
11006 mInput->stream->setGain(silenced ? 0.0f: 1.0f);
11007 }
11008}
11009
Andy Hungee58e4a2023-07-07 13:47:37 -070011010ThreadBase::MetadataUpdate MmapCaptureThread::updateMetadata_l()
Kevin Rocard069c2712018-03-29 19:09:14 -070011011{
Jasmine Chaeaa10e42021-05-11 10:11:14 +080011012 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
Vlad Popa7e81cea2023-01-19 16:34:16 +010011013 return {}; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -070011014 }
11015 StreamInHalInterface::SinkMetadata metadata;
Andy Hung8d31fd22023-06-26 19:20:57 -070011016 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Kevin Rocard069c2712018-03-29 19:09:14 -070011017 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurent94579172020-11-20 18:41:04 +010011018 record_track_metadata_v7_t trackMetadata;
11019 trackMetadata.base = {
Kevin Rocard069c2712018-03-29 19:09:14 -070011020 .source = track->attributes().source,
11021 .gain = 1, // capture tracks do not have volumes
Eric Laurent94579172020-11-20 18:41:04 +010011022 };
11023 trackMetadata.channel_mask = track->channelMask(),
11024 strncpy(trackMetadata.tags, track->attributes().tags, AUDIO_ATTRIBUTES_TAGS_MAX_SIZE);
11025 metadata.tracks.push_back(trackMetadata);
Kevin Rocard069c2712018-03-29 19:09:14 -070011026 }
11027 mInput->stream->updateSinkMetadata(metadata);
Vlad Popa7e81cea2023-01-19 16:34:16 +010011028 MetadataUpdate change;
11029 change.recordMetadataUpdate = metadata.tracks;
11030 return change;
Kevin Rocard069c2712018-03-29 19:09:14 -070011031}
11032
Andy Hungee58e4a2023-07-07 13:47:37 -070011033void MmapCaptureThread::setRecordSilenced(audio_port_handle_t portId, bool silenced)
Eric Laurent331679c2018-04-16 17:03:16 -070011034{
11035 Mutex::Autolock _l(mLock);
11036 for (size_t i = 0; i < mActiveTracks.size() ; i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -070011037 if (mActiveTracks[i]->portId() == portId) {
Eric Laurent331679c2018-04-16 17:03:16 -070011038 mActiveTracks[i]->setSilenced_l(silenced);
11039 broadcast_l();
11040 }
11041 }
jiabin09609032022-06-15 19:26:01 +000011042 setClientSilencedIfExists_l(portId, silenced);
Eric Laurent331679c2018-04-16 17:03:16 -070011043}
11044
Andy Hungee58e4a2023-07-07 13:47:37 -070011045void MmapCaptureThread::toAudioPortConfig(struct audio_port_config* config)
Mikhail Naganov32abc2b2018-05-24 12:57:11 -070011046{
11047 MmapThread::toAudioPortConfig(config);
11048 if (mInput && mInput->flags != AUDIO_INPUT_FLAG_NONE) {
11049 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
11050 config->flags.input = mInput->flags;
11051 }
11052}
11053
Andy Hungee58e4a2023-07-07 13:47:37 -070011054status_t MmapCaptureThread::getExternalPosition(
Andy Hung440901d2023-06-29 21:19:25 -070011055 uint64_t* position, int64_t* timeNanos) const
jiabinb7d8c5a2020-08-26 17:24:52 -070011056{
11057 if (mInput == nullptr) {
11058 return NO_INIT;
11059 }
11060 return mInput->getCapturePosition((int64_t*)position, timeNanos);
11061}
11062
jiabinc658e452022-10-21 20:52:21 +000011063// ----------------------------------------------------------------------------
11064
Andy Hungee58e4a2023-07-07 13:47:37 -070011065/* static */
11066sp<IAfPlaybackThread> IAfPlaybackThread::createBitPerfectThread(
Andy Hung583043b2023-07-17 17:05:00 -070011067 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hungee58e4a2023-07-07 13:47:37 -070011068 AudioStreamOut* output, audio_io_handle_t id, bool systemReady) {
Andy Hung583043b2023-07-17 17:05:00 -070011069 return sp<BitPerfectThread>::make(afThreadCallback, output, id, systemReady);
Andy Hungee58e4a2023-07-07 13:47:37 -070011070}
11071
Andy Hung583043b2023-07-17 17:05:00 -070011072BitPerfectThread::BitPerfectThread(const sp<IAfThreadCallback> &afThreadCallback,
jiabinc658e452022-10-21 20:52:21 +000011073 AudioStreamOut *output, audio_io_handle_t id, bool systemReady)
Andy Hung583043b2023-07-17 17:05:00 -070011074 : MixerThread(afThreadCallback, output, id, systemReady, BIT_PERFECT) {}
jiabinc658e452022-10-21 20:52:21 +000011075
Andy Hungee58e4a2023-07-07 13:47:37 -070011076PlaybackThread::mixer_state BitPerfectThread::prepareTracks_l(
Andy Hung8d31fd22023-06-26 19:20:57 -070011077 Vector<sp<IAfTrack>>* tracksToRemove) {
jiabinc658e452022-10-21 20:52:21 +000011078 mixer_state result = MixerThread::prepareTracks_l(tracksToRemove);
11079 // If there is only one active track and it is bit-perfect, enable tee buffer.
jiabin76d94692022-12-15 21:51:21 +000011080 float volumeLeft = 1.0f;
11081 float volumeRight = 1.0f;
jiabinc658e452022-10-21 20:52:21 +000011082 if (mActiveTracks.size() == 1 && mActiveTracks[0]->isBitPerfect()) {
11083 const int trackId = mActiveTracks[0]->id();
11084 mAudioMixer->setParameter(
11085 trackId, AudioMixer::TRACK, AudioMixer::TEE_BUFFER, (void *)mSinkBuffer);
11086 mAudioMixer->setParameter(
11087 trackId, AudioMixer::TRACK, AudioMixer::TEE_BUFFER_FRAME_COUNT,
11088 (void *)(uintptr_t)mNormalFrameCount);
jiabin76d94692022-12-15 21:51:21 +000011089 mActiveTracks[0]->getFinalVolume(&volumeLeft, &volumeRight);
jiabinc658e452022-10-21 20:52:21 +000011090 mIsBitPerfect = true;
11091 } else {
11092 mIsBitPerfect = false;
11093 // No need to copy bit-perfect data directly to sink buffer given there are multiple tracks
11094 // active.
11095 for (const auto& track : mActiveTracks) {
11096 const int trackId = track->id();
11097 mAudioMixer->setParameter(
11098 trackId, AudioMixer::TRACK, AudioMixer::TEE_BUFFER, nullptr);
11099 }
11100 }
jiabin76d94692022-12-15 21:51:21 +000011101 if (mVolumeLeft != volumeLeft || mVolumeRight != volumeRight) {
11102 mVolumeLeft = volumeLeft;
11103 mVolumeRight = volumeRight;
11104 setVolumeForOutput_l(volumeLeft, volumeRight);
11105 }
jiabinc658e452022-10-21 20:52:21 +000011106 return result;
11107}
11108
Andy Hungee58e4a2023-07-07 13:47:37 -070011109void BitPerfectThread::threadLoop_mix() {
jiabinc658e452022-10-21 20:52:21 +000011110 MixerThread::threadLoop_mix();
11111 mHasDataCopiedToSinkBuffer = mIsBitPerfect;
11112}
11113
Glenn Kasten63238ef2015-03-02 15:50:29 -080011114} // namespace android