blob: 1d398e630888552fb0d5574bab14a0adfea8d6fb [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 Hung71742ab2023-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 Hungbef3a1e2023-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 Hung21ff9672023-07-18 20:54:44 -070097#include <afutils/DumpTryLock.h>
Andy Hungc5106312023-07-19 16:56:19 -070098#include <afutils/Permission.h>
Andy Hungb776e372023-05-24 11:53:47 -070099#include <afutils/TypedLogger.h>
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800100
Eric Laurent81784c32012-11-19 14:55:58 -0800101// ----------------------------------------------------------------------------
102
103// Note: the following macro is used for extremely verbose logging message. In
104// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
105// 0; but one side effect of this is to turn all LOGV's as well. Some messages
106// are so verbose that we want to suppress them even when we have ALOG_ASSERT
107// turned on. Do not uncomment the #def below unless you really know what you
108// are doing and want to see all of the extremely verbose messages.
109//#define VERY_VERY_VERBOSE_LOGGING
110#ifdef VERY_VERY_VERBOSE_LOGGING
111#define ALOGVV ALOGV
112#else
113#define ALOGVV(a...) do { } while(0)
114#endif
115
Andy Hung6770c6f2015-04-07 13:43:36 -0700116// TODO: Move these macro/inlines to a header file.
Glenn Kasten49d00ad2014-07-21 11:22:03 -0700117#define max(a, b) ((a) > (b) ? (a) : (b))
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700118
Andy Hung6770c6f2015-04-07 13:43:36 -0700119template <typename T>
120static inline T min(const T& a, const T& b)
121{
122 return a < b ? a : b;
123}
Glenn Kasten49d00ad2014-07-21 11:22:03 -0700124
Eric Laurent81784c32012-11-19 14:55:58 -0800125namespace android {
126
Andy Hung71742ab2023-07-07 13:47:37 -0700127using audioflinger::SyncEvent;
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -0700128using media::IEffectClient;
Svet Ganov33761132021-05-13 22:51:08 +0000129using content::AttributionSourceState;
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -0700130
Eric Laurent81784c32012-11-19 14:55:58 -0800131// retry counts for buffer fill timeout
132// 50 * ~20msecs = 1 second
133static const int8_t kMaxTrackRetries = 50;
134static const int8_t kMaxTrackStartupRetries = 50;
Andy Hung455982f2021-04-27 17:46:12 -0700135
Eric Laurent81784c32012-11-19 14:55:58 -0800136// allow less retry attempts on direct output thread.
137// direct outputs can be a scarce resource in audio hardware and should
138// be released as quickly as possible.
Andy Hung455982f2021-04-27 17:46:12 -0700139// Notes:
140// 1) The retry duration kMaxTrackRetriesDirectMs may be increased
141// in case the data write is bursty for the AudioTrack. The application
142// should endeavor to write at least once every kMaxTrackRetriesDirectMs
143// to prevent an underrun situation. If the data is bursty, then
144// the application can also throttle the data sent to be even.
145// 2) For compressed audio data, any data present in the AudioTrack buffer
146// will be sent and reset the retry count. This delivers data as
147// it arrives, with approximately kDirectMinSleepTimeUs = 10ms checking interval.
148// 3) For linear PCM or proportional PCM, we wait one period for a period's worth
149// of data to be available, then any remaining data is delivered.
150// This is required to ensure the last bit of data is delivered before underrun.
151//
152// Sleep time per cycle is kDirectMinSleepTimeUs for compressed tracks
153// or the size of the HAL period for proportional / linear PCM tracks.
154static const int32_t kMaxTrackRetriesDirectMs = 200;
Eric Laurent81784c32012-11-19 14:55:58 -0800155
156// don't warn about blocked writes or record buffer overflows more often than this
157static const nsecs_t kWarningThrottleNs = seconds(5);
158
159// RecordThread loop sleep time upon application overrun or audio HAL read error
160static const int kRecordThreadSleepUs = 5000;
161
Eric Laurent10351942014-05-08 18:49:52 -0700162// maximum time to wait in sendConfigEvent_l() for a status to be received
163static const nsecs_t kConfigEventTimeoutNs = seconds(2);
Eric Laurent81784c32012-11-19 14:55:58 -0800164
165// minimum sleep time for the mixer thread loop when tracks are active but in underrun
166static const uint32_t kMinThreadSleepTimeUs = 5000;
167// maximum divider applied to the active sleep time in the mixer thread loop
168static const uint32_t kMaxThreadSleepTimeShift = 2;
169
Andy Hung09a50072014-02-27 14:30:47 -0800170// minimum normal sink buffer size, expressed in milliseconds rather than frames
Glenn Kasteneb9487e2015-07-22 09:15:17 -0700171// FIXME This should be based on experimentally observed scheduling jitter
Andy Hung09a50072014-02-27 14:30:47 -0800172static const uint32_t kMinNormalSinkBufferSizeMs = 20;
173// maximum normal sink buffer size
174static const uint32_t kMaxNormalSinkBufferSizeMs = 24;
Eric Laurent81784c32012-11-19 14:55:58 -0800175
Glenn Kasteneb9487e2015-07-22 09:15:17 -0700176// minimum capture buffer size in milliseconds to _not_ need a fast capture thread
177// FIXME This should be based on experimentally observed scheduling jitter
178static const uint32_t kMinNormalCaptureBufferSizeMs = 12;
179
Eric Laurent972a1732013-09-04 09:42:59 -0700180// Offloaded output thread standby delay: allows track transition without going to standby
181static const nsecs_t kOffloadStandbyDelayNs = seconds(1);
182
Eric Laurent51716182016-02-29 18:00:56 -0800183// Direct output thread minimum sleep time in idle or active(underrun) state
184static const nsecs_t kDirectMinSleepTimeUs = 10000;
185
Brian Lindahl9e661ad2022-07-27 18:01:07 +0200186// Minimum amount of time between checking to see if the timestamp is advancing
187// for underrun detection. If we check too frequently, we may not detect a
188// timestamp update and will falsely detect underrun.
189static const nsecs_t kMinimumTimeBetweenTimestampChecksNs = 150 /* ms */ * 1000;
190
Glenn Kasten1b291842016-07-18 14:55:21 -0700191// The universal constant for ubiquitous 20ms value. The value of 20ms seems to provide a good
192// balance between power consumption and latency, and allows threads to be scheduled reliably
193// by the CFS scheduler.
194// FIXME Express other hardcoded references to 20ms with references to this constant and move
195// it appropriately.
196#define FMS_20 20
Eric Laurent51716182016-02-29 18:00:56 -0800197
Eric Laurent81784c32012-11-19 14:55:58 -0800198// Whether to use fast mixer
199static const enum {
200 FastMixer_Never, // never initialize or use: for debugging only
201 FastMixer_Always, // always initialize and use, even if not needed: for debugging only
202 // normal mixer multiplier is 1
203 FastMixer_Static, // initialize if needed, then use all the time if initialized,
204 // multiplier is calculated based on min & max normal mixer buffer size
205 FastMixer_Dynamic, // initialize if needed, then use dynamically depending on track load,
206 // multiplier is calculated based on min & max normal mixer buffer size
207 // FIXME for FastMixer_Dynamic:
208 // Supporting this option will require fixing HALs that can't handle large writes.
209 // For example, one HAL implementation returns an error from a large write,
210 // and another HAL implementation corrupts memory, possibly in the sample rate converter.
211 // We could either fix the HAL implementations, or provide a wrapper that breaks
212 // up large writes into smaller ones, and the wrapper would need to deal with scheduler.
213} kUseFastMixer = FastMixer_Static;
214
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700215// Whether to use fast capture
216static const enum {
217 FastCapture_Never, // never initialize or use: for debugging only
218 FastCapture_Always, // always initialize and use, even if not needed: for debugging only
219 FastCapture_Static, // initialize if needed, then use all the time if initialized
220} kUseFastCapture = FastCapture_Static;
221
Eric Laurent81784c32012-11-19 14:55:58 -0800222// Priorities for requestPriority
223static const int kPriorityAudioApp = 2;
224static const int kPriorityFastMixer = 3;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700225static const int kPriorityFastCapture = 3;
Eric Laurent81784c32012-11-19 14:55:58 -0800226
Glenn Kastenea38ee72016-04-18 11:08:01 -0700227// IAudioFlinger::createTrack() has an in/out parameter 'pFrameCount' for the total size of the
228// track buffer in shared memory. Zero on input means to use a default value. For fast tracks,
229// AudioFlinger derives the default from HAL buffer size and 'fast track multiplier'.
Glenn Kasten03490092014-05-27 12:30:54 -0700230
231// This is the default value, if not specified by property.
Glenn Kastenb5fed682013-12-03 09:06:43 -0800232static const int kFastTrackMultiplier = 2;
Eric Laurent81784c32012-11-19 14:55:58 -0800233
Glenn Kasten03490092014-05-27 12:30:54 -0700234// The minimum and maximum allowed values
235static const int kFastTrackMultiplierMin = 1;
236static const int kFastTrackMultiplierMax = 2;
237
238// The actual value to use, which can be specified per-device via property af.fast_track_multiplier.
239static int sFastTrackMultiplier = kFastTrackMultiplier;
240
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700241// See Thread::readOnlyHeap().
242// Initially this heap is used to allocate client buffers for "fast" AudioRecord.
243// Eventually it will be the single buffer that FastCapture writes into via HAL read(),
244// and that all "fast" AudioRecord clients read from. In either case, the size can be small.
Mikhail Naganov79a77822018-05-10 15:57:25 -0700245static const size_t kRecordThreadReadOnlyHeapSize = 0xD000;
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700246
Eric Laurent81784c32012-11-19 14:55:58 -0800247// ----------------------------------------------------------------------------
248
Andy Hungb68f5eb2019-12-03 16:49:17 -0800249// TODO: move all toString helpers to audio.h
250// under #ifdef __cplusplus #endif
251static std::string patchSinksToString(const struct audio_patch *patch)
252{
253 std::stringstream ss;
254 for (size_t i = 0; i < patch->num_sinks; ++i) {
Andy Hungc2b11cb2020-04-22 09:04:01 -0700255 if (i > 0) {
256 ss << "|";
257 }
Andy Hungb68f5eb2019-12-03 16:49:17 -0800258 ss << "(" << toString(patch->sinks[i].ext.device.type)
259 << ", " << patch->sinks[i].ext.device.address << ")";
260 }
261 return ss.str();
262}
263
264static std::string patchSourcesToString(const struct audio_patch *patch)
265{
266 std::stringstream ss;
267 for (size_t i = 0; i < patch->num_sources; ++i) {
Andy Hungc2b11cb2020-04-22 09:04:01 -0700268 if (i > 0) {
269 ss << "|";
270 }
Andy Hungb68f5eb2019-12-03 16:49:17 -0800271 ss << "(" << toString(patch->sources[i].ext.device.type)
272 << ", " << patch->sources[i].ext.device.address << ")";
273 }
274 return ss.str();
275}
276
Andy Hung4bd53e72022-11-17 17:21:45 -0800277static std::string toString(audio_latency_mode_t mode) {
278 // We convert to the AIDL type to print (eventually the legacy type will be removed).
Mikhail Naganova77d5552022-12-18 02:48:14 +0000279 const auto result = legacy2aidl_audio_latency_mode_t_AudioLatencyMode(mode);
280 return result.has_value() ? media::audio::common::toString(*result) : "UNKNOWN";
Andy Hung4bd53e72022-11-17 17:21:45 -0800281}
282
283// Could be made a template, but other toString overloads for std::vector are confused.
284static std::string toString(const std::vector<audio_latency_mode_t>& elements) {
285 std::string s("{ ");
286 for (const auto& e : elements) {
287 s.append(toString(e));
288 s.append(" ");
289 }
290 s.append("}");
291 return s;
292}
293
Glenn Kasten03490092014-05-27 12:30:54 -0700294static pthread_once_t sFastTrackMultiplierOnce = PTHREAD_ONCE_INIT;
295
296static void sFastTrackMultiplierInit()
297{
298 char value[PROPERTY_VALUE_MAX];
299 if (property_get("af.fast_track_multiplier", value, NULL) > 0) {
300 char *endptr;
301 unsigned long ul = strtoul(value, &endptr, 0);
302 if (*endptr == '\0' && kFastTrackMultiplierMin <= ul && ul <= kFastTrackMultiplierMax) {
303 sFastTrackMultiplier = (int) ul;
304 }
305 }
306}
307
308// ----------------------------------------------------------------------------
309
Eric Laurent81784c32012-11-19 14:55:58 -0800310#ifdef ADD_BATTERY_DATA
311// To collect the amplifier usage
312static void addBatteryData(uint32_t params) {
313 sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService();
314 if (service == NULL) {
315 // it already logged
316 return;
317 }
318
319 service->addBatteryData(params);
320}
321#endif
322
Andy Hung3f0c9022016-01-15 17:49:46 -0800323// Track the CLOCK_BOOTTIME versus CLOCK_MONOTONIC timebase offset
324struct {
325 // call when you acquire a partial wakelock
326 void acquire(const sp<IBinder> &wakeLockToken) {
327 pthread_mutex_lock(&mLock);
328 if (wakeLockToken.get() == nullptr) {
329 adjustTimebaseOffset(&mBoottimeOffset, ExtendedTimestamp::TIMEBASE_BOOTTIME);
330 } else {
331 if (mCount == 0) {
332 adjustTimebaseOffset(&mBoottimeOffset, ExtendedTimestamp::TIMEBASE_BOOTTIME);
333 }
334 ++mCount;
335 }
336 pthread_mutex_unlock(&mLock);
337 }
338
339 // call when you release a partial wakelock.
340 void release(const sp<IBinder> &wakeLockToken) {
341 if (wakeLockToken.get() == nullptr) {
342 return;
343 }
344 pthread_mutex_lock(&mLock);
345 if (--mCount < 0) {
346 ALOGE("negative wakelock count");
347 mCount = 0;
348 }
349 pthread_mutex_unlock(&mLock);
350 }
351
352 // retrieves the boottime timebase offset from monotonic.
353 int64_t getBoottimeOffset() {
354 pthread_mutex_lock(&mLock);
355 int64_t boottimeOffset = mBoottimeOffset;
356 pthread_mutex_unlock(&mLock);
357 return boottimeOffset;
358 }
359
360 // Adjusts the timebase offset between TIMEBASE_MONOTONIC
361 // and the selected timebase.
362 // Currently only TIMEBASE_BOOTTIME is allowed.
363 //
364 // This only needs to be called upon acquiring the first partial wakelock
365 // after all other partial wakelocks are released.
366 //
367 // We do an empirical measurement of the offset rather than parsing
368 // /proc/timer_list since the latter is not a formal kernel ABI.
369 static void adjustTimebaseOffset(int64_t *offset, ExtendedTimestamp::Timebase timebase) {
370 int clockbase;
371 switch (timebase) {
372 case ExtendedTimestamp::TIMEBASE_BOOTTIME:
373 clockbase = SYSTEM_TIME_BOOTTIME;
374 break;
375 default:
376 LOG_ALWAYS_FATAL("invalid timebase %d", timebase);
377 break;
378 }
379 // try three times to get the clock offset, choose the one
380 // with the minimum gap in measurements.
381 const int tries = 3;
Andy Hung71ba4b32022-10-06 12:09:49 -0700382 nsecs_t bestGap = 0, measured = 0; // not required, initialized for clang-tidy
Andy Hung3f0c9022016-01-15 17:49:46 -0800383 for (int i = 0; i < tries; ++i) {
384 const nsecs_t tmono = systemTime(SYSTEM_TIME_MONOTONIC);
385 const nsecs_t tbase = systemTime(clockbase);
386 const nsecs_t tmono2 = systemTime(SYSTEM_TIME_MONOTONIC);
387 const nsecs_t gap = tmono2 - tmono;
388 if (i == 0 || gap < bestGap) {
389 bestGap = gap;
390 measured = tbase - ((tmono + tmono2) >> 1);
391 }
392 }
393
394 // to avoid micro-adjusting, we don't change the timebase
395 // unless it is significantly different.
396 //
397 // Assumption: It probably takes more than toleranceNs to
398 // suspend and resume the device.
399 static int64_t toleranceNs = 10000; // 10 us
400 if (llabs(*offset - measured) > toleranceNs) {
401 ALOGV("Adjusting timebase offset old: %lld new: %lld",
402 (long long)*offset, (long long)measured);
403 *offset = measured;
404 }
405 }
406
407 pthread_mutex_t mLock;
408 int32_t mCount;
409 int64_t mBoottimeOffset;
410} gBoottime = { PTHREAD_MUTEX_INITIALIZER, 0, 0 }; // static, so use POD initialization
Eric Laurent81784c32012-11-19 14:55:58 -0800411
412// ----------------------------------------------------------------------------
413// CPU Stats
414// ----------------------------------------------------------------------------
415
416class CpuStats {
417public:
418 CpuStats();
419 void sample(const String8 &title);
420#ifdef DEBUG_CPU_USAGE
421private:
422 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns
Andy Hung16698b82018-08-01 10:48:38 -0700423 audio_utils::Statistics<double> mWcStats; // statistics on thread CPU usage in wall clock ns
Eric Laurent81784c32012-11-19 14:55:58 -0800424
Andy Hung16698b82018-08-01 10:48:38 -0700425 audio_utils::Statistics<double> mHzStats; // statistics on thread CPU usage in cycles
Eric Laurent81784c32012-11-19 14:55:58 -0800426
427 int mCpuNum; // thread's current CPU number
428 int mCpukHz; // frequency of thread's current CPU in kHz
429#endif
430};
431
432CpuStats::CpuStats()
433#ifdef DEBUG_CPU_USAGE
434 : mCpuNum(-1), mCpukHz(-1)
435#endif
436{
437}
438
Glenn Kasten0f11b512014-01-31 16:18:54 -0800439void CpuStats::sample(const String8 &title
440#ifndef DEBUG_CPU_USAGE
441 __unused
442#endif
443 ) {
Eric Laurent81784c32012-11-19 14:55:58 -0800444#ifdef DEBUG_CPU_USAGE
445 // get current thread's delta CPU time in wall clock ns
446 double wcNs;
447 bool valid = mCpuUsage.sampleAndEnable(wcNs);
448
449 // record sample for wall clock statistics
450 if (valid) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700451 mWcStats.add(wcNs);
Eric Laurent81784c32012-11-19 14:55:58 -0800452 }
453
454 // get the current CPU number
455 int cpuNum = sched_getcpu();
456
457 // get the current CPU frequency in kHz
458 int cpukHz = mCpuUsage.getCpukHz(cpuNum);
459
460 // check if either CPU number or frequency changed
461 if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
462 mCpuNum = cpuNum;
463 mCpukHz = cpukHz;
464 // ignore sample for purposes of cycles
465 valid = false;
466 }
467
468 // if no change in CPU number or frequency, then record sample for cycle statistics
469 if (valid && mCpukHz > 0) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700470 const double cycles = wcNs * cpukHz * 0.000001;
471 mHzStats.add(cycles);
Eric Laurent81784c32012-11-19 14:55:58 -0800472 }
473
Eric Tan5b13ff82018-07-27 11:20:17 -0700474 const unsigned n = mWcStats.getN();
Eric Laurent81784c32012-11-19 14:55:58 -0800475 // mCpuUsage.elapsed() is expensive, so don't call it every loop
476 if ((n & 127) == 1) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700477 const long long elapsed = mCpuUsage.elapsed();
Eric Laurent81784c32012-11-19 14:55:58 -0800478 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700479 const double perLoop = elapsed / (double) n;
480 const double perLoop100 = perLoop * 0.01;
481 const double perLoop1k = perLoop * 0.001;
482 const double mean = mWcStats.getMean();
483 const double stddev = mWcStats.getStdDev();
484 const double minimum = mWcStats.getMin();
485 const double maximum = mWcStats.getMax();
486 const double meanCycles = mHzStats.getMean();
487 const double stddevCycles = mHzStats.getStdDev();
488 const double minCycles = mHzStats.getMin();
489 const double maxCycles = mHzStats.getMax();
Eric Laurent81784c32012-11-19 14:55:58 -0800490 mCpuUsage.resetElapsed();
491 mWcStats.reset();
492 mHzStats.reset();
493 ALOGD("CPU usage for %s over past %.1f secs\n"
494 " (%u mixer loops at %.1f mean ms per loop):\n"
495 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
496 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
497 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
Tomasz Wasilczyk8f36f6e2023-08-15 20:59:35 +0000498 title.c_str(),
Eric Laurent81784c32012-11-19 14:55:58 -0800499 elapsed * .000000001, n, perLoop * .000001,
500 mean * .001,
501 stddev * .001,
502 minimum * .001,
503 maximum * .001,
504 mean / perLoop100,
505 stddev / perLoop100,
506 minimum / perLoop100,
507 maximum / perLoop100,
508 meanCycles / perLoop1k,
509 stddevCycles / perLoop1k,
510 minCycles / perLoop1k,
511 maxCycles / perLoop1k);
512
513 }
514 }
515#endif
516};
517
518// ----------------------------------------------------------------------------
519// ThreadBase
520// ----------------------------------------------------------------------------
521
Glenn Kasten97b7b752014-09-28 13:04:24 -0700522// static
Andy Hung71742ab2023-07-07 13:47:37 -0700523const char* ThreadBase::threadTypeToString(ThreadBase::type_t type)
Glenn Kasten97b7b752014-09-28 13:04:24 -0700524{
525 switch (type) {
526 case MIXER:
527 return "MIXER";
528 case DIRECT:
529 return "DIRECT";
530 case DUPLICATING:
531 return "DUPLICATING";
532 case RECORD:
533 return "RECORD";
534 case OFFLOAD:
535 return "OFFLOAD";
Andy Hungea840382020-05-05 21:50:17 -0700536 case MMAP_PLAYBACK:
537 return "MMAP_PLAYBACK";
538 case MMAP_CAPTURE:
539 return "MMAP_CAPTURE";
Eric Laurent1c5e2e32021-08-18 18:50:28 +0200540 case SPATIALIZER:
541 return "SPATIALIZER";
jiabinc658e452022-10-21 20:52:21 +0000542 case BIT_PERFECT:
543 return "BIT_PERFECT";
Glenn Kasten97b7b752014-09-28 13:04:24 -0700544 default:
545 return "unknown";
546 }
547}
548
Andy Hung2cbc2722023-07-17 17:05:00 -0700549ThreadBase::ThreadBase(const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
Andy Hungcf10d742020-04-28 15:38:24 -0700550 type_t type, bool systemReady, bool isOut)
Eric Laurent81784c32012-11-19 14:55:58 -0800551 : Thread(false /*canCallJava*/),
552 mType(type),
Andy Hung2cbc2722023-07-17 17:05:00 -0700553 mAfThreadCallback(afThreadCallback),
Andy Hungcf10d742020-04-28 15:38:24 -0700554 mThreadMetrics(std::string(AMEDIAMETRICS_KEY_PREFIX_AUDIO_THREAD) + std::to_string(id),
555 isOut),
556 mIsOut(isOut),
Glenn Kasten70949c42013-08-06 07:40:12 -0700557 // mSampleRate, mFrameCount, mChannelMask, mChannelCount, mFrameSize, mFormat, mBufferSize
Glenn Kastendeca2ae2014-02-07 10:25:56 -0800558 // are set by PlaybackThread::readOutputParameters_l() or
559 // RecordThread::readInputParameters_l()
Eric Laurentfd477972013-10-25 18:10:40 -0700560 //FIXME: mStandby should be true here. Is this some kind of hack?
jiabinc52b1ff2019-10-31 17:20:42 -0700561 mStandby(false),
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700562 mAudioSource(AUDIO_SOURCE_DEFAULT), mId(id),
Eric Laurent81784c32012-11-19 14:55:58 -0800563 // mName will be set by concrete (non-virtual) subclass
Eric Laurent72e3f392015-05-20 14:43:50 -0700564 mDeathRecipient(new PMDeathRecipient(this)),
Eric Laurent6acd1d42017-01-04 14:23:29 -0800565 mSystemReady(systemReady),
566 mSignalPending(false)
Eric Laurent81784c32012-11-19 14:55:58 -0800567{
Andy Hungcf10d742020-04-28 15:38:24 -0700568 mThreadMetrics.logConstructor(getpid(), threadTypeToString(type), id);
Eric Laurent296fb132015-05-01 11:38:42 -0700569 memset(&mPatch, 0, sizeof(struct audio_patch));
Eric Laurent81784c32012-11-19 14:55:58 -0800570}
571
Andy Hung71742ab2023-07-07 13:47:37 -0700572ThreadBase::~ThreadBase()
Eric Laurent81784c32012-11-19 14:55:58 -0800573{
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700574 // mConfigEvents should be empty, but just in case it isn't, free the memory it owns
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700575 mConfigEvents.clear();
576
Eric Laurent81784c32012-11-19 14:55:58 -0800577 // do not lock the mutex in destructor
578 releaseWakeLock_l();
579 if (mPowerManager != 0) {
Marco Nelissen06b46062014-11-14 07:58:25 -0800580 sp<IBinder> binder = IInterface::asBinder(mPowerManager);
Eric Laurent81784c32012-11-19 14:55:58 -0800581 binder->unlinkToDeath(mDeathRecipient);
582 }
Andy Hungd0979812019-02-21 15:51:44 -0800583
584 sendStatistics(true /* force */);
Eric Laurent81784c32012-11-19 14:55:58 -0800585}
586
Andy Hung71742ab2023-07-07 13:47:37 -0700587status_t ThreadBase::readyToRun()
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700588{
589 status_t status = initCheck();
590 if (status == NO_ERROR) {
Glenn Kasten1bfe09a2017-02-21 13:05:56 -0800591 ALOGI("AudioFlinger's thread %p tid=%d ready to run", this, getTid());
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700592 } else {
593 ALOGE("No working audio driver found.");
594 }
595 return status;
596}
597
Andy Hung71742ab2023-07-07 13:47:37 -0700598void ThreadBase::exit()
Eric Laurent81784c32012-11-19 14:55:58 -0800599{
600 ALOGV("ThreadBase::exit");
601 // do any cleanup required for exit to succeed
602 preExit();
603 {
604 // This lock prevents the following race in thread (uniprocessor for illustration):
605 // if (!exitPending()) {
606 // // context switch from here to exit()
607 // // exit() calls requestExit(), what exitPending() observes
608 // // exit() calls signal(), which is dropped since no waiters
609 // // context switch back from exit() to here
610 // mWaitWorkCV.wait(...);
611 // // now thread is hung
612 // }
613 AutoMutex lock(mLock);
614 requestExit();
615 mWaitWorkCV.broadcast();
616 }
617 // When Thread::requestExitAndWait is made virtual and this method is renamed to
618 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
619 requestExitAndWait();
620}
621
Andy Hung71742ab2023-07-07 13:47:37 -0700622status_t ThreadBase::setParameters(const String8& keyValuePairs)
Eric Laurent81784c32012-11-19 14:55:58 -0800623{
Tomasz Wasilczyk8f36f6e2023-08-15 20:59:35 +0000624 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.c_str());
Eric Laurent81784c32012-11-19 14:55:58 -0800625 Mutex::Autolock _l(mLock);
626
Eric Laurent10351942014-05-08 18:49:52 -0700627 return sendSetParameterConfigEvent_l(keyValuePairs);
628}
629
630// sendConfigEvent_l() must be called with ThreadBase::mLock held
631// Can temporarily release the lock if waiting for a reply from processConfigEvents_l().
Andy Hung71742ab2023-07-07 13:47:37 -0700632status_t ThreadBase::sendConfigEvent_l(sp<ConfigEvent>& event)
Andy Hung71ba4b32022-10-06 12:09:49 -0700633NO_THREAD_SAFETY_ANALYSIS // condition variable
Eric Laurent10351942014-05-08 18:49:52 -0700634{
635 status_t status = NO_ERROR;
636
Eric Laurent72e3f392015-05-20 14:43:50 -0700637 if (event->mRequiresSystemReady && !mSystemReady) {
638 event->mWaitStatus = false;
639 mPendingConfigEvents.add(event);
640 return status;
641 }
Eric Laurent10351942014-05-08 18:49:52 -0700642 mConfigEvents.add(event);
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700643 ALOGV("sendConfigEvent_l() num events %zu event %d", mConfigEvents.size(), event->mType);
Eric Laurent81784c32012-11-19 14:55:58 -0800644 mWaitWorkCV.signal();
Eric Laurent10351942014-05-08 18:49:52 -0700645 mLock.unlock();
646 {
647 Mutex::Autolock _l(event->mLock);
648 while (event->mWaitStatus) {
649 if (event->mCond.waitRelative(event->mLock, kConfigEventTimeoutNs) != NO_ERROR) {
650 event->mStatus = TIMED_OUT;
651 event->mWaitStatus = false;
652 }
653 }
654 status = event->mStatus;
Eric Laurent81784c32012-11-19 14:55:58 -0800655 }
Eric Laurent10351942014-05-08 18:49:52 -0700656 mLock.lock();
Eric Laurent81784c32012-11-19 14:55:58 -0800657 return status;
658}
659
Andy Hung71742ab2023-07-07 13:47:37 -0700660void ThreadBase::sendIoConfigEvent(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -0700661 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -0800662{
663 Mutex::Autolock _l(mLock);
Eric Laurent09f1ed22019-04-24 17:45:17 -0700664 sendIoConfigEvent_l(event, pid, portId);
Eric Laurent81784c32012-11-19 14:55:58 -0800665}
666
667// sendIoConfigEvent_l() must be called with ThreadBase::mLock held
Andy Hung71742ab2023-07-07 13:47:37 -0700668void ThreadBase::sendIoConfigEvent_l(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -0700669 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -0800670{
Andy Hungd0979812019-02-21 15:51:44 -0800671 // The audio statistics history is exponentially weighted to forget events
672 // about five or more seconds in the past. In order to have
673 // crisper statistics for mediametrics, we reset the statistics on
674 // an IoConfigEvent, to reflect different properties for a new device.
675 mIoJitterMs.reset();
676 mLatencyMs.reset();
677 mProcessTimeMs.reset();
Robert Wu06db0a32021-08-10 19:05:34 +0000678 mMonopipePipeDepthStats.reset();
Dean Wheatley12473e92021-03-18 23:00:55 +1100679 mTimestampVerifier.discontinuity(mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS);
Andy Hungd0979812019-02-21 15:51:44 -0800680
Eric Laurent09f1ed22019-04-24 17:45:17 -0700681 sp<ConfigEvent> configEvent = (ConfigEvent *)new IoConfigEvent(event, pid, portId);
Eric Laurent10351942014-05-08 18:49:52 -0700682 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800683}
684
Andy Hung71742ab2023-07-07 13:47:37 -0700685void ThreadBase::sendPrioConfigEvent(pid_t pid, pid_t tid, int32_t prio, bool forApp)
Eric Laurent72e3f392015-05-20 14:43:50 -0700686{
687 Mutex::Autolock _l(mLock);
Mikhail Naganov83f04272017-02-07 10:45:09 -0800688 sendPrioConfigEvent_l(pid, tid, prio, forApp);
Eric Laurent72e3f392015-05-20 14:43:50 -0700689}
690
Eric Laurent81784c32012-11-19 14:55:58 -0800691// sendPrioConfigEvent_l() must be called with ThreadBase::mLock held
Andy Hung71742ab2023-07-07 13:47:37 -0700692void ThreadBase::sendPrioConfigEvent_l(
Mikhail Naganov83f04272017-02-07 10:45:09 -0800693 pid_t pid, pid_t tid, int32_t prio, bool forApp)
Eric Laurent81784c32012-11-19 14:55:58 -0800694{
Mikhail Naganov83f04272017-02-07 10:45:09 -0800695 sp<ConfigEvent> configEvent = (ConfigEvent *)new PrioConfigEvent(pid, tid, prio, forApp);
Eric Laurent10351942014-05-08 18:49:52 -0700696 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800697}
698
Eric Laurent10351942014-05-08 18:49:52 -0700699// sendSetParameterConfigEvent_l() must be called with ThreadBase::mLock held
Andy Hung71742ab2023-07-07 13:47:37 -0700700status_t ThreadBase::sendSetParameterConfigEvent_l(const String8& keyValuePair)
Eric Laurent81784c32012-11-19 14:55:58 -0800701{
Andy Hung2ddee192015-12-18 17:34:44 -0800702 sp<ConfigEvent> configEvent;
703 AudioParameter param(keyValuePair);
704 int value;
Mikhail Naganov00260b52016-10-13 12:54:24 -0700705 if (param.getInt(String8(AudioParameter::keyMonoOutput), value) == NO_ERROR) {
Andy Hung2ddee192015-12-18 17:34:44 -0800706 setMasterMono_l(value != 0);
707 if (param.size() == 1) {
708 return NO_ERROR; // should be a solo parameter - we don't pass down
709 }
Mikhail Naganov00260b52016-10-13 12:54:24 -0700710 param.remove(String8(AudioParameter::keyMonoOutput));
Andy Hung2ddee192015-12-18 17:34:44 -0800711 configEvent = new SetParameterConfigEvent(param.toString());
712 } else {
713 configEvent = new SetParameterConfigEvent(keyValuePair);
714 }
Eric Laurent10351942014-05-08 18:49:52 -0700715 return sendConfigEvent_l(configEvent);
Glenn Kastenf7773312013-08-13 16:00:42 -0700716}
717
Andy Hung71742ab2023-07-07 13:47:37 -0700718status_t ThreadBase::sendCreateAudioPatchConfigEvent(
Eric Laurent1c333e22014-05-20 10:48:17 -0700719 const struct audio_patch *patch,
720 audio_patch_handle_t *handle)
721{
722 Mutex::Autolock _l(mLock);
723 sp<ConfigEvent> configEvent = (ConfigEvent *)new CreateAudioPatchConfigEvent(*patch, *handle);
724 status_t status = sendConfigEvent_l(configEvent);
725 if (status == NO_ERROR) {
726 CreateAudioPatchConfigEventData *data =
727 (CreateAudioPatchConfigEventData *)configEvent->mData.get();
728 *handle = data->mHandle;
729 }
730 return status;
731}
732
Andy Hung71742ab2023-07-07 13:47:37 -0700733status_t ThreadBase::sendReleaseAudioPatchConfigEvent(
Eric Laurent1c333e22014-05-20 10:48:17 -0700734 const audio_patch_handle_t handle)
735{
736 Mutex::Autolock _l(mLock);
737 sp<ConfigEvent> configEvent = (ConfigEvent *)new ReleaseAudioPatchConfigEvent(handle);
738 return sendConfigEvent_l(configEvent);
739}
740
Andy Hung71742ab2023-07-07 13:47:37 -0700741status_t ThreadBase::sendUpdateOutDeviceConfigEvent(
jiabinc52b1ff2019-10-31 17:20:42 -0700742 const DeviceDescriptorBaseVector& outDevices)
743{
744 if (type() != RECORD) {
745 // The update out device operation is only for record thread.
746 return INVALID_OPERATION;
747 }
748 Mutex::Autolock _l(mLock);
749 sp<ConfigEvent> configEvent = (ConfigEvent *)new UpdateOutDevicesConfigEvent(outDevices);
750 return sendConfigEvent_l(configEvent);
751}
752
Andy Hung71742ab2023-07-07 13:47:37 -0700753void ThreadBase::sendResizeBufferConfigEvent_l(int32_t maxSharedAudioHistoryMs)
Eric Laurentec376dc2021-04-08 20:41:22 +0200754{
755 ALOG_ASSERT(type() == RECORD, "sendResizeBufferConfigEvent_l() called on non record thread");
756 sp<ConfigEvent> configEvent =
757 (ConfigEvent *)new ResizeBufferConfigEvent(maxSharedAudioHistoryMs);
758 sendConfigEvent_l(configEvent);
759}
Eric Laurent1c333e22014-05-20 10:48:17 -0700760
Andy Hung71742ab2023-07-07 13:47:37 -0700761void ThreadBase::sendCheckOutputStageEffectsEvent()
Eric Laurentb3f315a2021-07-13 15:09:05 +0200762{
763 Mutex::Autolock _l(mLock);
764 sendCheckOutputStageEffectsEvent_l();
765}
766
Andy Hung71742ab2023-07-07 13:47:37 -0700767void ThreadBase::sendCheckOutputStageEffectsEvent_l()
Eric Laurentb3f315a2021-07-13 15:09:05 +0200768{
769 sp<ConfigEvent> configEvent =
770 (ConfigEvent *)new CheckOutputStageEffectsEvent();
771 sendConfigEvent_l(configEvent);
772}
773
Andy Hung71742ab2023-07-07 13:47:37 -0700774void ThreadBase::sendHalLatencyModesChangedEvent_l()
Eric Laurent6f9534f2022-05-03 18:15:04 +0200775{
776 sp<ConfigEvent> configEvent = sp<HalLatencyModesChangedEvent>::make();
777 sendConfigEvent_l(configEvent);
778}
779
Glenn Kasten2cfbf882013-08-14 13:12:11 -0700780// post condition: mConfigEvents.isEmpty()
Andy Hung71742ab2023-07-07 13:47:37 -0700781void ThreadBase::processConfigEvents_l()
Glenn Kastenf7773312013-08-13 16:00:42 -0700782{
Eric Laurent10351942014-05-08 18:49:52 -0700783 bool configChanged = false;
784
Eric Laurent81784c32012-11-19 14:55:58 -0800785 while (!mConfigEvents.isEmpty()) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700786 ALOGV("processConfigEvents_l() remaining events %zu", mConfigEvents.size());
Eric Laurent10351942014-05-08 18:49:52 -0700787 sp<ConfigEvent> event = mConfigEvents[0];
Eric Laurent81784c32012-11-19 14:55:58 -0800788 mConfigEvents.removeAt(0);
Eric Laurent10351942014-05-08 18:49:52 -0700789 switch (event->mType) {
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700790 case CFG_EVENT_PRIO: {
Eric Laurent10351942014-05-08 18:49:52 -0700791 PrioConfigEventData *data = (PrioConfigEventData *)event->mData.get();
792 // FIXME Need to understand why this has to be done asynchronously
Mikhail Naganov83f04272017-02-07 10:45:09 -0800793 int err = requestPriority(data->mPid, data->mTid, data->mPrio, data->mForApp,
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700794 true /*asynchronous*/);
795 if (err != 0) {
796 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Eric Laurent10351942014-05-08 18:49:52 -0700797 data->mPrio, data->mPid, data->mTid, err);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700798 }
799 } break;
800 case CFG_EVENT_IO: {
Eric Laurent10351942014-05-08 18:49:52 -0700801 IoConfigEventData *data = (IoConfigEventData *)event->mData.get();
Eric Laurent09f1ed22019-04-24 17:45:17 -0700802 ioConfigChanged(data->mEvent, data->mPid, data->mPortId);
Eric Laurent10351942014-05-08 18:49:52 -0700803 } break;
804 case CFG_EVENT_SET_PARAMETER: {
805 SetParameterConfigEventData *data = (SetParameterConfigEventData *)event->mData.get();
806 if (checkForNewParameter_l(data->mKeyValuePairs, event->mStatus)) {
807 configChanged = true;
Andy Hung293558a2017-03-21 12:19:20 -0700808 mLocalLog.log("CFG_EVENT_SET_PARAMETER: (%s) configuration changed",
Tomasz Wasilczyk8f36f6e2023-08-15 20:59:35 +0000809 data->mKeyValuePairs.c_str());
Glenn Kastend5418eb2013-08-14 13:11:06 -0700810 }
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700811 } break;
Eric Laurent1c333e22014-05-20 10:48:17 -0700812 case CFG_EVENT_CREATE_AUDIO_PATCH: {
jiabinc52b1ff2019-10-31 17:20:42 -0700813 const DeviceTypeSet oldDevices = getDeviceTypes();
Eric Laurent1c333e22014-05-20 10:48:17 -0700814 CreateAudioPatchConfigEventData *data =
815 (CreateAudioPatchConfigEventData *)event->mData.get();
816 event->mStatus = createAudioPatch_l(&data->mPatch, &data->mHandle);
jiabinc52b1ff2019-10-31 17:20:42 -0700817 const DeviceTypeSet newDevices = getDeviceTypes();
Eric Laurent52568142022-10-28 11:23:28 +0200818 configChanged = oldDevices != newDevices;
jiabinc52b1ff2019-10-31 17:20:42 -0700819 mLocalLog.log("CFG_EVENT_CREATE_AUDIO_PATCH: old device %s (%s) new device %s (%s)",
820 dumpDeviceTypes(oldDevices).c_str(), toString(oldDevices).c_str(),
821 dumpDeviceTypes(newDevices).c_str(), toString(newDevices).c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -0700822 } break;
823 case CFG_EVENT_RELEASE_AUDIO_PATCH: {
jiabinc52b1ff2019-10-31 17:20:42 -0700824 const DeviceTypeSet oldDevices = getDeviceTypes();
Eric Laurent1c333e22014-05-20 10:48:17 -0700825 ReleaseAudioPatchConfigEventData *data =
826 (ReleaseAudioPatchConfigEventData *)event->mData.get();
827 event->mStatus = releaseAudioPatch_l(data->mHandle);
jiabinc52b1ff2019-10-31 17:20:42 -0700828 const DeviceTypeSet newDevices = getDeviceTypes();
Eric Laurent52568142022-10-28 11:23:28 +0200829 configChanged = oldDevices != newDevices;
jiabinc52b1ff2019-10-31 17:20:42 -0700830 mLocalLog.log("CFG_EVENT_RELEASE_AUDIO_PATCH: old device %s (%s) new device %s (%s)",
831 dumpDeviceTypes(oldDevices).c_str(), toString(oldDevices).c_str(),
832 dumpDeviceTypes(newDevices).c_str(), toString(newDevices).c_str());
833 } break;
834 case CFG_EVENT_UPDATE_OUT_DEVICE: {
835 UpdateOutDevicesConfigEventData *data =
836 (UpdateOutDevicesConfigEventData *)event->mData.get();
837 updateOutDevices(data->mOutDevices);
Eric Laurent1c333e22014-05-20 10:48:17 -0700838 } break;
Eric Laurentec376dc2021-04-08 20:41:22 +0200839 case CFG_EVENT_RESIZE_BUFFER: {
840 ResizeBufferConfigEventData *data =
841 (ResizeBufferConfigEventData *)event->mData.get();
842 resizeInputBuffer_l(data->mMaxSharedAudioHistoryMs);
843 } break;
Eric Laurentb3f315a2021-07-13 15:09:05 +0200844
845 case CFG_EVENT_CHECK_OUTPUT_STAGE_EFFECTS: {
846 setCheckOutputStageEffects();
847 } break;
848
Eric Laurent6f9534f2022-05-03 18:15:04 +0200849 case CFG_EVENT_HAL_LATENCY_MODES_CHANGED: {
850 onHalLatencyModesChanged_l();
851 } break;
852
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700853 default:
Eric Laurent10351942014-05-08 18:49:52 -0700854 ALOG_ASSERT(false, "processConfigEvents_l() unknown event type %d", event->mType);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700855 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800856 }
Eric Laurent10351942014-05-08 18:49:52 -0700857 {
858 Mutex::Autolock _l(event->mLock);
859 if (event->mWaitStatus) {
860 event->mWaitStatus = false;
861 event->mCond.signal();
862 }
863 }
864 ALOGV_IF(mConfigEvents.isEmpty(), "processConfigEvents_l() DONE thread %p", this);
865 }
866
867 if (configChanged) {
868 cacheParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800869 }
Eric Laurent81784c32012-11-19 14:55:58 -0800870}
871
Marco Nelissenb2208842014-02-07 14:00:50 -0800872String8 channelMaskToString(audio_channel_mask_t mask, bool output) {
873 String8 s;
Glenn Kastene1635ec2015-06-08 15:46:49 -0700874 const audio_channel_representation_t representation =
875 audio_channel_mask_get_representation(mask);
Andy Hungf98ec8d2015-05-19 12:53:24 -0700876
877 switch (representation) {
jiabin245cdd92018-12-07 17:55:15 -0800878 // Travel all single bit channel mask to convert channel mask to string.
Andy Hungf98ec8d2015-05-19 12:53:24 -0700879 case AUDIO_CHANNEL_REPRESENTATION_POSITION: {
880 if (output) {
881 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT) s.append("front-left, ");
882 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT) s.append("front-right, ");
883 if (mask & AUDIO_CHANNEL_OUT_FRONT_CENTER) s.append("front-center, ");
Andy Hungfba71252021-05-07 11:58:32 -0700884 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY) s.append("low-frequency, ");
Andy Hungf98ec8d2015-05-19 12:53:24 -0700885 if (mask & AUDIO_CHANNEL_OUT_BACK_LEFT) s.append("back-left, ");
886 if (mask & AUDIO_CHANNEL_OUT_BACK_RIGHT) s.append("back-right, ");
887 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT_OF_CENTER) s.append("front-left-of-center, ");
888 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT_OF_CENTER) s.append("front-right-of-center, ");
889 if (mask & AUDIO_CHANNEL_OUT_BACK_CENTER) s.append("back-center, ");
890 if (mask & AUDIO_CHANNEL_OUT_SIDE_LEFT) s.append("side-left, ");
891 if (mask & AUDIO_CHANNEL_OUT_SIDE_RIGHT) s.append("side-right, ");
892 if (mask & AUDIO_CHANNEL_OUT_TOP_CENTER) s.append("top-center ,");
893 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_LEFT) s.append("top-front-left, ");
894 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_CENTER) s.append("top-front-center, ");
895 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_RIGHT) s.append("top-front-right, ");
896 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_LEFT) s.append("top-back-left, ");
Andy Hungae81b4c2021-05-07 08:54:28 -0700897 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_CENTER) s.append("top-back-center, ");
898 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_RIGHT) s.append("top-back-right, ");
899 if (mask & AUDIO_CHANNEL_OUT_TOP_SIDE_LEFT) s.append("top-side-left, ");
900 if (mask & AUDIO_CHANNEL_OUT_TOP_SIDE_RIGHT) s.append("top-side-right, ");
901 if (mask & AUDIO_CHANNEL_OUT_BOTTOM_FRONT_LEFT) s.append("bottom-front-left, ");
902 if (mask & AUDIO_CHANNEL_OUT_BOTTOM_FRONT_CENTER) s.append("bottom-front-center, ");
903 if (mask & AUDIO_CHANNEL_OUT_BOTTOM_FRONT_RIGHT) s.append("bottom-front-right, ");
Andy Hungfba71252021-05-07 11:58:32 -0700904 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY_2) s.append("low-frequency-2, ");
Andy Hungae81b4c2021-05-07 08:54:28 -0700905 if (mask & AUDIO_CHANNEL_OUT_HAPTIC_B) s.append("haptic-B, ");
906 if (mask & AUDIO_CHANNEL_OUT_HAPTIC_A) s.append("haptic-A, ");
Andy Hungf98ec8d2015-05-19 12:53:24 -0700907 if (mask & ~AUDIO_CHANNEL_OUT_ALL) s.append("unknown, ");
908 } else {
909 if (mask & AUDIO_CHANNEL_IN_LEFT) s.append("left, ");
910 if (mask & AUDIO_CHANNEL_IN_RIGHT) s.append("right, ");
911 if (mask & AUDIO_CHANNEL_IN_FRONT) s.append("front, ");
912 if (mask & AUDIO_CHANNEL_IN_BACK) s.append("back, ");
913 if (mask & AUDIO_CHANNEL_IN_LEFT_PROCESSED) s.append("left-processed, ");
914 if (mask & AUDIO_CHANNEL_IN_RIGHT_PROCESSED) s.append("right-processed, ");
915 if (mask & AUDIO_CHANNEL_IN_FRONT_PROCESSED) s.append("front-processed, ");
916 if (mask & AUDIO_CHANNEL_IN_BACK_PROCESSED) s.append("back-processed, ");
917 if (mask & AUDIO_CHANNEL_IN_PRESSURE) s.append("pressure, ");
918 if (mask & AUDIO_CHANNEL_IN_X_AXIS) s.append("X, ");
919 if (mask & AUDIO_CHANNEL_IN_Y_AXIS) s.append("Y, ");
920 if (mask & AUDIO_CHANNEL_IN_Z_AXIS) s.append("Z, ");
Mikhail Naganovc9948492018-05-10 17:25:28 -0700921 if (mask & AUDIO_CHANNEL_IN_BACK_LEFT) s.append("back-left, ");
922 if (mask & AUDIO_CHANNEL_IN_BACK_RIGHT) s.append("back-right, ");
923 if (mask & AUDIO_CHANNEL_IN_CENTER) s.append("center, ");
Andy Hungfba71252021-05-07 11:58:32 -0700924 if (mask & AUDIO_CHANNEL_IN_LOW_FREQUENCY) s.append("low-frequency, ");
Andy Hungae81b4c2021-05-07 08:54:28 -0700925 if (mask & AUDIO_CHANNEL_IN_TOP_LEFT) s.append("top-left, ");
926 if (mask & AUDIO_CHANNEL_IN_TOP_RIGHT) s.append("top-right, ");
Andy Hungf98ec8d2015-05-19 12:53:24 -0700927 if (mask & AUDIO_CHANNEL_IN_VOICE_UPLINK) s.append("voice-uplink, ");
928 if (mask & AUDIO_CHANNEL_IN_VOICE_DNLINK) s.append("voice-dnlink, ");
929 if (mask & ~AUDIO_CHANNEL_IN_ALL) s.append("unknown, ");
930 }
931 const int len = s.length();
932 if (len > 2) {
Glenn Kasten57c4e6f2016-03-18 14:54:07 -0700933 (void) s.lockBuffer(len); // needed?
Andy Hungf98ec8d2015-05-19 12:53:24 -0700934 s.unlockBuffer(len - 2); // remove trailing ", "
935 }
936 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -0800937 }
Andy Hungf98ec8d2015-05-19 12:53:24 -0700938 case AUDIO_CHANNEL_REPRESENTATION_INDEX:
939 s.appendFormat("index mask, bits:%#x", audio_channel_mask_get_bits(mask));
940 return s;
941 default:
942 s.appendFormat("unknown mask, representation:%d bits:%#x",
943 representation, audio_channel_mask_get_bits(mask));
944 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -0800945 }
Marco Nelissenb2208842014-02-07 14:00:50 -0800946}
947
Andy Hung71742ab2023-07-07 13:47:37 -0700948void ThreadBase::dump(int fd, const Vector<String16>& args)
Andy Hung71ba4b32022-10-06 12:09:49 -0700949NO_THREAD_SAFETY_ANALYSIS // conditional try lock
Eric Laurent81784c32012-11-19 14:55:58 -0800950{
Glenn Kasten1bfe09a2017-02-21 13:05:56 -0800951 dprintf(fd, "\n%s thread %p, name %s, tid %d, type %d (%s):\n", isOutput() ? "Output" : "Input",
952 this, mThreadName, getTid(), type(), threadTypeToString(type()));
953
Andy Hung21ff9672023-07-18 20:54:44 -0700954 const bool locked = afutils::dumpTryLock(mLock);
Eric Laurent81784c32012-11-19 14:55:58 -0800955 if (!locked) {
Glenn Kasten1bfe09a2017-02-21 13:05:56 -0800956 dprintf(fd, " Thread may be deadlocked\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800957 }
958
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -0700959 dumpBase_l(fd, args);
960 dumpInternals_l(fd, args);
961 dumpTracks_l(fd, args);
962 dumpEffectChains_l(fd, args);
963
964 if (locked) {
965 mLock.unlock();
966 }
967
968 dprintf(fd, " Local log:\n");
969 mLocalLog.dump(fd, " " /* prefix */, 40 /* lines */);
Andy Hungafc51db2022-04-08 17:33:40 -0700970
971 // --all does the statistics
972 bool dumpAll = false;
973 for (const auto &arg : args) {
974 if (arg == String16("--all")) {
975 dumpAll = true;
976 }
977 }
978 if (dumpAll || type() == SPATIALIZER) {
Andy Hung44d648b2022-04-08 17:33:40 -0700979 const std::string sched = mThreadSnapshot.toString();
Andy Hungafc51db2022-04-08 17:33:40 -0700980 if (!sched.empty()) {
981 (void)write(fd, sched.c_str(), sched.size());
982 }
983 }
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -0700984}
985
Andy Hung71742ab2023-07-07 13:47:37 -0700986void ThreadBase::dumpBase_l(int fd, const Vector<String16>& /* args */)
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -0700987{
Elliott Hughes87cebad2014-05-22 10:14:43 -0700988 dprintf(fd, " I/O handle: %d\n", mId);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700989 dprintf(fd, " Standby: %s\n", mStandby ? "yes" : "no");
Glenn Kasten97b7b752014-09-28 13:04:24 -0700990 dprintf(fd, " Sample rate: %u Hz\n", mSampleRate);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700991 dprintf(fd, " HAL frame count: %zu\n", mFrameCount);
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700992 dprintf(fd, " HAL format: 0x%x (%s)\n", mHALFormat, formatToString(mHALFormat).c_str());
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700993 dprintf(fd, " HAL buffer size: %zu bytes\n", mBufferSize);
Glenn Kasten97b7b752014-09-28 13:04:24 -0700994 dprintf(fd, " Channel count: %u\n", mChannelCount);
995 dprintf(fd, " Channel mask: 0x%08x (%s)\n", mChannelMask,
Tomasz Wasilczyk8f36f6e2023-08-15 20:59:35 +0000996 channelMaskToString(mChannelMask, mType != RECORD).c_str());
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700997 dprintf(fd, " Processing format: 0x%x (%s)\n", mFormat, formatToString(mFormat).c_str());
Glenn Kastenf87c2f52015-08-21 08:03:57 -0700998 dprintf(fd, " Processing frame size: %zu bytes\n", mFrameSize);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700999 dprintf(fd, " Pending config events:");
Marco Nelissenb2208842014-02-07 14:00:50 -08001000 size_t numConfig = mConfigEvents.size();
1001 if (numConfig) {
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001002 const size_t SIZE = 256;
1003 char buffer[SIZE];
Marco Nelissenb2208842014-02-07 14:00:50 -08001004 for (size_t i = 0; i < numConfig; i++) {
1005 mConfigEvents[i]->dump(buffer, SIZE);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001006 dprintf(fd, "\n %s", buffer);
Marco Nelissenb2208842014-02-07 14:00:50 -08001007 }
Elliott Hughes87cebad2014-05-22 10:14:43 -07001008 dprintf(fd, "\n");
Marco Nelissenb2208842014-02-07 14:00:50 -08001009 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07001010 dprintf(fd, " none\n");
Eric Laurent81784c32012-11-19 14:55:58 -08001011 }
Andy Hung293558a2017-03-21 12:19:20 -07001012 // Note: output device may be used by capture threads for effects such as AEC.
jiabinc52b1ff2019-10-31 17:20:42 -07001013 dprintf(fd, " Output devices: %s (%s)\n",
1014 dumpDeviceTypes(outDeviceTypes()).c_str(), toString(outDeviceTypes()).c_str());
1015 dprintf(fd, " Input device: %#x (%s)\n",
1016 inDeviceType(), toString(inDeviceType()).c_str());
Andy Hung9b181952019-02-25 14:53:36 -08001017 dprintf(fd, " Audio source: %d (%s)\n", mAudioSource, toString(mAudioSource).c_str());
Eric Laurent81784c32012-11-19 14:55:58 -08001018
Andy Hung2e2c0bb2018-06-11 19:13:11 -07001019 // Dump timestamp statistics for the Thread types that support it.
1020 if (mType == RECORD
1021 || mType == MIXER
1022 || mType == DUPLICATING
Andy Hungf3234512018-07-03 14:51:47 -07001023 || mType == DIRECT
Andy Hung4b7f54f2022-04-28 17:45:28 -07001024 || mType == OFFLOAD
1025 || mType == SPATIALIZER) {
Andy Hung2e2c0bb2018-06-11 19:13:11 -07001026 dprintf(fd, " Timestamp stats: %s\n", mTimestampVerifier.toString().c_str());
Andy Hungc8fddf32018-08-08 18:32:37 -07001027 dprintf(fd, " Timestamp corrected: %s\n", isTimestampCorrectionEnabled() ? "yes" : "no");
Andy Hung2e2c0bb2018-06-11 19:13:11 -07001028 }
1029
Andy Hung446f4df2019-02-21 12:26:41 -08001030 if (mLastIoBeginNs > 0) { // MMAP may not set this
1031 dprintf(fd, " Last %s occurred (msecs): %lld\n",
1032 isOutput() ? "write" : "read",
1033 (long long) (systemTime() - mLastIoBeginNs) / NANOS_PER_MILLISECOND);
1034 }
1035
1036 if (mProcessTimeMs.getN() > 0) {
1037 dprintf(fd, " Process time ms stats: %s\n", mProcessTimeMs.toString().c_str());
1038 }
1039
1040 if (mIoJitterMs.getN() > 0) {
1041 dprintf(fd, " Hal %s jitter ms stats: %s\n",
1042 isOutput() ? "write" : "read",
1043 mIoJitterMs.toString().c_str());
1044 }
1045
Andy Hunge6c37112019-02-26 17:38:10 -08001046 if (mLatencyMs.getN() > 0) {
1047 dprintf(fd, " Threadloop %s latency stats: %s\n",
1048 isOutput() ? "write" : "read",
1049 mLatencyMs.toString().c_str());
1050 }
Robert Wu06db0a32021-08-10 19:05:34 +00001051
1052 if (mMonopipePipeDepthStats.getN() > 0) {
1053 dprintf(fd, " Monopipe %s pipe depth stats: %s\n",
1054 isOutput() ? "write" : "read",
1055 mMonopipePipeDepthStats.toString().c_str());
1056 }
Eric Laurent81784c32012-11-19 14:55:58 -08001057}
1058
Andy Hung71742ab2023-07-07 13:47:37 -07001059void ThreadBase::dumpEffectChains_l(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -08001060{
1061 const size_t SIZE = 256;
1062 char buffer[SIZE];
Eric Laurent81784c32012-11-19 14:55:58 -08001063
Marco Nelissenb2208842014-02-07 14:00:50 -08001064 size_t numEffectChains = mEffectChains.size();
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +00001065 snprintf(buffer, SIZE, " %zu Effect Chains\n", numEffectChains);
Eric Laurent81784c32012-11-19 14:55:58 -08001066 write(fd, buffer, strlen(buffer));
1067
Marco Nelissenb2208842014-02-07 14:00:50 -08001068 for (size_t i = 0; i < numEffectChains; ++i) {
Andy Hungbd72c542023-06-20 18:56:17 -07001069 sp<IAfEffectChain> chain = mEffectChains[i];
Eric Laurent81784c32012-11-19 14:55:58 -08001070 if (chain != 0) {
1071 chain->dump(fd, args);
1072 }
1073 }
1074}
1075
Andy Hung71742ab2023-07-07 13:47:37 -07001076void ThreadBase::acquireWakeLock()
Eric Laurent81784c32012-11-19 14:55:58 -08001077{
1078 Mutex::Autolock _l(mLock);
Andy Hungdae27702016-10-31 14:01:16 -07001079 acquireWakeLock_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001080}
1081
Andy Hung71742ab2023-07-07 13:47:37 -07001082String16 ThreadBase::getWakeLockTag()
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001083{
1084 switch (mType) {
Glenn Kastenbcb14862015-03-05 17:11:21 -08001085 case MIXER:
1086 return String16("AudioMix");
1087 case DIRECT:
1088 return String16("AudioDirectOut");
1089 case DUPLICATING:
1090 return String16("AudioDup");
1091 case RECORD:
1092 return String16("AudioIn");
1093 case OFFLOAD:
1094 return String16("AudioOffload");
Andy Hungea840382020-05-05 21:50:17 -07001095 case MMAP_PLAYBACK:
1096 return String16("MmapPlayback");
1097 case MMAP_CAPTURE:
1098 return String16("MmapCapture");
Eric Laurent1c5e2e32021-08-18 18:50:28 +02001099 case SPATIALIZER:
1100 return String16("AudioSpatial");
Glenn Kastenbcb14862015-03-05 17:11:21 -08001101 default:
1102 ALOG_ASSERT(false);
1103 return String16("AudioUnknown");
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001104 }
1105}
1106
Andy Hung71742ab2023-07-07 13:47:37 -07001107void ThreadBase::acquireWakeLock_l()
Eric Laurent81784c32012-11-19 14:55:58 -08001108{
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001109 getPowerManager_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001110 if (mPowerManager != 0) {
1111 sp<IBinder> binder = new BBinder();
Andy Hungdae27702016-10-31 14:01:16 -07001112 // Uses AID_AUDIOSERVER for wakelock. updateWakeLockUids_l() updates with client uids.
Chris Ye6597d732020-02-28 22:38:25 -08001113 binder::Status status = mPowerManager->acquireWakeLockAsync(binder,
1114 POWERMANAGER_PARTIAL_WAKE_LOCK,
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001115 getWakeLockTag(),
Marco Nelissendcb346b2015-09-09 10:47:29 -07001116 String16("audioserver"),
Chris Ye6597d732020-02-28 22:38:25 -08001117 {} /* workSource */,
1118 {} /* historyTag */);
1119 if (status.isOk()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001120 mWakeLockToken = binder;
1121 }
Chris Ye6597d732020-02-28 22:38:25 -08001122 ALOGV("acquireWakeLock_l() %s status %d", mThreadName, status.exceptionCode());
Eric Laurent81784c32012-11-19 14:55:58 -08001123 }
Wei Jia3f273d12015-11-24 09:06:49 -08001124
Andy Hung3f0c9022016-01-15 17:49:46 -08001125 gBoottime.acquire(mWakeLockToken);
Andy Hung818e7a32016-02-16 18:08:07 -08001126 mTimestamp.mTimebaseOffset[ExtendedTimestamp::TIMEBASE_BOOTTIME] =
1127 gBoottime.getBoottimeOffset();
Eric Laurent81784c32012-11-19 14:55:58 -08001128}
1129
Andy Hung71742ab2023-07-07 13:47:37 -07001130void ThreadBase::releaseWakeLock()
Eric Laurent81784c32012-11-19 14:55:58 -08001131{
1132 Mutex::Autolock _l(mLock);
1133 releaseWakeLock_l();
1134}
1135
Andy Hung71742ab2023-07-07 13:47:37 -07001136void ThreadBase::releaseWakeLock_l()
Eric Laurent81784c32012-11-19 14:55:58 -08001137{
Andy Hung3f0c9022016-01-15 17:49:46 -08001138 gBoottime.release(mWakeLockToken);
Eric Laurent81784c32012-11-19 14:55:58 -08001139 if (mWakeLockToken != 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -08001140 ALOGV("releaseWakeLock_l() %s", mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08001141 if (mPowerManager != 0) {
Chris Ye6597d732020-02-28 22:38:25 -08001142 mPowerManager->releaseWakeLockAsync(mWakeLockToken, 0);
Eric Laurent81784c32012-11-19 14:55:58 -08001143 }
1144 mWakeLockToken.clear();
1145 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001146}
1147
Andy Hung71742ab2023-07-07 13:47:37 -07001148void ThreadBase::getPowerManager_l() {
Eric Laurent72e3f392015-05-20 14:43:50 -07001149 if (mSystemReady && mPowerManager == 0) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001150 // use checkService() to avoid blocking if power service is not up yet
1151 sp<IBinder> binder =
1152 defaultServiceManager()->checkService(String16("power"));
1153 if (binder == 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -08001154 ALOGW("Thread %s cannot connect to the power manager service", mThreadName);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001155 } else {
Chris Ye6597d732020-02-28 22:38:25 -08001156 mPowerManager = interface_cast<os::IPowerManager>(binder);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001157 binder->linkToDeath(mDeathRecipient);
1158 }
1159 }
1160}
1161
Andy Hung71742ab2023-07-07 13:47:37 -07001162void ThreadBase::updateWakeLockUids_l(const SortedVector<uid_t>& uids) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001163 getPowerManager_l();
Andy Hungdae27702016-10-31 14:01:16 -07001164
1165#if !LOG_NDEBUG
1166 std::stringstream s;
Andy Hungd01b0f12016-11-07 16:10:30 -08001167 for (uid_t uid : uids) {
Andy Hungdae27702016-10-31 14:01:16 -07001168 s << uid << " ";
1169 }
1170 ALOGD("updateWakeLockUids_l %s uids:%s", mThreadName, s.str().c_str());
1171#endif
1172
Andy Hung438e7572015-12-14 15:51:17 -08001173 if (mWakeLockToken == NULL) { // token may be NULL if AudioFlinger::systemReady() not called.
1174 if (mSystemReady) {
1175 ALOGE("no wake lock to update, but system ready!");
1176 } else {
1177 ALOGW("no wake lock to update, system not ready yet");
1178 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001179 return;
1180 }
1181 if (mPowerManager != 0) {
Andy Hung1f12a8a2016-11-07 16:10:30 -08001182 std::vector<int> uidsAsInt(uids.begin(), uids.end()); // powermanager expects uids as ints
Chris Ye6597d732020-02-28 22:38:25 -08001183 binder::Status status = mPowerManager->updateWakeLockUidsAsync(
1184 mWakeLockToken, uidsAsInt);
1185 ALOGV("updateWakeLockUids_l() %s status %d", mThreadName, status.exceptionCode());
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001186 }
1187}
1188
Andy Hung71742ab2023-07-07 13:47:37 -07001189void ThreadBase::clearPowerManager()
Eric Laurent81784c32012-11-19 14:55:58 -08001190{
1191 Mutex::Autolock _l(mLock);
1192 releaseWakeLock_l();
1193 mPowerManager.clear();
1194}
1195
Andy Hung71742ab2023-07-07 13:47:37 -07001196void ThreadBase::updateOutDevices(
jiabinc52b1ff2019-10-31 17:20:42 -07001197 const DeviceDescriptorBaseVector& outDevices __unused)
1198{
1199 ALOGE("%s should only be called in RecordThread", __func__);
1200}
1201
Andy Hung71742ab2023-07-07 13:47:37 -07001202void ThreadBase::resizeInputBuffer_l(int32_t /* maxSharedAudioHistoryMs */)
Eric Laurentec376dc2021-04-08 20:41:22 +02001203{
1204 ALOGE("%s should only be called in RecordThread", __func__);
1205}
1206
Andy Hung71742ab2023-07-07 13:47:37 -07001207void ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& /* who */)
Eric Laurent81784c32012-11-19 14:55:58 -08001208{
1209 sp<ThreadBase> thread = mThread.promote();
1210 if (thread != 0) {
1211 thread->clearPowerManager();
1212 }
1213 ALOGW("power manager service died !!!");
1214}
1215
Andy Hung71742ab2023-07-07 13:47:37 -07001216void ThreadBase::setEffectSuspended_l(
Glenn Kastend848eb42016-03-08 13:42:11 -08001217 const effect_uuid_t *type, bool suspend, audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001218{
Andy Hungbd72c542023-06-20 18:56:17 -07001219 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08001220 if (chain != 0) {
1221 if (type != NULL) {
1222 chain->setEffectSuspended_l(type, suspend);
1223 } else {
1224 chain->setEffectSuspendedAll_l(suspend);
1225 }
1226 }
1227
1228 updateSuspendedSessions_l(type, suspend, sessionId);
1229}
1230
Andy Hung71742ab2023-07-07 13:47:37 -07001231void ThreadBase::checkSuspendOnAddEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08001232{
1233 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
1234 if (index < 0) {
1235 return;
1236 }
1237
1238 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
1239 mSuspendedSessions.valueAt(index);
1240
1241 for (size_t i = 0; i < sessionEffects.size(); i++) {
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07001242 const sp<SuspendedSessionDesc>& desc = sessionEffects.valueAt(i);
Eric Laurent81784c32012-11-19 14:55:58 -08001243 for (int j = 0; j < desc->mRefCount; j++) {
Andy Hungbd72c542023-06-20 18:56:17 -07001244 if (sessionEffects.keyAt(i) == IAfEffectChain::kKeyForSuspendAll) {
Eric Laurent81784c32012-11-19 14:55:58 -08001245 chain->setEffectSuspendedAll_l(true);
1246 } else {
1247 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
1248 desc->mType.timeLow);
1249 chain->setEffectSuspended_l(&desc->mType, true);
1250 }
1251 }
1252 }
1253}
1254
Andy Hung71742ab2023-07-07 13:47:37 -07001255void ThreadBase::updateSuspendedSessions_l(const effect_uuid_t* type,
Eric Laurent81784c32012-11-19 14:55:58 -08001256 bool suspend,
Glenn Kastend848eb42016-03-08 13:42:11 -08001257 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001258{
1259 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
1260
1261 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1262
1263 if (suspend) {
1264 if (index >= 0) {
1265 sessionEffects = mSuspendedSessions.valueAt(index);
1266 } else {
1267 mSuspendedSessions.add(sessionId, sessionEffects);
1268 }
1269 } else {
1270 if (index < 0) {
1271 return;
1272 }
1273 sessionEffects = mSuspendedSessions.valueAt(index);
1274 }
1275
1276
Andy Hungbd72c542023-06-20 18:56:17 -07001277 int key = IAfEffectChain::kKeyForSuspendAll;
Eric Laurent81784c32012-11-19 14:55:58 -08001278 if (type != NULL) {
1279 key = type->timeLow;
1280 }
1281 index = sessionEffects.indexOfKey(key);
1282
1283 sp<SuspendedSessionDesc> desc;
1284 if (suspend) {
1285 if (index >= 0) {
1286 desc = sessionEffects.valueAt(index);
1287 } else {
1288 desc = new SuspendedSessionDesc();
1289 if (type != NULL) {
1290 desc->mType = *type;
1291 }
1292 sessionEffects.add(key, desc);
1293 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
1294 }
1295 desc->mRefCount++;
1296 } else {
1297 if (index < 0) {
1298 return;
1299 }
1300 desc = sessionEffects.valueAt(index);
1301 if (--desc->mRefCount == 0) {
1302 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
1303 sessionEffects.removeItemsAt(index);
1304 if (sessionEffects.isEmpty()) {
1305 ALOGV("updateSuspendedSessions_l() restore removing session %d",
1306 sessionId);
1307 mSuspendedSessions.removeItem(sessionId);
1308 }
1309 }
1310 }
1311 if (!sessionEffects.isEmpty()) {
1312 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1313 }
1314}
1315
Andy Hung71742ab2023-07-07 13:47:37 -07001316void ThreadBase::checkSuspendOnEffectEnabled(bool enabled,
Eric Laurent6b446ce2019-12-13 10:56:31 -08001317 audio_session_t sessionId,
Andy Hung71ba4b32022-10-06 12:09:49 -07001318 bool threadLocked)
1319NO_THREAD_SAFETY_ANALYSIS // manual locking
1320{
Eric Laurent6b446ce2019-12-13 10:56:31 -08001321 if (!threadLocked) {
1322 mLock.lock();
1323 }
Eric Laurent81784c32012-11-19 14:55:58 -08001324
Eric Laurent81784c32012-11-19 14:55:58 -08001325 if (mType != RECORD) {
1326 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1327 // another session. This gives the priority to well behaved effect control panels
1328 // and applications not using global effects.
1329 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
1330 // global effects
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001331 if (!audio_is_global_session(sessionId)) {
Eric Laurent81784c32012-11-19 14:55:58 -08001332 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1333 }
1334 }
1335
Eric Laurent6b446ce2019-12-13 10:56:31 -08001336 if (!threadLocked) {
1337 mLock.unlock();
Eric Laurent81784c32012-11-19 14:55:58 -08001338 }
1339}
1340
Eric Laurent4c415062016-06-17 16:14:16 -07001341// checkEffectCompatibility_l() must be called with ThreadBase::mLock held
Andy Hung71742ab2023-07-07 13:47:37 -07001342status_t RecordThread::checkEffectCompatibility_l(
Eric Laurent4c415062016-06-17 16:14:16 -07001343 const effect_descriptor_t *desc, audio_session_t sessionId)
1344{
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001345 // No global output effect sessions on record threads
1346 if (sessionId == AUDIO_SESSION_OUTPUT_MIX
1347 || sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Eric Laurent4c415062016-06-17 16:14:16 -07001348 ALOGW("checkEffectCompatibility_l(): global effect %s on record thread %s",
1349 desc->name, mThreadName);
1350 return BAD_VALUE;
1351 }
1352 // only pre processing effects on record thread
1353 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC) {
1354 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on record thread %s",
1355 desc->name, mThreadName);
1356 return BAD_VALUE;
1357 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001358
1359 // always allow effects without processing load or latency
1360 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1361 return NO_ERROR;
1362 }
1363
Eric Laurent4c415062016-06-17 16:14:16 -07001364 audio_input_flags_t flags = mInput->flags;
1365 if (hasFastCapture() || (flags & AUDIO_INPUT_FLAG_FAST)) {
1366 if (flags & AUDIO_INPUT_FLAG_RAW) {
1367 ALOGW("checkEffectCompatibility_l(): effect %s on record thread %s in raw mode",
1368 desc->name, mThreadName);
1369 return BAD_VALUE;
1370 }
1371 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1372 ALOGW("checkEffectCompatibility_l(): non HW effect %s on record thread %s in fast mode",
1373 desc->name, mThreadName);
1374 return BAD_VALUE;
1375 }
1376 }
jiabineb3bda02020-06-30 14:07:03 -07001377
Andy Hungbd72c542023-06-20 18:56:17 -07001378 if (IAfEffectModule::isHapticGenerator(&desc->type)) {
jiabineb3bda02020-06-30 14:07:03 -07001379 ALOGE("%s(): HapticGenerator is not supported in RecordThread", __func__);
1380 return BAD_VALUE;
1381 }
Eric Laurent4c415062016-06-17 16:14:16 -07001382 return NO_ERROR;
1383}
1384
1385// checkEffectCompatibility_l() must be called with ThreadBase::mLock held
Andy Hung71742ab2023-07-07 13:47:37 -07001386status_t PlaybackThread::checkEffectCompatibility_l(
Eric Laurent4c415062016-06-17 16:14:16 -07001387 const effect_descriptor_t *desc, audio_session_t sessionId)
1388{
1389 // no preprocessing on playback threads
1390 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001391 ALOGW("%s: pre processing effect %s created on playback"
1392 " thread %s", __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001393 return BAD_VALUE;
1394 }
1395
Eric Laurent3e4de772017-07-16 16:55:08 -07001396 // always allow effects without processing load or latency
1397 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1398 return NO_ERROR;
1399 }
1400
Andy Hungbd72c542023-06-20 18:56:17 -07001401 if (IAfEffectModule::isHapticGenerator(&desc->type) && mHapticChannelCount == 0) {
jiabineb3bda02020-06-30 14:07:03 -07001402 ALOGW("%s: thread doesn't support haptic playback while the effect is HapticGenerator",
1403 __func__);
1404 return BAD_VALUE;
1405 }
1406
Eric Laurentf690c462021-09-17 14:47:03 +02001407 if (memcmp(&desc->type, FX_IID_SPATIALIZER, sizeof(effect_uuid_t)) == 0
1408 && mType != SPATIALIZER) {
1409 ALOGW("%s: attempt to create a spatializer effect on a thread of type %d",
1410 __func__, mType);
1411 return BAD_VALUE;
1412 }
1413
Eric Laurent4c415062016-06-17 16:14:16 -07001414 switch (mType) {
1415 case MIXER: {
Eric Laurent4c415062016-06-17 16:14:16 -07001416 audio_output_flags_t flags = mOutput->flags;
1417 if (hasFastMixer() || (flags & AUDIO_OUTPUT_FLAG_FAST)) {
1418 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1419 // global effects are applied only to non fast tracks if they are SW
1420 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1421 break;
1422 }
1423 } else if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1424 // only post processing on output stage session
1425 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001426 ALOGW("%s: non post processing effect %s not allowed on output stage session",
1427 __func__, desc->name);
Eric Laurent4c415062016-06-17 16:14:16 -07001428 return BAD_VALUE;
1429 }
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001430 } else if (sessionId == AUDIO_SESSION_DEVICE) {
1431 // only post processing on output stage session
1432 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001433 ALOGW("%s: non post processing effect %s not allowed on device session",
1434 __func__, desc->name);
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001435 return BAD_VALUE;
1436 }
Eric Laurent4c415062016-06-17 16:14:16 -07001437 } else {
1438 // no restriction on effects applied on non fast tracks
1439 if ((hasAudioSession_l(sessionId) & ThreadBase::FAST_SESSION) == 0) {
1440 break;
1441 }
1442 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001443
Eric Laurent4c415062016-06-17 16:14:16 -07001444 if (flags & AUDIO_OUTPUT_FLAG_RAW) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001445 ALOGW("%s: effect %s on playback thread in raw mode", __func__, desc->name);
Eric Laurent4c415062016-06-17 16:14:16 -07001446 return BAD_VALUE;
1447 }
1448 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001449 ALOGW("%s: non HW effect %s on playback thread in fast mode",
1450 __func__, desc->name);
Eric Laurent4c415062016-06-17 16:14:16 -07001451 return BAD_VALUE;
1452 }
1453 }
1454 } break;
1455 case OFFLOAD:
Jean-Michel Trivi773ee952016-07-11 16:53:18 -07001456 // nothing actionable on offload threads, if the effect:
1457 // - is offloadable: the effect can be created
1458 // - is NOT offloadable: the effect should still be created, but EffectHandle::enable()
1459 // will take care of invalidating the tracks of the thread
Eric Laurent4c415062016-06-17 16:14:16 -07001460 break;
1461 case DIRECT:
1462 // Reject any effect on Direct output threads for now, since the format of
1463 // mSinkBuffer is not guaranteed to be compatible with effect processing (PCM 16 stereo).
Eric Laurentb62d0362021-10-26 17:40:18 +02001464 ALOGW("%s: effect %s on DIRECT output thread %s",
1465 __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001466 return BAD_VALUE;
1467 case DUPLICATING:
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001468 if (audio_is_global_session(sessionId)) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001469 ALOGW("%s: global effect %s on DUPLICATING thread %s",
1470 __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001471 return BAD_VALUE;
1472 }
1473 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001474 ALOGW("%s: post processing effect %s on DUPLICATING thread %s",
1475 __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001476 return BAD_VALUE;
1477 }
1478 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) != 0) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001479 ALOGW("%s: HW tunneled effect %s on DUPLICATING thread %s",
1480 __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001481 return BAD_VALUE;
1482 }
1483 break;
Eric Laurent1c5e2e32021-08-18 18:50:28 +02001484 case SPATIALIZER:
Eric Laurentb62d0362021-10-26 17:40:18 +02001485 // Global effects (AUDIO_SESSION_OUTPUT_MIX) are not supported on spatializer mixer
1486 // as there is no common accumulation buffer for sptialized and non sptialized tracks.
1487 // Post processing effects (AUDIO_SESSION_OUTPUT_STAGE or AUDIO_SESSION_DEVICE)
1488 // are supported and added after the spatializer.
1489 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1490 ALOGW("%s: global effect %s not supported on spatializer thread %s",
1491 __func__, desc->name, mThreadName);
Eric Laurentb3f315a2021-07-13 15:09:05 +02001492 return BAD_VALUE;
Eric Laurentb62d0362021-10-26 17:40:18 +02001493 } else if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1494 // only post processing , downmixer or spatializer effects on output stage session
1495 if (memcmp(&desc->type, FX_IID_SPATIALIZER, sizeof(effect_uuid_t)) == 0
1496 || memcmp(&desc->type, EFFECT_UIID_DOWNMIX, sizeof(effect_uuid_t)) == 0) {
1497 break;
1498 }
1499 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
1500 ALOGW("%s: non post processing effect %s not allowed on output stage session",
1501 __func__, desc->name);
1502 return BAD_VALUE;
1503 }
1504 } else if (sessionId == AUDIO_SESSION_DEVICE) {
1505 // only post processing on output stage session
1506 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
1507 ALOGW("%s: non post processing effect %s not allowed on device session",
1508 __func__, desc->name);
1509 return BAD_VALUE;
1510 }
Eric Laurentb3f315a2021-07-13 15:09:05 +02001511 }
1512 break;
jiabinc658e452022-10-21 20:52:21 +00001513 case BIT_PERFECT:
1514 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) != 0) {
1515 // Allow HW accelerated effects of tunnel type
1516 break;
1517 }
1518 // As bit-perfect tracks will not be allowed to apply audio effect that will touch the audio
1519 // data, effects will not be allowed on 1) global effects (AUDIO_SESSION_OUTPUT_MIX),
1520 // 2) post-processing effects (AUDIO_SESSION_OUTPUT_STAGE or AUDIO_SESSION_DEVICE) and
1521 // 3) there is any bit-perfect track with the given session id.
1522 if (sessionId == AUDIO_SESSION_OUTPUT_MIX || sessionId == AUDIO_SESSION_OUTPUT_STAGE ||
1523 sessionId == AUDIO_SESSION_DEVICE) {
1524 ALOGW("%s: effect %s not supported on bit-perfect thread %s",
1525 __func__, desc->name, mThreadName);
1526 return BAD_VALUE;
1527 } else if ((hasAudioSession_l(sessionId) & ThreadBase::BIT_PERFECT_SESSION) != 0) {
1528 ALOGW("%s: effect %s not supported as there is a bit-perfect track with session as %d",
1529 __func__, desc->name, sessionId);
1530 return BAD_VALUE;
1531 }
1532 break;
Eric Laurent4c415062016-06-17 16:14:16 -07001533 default:
1534 LOG_ALWAYS_FATAL("checkEffectCompatibility_l(): wrong thread type %d", mType);
1535 }
1536
1537 return NO_ERROR;
1538}
1539
Eric Laurent81784c32012-11-19 14:55:58 -08001540// ThreadBase::createEffect_l() must be called with AudioFlinger::mLock held
Andy Hung71742ab2023-07-07 13:47:37 -07001541sp<IAfEffectHandle> ThreadBase::createEffect_l(
Andy Hungd65869f2023-06-27 17:05:02 -07001542 const sp<Client>& client,
Eric Laurent81784c32012-11-19 14:55:58 -08001543 const sp<IEffectClient>& effectClient,
1544 int32_t priority,
Glenn Kastend848eb42016-03-08 13:42:11 -08001545 audio_session_t sessionId,
Eric Laurent81784c32012-11-19 14:55:58 -08001546 effect_descriptor_t *desc,
1547 int *enabled,
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001548 status_t *status,
Eric Laurent2fe0acd2020-03-13 14:30:46 -07001549 bool pinned,
Eric Laurentde8caf42021-08-11 17:19:25 +02001550 bool probe,
1551 bool notifyFramesProcessed)
Eric Laurent81784c32012-11-19 14:55:58 -08001552{
Andy Hungbd72c542023-06-20 18:56:17 -07001553 sp<IAfEffectModule> effect;
1554 sp<IAfEffectHandle> handle;
Eric Laurent81784c32012-11-19 14:55:58 -08001555 status_t lStatus;
Andy Hungbd72c542023-06-20 18:56:17 -07001556 sp<IAfEffectChain> chain;
Eric Laurent81784c32012-11-19 14:55:58 -08001557 bool chainCreated = false;
1558 bool effectCreated = false;
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001559 audio_unique_id_t effectId = AUDIO_UNIQUE_ID_USE_UNSPECIFIED;
Eric Laurent81784c32012-11-19 14:55:58 -08001560
1561 lStatus = initCheck();
1562 if (lStatus != NO_ERROR) {
1563 ALOGW("createEffect_l() Audio driver not initialized.");
1564 goto Exit;
1565 }
1566
Eric Laurent81784c32012-11-19 14:55:58 -08001567 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
1568
1569 { // scope for mLock
1570 Mutex::Autolock _l(mLock);
1571
Eric Laurent4c415062016-06-17 16:14:16 -07001572 lStatus = checkEffectCompatibility_l(desc, sessionId);
Eric Laurent2fe0acd2020-03-13 14:30:46 -07001573 if (probe || lStatus != NO_ERROR) {
Eric Laurent4c415062016-06-17 16:14:16 -07001574 goto Exit;
1575 }
1576
Eric Laurent81784c32012-11-19 14:55:58 -08001577 // check for existing effect chain with the requested audio session
1578 chain = getEffectChain_l(sessionId);
1579 if (chain == 0) {
1580 // create a new chain for this session
1581 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
Andy Hungbd72c542023-06-20 18:56:17 -07001582 chain = IAfEffectChain::create(this, sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08001583 addEffectChain_l(chain);
1584 chain->setStrategy(getStrategyForSession_l(sessionId));
1585 chainCreated = true;
1586 } else {
1587 effect = chain->getEffectFromDesc_l(desc);
1588 }
1589
1590 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
1591
1592 if (effect == 0) {
Andy Hung2cbc2722023-07-17 17:05:00 -07001593 effectId = mAfThreadCallback->nextUniqueId(AUDIO_UNIQUE_ID_USE_EFFECT);
Eric Laurent81784c32012-11-19 14:55:58 -08001594 // create a new effect module if none present in the chain
Eric Laurent6b446ce2019-12-13 10:56:31 -08001595 lStatus = chain->createEffect_l(effect, desc, effectId, sessionId, pinned);
Eric Laurent81784c32012-11-19 14:55:58 -08001596 if (lStatus != NO_ERROR) {
1597 goto Exit;
1598 }
1599 effectCreated = true;
1600
jiabinc52b1ff2019-10-31 17:20:42 -07001601 // FIXME: use vector of device and address when effect interface is ready.
jiabin8f278ee2019-11-11 12:16:27 -08001602 effect->setDevices(outDeviceTypeAddrs());
1603 effect->setInputDevice(inDeviceTypeAddr());
Andy Hung2cbc2722023-07-17 17:05:00 -07001604 effect->setMode(mAfThreadCallback->getMode());
Eric Laurent81784c32012-11-19 14:55:58 -08001605 effect->setAudioSource(mAudioSource);
1606 }
jiabin1319f5a2021-03-30 22:21:24 +00001607 if (effect->isHapticGenerator()) {
1608 // TODO(b/184194057): Use the vibrator information from the vibrator that will be used
1609 // for the HapticGenerator.
Lais Andradebc3f37a2021-07-02 00:13:19 +01001610 const std::optional<media::AudioVibratorInfo> defaultVibratorInfo =
Andy Hung2cbc2722023-07-17 17:05:00 -07001611 std::move(mAfThreadCallback->getDefaultVibratorInfo_l());
Lais Andradebc3f37a2021-07-02 00:13:19 +01001612 if (defaultVibratorInfo) {
jiabin1319f5a2021-03-30 22:21:24 +00001613 // Only set the vibrator info when it is a valid one.
Lais Andradebc3f37a2021-07-02 00:13:19 +01001614 effect->setVibratorInfo(*defaultVibratorInfo);
jiabin1319f5a2021-03-30 22:21:24 +00001615 }
1616 }
Eric Laurent81784c32012-11-19 14:55:58 -08001617 // create effect handle and connect it to effect module
Andy Hungbd72c542023-06-20 18:56:17 -07001618 handle = IAfEffectHandle::create(
1619 effect, client, effectClient, priority, notifyFramesProcessed);
Glenn Kastene75da402013-11-20 13:54:52 -08001620 lStatus = handle->initCheck();
1621 if (lStatus == OK) {
1622 lStatus = effect->addHandle(handle.get());
Eric Laurentb3f315a2021-07-13 15:09:05 +02001623 sendCheckOutputStageEffectsEvent_l();
Glenn Kastene75da402013-11-20 13:54:52 -08001624 }
Eric Laurent81784c32012-11-19 14:55:58 -08001625 if (enabled != NULL) {
1626 *enabled = (int)effect->isEnabled();
1627 }
1628 }
1629
1630Exit:
Eric Laurent2fe0acd2020-03-13 14:30:46 -07001631 if (!probe && lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurent81784c32012-11-19 14:55:58 -08001632 Mutex::Autolock _l(mLock);
1633 if (effectCreated) {
1634 chain->removeEffect_l(effect);
1635 }
Eric Laurent81784c32012-11-19 14:55:58 -08001636 if (chainCreated) {
1637 removeEffectChain_l(chain);
1638 }
haobo101735295ff7b0d2017-03-17 17:44:03 +08001639 // handle must be cleared by caller to avoid deadlock.
Eric Laurent81784c32012-11-19 14:55:58 -08001640 }
1641
Glenn Kasten9156ef32013-08-06 15:39:08 -07001642 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001643 return handle;
1644}
1645
Andy Hung71742ab2023-07-07 13:47:37 -07001646void ThreadBase::disconnectEffectHandle(IAfEffectHandle* handle,
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001647 bool unpinIfLast)
1648{
1649 bool remove = false;
Andy Hungbd72c542023-06-20 18:56:17 -07001650 sp<IAfEffectModule> effect;
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001651 {
1652 Mutex::Autolock _l(mLock);
Andy Hungbd72c542023-06-20 18:56:17 -07001653 sp<IAfEffectBase> effectBase = handle->effect().promote();
Eric Laurent41709552019-12-16 19:34:05 -08001654 if (effectBase == nullptr) {
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001655 return;
1656 }
Eric Laurentb82e6b72019-11-22 17:25:04 -08001657 effect = effectBase->asEffectModule();
1658 if (effect == nullptr) {
1659 return;
1660 }
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001661 // restore suspended effects if the disconnected handle was enabled and the last one.
1662 remove = (effect->removeHandle(handle) == 0) && (!effect->isPinned() || unpinIfLast);
1663 if (remove) {
1664 removeEffect_l(effect, true);
1665 }
Eric Laurentb3f315a2021-07-13 15:09:05 +02001666 sendCheckOutputStageEffectsEvent_l();
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001667 }
1668 if (remove) {
Andy Hung2cbc2722023-07-17 17:05:00 -07001669 mAfThreadCallback->updateOrphanEffectChains(effect);
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001670 if (handle->enabled()) {
Eric Laurent6b446ce2019-12-13 10:56:31 -08001671 effect->checkSuspendOnEffectEnabled(false, false /*threadLocked*/);
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001672 }
1673 }
1674}
1675
Andy Hung71742ab2023-07-07 13:47:37 -07001676void ThreadBase::onEffectEnable(const sp<IAfEffectModule>& effect) {
Andy Hungea840382020-05-05 21:50:17 -07001677 if (isOffloadOrMmap()) {
Eric Laurent6b446ce2019-12-13 10:56:31 -08001678 Mutex::Autolock _l(mLock);
1679 broadcast_l();
1680 }
1681 if (!effect->isOffloadable()) {
1682 if (mType == ThreadBase::OFFLOAD) {
1683 PlaybackThread *t = (PlaybackThread *)this;
1684 t->invalidateTracks(AUDIO_STREAM_MUSIC);
1685 }
1686 if (effect->sessionId() == AUDIO_SESSION_OUTPUT_MIX) {
Andy Hung2cbc2722023-07-17 17:05:00 -07001687 mAfThreadCallback->onNonOffloadableGlobalEffectEnable();
Eric Laurent6b446ce2019-12-13 10:56:31 -08001688 }
1689 }
1690}
1691
Andy Hung71742ab2023-07-07 13:47:37 -07001692void ThreadBase::onEffectDisable() {
Andy Hungea840382020-05-05 21:50:17 -07001693 if (isOffloadOrMmap()) {
Eric Laurent6b446ce2019-12-13 10:56:31 -08001694 Mutex::Autolock _l(mLock);
1695 broadcast_l();
1696 }
1697}
1698
Andy Hung71742ab2023-07-07 13:47:37 -07001699sp<IAfEffectModule> ThreadBase::getEffect(audio_session_t sessionId,
Andy Hung4989d312023-06-29 21:19:25 -07001700 int effectId) const
Eric Laurent81784c32012-11-19 14:55:58 -08001701{
1702 Mutex::Autolock _l(mLock);
1703 return getEffect_l(sessionId, effectId);
1704}
1705
Andy Hung71742ab2023-07-07 13:47:37 -07001706sp<IAfEffectModule> ThreadBase::getEffect_l(audio_session_t sessionId,
Andy Hung4989d312023-06-29 21:19:25 -07001707 int effectId) const
Eric Laurent81784c32012-11-19 14:55:58 -08001708{
Andy Hungbd72c542023-06-20 18:56:17 -07001709 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08001710 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
1711}
1712
Andy Hung71742ab2023-07-07 13:47:37 -07001713std::vector<int> ThreadBase::getEffectIds_l(audio_session_t sessionId) const
Eric Laurent6c796322019-04-09 14:13:17 -07001714{
Andy Hungbd72c542023-06-20 18:56:17 -07001715 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent6c796322019-04-09 14:13:17 -07001716 return chain != nullptr ? chain->getEffectIds() : std::vector<int>{};
1717}
1718
Eric Laurent81784c32012-11-19 14:55:58 -08001719// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
1720// PlaybackThread::mLock held
Andy Hung71742ab2023-07-07 13:47:37 -07001721status_t ThreadBase::addEffect_l(const sp<IAfEffectModule>& effect)
Eric Laurent81784c32012-11-19 14:55:58 -08001722{
1723 // check for existing effect chain with the requested audio session
Glenn Kastend848eb42016-03-08 13:42:11 -08001724 audio_session_t sessionId = effect->sessionId();
Andy Hungbd72c542023-06-20 18:56:17 -07001725 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08001726 bool chainCreated = false;
1727
Eric Laurent5baf2af2013-09-12 17:37:00 -07001728 ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(),
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001729 "addEffect_l() on offloaded thread %p: effect %s does not support offload flags %#x",
Eric Laurent5baf2af2013-09-12 17:37:00 -07001730 this, effect->desc().name, effect->desc().flags);
1731
Eric Laurent81784c32012-11-19 14:55:58 -08001732 if (chain == 0) {
1733 // create a new chain for this session
1734 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
Andy Hungbd72c542023-06-20 18:56:17 -07001735 chain = IAfEffectChain::create(this, sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08001736 addEffectChain_l(chain);
1737 chain->setStrategy(getStrategyForSession_l(sessionId));
1738 chainCreated = true;
1739 }
1740 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
1741
1742 if (chain->getEffectFromId_l(effect->id()) != 0) {
1743 ALOGW("addEffect_l() %p effect %s already present in chain %p",
1744 this, effect->desc().name, chain.get());
1745 return BAD_VALUE;
1746 }
1747
Eric Laurent5baf2af2013-09-12 17:37:00 -07001748 effect->setOffloaded(mType == OFFLOAD, mId);
1749
Eric Laurent81784c32012-11-19 14:55:58 -08001750 status_t status = chain->addEffect_l(effect);
1751 if (status != NO_ERROR) {
1752 if (chainCreated) {
1753 removeEffectChain_l(chain);
1754 }
1755 return status;
1756 }
1757
jiabin8f278ee2019-11-11 12:16:27 -08001758 effect->setDevices(outDeviceTypeAddrs());
1759 effect->setInputDevice(inDeviceTypeAddr());
Andy Hung2cbc2722023-07-17 17:05:00 -07001760 effect->setMode(mAfThreadCallback->getMode());
Eric Laurent81784c32012-11-19 14:55:58 -08001761 effect->setAudioSource(mAudioSource);
Eric Laurentd8365c52017-07-16 15:27:05 -07001762
Eric Laurent81784c32012-11-19 14:55:58 -08001763 return NO_ERROR;
1764}
1765
Andy Hung71742ab2023-07-07 13:47:37 -07001766void ThreadBase::removeEffect_l(const sp<IAfEffectModule>& effect, bool release) {
Eric Laurent81784c32012-11-19 14:55:58 -08001767
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001768 ALOGV("%s %p effect %p", __FUNCTION__, this, effect.get());
Eric Laurent81784c32012-11-19 14:55:58 -08001769 effect_descriptor_t desc = effect->desc();
1770 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
1771 detachAuxEffect_l(effect->id());
1772 }
1773
Andy Hungbd72c542023-06-20 18:56:17 -07001774 sp<IAfEffectChain> chain = effect->getCallback()->chain().promote();
Eric Laurent81784c32012-11-19 14:55:58 -08001775 if (chain != 0) {
1776 // remove effect chain if removing last effect
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001777 if (chain->removeEffect_l(effect, release) == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08001778 removeEffectChain_l(chain);
1779 }
1780 } else {
1781 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
1782 }
1783}
1784
Andy Hung71742ab2023-07-07 13:47:37 -07001785void ThreadBase::lockEffectChains_l(
Andy Hungbd72c542023-06-20 18:56:17 -07001786 Vector<sp<IAfEffectChain>>& effectChains)
Andy Hung71ba4b32022-10-06 12:09:49 -07001787NO_THREAD_SAFETY_ANALYSIS // calls EffectChain::lock()
Eric Laurent81784c32012-11-19 14:55:58 -08001788{
1789 effectChains = mEffectChains;
1790 for (size_t i = 0; i < mEffectChains.size(); i++) {
1791 mEffectChains[i]->lock();
1792 }
1793}
1794
Andy Hung71742ab2023-07-07 13:47:37 -07001795void ThreadBase::unlockEffectChains(
Andy Hungbd72c542023-06-20 18:56:17 -07001796 const Vector<sp<IAfEffectChain>>& effectChains)
Andy Hung71ba4b32022-10-06 12:09:49 -07001797NO_THREAD_SAFETY_ANALYSIS // calls EffectChain::unlock()
Eric Laurent81784c32012-11-19 14:55:58 -08001798{
1799 for (size_t i = 0; i < effectChains.size(); i++) {
1800 effectChains[i]->unlock();
1801 }
1802}
1803
Andy Hung71742ab2023-07-07 13:47:37 -07001804sp<IAfEffectChain> ThreadBase::getEffectChain(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08001805{
1806 Mutex::Autolock _l(mLock);
1807 return getEffectChain_l(sessionId);
1808}
1809
Andy Hung71742ab2023-07-07 13:47:37 -07001810sp<IAfEffectChain> ThreadBase::getEffectChain_l(audio_session_t sessionId)
Glenn Kastend848eb42016-03-08 13:42:11 -08001811 const
Eric Laurent81784c32012-11-19 14:55:58 -08001812{
1813 size_t size = mEffectChains.size();
1814 for (size_t i = 0; i < size; i++) {
1815 if (mEffectChains[i]->sessionId() == sessionId) {
1816 return mEffectChains[i];
1817 }
1818 }
1819 return 0;
1820}
1821
Andy Hung71742ab2023-07-07 13:47:37 -07001822void ThreadBase::setMode(audio_mode_t mode)
Eric Laurent81784c32012-11-19 14:55:58 -08001823{
1824 Mutex::Autolock _l(mLock);
1825 size_t size = mEffectChains.size();
1826 for (size_t i = 0; i < size; i++) {
1827 mEffectChains[i]->setMode_l(mode);
1828 }
1829}
1830
Andy Hung71742ab2023-07-07 13:47:37 -07001831void ThreadBase::toAudioPortConfig(struct audio_port_config* config)
Eric Laurent83b88082014-06-20 18:31:16 -07001832{
1833 config->type = AUDIO_PORT_TYPE_MIX;
1834 config->ext.mix.handle = mId;
1835 config->sample_rate = mSampleRate;
Mikhail Naganov88d54da2023-09-11 11:53:50 -07001836 config->format = mHALFormat;
Eric Laurent83b88082014-06-20 18:31:16 -07001837 config->channel_mask = mChannelMask;
1838 config->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
1839 AUDIO_PORT_CONFIG_FORMAT;
1840}
1841
Andy Hung71742ab2023-07-07 13:47:37 -07001842void ThreadBase::systemReady()
Eric Laurent72e3f392015-05-20 14:43:50 -07001843{
1844 Mutex::Autolock _l(mLock);
1845 if (mSystemReady) {
1846 return;
1847 }
1848 mSystemReady = true;
1849
1850 for (size_t i = 0; i < mPendingConfigEvents.size(); i++) {
1851 sendConfigEvent_l(mPendingConfigEvents.editItemAt(i));
1852 }
1853 mPendingConfigEvents.clear();
1854}
1855
Andy Hungdae27702016-10-31 14:01:16 -07001856template <typename T>
Andy Hung71742ab2023-07-07 13:47:37 -07001857ssize_t ThreadBase::ActiveTracks<T>::add(const sp<T>& track) {
Andy Hungdae27702016-10-31 14:01:16 -07001858 ssize_t index = mActiveTracks.indexOf(track);
1859 if (index >= 0) {
1860 ALOGW("ActiveTracks<T>::add track %p already there", track.get());
1861 return index;
1862 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001863 logTrack("add", track);
Andy Hungdae27702016-10-31 14:01:16 -07001864 mActiveTracksGeneration++;
1865 mLatestActiveTrack = track;
1866 ++mBatteryCounter[track->uid()].second;
Kevin Rocard069c2712018-03-29 19:09:14 -07001867 mHasChanged = true;
Andy Hungdae27702016-10-31 14:01:16 -07001868 return mActiveTracks.add(track);
1869}
1870
1871template <typename T>
Andy Hung71742ab2023-07-07 13:47:37 -07001872ssize_t ThreadBase::ActiveTracks<T>::remove(const sp<T>& track) {
Andy Hungdae27702016-10-31 14:01:16 -07001873 ssize_t index = mActiveTracks.remove(track);
1874 if (index < 0) {
1875 ALOGW("ActiveTracks<T>::remove nonexistent track %p", track.get());
1876 return index;
1877 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001878 logTrack("remove", track);
Andy Hungdae27702016-10-31 14:01:16 -07001879 mActiveTracksGeneration++;
1880 --mBatteryCounter[track->uid()].second;
1881 // mLatestActiveTrack is not cleared even if is the same as track.
Kevin Rocard069c2712018-03-29 19:09:14 -07001882 mHasChanged = true;
Andy Hung8946a282018-04-19 20:04:56 -07001883#ifdef TEE_SINK
1884 track->dumpTee(-1 /* fd */, "_REMOVE");
1885#endif
Andy Hungc2b11cb2020-04-22 09:04:01 -07001886 track->logEndInterval(); // log to MediaMetrics
Andy Hungdae27702016-10-31 14:01:16 -07001887 return index;
1888}
1889
1890template <typename T>
Andy Hung71742ab2023-07-07 13:47:37 -07001891void ThreadBase::ActiveTracks<T>::clear() {
Andy Hungdae27702016-10-31 14:01:16 -07001892 for (const sp<T> &track : mActiveTracks) {
1893 BatteryNotifier::getInstance().noteStopAudio(track->uid());
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001894 logTrack("clear", track);
Andy Hungdae27702016-10-31 14:01:16 -07001895 }
1896 mLastActiveTracksGeneration = mActiveTracksGeneration;
Kevin Rocard069c2712018-03-29 19:09:14 -07001897 if (!mActiveTracks.empty()) { mHasChanged = true; }
Andy Hungdae27702016-10-31 14:01:16 -07001898 mActiveTracks.clear();
1899 mLatestActiveTrack.clear();
1900 mBatteryCounter.clear();
1901}
1902
1903template <typename T>
Andy Hung71742ab2023-07-07 13:47:37 -07001904void ThreadBase::ActiveTracks<T>::updatePowerState(
Andy Hung71ba4b32022-10-06 12:09:49 -07001905 const sp<ThreadBase>& thread, bool force) {
Andy Hungdae27702016-10-31 14:01:16 -07001906 // Updates ActiveTracks client uids to the thread wakelock.
1907 if (mActiveTracksGeneration != mLastActiveTracksGeneration || force) {
1908 thread->updateWakeLockUids_l(getWakeLockUids());
1909 mLastActiveTracksGeneration = mActiveTracksGeneration;
1910 }
1911
1912 // Updates BatteryNotifier uids
1913 for (auto it = mBatteryCounter.begin(); it != mBatteryCounter.end();) {
1914 const uid_t uid = it->first;
1915 ssize_t &previous = it->second.first;
1916 ssize_t &current = it->second.second;
1917 if (current > 0) {
1918 if (previous == 0) {
1919 BatteryNotifier::getInstance().noteStartAudio(uid);
1920 }
1921 previous = current;
1922 ++it;
1923 } else if (current == 0) {
1924 if (previous > 0) {
1925 BatteryNotifier::getInstance().noteStopAudio(uid);
1926 }
1927 it = mBatteryCounter.erase(it); // std::map<> is stable on iterator erase.
1928 } else /* (current < 0) */ {
1929 LOG_ALWAYS_FATAL("negative battery count %zd", current);
1930 }
1931 }
1932}
Eric Laurent83b88082014-06-20 18:31:16 -07001933
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001934template <typename T>
Andy Hung71742ab2023-07-07 13:47:37 -07001935bool ThreadBase::ActiveTracks<T>::readAndClearHasChanged() {
Jasmine Chaeaa10e42021-05-11 10:11:14 +08001936 bool hasChanged = mHasChanged;
Kevin Rocard069c2712018-03-29 19:09:14 -07001937 mHasChanged = false;
Jasmine Chaeaa10e42021-05-11 10:11:14 +08001938
1939 for (const sp<T> &track : mActiveTracks) {
1940 // Do not short-circuit as all hasChanged states must be reset
1941 // as all the metadata are going to be sent
1942 hasChanged |= track->readAndClearHasChanged();
1943 }
Kevin Rocard069c2712018-03-29 19:09:14 -07001944 return hasChanged;
1945}
1946
1947template <typename T>
Andy Hung71742ab2023-07-07 13:47:37 -07001948void ThreadBase::ActiveTracks<T>::logTrack(
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001949 const char *funcName, const sp<T> &track) const {
1950 if (mLocalLog != nullptr) {
1951 String8 result;
1952 track->appendDump(result, false /* active */);
Tomasz Wasilczyk8f36f6e2023-08-15 20:59:35 +00001953 mLocalLog->log("AT::%-10s(%p) %s", funcName, track.get(), result.c_str());
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001954 }
1955}
1956
Andy Hung71742ab2023-07-07 13:47:37 -07001957void ThreadBase::broadcast_l()
Eric Laurent6acd1d42017-01-04 14:23:29 -08001958{
1959 // Thread could be blocked waiting for async
1960 // so signal it to handle state changes immediately
1961 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
1962 // be lost so we also flag to prevent it blocking on mWaitWorkCV
1963 mSignalPending = true;
1964 mWaitWorkCV.broadcast();
1965}
1966
Andy Hungd0979812019-02-21 15:51:44 -08001967// Call only from threadLoop() or when it is idle.
1968// Do not call from high performance code as this may do binder rpc to the MediaMetrics service.
Andy Hung71742ab2023-07-07 13:47:37 -07001969void ThreadBase::sendStatistics(bool force)
Andy Hungd0979812019-02-21 15:51:44 -08001970{
1971 // Do not log if we have no stats.
1972 // We choose the timestamp verifier because it is the most likely item to be present.
1973 const int64_t nstats = mTimestampVerifier.getN() - mLastRecordedTimestampVerifierN;
1974 if (nstats == 0) {
1975 return;
1976 }
1977
1978 // Don't log more frequently than once per 12 hours.
1979 // We use BOOTTIME to include suspend time.
1980 const int64_t timeNs = systemTime(SYSTEM_TIME_BOOTTIME);
1981 const int64_t sinceNs = timeNs - mLastRecordedTimeNs; // ok if mLastRecordedTimeNs = 0
1982 if (!force && sinceNs <= 12 * NANOS_PER_HOUR) {
1983 return;
1984 }
1985
1986 mLastRecordedTimestampVerifierN = mTimestampVerifier.getN();
1987 mLastRecordedTimeNs = timeNs;
1988
Ray Essickf27e9872019-12-07 06:28:46 -08001989 std::unique_ptr<mediametrics::Item> item(mediametrics::Item::create("audiothread"));
Andy Hungd0979812019-02-21 15:51:44 -08001990
1991#define MM_PREFIX "android.media.audiothread." // avoid cut-n-paste errors.
1992
1993 // thread configuration
1994 item->setInt32(MM_PREFIX "id", (int32_t)mId); // IO handle
1995 // item->setInt32(MM_PREFIX "portId", (int32_t)mPortId);
1996 item->setCString(MM_PREFIX "type", threadTypeToString(mType));
1997 item->setInt32(MM_PREFIX "sampleRate", (int32_t)mSampleRate);
1998 item->setInt64(MM_PREFIX "channelMask", (int64_t)mChannelMask);
1999 item->setCString(MM_PREFIX "encoding", toString(mFormat).c_str());
2000 item->setInt32(MM_PREFIX "frameCount", (int32_t)mFrameCount);
jiabinc52b1ff2019-10-31 17:20:42 -07002001 item->setCString(MM_PREFIX "outDevice", toString(outDeviceTypes()).c_str());
2002 item->setCString(MM_PREFIX "inDevice", toString(inDeviceType()).c_str());
Andy Hungd0979812019-02-21 15:51:44 -08002003
2004 // thread statistics
2005 if (mIoJitterMs.getN() > 0) {
2006 item->setDouble(MM_PREFIX "ioJitterMs.mean", mIoJitterMs.getMean());
2007 item->setDouble(MM_PREFIX "ioJitterMs.std", mIoJitterMs.getStdDev());
2008 }
2009 if (mProcessTimeMs.getN() > 0) {
2010 item->setDouble(MM_PREFIX "processTimeMs.mean", mProcessTimeMs.getMean());
2011 item->setDouble(MM_PREFIX "processTimeMs.std", mProcessTimeMs.getStdDev());
2012 }
2013 const auto tsjitter = mTimestampVerifier.getJitterMs();
2014 if (tsjitter.getN() > 0) {
2015 item->setDouble(MM_PREFIX "timestampJitterMs.mean", tsjitter.getMean());
2016 item->setDouble(MM_PREFIX "timestampJitterMs.std", tsjitter.getStdDev());
2017 }
2018 if (mLatencyMs.getN() > 0) {
2019 item->setDouble(MM_PREFIX "latencyMs.mean", mLatencyMs.getMean());
2020 item->setDouble(MM_PREFIX "latencyMs.std", mLatencyMs.getStdDev());
2021 }
Robert Wu06db0a32021-08-10 19:05:34 +00002022 if (mMonopipePipeDepthStats.getN() > 0) {
2023 item->setDouble(MM_PREFIX "monopipePipeDepthStats.mean",
2024 mMonopipePipeDepthStats.getMean());
2025 item->setDouble(MM_PREFIX "monopipePipeDepthStats.std",
2026 mMonopipePipeDepthStats.getStdDev());
2027 }
Andy Hungd0979812019-02-21 15:51:44 -08002028
2029 item->selfrecord();
2030}
2031
Andy Hung71742ab2023-07-07 13:47:37 -07002032product_strategy_t ThreadBase::getStrategyForStream(audio_stream_type_t stream) const
Eric Laurentd66d7a12021-07-13 13:35:32 +02002033{
Andy Hung2cbc2722023-07-17 17:05:00 -07002034 if (!mAfThreadCallback->isAudioPolicyReady()) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02002035 return PRODUCT_STRATEGY_NONE;
2036 }
2037 return AudioSystem::getStrategyForStream(stream);
2038}
2039
Vlad Popa6fbbfbf2023-02-22 15:05:43 +01002040// startMelComputation_l() must be called with AudioFlinger::mLock held
Andy Hung71742ab2023-07-07 13:47:37 -07002041void ThreadBase::startMelComputation_l(
Vlad Popa6fbbfbf2023-02-22 15:05:43 +01002042 const sp<audio_utils::MelProcessor>& /*processor*/)
2043{
2044 // Do nothing
2045 ALOGW("%s: ThreadBase does not support CSD", __func__);
2046}
2047
2048// stopMelComputation_l() must be called with AudioFlinger::mLock held
Andy Hung71742ab2023-07-07 13:47:37 -07002049void ThreadBase::stopMelComputation_l()
Vlad Popa6fbbfbf2023-02-22 15:05:43 +01002050{
2051 // Do nothing
2052 ALOGW("%s: ThreadBase does not support CSD", __func__);
2053}
2054
Eric Laurent81784c32012-11-19 14:55:58 -08002055// ----------------------------------------------------------------------------
2056// Playback
2057// ----------------------------------------------------------------------------
2058
Andy Hung2cbc2722023-07-17 17:05:00 -07002059PlaybackThread::PlaybackThread(const sp<IAfThreadCallback>& afThreadCallback,
Eric Laurent81784c32012-11-19 14:55:58 -08002060 AudioStreamOut* output,
2061 audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -07002062 type_t type,
Eric Laurentf1f22e72021-07-13 14:04:14 +02002063 bool systemReady,
2064 audio_config_base_t *mixerConfig)
Andy Hung2cbc2722023-07-17 17:05:00 -07002065 : ThreadBase(afThreadCallback, id, type, systemReady, true /* isOut */),
Andy Hung2098f272014-02-27 14:00:06 -08002066 mNormalFrameCount(0), mSinkBuffer(NULL),
Eric Laurent1c5e2e32021-08-18 18:50:28 +02002067 mMixerBufferEnabled(AudioFlinger::kEnableExtendedPrecision || type == SPATIALIZER),
Andy Hung69aed5f2014-02-25 17:24:40 -08002068 mMixerBuffer(NULL),
2069 mMixerBufferSize(0),
2070 mMixerBufferFormat(AUDIO_FORMAT_INVALID),
2071 mMixerBufferValid(false),
Eric Laurent1c5e2e32021-08-18 18:50:28 +02002072 mEffectBufferEnabled(AudioFlinger::kEnableExtendedPrecision || type == SPATIALIZER),
Andy Hung98ef9782014-03-04 14:46:50 -08002073 mEffectBuffer(NULL),
2074 mEffectBufferSize(0),
2075 mEffectBufferFormat(AUDIO_FORMAT_INVALID),
2076 mEffectBufferValid(false),
Glenn Kastenc1fac192013-08-06 07:41:36 -07002077 mSuspended(0), mBytesWritten(0),
Andy Hungc54b1ff2016-02-23 14:07:07 -08002078 mFramesWritten(0),
Andy Hung238fa3d2016-07-28 10:53:22 -07002079 mSuspendedFrames(0),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002080 mActiveTracks(&this->mLocalLog),
Eric Laurent81784c32012-11-19 14:55:58 -08002081 // mStreamTypes[] initialized in constructor body
Andy Hung1bc088a2018-02-09 15:57:31 -08002082 mTracks(type == MIXER),
Eric Laurent81784c32012-11-19 14:55:58 -08002083 mOutput(output),
Andy Hung446f4df2019-02-21 12:26:41 -08002084 mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
Eric Laurent81784c32012-11-19 14:55:58 -08002085 mMixerStatus(MIXER_IDLE),
2086 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002087 mStandbyDelayNs(AudioFlinger::mStandbyTimeInNsecs),
Eric Laurentbfb1b832013-01-07 09:53:42 -08002088 mBytesRemaining(0),
2089 mCurrentWriteLength(0),
2090 mUseAsyncWrite(false),
Eric Laurent3b4529e2013-09-05 18:09:19 -07002091 mWriteAckSequence(0),
2092 mDrainSequence(0),
Andy Hung01b29482023-07-19 16:22:58 -07002093 mScreenState(mAfThreadCallback->getScreenState()),
Eric Laurent81784c32012-11-19 14:55:58 -08002094 // index 0 is reserved for normal mixer's submix
Glenn Kastendc2c50b2016-04-21 08:13:14 -07002095 mFastTrackAvailMask(((1 << FastMixerState::sMaxFastTracks) - 1) & ~1),
Eric Laurent7c29ec92017-09-20 17:54:22 -07002096 mHwSupportsPause(false), mHwPaused(false), mFlushPending(false),
Eric Laurent74c38dc2020-12-23 18:19:44 +01002097 mLeftVolFloat(-1.0), mRightVolFloat(-1.0),
Brian Lindahl9e661ad2022-07-27 18:01:07 +02002098 mDownStreamPatch{},
Eric Laurentb0463942022-12-20 16:31:10 +01002099 mIsTimestampAdvancing(kMinimumTimeBetweenTimestampChecksNs)
Eric Laurent81784c32012-11-19 14:55:58 -08002100{
Glenn Kastend7dca052015-03-05 16:05:54 -08002101 snprintf(mThreadName, kThreadNameLength, "AudioOut_%X", id);
Andy Hung2cbc2722023-07-17 17:05:00 -07002102 mNBLogWriter = afThreadCallback->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08002103
2104 // Assumes constructor is called by AudioFlinger with it's mLock held, but
2105 // it would be safer to explicitly pass initial masterVolume/masterMute as
2106 // parameter.
2107 //
2108 // If the HAL we are using has support for master volume or master mute,
2109 // then do not attenuate or mute during mixing (just leave the volume at 1.0
2110 // and the mute set to false).
Andy Hung2cbc2722023-07-17 17:05:00 -07002111 mMasterVolume = afThreadCallback->masterVolume_l();
2112 mMasterMute = afThreadCallback->masterMute_l();
George Burgess IV5e4d86f2020-02-18 12:55:36 -08002113 if (mOutput->audioHwDev) {
Eric Laurent81784c32012-11-19 14:55:58 -08002114 if (mOutput->audioHwDev->canSetMasterVolume()) {
2115 mMasterVolume = 1.0;
2116 }
2117
2118 if (mOutput->audioHwDev->canSetMasterMute()) {
2119 mMasterMute = false;
2120 }
Andy Hungc8fddf32018-08-08 18:32:37 -07002121 mIsMsdDevice = strcmp(
2122 mOutput->audioHwDev->moduleName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002123 }
2124
Eric Laurentf1f22e72021-07-13 14:04:14 +02002125 if (mixerConfig != nullptr && mixerConfig->channel_mask != AUDIO_CHANNEL_NONE) {
2126 mMixerChannelMask = mixerConfig->channel_mask;
2127 }
2128
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002129 readOutputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002130
Eric Laurent1c5e2e32021-08-18 18:50:28 +02002131 if (mType != SPATIALIZER
Eric Laurentb3f315a2021-07-13 15:09:05 +02002132 && mMixerChannelMask != mChannelMask) {
2133 LOG_ALWAYS_FATAL("HAL channel mask %#x does not match mixer channel mask %#x",
2134 mChannelMask, mMixerChannelMask);
2135 }
2136
Andy Hungc8fddf32018-08-08 18:32:37 -07002137 // TODO: We may also match on address as well as device type for
2138 // AUDIO_DEVICE_OUT_BUS, AUDIO_DEVICE_OUT_ALL_A2DP, AUDIO_DEVICE_OUT_REMOTE_SUBMIX
Dean Wheatleyf8726f02019-12-02 14:12:01 +11002139 if (type == MIXER || type == DIRECT || type == OFFLOAD) {
jiabinc52b1ff2019-10-31 17:20:42 -07002140 // TODO: This property should be ensure that only contains one single device type.
2141 mTimestampCorrectedDevice = (audio_devices_t)property_get_int64(
2142 "audio.timestamp.corrected_output_device",
Andy Hungc8fddf32018-08-08 18:32:37 -07002143 (int64_t)(mIsMsdDevice ? AUDIO_DEVICE_OUT_BUS // turn on by default for MSD
2144 : AUDIO_DEVICE_NONE));
2145 }
2146
Mikhail Naganovf33115d2020-09-25 23:03:05 +00002147 for (int i = AUDIO_STREAM_MIN; i < AUDIO_STREAM_FOR_POLICY_CNT; ++i) {
2148 const audio_stream_type_t stream{static_cast<audio_stream_type_t>(i)};
Eric Laurent98e38192018-02-15 18:31:53 -08002149 mStreamTypes[stream].volume = 0.0f;
Andy Hung2cbc2722023-07-17 17:05:00 -07002150 mStreamTypes[stream].mute = mAfThreadCallback->streamMute_l(stream);
Eric Laurent81784c32012-11-19 14:55:58 -08002151 }
Eric Laurent35f8c7c2020-02-08 11:42:35 -08002152 // Audio patch and call assistant volume are always max
Eric Laurent98e38192018-02-15 18:31:53 -08002153 mStreamTypes[AUDIO_STREAM_PATCH].volume = 1.0f;
2154 mStreamTypes[AUDIO_STREAM_PATCH].mute = false;
Eric Laurent35f8c7c2020-02-08 11:42:35 -08002155 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].volume = 1.0f;
2156 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].mute = false;
Eric Laurent81784c32012-11-19 14:55:58 -08002157}
2158
Andy Hung71742ab2023-07-07 13:47:37 -07002159PlaybackThread::~PlaybackThread()
Eric Laurent81784c32012-11-19 14:55:58 -08002160{
Andy Hung2cbc2722023-07-17 17:05:00 -07002161 mAfThreadCallback->unregisterWriter(mNBLogWriter);
Andy Hung010a1a12014-03-13 13:57:33 -07002162 free(mSinkBuffer);
Andy Hung69aed5f2014-02-25 17:24:40 -08002163 free(mMixerBuffer);
Andy Hung98ef9782014-03-04 14:46:50 -08002164 free(mEffectBuffer);
Eric Laurentb62d0362021-10-26 17:40:18 +02002165 free(mPostSpatializerBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08002166}
2167
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002168// Thread virtuals
2169
Andy Hung71742ab2023-07-07 13:47:37 -07002170void PlaybackThread::onFirstRef()
Eric Laurent81784c32012-11-19 14:55:58 -08002171{
Jasmine Chaeaa10e42021-05-11 10:11:14 +08002172 if (!isStreamInitialized()) {
jiabinf6eb4c32020-02-25 14:06:25 -08002173 ALOGE("The stream is not open yet"); // This should not happen.
2174 } else {
Mikhail Naganovaec565e2023-02-22 16:31:28 -08002175 // Callbacks take strong or weak pointers as a parameter.
2176 // Since PlaybackThread passes itself as a callback handler, it can only
2177 // be done outside of the constructor. Creating weak and especially strong
2178 // pointers to a refcounted object in its own constructor is strongly
2179 // discouraged, see comments in system/core/libutils/include/utils/RefBase.h.
2180 // Even if a function takes a weak pointer, it is possible that it will
2181 // need to convert it to a strong pointer down the line.
2182 if (mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING &&
2183 mOutput->stream->setCallback(this) == OK) {
2184 mUseAsyncWrite = true;
Andy Hung71742ab2023-07-07 13:47:37 -07002185 mCallbackThread = sp<AsyncCallbackThread>::make(this);
Mikhail Naganovaec565e2023-02-22 16:31:28 -08002186 }
2187
jiabinf6eb4c32020-02-25 14:06:25 -08002188 if (mOutput->stream->setEventCallback(this) != OK) {
jiabinf1a36052020-08-19 14:33:31 -07002189 ALOGD("Failed to add event callback");
jiabinf6eb4c32020-02-25 14:06:25 -08002190 }
2191 }
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002192 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
Andy Hung44d648b2022-04-08 17:33:40 -07002193 mThreadSnapshot.setTid(getTid());
Eric Laurent81784c32012-11-19 14:55:58 -08002194}
2195
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002196// ThreadBase virtuals
Andy Hung71742ab2023-07-07 13:47:37 -07002197void PlaybackThread::preExit()
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002198{
2199 ALOGV(" preExit()");
Ytai Ben-Tsvi7e0183f2022-02-04 10:49:54 -08002200 status_t result = mOutput->stream->exit();
2201 ALOGE_IF(result != OK, "Error when calling exit(): %d", result);
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002202}
2203
Andy Hung71742ab2023-07-07 13:47:37 -07002204void PlaybackThread::dumpTracks_l(int fd, const Vector<String16>& /* args */)
Eric Laurent81784c32012-11-19 14:55:58 -08002205{
Eric Laurent81784c32012-11-19 14:55:58 -08002206 String8 result;
2207
Marco Nelissenb2208842014-02-07 14:00:50 -08002208 result.appendFormat(" Stream volumes in dB: ");
Eric Laurent81784c32012-11-19 14:55:58 -08002209 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
2210 const stream_type_t *st = &mStreamTypes[i];
2211 if (i > 0) {
2212 result.appendFormat(", ");
2213 }
2214 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
2215 if (st->mute) {
2216 result.append("M");
2217 }
2218 }
2219 result.append("\n");
Tomasz Wasilczyk8f36f6e2023-08-15 20:59:35 +00002220 write(fd, result.c_str(), result.length());
Eric Laurent81784c32012-11-19 14:55:58 -08002221 result.clear();
2222
Eric Laurent81784c32012-11-19 14:55:58 -08002223 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
2224 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
Elliott Hughes87cebad2014-05-22 10:14:43 -07002225 dprintf(fd, " Normal mixer raw underrun counters: partial=%u empty=%u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08002226 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Marco Nelissenb2208842014-02-07 14:00:50 -08002227
2228 size_t numtracks = mTracks.size();
2229 size_t numactive = mActiveTracks.size();
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002230 dprintf(fd, " %zu Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08002231 size_t numactiveseen = 0;
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002232 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08002233 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002234 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002235 result.append(prefix);
Andy Hungf6ab58d2018-05-25 12:50:39 -07002236 mTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08002237 for (size_t i = 0; i < numtracks; ++i) {
Andy Hung3ff4b552023-06-26 19:20:57 -07002238 sp<IAfTrack> track = mTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08002239 if (track != 0) {
2240 bool active = mActiveTracks.indexOf(track) >= 0;
2241 if (active) {
2242 numactiveseen++;
2243 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002244 result.append(prefix);
2245 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08002246 }
2247 }
2248 } else {
2249 result.append("\n");
2250 }
2251 if (numactiveseen != numactive) {
2252 // some tracks in the active list were not in the tracks list
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002253 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08002254 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002255 result.append(prefix);
Andy Hungf6ab58d2018-05-25 12:50:39 -07002256 mActiveTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08002257 for (size_t i = 0; i < numactive; ++i) {
Andy Hung3ff4b552023-06-26 19:20:57 -07002258 sp<IAfTrack> track = mActiveTracks[i];
Andy Hungdae27702016-10-31 14:01:16 -07002259 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002260 result.append(prefix);
2261 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08002262 }
2263 }
2264 }
2265
Tomasz Wasilczyk8f36f6e2023-08-15 20:59:35 +00002266 write(fd, result.c_str(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08002267}
2268
Andy Hung71742ab2023-07-07 13:47:37 -07002269void PlaybackThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -08002270{
Andy Hung04cb8f72020-03-20 13:44:33 -07002271 dprintf(fd, " Master volume: %f\n", mMasterVolume);
Mikhail Naganovdfb411f2018-09-11 13:39:56 -07002272 dprintf(fd, " Master mute: %s\n", mMasterMute ? "on" : "off");
Eric Laurentf1f22e72021-07-13 14:04:14 +02002273 dprintf(fd, " Mixer channel Mask: %#x (%s)\n",
2274 mMixerChannelMask, channelMaskToString(mMixerChannelMask, true /* output */).c_str());
jiabin245cdd92018-12-07 17:55:15 -08002275 if (mHapticChannelMask != AUDIO_CHANNEL_NONE) {
2276 dprintf(fd, " Haptic channel mask: %#x (%s)\n", mHapticChannelMask,
2277 channelMaskToString(mHapticChannelMask, true /* output */).c_str());
2278 }
Elliott Hughes87cebad2014-05-22 10:14:43 -07002279 dprintf(fd, " Normal frame count: %zu\n", mNormalFrameCount);
Elliott Hughes87cebad2014-05-22 10:14:43 -07002280 dprintf(fd, " Total writes: %d\n", mNumWrites);
2281 dprintf(fd, " Delayed writes: %d\n", mNumDelayedWrites);
2282 dprintf(fd, " Blocked in write: %s\n", mInWrite ? "yes" : "no");
2283 dprintf(fd, " Suspend count: %d\n", mSuspended);
2284 dprintf(fd, " Sink buffer : %p\n", mSinkBuffer);
2285 dprintf(fd, " Mixer buffer: %p\n", mMixerBuffer);
2286 dprintf(fd, " Effect buffer: %p\n", mEffectBuffer);
2287 dprintf(fd, " Fast track availMask=%#x\n", mFastTrackAvailMask);
Eric Laurent42537be2016-01-08 17:16:42 -08002288 dprintf(fd, " Standby delay ns=%lld\n", (long long)mStandbyDelayNs);
Glenn Kasten97b7b752014-09-28 13:04:24 -07002289 AudioStreamOut *output = mOutput;
2290 audio_output_flags_t flags = output != NULL ? output->flags : AUDIO_OUTPUT_FLAG_NONE;
Mikhail Naganov913d06c2016-11-01 12:49:22 -07002291 dprintf(fd, " AudioStreamOut: %p flags %#x (%s)\n",
Andy Hung9b181952019-02-25 14:53:36 -08002292 output, flags, toString(flags).c_str());
Andy Hungb54c8542016-09-21 12:55:15 -07002293 dprintf(fd, " Frames written: %lld\n", (long long)mFramesWritten);
2294 dprintf(fd, " Suspended frames: %lld\n", (long long)mSuspendedFrames);
2295 if (mPipeSink.get() != nullptr) {
2296 dprintf(fd, " PipeSink frames written: %lld\n", (long long)mPipeSink->framesWritten());
2297 }
2298 if (output != nullptr) {
2299 dprintf(fd, " Hal stream dump:\n");
Andy Hung61589a42021-06-16 09:37:53 -07002300 (void)output->stream->dump(fd, args);
Andy Hungb54c8542016-09-21 12:55:15 -07002301 }
Eric Laurent81784c32012-11-19 14:55:58 -08002302}
2303
Eric Laurent81784c32012-11-19 14:55:58 -08002304// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
Andy Hung71742ab2023-07-07 13:47:37 -07002305sp<IAfTrack> PlaybackThread::createTrack_l(
Andy Hungd65869f2023-06-27 17:05:02 -07002306 const sp<Client>& client,
Eric Laurent81784c32012-11-19 14:55:58 -08002307 audio_stream_type_t streamType,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07002308 const audio_attributes_t& attr,
Eric Laurent21da6472017-11-09 16:29:26 -08002309 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08002310 audio_format_t format,
2311 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08002312 size_t *pFrameCount,
Eric Laurent21da6472017-11-09 16:29:26 -08002313 size_t *pNotificationFrameCount,
2314 uint32_t notificationsPerBuffer,
2315 float speed,
Eric Laurent81784c32012-11-19 14:55:58 -08002316 const sp<IMemory>& sharedBuffer,
Glenn Kastend848eb42016-03-08 13:42:11 -08002317 audio_session_t sessionId,
Eric Laurent05067782016-06-01 18:27:28 -07002318 audio_output_flags_t *flags,
Eric Laurent09f1ed22019-04-24 17:45:17 -07002319 pid_t creatorPid,
Svet Ganov33761132021-05-13 22:51:08 +00002320 const AttributionSourceState& attributionSource,
Eric Laurent81784c32012-11-19 14:55:58 -08002321 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002322 status_t *status,
jiabinf6eb4c32020-02-25 14:06:25 -08002323 audio_port_handle_t portId,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02002324 const sp<media::IAudioTrackCallback>& callback,
jiabinc658e452022-10-21 20:52:21 +00002325 bool isSpatialized,
2326 bool isBitPerfect)
Eric Laurent81784c32012-11-19 14:55:58 -08002327{
Glenn Kasten74935e42013-12-19 08:56:45 -08002328 size_t frameCount = *pFrameCount;
Eric Laurent21da6472017-11-09 16:29:26 -08002329 size_t notificationFrameCount = *pNotificationFrameCount;
Andy Hung3ff4b552023-06-26 19:20:57 -07002330 sp<IAfTrack> track;
Eric Laurent81784c32012-11-19 14:55:58 -08002331 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07002332 audio_output_flags_t outputFlags = mOutput->flags;
Eric Laurent21da6472017-11-09 16:29:26 -08002333 audio_output_flags_t requestedFlags = *flags;
Eric Laurent9b11c022018-06-06 19:19:22 -07002334 uint32_t sampleRate;
2335
2336 if (sharedBuffer != 0 && checkIMemory(sharedBuffer) != NO_ERROR) {
2337 lStatus = BAD_VALUE;
2338 goto Exit;
2339 }
Eric Laurent21da6472017-11-09 16:29:26 -08002340
2341 if (*pSampleRate == 0) {
2342 *pSampleRate = mSampleRate;
2343 }
Eric Laurent9b11c022018-06-06 19:19:22 -07002344 sampleRate = *pSampleRate;
Eric Laurent05067782016-06-01 18:27:28 -07002345
2346 // special case for FAST flag considered OK if fast mixer is present
2347 if (hasFastMixer()) {
2348 outputFlags = (audio_output_flags_t)(outputFlags | AUDIO_OUTPUT_FLAG_FAST);
2349 }
2350
2351 // Check if requested flags are compatible with output stream flags
2352 if ((*flags & outputFlags) != *flags) {
2353 ALOGW("createTrack_l(): mismatch between requested flags (%08x) and output flags (%08x)",
2354 *flags, outputFlags);
2355 *flags = (audio_output_flags_t)(*flags & outputFlags);
2356 }
Eric Laurent81784c32012-11-19 14:55:58 -08002357
jiabinc658e452022-10-21 20:52:21 +00002358 if (isBitPerfect) {
Andy Hungbd72c542023-06-20 18:56:17 -07002359 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
jiabinc658e452022-10-21 20:52:21 +00002360 if (chain.get() != nullptr) {
2361 // Bit-perfect is required according to the configuration and preferred mixer
2362 // attributes, but it is not in the output flag from the client's request. Explicitly
2363 // adding bit-perfect flag to check the compatibility
2364 audio_output_flags_t flagsToCheck =
2365 (audio_output_flags_t)(*flags & AUDIO_OUTPUT_FLAG_BIT_PERFECT);
2366 chain->checkOutputFlagCompatibility(&flagsToCheck);
2367 if ((flagsToCheck & AUDIO_OUTPUT_FLAG_BIT_PERFECT) == AUDIO_OUTPUT_FLAG_NONE) {
2368 ALOGE("%s cannot create track as there is data-processing effect attached to "
2369 "given session id(%d)", __func__, sessionId);
2370 lStatus = BAD_VALUE;
2371 goto Exit;
2372 }
2373 *flags = flagsToCheck;
2374 }
2375 }
2376
Eric Laurent81784c32012-11-19 14:55:58 -08002377 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07002378 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
Eric Laurent81784c32012-11-19 14:55:58 -08002379 if (
Eric Laurent81784c32012-11-19 14:55:58 -08002380 // PCM data
2381 audio_is_linear_pcm(format) &&
Andy Hung1f439e12015-05-19 12:57:41 -07002382 // TODO: extract as a data library function that checks that a computationally
2383 // expensive downmixer is not required: isFastOutputChannelConversion()
jiabin245cdd92018-12-07 17:55:15 -08002384 (channelMask == (mChannelMask | mHapticChannelMask) ||
Andy Hung1f439e12015-05-19 12:57:41 -07002385 mChannelMask != AUDIO_CHANNEL_OUT_STEREO ||
2386 (channelMask == AUDIO_CHANNEL_OUT_MONO
2387 /* && mChannelMask == AUDIO_CHANNEL_OUT_STEREO */)) &&
Eric Laurent81784c32012-11-19 14:55:58 -08002388 // hardware sample rate
2389 (sampleRate == mSampleRate) &&
Eric Laurent81784c32012-11-19 14:55:58 -08002390 // normal mixer has an associated fast mixer
2391 hasFastMixer() &&
2392 // there are sufficient fast track slots available
2393 (mFastTrackAvailMask != 0)
2394 // FIXME test that MixerThread for this fast track has a capable output HAL
2395 // FIXME add a permission test also?
2396 ) {
Andy Hunge0a269a2016-03-23 15:13:42 -07002397 // static tracks can have any nonzero framecount, streaming tracks check against minimum.
2398 if (sharedBuffer == 0) {
Glenn Kasten03490092014-05-27 12:30:54 -07002399 // read the fast track multiplier property the first time it is needed
2400 int ok = pthread_once(&sFastTrackMultiplierOnce, sFastTrackMultiplierInit);
2401 if (ok != 0) {
2402 ALOGE("%s pthread_once failed: %d", __func__, ok);
2403 }
Andy Hunge0a269a2016-03-23 15:13:42 -07002404 frameCount = max(frameCount, mFrameCount * sFastTrackMultiplier); // incl framecount 0
Eric Laurent81784c32012-11-19 14:55:58 -08002405 }
Eric Laurent4c415062016-06-17 16:14:16 -07002406
2407 // check compatibility with audio effects.
2408 { // scope for mLock
2409 Mutex::Autolock _l(mLock);
Andy Hungd3bb0ad2016-10-11 17:16:43 -07002410 for (audio_session_t session : {
Eric Laurent3f75a5b2019-11-12 15:55:51 -08002411 AUDIO_SESSION_DEVICE,
Andy Hungd3bb0ad2016-10-11 17:16:43 -07002412 AUDIO_SESSION_OUTPUT_STAGE,
2413 AUDIO_SESSION_OUTPUT_MIX,
2414 sessionId,
2415 }) {
Andy Hungbd72c542023-06-20 18:56:17 -07002416 sp<IAfEffectChain> chain = getEffectChain_l(session);
Andy Hungd3bb0ad2016-10-11 17:16:43 -07002417 if (chain.get() != nullptr) {
2418 audio_output_flags_t old = *flags;
2419 chain->checkOutputFlagCompatibility(flags);
2420 if (old != *flags) {
2421 ALOGV("AUDIO_OUTPUT_FLAGS denied by effect, session=%d old=%#x new=%#x",
2422 (int)session, (int)old, (int)*flags);
2423 }
Eric Laurent4c415062016-06-17 16:14:16 -07002424 }
2425 }
2426 }
Eric Laurent122f7e72016-06-29 11:53:29 -07002427 ALOGV_IF((*flags & AUDIO_OUTPUT_FLAG_FAST) != 0,
Eric Laurent4c415062016-06-17 16:14:16 -07002428 "AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
2429 frameCount, mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08002430 } else {
Robert Wu4c7bb7d2021-08-12 18:50:13 +00002431 ALOGD("AUDIO_OUTPUT_FLAG_FAST denied: sharedBuffer=%p frameCount=%zu "
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002432 "mFrameCount=%zu format=%#x mFormat=%#x isLinear=%d channelMask=%#x "
Andy Hung6146c082014-03-18 11:56:15 -07002433 "sampleRate=%u mSampleRate=%u "
Eric Laurent81784c32012-11-19 14:55:58 -08002434 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
Glenn Kastend79072e2016-01-06 08:41:20 -08002435 sharedBuffer.get(), frameCount, mFrameCount, format, mFormat,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07002436 audio_is_linear_pcm(format), channelMask, sampleRate,
2437 mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
Eric Laurent4c415062016-06-17 16:14:16 -07002438 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_FAST);
Andy Hung0e48d252015-01-26 11:43:15 -08002439 }
2440 }
Eric Laurent21da6472017-11-09 16:29:26 -08002441
2442 if (!audio_has_proportional_frames(format)) {
2443 if (sharedBuffer != 0) {
2444 // Same comment as below about ignoring frameCount parameter for set()
2445 frameCount = sharedBuffer->size();
2446 } else if (frameCount == 0) {
2447 frameCount = mNormalFrameCount;
2448 }
2449 if (notificationFrameCount != frameCount) {
2450 notificationFrameCount = frameCount;
2451 }
2452 } else if (sharedBuffer != 0) {
2453 // FIXME: Ensure client side memory buffers need
2454 // not have additional alignment beyond sample
2455 // (e.g. 16 bit stereo accessed as 32 bit frame).
2456 size_t alignment = audio_bytes_per_sample(format);
2457 if (alignment & 1) {
2458 // for AUDIO_FORMAT_PCM_24_BIT_PACKED (not exposed through Java).
2459 alignment = 1;
2460 }
2461 uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
2462 size_t frameSize = channelCount * audio_bytes_per_sample(format);
2463 if (channelCount > 1) {
2464 // More than 2 channels does not require stronger alignment than stereo
2465 alignment <<= 1;
2466 }
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07002467 if (((uintptr_t)sharedBuffer->unsecurePointer() & (alignment - 1)) != 0) {
Eric Laurent21da6472017-11-09 16:29:26 -08002468 ALOGE("Invalid buffer alignment: address %p, channel count %u",
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07002469 sharedBuffer->unsecurePointer(), channelCount);
Eric Laurent21da6472017-11-09 16:29:26 -08002470 lStatus = BAD_VALUE;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002471 goto Exit;
2472 }
Eric Laurent21da6472017-11-09 16:29:26 -08002473
2474 // When initializing a shared buffer AudioTrack via constructors,
2475 // there's no frameCount parameter.
2476 // But when initializing a shared buffer AudioTrack via set(),
2477 // there _is_ a frameCount parameter. We silently ignore it.
2478 frameCount = sharedBuffer->size() / frameSize;
2479 } else {
2480 size_t minFrameCount = 0;
2481 // For fast tracks we try to respect the application's request for notifications per buffer.
2482 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
2483 if (notificationsPerBuffer > 0) {
2484 // Avoid possible arithmetic overflow during multiplication.
2485 if (notificationsPerBuffer > SIZE_MAX / mFrameCount) {
2486 ALOGE("Requested notificationPerBuffer=%u ignored for HAL frameCount=%zu",
2487 notificationsPerBuffer, mFrameCount);
2488 } else {
2489 minFrameCount = mFrameCount * notificationsPerBuffer;
2490 }
2491 }
2492 } else {
2493 // For normal PCM streaming tracks, update minimum frame count.
2494 // Buffer depth is forced to be at least 2 x the normal mixer frame count and
2495 // cover audio hardware latency.
2496 // This is probably too conservative, but legacy application code may depend on it.
2497 // If you change this calculation, also review the start threshold which is related.
2498 uint32_t latencyMs = latency_l();
2499 if (latencyMs == 0) {
2500 ALOGE("Error when retrieving output stream latency");
2501 lStatus = UNKNOWN_ERROR;
2502 goto Exit;
2503 }
2504
2505 minFrameCount = AudioSystem::calculateMinFrameCount(latencyMs, mNormalFrameCount,
2506 mSampleRate, sampleRate, speed /*, 0 mNotificationsPerBufferReq*/);
2507
Eric Laurent81784c32012-11-19 14:55:58 -08002508 }
Eric Laurent21da6472017-11-09 16:29:26 -08002509 if (frameCount < minFrameCount) {
Eric Laurent81784c32012-11-19 14:55:58 -08002510 frameCount = minFrameCount;
2511 }
Eric Laurent81784c32012-11-19 14:55:58 -08002512 }
Eric Laurent21da6472017-11-09 16:29:26 -08002513
2514 // Make sure that application is notified with sufficient margin before underrun.
2515 // The client can divide the AudioTrack buffer into sub-buffers,
2516 // and expresses its desire to server as the notification frame count.
2517 if (sharedBuffer == 0 && audio_is_linear_pcm(format)) {
2518 size_t maxNotificationFrames;
2519 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
2520 // notify every HAL buffer, regardless of the size of the track buffer
2521 maxNotificationFrames = mFrameCount;
2522 } else {
Andy Hungfa117802019-04-12 13:50:39 -07002523 // Triple buffer the notification period for a triple buffered mixer period;
2524 // otherwise, double buffering for the notification period is fine.
2525 //
2526 // TODO: This should be moved to AudioTrack to modify the notification period
2527 // on AudioTrack::setBufferSizeInFrames() changes.
2528 const int nBuffering =
2529 (uint64_t{frameCount} * mSampleRate)
2530 / (uint64_t{mNormalFrameCount} * sampleRate) == 3 ? 3 : 2;
2531
Eric Laurent21da6472017-11-09 16:29:26 -08002532 maxNotificationFrames = frameCount / nBuffering;
2533 // If client requested a fast track but this was denied, then use the smaller maximum.
2534 if (requestedFlags & AUDIO_OUTPUT_FLAG_FAST) {
2535 size_t maxNotificationFramesFastDenied = FMS_20 * sampleRate / 1000;
2536 if (maxNotificationFrames > maxNotificationFramesFastDenied) {
2537 maxNotificationFrames = maxNotificationFramesFastDenied;
2538 }
2539 }
2540 }
2541 if (notificationFrameCount == 0 || notificationFrameCount > maxNotificationFrames) {
2542 if (notificationFrameCount == 0) {
2543 ALOGD("Client defaulted notificationFrames to %zu for frameCount %zu",
2544 maxNotificationFrames, frameCount);
2545 } else {
2546 ALOGW("Client adjusted notificationFrames from %zu to %zu for frameCount %zu",
2547 notificationFrameCount, maxNotificationFrames, frameCount);
2548 }
2549 notificationFrameCount = maxNotificationFrames;
2550 }
2551 }
2552
Glenn Kasten74935e42013-12-19 08:56:45 -08002553 *pFrameCount = frameCount;
Eric Laurent21da6472017-11-09 16:29:26 -08002554 *pNotificationFrameCount = notificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08002555
Glenn Kastenc3df8382014-03-13 15:05:25 -07002556 switch (mType) {
jiabinc658e452022-10-21 20:52:21 +00002557 case BIT_PERFECT:
2558 if (isBitPerfect) {
2559 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
2560 ALOGE("%s, bad parameter when request streaming bit-perfect, sampleRate=%u, "
2561 "format=%#x, channelMask=%#x, mSampleRate=%u, mFormat=%#x, mChannelMask=%#x",
2562 __func__, sampleRate, format, channelMask, mSampleRate, mFormat,
2563 mChannelMask);
2564 lStatus = BAD_VALUE;
2565 goto Exit;
2566 }
2567 }
2568 break;
Glenn Kastenc3df8382014-03-13 15:05:25 -07002569
2570 case DIRECT:
Phil Burkfdb3c072016-02-09 10:47:02 -08002571 if (audio_is_linear_pcm(format)) { // TODO maybe use audio_has_proportional_frames()?
Eric Laurent81784c32012-11-19 14:55:58 -08002572 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002573 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
2574 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08002575 sampleRate, format, channelMask, mOutput, mFormat);
2576 lStatus = BAD_VALUE;
2577 goto Exit;
2578 }
2579 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002580 break;
2581
2582 case OFFLOAD:
Eric Laurentbfb1b832013-01-07 09:53:42 -08002583 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002584 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
2585 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002586 sampleRate, format, channelMask, mOutput, mFormat);
2587 lStatus = BAD_VALUE;
2588 goto Exit;
2589 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002590 break;
2591
2592 default:
Glenn Kasten993fa062014-05-02 11:14:34 -07002593 if (!audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002594 ALOGE("createTrack_l() Bad parameter: format %#x \""
2595 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002596 format, mOutput, mFormat);
2597 lStatus = BAD_VALUE;
2598 goto Exit;
2599 }
Andy Hungcd044842014-08-07 11:04:34 -07002600 if (sampleRate > mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Eric Laurent81784c32012-11-19 14:55:58 -08002601 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
2602 lStatus = BAD_VALUE;
2603 goto Exit;
2604 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002605 break;
2606
Eric Laurent81784c32012-11-19 14:55:58 -08002607 }
2608
2609 lStatus = initCheck();
2610 if (lStatus != NO_ERROR) {
Glenn Kasten15e57982013-09-24 11:52:37 -07002611 ALOGE("createTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08002612 goto Exit;
2613 }
2614
2615 { // scope for mLock
2616 Mutex::Autolock _l(mLock);
2617
2618 // all tracks in same audio session must share the same routing strategy otherwise
2619 // conflicts will happen when tracks are moved from one output to another by audio policy
2620 // manager
Eric Laurentd66d7a12021-07-13 13:35:32 +02002621 product_strategy_t strategy = getStrategyForStream(streamType);
Eric Laurent81784c32012-11-19 14:55:58 -08002622 for (size_t i = 0; i < mTracks.size(); ++i) {
Andy Hung3ff4b552023-06-26 19:20:57 -07002623 sp<IAfTrack> t = mTracks[i];
Eric Laurent83b88082014-06-20 18:31:16 -07002624 if (t != 0 && t->isExternalTrack()) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02002625 product_strategy_t actual = getStrategyForStream(t->streamType());
Eric Laurent81784c32012-11-19 14:55:58 -08002626 if (sessionId == t->sessionId() && strategy != actual) {
2627 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
2628 strategy, actual);
2629 lStatus = BAD_VALUE;
2630 goto Exit;
2631 }
2632 }
2633 }
2634
yucliuc9c49cd2020-07-13 16:25:21 -07002635 // Set DIRECT flag if current thread is DirectOutputThread. This can
2636 // happen when the playback is rerouted to direct output thread by
2637 // dynamic audio policy.
2638 // Do NOT report the flag changes back to client, since the client
2639 // doesn't explicitly request a direct flag.
2640 audio_output_flags_t trackFlags = *flags;
2641 if (mType == DIRECT) {
2642 trackFlags = static_cast<audio_output_flags_t>(trackFlags | AUDIO_OUTPUT_FLAG_DIRECT);
2643 }
2644
Andy Hung3ff4b552023-06-26 19:20:57 -07002645 track = IAfTrack::create(this, client, streamType, attr, sampleRate, format,
Andy Hung8fe68032017-06-05 16:17:51 -07002646 channelMask, frameCount,
2647 nullptr /* buffer */, (size_t)0 /* bufferSize */, sharedBuffer,
Svet Ganov33761132021-05-13 22:51:08 +00002648 sessionId, creatorPid, attributionSource, trackFlags,
Andy Hung3ff4b552023-06-26 19:20:57 -07002649 IAfTrackBase::TYPE_DEFAULT, portId, SIZE_MAX /*frameCountToBeReady*/,
jiabinc658e452022-10-21 20:52:21 +00002650 speed, isSpatialized, isBitPerfect);
Glenn Kasten03003332013-08-06 15:40:54 -07002651
Glenn Kasten03003332013-08-06 15:40:54 -07002652 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
2653 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08002654 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08002655 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08002656 goto Exit;
2657 }
2658 mTracks.add(track);
jiabinf6eb4c32020-02-25 14:06:25 -08002659 {
2660 Mutex::Autolock _atCbL(mAudioTrackCbLock);
2661 if (callback.get() != nullptr) {
jiabin18a4b1c2020-09-17 11:40:42 -07002662 mAudioTrackCallbacks.emplace(track, callback);
jiabinf6eb4c32020-02-25 14:06:25 -08002663 }
2664 }
Eric Laurent81784c32012-11-19 14:55:58 -08002665
Andy Hungbd72c542023-06-20 18:56:17 -07002666 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08002667 if (chain != 0) {
2668 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
2669 track->setMainBuffer(chain->inBuffer());
Eric Laurentd66d7a12021-07-13 13:35:32 +02002670 chain->setStrategy(getStrategyForStream(track->streamType()));
Eric Laurent81784c32012-11-19 14:55:58 -08002671 chain->incTrackCnt();
2672 }
2673
Eric Laurent05067782016-06-01 18:27:28 -07002674 if ((*flags & AUDIO_OUTPUT_FLAG_FAST) && (tid != -1)) {
Eric Laurent81784c32012-11-19 14:55:58 -08002675 pid_t callingPid = IPCThreadState::self()->getCallingPid();
2676 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
2677 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07002678 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08002679 }
2680 }
2681
2682 lStatus = NO_ERROR;
2683
2684Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07002685 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08002686 return track;
2687}
2688
Andy Hung1bc088a2018-02-09 15:57:31 -08002689template<typename T>
Andy Hung71742ab2023-07-07 13:47:37 -07002690ssize_t PlaybackThread::Tracks<T>::remove(const sp<T>& track)
Andy Hung1bc088a2018-02-09 15:57:31 -08002691{
Andy Hungc0691382018-09-12 18:01:57 -07002692 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08002693 const ssize_t index = mTracks.remove(track);
2694 if (index >= 0) {
Andy Hungc0691382018-09-12 18:01:57 -07002695 if (mSaveDeletedTrackIds) {
Andy Hung1bc088a2018-02-09 15:57:31 -08002696 // We can't directly access mAudioMixer since the caller may be outside of threadLoop.
Andy Hungc0691382018-09-12 18:01:57 -07002697 // Instead, we add to mDeletedTrackIds which is solely used for mAudioMixer update,
Andy Hung1bc088a2018-02-09 15:57:31 -08002698 // to be handled when MixerThread::prepareTracks_l() next changes mAudioMixer.
Andy Hungc0691382018-09-12 18:01:57 -07002699 mDeletedTrackIds.emplace(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08002700 }
Andy Hung1bc088a2018-02-09 15:57:31 -08002701 }
2702 return index;
2703}
2704
Andy Hung71742ab2023-07-07 13:47:37 -07002705uint32_t PlaybackThread::correctLatency_l(uint32_t latency) const
Eric Laurent81784c32012-11-19 14:55:58 -08002706{
2707 return latency;
2708}
2709
Andy Hung71742ab2023-07-07 13:47:37 -07002710uint32_t PlaybackThread::latency() const
Eric Laurent81784c32012-11-19 14:55:58 -08002711{
2712 Mutex::Autolock _l(mLock);
2713 return latency_l();
2714}
Andy Hung71742ab2023-07-07 13:47:37 -07002715uint32_t PlaybackThread::latency_l() const
Eric Laurent81784c32012-11-19 14:55:58 -08002716{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002717 uint32_t latency;
2718 if (initCheck() == NO_ERROR && mOutput->stream->getLatency(&latency) == OK) {
2719 return correctLatency_l(latency);
Eric Laurent81784c32012-11-19 14:55:58 -08002720 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002721 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002722}
2723
Andy Hung71742ab2023-07-07 13:47:37 -07002724void PlaybackThread::setMasterVolume(float value)
Eric Laurent81784c32012-11-19 14:55:58 -08002725{
2726 Mutex::Autolock _l(mLock);
2727 // Don't apply master volume in SW if our HAL can do it for us.
2728 if (mOutput && mOutput->audioHwDev &&
2729 mOutput->audioHwDev->canSetMasterVolume()) {
2730 mMasterVolume = 1.0;
2731 } else {
2732 mMasterVolume = value;
2733 }
2734}
2735
Andy Hung71742ab2023-07-07 13:47:37 -07002736void PlaybackThread::setMasterBalance(float balance)
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01002737{
2738 mMasterBalance.store(balance);
2739}
2740
Andy Hung71742ab2023-07-07 13:47:37 -07002741void PlaybackThread::setMasterMute(bool muted)
Eric Laurent81784c32012-11-19 14:55:58 -08002742{
Eric Laurent6acd1d42017-01-04 14:23:29 -08002743 if (isDuplicating()) {
2744 return;
2745 }
Eric Laurent81784c32012-11-19 14:55:58 -08002746 Mutex::Autolock _l(mLock);
2747 // Don't apply master mute in SW if our HAL can do it for us.
2748 if (mOutput && mOutput->audioHwDev &&
2749 mOutput->audioHwDev->canSetMasterMute()) {
2750 mMasterMute = false;
2751 } else {
2752 mMasterMute = muted;
2753 }
2754}
2755
Andy Hung71742ab2023-07-07 13:47:37 -07002756void PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
Eric Laurent81784c32012-11-19 14:55:58 -08002757{
2758 Mutex::Autolock _l(mLock);
2759 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002760 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002761}
2762
Andy Hung71742ab2023-07-07 13:47:37 -07002763void PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
Eric Laurent81784c32012-11-19 14:55:58 -08002764{
2765 Mutex::Autolock _l(mLock);
2766 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002767 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002768}
2769
Andy Hung71742ab2023-07-07 13:47:37 -07002770float PlaybackThread::streamVolume(audio_stream_type_t stream) const
Eric Laurent81784c32012-11-19 14:55:58 -08002771{
2772 Mutex::Autolock _l(mLock);
2773 return mStreamTypes[stream].volume;
2774}
2775
Andy Hung71742ab2023-07-07 13:47:37 -07002776void PlaybackThread::setVolumeForOutput_l(float left, float right) const
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09002777{
2778 mOutput->stream->setVolume(left, right);
2779}
2780
Eric Laurent81784c32012-11-19 14:55:58 -08002781// addTrack_l() must be called with ThreadBase::mLock held
Andy Hung71742ab2023-07-07 13:47:37 -07002782status_t PlaybackThread::addTrack_l(const sp<IAfTrack>& track)
Andy Hung71ba4b32022-10-06 12:09:49 -07002783NO_THREAD_SAFETY_ANALYSIS // release and re-acquire mLock
Eric Laurent81784c32012-11-19 14:55:58 -08002784{
2785 status_t status = ALREADY_EXISTS;
2786
Eric Laurent81784c32012-11-19 14:55:58 -08002787 if (mActiveTracks.indexOf(track) < 0) {
2788 // the track is newly added, make sure it fills up all its
2789 // buffers before playing. This is to ensure the client will
2790 // effectively get the latency it requested.
Eric Laurent83b88082014-06-20 18:31:16 -07002791 if (track->isExternalTrack()) {
Andy Hung3ff4b552023-06-26 19:20:57 -07002792 IAfTrackBase::track_state state = track->state();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002793 mLock.unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002794 status = AudioSystem::startOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002795 mLock.lock();
2796 // abort track was stopped/paused while we released the lock
Andy Hung3ff4b552023-06-26 19:20:57 -07002797 if (state != track->state()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002798 if (status == NO_ERROR) {
2799 mLock.unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002800 AudioSystem::stopOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002801 mLock.lock();
2802 }
2803 return INVALID_OPERATION;
2804 }
2805 // abort if start is rejected by audio policy manager
2806 if (status != NO_ERROR) {
jiabina84c3d32022-12-02 18:59:55 +00002807 // Do not replace the error if it is DEAD_OBJECT. When this happens, it indicates
2808 // current playback thread is reopened, which may happen when clients set preferred
2809 // mixer configuration. Returning DEAD_OBJECT will make the client restore track
2810 // immediately.
2811 return status == DEAD_OBJECT ? status : PERMISSION_DENIED;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002812 }
2813#ifdef ADD_BATTERY_DATA
2814 // to track the speaker usage
2815 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
2816#endif
Eric Laurent09f1ed22019-04-24 17:45:17 -07002817 sendIoConfigEvent_l(AUDIO_CLIENT_STARTED, track->creatorPid(), track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002818 }
2819
Eric Laurent51716182016-02-29 18:00:56 -08002820 // set retry count for buffer fill
2821 if (track->isOffloaded()) {
Eric Laurente93cc032016-05-05 10:15:10 -07002822 if (track->isStopping_1()) {
Andy Hung3ff4b552023-06-26 19:20:57 -07002823 track->retryCount() = kMaxTrackStopRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07002824 } else {
Andy Hung3ff4b552023-06-26 19:20:57 -07002825 track->retryCount() = kMaxTrackStartupRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07002826 }
Andy Hung3ff4b552023-06-26 19:20:57 -07002827 track->fillingStatus() = mStandby ? IAfTrack::FS_FILLING : IAfTrack::FS_FILLED;
Eric Laurent51716182016-02-29 18:00:56 -08002828 } else {
Andy Hung3ff4b552023-06-26 19:20:57 -07002829 track->retryCount() = kMaxTrackStartupRetries;
2830 track->fillingStatus() =
2831 track->sharedBuffer() != 0 ? IAfTrack::FS_FILLED : IAfTrack::FS_FILLING;
Eric Laurent51716182016-02-29 18:00:56 -08002832 }
2833
Andy Hungbd72c542023-06-20 18:56:17 -07002834 sp<IAfEffectChain> chain = getEffectChain_l(track->sessionId());
jiabineb3bda02020-06-30 14:07:03 -07002835 if (mHapticChannelMask != AUDIO_CHANNEL_NONE
2836 && ((track->channelMask() & AUDIO_CHANNEL_HAPTIC_ALL) != AUDIO_CHANNEL_NONE
2837 || (chain != nullptr && chain->containsHapticGeneratingEffect_l()))) {
jiabin57303cc2018-12-18 15:45:57 -08002838 // Unlock due to VibratorService will lock for this call and will
2839 // call Tracks.mute/unmute which also require thread's lock.
2840 mLock.unlock();
Simon Bowden62823412022-10-17 14:52:26 +00002841 const os::HapticScale intensity = AudioFlinger::onExternalVibrationStart(
jiabin57303cc2018-12-18 15:45:57 -08002842 track->getExternalVibration());
Lais Andradebc3f37a2021-07-02 00:13:19 +01002843 std::optional<media::AudioVibratorInfo> vibratorInfo;
2844 {
2845 // TODO(b/184194780): Use the vibrator information from the vibrator that will be
2846 // used to play this track.
Andy Hung2cbc2722023-07-17 17:05:00 -07002847 Mutex::Autolock _l(mAfThreadCallback->mutex());
2848 vibratorInfo = std::move(mAfThreadCallback->getDefaultVibratorInfo_l());
Lais Andradebc3f37a2021-07-02 00:13:19 +01002849 }
jiabin57303cc2018-12-18 15:45:57 -08002850 mLock.lock();
Simon Bowden62823412022-10-17 14:52:26 +00002851 track->setHapticIntensity(intensity);
Lais Andradebc3f37a2021-07-02 00:13:19 +01002852 if (vibratorInfo) {
2853 track->setHapticMaxAmplitude(vibratorInfo->maxAmplitude);
2854 }
2855
jiabin57303cc2018-12-18 15:45:57 -08002856 // Haptic playback should be enabled by vibrator service.
2857 if (track->getHapticPlaybackEnabled()) {
2858 // Disable haptic playback of all active track to ensure only
2859 // one track playing haptic if current track should play haptic.
2860 for (const auto &t : mActiveTracks) {
2861 t->setHapticPlaybackEnabled(false);
2862 }
jiabin245cdd92018-12-07 17:55:15 -08002863 }
jiabine70bc7f2020-06-30 22:07:55 -07002864
2865 // Set haptic intensity for effect
2866 if (chain != nullptr) {
2867 chain->setHapticIntensity_l(track->id(), intensity);
2868 }
jiabin245cdd92018-12-07 17:55:15 -08002869 }
2870
Andy Hung3ff4b552023-06-26 19:20:57 -07002871 track->setResetDone(false);
Andy Hung59de4262021-06-14 10:53:54 -07002872 track->resetPresentationComplete();
Eric Laurent81784c32012-11-19 14:55:58 -08002873 mActiveTracks.add(track);
Eric Laurentd0107bc2013-06-11 14:38:48 -07002874 if (chain != 0) {
2875 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
2876 track->sessionId());
2877 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08002878 }
2879
Andy Hungc2b11cb2020-04-22 09:04:01 -07002880 track->logBeginInterval(patchSinksToString(&mPatch)); // log to MediaMetrics
Eric Laurent81784c32012-11-19 14:55:58 -08002881 status = NO_ERROR;
2882 }
2883
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08002884 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002885 return status;
2886}
2887
Andy Hung71742ab2023-07-07 13:47:37 -07002888bool PlaybackThread::destroyTrack_l(const sp<IAfTrack>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002889{
Eric Laurentbfb1b832013-01-07 09:53:42 -08002890 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08002891 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002892 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
Andy Hung3ff4b552023-06-26 19:20:57 -07002893 track->setState(IAfTrackBase::STOPPED);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002894 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08002895 removeTrack_l(track);
Eric Laurentab5cdba2014-06-09 17:22:27 -07002896 } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) {
Andy Hung916987e2023-03-20 19:08:16 -07002897 if (track->isPausePending()) {
2898 track->pauseAck();
2899 }
Andy Hung3ff4b552023-06-26 19:20:57 -07002900 track->setState(IAfTrackBase::STOPPING_1);
Eric Laurent81784c32012-11-19 14:55:58 -08002901 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002902
2903 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08002904}
2905
Andy Hung71742ab2023-07-07 13:47:37 -07002906void PlaybackThread::removeTrack_l(const sp<IAfTrack>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002907{
2908 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Andy Hung2148bf02016-11-28 19:01:02 -08002909
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002910 String8 result;
2911 track->appendDump(result, false /* active */);
Tomasz Wasilczyk8f36f6e2023-08-15 20:59:35 +00002912 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.c_str());
Andy Hung2148bf02016-11-28 19:01:02 -08002913
Eric Laurent81784c32012-11-19 14:55:58 -08002914 mTracks.remove(track);
jiabin18a4b1c2020-09-17 11:40:42 -07002915 {
2916 Mutex::Autolock _atCbL(mAudioTrackCbLock);
2917 mAudioTrackCallbacks.erase(track);
2918 }
Eric Laurent81784c32012-11-19 14:55:58 -08002919 if (track->isFastTrack()) {
Andy Hung3ff4b552023-06-26 19:20:57 -07002920 int index = track->fastIndex();
Glenn Kastendc2c50b2016-04-21 08:13:14 -07002921 ALOG_ASSERT(0 < index && index < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08002922 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
2923 mFastTrackAvailMask |= 1 << index;
2924 // redundant as track is about to be destroyed, for dumpsys only
Andy Hung3ff4b552023-06-26 19:20:57 -07002925 track->fastIndex() = -1;
Eric Laurent81784c32012-11-19 14:55:58 -08002926 }
Andy Hungbd72c542023-06-20 18:56:17 -07002927 sp<IAfEffectChain> chain = getEffectChain_l(track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08002928 if (chain != 0) {
2929 chain->decTrackCnt();
2930 }
2931}
2932
Andy Hung71742ab2023-07-07 13:47:37 -07002933String8 PlaybackThread::getParameters(const String8& keys)
Eric Laurent81784c32012-11-19 14:55:58 -08002934{
Eric Laurent81784c32012-11-19 14:55:58 -08002935 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002936 String8 out_s8;
2937 if (initCheck() == NO_ERROR && mOutput->stream->getParameters(keys, &out_s8) == OK) {
2938 return out_s8;
Eric Laurent81784c32012-11-19 14:55:58 -08002939 }
Andy Hung71ba4b32022-10-06 12:09:49 -07002940 return {};
Eric Laurent81784c32012-11-19 14:55:58 -08002941}
2942
Andy Hung71742ab2023-07-07 13:47:37 -07002943status_t DirectOutputThread::selectPresentation(int presentationId, int programId) {
Mikhail Naganovac917ac2018-11-28 14:03:52 -08002944 Mutex::Autolock _l(mLock);
Jasmine Chaeaa10e42021-05-11 10:11:14 +08002945 if (!isStreamInitialized()) {
Mikhail Naganovac917ac2018-11-28 14:03:52 -08002946 return NO_INIT;
2947 }
2948 return mOutput->stream->selectPresentation(presentationId, programId);
2949}
2950
Andy Hung71742ab2023-07-07 13:47:37 -07002951void PlaybackThread::ioConfigChanged(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -07002952 audio_port_handle_t portId) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002953 ALOGV("PlaybackThread::ioConfigChanged, thread %p, event %d", this, event);
Mikhail Naganov88536df2021-07-26 17:30:29 -07002954 sp<AudioIoDescriptor> desc;
2955 const struct audio_patch patch = isMsdDevice() ? mDownStreamPatch : mPatch;
Eric Laurent81784c32012-11-19 14:55:58 -08002956 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002957 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07002958 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07002959 case AUDIO_OUTPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07002960 desc = sp<AudioIoDescriptor>::make(mId, patch, false /*isInput*/,
2961 mSampleRate, mFormat, mChannelMask,
2962 // FIXME AudioFlinger::frameCount(audio_io_handle_t) instead of mNormalFrameCount?
2963 mNormalFrameCount, mFrameCount, latency_l());
Eric Laurent81784c32012-11-19 14:55:58 -08002964 break;
Eric Laurent09f1ed22019-04-24 17:45:17 -07002965 case AUDIO_CLIENT_STARTED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07002966 desc = sp<AudioIoDescriptor>::make(mId, patch, portId);
Eric Laurent09f1ed22019-04-24 17:45:17 -07002967 break;
Eric Laurent73e26b62015-04-27 16:55:58 -07002968 case AUDIO_OUTPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08002969 default:
Mikhail Naganov88536df2021-07-26 17:30:29 -07002970 desc = sp<AudioIoDescriptor>::make(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08002971 break;
2972 }
Andy Hung2cbc2722023-07-17 17:05:00 -07002973 mAfThreadCallback->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08002974}
2975
Andy Hung71742ab2023-07-07 13:47:37 -07002976void PlaybackThread::onWriteReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002977{
Eric Laurent3b4529e2013-09-05 18:09:19 -07002978 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002979}
2980
Andy Hung71742ab2023-07-07 13:47:37 -07002981void PlaybackThread::onDrainReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002982{
Eric Laurent3b4529e2013-09-05 18:09:19 -07002983 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002984}
2985
Andy Hung71742ab2023-07-07 13:47:37 -07002986void PlaybackThread::onError()
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002987{
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002988 mCallbackThread->setAsyncError();
2989}
2990
Andy Hung71742ab2023-07-07 13:47:37 -07002991void PlaybackThread::onCodecFormatChanged(
jiabinf6eb4c32020-02-25 14:06:25 -08002992 const std::basic_string<uint8_t>& metadataBs)
2993{
Andy Hung71742ab2023-07-07 13:47:37 -07002994 const auto weakPointerThis = wp<PlaybackThread>::fromExisting(this);
Kuowei Li9e2f6162022-11-23 16:25:26 +08002995 std::thread([this, metadataBs, weakPointerThis]() {
Andy Hung71742ab2023-07-07 13:47:37 -07002996 const sp<PlaybackThread> playbackThread = weakPointerThis.promote();
Kuowei Li9e2f6162022-11-23 16:25:26 +08002997 if (playbackThread == nullptr) {
2998 ALOGW("PlaybackThread was destroyed, skip codec format change event");
2999 return;
3000 }
3001
jiabinf6eb4c32020-02-25 14:06:25 -08003002 audio_utils::metadata::Data metadata =
3003 audio_utils::metadata::dataFromByteString(metadataBs);
3004 if (metadata.empty()) {
3005 ALOGW("Can not transform the buffer to audio metadata, %s, %d",
3006 reinterpret_cast<char*>(const_cast<uint8_t*>(metadataBs.data())),
3007 (int)metadataBs.size());
3008 return;
3009 }
3010
3011 audio_utils::metadata::ByteString metaDataStr =
3012 audio_utils::metadata::byteStringFromData(metadata);
3013 std::vector metadataVec(metaDataStr.begin(), metaDataStr.end());
3014 Mutex::Autolock _l(mAudioTrackCbLock);
jiabin18a4b1c2020-09-17 11:40:42 -07003015 for (const auto& callbackPair : mAudioTrackCallbacks) {
3016 callbackPair.second->onCodecFormatChanged(metadataVec);
jiabinf6eb4c32020-02-25 14:06:25 -08003017 }
3018 }).detach();
3019}
3020
Andy Hung71742ab2023-07-07 13:47:37 -07003021void PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08003022{
3023 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003024 // reject out of sequence requests
3025 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
3026 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003027 mWaitWorkCV.signal();
3028 }
3029}
3030
Andy Hung71742ab2023-07-07 13:47:37 -07003031void PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08003032{
3033 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003034 // reject out of sequence requests
3035 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
Andy Hungf3234512018-07-03 14:51:47 -07003036 // Register discontinuity when HW drain is completed because that can cause
3037 // the timestamp frame position to reset to 0 for direct and offload threads.
3038 // (Out of sequence requests are ignored, since the discontinuity would be handled
3039 // elsewhere, e.g. in flush).
Dean Wheatley12473e92021-03-18 23:00:55 +11003040 mTimestampVerifier.discontinuity(mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003041 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003042 mWaitWorkCV.signal();
3043 }
3044}
3045
Andy Hung71742ab2023-07-07 13:47:37 -07003046void PlaybackThread::readOutputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08003047{
Glenn Kastenadad3d72014-02-21 14:51:43 -08003048 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Mikhail Naganov560637e2021-03-31 22:40:13 +00003049 const audio_config_base_t audioConfig = mOutput->getAudioProperties();
3050 mSampleRate = audioConfig.sample_rate;
3051 mChannelMask = audioConfig.channel_mask;
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003052 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08003053 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003054 }
Andy Hung71742ab2023-07-07 13:47:37 -07003055 if (hasMixer() && !AudioFlinger::isValidPcmSinkChannelMask(mChannelMask)) {
Andy Hung9a592762014-07-21 21:56:01 -07003056 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output",
3057 mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003058 }
Eric Laurentf1f22e72021-07-13 14:04:14 +02003059
3060 if (mMixerChannelMask == AUDIO_CHANNEL_NONE) {
3061 mMixerChannelMask = mChannelMask;
3062 }
3063
Andy Hunge5412692014-05-16 11:25:07 -07003064 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01003065 mBalance.setChannelMask(mChannelMask);
Phil Burkca5e6142015-07-14 09:42:29 -07003066
Eric Laurentf1f22e72021-07-13 14:04:14 +02003067 uint32_t mixerChannelCount = audio_channel_count_from_out_mask(mMixerChannelMask);
3068
Phil Burkca5e6142015-07-14 09:42:29 -07003069 // Get actual HAL format.
Mikhail Naganov560637e2021-03-31 22:40:13 +00003070 status_t result = mOutput->stream->getAudioProperties(nullptr, nullptr, &mHALFormat);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003071 LOG_ALWAYS_FATAL_IF(result != OK, "Error when retrieving output stream format: %d", result);
Phil Burkca5e6142015-07-14 09:42:29 -07003072 // Get format from the shim, which will be different than the HAL format
3073 // if playing compressed audio over HDMI passthrough.
Mikhail Naganov560637e2021-03-31 22:40:13 +00003074 mFormat = audioConfig.format;
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003075 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08003076 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003077 }
Andy Hung71742ab2023-07-07 13:47:37 -07003078 if (hasMixer() && !AudioFlinger::isValidPcmSinkFormat(mFormat)) {
Andy Hung6146c082014-03-18 11:56:15 -07003079 LOG_FATAL("HAL format %#x not supported for mixed output",
3080 mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003081 }
Phil Burk062e67a2015-02-11 13:40:50 -08003082 mFrameSize = mOutput->getFrameSize();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003083 result = mOutput->stream->getBufferSize(&mBufferSize);
3084 LOG_ALWAYS_FATAL_IF(result != OK,
3085 "Error when retrieving output stream buffer size: %d", result);
Glenn Kasten70949c42013-08-06 07:40:12 -07003086 mFrameCount = mBufferSize / mFrameSize;
Eric Laurentb3f315a2021-07-13 15:09:05 +02003087 if (hasMixer() && (mFrameCount & 15)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003088 ALOGW("HAL output buffer size is %zu frames but AudioMixer requires multiples of 16 frames",
Eric Laurent81784c32012-11-19 14:55:58 -08003089 mFrameCount);
3090 }
3091
Eric Laurentd1f69b02014-12-15 14:33:13 -08003092 mHwSupportsPause = false;
3093 if (mOutput->flags & AUDIO_OUTPUT_FLAG_DIRECT) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003094 bool supportsPause = false, supportsResume = false;
3095 if (mOutput->stream->supportsPauseAndResume(&supportsPause, &supportsResume) == OK) {
3096 if (supportsPause && supportsResume) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08003097 mHwSupportsPause = true;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003098 } else if (supportsPause) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08003099 ALOGW("direct output implements pause but not resume");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003100 } else if (supportsResume) {
3101 ALOGW("direct output implements resume but not pause");
Eric Laurentd1f69b02014-12-15 14:33:13 -08003102 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08003103 }
3104 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07003105 if (!mHwSupportsPause && mOutput->flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) {
3106 LOG_ALWAYS_FATAL("HW_AV_SYNC requested but HAL does not implement pause and resume");
3107 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08003108
Andy Hungfbfc3952015-01-15 13:33:51 -08003109 if (mType == DUPLICATING && mMixerBufferEnabled && mEffectBufferEnabled) {
3110 // For best precision, we use float instead of the associated output
3111 // device format (typically PCM 16 bit).
3112
3113 mFormat = AUDIO_FORMAT_PCM_FLOAT;
3114 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
3115 mBufferSize = mFrameSize * mFrameCount;
3116
3117 // TODO: We currently use the associated output device channel mask and sample rate.
3118 // (1) Perhaps use the ORed channel mask of all downstream MixerThreads
3119 // (if a valid mask) to avoid premature downmix.
3120 // (2) Perhaps use the maximum sample rate of all downstream MixerThreads
3121 // instead of the output device sample rate to avoid loss of high frequency information.
3122 // This may need to be updated as MixerThread/OutputTracks are added and not here.
3123 }
3124
Andy Hung09a50072014-02-27 14:30:47 -08003125 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08003126 double multiplier = 1.0;
Andy Hungd3639922022-04-28 18:00:49 -07003127 // Note: mType == SPATIALIZER does not support FastMixer.
Eric Laurent81784c32012-11-19 14:55:58 -08003128 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
3129 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08003130 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
3131 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Haynes Mathew George227a14b2016-05-09 12:45:48 -07003132
Eric Laurent81784c32012-11-19 14:55:58 -08003133 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
3134 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
3135 maxNormalFrameCount = maxNormalFrameCount & ~15;
3136 if (maxNormalFrameCount < minNormalFrameCount) {
3137 maxNormalFrameCount = minNormalFrameCount;
3138 }
3139 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
3140 if (multiplier <= 1.0) {
3141 multiplier = 1.0;
3142 } else if (multiplier <= 2.0) {
3143 if (2 * mFrameCount <= maxNormalFrameCount) {
3144 multiplier = 2.0;
3145 } else {
3146 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
3147 }
3148 } else {
Haynes Mathew George227a14b2016-05-09 12:45:48 -07003149 multiplier = floor(multiplier);
Eric Laurent81784c32012-11-19 14:55:58 -08003150 }
3151 }
3152 mNormalFrameCount = multiplier * mFrameCount;
3153 // round up to nearest 16 frames to satisfy AudioMixer
Eric Laurentb3f315a2021-07-13 15:09:05 +02003154 if (hasMixer()) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07003155 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
3156 }
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003157 ALOGI("HAL output buffer size %zu frames, normal sink buffer size %zu frames", mFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08003158 mNormalFrameCount);
3159
Andy Hung08fb1742015-05-31 23:22:10 -07003160 // Check if we want to throttle the processing to no more than 2x normal rate
3161 mThreadThrottle = property_get_bool("af.thread.throttle", true /* default_value */);
Andy Hung40eb1a12015-06-18 13:42:02 -07003162 mThreadThrottleTimeMs = 0;
3163 mThreadThrottleEndMs = 0;
Andy Hung08fb1742015-05-31 23:22:10 -07003164 mHalfBufferMs = mNormalFrameCount * 1000 / (2 * mSampleRate);
3165
Andy Hung010a1a12014-03-13 13:57:33 -07003166 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
3167 // Originally this was int16_t[] array, need to remove legacy implications.
3168 free(mSinkBuffer);
3169 mSinkBuffer = NULL;
Eric Laurent39095982021-08-24 18:29:27 +02003170
Andy Hung5b10a202014-03-13 13:59:29 -07003171 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
3172 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
3173 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07003174 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08003175
Andy Hung69aed5f2014-02-25 17:24:40 -08003176 // We resize the mMixerBuffer according to the requirements of the sink buffer which
3177 // drives the output.
3178 free(mMixerBuffer);
3179 mMixerBuffer = NULL;
3180 if (mMixerBufferEnabled) {
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01003181 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // no longer valid: AUDIO_FORMAT_PCM_16_BIT.
Eric Laurentf1f22e72021-07-13 14:04:14 +02003182 mMixerBufferSize = mNormalFrameCount * mixerChannelCount
Andy Hung69aed5f2014-02-25 17:24:40 -08003183 * audio_bytes_per_sample(mMixerBufferFormat);
3184 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
3185 }
Andy Hung98ef9782014-03-04 14:46:50 -08003186 free(mEffectBuffer);
3187 mEffectBuffer = NULL;
3188 if (mEffectBufferEnabled) {
Andy Hung319587b2023-05-23 14:01:03 -07003189 mEffectBufferFormat = AUDIO_FORMAT_PCM_FLOAT;
Eric Laurentf1f22e72021-07-13 14:04:14 +02003190 mEffectBufferSize = mNormalFrameCount * mixerChannelCount
Andy Hung98ef9782014-03-04 14:46:50 -08003191 * audio_bytes_per_sample(mEffectBufferFormat);
3192 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
3193 }
Andy Hung69aed5f2014-02-25 17:24:40 -08003194
Eric Laurentb62d0362021-10-26 17:40:18 +02003195 if (mType == SPATIALIZER) {
3196 free(mPostSpatializerBuffer);
3197 mPostSpatializerBuffer = nullptr;
3198 mPostSpatializerBufferSize = mNormalFrameCount * mChannelCount
3199 * audio_bytes_per_sample(mEffectBufferFormat);
3200 (void)posix_memalign(&mPostSpatializerBuffer, 32, mPostSpatializerBufferSize);
3201 }
3202
Mikhail Naganov55773032020-10-01 15:08:13 -07003203 mHapticChannelMask = static_cast<audio_channel_mask_t>(mChannelMask & AUDIO_CHANNEL_HAPTIC_ALL);
3204 mChannelMask = static_cast<audio_channel_mask_t>(mChannelMask & ~mHapticChannelMask);
jiabin245cdd92018-12-07 17:55:15 -08003205 mHapticChannelCount = audio_channel_count_from_out_mask(mHapticChannelMask);
3206 mChannelCount -= mHapticChannelCount;
Eric Laurentf1f22e72021-07-13 14:04:14 +02003207 mMixerChannelMask = static_cast<audio_channel_mask_t>(mMixerChannelMask & ~mHapticChannelMask);
jiabin245cdd92018-12-07 17:55:15 -08003208
Eric Laurent81784c32012-11-19 14:55:58 -08003209 // force reconfiguration of effect chains and engines to take new buffer size and audio
3210 // parameters into account
Glenn Kastendeca2ae2014-02-07 10:25:56 -08003211 // Note that mLock is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08003212 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
3213 // matter.
3214 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
Andy Hungbd72c542023-06-20 18:56:17 -07003215 Vector<sp<IAfEffectChain>> effectChains = mEffectChains;
Eric Laurent81784c32012-11-19 14:55:58 -08003216 for (size_t i = 0; i < effectChains.size(); i ++) {
Andy Hung2cbc2722023-07-17 17:05:00 -07003217 mAfThreadCallback->moveEffectChain_l(effectChains[i]->sessionId(),
Eric Laurent6c796322019-04-09 14:13:17 -07003218 this/* srcThread */, this/* dstThread */);
Eric Laurent81784c32012-11-19 14:55:58 -08003219 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08003220
George Burgess IV5e4d86f2020-02-18 12:55:36 -08003221 audio_output_flags_t flags = mOutput->flags;
Andy Hungcf10d742020-04-28 15:38:24 -07003222 mediametrics::LogItem item(mThreadMetrics.getMetricsId()); // TODO: method in ThreadMetrics?
Andy Hungb68f5eb2019-12-03 16:49:17 -08003223 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
3224 .set(AMEDIAMETRICS_PROP_ENCODING, formatToString(mFormat).c_str())
3225 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
3226 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
3227 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
3228 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mNormalFrameCount)
3229 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
3230 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELMASK,
3231 (int32_t)mHapticChannelMask)
3232 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELCOUNT,
3233 (int32_t)mHapticChannelCount)
3234 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_ENCODING,
3235 formatToString(mHALFormat).c_str())
3236 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_FRAMECOUNT,
3237 (int32_t)mFrameCount) // sic - added HAL
3238 ;
3239 uint32_t latencyMs;
3240 if (mOutput->stream->getLatency(&latencyMs) == NO_ERROR) {
3241 item.set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_LATENCYMS, (double)latencyMs);
3242 }
3243 item.record();
Eric Laurent81784c32012-11-19 14:55:58 -08003244}
3245
Andy Hung71742ab2023-07-07 13:47:37 -07003246ThreadBase::MetadataUpdate PlaybackThread::updateMetadata_l()
Kevin Rocard069c2712018-03-29 19:09:14 -07003247{
Jasmine Chaeaa10e42021-05-11 10:11:14 +08003248 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
Vlad Popa7e81cea2023-01-19 16:34:16 +01003249 return {}; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -07003250 }
3251 StreamOutHalInterface::SourceMetadata metadata;
Kevin Rocard12381092018-04-11 09:19:59 -07003252 auto backInserter = std::back_inserter(metadata.tracks);
Andy Hung3ff4b552023-06-26 19:20:57 -07003253 for (const sp<IAfTrack>& track : mActiveTracks) {
Kevin Rocard069c2712018-03-29 19:09:14 -07003254 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurent49e39282022-06-24 18:42:45 +02003255 track->copyMetadataTo(backInserter);
Kevin Rocard069c2712018-03-29 19:09:14 -07003256 }
Kevin Rocard12381092018-04-11 09:19:59 -07003257 sendMetadataToBackend_l(metadata);
Vlad Popa7e81cea2023-01-19 16:34:16 +01003258 MetadataUpdate change;
3259 change.playbackMetadataUpdate = metadata.tracks;
3260 return change;
Kevin Rocard80ee2722018-04-11 15:53:48 +00003261}
Kevin Rocardc86a7f72018-04-03 09:00:09 -07003262
Andy Hung71742ab2023-07-07 13:47:37 -07003263void PlaybackThread::sendMetadataToBackend_l(
Kevin Rocard12381092018-04-11 09:19:59 -07003264 const StreamOutHalInterface::SourceMetadata& metadata)
3265{
3266 mOutput->stream->updateSourceMetadata(metadata);
3267};
3268
Andy Hung71742ab2023-07-07 13:47:37 -07003269status_t PlaybackThread::getRenderPosition(
Andy Hung4989d312023-06-29 21:19:25 -07003270 uint32_t* halFrames, uint32_t* dspFrames) const
Eric Laurent81784c32012-11-19 14:55:58 -08003271{
3272 if (halFrames == NULL || dspFrames == NULL) {
3273 return BAD_VALUE;
3274 }
3275 Mutex::Autolock _l(mLock);
3276 if (initCheck() != NO_ERROR) {
3277 return INVALID_OPERATION;
3278 }
Andy Hung818e7a32016-02-16 18:08:07 -08003279 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08003280 *halFrames = framesWritten;
3281
3282 if (isSuspended()) {
3283 // return an estimation of rendered frames when the output is suspended
3284 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08003285 *dspFrames = (uint32_t)
3286 (framesWritten >= (int64_t)latencyFrames ? framesWritten - latencyFrames : 0);
Eric Laurent81784c32012-11-19 14:55:58 -08003287 return NO_ERROR;
3288 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003289 status_t status;
3290 uint32_t frames;
Phil Burk062e67a2015-02-11 13:40:50 -08003291 status = mOutput->getRenderPosition(&frames);
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003292 *dspFrames = (size_t)frames;
3293 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08003294 }
3295}
3296
Andy Hung71742ab2023-07-07 13:47:37 -07003297product_strategy_t PlaybackThread::getStrategyForSession_l(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08003298{
3299 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
3300 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
3301 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02003302 return getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurent81784c32012-11-19 14:55:58 -08003303 }
3304 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung3ff4b552023-06-26 19:20:57 -07003305 sp<IAfTrack> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08003306 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02003307 return getStrategyForStream(track->streamType());
Eric Laurent81784c32012-11-19 14:55:58 -08003308 }
3309 }
Eric Laurentd66d7a12021-07-13 13:35:32 +02003310 return getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurent81784c32012-11-19 14:55:58 -08003311}
3312
3313
Andy Hung71742ab2023-07-07 13:47:37 -07003314AudioStreamOut* PlaybackThread::getOutput() const
Eric Laurent81784c32012-11-19 14:55:58 -08003315{
3316 Mutex::Autolock _l(mLock);
3317 return mOutput;
3318}
3319
Andy Hung71742ab2023-07-07 13:47:37 -07003320AudioStreamOut* PlaybackThread::clearOutput()
Eric Laurent81784c32012-11-19 14:55:58 -08003321{
3322 Mutex::Autolock _l(mLock);
3323 AudioStreamOut *output = mOutput;
3324 mOutput = NULL;
3325 // FIXME FastMixer might also have a raw ptr to mOutputSink;
3326 // must push a NULL and wait for ack
3327 mOutputSink.clear();
3328 mPipeSink.clear();
3329 mNormalSink.clear();
3330 return output;
3331}
3332
3333// this method must always be called either with ThreadBase mLock held or inside the thread loop
Andy Hung71742ab2023-07-07 13:47:37 -07003334sp<StreamHalInterface> PlaybackThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08003335{
3336 if (mOutput == NULL) {
3337 return NULL;
3338 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003339 return mOutput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08003340}
3341
Andy Hung71742ab2023-07-07 13:47:37 -07003342uint32_t PlaybackThread::activeSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08003343{
3344 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
3345}
3346
Andy Hung71742ab2023-07-07 13:47:37 -07003347status_t PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
Eric Laurent81784c32012-11-19 14:55:58 -08003348{
3349 if (!isValidSyncEvent(event)) {
3350 return BAD_VALUE;
3351 }
3352
3353 Mutex::Autolock _l(mLock);
3354
3355 for (size_t i = 0; i < mTracks.size(); ++i) {
Andy Hung3ff4b552023-06-26 19:20:57 -07003356 sp<IAfTrack> track = mTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08003357 if (event->triggerSession() == track->sessionId()) {
3358 (void) track->setSyncEvent(event);
3359 return NO_ERROR;
3360 }
3361 }
3362
3363 return NAME_NOT_FOUND;
3364}
3365
Andy Hung71742ab2023-07-07 13:47:37 -07003366bool PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
Eric Laurent81784c32012-11-19 14:55:58 -08003367{
3368 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
3369}
3370
Andy Hung71742ab2023-07-07 13:47:37 -07003371void PlaybackThread::threadLoop_removeTracks(
Andy Hung3ff4b552023-06-26 19:20:57 -07003372 [[maybe_unused]] const Vector<sp<IAfTrack>>& tracksToRemove)
Eric Laurent81784c32012-11-19 14:55:58 -08003373{
Andy Hungfe726a62018-09-27 15:17:25 -07003374 // Miscellaneous track cleanup when removed from the active list,
3375 // called without Thread lock but synchronized with threadLoop processing.
Eric Laurentbfb1b832013-01-07 09:53:42 -08003376#ifdef ADD_BATTERY_DATA
Andy Hungfe726a62018-09-27 15:17:25 -07003377 for (const auto& track : tracksToRemove) {
3378 if (track->isExternalTrack()) {
3379 // to track the speaker usage
3380 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Eric Laurent81784c32012-11-19 14:55:58 -08003381 }
3382 }
Andy Hungfe726a62018-09-27 15:17:25 -07003383#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003384}
3385
Andy Hung71742ab2023-07-07 13:47:37 -07003386void PlaybackThread::checkSilentMode_l()
Eric Laurent81784c32012-11-19 14:55:58 -08003387{
3388 if (!mMasterMute) {
3389 char value[PROPERTY_VALUE_MAX];
jiabin0a957d32020-04-29 10:56:20 -07003390 if (mOutDeviceTypeAddrs.empty()) {
3391 ALOGD("ro.audio.silent is ignored since no output device is set");
3392 return;
3393 }
jiabinc52b1ff2019-10-31 17:20:42 -07003394 if (isSingleDeviceType(outDeviceTypes(), AUDIO_DEVICE_OUT_REMOTE_SUBMIX)) {
Jean-Michel Trivi32f37c22016-03-31 16:00:32 -07003395 ALOGD("ro.audio.silent will be ignored for threads on AUDIO_DEVICE_OUT_REMOTE_SUBMIX");
3396 return;
3397 }
Eric Laurent81784c32012-11-19 14:55:58 -08003398 if (property_get("ro.audio.silent", value, "0") > 0) {
3399 char *endptr;
3400 unsigned long ul = strtoul(value, &endptr, 0);
3401 if (*endptr == '\0' && ul != 0) {
3402 ALOGD("Silence is golden");
3403 // The setprop command will not allow a property to be changed after
3404 // the first time it is set, so we don't have to worry about un-muting.
3405 setMasterMute_l(true);
3406 }
3407 }
3408 }
3409}
3410
3411// shared by MIXER and DIRECT, overridden by DUPLICATING
Andy Hung71742ab2023-07-07 13:47:37 -07003412ssize_t PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08003413{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07003414 LOG_HIST_TS();
Eric Laurent81784c32012-11-19 14:55:58 -08003415 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003416 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07003417 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08003418
3419 // If an NBAIO sink is present, use it to write the normal mixer's submix
3420 if (mNormalSink != 0) {
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003421
Andy Hung010a1a12014-03-13 13:57:33 -07003422 const size_t count = mBytesRemaining / mFrameSize;
3423
Simon Wilson2d590962012-11-29 15:18:50 -08003424 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08003425 // update the setpoint when AudioFlinger::mScreenState changes
Andy Hung01b29482023-07-19 16:22:58 -07003426 const uint32_t screenState = mAfThreadCallback->getScreenState();
Eric Laurent81784c32012-11-19 14:55:58 -08003427 if (screenState != mScreenState) {
3428 mScreenState = screenState;
3429 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
3430 if (pipe != NULL) {
3431 pipe->setAvgFrames((mScreenState & 1) ?
3432 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
3433 }
3434 }
Andy Hung010a1a12014-03-13 13:57:33 -07003435 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08003436 ATRACE_END();
Vlad Popab042ee62022-10-20 18:05:00 +02003437
Eric Laurent81784c32012-11-19 14:55:58 -08003438 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07003439 bytesWritten = framesWritten * mFrameSize;
Andy Hung58e32872022-11-15 16:12:24 -08003440
Andy Hung8946a282018-04-19 20:04:56 -07003441#ifdef TEE_SINK
3442 mTee.write((char *)mSinkBuffer + offset, framesWritten);
3443#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003444 } else {
3445 bytesWritten = framesWritten;
3446 }
3447 // otherwise use the HAL / AudioStreamOut directly
3448 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003449 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07003450
Eric Laurentbfb1b832013-01-07 09:53:42 -08003451 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003452 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
3453 mWriteAckSequence += 2;
3454 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003455 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003456 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003457 }
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07003458 ATRACE_BEGIN("write");
Glenn Kasten767094d2013-08-23 13:51:43 -07003459 // FIXME We should have an implementation of timestamps for direct output threads.
3460 // They are used e.g for multichannel PCM playback over HDMI.
Phil Burk062e67a2015-02-11 13:40:50 -08003461 bytesWritten = mOutput->write((char *)mSinkBuffer + offset, mBytesRemaining);
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07003462 ATRACE_END();
Eric Laurent51716182016-02-29 18:00:56 -08003463
Eric Laurentbfb1b832013-01-07 09:53:42 -08003464 if (mUseAsyncWrite &&
3465 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
3466 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07003467 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003468 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003469 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003470 }
Eric Laurent81784c32012-11-19 14:55:58 -08003471 }
3472
Eric Laurent81784c32012-11-19 14:55:58 -08003473 mNumWrites++;
3474 mInWrite = false;
Andy Hungcf10d742020-04-28 15:38:24 -07003475 if (mStandby) {
3476 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07003477 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -07003478 mStandby = false;
3479 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003480 return bytesWritten;
3481}
3482
Vlad Popa6fbbfbf2023-02-22 15:05:43 +01003483// startMelComputation_l() must be called with AudioFlinger::mLock held
Andy Hung71742ab2023-07-07 13:47:37 -07003484void PlaybackThread::startMelComputation_l(
Vlad Popaf09e93f2022-10-31 16:27:12 +01003485 const sp<audio_utils::MelProcessor>& processor)
Vlad Popab042ee62022-10-20 18:05:00 +02003486{
Vlad Popa3c7a2662023-02-14 20:09:47 +01003487 auto outputSink = static_cast<AudioStreamOutSink*>(mOutputSink.get());
Vlad Popa1a0c3ab2023-03-17 01:07:01 +01003488 if (outputSink != nullptr) {
3489 outputSink->startMelComputation(processor);
3490 }
Vlad Popab042ee62022-10-20 18:05:00 +02003491}
3492
Vlad Popa6fbbfbf2023-02-22 15:05:43 +01003493// stopMelComputation_l() must be called with AudioFlinger::mLock held
Andy Hung71742ab2023-07-07 13:47:37 -07003494void PlaybackThread::stopMelComputation_l()
Vlad Popa3c7a2662023-02-14 20:09:47 +01003495{
3496 auto outputSink = static_cast<AudioStreamOutSink*>(mOutputSink.get());
Vlad Popa1a0c3ab2023-03-17 01:07:01 +01003497 if (outputSink != nullptr) {
3498 outputSink->stopMelComputation();
3499 }
Vlad Popab042ee62022-10-20 18:05:00 +02003500}
3501
Andy Hung71742ab2023-07-07 13:47:37 -07003502void PlaybackThread::threadLoop_drain()
Eric Laurentbfb1b832013-01-07 09:53:42 -08003503{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003504 bool supportsDrain = false;
3505 if (mOutput->stream->supportsDrain(&supportsDrain) == OK && supportsDrain) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003506 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
3507 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003508 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
3509 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003510 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003511 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003512 }
Mikhail Naganovcbc8f612016-10-11 18:05:13 -07003513 status_t result = mOutput->stream->drain(mMixerStatus == MIXER_DRAIN_TRACK);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003514 ALOGE_IF(result != OK, "Error when draining stream: %d", result);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003515 }
3516}
3517
Andy Hung71742ab2023-07-07 13:47:37 -07003518void PlaybackThread::threadLoop_exit()
Eric Laurentbfb1b832013-01-07 09:53:42 -08003519{
Eric Laurent275e8e92014-11-30 15:14:47 -08003520 {
3521 Mutex::Autolock _l(mLock);
3522 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung3ff4b552023-06-26 19:20:57 -07003523 sp<IAfTrack> track = mTracks[i];
Eric Laurent275e8e92014-11-30 15:14:47 -08003524 track->invalidate();
3525 }
Andy Hungdae27702016-10-31 14:01:16 -07003526 // Clear ActiveTracks to update BatteryNotifier in case active tracks remain.
3527 // After we exit there are no more track changes sent to BatteryNotifier
3528 // because that requires an active threadLoop.
3529 // TODO: should we decActiveTrackCnt() of the cleared track effect chain?
3530 mActiveTracks.clear();
Eric Laurent275e8e92014-11-30 15:14:47 -08003531 }
Eric Laurent81784c32012-11-19 14:55:58 -08003532}
3533
3534/*
3535The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08003536 - mSinkBufferSize from frame count * frame size
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003537 - mActiveSleepTimeUs from activeSleepTimeUs()
3538 - mIdleSleepTimeUs from idleSleepTimeUs()
Eric Laurent42537be2016-01-08 17:16:42 -08003539 - mStandbyDelayNs from mActiveSleepTimeUs (DIRECT only) or forced to at least
3540 kDefaultStandbyTimeInNsecs when connected to an A2DP device.
Eric Laurent81784c32012-11-19 14:55:58 -08003541 - maxPeriod from frame count and sample rate (MIXER only)
3542
3543The parameters that affect these derived values are:
3544 - frame count
3545 - frame size
3546 - sample rate
3547 - device type: A2DP or not
3548 - device latency
3549 - format: PCM or not
3550 - active sleep time
3551 - idle sleep time
3552*/
3553
Andy Hung71742ab2023-07-07 13:47:37 -07003554void PlaybackThread::cacheParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08003555{
Andy Hung25c2dac2014-02-27 14:56:00 -08003556 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003557 mActiveSleepTimeUs = activeSleepTimeUs();
3558 mIdleSleepTimeUs = idleSleepTimeUs();
Eric Laurent42537be2016-01-08 17:16:42 -08003559
Eric Laurent52568142022-10-28 11:23:28 +02003560 mStandbyDelayNs = AudioFlinger::mStandbyTimeInNsecs;
Carter Hsu0ca47c22023-06-02 18:01:45 +08003561
Eric Laurent42537be2016-01-08 17:16:42 -08003562 // make sure standby delay is not too short when connected to an A2DP sink to avoid
3563 // truncating audio when going to standby.
jiabinc52b1ff2019-10-31 17:20:42 -07003564 if (!Intersection(outDeviceTypes(), getAudioDeviceOutAllA2dpSet()).empty()) {
Eric Laurent42537be2016-01-08 17:16:42 -08003565 if (mStandbyDelayNs < kDefaultStandbyTimeInNsecs) {
3566 mStandbyDelayNs = kDefaultStandbyTimeInNsecs;
3567 }
3568 }
Eric Laurent81784c32012-11-19 14:55:58 -08003569}
3570
Andy Hung71742ab2023-07-07 13:47:37 -07003571bool PlaybackThread::invalidateTracks_l(audio_stream_type_t streamType)
Eric Laurent81784c32012-11-19 14:55:58 -08003572{
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003573 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %zu",
Eric Laurent81784c32012-11-19 14:55:58 -08003574 this, streamType, mTracks.size());
Eric Laurent13084622016-05-17 10:51:49 -07003575 bool trackMatch = false;
Eric Laurent81784c32012-11-19 14:55:58 -08003576 size_t size = mTracks.size();
3577 for (size_t i = 0; i < size; i++) {
Andy Hung3ff4b552023-06-26 19:20:57 -07003578 sp<IAfTrack> t = mTracks[i];
Eric Laurentd60560a2015-04-10 11:31:20 -07003579 if (t->streamType() == streamType && t->isExternalTrack()) {
Glenn Kasten5736c352012-12-04 12:12:34 -08003580 t->invalidate();
Eric Laurent13084622016-05-17 10:51:49 -07003581 trackMatch = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003582 }
3583 }
Eric Laurent13084622016-05-17 10:51:49 -07003584 return trackMatch;
Eric Laurent81784c32012-11-19 14:55:58 -08003585}
3586
Andy Hung71742ab2023-07-07 13:47:37 -07003587void PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
Haynes Mathew George05317d22016-05-03 16:34:26 -07003588{
3589 Mutex::Autolock _l(mLock);
3590 invalidateTracks_l(streamType);
3591}
3592
Andy Hung71742ab2023-07-07 13:47:37 -07003593void PlaybackThread::invalidateTracks(std::set<audio_port_handle_t>& portIds) {
jiabinc44b3462022-12-08 12:52:31 -08003594 Mutex::Autolock _l(mLock);
3595 invalidateTracks_l(portIds);
3596}
3597
Andy Hung71742ab2023-07-07 13:47:37 -07003598bool PlaybackThread::invalidateTracks_l(std::set<audio_port_handle_t>& portIds) {
jiabinc44b3462022-12-08 12:52:31 -08003599 bool trackMatch = false;
3600 const size_t size = mTracks.size();
3601 for (size_t i = 0; i < size; i++) {
Andy Hung3ff4b552023-06-26 19:20:57 -07003602 sp<IAfTrack> t = mTracks[i];
jiabinc44b3462022-12-08 12:52:31 -08003603 if (t->isExternalTrack() && portIds.find(t->portId()) != portIds.end()) {
3604 t->invalidate();
3605 portIds.erase(t->portId());
3606 trackMatch = true;
3607 }
3608 if (portIds.empty()) {
3609 break;
3610 }
3611 }
3612 return trackMatch;
3613}
3614
jiabinf042b9b2021-05-07 23:46:28 +00003615// getTrackById_l must be called with holding thread lock
Andy Hung71742ab2023-07-07 13:47:37 -07003616IAfTrack* PlaybackThread::getTrackById_l(
jiabinf042b9b2021-05-07 23:46:28 +00003617 audio_port_handle_t trackPortId) {
3618 for (size_t i = 0; i < mTracks.size(); i++) {
3619 if (mTracks[i]->portId() == trackPortId) {
3620 return mTracks[i].get();
3621 }
3622 }
3623 return nullptr;
3624}
3625
Andy Hung71742ab2023-07-07 13:47:37 -07003626status_t PlaybackThread::addEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08003627{
Glenn Kastend848eb42016-03-08 13:42:11 -08003628 audio_session_t session = chain->sessionId();
Mikhail Naganov022b9952017-01-04 16:36:51 -08003629 sp<EffectBufferHalInterface> halInBuffer, halOutBuffer;
Andy Hung319587b2023-05-23 14:01:03 -07003630 float *buffer = nullptr; // only used for non global sessions
Eric Laurentb62d0362021-10-26 17:40:18 +02003631
Andy Hungd3639922022-04-28 18:00:49 -07003632 if (mType == SPATIALIZER) {
Eric Laurentb62d0362021-10-26 17:40:18 +02003633 if (!audio_is_global_session(session)) {
3634 // player sessions on a spatializer output will use a dedicated input buffer and
3635 // will either output multi channel to mEffectBuffer if the track is spatilaized
3636 // or stereo to mPostSpatializerBuffer if not spatialized.
3637 uint32_t channelMask;
3638 bool isSessionSpatialized =
3639 (hasAudioSession_l(session) & ThreadBase::SPATIALIZED_SESSION) != 0;
3640 if (isSessionSpatialized) {
3641 channelMask = mMixerChannelMask;
3642 } else {
3643 channelMask = mChannelMask;
3644 }
Eric Laurentf1f22e72021-07-13 14:04:14 +02003645 size_t numSamples = mNormalFrameCount
Eric Laurentb62d0362021-10-26 17:40:18 +02003646 * (audio_channel_count_from_out_mask(channelMask) + mHapticChannelCount);
Andy Hung2cbc2722023-07-17 17:05:00 -07003647 status_t result = mAfThreadCallback->getEffectsFactoryHal()->allocateBuffer(
Andy Hung319587b2023-05-23 14:01:03 -07003648 numSamples * sizeof(float),
Mikhail Naganov022b9952017-01-04 16:36:51 -08003649 &halInBuffer);
3650 if (result != OK) return result;
Eric Laurentb62d0362021-10-26 17:40:18 +02003651
Andy Hung2cbc2722023-07-17 17:05:00 -07003652 result = mAfThreadCallback->getEffectsFactoryHal()->mirrorBuffer(
Eric Laurentb62d0362021-10-26 17:40:18 +02003653 isSessionSpatialized ? mEffectBuffer : mPostSpatializerBuffer,
3654 isSessionSpatialized ? mEffectBufferSize : mPostSpatializerBufferSize,
3655 &halOutBuffer);
3656 if (result != OK) return result;
3657
Shunkai Yao44bdbad2023-01-14 05:11:58 +00003658 buffer = halInBuffer ? halInBuffer->audioBuffer()->f32 : buffer;
Andy Hung26836922023-05-22 17:31:57 -07003659
Mikhail Naganov022b9952017-01-04 16:36:51 -08003660 ALOGV("addEffectChain_l() creating new input buffer %p session %d",
3661 buffer, session);
Eric Laurentb62d0362021-10-26 17:40:18 +02003662 } else {
3663 // A global session on a SPATIALIZER thread is either OUTPUT_STAGE or DEVICE
3664 // - OUTPUT_STAGE session uses the mEffectBuffer as input buffer and
3665 // mPostSpatializerBuffer as output buffer
3666 // - DEVICE session uses the mPostSpatializerBuffer as input and output buffer.
Andy Hung2cbc2722023-07-17 17:05:00 -07003667 status_t result = mAfThreadCallback->getEffectsFactoryHal()->mirrorBuffer(
Eric Laurentb62d0362021-10-26 17:40:18 +02003668 mEffectBuffer, mEffectBufferSize, &halInBuffer);
3669 if (result != OK) return result;
Andy Hung2cbc2722023-07-17 17:05:00 -07003670 result = mAfThreadCallback->getEffectsFactoryHal()->mirrorBuffer(
Eric Laurentb62d0362021-10-26 17:40:18 +02003671 mPostSpatializerBuffer, mPostSpatializerBufferSize, &halOutBuffer);
3672 if (result != OK) return result;
Eric Laurent81784c32012-11-19 14:55:58 -08003673
Eric Laurentb62d0362021-10-26 17:40:18 +02003674 if (session == AUDIO_SESSION_DEVICE) {
3675 halInBuffer = halOutBuffer;
3676 }
3677 }
3678 } else {
Andy Hung2cbc2722023-07-17 17:05:00 -07003679 status_t result = mAfThreadCallback->getEffectsFactoryHal()->mirrorBuffer(
Eric Laurentb62d0362021-10-26 17:40:18 +02003680 mEffectBufferEnabled ? mEffectBuffer : mSinkBuffer,
3681 mEffectBufferEnabled ? mEffectBufferSize : mSinkBufferSize,
3682 &halInBuffer);
3683 if (result != OK) return result;
3684 halOutBuffer = halInBuffer;
3685 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
3686 if (!audio_is_global_session(session)) {
Andy Hung319587b2023-05-23 14:01:03 -07003687 buffer = halInBuffer ? reinterpret_cast<float*>(halInBuffer->externalData())
Shunkai Yao44bdbad2023-01-14 05:11:58 +00003688 : buffer;
Eric Laurentb62d0362021-10-26 17:40:18 +02003689 // Only one effect chain can be present in direct output thread and it uses
3690 // the sink buffer as input
3691 if (mType != DIRECT) {
3692 size_t numSamples = mNormalFrameCount
3693 * (audio_channel_count_from_out_mask(mMixerChannelMask)
3694 + mHapticChannelCount);
Andy Hung2cbc2722023-07-17 17:05:00 -07003695 const status_t allocateStatus =
3696 mAfThreadCallback->getEffectsFactoryHal()->allocateBuffer(
Andy Hung319587b2023-05-23 14:01:03 -07003697 numSamples * sizeof(float),
Eric Laurentb62d0362021-10-26 17:40:18 +02003698 &halInBuffer);
Andy Hung71ba4b32022-10-06 12:09:49 -07003699 if (allocateStatus != OK) return allocateStatus;
Andy Hung26836922023-05-22 17:31:57 -07003700
Shunkai Yao44bdbad2023-01-14 05:11:58 +00003701 buffer = halInBuffer ? halInBuffer->audioBuffer()->f32 : buffer;
Eric Laurentb62d0362021-10-26 17:40:18 +02003702 ALOGV("addEffectChain_l() creating new input buffer %p session %d",
3703 buffer, session);
3704 }
3705 }
3706 }
3707
3708 if (!audio_is_global_session(session)) {
Eric Laurent81784c32012-11-19 14:55:58 -08003709 // Attach all tracks with same session ID to this chain.
3710 for (size_t i = 0; i < mTracks.size(); ++i) {
Andy Hung3ff4b552023-06-26 19:20:57 -07003711 sp<IAfTrack> track = mTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08003712 if (session == track->sessionId()) {
Eric Laurentb62d0362021-10-26 17:40:18 +02003713 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p",
3714 track.get(), buffer);
Eric Laurent81784c32012-11-19 14:55:58 -08003715 track->setMainBuffer(buffer);
3716 chain->incTrackCnt();
3717 }
3718 }
3719
3720 // indicate all active tracks in the chain
Andy Hung3ff4b552023-06-26 19:20:57 -07003721 for (const sp<IAfTrack>& track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08003722 if (session == track->sessionId()) {
Eric Laurentb62d0362021-10-26 17:40:18 +02003723 ALOGV("addEffectChain_l() activating track %p on session %d",
3724 track.get(), session);
Eric Laurent81784c32012-11-19 14:55:58 -08003725 chain->incActiveTrackCnt();
3726 }
3727 }
3728 }
Eric Laurentb62d0362021-10-26 17:40:18 +02003729
Eric Laurentaaa44472014-09-12 17:41:50 -07003730 chain->setThread(this);
Mikhail Naganov022b9952017-01-04 16:36:51 -08003731 chain->setInBuffer(halInBuffer);
3732 chain->setOutBuffer(halOutBuffer);
Eric Laurent3f75a5b2019-11-12 15:55:51 -08003733 // Effect chain for session AUDIO_SESSION_DEVICE is inserted at end of effect
3734 // chains list in order to be processed last as it contains output device effects.
3735 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted just before to apply post
3736 // processing effects specific to an output stream before effects applied to all streams
3737 // routed to a given device.
Eric Laurent81784c32012-11-19 14:55:58 -08003738 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
3739 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Glenn Kastend848eb42016-03-08 13:42:11 -08003740 // after track specific effects and before output stage.
Eric Laurent81784c32012-11-19 14:55:58 -08003741 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
Glenn Kastend848eb42016-03-08 13:42:11 -08003742 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX.
Eric Laurent81784c32012-11-19 14:55:58 -08003743 // Effect chain for other sessions are inserted at beginning of effect
3744 // chains list to be processed before output mix effects. Relative order between other
Glenn Kastend848eb42016-03-08 13:42:11 -08003745 // sessions is not important.
3746 static_assert(AUDIO_SESSION_OUTPUT_MIX == 0 &&
Eric Laurent3f75a5b2019-11-12 15:55:51 -08003747 AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX &&
3748 AUDIO_SESSION_DEVICE < AUDIO_SESSION_OUTPUT_STAGE,
Glenn Kastend848eb42016-03-08 13:42:11 -08003749 "audio_session_t constants misdefined");
Eric Laurent81784c32012-11-19 14:55:58 -08003750 size_t size = mEffectChains.size();
3751 size_t i = 0;
3752 for (i = 0; i < size; i++) {
3753 if (mEffectChains[i]->sessionId() < session) {
3754 break;
3755 }
3756 }
3757 mEffectChains.insertAt(chain, i);
3758 checkSuspendOnAddEffectChain_l(chain);
3759
3760 return NO_ERROR;
3761}
3762
Andy Hung71742ab2023-07-07 13:47:37 -07003763size_t PlaybackThread::removeEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08003764{
Glenn Kastend848eb42016-03-08 13:42:11 -08003765 audio_session_t session = chain->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08003766
3767 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
3768
3769 for (size_t i = 0; i < mEffectChains.size(); i++) {
3770 if (chain == mEffectChains[i]) {
3771 mEffectChains.removeAt(i);
3772 // detach all active tracks from the chain
Andy Hung3ff4b552023-06-26 19:20:57 -07003773 for (const sp<IAfTrack>& track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08003774 if (session == track->sessionId()) {
3775 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
3776 chain.get(), session);
3777 chain->decActiveTrackCnt();
3778 }
3779 }
3780
3781 // detach all tracks with same session ID from this chain
Andy Hung71ba4b32022-10-06 12:09:49 -07003782 for (size_t j = 0; j < mTracks.size(); ++j) {
Andy Hung3ff4b552023-06-26 19:20:57 -07003783 sp<IAfTrack> track = mTracks[j];
Eric Laurent81784c32012-11-19 14:55:58 -08003784 if (session == track->sessionId()) {
Andy Hung319587b2023-05-23 14:01:03 -07003785 track->setMainBuffer(reinterpret_cast<float*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08003786 chain->decTrackCnt();
3787 }
3788 }
3789 break;
3790 }
3791 }
3792 return mEffectChains.size();
3793}
3794
Andy Hung71742ab2023-07-07 13:47:37 -07003795status_t PlaybackThread::attachAuxEffect(
Andy Hung3ff4b552023-06-26 19:20:57 -07003796 const sp<IAfTrack>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003797{
3798 Mutex::Autolock _l(mLock);
3799 return attachAuxEffect_l(track, EffectId);
3800}
3801
Andy Hung71742ab2023-07-07 13:47:37 -07003802status_t PlaybackThread::attachAuxEffect_l(
Andy Hung3ff4b552023-06-26 19:20:57 -07003803 const sp<IAfTrack>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003804{
3805 status_t status = NO_ERROR;
3806
3807 if (EffectId == 0) {
3808 track->setAuxBuffer(0, NULL);
3809 } else {
3810 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
Andy Hungbd72c542023-06-20 18:56:17 -07003811 sp<IAfEffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Eric Laurent81784c32012-11-19 14:55:58 -08003812 if (effect != 0) {
3813 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
3814 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
3815 } else {
3816 status = INVALID_OPERATION;
3817 }
3818 } else {
3819 status = BAD_VALUE;
3820 }
3821 }
3822 return status;
3823}
3824
Andy Hung71742ab2023-07-07 13:47:37 -07003825void PlaybackThread::detachAuxEffect_l(int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003826{
3827 for (size_t i = 0; i < mTracks.size(); ++i) {
Andy Hung3ff4b552023-06-26 19:20:57 -07003828 sp<IAfTrack> track = mTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08003829 if (track->auxEffectId() == effectId) {
3830 attachAuxEffect_l(track, 0);
3831 }
3832 }
3833}
3834
Andy Hung71742ab2023-07-07 13:47:37 -07003835bool PlaybackThread::threadLoop()
Andy Hung71ba4b32022-10-06 12:09:49 -07003836NO_THREAD_SAFETY_ANALYSIS // manual locking of AudioFlinger
Eric Laurent81784c32012-11-19 14:55:58 -08003837{
Andy Hung4bf583b2023-05-30 18:10:23 -07003838 aflog::setThreadWriter(mNBLogWriter.get());
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003839
Andy Hung3ff4b552023-06-26 19:20:57 -07003840 Vector<sp<IAfTrack>> tracksToRemove;
Eric Laurent81784c32012-11-19 14:55:58 -08003841
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003842 mStandbyTimeNs = systemTime();
Andy Hung446f4df2019-02-21 12:26:41 -08003843 int64_t lastLoopCountWritten = -2; // never matches "previous" loop, when loopCount = 0.
Eric Laurent81784c32012-11-19 14:55:58 -08003844
3845 // MIXER
3846 nsecs_t lastWarning = 0;
3847
3848 // DUPLICATING
3849 // FIXME could this be made local to while loop?
3850 writeFrames = 0;
3851
3852 cacheParameters_l();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003853 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003854
Andy Hungd3639922022-04-28 18:00:49 -07003855 if (mType == MIXER || mType == SPATIALIZER) {
Eric Laurent81784c32012-11-19 14:55:58 -08003856 sleepTimeShift = 0;
3857 }
3858
3859 CpuStats cpuStats;
3860 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
3861
3862 acquireWakeLock();
3863
Glenn Kasteneef598c2017-04-03 14:41:13 -07003864 // mNBLogWriter logging APIs can only be called by a single thread, typically the
3865 // thread associated with this PlaybackThread.
3866 // If you want to share the mNBLogWriter with other threads (for example, binder threads)
3867 // then all such threads must agree to hold a common mutex before logging.
Glenn Kasten9e58b552013-01-18 15:09:48 -08003868 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
3869 // and then that string will be logged at the next convenient opportunity.
Glenn Kasteneef598c2017-04-03 14:41:13 -07003870 // See reference to logString below.
Glenn Kasten9e58b552013-01-18 15:09:48 -08003871 const char *logString = NULL;
3872
rago1bb90822017-05-02 18:31:48 -07003873 // Estimated time for next buffer to be written to hal. This is used only on
3874 // suspended mode (for now) to help schedule the wait time until next iteration.
3875 nsecs_t timeLoopNextNs = 0;
3876
Eric Laurent664539d2013-09-23 18:24:31 -07003877 checkSilentMode_l();
Glenn Kasteneef598c2017-04-03 14:41:13 -07003878
Andy Hung2dbffc22018-08-08 18:50:41 -07003879 audio_patch_handle_t lastDownstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Andy Hungf3234512018-07-03 14:51:47 -07003880
Eric Laurentb3f315a2021-07-13 15:09:05 +02003881 sendCheckOutputStageEffectsEvent();
3882
Andy Hung446f4df2019-02-21 12:26:41 -08003883 // loopCount is used for statistics and diagnostics.
3884 for (int64_t loopCount = 0; !exitPending(); ++loopCount)
Eric Laurent81784c32012-11-19 14:55:58 -08003885 {
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08003886 // Log merge requests are performed during AudioFlinger binder transactions, but
3887 // that does not cover audio playback. It's requested here for that reason.
Andy Hung2cbc2722023-07-17 17:05:00 -07003888 mAfThreadCallback->requestLogMerge();
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08003889
Eric Laurent81784c32012-11-19 14:55:58 -08003890 cpuStats.sample(myName);
3891
Andy Hungbd72c542023-06-20 18:56:17 -07003892 Vector<sp<IAfEffectChain>> effectChains;
Andy Hung6e6a2e62019-04-30 16:38:41 -07003893 audio_session_t activeHapticSessionId = AUDIO_SESSION_NONE;
Eric Laurentb62d0362021-10-26 17:40:18 +02003894 bool isHapticSessionSpatialized = false;
Andy Hung3ff4b552023-06-26 19:20:57 -07003895 std::vector<sp<IAfTrack>> activeTracks;
Eric Laurent81784c32012-11-19 14:55:58 -08003896
Andy Hung2dbffc22018-08-08 18:50:41 -07003897 // If the device is AUDIO_DEVICE_OUT_BUS, check for downstream latency.
3898 //
jiabinc52b1ff2019-10-31 17:20:42 -07003899 // Note: we access outDeviceTypes() outside of mLock.
3900 if (isMsdDevice() && outDeviceTypes().count(AUDIO_DEVICE_OUT_BUS) != 0) {
Andy Hung2dbffc22018-08-08 18:50:41 -07003901 // Here, we try for the AF lock, but do not block on it as the latency
3902 // is more informational.
Andy Hung2cbc2722023-07-17 17:05:00 -07003903 if (mAfThreadCallback->mutex().tryLock() == NO_ERROR) {
Andy Hungd63e79d2023-07-13 16:52:46 -07003904 std::vector<SoftwarePatch> swPatches;
Andy Hung71ba4b32022-10-06 12:09:49 -07003905 double latencyMs = 0.; // not required; initialized for clang-tidy
Andy Hung2dbffc22018-08-08 18:50:41 -07003906 status_t status = INVALID_OPERATION;
3907 audio_patch_handle_t downstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Andy Hung2cbc2722023-07-17 17:05:00 -07003908 if (mAfThreadCallback->getPatchPanel()->getDownstreamSoftwarePatches(
Andy Hungd63e79d2023-07-13 16:52:46 -07003909 id(), &swPatches) == OK
Andy Hung2dbffc22018-08-08 18:50:41 -07003910 && swPatches.size() > 0) {
3911 status = swPatches[0].getLatencyMs_l(&latencyMs);
3912 downstreamPatchHandle = swPatches[0].getPatchHandle();
3913 }
3914 if (downstreamPatchHandle != lastDownstreamPatchHandle) {
Dean Wheatley30d28422018-11-06 10:27:40 +11003915 mDownstreamLatencyStatMs.reset();
Andy Hung2dbffc22018-08-08 18:50:41 -07003916 lastDownstreamPatchHandle = downstreamPatchHandle;
3917 }
3918 if (status == OK) {
3919 // verify downstream latency (we assume a max reasonable
Mikhail Naganov6aa0a312018-11-09 11:00:01 -08003920 // latency of 5 seconds).
3921 const double minLatency = 0., maxLatency = 5000.;
3922 if (latencyMs >= minLatency && latencyMs <= maxLatency) {
Dean Wheatley56a583e2020-05-08 15:12:17 +10003923 ALOGVV("new downstream latency %lf ms", latencyMs);
Andy Hung2dbffc22018-08-08 18:50:41 -07003924 } else {
3925 ALOGD("out of range downstream latency %lf ms", latencyMs);
Andy Hung71ba4b32022-10-06 12:09:49 -07003926 latencyMs = std::clamp(latencyMs, minLatency, maxLatency);
Andy Hung2dbffc22018-08-08 18:50:41 -07003927 }
Dean Wheatley30d28422018-11-06 10:27:40 +11003928 mDownstreamLatencyStatMs.add(latencyMs);
Andy Hung2dbffc22018-08-08 18:50:41 -07003929 }
Andy Hung2cbc2722023-07-17 17:05:00 -07003930 mAfThreadCallback->mutex().unlock();
Andy Hung2dbffc22018-08-08 18:50:41 -07003931 }
3932 } else {
3933 if (lastDownstreamPatchHandle != AUDIO_PATCH_HANDLE_NONE) {
3934 // our device is no longer AUDIO_DEVICE_OUT_BUS, reset patch handle and stats.
Dean Wheatley30d28422018-11-06 10:27:40 +11003935 mDownstreamLatencyStatMs.reset();
Andy Hung2dbffc22018-08-08 18:50:41 -07003936 lastDownstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
3937 }
3938 }
3939
Eric Laurentb3f315a2021-07-13 15:09:05 +02003940 if (mCheckOutputStageEffects.exchange(false)) {
3941 checkOutputStageEffects();
3942 }
3943
Vlad Popa7e81cea2023-01-19 16:34:16 +01003944 MetadataUpdate metadataUpdate;
Eric Laurent81784c32012-11-19 14:55:58 -08003945 { // scope for mLock
3946
3947 Mutex::Autolock _l(mLock);
3948
Eric Laurent021cf962014-05-13 10:18:14 -07003949 processConfigEvents_l();
Eric Laurentb3f315a2021-07-13 15:09:05 +02003950 if (mCheckOutputStageEffects.load()) {
3951 continue;
3952 }
Eric Laurent10351942014-05-08 18:49:52 -07003953
Glenn Kasteneef598c2017-04-03 14:41:13 -07003954 // See comment at declaration of logString for why this is done under mLock
Glenn Kasten9e58b552013-01-18 15:09:48 -08003955 if (logString != NULL) {
3956 mNBLogWriter->logTimestamp();
3957 mNBLogWriter->log(logString);
3958 logString = NULL;
3959 }
3960
Dean Wheatley12473e92021-03-18 23:00:55 +11003961 collectTimestamps_l();
Andy Hungc8fddf32018-08-08 18:32:37 -07003962
Eric Laurent81784c32012-11-19 14:55:58 -08003963 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003964 if (mSignalPending) {
3965 // A signal was raised while we were unlocked
3966 mSignalPending = false;
3967 } else if (waitingAsyncCallback_l()) {
3968 if (exitPending()) {
3969 break;
3970 }
Marco Nelissen078538c2015-05-12 09:17:57 -07003971 bool released = false;
Eric Laurent64667972016-03-30 18:19:46 -07003972 if (!keepWakeLock()) {
Marco Nelissen078538c2015-05-12 09:17:57 -07003973 releaseWakeLock_l();
3974 released = true;
3975 }
Andy Hung10cbff12017-02-21 17:30:14 -08003976
3977 const int64_t waitNs = computeWaitTimeNs_l();
3978 ALOGV("wait async completion (wait time: %lld)", (long long)waitNs);
3979 status_t status = mWaitWorkCV.waitRelative(mLock, waitNs);
3980 if (status == TIMED_OUT) {
3981 mSignalPending = true; // if timeout recheck everything
3982 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003983 ALOGV("async completion/wake");
Marco Nelissen078538c2015-05-12 09:17:57 -07003984 if (released) {
3985 acquireWakeLock_l();
3986 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003987 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3988 mSleepTimeUs = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07003989
3990 continue;
3991 }
Eric Tan39ec8d62018-07-24 09:49:29 -07003992 if ((mActiveTracks.isEmpty() && systemTime() > mStandbyTimeNs) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08003993 isSuspended()) {
3994 // put audio hardware into standby after short delay
3995 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003996
3997 threadLoop_standby();
3998
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07003999 // This is where we go into standby
4000 if (!mStandby) {
4001 LOG_AUDIO_STATE();
Andy Hungcf10d742020-04-28 15:38:24 -07004002 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07004003 mThreadSnapshot.onEnd();
Eric Laurent19952e12023-04-20 10:08:29 +02004004 setStandby_l();
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07004005 }
Andy Hungd0979812019-02-21 15:51:44 -08004006 sendStatistics(false /* force */);
Eric Laurent81784c32012-11-19 14:55:58 -08004007 }
4008
Eric Tan39ec8d62018-07-24 09:49:29 -07004009 if (mActiveTracks.isEmpty() && mConfigEvents.isEmpty()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004010 // we're about to wait, flush the binder command buffer
4011 IPCThreadState::self()->flushCommands();
4012
4013 clearOutputTracks();
4014
4015 if (exitPending()) {
4016 break;
4017 }
4018
4019 releaseWakeLock_l();
4020 // wait until we have something to do...
Tomasz Wasilczyk8f36f6e2023-08-15 20:59:35 +00004021 ALOGV("%s going to sleep", myName.c_str());
Eric Laurent81784c32012-11-19 14:55:58 -08004022 mWaitWorkCV.wait(mLock);
Tomasz Wasilczyk8f36f6e2023-08-15 20:59:35 +00004023 ALOGV("%s waking up", myName.c_str());
Eric Laurent81784c32012-11-19 14:55:58 -08004024 acquireWakeLock_l();
4025
4026 mMixerStatus = MIXER_IDLE;
4027 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
4028 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004029 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08004030 checkSilentMode_l();
4031
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004032 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
4033 mSleepTimeUs = mIdleSleepTimeUs;
Andy Hungd3639922022-04-28 18:00:49 -07004034 if (mType == MIXER || mType == SPATIALIZER) {
Eric Laurent81784c32012-11-19 14:55:58 -08004035 sleepTimeShift = 0;
4036 }
4037
4038 continue;
4039 }
4040 }
Eric Laurent81784c32012-11-19 14:55:58 -08004041 // mMixerStatusIgnoringFastTracks is also updated internally
4042 mMixerStatus = prepareTracks_l(&tracksToRemove);
4043
Andy Hungdae27702016-10-31 14:01:16 -07004044 mActiveTracks.updatePowerState(this);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08004045
Vlad Popa7e81cea2023-01-19 16:34:16 +01004046 metadataUpdate = updateMetadata_l();
Kevin Rocard069c2712018-03-29 19:09:14 -07004047
Eric Laurent81784c32012-11-19 14:55:58 -08004048 // prevent any changes in effect chain list and in each effect chain
4049 // during mixing and effect process as the audio buffers could be deleted
4050 // or modified if an effect is created or deleted
4051 lockEffectChains_l(effectChains);
Andy Hung6e6a2e62019-04-30 16:38:41 -07004052
4053 // Determine which session to pick up haptic data.
4054 // This must be done under the same lock as prepareTracks_l().
jiabineb3bda02020-06-30 14:07:03 -07004055 // The haptic data from the effect is at a higher priority than the one from track.
Andy Hung6e6a2e62019-04-30 16:38:41 -07004056 // TODO: Write haptic data directly to sink buffer when mixing.
Eric Laurentb62d0362021-10-26 17:40:18 +02004057 if (mHapticChannelCount > 0) {
Andy Hung6e6a2e62019-04-30 16:38:41 -07004058 for (const auto& track : mActiveTracks) {
Andy Hungbd72c542023-06-20 18:56:17 -07004059 sp<IAfEffectChain> effectChain = getEffectChain_l(track->sessionId());
Eric Laurentb62d0362021-10-26 17:40:18 +02004060 if (effectChain != nullptr
4061 && effectChain->containsHapticGeneratingEffect_l()) {
jiabineb3bda02020-06-30 14:07:03 -07004062 activeHapticSessionId = track->sessionId();
Eric Laurentb62d0362021-10-26 17:40:18 +02004063 isHapticSessionSpatialized =
Eric Laurentb0a7bc92022-04-05 15:06:08 +02004064 mType == SPATIALIZER && track->isSpatialized();
jiabineb3bda02020-06-30 14:07:03 -07004065 break;
4066 }
Eric Laurentb62d0362021-10-26 17:40:18 +02004067 if (activeHapticSessionId == AUDIO_SESSION_NONE
4068 && track->getHapticPlaybackEnabled()) {
Andy Hung6e6a2e62019-04-30 16:38:41 -07004069 activeHapticSessionId = track->sessionId();
Eric Laurentb62d0362021-10-26 17:40:18 +02004070 isHapticSessionSpatialized =
Eric Laurentb0a7bc92022-04-05 15:06:08 +02004071 mType == SPATIALIZER && track->isSpatialized();
Andy Hung6e6a2e62019-04-30 16:38:41 -07004072 }
4073 }
4074 }
4075
Andy Hungc1646382019-04-30 16:12:10 -07004076 // Acquire a local copy of active tracks with lock (release w/o lock).
4077 //
4078 // Control methods on the track acquire the ThreadBase lock (e.g. start()
4079 // stop(), pause(), etc.), but the threadLoop is entitled to call audio
4080 // data / buffer methods on tracks from activeTracks without the ThreadBase lock.
4081 activeTracks.insert(activeTracks.end(), mActiveTracks.begin(), mActiveTracks.end());
Eric Laurent6f9534f2022-05-03 18:15:04 +02004082
4083 setHalLatencyMode_l();
Eric Laurent19952e12023-04-20 10:08:29 +02004084
Jiabin Huangfb476842022-12-06 03:18:10 +00004085 for (const auto &track : mActiveTracks ) {
4086 track->updateTeePatches();
4087 }
4088
Eric Laurent19952e12023-04-20 10:08:29 +02004089 // signal actual start of output stream when the render position reported by the kernel
4090 // starts moving.
Eric Laurent4edbd8c2023-05-22 17:00:24 +02004091 if (!mHalStarted && ((isSuspended() && (mBytesWritten != 0)) || (!mStandby
4092 && (mKernelPositionOnStandby
4093 != mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL])))) {
Eric Laurent19952e12023-04-20 10:08:29 +02004094 mHalStarted = true;
4095 mWaitHalStartCV.broadcast();
4096 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -08004097 } // mLock scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08004098
Eric Laurentbfb1b832013-01-07 09:53:42 -08004099 if (mBytesRemaining == 0) {
4100 mCurrentWriteLength = 0;
4101 if (mMixerStatus == MIXER_TRACKS_READY) {
4102 // threadLoop_mix() sets mCurrentWriteLength
4103 threadLoop_mix();
4104 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
4105 && (mMixerStatus != MIXER_DRAIN_ALL)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004106 // threadLoop_sleepTime sets mSleepTimeUs to 0 if data
Eric Laurentbfb1b832013-01-07 09:53:42 -08004107 // must be written to HAL
4108 threadLoop_sleepTime();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004109 if (mSleepTimeUs == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08004110 mCurrentWriteLength = mSinkBufferSize;
Andy Hungc1646382019-04-30 16:12:10 -07004111
4112 // Tally underrun frames as we are inserting 0s here.
4113 for (const auto& track : activeTracks) {
Andy Hung3ff4b552023-06-26 19:20:57 -07004114 if (track->fillingStatus() == IAfTrack::FS_ACTIVE
Andy Hunge2e830f2019-12-03 12:54:46 -08004115 && !track->isStopped()
4116 && !track->isPaused()
4117 && !track->isTerminated()) {
4118 ALOGV("%s: track(%d) %s underrun due to thread sleep of %zu frames",
4119 __func__, track->id(), track->getTrackStateAsString(),
4120 mNormalFrameCount);
Andy Hung3ff4b552023-06-26 19:20:57 -07004121 track->audioTrackServerProxy()->tallyUnderrunFrames(
4122 mNormalFrameCount);
Andy Hungc1646382019-04-30 16:12:10 -07004123 }
4124 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004125 }
4126 }
Andy Hung98ef9782014-03-04 14:46:50 -08004127 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004128 // mMixerBuffer with data if mMixerBufferValid is true and mSleepTimeUs == 0.
Andy Hung98ef9782014-03-04 14:46:50 -08004129 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
jiabinc658e452022-10-21 20:52:21 +00004130 // or mSinkBuffer (if there are no effects and there is no data already copied to
4131 // mSinkBuffer).
Andy Hung98ef9782014-03-04 14:46:50 -08004132 //
4133 // This is done pre-effects computation; if effects change to
4134 // support higher precision, this needs to move.
4135 //
4136 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004137 // TODO use mSleepTimeUs == 0 as an additional condition.
Eric Laurent39095982021-08-24 18:29:27 +02004138 uint32_t mixerChannelCount = mEffectBufferValid ?
4139 audio_channel_count_from_out_mask(mMixerChannelMask) : mChannelCount;
jiabinc658e452022-10-21 20:52:21 +00004140 if (mMixerBufferValid && (mEffectBufferValid || !mHasDataCopiedToSinkBuffer)) {
Andy Hung98ef9782014-03-04 14:46:50 -08004141 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
4142 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
4143
David Li88ee0902022-06-22 10:01:21 +08004144 // Apply mono blending and balancing if the effect buffer is not valid. Otherwise,
4145 // do these processes after effects are applied.
4146 if (!mEffectBufferValid) {
4147 // mono blend occurs for mixer threads only (not direct or offloaded)
4148 // and is handled here if we're going directly to the sink.
4149 if (requireMonoBlend()) {
4150 mono_blend(mMixerBuffer, mMixerBufferFormat, mChannelCount,
4151 mNormalFrameCount, true /*limit*/);
4152 }
Andy Hung2ddee192015-12-18 17:34:44 -08004153
David Li88ee0902022-06-22 10:01:21 +08004154 if (!hasFastMixer()) {
4155 // Balance must take effect after mono conversion.
4156 // We do it here if there is no FastMixer.
4157 // mBalance detects zero balance within the class for speed
4158 // (not needed here).
4159 mBalance.setBalance(mMasterBalance.load());
4160 mBalance.process((float *)mMixerBuffer, mNormalFrameCount);
4161 }
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01004162 }
4163
Andy Hung98ef9782014-03-04 14:46:50 -08004164 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
Eric Laurent39095982021-08-24 18:29:27 +02004165 mNormalFrameCount * (mixerChannelCount + mHapticChannelCount));
jiabin245cdd92018-12-07 17:55:15 -08004166
4167 // If we're going directly to the sink and there are haptic channels,
4168 // we should adjust channels as the sample data is partially interleaved
4169 // in this case.
4170 if (!mEffectBufferValid && mHapticChannelCount > 0) {
4171 adjust_channels_non_destructive(buffer, mChannelCount, buffer,
4172 mChannelCount + mHapticChannelCount,
4173 audio_bytes_per_sample(format),
4174 audio_bytes_per_frame(mChannelCount, format) * mNormalFrameCount);
4175 }
Andy Hung98ef9782014-03-04 14:46:50 -08004176 }
4177
Eric Laurentbfb1b832013-01-07 09:53:42 -08004178 mBytesRemaining = mCurrentWriteLength;
4179 if (isSuspended()) {
Andy Hung238fa3d2016-07-28 10:53:22 -07004180 // Simulate write to HAL when suspended (e.g. BT SCO phone call).
4181 mSleepTimeUs = suspendSleepTimeUs(); // assumes full buffer.
4182 const size_t framesRemaining = mBytesRemaining / mFrameSize;
4183 mBytesWritten += mBytesRemaining;
4184 mFramesWritten += framesRemaining;
4185 mSuspendedFrames += framesRemaining; // to adjust kernel HAL position
Eric Laurentbfb1b832013-01-07 09:53:42 -08004186 mBytesRemaining = 0;
4187 }
Eric Laurent81784c32012-11-19 14:55:58 -08004188
Eric Laurentbfb1b832013-01-07 09:53:42 -08004189 // only process effects if we're going to write
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004190 if (mSleepTimeUs == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004191 for (size_t i = 0; i < effectChains.size(); i ++) {
4192 effectChains[i]->process_l();
jiabin47affe52019-04-04 18:02:07 -07004193 // TODO: Write haptic data directly to sink buffer when mixing.
Andy Hung6e6a2e62019-04-30 16:38:41 -07004194 if (activeHapticSessionId != AUDIO_SESSION_NONE
4195 && activeHapticSessionId == effectChains[i]->sessionId()) {
jiabin47affe52019-04-04 18:02:07 -07004196 // Haptic data is active in this case, copy it directly from
4197 // in buffer to out buffer.
Eric Laurentb62d0362021-10-26 17:40:18 +02004198 uint32_t hapticSessionChannelCount = mEffectBufferValid ?
4199 audio_channel_count_from_out_mask(mMixerChannelMask) :
4200 mChannelCount;
4201 if (mType == SPATIALIZER && !isHapticSessionSpatialized) {
4202 hapticSessionChannelCount = mChannelCount;
4203 }
4204
jiabin47affe52019-04-04 18:02:07 -07004205 const size_t audioBufferSize = mNormalFrameCount
Eric Laurentb62d0362021-10-26 17:40:18 +02004206 * audio_bytes_per_frame(hapticSessionChannelCount,
Andy Hung319587b2023-05-23 14:01:03 -07004207 AUDIO_FORMAT_PCM_FLOAT);
jiabin47affe52019-04-04 18:02:07 -07004208 memcpy_by_audio_format(
4209 (uint8_t*)effectChains[i]->outBuffer() + audioBufferSize,
Andy Hung319587b2023-05-23 14:01:03 -07004210 AUDIO_FORMAT_PCM_FLOAT,
jiabin47affe52019-04-04 18:02:07 -07004211 (const uint8_t*)effectChains[i]->inBuffer() + audioBufferSize,
Andy Hung319587b2023-05-23 14:01:03 -07004212 AUDIO_FORMAT_PCM_FLOAT, mNormalFrameCount * mHapticChannelCount);
jiabin47affe52019-04-04 18:02:07 -07004213 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004214 }
Eric Laurent81784c32012-11-19 14:55:58 -08004215 }
4216 }
Eric Laurent59fe0102013-09-27 18:48:26 -07004217 // Process effect chains for offloaded thread even if no audio
4218 // was read from audio track: process only updates effect state
4219 // and thus does have to be synchronized with audio writes but may have
4220 // to be called while waiting for async write callback
4221 if (mType == OFFLOAD) {
4222 for (size_t i = 0; i < effectChains.size(); i ++) {
4223 effectChains[i]->process_l();
4224 }
4225 }
Eric Laurent81784c32012-11-19 14:55:58 -08004226
Andy Hung98ef9782014-03-04 14:46:50 -08004227 // Only if the Effects buffer is enabled and there is data in the
4228 // Effects buffer (buffer valid), we need to
4229 // copy into the sink buffer.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004230 // TODO use mSleepTimeUs == 0 as an additional condition.
jiabinc658e452022-10-21 20:52:21 +00004231 if (mEffectBufferValid && !mHasDataCopiedToSinkBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08004232 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
Eric Laurentb62d0362021-10-26 17:40:18 +02004233 void *effectBuffer = (mType == SPATIALIZER) ? mPostSpatializerBuffer : mEffectBuffer;
Andy Hung2ddee192015-12-18 17:34:44 -08004234 if (requireMonoBlend()) {
Eric Laurentb62d0362021-10-26 17:40:18 +02004235 mono_blend(effectBuffer, mEffectBufferFormat, mChannelCount, mNormalFrameCount,
Glenn Kasten03c48d52016-01-27 17:25:17 -08004236 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08004237 }
4238
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01004239 if (!hasFastMixer()) {
4240 // Balance must take effect after mono conversion.
4241 // We do it here if there is no FastMixer.
4242 // mBalance detects zero balance within the class for speed (not needed here).
4243 mBalance.setBalance(mMasterBalance.load());
Eric Laurentb62d0362021-10-26 17:40:18 +02004244 mBalance.process((float *)effectBuffer, mNormalFrameCount);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01004245 }
4246
Eric Laurentb62d0362021-10-26 17:40:18 +02004247 // for SPATIALIZER thread, Move haptics channels from mEffectBuffer to
4248 // mPostSpatializerBuffer if the haptics track is spatialized.
4249 // Otherwise, the haptics channels are already in mPostSpatializerBuffer.
4250 // For other thread types, the haptics channels are already in mEffectBuffer.
4251 if (mType == SPATIALIZER && isHapticSessionSpatialized) {
4252 const size_t srcBufferSize = mNormalFrameCount *
4253 audio_bytes_per_frame(audio_channel_count_from_out_mask(mMixerChannelMask),
4254 mEffectBufferFormat);
4255 const size_t dstBufferSize = mNormalFrameCount
4256 * audio_bytes_per_frame(mChannelCount, mEffectBufferFormat);
4257
4258 memcpy_by_audio_format((uint8_t*)mPostSpatializerBuffer + dstBufferSize,
4259 mEffectBufferFormat,
4260 (uint8_t*)mEffectBuffer + srcBufferSize,
4261 mEffectBufferFormat,
4262 mNormalFrameCount * mHapticChannelCount);
Eric Laurent39095982021-08-24 18:29:27 +02004263 }
Atneya Nair68436cf2022-09-19 17:51:37 -07004264 const size_t framesToCopy = mNormalFrameCount * (mChannelCount + mHapticChannelCount);
4265 if (mFormat == AUDIO_FORMAT_PCM_FLOAT &&
4266 mEffectBufferFormat == AUDIO_FORMAT_PCM_FLOAT) {
4267 // Clamp PCM float values more than this distance from 0 to insulate
4268 // a HAL which doesn't handle NaN correctly.
4269 static constexpr float HAL_FLOAT_SAMPLE_LIMIT = 2.0f;
4270 memcpy_to_float_from_float_with_clamping(static_cast<float*>(mSinkBuffer),
4271 static_cast<const float*>(effectBuffer),
4272 framesToCopy, HAL_FLOAT_SAMPLE_LIMIT /* absMax */);
4273 } else {
4274 memcpy_by_audio_format(mSinkBuffer, mFormat,
4275 effectBuffer, mEffectBufferFormat, framesToCopy);
4276 }
jiabin245cdd92018-12-07 17:55:15 -08004277 // The sample data is partially interleaved when haptic channels exist,
4278 // we need to adjust channels here.
4279 if (mHapticChannelCount > 0) {
4280 adjust_channels_non_destructive(mSinkBuffer, mChannelCount, mSinkBuffer,
4281 mChannelCount + mHapticChannelCount,
4282 audio_bytes_per_sample(mFormat),
4283 audio_bytes_per_frame(mChannelCount, mFormat) * mNormalFrameCount);
4284 }
Andy Hung98ef9782014-03-04 14:46:50 -08004285 }
4286
Eric Laurent81784c32012-11-19 14:55:58 -08004287 // enable changes in effect chain
4288 unlockEffectChains(effectChains);
4289
Vlad Popafce10862023-02-03 10:37:07 +01004290 if (!metadataUpdate.playbackMetadataUpdate.empty()) {
Andy Hung2cbc2722023-07-17 17:05:00 -07004291 mAfThreadCallback->getMelReporter()->updateMetadataForCsd(id(),
Vlad Popafce10862023-02-03 10:37:07 +01004292 metadataUpdate.playbackMetadataUpdate);
4293 }
4294
Eric Laurentbfb1b832013-01-07 09:53:42 -08004295 if (!waitingAsyncCallback()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004296 // mSleepTimeUs == 0 means we must write to audio hardware
4297 if (mSleepTimeUs == 0) {
Andy Hung08fb1742015-05-31 23:22:10 -07004298 ssize_t ret = 0;
Andy Hung446f4df2019-02-21 12:26:41 -08004299 // writePeriodNs is updated >= 0 when ret > 0.
4300 int64_t writePeriodNs = -1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004301 if (mBytesRemaining) {
Andy Hung69488c42016-05-16 18:43:33 -07004302 // FIXME rewrite to reduce number of system calls
Andy Hung446f4df2019-02-21 12:26:41 -08004303 const int64_t lastIoBeginNs = systemTime();
Andy Hung08fb1742015-05-31 23:22:10 -07004304 ret = threadLoop_write();
Andy Hung446f4df2019-02-21 12:26:41 -08004305 const int64_t lastIoEndNs = systemTime();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004306 if (ret < 0) {
4307 mBytesRemaining = 0;
Andy Hung446f4df2019-02-21 12:26:41 -08004308 } else if (ret > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004309 mBytesWritten += ret;
4310 mBytesRemaining -= ret;
Andy Hung446f4df2019-02-21 12:26:41 -08004311 const int64_t frames = ret / mFrameSize;
4312 mFramesWritten += frames;
4313
4314 writePeriodNs = lastIoEndNs - mLastIoEndNs;
4315 // process information relating to write time.
4316 if (audio_has_proportional_frames(mFormat)) {
4317 // we are in a continuous mixing cycle
4318 if (mMixerStatus == MIXER_TRACKS_READY &&
4319 loopCount == lastLoopCountWritten + 1) {
4320
4321 const double jitterMs =
4322 TimestampVerifier<int64_t, int64_t>::computeJitterMs(
4323 {frames, writePeriodNs},
4324 {0, 0} /* lastTimestamp */, mSampleRate);
4325 const double processMs =
4326 (lastIoBeginNs - mLastIoEndNs) * 1e-6;
4327
4328 Mutex::Autolock _l(mLock);
4329 mIoJitterMs.add(jitterMs);
4330 mProcessTimeMs.add(processMs);
Robert Wu06db0a32021-08-10 19:05:34 +00004331
4332 if (mPipeSink.get() != nullptr) {
4333 // Using the Monopipe availableToWrite, we estimate the current
4334 // buffer size.
4335 MonoPipe* monoPipe = static_cast<MonoPipe*>(mPipeSink.get());
4336 const ssize_t
4337 availableToWrite = mPipeSink->availableToWrite();
4338 const size_t pipeFrames = monoPipe->maxFrames();
4339 const size_t
4340 remainingFrames = pipeFrames - max(availableToWrite, 0);
4341 mMonopipePipeDepthStats.add(remainingFrames);
4342 }
Andy Hung446f4df2019-02-21 12:26:41 -08004343 }
4344
4345 // write blocked detection
4346 const int64_t deltaWriteNs = lastIoEndNs - lastIoBeginNs;
Andy Hungd3639922022-04-28 18:00:49 -07004347 if ((mType == MIXER || mType == SPATIALIZER)
4348 && deltaWriteNs > maxPeriod) {
Andy Hung446f4df2019-02-21 12:26:41 -08004349 mNumDelayedWrites++;
4350 if ((lastIoEndNs - lastWarning) > kWarningThrottleNs) {
4351 ATRACE_NAME("underrun");
4352 ALOGW("write blocked for %lld msecs, "
4353 "%d delayed writes, thread %d",
4354 (long long)deltaWriteNs / NANOS_PER_MILLISECOND,
4355 mNumDelayedWrites, mId);
4356 lastWarning = lastIoEndNs;
4357 }
4358 }
4359 }
4360 // update timing info.
4361 mLastIoBeginNs = lastIoBeginNs;
4362 mLastIoEndNs = lastIoEndNs;
4363 lastLoopCountWritten = loopCount;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004364 }
4365 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
4366 (mMixerStatus == MIXER_DRAIN_ALL)) {
4367 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08004368 }
Andy Hungd3639922022-04-28 18:00:49 -07004369 if ((mType == MIXER || mType == SPATIALIZER) && !mStandby) {
Andy Hung08fb1742015-05-31 23:22:10 -07004370
4371 if (mThreadThrottle
4372 && mMixerStatus == MIXER_TRACKS_READY // we are mixing (active tracks)
Andy Hung446f4df2019-02-21 12:26:41 -08004373 && writePeriodNs > 0) { // we have write period info
Andy Hung08fb1742015-05-31 23:22:10 -07004374 // Limit MixerThread data processing to no more than twice the
4375 // expected processing rate.
4376 //
4377 // This helps prevent underruns with NuPlayer and other applications
4378 // which may set up buffers that are close to the minimum size, or use
4379 // deep buffers, and rely on a double-buffering sleep strategy to fill.
4380 //
4381 // The throttle smooths out sudden large data drains from the device,
4382 // e.g. when it comes out of standby, which often causes problems with
4383 // (1) mixer threads without a fast mixer (which has its own warm-up)
4384 // (2) minimum buffer sized tracks (even if the track is full,
4385 // the app won't fill fast enough to handle the sudden draw).
Haynes Mathew Georgef92b2172016-05-09 11:34:15 -07004386 //
4387 // Total time spent in last processing cycle equals time spent in
4388 // 1. threadLoop_write, as well as time spent in
4389 // 2. threadLoop_mix (significant for heavy mixing, especially
4390 // on low tier processors)
Andy Hung08fb1742015-05-31 23:22:10 -07004391
Andy Hung446f4df2019-02-21 12:26:41 -08004392 // it's OK if deltaMs is an overestimate.
4393
4394 const int32_t deltaMs = writePeriodNs / NANOS_PER_MILLISECOND;
Ivan Lozanoe02bc542017-10-26 09:51:54 -07004395
Ivan Lozanoea04d392017-11-07 14:37:07 -08004396 const int32_t throttleMs = (int32_t)mHalfBufferMs - deltaMs;
Andy Hung08fb1742015-05-31 23:22:10 -07004397 if ((signed)mHalfBufferMs >= throttleMs && throttleMs > 0) {
Andy Hungcf10d742020-04-28 15:38:24 -07004398 mThreadMetrics.logThrottleMs((double)throttleMs);
Andy Hungb68f5eb2019-12-03 16:49:17 -08004399
Andy Hung08fb1742015-05-31 23:22:10 -07004400 usleep(throttleMs * 1000);
Andy Hung40eb1a12015-06-18 13:42:02 -07004401 // notify of throttle start on verbose log
4402 ALOGV_IF(mThreadThrottleEndMs == mThreadThrottleTimeMs,
4403 "mixer(%p) throttle begin:"
4404 " ret(%zd) deltaMs(%d) requires sleep %d ms",
Andy Hung08fb1742015-05-31 23:22:10 -07004405 this, ret, deltaMs, throttleMs);
Andy Hung40eb1a12015-06-18 13:42:02 -07004406 mThreadThrottleTimeMs += throttleMs;
Andy Hung0a31ddd2016-07-06 19:10:29 -07004407 // Throttle must be attributed to the previous mixer loop's write time
4408 // to allow back-to-back throttling.
Andy Hung446f4df2019-02-21 12:26:41 -08004409 // This also ensures proper timing statistics.
4410 mLastIoEndNs = systemTime(); // we fetch the write end time again.
Andy Hung40eb1a12015-06-18 13:42:02 -07004411 } else {
4412 uint32_t diff = mThreadThrottleTimeMs - mThreadThrottleEndMs;
4413 if (diff > 0) {
4414 // notify of throttle end on debug log
Andy Hung3ea004d2016-05-05 16:48:37 -07004415 // but prevent spamming for bluetooth
jiabinc52b1ff2019-10-31 17:20:42 -07004416 ALOGD_IF(!isSingleDeviceType(
4417 outDeviceTypes(), audio_is_a2dp_out_device) &&
4418 !isSingleDeviceType(
4419 outDeviceTypes(), audio_is_hearing_aid_out_device),
Andy Hung3ea004d2016-05-05 16:48:37 -07004420 "mixer(%p) throttle end: throttle time(%u)", this, diff);
Andy Hung40eb1a12015-06-18 13:42:02 -07004421 mThreadThrottleEndMs = mThreadThrottleTimeMs;
4422 }
Andy Hung08fb1742015-05-31 23:22:10 -07004423 }
4424 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004425 }
Eric Laurent81784c32012-11-19 14:55:58 -08004426
Eric Laurentbfb1b832013-01-07 09:53:42 -08004427 } else {
Glenn Kastene7754022014-10-31 12:11:26 -07004428 ATRACE_BEGIN("sleep");
Eric Laurente93cc032016-05-05 10:15:10 -07004429 Mutex::Autolock _l(mLock);
rago1bb90822017-05-02 18:31:48 -07004430 // suspended requires accurate metering of sleep time.
4431 if (isSuspended()) {
4432 // advance by expected sleepTime
4433 timeLoopNextNs += microseconds((nsecs_t)mSleepTimeUs);
4434 const nsecs_t nowNs = systemTime();
4435
4436 // compute expected next time vs current time.
4437 // (negative deltas are treated as delays).
4438 nsecs_t deltaNs = timeLoopNextNs - nowNs;
4439 if (deltaNs < -kMaxNextBufferDelayNs) {
4440 // Delays longer than the max allowed trigger a reset.
4441 ALOGV("DelayNs: %lld, resetting timeLoopNextNs", (long long) deltaNs);
4442 deltaNs = microseconds((nsecs_t)mSleepTimeUs);
4443 timeLoopNextNs = nowNs + deltaNs;
4444 } else if (deltaNs < 0) {
4445 // Delays within the max delay allowed: zero the delta/sleepTime
4446 // to help the system catch up in the next iteration(s)
4447 ALOGV("DelayNs: %lld, catching-up", (long long) deltaNs);
4448 deltaNs = 0;
4449 }
4450 // update sleep time (which is >= 0)
4451 mSleepTimeUs = deltaNs / 1000;
4452 }
Eric Laurente93cc032016-05-05 10:15:10 -07004453 if (!mSignalPending && mConfigEvents.isEmpty() && !exitPending()) {
4454 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)mSleepTimeUs));
Eric Laurent51716182016-02-29 18:00:56 -08004455 }
Glenn Kastene7754022014-10-31 12:11:26 -07004456 ATRACE_END();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004457 }
Eric Laurent81784c32012-11-19 14:55:58 -08004458 }
4459
4460 // Finally let go of removed track(s), without the lock held
4461 // since we can't guarantee the destructors won't acquire that
4462 // same lock. This will also mutate and push a new fast mixer state.
4463 threadLoop_removeTracks(tracksToRemove);
4464 tracksToRemove.clear();
4465
4466 // FIXME I don't understand the need for this here;
4467 // it was in the original code but maybe the
4468 // assignment in saveOutputTracks() makes this unnecessary?
4469 clearOutputTracks();
4470
4471 // Effect chains will be actually deleted here if they were removed from
4472 // mEffectChains list during mixing or effects processing
4473 effectChains.clear();
4474
4475 // FIXME Note that the above .clear() is no longer necessary since effectChains
4476 // is now local to this block, but will keep it for now (at least until merge done).
4477 }
4478
Eric Laurentbfb1b832013-01-07 09:53:42 -08004479 threadLoop_exit();
4480
Eric Laurentcf817a22014-08-04 20:36:31 -07004481 if (!mStandby) {
4482 threadLoop_standby();
Eric Laurent19952e12023-04-20 10:08:29 +02004483 setStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08004484 }
4485
4486 releaseWakeLock();
4487
4488 ALOGV("Thread %p type %d exiting", this, mType);
4489 return false;
4490}
4491
Andy Hung71742ab2023-07-07 13:47:37 -07004492void PlaybackThread::collectTimestamps_l()
Dean Wheatley12473e92021-03-18 23:00:55 +11004493{
Dean Wheatley12473e92021-03-18 23:00:55 +11004494 if (mStandby) {
4495 mTimestampVerifier.discontinuity(discontinuityForStandbyOrFlush());
4496 return;
4497 } else if (mHwPaused) {
4498 mTimestampVerifier.discontinuity(mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS);
4499 return;
4500 }
4501
4502 // Gather the framesReleased counters for all active tracks,
4503 // and associate with the sink frames written out. We need
4504 // this to convert the sink timestamp to the track timestamp.
4505 bool kernelLocationUpdate = false;
4506 ExtendedTimestamp timestamp; // use private copy to fetch
4507
4508 // Always query HAL timestamp and update timestamp verifier. In standby or pause,
4509 // HAL may be draining some small duration buffered data for fade out.
4510 if (threadloop_getHalTimestamp_l(&timestamp) == OK) {
4511 mTimestampVerifier.add(timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL],
4512 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4513 mSampleRate);
4514
4515 if (isTimestampCorrectionEnabled()) {
4516 ALOGVV("TS_BEFORE: %d %lld %lld", id(),
4517 (long long)timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4518 (long long)timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]);
4519 auto correctedTimestamp = mTimestampVerifier.getLastCorrectedTimestamp();
4520 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4521 = correctedTimestamp.mFrames;
4522 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]
4523 = correctedTimestamp.mTimeNs;
4524 ALOGVV("TS_AFTER: %d %lld %lld", id(),
4525 (long long)timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4526 (long long)timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]);
4527
4528 // Note: Downstream latency only added if timestamp correction enabled.
4529 if (mDownstreamLatencyStatMs.getN() > 0) { // we have latency info.
4530 const int64_t newPosition =
4531 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4532 - int64_t(mDownstreamLatencyStatMs.getMean() * mSampleRate * 1e-3);
4533 // prevent retrograde
4534 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = max(
4535 newPosition,
4536 (mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4537 - mSuspendedFrames));
4538 }
4539 }
4540
4541 // We always fetch the timestamp here because often the downstream
4542 // sink will block while writing.
4543
4544 // We keep track of the last valid kernel position in case we are in underrun
4545 // and the normal mixer period is the same as the fast mixer period, or there
4546 // is some error from the HAL.
4547 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
4548 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
4549 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
4550 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
4551 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4552
4553 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
4554 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER];
4555 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
4556 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER];
4557 }
4558
4559 if (timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
4560 kernelLocationUpdate = true;
4561 } else {
4562 ALOGVV("getTimestamp error - no valid kernel position");
4563 }
4564
4565 // copy over kernel info
4566 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] =
4567 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4568 + mSuspendedFrames; // add frames discarded when suspended
4569 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] =
4570 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4571 } else {
4572 mTimestampVerifier.error();
4573 }
4574
4575 // mFramesWritten for non-offloaded tracks are contiguous
4576 // even after standby() is called. This is useful for the track frame
4577 // to sink frame mapping.
4578 bool serverLocationUpdate = false;
4579 if (mFramesWritten != mLastFramesWritten) {
4580 serverLocationUpdate = true;
4581 mLastFramesWritten = mFramesWritten;
4582 }
4583 // Only update timestamps if there is a meaningful change.
4584 // Either the kernel timestamp must be valid or we have written something.
4585 if (kernelLocationUpdate || serverLocationUpdate) {
4586 if (serverLocationUpdate) {
4587 // use the time before we called the HAL write - it is a bit more accurate
4588 // to when the server last read data than the current time here.
4589 //
4590 // If we haven't written anything, mLastIoBeginNs will be -1
4591 // and we use systemTime().
4592 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] = mFramesWritten;
4593 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = mLastIoBeginNs == -1
4594 ? systemTime() : mLastIoBeginNs;
4595 }
4596
Andy Hung3ff4b552023-06-26 19:20:57 -07004597 for (const sp<IAfTrack>& t : mActiveTracks) {
Dean Wheatley12473e92021-03-18 23:00:55 +11004598 if (!t->isFastTrack()) {
4599 t->updateTrackFrameInfo(
Andy Hung3ff4b552023-06-26 19:20:57 -07004600 t->audioTrackServerProxy()->framesReleased(),
Dean Wheatley12473e92021-03-18 23:00:55 +11004601 mFramesWritten,
4602 mSampleRate,
4603 mTimestamp);
4604 }
4605 }
4606 }
4607
4608 if (audio_has_proportional_frames(mFormat)) {
4609 const double latencyMs = mTimestamp.getOutputServerLatencyMs(mSampleRate);
4610 if (latencyMs != 0.) { // note 0. means timestamp is empty.
4611 mLatencyMs.add(latencyMs);
4612 }
4613 }
4614#if 0
4615 // logFormat example
4616 if (z % 100 == 0) {
4617 timespec ts;
4618 clock_gettime(CLOCK_MONOTONIC, &ts);
4619 LOGT("This is an integer %d, this is a float %f, this is my "
4620 "pid %p %% %s %t", 42, 3.14, "and this is a timestamp", ts);
4621 LOGT("A deceptive null-terminated string %\0");
4622 }
4623 ++z;
4624#endif
4625}
4626
Eric Laurentbfb1b832013-01-07 09:53:42 -08004627// removeTracks_l() must be called with ThreadBase::mLock held
Andy Hung71742ab2023-07-07 13:47:37 -07004628void PlaybackThread::removeTracks_l(const Vector<sp<IAfTrack>>& tracksToRemove)
Andy Hung71ba4b32022-10-06 12:09:49 -07004629NO_THREAD_SAFETY_ANALYSIS // release and re-acquire mLock
Eric Laurentbfb1b832013-01-07 09:53:42 -08004630{
Andy Hungfe726a62018-09-27 15:17:25 -07004631 for (const auto& track : tracksToRemove) {
4632 mActiveTracks.remove(track);
4633 ALOGV("%s(%d): removing track on session %d", __func__, track->id(), track->sessionId());
Andy Hungbd72c542023-06-20 18:56:17 -07004634 sp<IAfEffectChain> chain = getEffectChain_l(track->sessionId());
Andy Hungfe726a62018-09-27 15:17:25 -07004635 if (chain != 0) {
4636 ALOGV("%s(%d): stopping track on chain %p for session Id: %d",
4637 __func__, track->id(), chain.get(), track->sessionId());
4638 chain->decActiveTrackCnt();
4639 }
4640 // If an external client track, inform APM we're no longer active, and remove if needed.
4641 // We do this under lock so that the state is consistent if the Track is destroyed.
4642 if (track->isExternalTrack()) {
4643 AudioSystem::stopOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08004644 if (track->isTerminated()) {
Andy Hungfe726a62018-09-27 15:17:25 -07004645 AudioSystem::releaseOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08004646 }
4647 }
Andy Hungfe726a62018-09-27 15:17:25 -07004648 if (track->isTerminated()) {
4649 // remove from our tracks vector
4650 removeTrack_l(track);
4651 }
jiabineb3bda02020-06-30 14:07:03 -07004652 if (mHapticChannelCount > 0 &&
4653 ((track->channelMask() & AUDIO_CHANNEL_HAPTIC_ALL) != AUDIO_CHANNEL_NONE
4654 || (chain != nullptr && chain->containsHapticGeneratingEffect_l()))) {
jiabin57303cc2018-12-18 15:45:57 -08004655 mLock.unlock();
4656 // Unlock due to VibratorService will lock for this call and will
4657 // call Tracks.mute/unmute which also require thread's lock.
4658 AudioFlinger::onExternalVibrationStop(track->getExternalVibration());
4659 mLock.lock();
jiabine70bc7f2020-06-30 22:07:55 -07004660
4661 // When the track is stop, set the haptic intensity as MUTE
4662 // for the HapticGenerator effect.
4663 if (chain != nullptr) {
Simon Bowden62823412022-10-17 14:52:26 +00004664 chain->setHapticIntensity_l(track->id(), os::HapticScale::MUTE);
jiabine70bc7f2020-06-30 22:07:55 -07004665 }
jiabin245cdd92018-12-07 17:55:15 -08004666 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004667 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004668}
Eric Laurent81784c32012-11-19 14:55:58 -08004669
Andy Hung71742ab2023-07-07 13:47:37 -07004670status_t PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
Eric Laurentaccc1472013-09-20 09:36:34 -07004671{
4672 if (mNormalSink != 0) {
Andy Hung818e7a32016-02-16 18:08:07 -08004673 ExtendedTimestamp ets;
4674 status_t status = mNormalSink->getTimestamp(ets);
4675 if (status == NO_ERROR) {
4676 status = ets.getBestTimestamp(&timestamp);
4677 }
4678 return status;
Eric Laurentaccc1472013-09-20 09:36:34 -07004679 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004680 if ((mType == OFFLOAD || mType == DIRECT) && mOutput != NULL) {
Dean Wheatley12473e92021-03-18 23:00:55 +11004681 collectTimestamps_l();
4682 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] <= 0) {
4683 return INVALID_OPERATION;
Eric Laurentaccc1472013-09-20 09:36:34 -07004684 }
Dean Wheatley12473e92021-03-18 23:00:55 +11004685 timestamp.mPosition = mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
4686 const int64_t timeNs = mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4687 timestamp.mTime.tv_sec = timeNs / NANOS_PER_SECOND;
4688 timestamp.mTime.tv_nsec = timeNs - (timestamp.mTime.tv_sec * NANOS_PER_SECOND);
4689 return NO_ERROR;
Eric Laurentaccc1472013-09-20 09:36:34 -07004690 }
4691 return INVALID_OPERATION;
4692}
Eric Laurent1c333e22014-05-20 10:48:17 -07004693
Eric Laurenteab90452019-06-24 15:17:46 -07004694// For dedicated VoIP outputs, let the HAL apply the stream volume. Track volume is
4695// still applied by the mixer.
4696// All tracks attached to a mixer with flag VOIP_RX are tied to the same
4697// stream type STREAM_VOICE_CALL so this will only change the HAL volume once even
4698// if more than one track are active
Andy Hung71742ab2023-07-07 13:47:37 -07004699status_t PlaybackThread::handleVoipVolume_l(float* volume)
Eric Laurenteab90452019-06-24 15:17:46 -07004700{
4701 status_t result = NO_ERROR;
4702 if ((mOutput->flags & AUDIO_OUTPUT_FLAG_VOIP_RX) != 0) {
4703 if (*volume != mLeftVolFloat) {
4704 result = mOutput->stream->setVolume(*volume, *volume);
Alex Leungc5dedb22023-05-10 08:00:50 -07004705 // HAL can return INVALID_OPERATION if operation is not supported.
4706 ALOGE_IF(result != OK && result != INVALID_OPERATION,
Eric Laurenteab90452019-06-24 15:17:46 -07004707 "Error when setting output stream volume: %d", result);
4708 if (result == NO_ERROR) {
4709 mLeftVolFloat = *volume;
4710 }
4711 }
4712 // if stream volume was successfully sent to the HAL, mLeftVolFloat == v here and we
4713 // remove stream volume contribution from software volume.
4714 if (mLeftVolFloat == *volume) {
4715 *volume = 1.0f;
4716 }
4717 }
4718 return result;
4719}
4720
Andy Hung71742ab2023-07-07 13:47:37 -07004721status_t MixerThread::createAudioPatch_l(const struct audio_patch* patch,
Eric Laurent054d9d32015-04-24 08:48:48 -07004722 audio_patch_handle_t *handle)
4723{
Andy Hungf60abce2016-08-26 11:37:54 -07004724 status_t status;
4725 if (property_get_bool("af.patch_park", false /* default_value */)) {
4726 // Park FastMixer to avoid potential DOS issues with writing to the HAL
4727 // or if HAL does not properly lock against access.
4728 AutoPark<FastMixer> park(mFastMixer);
4729 status = PlaybackThread::createAudioPatch_l(patch, handle);
4730 } else {
4731 status = PlaybackThread::createAudioPatch_l(patch, handle);
4732 }
Eric Laurentb0463942022-12-20 16:31:10 +01004733
4734 updateHalSupportedLatencyModes_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07004735 return status;
4736}
4737
Andy Hung71742ab2023-07-07 13:47:37 -07004738status_t PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
Eric Laurent1c333e22014-05-20 10:48:17 -07004739 audio_patch_handle_t *handle)
4740{
4741 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07004742
4743 // store new device and send to effects
4744 audio_devices_t type = AUDIO_DEVICE_NONE;
jiabinc52b1ff2019-10-31 17:20:42 -07004745 AudioDeviceTypeAddrVector deviceTypeAddrs;
Eric Laurent054d9d32015-04-24 08:48:48 -07004746 for (unsigned int i = 0; i < patch->num_sinks; i++) {
jiabinc52b1ff2019-10-31 17:20:42 -07004747 LOG_ALWAYS_FATAL_IF(popcount(patch->sinks[i].ext.device.type) > 1
4748 && !mOutput->audioHwDev->supportsAudioPatches(),
4749 "Enumerated device type(%#x) must not be used "
4750 "as it does not support audio patches",
4751 patch->sinks[i].ext.device.type);
Mikhail Naganov55773032020-10-01 15:08:13 -07004752 type = static_cast<audio_devices_t>(type | patch->sinks[i].ext.device.type);
Andy Hung71ba4b32022-10-06 12:09:49 -07004753 deviceTypeAddrs.emplace_back(patch->sinks[i].ext.device.type,
4754 patch->sinks[i].ext.device.address);
Eric Laurent054d9d32015-04-24 08:48:48 -07004755 }
4756
François Gaffie0c280aa2018-07-25 10:02:15 +02004757 audio_port_handle_t sinkPortId = patch->sinks[0].id;
Eric Laurent054d9d32015-04-24 08:48:48 -07004758#ifdef ADD_BATTERY_DATA
4759 // when changing the audio output device, call addBatteryData to notify
4760 // the change
jiabinc52b1ff2019-10-31 17:20:42 -07004761 if (outDeviceTypes() != deviceTypes) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004762 uint32_t params = 0;
4763 // check whether speaker is on
jiabinc52b1ff2019-10-31 17:20:42 -07004764 if (deviceTypes.count(AUDIO_DEVICE_OUT_SPEAKER) > 0) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004765 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent1c333e22014-05-20 10:48:17 -07004766 }
4767
Eric Laurent054d9d32015-04-24 08:48:48 -07004768 // check if any other device (except speaker) is on
jiabinc52b1ff2019-10-31 17:20:42 -07004769 if (!isSingleDeviceType(deviceTypes, AUDIO_DEVICE_OUT_SPEAKER)) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004770 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
4771 }
4772
4773 if (params != 0) {
4774 addBatteryData(params);
4775 }
4776 }
4777#endif
4778
4779 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08004780 mEffectChains[i]->setDevices_l(deviceTypeAddrs);
Eric Laurent054d9d32015-04-24 08:48:48 -07004781 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07004782
jiabinc52b1ff2019-10-31 17:20:42 -07004783 // mPatch.num_sinks is not set when the thread is created so that
4784 // the first patch creation triggers an ioConfigChanged callback
4785 bool configChanged = (mPatch.num_sinks == 0) ||
4786 (mPatch.sinks[0].id != sinkPortId);
Eric Laurent296fb132015-05-01 11:38:42 -07004787 mPatch = *patch;
jiabinc52b1ff2019-10-31 17:20:42 -07004788 mOutDeviceTypeAddrs = deviceTypeAddrs;
jiabin0a957d32020-04-29 10:56:20 -07004789 checkSilentMode_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07004790
Mikhail Naganov9ee05402016-10-13 15:58:17 -07004791 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07004792 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
4793 status = hwDevice->createAudioPatch(patch->num_sources,
4794 patch->sources,
4795 patch->num_sinks,
4796 patch->sinks,
4797 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07004798 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08004799 status = mOutput->stream->legacyCreateAudioPatch(patch->sinks[0], std::nullopt, type);
Eric Laurent054d9d32015-04-24 08:48:48 -07004800 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07004801 }
Andy Hungc2b11cb2020-04-22 09:04:01 -07004802 const std::string patchSinksAsString = patchSinksToString(patch);
Andy Hungcf10d742020-04-28 15:38:24 -07004803
4804 mThreadMetrics.logEndInterval();
Andy Hungea840382020-05-05 21:50:17 -07004805 mThreadMetrics.logCreatePatch(/* inDevices */ {}, patchSinksAsString);
Andy Hungcf10d742020-04-28 15:38:24 -07004806 mThreadMetrics.logBeginInterval();
Andy Hungc2b11cb2020-04-22 09:04:01 -07004807 // also dispatch to active AudioTracks for MediaMetrics
4808 for (const auto &track : mActiveTracks) {
4809 track->logEndInterval();
4810 track->logBeginInterval(patchSinksAsString);
4811 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08004812
Eric Laurente8726fe2015-06-26 09:39:24 -07004813 if (configChanged) {
4814 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
4815 }
Vlad Popa7e81cea2023-01-19 16:34:16 +01004816 // Force metadata update after a route change
Eric Laurentdda206a2022-07-08 17:28:35 +02004817 mActiveTracks.setHasChanged();
4818
Eric Laurent1c333e22014-05-20 10:48:17 -07004819 return status;
4820}
4821
Andy Hung71742ab2023-07-07 13:47:37 -07004822status_t MixerThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
Eric Laurent054d9d32015-04-24 08:48:48 -07004823{
Andy Hungf60abce2016-08-26 11:37:54 -07004824 status_t status;
4825 if (property_get_bool("af.patch_park", false /* default_value */)) {
4826 // Park FastMixer to avoid potential DOS issues with writing to the HAL
4827 // or if HAL does not properly lock against access.
4828 AutoPark<FastMixer> park(mFastMixer);
4829 status = PlaybackThread::releaseAudioPatch_l(handle);
4830 } else {
4831 status = PlaybackThread::releaseAudioPatch_l(handle);
4832 }
Eric Laurent054d9d32015-04-24 08:48:48 -07004833 return status;
4834}
4835
Andy Hung71742ab2023-07-07 13:47:37 -07004836status_t PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004837{
4838 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07004839
jiabinc52b1ff2019-10-31 17:20:42 -07004840 mPatch = audio_patch{};
4841 mOutDeviceTypeAddrs.clear();
Eric Laurent054d9d32015-04-24 08:48:48 -07004842
Mikhail Naganov9ee05402016-10-13 15:58:17 -07004843 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07004844 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
4845 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07004846 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08004847 status = mOutput->stream->legacyReleaseAudioPatch();
Eric Laurent1c333e22014-05-20 10:48:17 -07004848 }
Eric Laurentdda206a2022-07-08 17:28:35 +02004849 // Force meteadata update after a route change
4850 mActiveTracks.setHasChanged();
4851
Eric Laurent1c333e22014-05-20 10:48:17 -07004852 return status;
4853}
4854
Andy Hung71742ab2023-07-07 13:47:37 -07004855void PlaybackThread::addPatchTrack(const sp<IAfPatchTrack>& track)
Eric Laurent83b88082014-06-20 18:31:16 -07004856{
4857 Mutex::Autolock _l(mLock);
4858 mTracks.add(track);
4859}
4860
Andy Hung71742ab2023-07-07 13:47:37 -07004861void PlaybackThread::deletePatchTrack(const sp<IAfPatchTrack>& track)
Eric Laurent83b88082014-06-20 18:31:16 -07004862{
4863 Mutex::Autolock _l(mLock);
4864 destroyTrack_l(track);
4865}
4866
Andy Hung71742ab2023-07-07 13:47:37 -07004867void PlaybackThread::toAudioPortConfig(struct audio_port_config* config)
Eric Laurent83b88082014-06-20 18:31:16 -07004868{
Mikhail Naganovdc769682018-05-04 15:34:08 -07004869 ThreadBase::toAudioPortConfig(config);
Eric Laurent83b88082014-06-20 18:31:16 -07004870 config->role = AUDIO_PORT_ROLE_SOURCE;
4871 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
4872 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07004873 if (mOutput && mOutput->flags != AUDIO_OUTPUT_FLAG_NONE) {
4874 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
4875 config->flags.output = mOutput->flags;
4876 }
Eric Laurent83b88082014-06-20 18:31:16 -07004877}
4878
Eric Laurent81784c32012-11-19 14:55:58 -08004879// ----------------------------------------------------------------------------
4880
Andy Hung71742ab2023-07-07 13:47:37 -07004881/* static */
4882sp<IAfPlaybackThread> IAfPlaybackThread::createMixerThread(
Andy Hung2cbc2722023-07-17 17:05:00 -07004883 const sp<IAfThreadCallback>& afThreadCallback, AudioStreamOut* output,
Andy Hung71742ab2023-07-07 13:47:37 -07004884 audio_io_handle_t id, bool systemReady, type_t type, audio_config_base_t* mixerConfig) {
Andy Hung2cbc2722023-07-17 17:05:00 -07004885 return sp<MixerThread>::make(afThreadCallback, output, id, systemReady, type, mixerConfig);
Andy Hung71742ab2023-07-07 13:47:37 -07004886}
4887
Andy Hung2cbc2722023-07-17 17:05:00 -07004888MixerThread::MixerThread(const sp<IAfThreadCallback>& afThreadCallback, AudioStreamOut* output,
Eric Laurentf1f22e72021-07-13 14:04:14 +02004889 audio_io_handle_t id, bool systemReady, type_t type, audio_config_base_t *mixerConfig)
Andy Hung2cbc2722023-07-17 17:05:00 -07004890 : PlaybackThread(afThreadCallback, output, id, type, systemReady, mixerConfig),
Eric Laurent81784c32012-11-19 14:55:58 -08004891 // mAudioMixer below
4892 // mFastMixer below
Eric Laurentb0463942022-12-20 16:31:10 +01004893 mBluetoothLatencyModesEnabled(false),
Andy Hung2ddee192015-12-18 17:34:44 -08004894 mFastMixerFutex(0),
4895 mMasterMono(false)
Eric Laurent81784c32012-11-19 14:55:58 -08004896 // mOutputSink below
4897 // mPipeSink below
4898 // mNormalSink below
4899{
Andy Hung2cbc2722023-07-17 17:05:00 -07004900 setMasterBalance(afThreadCallback->getMasterBalance_l());
jiabinc52b1ff2019-10-31 17:20:42 -07004901 ALOGV("MixerThread() id=%d type=%d", id, type);
Glenn Kasten49f36ba2017-12-06 13:02:02 -08004902 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%#x, mFrameSize=%zu, "
Glenn Kastenc42e9b42016-03-21 11:35:03 -07004903 "mFrameCount=%zu, mNormalFrameCount=%zu",
Eric Laurent81784c32012-11-19 14:55:58 -08004904 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
4905 mNormalFrameCount);
4906 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
4907
Andy Hungfbfc3952015-01-15 13:33:51 -08004908 if (type == DUPLICATING) {
4909 // The Duplicating thread uses the AudioMixer and delivers data to OutputTracks
4910 // (downstream MixerThreads) in DuplicatingThread::threadLoop_write().
4911 // Do not create or use mFastMixer, mOutputSink, mPipeSink, or mNormalSink.
4912 return;
4913 }
Eric Laurent81784c32012-11-19 14:55:58 -08004914 // create an NBAIO sink for the HAL output stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07004915 mOutputSink = new AudioStreamOutSink(output->stream);
Eric Laurent81784c32012-11-19 14:55:58 -08004916 size_t numCounterOffers = 0;
jiabin245cdd92018-12-07 17:55:15 -08004917 const NBAIO_Format offers[1] = {Format_from_SR_C(
4918 mSampleRate, mChannelCount + mHapticChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07004919#if !LOG_NDEBUG
4920 ssize_t index =
4921#else
4922 (void)
4923#endif
4924 mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08004925 ALOG_ASSERT(index == 0);
4926
4927 // initialize fast mixer depending on configuration
4928 bool initFastMixer;
jiabinc658e452022-10-21 20:52:21 +00004929 if (mType == SPATIALIZER || mType == BIT_PERFECT) {
Eric Laurent81784c32012-11-19 14:55:58 -08004930 initFastMixer = false;
Eric Laurentb62d0362021-10-26 17:40:18 +02004931 } else {
4932 switch (kUseFastMixer) {
4933 case FastMixer_Never:
4934 initFastMixer = false;
4935 break;
4936 case FastMixer_Always:
4937 initFastMixer = true;
4938 break;
4939 case FastMixer_Static:
4940 case FastMixer_Dynamic:
4941 initFastMixer = mFrameCount < mNormalFrameCount;
4942 break;
4943 }
4944 ALOGW_IF(initFastMixer == false && mFrameCount < mNormalFrameCount,
4945 "FastMixer is preferred for this sink as frameCount %zu is less than threshold %zu",
4946 mFrameCount, mNormalFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08004947 }
4948 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07004949 audio_format_t fastMixerFormat;
4950 if (mMixerBufferEnabled && mEffectBufferEnabled) {
4951 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
4952 } else {
4953 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
4954 }
4955 if (mFormat != fastMixerFormat) {
4956 // change our Sink format to accept our intermediate precision
4957 mFormat = fastMixerFormat;
4958 free(mSinkBuffer);
jiabin245cdd92018-12-07 17:55:15 -08004959 mFrameSize = audio_bytes_per_frame(mChannelCount + mHapticChannelCount, mFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07004960 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
4961 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
4962 }
Eric Laurent81784c32012-11-19 14:55:58 -08004963
4964 // create a MonoPipe to connect our submix to FastMixer
4965 NBAIO_Format format = mOutputSink->format();
Andy Hung8946a282018-04-19 20:04:56 -07004966
Andy Hung1258c1a2014-05-23 21:22:17 -07004967 // adjust format to match that of the Fast Mixer
Glenn Kasten49f36ba2017-12-06 13:02:02 -08004968 ALOGV("format changed from %#x to %#x", format.mFormat, fastMixerFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07004969 format.mFormat = fastMixerFormat;
4970 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
4971
Eric Laurent81784c32012-11-19 14:55:58 -08004972 // This pipe depth compensates for scheduling latency of the normal mixer thread.
4973 // When it wakes up after a maximum latency, it runs a few cycles quickly before
4974 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
4975 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
Andy Hung71ba4b32022-10-06 12:09:49 -07004976 const NBAIO_Format offersFast[1] = {format};
4977 size_t numCounterOffersFast = 0;
Andy Hung8946a282018-04-19 20:04:56 -07004978#if !LOG_NDEBUG
Eric Laurent1e28aaa2023-04-16 19:34:23 +02004979 index =
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07004980#else
4981 (void)
4982#endif
Andy Hung71ba4b32022-10-06 12:09:49 -07004983 monoPipe->negotiate(offersFast, std::size(offersFast),
4984 nullptr /* counterOffers */, numCounterOffersFast);
Eric Laurent81784c32012-11-19 14:55:58 -08004985 ALOG_ASSERT(index == 0);
4986 monoPipe->setAvgFrames((mScreenState & 1) ?
4987 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
4988 mPipeSink = monoPipe;
4989
Eric Laurent81784c32012-11-19 14:55:58 -08004990 // create fast mixer and configure it initially with just one fast track for our submix
Andy Hung8946a282018-04-19 20:04:56 -07004991 mFastMixer = new FastMixer(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08004992 FastMixerStateQueue *sq = mFastMixer->sq();
4993#ifdef STATE_QUEUE_DUMP
4994 sq->setObserverDump(&mStateQueueObserverDump);
4995 sq->setMutatorDump(&mStateQueueMutatorDump);
4996#endif
4997 FastMixerState *state = sq->begin();
4998 FastTrack *fastTrack = &state->mFastTracks[0];
4999 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
5000 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
5001 fastTrack->mVolumeProvider = NULL;
Mikhail Naganov55773032020-10-01 15:08:13 -07005002 fastTrack->mChannelMask = static_cast<audio_channel_mask_t>(
5003 mChannelMask | mHapticChannelMask); // mPipeSink channel mask for
5004 // audio to FastMixer
Andy Hunge8a1ced2014-05-09 15:02:21 -07005005 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
jiabin245cdd92018-12-07 17:55:15 -08005006 fastTrack->mHapticPlaybackEnabled = mHapticChannelMask != AUDIO_CHANNEL_NONE;
jiabine70bc7f2020-06-30 22:07:55 -07005007 fastTrack->mHapticIntensity = os::HapticScale::NONE;
Lais Andradebc3f37a2021-07-02 00:13:19 +01005008 fastTrack->mHapticMaxAmplitude = NAN;
Eric Laurent81784c32012-11-19 14:55:58 -08005009 fastTrack->mGeneration++;
5010 state->mFastTracksGen++;
5011 state->mTrackMask = 1;
5012 // fast mixer will use the HAL output sink
5013 state->mOutputSink = mOutputSink.get();
5014 state->mOutputSinkGen++;
5015 state->mFrameCount = mFrameCount;
jiabin245cdd92018-12-07 17:55:15 -08005016 // specify sink channel mask when haptic channel mask present as it can not
5017 // be calculated directly from channel count
5018 state->mSinkChannelMask = mHapticChannelMask == AUDIO_CHANNEL_NONE
Mikhail Naganov55773032020-10-01 15:08:13 -07005019 ? AUDIO_CHANNEL_NONE
5020 : static_cast<audio_channel_mask_t>(mChannelMask | mHapticChannelMask);
Eric Laurent81784c32012-11-19 14:55:58 -08005021 state->mCommand = FastMixerState::COLD_IDLE;
5022 // already done in constructor initialization list
5023 //mFastMixerFutex = 0;
5024 state->mColdFutexAddr = &mFastMixerFutex;
5025 state->mColdGen++;
5026 state->mDumpState = &mFastMixerDumpState;
Andy Hung2cbc2722023-07-17 17:05:00 -07005027 mFastMixerNBLogWriter = afThreadCallback->newWriter_l(kFastMixerLogSize, "FastMixer");
Glenn Kasten9e58b552013-01-18 15:09:48 -08005028 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08005029 sq->end();
5030 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
5031
Eric Tan0513b5d2018-09-17 10:32:48 -07005032 NBLog::thread_info_t info;
5033 info.id = mId;
5034 info.type = NBLog::FASTMIXER;
5035 mFastMixerNBLogWriter->log<NBLog::EVENT_THREAD_INFO>(info);
5036
Eric Laurent81784c32012-11-19 14:55:58 -08005037 // start the fast mixer
5038 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
5039 pid_t tid = mFastMixer->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07005040 sendPrioConfigEvent(getpid(), tid, kPriorityFastMixer, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08005041 stream()->setHalThreadPriority(kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08005042
5043#ifdef AUDIO_WATCHDOG
5044 // create and start the watchdog
5045 mAudioWatchdog = new AudioWatchdog();
5046 mAudioWatchdog->setDump(&mAudioWatchdogDump);
5047 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
5048 tid = mAudioWatchdog->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07005049 sendPrioConfigEvent(getpid(), tid, kPriorityFastMixer, false /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08005050#endif
Andy Hung8946a282018-04-19 20:04:56 -07005051 } else {
5052#ifdef TEE_SINK
5053 // Only use the MixerThread tee if there is no FastMixer.
5054 mTee.set(mOutputSink->format(), NBAIO_Tee::TEE_FLAG_OUTPUT_THREAD);
5055 mTee.setId(std::string("_") + std::to_string(mId) + "_M");
5056#endif
Eric Laurent81784c32012-11-19 14:55:58 -08005057 }
5058
5059 switch (kUseFastMixer) {
5060 case FastMixer_Never:
5061 case FastMixer_Dynamic:
5062 mNormalSink = mOutputSink;
5063 break;
5064 case FastMixer_Always:
5065 mNormalSink = mPipeSink;
5066 break;
5067 case FastMixer_Static:
5068 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
5069 break;
5070 }
5071}
5072
Andy Hung71742ab2023-07-07 13:47:37 -07005073MixerThread::~MixerThread()
Eric Laurent81784c32012-11-19 14:55:58 -08005074{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005075 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005076 FastMixerStateQueue *sq = mFastMixer->sq();
5077 FastMixerState *state = sq->begin();
5078 if (state->mCommand == FastMixerState::COLD_IDLE) {
5079 int32_t old = android_atomic_inc(&mFastMixerFutex);
5080 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07005081 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08005082 }
5083 }
5084 state->mCommand = FastMixerState::EXIT;
5085 sq->end();
5086 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
5087 mFastMixer->join();
5088 // Though the fast mixer thread has exited, it's state queue is still valid.
5089 // We'll use that extract the final state which contains one remaining fast track
5090 // corresponding to our sub-mix.
5091 state = sq->begin();
5092 ALOG_ASSERT(state->mTrackMask == 1);
5093 FastTrack *fastTrack = &state->mFastTracks[0];
5094 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
5095 delete fastTrack->mBufferProvider;
5096 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005097 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08005098#ifdef AUDIO_WATCHDOG
5099 if (mAudioWatchdog != 0) {
5100 mAudioWatchdog->requestExit();
5101 mAudioWatchdog->requestExitAndWait();
5102 mAudioWatchdog.clear();
5103 }
5104#endif
5105 }
Andy Hung2cbc2722023-07-17 17:05:00 -07005106 mAfThreadCallback->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08005107 delete mAudioMixer;
5108}
5109
Andy Hung71742ab2023-07-07 13:47:37 -07005110void MixerThread::onFirstRef() {
Eric Laurentb0463942022-12-20 16:31:10 +01005111 PlaybackThread::onFirstRef();
5112
5113 Mutex::Autolock _l(mLock);
5114 if (mOutput != nullptr && mOutput->stream != nullptr) {
5115 status_t status = mOutput->stream->setLatencyModeCallback(this);
5116 if (status != INVALID_OPERATION) {
5117 updateHalSupportedLatencyModes_l();
5118 }
5119 // Default to enabled if the HAL supports it. This can be changed by Audioflinger after
5120 // the thread construction according to AudioFlinger::mBluetoothLatencyModesEnabled
5121 mBluetoothLatencyModesEnabled.store(
5122 mOutput->audioHwDev->supportsBluetoothVariableLatency());
5123 }
5124}
Eric Laurent81784c32012-11-19 14:55:58 -08005125
Andy Hung71742ab2023-07-07 13:47:37 -07005126uint32_t MixerThread::correctLatency_l(uint32_t latency) const
Eric Laurent81784c32012-11-19 14:55:58 -08005127{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005128 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005129 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
5130 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
5131 }
5132 return latency;
5133}
5134
Andy Hung71742ab2023-07-07 13:47:37 -07005135ssize_t MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08005136{
5137 // FIXME we should only do one push per cycle; confirm this is true
5138 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005139 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005140 FastMixerStateQueue *sq = mFastMixer->sq();
5141 FastMixerState *state = sq->begin();
5142 if (state->mCommand != FastMixerState::MIX_WRITE &&
5143 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
5144 if (state->mCommand == FastMixerState::COLD_IDLE) {
Eric Laurenta2ab4502015-09-09 12:25:51 -07005145
5146 // FIXME workaround for first HAL write being CPU bound on some devices
5147 ATRACE_BEGIN("write");
5148 mOutput->write((char *)mSinkBuffer, 0);
5149 ATRACE_END();
5150
Eric Laurent81784c32012-11-19 14:55:58 -08005151 int32_t old = android_atomic_inc(&mFastMixerFutex);
5152 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07005153 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08005154 }
5155#ifdef AUDIO_WATCHDOG
5156 if (mAudioWatchdog != 0) {
5157 mAudioWatchdog->resume();
5158 }
5159#endif
5160 }
5161 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kastend797a9d2015-03-02 14:19:25 -08005162#ifdef FAST_THREAD_STATISTICS
Andy Hung2cbc2722023-07-17 17:05:00 -07005163 mFastMixerDumpState.increaseSamplingN(mAfThreadCallback->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08005164 FastThreadDumpState::kSamplingNforLowRamDevice : FastThreadDumpState::kSamplingN);
Glenn Kastend797a9d2015-03-02 14:19:25 -08005165#endif
Eric Laurent81784c32012-11-19 14:55:58 -08005166 sq->end();
5167 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
5168 if (kUseFastMixer == FastMixer_Dynamic) {
5169 mNormalSink = mPipeSink;
5170 }
5171 } else {
5172 sq->end(false /*didModify*/);
5173 }
5174 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005175 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08005176}
5177
Andy Hung71742ab2023-07-07 13:47:37 -07005178void MixerThread::threadLoop_standby()
Eric Laurent81784c32012-11-19 14:55:58 -08005179{
5180 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005181 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005182 FastMixerStateQueue *sq = mFastMixer->sq();
5183 FastMixerState *state = sq->begin();
5184 if (!(state->mCommand & FastMixerState::IDLE)) {
Andy Hung2148bf02016-11-28 19:01:02 -08005185 // Report any frames trapped in the Monopipe
5186 MonoPipe *monoPipe = (MonoPipe *)mPipeSink.get();
5187 const long long pipeFrames = monoPipe->maxFrames() - monoPipe->availableToWrite();
5188 mLocalLog.log("threadLoop_standby: framesWritten:%lld suspendedFrames:%lld "
5189 "monoPipeWritten:%lld monoPipeLeft:%lld",
5190 (long long)mFramesWritten, (long long)mSuspendedFrames,
5191 (long long)mPipeSink->framesWritten(), pipeFrames);
5192 mLocalLog.log("threadLoop_standby: %s", mTimestamp.toString().c_str());
5193
Eric Laurent81784c32012-11-19 14:55:58 -08005194 state->mCommand = FastMixerState::COLD_IDLE;
5195 state->mColdFutexAddr = &mFastMixerFutex;
5196 state->mColdGen++;
5197 mFastMixerFutex = 0;
5198 sq->end();
5199 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
5200 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
5201 if (kUseFastMixer == FastMixer_Dynamic) {
5202 mNormalSink = mOutputSink;
5203 }
5204#ifdef AUDIO_WATCHDOG
5205 if (mAudioWatchdog != 0) {
5206 mAudioWatchdog->pause();
5207 }
5208#endif
5209 } else {
5210 sq->end(false /*didModify*/);
5211 }
5212 }
5213 PlaybackThread::threadLoop_standby();
5214}
5215
Andy Hung71742ab2023-07-07 13:47:37 -07005216bool PlaybackThread::waitingAsyncCallback_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08005217{
5218 return false;
5219}
5220
Andy Hung71742ab2023-07-07 13:47:37 -07005221bool PlaybackThread::shouldStandby_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08005222{
5223 return !mStandby;
5224}
5225
Andy Hung71742ab2023-07-07 13:47:37 -07005226bool PlaybackThread::waitingAsyncCallback()
Eric Laurentbfb1b832013-01-07 09:53:42 -08005227{
5228 Mutex::Autolock _l(mLock);
5229 return waitingAsyncCallback_l();
5230}
5231
Eric Laurent81784c32012-11-19 14:55:58 -08005232// shared by MIXER and DIRECT, overridden by DUPLICATING
Andy Hung71742ab2023-07-07 13:47:37 -07005233void PlaybackThread::threadLoop_standby()
Eric Laurent81784c32012-11-19 14:55:58 -08005234{
5235 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
Phil Burk062e67a2015-02-11 13:40:50 -08005236 mOutput->standby();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005237 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005238 // discard any pending drain or write ack by incrementing sequence
5239 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
5240 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005241 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005242 mCallbackThread->setWriteBlocked(mWriteAckSequence);
5243 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005244 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08005245 mHwPaused = false;
Eric Laurent6f9534f2022-05-03 18:15:04 +02005246 setHalLatencyMode_l();
Eric Laurent81784c32012-11-19 14:55:58 -08005247}
5248
Andy Hung71742ab2023-07-07 13:47:37 -07005249void PlaybackThread::onAddNewTrack_l()
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08005250{
5251 ALOGV("signal playback thread");
5252 broadcast_l();
5253}
5254
Andy Hung71742ab2023-07-07 13:47:37 -07005255void PlaybackThread::onAsyncError()
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005256{
5257 for (int i = AUDIO_STREAM_SYSTEM; i < (int)AUDIO_STREAM_CNT; i++) {
5258 invalidateTracks((audio_stream_type_t)i);
5259 }
5260}
5261
Andy Hung71742ab2023-07-07 13:47:37 -07005262void MixerThread::threadLoop_mix()
Eric Laurent81784c32012-11-19 14:55:58 -08005263{
Eric Laurent81784c32012-11-19 14:55:58 -08005264 // mix buffers...
Glenn Kastend79072e2016-01-06 08:41:20 -08005265 mAudioMixer->process();
Andy Hung25c2dac2014-02-27 14:56:00 -08005266 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005267 // increase sleep time progressively when application underrun condition clears.
5268 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
5269 // that a steady state of alternating ready/not ready conditions keeps the sleep time
5270 // such that we would underrun the audio HAL.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005271 if ((mSleepTimeUs == 0) && (sleepTimeShift > 0)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005272 sleepTimeShift--;
5273 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005274 mSleepTimeUs = 0;
5275 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08005276 //TODO: delay standby when effects have a tail
Glenn Kasten4c053ea2014-09-28 14:41:07 -07005277
Eric Laurent81784c32012-11-19 14:55:58 -08005278}
5279
Andy Hung71742ab2023-07-07 13:47:37 -07005280void MixerThread::threadLoop_sleepTime()
Eric Laurent81784c32012-11-19 14:55:58 -08005281{
5282 // If no tracks are ready, sleep once for the duration of an output
5283 // buffer size, then write 0s to the output
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005284 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005285 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Andy Hung06d13222018-05-03 20:13:31 -07005286 if (mPipeSink.get() != nullptr && mPipeSink == mNormalSink) {
5287 // Using the Monopipe availableToWrite, we estimate the
5288 // sleep time to retry for more data (before we underrun).
5289 MonoPipe *monoPipe = static_cast<MonoPipe *>(mPipeSink.get());
5290 const ssize_t availableToWrite = mPipeSink->availableToWrite();
5291 const size_t pipeFrames = monoPipe->maxFrames();
5292 const size_t framesLeft = pipeFrames - max(availableToWrite, 0);
5293 // HAL_framecount <= framesDelay ~ framesLeft / 2 <= Normal_Mixer_framecount
5294 const size_t framesDelay = std::min(
5295 mNormalFrameCount, max(framesLeft / 2, mFrameCount));
5296 ALOGV("pipeFrames:%zu framesLeft:%zu framesDelay:%zu",
5297 pipeFrames, framesLeft, framesDelay);
5298 mSleepTimeUs = framesDelay * MICROS_PER_SECOND / mSampleRate;
5299 } else {
5300 mSleepTimeUs = mActiveSleepTimeUs >> sleepTimeShift;
5301 if (mSleepTimeUs < kMinThreadSleepTimeUs) {
5302 mSleepTimeUs = kMinThreadSleepTimeUs;
5303 }
5304 // reduce sleep time in case of consecutive application underruns to avoid
5305 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
5306 // duration we would end up writing less data than needed by the audio HAL if
5307 // the condition persists.
5308 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
5309 sleepTimeShift++;
5310 }
Eric Laurent81784c32012-11-19 14:55:58 -08005311 }
5312 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005313 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005314 }
5315 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08005316 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
5317 // before effects processing or output.
5318 if (mMixerBufferValid) {
5319 memset(mMixerBuffer, 0, mMixerBufferSize);
Eric Laurent39095982021-08-24 18:29:27 +02005320 if (mType == SPATIALIZER) {
5321 memset(mSinkBuffer, 0, mSinkBufferSize);
5322 }
Andy Hung98ef9782014-03-04 14:46:50 -08005323 } else {
5324 memset(mSinkBuffer, 0, mSinkBufferSize);
5325 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005326 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005327 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
5328 "anticipated start");
5329 }
5330 // TODO add standby time extension fct of effect tail
5331}
5332
5333// prepareTracks_l() must be called with ThreadBase::mLock held
Andy Hung71742ab2023-07-07 13:47:37 -07005334PlaybackThread::mixer_state MixerThread::prepareTracks_l(
Andy Hung3ff4b552023-06-26 19:20:57 -07005335 Vector<sp<IAfTrack>>* tracksToRemove)
Eric Laurent81784c32012-11-19 14:55:58 -08005336{
Andy Hungc0691382018-09-12 18:01:57 -07005337 // clean up deleted track ids in AudioMixer before allocating new tracks
5338 (void)mTracks.processDeletedTrackIds([this](int trackId) {
5339 // for each trackId, destroy it in the AudioMixer
5340 if (mAudioMixer->exists(trackId)) {
5341 mAudioMixer->destroy(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08005342 }
5343 });
Andy Hungc0691382018-09-12 18:01:57 -07005344 mTracks.clearDeletedTrackIds();
Eric Laurent81784c32012-11-19 14:55:58 -08005345
5346 mixer_state mixerStatus = MIXER_IDLE;
5347 // find out which tracks need to be processed
5348 size_t count = mActiveTracks.size();
5349 size_t mixedTracks = 0;
5350 size_t tracksWithEffect = 0;
5351 // counts only _active_ fast tracks
5352 size_t fastTracks = 0;
5353 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
5354
5355 float masterVolume = mMasterVolume;
5356 bool masterMute = mMasterMute;
5357
5358 if (masterMute) {
5359 masterVolume = 0;
5360 }
5361 // Delegate master volume control to effect in output mix effect chain if needed
Andy Hungbd72c542023-06-20 18:56:17 -07005362 sp<IAfEffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Eric Laurent81784c32012-11-19 14:55:58 -08005363 if (chain != 0) {
5364 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
5365 chain->setVolume_l(&v, &v);
5366 masterVolume = (float)((v + (1 << 23)) >> 24);
5367 chain.clear();
5368 }
5369
5370 // prepare a new state to push
5371 FastMixerStateQueue *sq = NULL;
5372 FastMixerState *state = NULL;
5373 bool didModify = false;
5374 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Andy Hungf2285312017-02-14 18:31:59 -08005375 bool coldIdle = false;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005376 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005377 sq = mFastMixer->sq();
5378 state = sq->begin();
Andy Hungf2285312017-02-14 18:31:59 -08005379 coldIdle = state->mCommand == FastMixerState::COLD_IDLE;
Eric Laurent81784c32012-11-19 14:55:58 -08005380 }
5381
Andy Hung69aed5f2014-02-25 17:24:40 -08005382 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08005383 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08005384
Andy Hungbd3b2b02018-05-21 10:53:11 -07005385 // DeferredOperations handles statistics after setting mixerStatus.
5386 class DeferredOperations {
5387 public:
Andy Hungea840382020-05-05 21:50:17 -07005388 DeferredOperations(mixer_state *mixerStatus, ThreadMetrics *threadMetrics)
5389 : mMixerStatus(mixerStatus)
5390 , mThreadMetrics(threadMetrics) {}
Andy Hungbd3b2b02018-05-21 10:53:11 -07005391
5392 // when leaving scope, tally frames properly.
5393 ~DeferredOperations() {
5394 // Tally underrun frames only if we are actually mixing (MIXER_TRACKS_READY)
5395 // because that is when the underrun occurs.
5396 // We do not distinguish between FastTracks and NormalTracks here.
Andy Hungea840382020-05-05 21:50:17 -07005397 size_t maxUnderrunFrames = 0;
Andy Hungb68f5eb2019-12-03 16:49:17 -08005398 if (*mMixerStatus == MIXER_TRACKS_READY && mUnderrunFrames.size() > 0) {
Andy Hungbd3b2b02018-05-21 10:53:11 -07005399 for (const auto &underrun : mUnderrunFrames) {
Andy Hungc2b11cb2020-04-22 09:04:01 -07005400 underrun.first->tallyUnderrunFrames(underrun.second);
Andy Hungea840382020-05-05 21:50:17 -07005401 maxUnderrunFrames = max(underrun.second, maxUnderrunFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07005402 }
5403 }
Andy Hungea840382020-05-05 21:50:17 -07005404 // send the max underrun frames for this mixer period
5405 mThreadMetrics->logUnderrunFrames(maxUnderrunFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07005406 }
5407
5408 // tallyUnderrunFrames() is called to update the track counters
5409 // with the number of underrun frames for a particular mixer period.
5410 // We defer tallying until we know the final mixer status.
Andy Hung3ff4b552023-06-26 19:20:57 -07005411 void tallyUnderrunFrames(const sp<IAfTrack>& track, size_t underrunFrames) {
Andy Hungbd3b2b02018-05-21 10:53:11 -07005412 mUnderrunFrames.emplace_back(track, underrunFrames);
5413 }
5414
5415 private:
5416 const mixer_state * const mMixerStatus;
Andy Hungea840382020-05-05 21:50:17 -07005417 ThreadMetrics * const mThreadMetrics;
Andy Hung3ff4b552023-06-26 19:20:57 -07005418 std::vector<std::pair<sp<IAfTrack>, size_t>> mUnderrunFrames;
Andy Hungea840382020-05-05 21:50:17 -07005419 } deferredOperations(&mixerStatus, &mThreadMetrics);
Andy Hungb68f5eb2019-12-03 16:49:17 -08005420 // implicit nested scope for variable capture
Andy Hungbd3b2b02018-05-21 10:53:11 -07005421
jiabin245cdd92018-12-07 17:55:15 -08005422 bool noFastHapticTrack = true;
Eric Laurent81784c32012-11-19 14:55:58 -08005423 for (size_t i=0 ; i<count ; i++) {
Andy Hung3ff4b552023-06-26 19:20:57 -07005424 const sp<IAfTrack> t = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08005425
5426 // this const just means the local variable doesn't change
Andy Hung3ff4b552023-06-26 19:20:57 -07005427 IAfTrack* const track = t.get();
Eric Laurent81784c32012-11-19 14:55:58 -08005428
5429 // process fast tracks
5430 if (track->isFastTrack()) {
Andy Hungae22b482019-05-09 15:38:55 -07005431 LOG_ALWAYS_FATAL_IF(mFastMixer.get() == nullptr,
5432 "%s(%d): FastTrack(%d) present without FastMixer",
5433 __func__, id(), track->id());
5434
jiabin245cdd92018-12-07 17:55:15 -08005435 if (track->getHapticPlaybackEnabled()) {
5436 noFastHapticTrack = false;
5437 }
Eric Laurent81784c32012-11-19 14:55:58 -08005438
5439 // It's theoretically possible (though unlikely) for a fast track to be created
5440 // and then removed within the same normal mix cycle. This is not a problem, as
5441 // the track never becomes active so it's fast mixer slot is never touched.
5442 // The converse, of removing an (active) track and then creating a new track
5443 // at the identical fast mixer slot within the same normal mix cycle,
5444 // is impossible because the slot isn't marked available until the end of each cycle.
Andy Hung3ff4b552023-06-26 19:20:57 -07005445 int j = track->fastIndex();
Glenn Kastendc2c50b2016-04-21 08:13:14 -07005446 ALOG_ASSERT(0 < j && j < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08005447 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
5448 FastTrack *fastTrack = &state->mFastTracks[j];
5449
5450 // Determine whether the track is currently in underrun condition,
5451 // and whether it had a recent underrun.
5452 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
5453 FastTrackUnderruns underruns = ftDump->mUnderruns;
5454 uint32_t recentFull = (underruns.mBitFields.mFull -
Andy Hung3ff4b552023-06-26 19:20:57 -07005455 track->fastTrackUnderruns().mBitFields.mFull) & UNDERRUN_MASK;
Eric Laurent81784c32012-11-19 14:55:58 -08005456 uint32_t recentPartial = (underruns.mBitFields.mPartial -
Andy Hung3ff4b552023-06-26 19:20:57 -07005457 track->fastTrackUnderruns().mBitFields.mPartial) & UNDERRUN_MASK;
Eric Laurent81784c32012-11-19 14:55:58 -08005458 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
Andy Hung3ff4b552023-06-26 19:20:57 -07005459 track->fastTrackUnderruns().mBitFields.mEmpty) & UNDERRUN_MASK;
Eric Laurent81784c32012-11-19 14:55:58 -08005460 uint32_t recentUnderruns = recentPartial + recentEmpty;
Andy Hung3ff4b552023-06-26 19:20:57 -07005461 track->fastTrackUnderruns() = underruns;
Eric Laurent81784c32012-11-19 14:55:58 -08005462 // don't count underruns that occur while stopping or pausing
5463 // or stopped which can occur when flush() is called while active
Andy Hungbd3b2b02018-05-21 10:53:11 -07005464 size_t underrunFrames = 0;
Glenn Kasten82aaf942013-07-17 16:05:07 -07005465 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
5466 recentUnderruns > 0) {
5467 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
Andy Hungbd3b2b02018-05-21 10:53:11 -07005468 underrunFrames = recentUnderruns * mFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08005469 }
Andy Hungbd3b2b02018-05-21 10:53:11 -07005470 // Immediately account for FastTrack underruns.
Andy Hung3ff4b552023-06-26 19:20:57 -07005471 track->audioTrackServerProxy()->tallyUnderrunFrames(underrunFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08005472
5473 // This is similar to the state machine for normal tracks,
5474 // with a few modifications for fast tracks.
5475 bool isActive = true;
Andy Hung3ff4b552023-06-26 19:20:57 -07005476 switch (track->state()) {
5477 case IAfTrackBase::STOPPING_1:
Eric Laurent81784c32012-11-19 14:55:58 -08005478 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08005479 if (recentUnderruns > 0 || track->isTerminated()) {
Andy Hung3ff4b552023-06-26 19:20:57 -07005480 track->setState(IAfTrackBase::STOPPING_2);
Eric Laurent81784c32012-11-19 14:55:58 -08005481 }
5482 break;
Andy Hung3ff4b552023-06-26 19:20:57 -07005483 case IAfTrackBase::PAUSING:
Eric Laurent81784c32012-11-19 14:55:58 -08005484 // ramp down is not yet implemented
5485 track->setPaused();
5486 break;
Andy Hung3ff4b552023-06-26 19:20:57 -07005487 case IAfTrackBase::RESUMING:
Eric Laurent81784c32012-11-19 14:55:58 -08005488 // ramp up is not yet implemented
Andy Hung3ff4b552023-06-26 19:20:57 -07005489 track->setState(IAfTrackBase::ACTIVE);
Eric Laurent81784c32012-11-19 14:55:58 -08005490 break;
Andy Hung3ff4b552023-06-26 19:20:57 -07005491 case IAfTrackBase::ACTIVE:
Eric Laurent81784c32012-11-19 14:55:58 -08005492 if (recentFull > 0 || recentPartial > 0) {
5493 // track has provided at least some frames recently: reset retry count
Andy Hung3ff4b552023-06-26 19:20:57 -07005494 track->retryCount() = kMaxTrackRetries;
Eric Laurent81784c32012-11-19 14:55:58 -08005495 }
5496 if (recentUnderruns == 0) {
5497 // no recent underruns: stay active
5498 break;
5499 }
5500 // there has recently been an underrun of some kind
5501 if (track->sharedBuffer() == 0) {
5502 // were any of the recent underruns "empty" (no frames available)?
5503 if (recentEmpty == 0) {
5504 // no, then ignore the partial underruns as they are allowed indefinitely
5505 break;
5506 }
5507 // there has recently been an "empty" underrun: decrement the retry counter
Andy Hung3ff4b552023-06-26 19:20:57 -07005508 if (--(track->retryCount()) > 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005509 break;
5510 }
5511 // indicate to client process that the track was disabled because of underrun;
5512 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08005513 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08005514 // remove from active list, but state remains ACTIVE [confusing but true]
5515 isActive = false;
5516 break;
5517 }
Chih-Hung Hsieh2b487032018-09-13 14:16:02 -07005518 FALLTHROUGH_INTENDED;
Andy Hung3ff4b552023-06-26 19:20:57 -07005519 case IAfTrackBase::STOPPING_2:
5520 case IAfTrackBase::PAUSED:
5521 case IAfTrackBase::STOPPED:
5522 case IAfTrackBase::FLUSHED: // flush() while active
Eric Laurent81784c32012-11-19 14:55:58 -08005523 // Check for presentation complete if track is inactive
5524 // We have consumed all the buffers of this track.
5525 // This would be incomplete if we auto-paused on underrun
5526 {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005527 uint32_t latency = 0;
5528 status_t result = mOutput->stream->getLatency(&latency);
5529 ALOGE_IF(result != OK,
5530 "Error when retrieving output stream latency: %d", result);
5531 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08005532 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005533 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
5534 // track stays in active list until presentation is complete
5535 break;
5536 }
5537 }
5538 if (track->isStopping_2()) {
Andy Hung3ff4b552023-06-26 19:20:57 -07005539 track->setState(IAfTrackBase::STOPPED);
Eric Laurent81784c32012-11-19 14:55:58 -08005540 }
5541 if (track->isStopped()) {
5542 // Can't reset directly, as fast mixer is still polling this track
5543 // track->reset();
5544 // So instead mark this track as needing to be reset after push with ack
5545 resetMask |= 1 << i;
5546 }
5547 isActive = false;
5548 break;
Andy Hung3ff4b552023-06-26 19:20:57 -07005549 case IAfTrackBase::IDLE:
Eric Laurent81784c32012-11-19 14:55:58 -08005550 default:
Andy Hung3ff4b552023-06-26 19:20:57 -07005551 LOG_ALWAYS_FATAL("unexpected track state %d", (int)track->state());
Eric Laurent81784c32012-11-19 14:55:58 -08005552 }
5553
5554 if (isActive) {
5555 // was it previously inactive?
5556 if (!(state->mTrackMask & (1 << j))) {
Andy Hung3ff4b552023-06-26 19:20:57 -07005557 ExtendedAudioBufferProvider *eabp = track->asExtendedAudioBufferProvider();
5558 VolumeProvider *vp = track->asVolumeProvider();
Eric Laurent81784c32012-11-19 14:55:58 -08005559 fastTrack->mBufferProvider = eabp;
5560 fastTrack->mVolumeProvider = vp;
Andy Hung3ff4b552023-06-26 19:20:57 -07005561 fastTrack->mChannelMask = track->channelMask();
5562 fastTrack->mFormat = track->format();
jiabin245cdd92018-12-07 17:55:15 -08005563 fastTrack->mHapticPlaybackEnabled = track->getHapticPlaybackEnabled();
jiabin77270b82018-12-18 15:41:29 -08005564 fastTrack->mHapticIntensity = track->getHapticIntensity();
Lais Andradebc3f37a2021-07-02 00:13:19 +01005565 fastTrack->mHapticMaxAmplitude = track->getHapticMaxAmplitude();
Eric Laurent81784c32012-11-19 14:55:58 -08005566 fastTrack->mGeneration++;
5567 state->mTrackMask |= 1 << j;
5568 didModify = true;
5569 // no acknowledgement required for newly active tracks
5570 }
Andy Hung3ff4b552023-06-26 19:20:57 -07005571 sp<AudioTrackServerProxy> proxy = track->audioTrackServerProxy();
Eric Laurenteab90452019-06-24 15:17:46 -07005572 float volume;
5573 if (track->isPlaybackRestricted() || mStreamTypes[track->streamType()].mute) {
5574 volume = 0.f;
5575 } else {
5576 volume = masterVolume * mStreamTypes[track->streamType()].volume;
5577 }
5578
5579 handleVoipVolume_l(&volume);
5580
Eric Laurent81784c32012-11-19 14:55:58 -08005581 // cache the combined master volume and stream type volume for fast mixer; this
5582 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005583 const float vh = track->getVolumeHandler()->getVolume(
Eric Laurenteab90452019-06-24 15:17:46 -07005584 proxy->framesReleased()).first;
5585 volume *= vh;
Andy Hung3ff4b552023-06-26 19:20:57 -07005586 track->setCachedVolume(volume);
Kevin Rocard12381092018-04-11 09:19:59 -07005587 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Vlad Popae2f5aef2022-07-25 16:00:20 +02005588 float vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
5589 float vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurenteab90452019-06-24 15:17:46 -07005590
Andy Hung2cbc2722023-07-17 17:05:00 -07005591 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
Vlad Popae2f5aef2022-07-25 16:00:20 +02005592 /*muteState=*/{masterVolume == 0.f,
5593 mStreamTypes[track->streamType()].volume == 0.f,
5594 mStreamTypes[track->streamType()].mute,
5595 track->isPlaybackRestricted(),
Vlad Popa436c9172022-08-02 15:25:08 +02005596 vlf == 0.f && vrf == 0.f,
5597 vh == 0.f});
Vlad Popae2f5aef2022-07-25 16:00:20 +02005598
5599 vlf *= volume;
5600 vrf *= volume;
Kevin Rocard12381092018-04-11 09:19:59 -07005601
jiabin76d94692022-12-15 21:51:21 +00005602 track->setFinalVolume(vlf, vrf);
Eric Laurent81784c32012-11-19 14:55:58 -08005603 ++fastTracks;
5604 } else {
5605 // was it previously active?
5606 if (state->mTrackMask & (1 << j)) {
5607 fastTrack->mBufferProvider = NULL;
5608 fastTrack->mGeneration++;
5609 state->mTrackMask &= ~(1 << j);
5610 didModify = true;
5611 // If any fast tracks were removed, we must wait for acknowledgement
5612 // because we're about to decrement the last sp<> on those tracks.
5613 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
5614 } else {
Glenn Kastenbf848af2017-12-22 11:55:01 -08005615 // ALOGW rather than LOG_ALWAYS_FATAL because it seems there are cases where an
5616 // AudioTrack may start (which may not be with a start() but with a write()
5617 // after underrun) and immediately paused or released. In that case the
5618 // FastTrack state hasn't had time to update.
5619 // TODO Remove the ALOGW when this theory is confirmed.
5620 ALOGW("fast track %d should have been active; "
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08005621 "mState=%d, mTrackMask=%#x, recentUnderruns=%u, isShared=%d",
Andy Hung3ff4b552023-06-26 19:20:57 -07005622 j, (int)track->state(), state->mTrackMask, recentUnderruns,
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08005623 track->sharedBuffer() != 0);
Glenn Kastenbf848af2017-12-22 11:55:01 -08005624 // Since the FastMixer state already has the track inactive, do nothing here.
Eric Laurent81784c32012-11-19 14:55:58 -08005625 }
5626 tracksToRemove->add(track);
5627 // Avoids a misleading display in dumpsys
Andy Hung3ff4b552023-06-26 19:20:57 -07005628 track->fastTrackUnderruns().mBitFields.mMostRecent = UNDERRUN_FULL;
Eric Laurent81784c32012-11-19 14:55:58 -08005629 }
jiabin245cdd92018-12-07 17:55:15 -08005630 if (fastTrack->mHapticPlaybackEnabled != track->getHapticPlaybackEnabled()) {
5631 fastTrack->mHapticPlaybackEnabled = track->getHapticPlaybackEnabled();
5632 didModify = true;
5633 }
Eric Laurent81784c32012-11-19 14:55:58 -08005634 continue;
5635 }
5636
5637 { // local variable scope to avoid goto warning
5638
5639 audio_track_cblk_t* cblk = track->cblk();
5640
5641 // The first time a track is added we wait
5642 // for all its buffers to be filled before processing it
Andy Hungc0691382018-09-12 18:01:57 -07005643 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08005644
5645 // if an active track doesn't exist in the AudioMixer, create it.
Andy Hungc0691382018-09-12 18:01:57 -07005646 // use the trackId as the AudioMixer name.
5647 if (!mAudioMixer->exists(trackId)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08005648 status_t status = mAudioMixer->create(
Andy Hungc0691382018-09-12 18:01:57 -07005649 trackId,
Andy Hung3ff4b552023-06-26 19:20:57 -07005650 track->channelMask(),
5651 track->format(),
5652 track->sessionId());
Andy Hung1bc088a2018-02-09 15:57:31 -08005653 if (status != OK) {
Andy Hungc0691382018-09-12 18:01:57 -07005654 ALOGW("%s(): AudioMixer cannot create track(%d)"
5655 " mask %#x, format %#x, sessionId %d",
5656 __func__, trackId,
Andy Hung3ff4b552023-06-26 19:20:57 -07005657 track->channelMask(), track->format(), track->sessionId());
Andy Hung1bc088a2018-02-09 15:57:31 -08005658 tracksToRemove->add(track);
5659 track->invalidate(); // consider it dead.
5660 continue;
5661 }
5662 }
5663
Eric Laurent81784c32012-11-19 14:55:58 -08005664 // make sure that we have enough frames to mix one full buffer.
5665 // enforce this condition only once to enable draining the buffer in case the client
5666 // app does not call stop() and relies on underrun to stop:
5667 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
5668 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005669 size_t desiredFrames;
Andy Hung3ff4b552023-06-26 19:20:57 -07005670 const uint32_t sampleRate = track->audioTrackServerProxy()->getSampleRate();
5671 const AudioPlaybackRate playbackRate = track->audioTrackServerProxy()->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07005672
5673 desiredFrames = sourceFramesNeededWithTimestretch(
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07005674 sampleRate, mNormalFrameCount, mSampleRate, playbackRate.mSpeed);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005675 // TODO: ONLY USED FOR LEGACY RESAMPLERS, remove when they are removed.
5676 // add frames already consumed but not yet released by the resampler
5677 // because mAudioTrackServerProxy->framesReady() will include these frames
Andy Hungc0691382018-09-12 18:01:57 -07005678 desiredFrames += mAudioMixer->getUnreleasedFrames(trackId);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005679
Eric Laurent81784c32012-11-19 14:55:58 -08005680 uint32_t minFrames = 1;
5681 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
5682 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005683 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08005684 }
Eric Laurent13e4c962013-12-20 17:36:01 -08005685
5686 size_t framesReady = track->framesReady();
Glenn Kastene7754022014-10-31 12:11:26 -07005687 if (ATRACE_ENABLED()) {
5688 // I wish we had formatted trace names
Andy Hung1bc088a2018-02-09 15:57:31 -08005689 std::string traceName("nRdy");
Andy Hungc0691382018-09-12 18:01:57 -07005690 traceName += std::to_string(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08005691 ATRACE_INT(traceName.c_str(), framesReady);
Glenn Kastene7754022014-10-31 12:11:26 -07005692 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005693 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08005694 !track->isPaused() && !track->isTerminated())
5695 {
Andy Hungc0691382018-09-12 18:01:57 -07005696 ALOGVV("track(%d) s=%08x [OK] on thread %p", trackId, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08005697
5698 mixedTracks++;
5699
Andy Hung69aed5f2014-02-25 17:24:40 -08005700 // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
5701 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08005702 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08005703 if (track->mainBuffer() != mSinkBuffer &&
5704 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08005705 if (mEffectBufferEnabled) {
5706 mEffectBufferValid = true; // Later can set directly.
5707 }
Eric Laurent81784c32012-11-19 14:55:58 -08005708 chain = getEffectChain_l(track->sessionId());
5709 // Delegate volume control to effect in track effect chain if needed
5710 if (chain != 0) {
5711 tracksWithEffect++;
5712 } else {
Andy Hungc0691382018-09-12 18:01:57 -07005713 ALOGW("prepareTracks_l(): track(%d) attached to effect but no chain found on "
Eric Laurent81784c32012-11-19 14:55:58 -08005714 "session %d",
Andy Hungc0691382018-09-12 18:01:57 -07005715 trackId, track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08005716 }
5717 }
5718
5719
5720 int param = AudioMixer::VOLUME;
Andy Hung3ff4b552023-06-26 19:20:57 -07005721 if (track->fillingStatus() == IAfTrack::FS_FILLED) {
Eric Laurent81784c32012-11-19 14:55:58 -08005722 // no ramp for the first volume setting
Andy Hung3ff4b552023-06-26 19:20:57 -07005723 track->fillingStatus() = IAfTrack::FS_ACTIVE;
5724 if (track->state() == IAfTrackBase::RESUMING) {
5725 track->setState(IAfTrackBase::ACTIVE);
Revathi Uddaraju453bcb52017-08-14 14:19:40 +08005726 // If a new track is paused immediately after start, do not ramp on resume.
5727 if (cblk->mServer != 0) {
5728 param = AudioMixer::RAMP_VOLUME;
5729 }
Eric Laurent81784c32012-11-19 14:55:58 -08005730 }
Andy Hungc0691382018-09-12 18:01:57 -07005731 mAudioMixer->setParameter(trackId, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Eric Laurent7c29ec92017-09-20 17:54:22 -07005732 mLeftVolFloat = -1.0;
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005733 // FIXME should not make a decision based on mServer
5734 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005735 // If the track is stopped before the first frame was mixed,
5736 // do not apply ramp
5737 param = AudioMixer::RAMP_VOLUME;
5738 }
5739
5740 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07005741 uint32_t vl, vr; // in U8.24 integer format
5742 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Eric Laurent7c29ec92017-09-20 17:54:22 -07005743 // read original volumes with volume control
Eric Laurenteab90452019-06-24 15:17:46 -07005744 float v = masterVolume * mStreamTypes[track->streamType()].volume;
Andy Hung333ab962019-05-28 20:23:35 -07005745 // Always fetch volumeshaper volume to ensure state is updated.
Andy Hung3ff4b552023-06-26 19:20:57 -07005746 const sp<AudioTrackServerProxy> proxy = track->audioTrackServerProxy();
Andy Hung333ab962019-05-28 20:23:35 -07005747 const float vh = track->getVolumeHandler()->getVolume(
Andy Hung3ff4b552023-06-26 19:20:57 -07005748 track->audioTrackServerProxy()->framesReleased()).first;
Eric Laurent7c29ec92017-09-20 17:54:22 -07005749
Eric Laurenteab90452019-06-24 15:17:46 -07005750 if (mStreamTypes[track->streamType()].mute || track->isPlaybackRestricted()) {
5751 v = 0;
5752 }
5753
5754 handleVoipVolume_l(&v);
5755
5756 if (track->isPausing()) {
Andy Hung6be49402014-05-30 10:42:03 -07005757 vl = vr = 0;
5758 vlf = vrf = vaf = 0.;
Eric Laurenteab90452019-06-24 15:17:46 -07005759 track->setPaused();
Eric Laurent81784c32012-11-19 14:55:58 -08005760 } else {
Glenn Kastenc56f3422014-03-21 17:53:17 -07005761 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07005762 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
5763 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08005764 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07005765 if (vlf > GAIN_FLOAT_UNITY) {
5766 ALOGV("Track left volume out of range: %.3g", vlf);
5767 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08005768 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07005769 if (vrf > GAIN_FLOAT_UNITY) {
5770 ALOGV("Track right volume out of range: %.3g", vrf);
5771 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08005772 }
Vlad Popae2f5aef2022-07-25 16:00:20 +02005773
Andy Hung2cbc2722023-07-17 17:05:00 -07005774 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
Vlad Popae2f5aef2022-07-25 16:00:20 +02005775 /*muteState=*/{masterVolume == 0.f,
5776 mStreamTypes[track->streamType()].volume == 0.f,
5777 mStreamTypes[track->streamType()].mute,
5778 track->isPlaybackRestricted(),
Vlad Popa436c9172022-08-02 15:25:08 +02005779 vlf == 0.f && vrf == 0.f,
5780 vh == 0.f});
Vlad Popae2f5aef2022-07-25 16:00:20 +02005781
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005782 // now apply the master volume and stream type volume and shaper volume
5783 vlf *= v * vh;
5784 vrf *= v * vh;
Eric Laurent81784c32012-11-19 14:55:58 -08005785 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07005786 // then derive vl and vr as U8.24 versions for the effect chain
5787 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
5788 vl = (uint32_t) (scaleto8_24 * vlf);
5789 vr = (uint32_t) (scaleto8_24 * vrf);
5790 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08005791 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08005792 // send level comes from shared memory and so may be corrupt
5793 if (sendLevel > MAX_GAIN_INT) {
5794 ALOGV("Track send level out of range: %04X", sendLevel);
5795 sendLevel = MAX_GAIN_INT;
5796 }
Andy Hung6be49402014-05-30 10:42:03 -07005797 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
5798 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08005799 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005800
jiabin76d94692022-12-15 21:51:21 +00005801 track->setFinalVolume(vrf, vlf);
Kevin Rocard12381092018-04-11 09:19:59 -07005802
Eric Laurent81784c32012-11-19 14:55:58 -08005803 // Delegate volume control to effect in track effect chain if needed
5804 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
5805 // Do not ramp volume if volume is controlled by effect
5806 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08005807 // Update remaining floating point volume levels
5808 vlf = (float)vl / (1 << 24);
5809 vrf = (float)vr / (1 << 24);
Andy Hung3ff4b552023-06-26 19:20:57 -07005810 track->setHasVolumeController(true);
Eric Laurent81784c32012-11-19 14:55:58 -08005811 } else {
5812 // force no volume ramp when volume controller was just disabled or removed
5813 // from effect chain to avoid volume spike
Andy Hung3ff4b552023-06-26 19:20:57 -07005814 if (track->hasVolumeController()) {
Eric Laurent81784c32012-11-19 14:55:58 -08005815 param = AudioMixer::VOLUME;
5816 }
Andy Hung3ff4b552023-06-26 19:20:57 -07005817 track->setHasVolumeController(false);
Eric Laurent81784c32012-11-19 14:55:58 -08005818 }
5819
Eric Laurent81784c32012-11-19 14:55:58 -08005820 // XXX: these things DON'T need to be done each time
Andy Hung3ff4b552023-06-26 19:20:57 -07005821 mAudioMixer->setBufferProvider(trackId, track->asExtendedAudioBufferProvider());
Andy Hungc0691382018-09-12 18:01:57 -07005822 mAudioMixer->enable(trackId);
Eric Laurent81784c32012-11-19 14:55:58 -08005823
Andy Hungc0691382018-09-12 18:01:57 -07005824 mAudioMixer->setParameter(trackId, param, AudioMixer::VOLUME0, &vlf);
5825 mAudioMixer->setParameter(trackId, param, AudioMixer::VOLUME1, &vrf);
5826 mAudioMixer->setParameter(trackId, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08005827 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005828 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005829 AudioMixer::TRACK,
5830 AudioMixer::FORMAT, (void *)track->format());
5831 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005832 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005833 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00005834 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Eric Laurent39095982021-08-24 18:29:27 +02005835
Eric Laurentb0a7bc92022-04-05 15:06:08 +02005836 if (mType == SPATIALIZER && !track->isSpatialized()) {
Eric Laurent39095982021-08-24 18:29:27 +02005837 mAudioMixer->setParameter(
5838 trackId,
5839 AudioMixer::TRACK,
5840 AudioMixer::MIXER_CHANNEL_MASK,
5841 (void *)(uintptr_t)(mChannelMask | mHapticChannelMask));
5842 } else {
5843 mAudioMixer->setParameter(
5844 trackId,
5845 AudioMixer::TRACK,
5846 AudioMixer::MIXER_CHANNEL_MASK,
5847 (void *)(uintptr_t)(mMixerChannelMask | mHapticChannelMask));
5848 }
5849
Glenn Kastene3aa6592012-12-04 12:22:46 -08005850 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07005851 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Andy Hung333ab962019-05-28 20:23:35 -07005852 uint32_t reqSampleRate = proxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08005853 if (reqSampleRate == 0) {
5854 reqSampleRate = mSampleRate;
5855 } else if (reqSampleRate > maxSampleRate) {
5856 reqSampleRate = maxSampleRate;
5857 }
Eric Laurent81784c32012-11-19 14:55:58 -08005858 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005859 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005860 AudioMixer::RESAMPLE,
5861 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00005862 (void *)(uintptr_t)reqSampleRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005863
Andy Hung8edb8dc2015-03-26 19:13:55 -07005864 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005865 trackId,
Andy Hung8edb8dc2015-03-26 19:13:55 -07005866 AudioMixer::TIMESTRETCH,
5867 AudioMixer::PLAYBACK_RATE,
Andy Hung71ba4b32022-10-06 12:09:49 -07005868 // cast away constness for this generic API.
5869 const_cast<void *>(reinterpret_cast<const void *>(&playbackRate)));
Andy Hung8edb8dc2015-03-26 19:13:55 -07005870
Andy Hung69aed5f2014-02-25 17:24:40 -08005871 /*
5872 * Select the appropriate output buffer for the track.
5873 *
Andy Hung98ef9782014-03-04 14:46:50 -08005874 * Tracks with effects go into their own effects chain buffer
5875 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08005876 *
5877 * Other tracks can use mMixerBuffer for higher precision
5878 * channel accumulation. If this buffer is enabled
5879 * (mMixerBufferEnabled true), then selected tracks will accumulate
5880 * into it.
5881 *
5882 */
5883 if (mMixerBufferEnabled
5884 && (track->mainBuffer() == mSinkBuffer
5885 || track->mainBuffer() == mMixerBuffer)) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02005886 if (mType == SPATIALIZER && !track->isSpatialized()) {
Eric Laurent39095982021-08-24 18:29:27 +02005887 mAudioMixer->setParameter(
5888 trackId,
5889 AudioMixer::TRACK,
Eric Laurentb62d0362021-10-26 17:40:18 +02005890 AudioMixer::MIXER_FORMAT, (void *)mEffectBufferFormat);
Eric Laurent39095982021-08-24 18:29:27 +02005891 mAudioMixer->setParameter(
5892 trackId,
5893 AudioMixer::TRACK,
Eric Laurentb62d0362021-10-26 17:40:18 +02005894 AudioMixer::MAIN_BUFFER, (void *)mPostSpatializerBuffer);
Eric Laurent39095982021-08-24 18:29:27 +02005895 } else {
5896 mAudioMixer->setParameter(
5897 trackId,
5898 AudioMixer::TRACK,
5899 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
5900 mAudioMixer->setParameter(
5901 trackId,
5902 AudioMixer::TRACK,
5903 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
5904 // TODO: override track->mainBuffer()?
5905 mMixerBufferValid = true;
5906 }
Andy Hung69aed5f2014-02-25 17:24:40 -08005907 } else {
5908 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005909 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08005910 AudioMixer::TRACK,
Andy Hung319587b2023-05-23 14:01:03 -07005911 AudioMixer::MIXER_FORMAT, (void *)AUDIO_FORMAT_PCM_FLOAT);
Andy Hung69aed5f2014-02-25 17:24:40 -08005912 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005913 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08005914 AudioMixer::TRACK,
5915 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
5916 }
Eric Laurent81784c32012-11-19 14:55:58 -08005917 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005918 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005919 AudioMixer::TRACK,
5920 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
jiabin245cdd92018-12-07 17:55:15 -08005921 mAudioMixer->setParameter(
5922 trackId,
5923 AudioMixer::TRACK,
5924 AudioMixer::HAPTIC_ENABLED, (void *)(uintptr_t)track->getHapticPlaybackEnabled());
jiabin77270b82018-12-18 15:41:29 -08005925 mAudioMixer->setParameter(
5926 trackId,
5927 AudioMixer::TRACK,
5928 AudioMixer::HAPTIC_INTENSITY, (void *)(uintptr_t)track->getHapticIntensity());
Andy Hung3ff4b552023-06-26 19:20:57 -07005929 const float hapticMaxAmplitude = track->getHapticMaxAmplitude();
Lais Andradebc3f37a2021-07-02 00:13:19 +01005930 mAudioMixer->setParameter(
5931 trackId,
5932 AudioMixer::TRACK,
Andy Hung3ff4b552023-06-26 19:20:57 -07005933 AudioMixer::HAPTIC_MAX_AMPLITUDE, (void *)&hapticMaxAmplitude);
Eric Laurent81784c32012-11-19 14:55:58 -08005934
5935 // reset retry count
Andy Hung3ff4b552023-06-26 19:20:57 -07005936 track->retryCount() = kMaxTrackRetries;
Eric Laurent81784c32012-11-19 14:55:58 -08005937
5938 // If one track is ready, set the mixer ready if:
5939 // - the mixer was not ready during previous round OR
5940 // - no other track is not ready
5941 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
5942 mixerStatus != MIXER_TRACKS_ENABLED) {
5943 mixerStatus = MIXER_TRACKS_READY;
5944 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08005945
5946 // Enable the next few lines to instrument a test for underrun log handling.
5947 // TODO: Remove when we have a better way of testing the underrun log.
5948#if 0
5949 static int i;
5950 if ((++i & 0xf) == 0) {
5951 deferredOperations.tallyUnderrunFrames(track, 10 /* underrunFrames */);
5952 }
5953#endif
Eric Laurent81784c32012-11-19 14:55:58 -08005954 } else {
Andy Hungbd3b2b02018-05-21 10:53:11 -07005955 size_t underrunFrames = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005956 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Andy Hungb68f5eb2019-12-03 16:49:17 -08005957 ALOGV("track(%d) underrun, track state %s framesReady(%zu) < framesDesired(%zd)",
5958 trackId, track->getTrackStateAsString(), framesReady, desiredFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07005959 underrunFrames = desiredFrames;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005960 }
Andy Hungbd3b2b02018-05-21 10:53:11 -07005961 deferredOperations.tallyUnderrunFrames(track, underrunFrames);
Phil Burk2812d9e2016-01-04 10:34:30 -08005962
Eric Laurent81784c32012-11-19 14:55:58 -08005963 // clear effect chain input buffer if an active track underruns to avoid sending
5964 // previous audio buffer again to effects
5965 chain = getEffectChain_l(track->sessionId());
5966 if (chain != 0) {
5967 chain->clearInputBuffer();
5968 }
5969
Andy Hungc0691382018-09-12 18:01:57 -07005970 ALOGVV("track(%d) s=%08x [NOT READY] on thread %p", trackId, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08005971 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
5972 track->isStopped() || track->isPaused()) {
5973 // We have consumed all the buffers of this track.
5974 // Remove it from the list of active tracks.
5975 // TODO: use actual buffer filling status instead of latency when available from
5976 // audio HAL
5977 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08005978 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005979 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
5980 if (track->isStopped()) {
5981 track->reset();
5982 }
5983 tracksToRemove->add(track);
5984 }
5985 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08005986 // No buffers for this track. Give it a few chances to
5987 // fill a buffer, then remove it from active list.
Andy Hung3ff4b552023-06-26 19:20:57 -07005988 if (--(track->retryCount()) <= 0) {
Andy Hungc0691382018-09-12 18:01:57 -07005989 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p",
5990 trackId, this);
Eric Laurent81784c32012-11-19 14:55:58 -08005991 tracksToRemove->add(track);
5992 // indicate to client process that the track was disabled because of underrun;
5993 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08005994 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08005995 // If one track is not ready, mark the mixer also not ready if:
5996 // - the mixer was ready during previous round OR
5997 // - no other track is ready
5998 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
5999 mixerStatus != MIXER_TRACKS_READY) {
6000 mixerStatus = MIXER_TRACKS_ENABLED;
6001 }
6002 }
Andy Hungc0691382018-09-12 18:01:57 -07006003 mAudioMixer->disable(trackId);
Eric Laurent81784c32012-11-19 14:55:58 -08006004 }
6005
6006 } // local variable scope to avoid goto warning
Eric Laurent81784c32012-11-19 14:55:58 -08006007
6008 }
6009
jiabin245cdd92018-12-07 17:55:15 -08006010 if (mHapticChannelMask != AUDIO_CHANNEL_NONE && sq != NULL) {
6011 // When there is no fast track playing haptic and FastMixer exists,
6012 // enabling the first FastTrack, which provides mixed data from normal
6013 // tracks, to play haptic data.
6014 FastTrack *fastTrack = &state->mFastTracks[0];
6015 if (fastTrack->mHapticPlaybackEnabled != noFastHapticTrack) {
6016 fastTrack->mHapticPlaybackEnabled = noFastHapticTrack;
6017 didModify = true;
6018 }
6019 }
6020
Eric Laurent81784c32012-11-19 14:55:58 -08006021 // Push the new FastMixer state if necessary
Jing Mike537412f2023-03-12 11:01:47 +08006022 [[maybe_unused]] bool pauseAudioWatchdog = false;
Eric Laurent81784c32012-11-19 14:55:58 -08006023 if (didModify) {
6024 state->mFastTracksGen++;
6025 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
6026 if (kUseFastMixer == FastMixer_Dynamic &&
6027 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
6028 state->mCommand = FastMixerState::COLD_IDLE;
6029 state->mColdFutexAddr = &mFastMixerFutex;
6030 state->mColdGen++;
6031 mFastMixerFutex = 0;
6032 if (kUseFastMixer == FastMixer_Dynamic) {
6033 mNormalSink = mOutputSink;
6034 }
6035 // If we go into cold idle, need to wait for acknowledgement
6036 // so that fast mixer stops doing I/O.
6037 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
6038 pauseAudioWatchdog = true;
6039 }
Eric Laurent81784c32012-11-19 14:55:58 -08006040 }
6041 if (sq != NULL) {
6042 sq->end(didModify);
Andy Hungf2285312017-02-14 18:31:59 -08006043 // No need to block if the FastMixer is in COLD_IDLE as the FastThread
6044 // is not active. (We BLOCK_UNTIL_ACKED when entering COLD_IDLE
6045 // when bringing the output sink into standby.)
6046 //
6047 // We will get the latest FastMixer state when we come out of COLD_IDLE.
6048 //
6049 // This occurs with BT suspend when we idle the FastMixer with
6050 // active tracks, which may be added or removed.
6051 sq->push(coldIdle ? FastMixerStateQueue::BLOCK_NEVER : block);
Eric Laurent81784c32012-11-19 14:55:58 -08006052 }
6053#ifdef AUDIO_WATCHDOG
6054 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
6055 mAudioWatchdog->pause();
6056 }
6057#endif
6058
6059 // Now perform the deferred reset on fast tracks that have stopped
6060 while (resetMask != 0) {
6061 size_t i = __builtin_ctz(resetMask);
6062 ALOG_ASSERT(i < count);
6063 resetMask &= ~(1 << i);
Andy Hung3ff4b552023-06-26 19:20:57 -07006064 sp<IAfTrack> track = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08006065 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
6066 track->reset();
6067 }
6068
Andy Hung80d03d22018-04-10 10:32:11 -07006069 // Track destruction may occur outside of threadLoop once it is removed from active tracks.
6070 // Ensure the AudioMixer doesn't have a raw "buffer provider" pointer to the track if
6071 // it ceases to be active, to allow safe removal from the AudioMixer at the start
6072 // of prepareTracks_l(); this releases any outstanding buffer back to the track.
6073 // See also the implementation of destroyTrack_l().
6074 for (const auto &track : *tracksToRemove) {
Andy Hungc0691382018-09-12 18:01:57 -07006075 const int trackId = track->id();
6076 if (mAudioMixer->exists(trackId)) { // Normal tracks here, fast tracks in FastMixer.
6077 mAudioMixer->setBufferProvider(trackId, nullptr /* bufferProvider */);
Andy Hung80d03d22018-04-10 10:32:11 -07006078 }
6079 }
6080
Eric Laurent81784c32012-11-19 14:55:58 -08006081 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08006082 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08006083
Eric Laurentb3f315a2021-07-13 15:09:05 +02006084 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0 ||
6085 getEffectChain_l(AUDIO_SESSION_OUTPUT_STAGE) != 0) {
Eric Laurent97d547d2014-09-02 14:45:53 -07006086 mEffectBufferValid = true;
Marco Nelissenac302142014-10-20 13:15:38 -07006087 }
6088
6089 if (mEffectBufferValid) {
Marco Nelissen57088b52014-10-17 16:39:39 -07006090 // as long as there are effects we should clear the effects buffer, to avoid
6091 // passing a non-clean buffer to the effect chain
6092 memset(mEffectBuffer, 0, mEffectBufferSize);
Eric Laurentb62d0362021-10-26 17:40:18 +02006093 if (mType == SPATIALIZER) {
6094 memset(mPostSpatializerBuffer, 0, mPostSpatializerBufferSize);
6095 }
Eric Laurent97d547d2014-09-02 14:45:53 -07006096 }
Andy Hung69aed5f2014-02-25 17:24:40 -08006097 // sink or mix buffer must be cleared if all tracks are connected to an
6098 // effect chain as in this case the mixer will not write to the sink or mix buffer
6099 // and track effects will accumulate into it
Eric Laurent39095982021-08-24 18:29:27 +02006100 // always clear sink buffer for spatializer output as the output of the spatializer
6101 // effect will be accumulated into it
6102 if ((mBytesRemaining == 0) && (((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
6103 (mixedTracks == 0 && fastTracks > 0)) || (mType == SPATIALIZER))) {
Eric Laurent81784c32012-11-19 14:55:58 -08006104 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08006105 if (mMixerBufferValid) {
6106 memset(mMixerBuffer, 0, mMixerBufferSize);
6107 // TODO: In testing, mSinkBuffer below need not be cleared because
6108 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
6109 // after mixing.
6110 //
6111 // To enforce this guarantee:
6112 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
6113 // (mixedTracks == 0 && fastTracks > 0))
6114 // must imply MIXER_TRACKS_READY.
6115 // Later, we may clear buffers regardless, and skip much of this logic.
6116 }
Andy Hung98ef9782014-03-04 14:46:50 -08006117 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07006118 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08006119 }
6120
6121 // if any fast tracks, then status is ready
6122 mMixerStatusIgnoringFastTracks = mixerStatus;
6123 if (fastTracks > 0) {
6124 mixerStatus = MIXER_TRACKS_READY;
6125 }
6126 return mixerStatus;
6127}
6128
Eric Laurentad7dd962016-09-22 12:38:37 -07006129// trackCountForUid_l() must be called with ThreadBase::mLock held
Andy Hung71742ab2023-07-07 13:47:37 -07006130uint32_t PlaybackThread::trackCountForUid_l(uid_t uid) const
Eric Laurentad7dd962016-09-22 12:38:37 -07006131{
6132 uint32_t trackCount = 0;
6133 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hung1f12a8a2016-11-07 16:10:30 -08006134 if (mTracks[i]->uid() == uid) {
Eric Laurentad7dd962016-09-22 12:38:37 -07006135 trackCount++;
6136 }
6137 }
6138 return trackCount;
6139}
6140
Andy Hung71742ab2023-07-07 13:47:37 -07006141bool PlaybackThread::IsTimestampAdvancing::check(AudioStreamOut* output)
ziyangch8f194f12021-12-01 13:48:04 -08006142{
Brian Lindahl9e661ad2022-07-27 18:01:07 +02006143 // Check the timestamp to see if it's advancing once every 150ms. If we check too frequently, we
6144 // could falsely detect that the frame position has stalled due to underrun because we haven't
6145 // given the Audio HAL enough time to update.
6146 const nsecs_t nowNs = systemTime();
6147 if (nowNs - mPreviousNs < mMinimumTimeBetweenChecksNs) {
6148 return mLatchedValue;
6149 }
6150 mPreviousNs = nowNs;
6151 mLatchedValue = false;
6152 // Determine if the presentation position is still advancing.
ziyangch8f194f12021-12-01 13:48:04 -08006153 uint64_t position = 0;
6154 struct timespec unused;
Brian Lindahl9e661ad2022-07-27 18:01:07 +02006155 const status_t ret = output->getPresentationPosition(&position, &unused);
ziyangch8f194f12021-12-01 13:48:04 -08006156 if (ret == NO_ERROR) {
Brian Lindahl9e661ad2022-07-27 18:01:07 +02006157 if (position != mPreviousPosition) {
6158 mPreviousPosition = position;
6159 mLatchedValue = true;
ziyangch8f194f12021-12-01 13:48:04 -08006160 }
6161 }
Brian Lindahl9e661ad2022-07-27 18:01:07 +02006162 return mLatchedValue;
6163}
6164
Andy Hung71742ab2023-07-07 13:47:37 -07006165void PlaybackThread::IsTimestampAdvancing::clear()
Brian Lindahl9e661ad2022-07-27 18:01:07 +02006166{
6167 mLatchedValue = true;
6168 mPreviousPosition = 0;
6169 mPreviousNs = 0;
ziyangch8f194f12021-12-01 13:48:04 -08006170}
6171
Andy Hung1bc088a2018-02-09 15:57:31 -08006172// isTrackAllowed_l() must be called with ThreadBase::mLock held
Andy Hung71742ab2023-07-07 13:47:37 -07006173bool MixerThread::isTrackAllowed_l(
Andy Hung1bc088a2018-02-09 15:57:31 -08006174 audio_channel_mask_t channelMask, audio_format_t format,
6175 audio_session_t sessionId, uid_t uid) const
Eric Laurent81784c32012-11-19 14:55:58 -08006176{
Andy Hung1bc088a2018-02-09 15:57:31 -08006177 if (!PlaybackThread::isTrackAllowed_l(channelMask, format, sessionId, uid)) {
6178 return false;
Eric Laurentad7dd962016-09-22 12:38:37 -07006179 }
Andy Hung1bc088a2018-02-09 15:57:31 -08006180 // Check validity as we don't call AudioMixer::create() here.
Mikhail Naganov7ad7a252019-07-30 14:42:32 -07006181 if (!mAudioMixer->isValidFormat(format)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08006182 ALOGW("%s: invalid format: %#x", __func__, format);
6183 return false;
6184 }
Mikhail Naganov7ad7a252019-07-30 14:42:32 -07006185 if (!mAudioMixer->isValidChannelMask(channelMask)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08006186 ALOGW("%s: invalid channelMask: %#x", __func__, channelMask);
6187 return false;
6188 }
6189 return true;
Eric Laurent81784c32012-11-19 14:55:58 -08006190}
6191
Eric Laurent10351942014-05-08 18:49:52 -07006192// checkForNewParameter_l() must be called with ThreadBase::mLock held
Andy Hung71742ab2023-07-07 13:47:37 -07006193bool MixerThread::checkForNewParameter_l(const String8& keyValuePair,
Eric Laurent10351942014-05-08 18:49:52 -07006194 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08006195{
Eric Laurent81784c32012-11-19 14:55:58 -08006196 bool reconfig = false;
Eric Laurent10351942014-05-08 18:49:52 -07006197 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006198
Glenn Kastenc05b8d72016-03-24 09:48:17 -07006199 AutoPark<FastMixer> park(mFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08006200
Eric Laurent10351942014-05-08 18:49:52 -07006201 AudioParameter param = AudioParameter(keyValuePair);
6202 int value;
6203 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
6204 reconfig = true;
6205 }
6206 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung71742ab2023-07-07 13:47:37 -07006207 if (!AudioFlinger::isValidPcmSinkFormat(static_cast<audio_format_t>(value))) {
Eric Laurent10351942014-05-08 18:49:52 -07006208 status = BAD_VALUE;
6209 } else {
6210 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08006211 reconfig = true;
6212 }
Eric Laurent10351942014-05-08 18:49:52 -07006213 }
6214 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hung71742ab2023-07-07 13:47:37 -07006215 if (!AudioFlinger::isValidPcmSinkChannelMask(static_cast<audio_channel_mask_t>(value))) {
Eric Laurent10351942014-05-08 18:49:52 -07006216 status = BAD_VALUE;
6217 } else {
6218 // no need to save value, since it's constant
6219 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006220 }
Eric Laurent10351942014-05-08 18:49:52 -07006221 }
6222 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6223 // do not accept frame count changes if tracks are open as the track buffer
6224 // size depends on frame count and correct behavior would not be guaranteed
6225 // if frame count is changed after track creation
6226 if (!mTracks.isEmpty()) {
6227 status = INVALID_OPERATION;
6228 } else {
6229 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006230 }
Eric Laurent10351942014-05-08 18:49:52 -07006231 }
6232 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07006233 LOG_FATAL("Should not set routing device in MixerThread");
Eric Laurent10351942014-05-08 18:49:52 -07006234 }
Eric Laurent81784c32012-11-19 14:55:58 -08006235
Eric Laurent10351942014-05-08 18:49:52 -07006236 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006237 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07006238 if (!mStandby && status == INVALID_OPERATION) {
Andy Hungb72a5502023-03-27 15:53:06 -07006239 ALOGW("%s: setParameters failed with keyValuePair %s, entering standby",
6240 __func__, keyValuePair.c_str());
Phil Burk062e67a2015-02-11 13:40:50 -08006241 mOutput->standby();
Andy Hungb72a5502023-03-27 15:53:06 -07006242 mThreadMetrics.logEndInterval();
6243 mThreadSnapshot.onEnd();
Andy Hungdda7aed2023-03-27 15:53:06 -07006244 setStandby_l();
Eric Laurent10351942014-05-08 18:49:52 -07006245 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006246 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent81784c32012-11-19 14:55:58 -08006247 }
Eric Laurent10351942014-05-08 18:49:52 -07006248 if (status == NO_ERROR && reconfig) {
6249 readOutputParameters_l();
6250 delete mAudioMixer;
6251 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
Andy Hung1bc088a2018-02-09 15:57:31 -08006252 for (const auto &track : mTracks) {
Andy Hungc0691382018-09-12 18:01:57 -07006253 const int trackId = track->id();
Andy Hung71ba4b32022-10-06 12:09:49 -07006254 const status_t createStatus = mAudioMixer->create(
Andy Hungc0691382018-09-12 18:01:57 -07006255 trackId,
Andy Hung3ff4b552023-06-26 19:20:57 -07006256 track->channelMask(),
6257 track->format(),
6258 track->sessionId());
Andy Hung71ba4b32022-10-06 12:09:49 -07006259 ALOGW_IF(createStatus != NO_ERROR,
Andy Hungc0691382018-09-12 18:01:57 -07006260 "%s(): AudioMixer cannot create track(%d)"
6261 " mask %#x, format %#x, sessionId %d",
Andy Hung1bc088a2018-02-09 15:57:31 -08006262 __func__,
Andy Hung3ff4b552023-06-26 19:20:57 -07006263 trackId, track->channelMask(), track->format(), track->sessionId());
Eric Laurent10351942014-05-08 18:49:52 -07006264 }
Eric Laurent73e26b62015-04-27 16:55:58 -07006265 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07006266 }
Eric Laurent81784c32012-11-19 14:55:58 -08006267 }
6268
Dean Wheatley68918102021-03-19 22:09:19 +11006269 return reconfig;
Eric Laurent81784c32012-11-19 14:55:58 -08006270}
6271
6272
Andy Hung71742ab2023-07-07 13:47:37 -07006273void MixerThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -08006274{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07006275 PlaybackThread::dumpInternals_l(fd, args);
Andy Hung40eb1a12015-06-18 13:42:02 -07006276 dprintf(fd, " Thread throttle time (msecs): %u\n", mThreadThrottleTimeMs);
Andy Hung8ed196a2018-01-05 13:21:11 -08006277 dprintf(fd, " AudioMixer tracks: %s\n", mAudioMixer->trackNames().c_str());
Andy Hung2ddee192015-12-18 17:34:44 -08006278 dprintf(fd, " Master mono: %s\n", mMasterMono ? "on" : "off");
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006279 dprintf(fd, " Master balance: %f (%s)\n", mMasterBalance.load(),
6280 (hasFastMixer() ? std::to_string(mFastMixer->getMasterBalance())
6281 : mBalance.toString()).c_str());
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006282 if (hasFastMixer()) {
6283 dprintf(fd, " FastMixer thread %p tid=%d", mFastMixer.get(), mFastMixer->getTid());
6284
6285 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
6286 // while we are dumping it. It may be inconsistent, but it won't mutate!
6287 // This is a large object so we place it on the heap.
6288 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
Eric Tan2942a4e2018-09-12 17:41:27 -07006289 const std::unique_ptr<FastMixerDumpState> copy =
6290 std::make_unique<FastMixerDumpState>(mFastMixerDumpState);
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006291 copy->dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08006292
6293#ifdef STATE_QUEUE_DUMP
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006294 // Similar for state queue
6295 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
6296 observerCopy.dump(fd);
6297 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
6298 mutatorCopy.dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08006299#endif
6300
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006301#ifdef AUDIO_WATCHDOG
6302 if (mAudioWatchdog != 0) {
6303 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
6304 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
6305 wdCopy.dump(fd);
6306 }
6307#endif
6308
6309 } else {
6310 dprintf(fd, " No FastMixer\n");
6311 }
Eric Laurent90cea102023-05-15 15:08:27 +02006312
6313 dprintf(fd, "Bluetooth latency modes are %senabled\n",
6314 mBluetoothLatencyModesEnabled ? "" : "not ");
6315 dprintf(fd, "HAL does %ssupport Bluetooth latency modes\n", mOutput != nullptr &&
6316 mOutput->audioHwDev->supportsBluetoothVariableLatency() ? "" : "not ");
6317 dprintf(fd, "Supported latency modes: %s\n", toString(mSupportedLatencyModes).c_str());
Eric Laurent81784c32012-11-19 14:55:58 -08006318}
6319
Andy Hung71742ab2023-07-07 13:47:37 -07006320uint32_t MixerThread::idleSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08006321{
6322 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
6323}
6324
Andy Hung71742ab2023-07-07 13:47:37 -07006325uint32_t MixerThread::suspendSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08006326{
6327 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
6328}
6329
Andy Hung71742ab2023-07-07 13:47:37 -07006330void MixerThread::cacheParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08006331{
6332 PlaybackThread::cacheParameters_l();
6333
6334 // FIXME: Relaxed timing because of a certain device that can't meet latency
6335 // Should be reduced to 2x after the vendor fixes the driver issue
6336 // increase threshold again due to low power audio mode. The way this warning
6337 // threshold is calculated and its usefulness should be reconsidered anyway.
6338 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
6339}
6340
Andy Hung71742ab2023-07-07 13:47:37 -07006341void MixerThread::onHalLatencyModesChanged_l() {
Andy Hung2cbc2722023-07-17 17:05:00 -07006342 mAfThreadCallback->onSupportedLatencyModesChanged(mId, mSupportedLatencyModes);
Eric Laurentb0463942022-12-20 16:31:10 +01006343}
6344
Andy Hung71742ab2023-07-07 13:47:37 -07006345void MixerThread::setHalLatencyMode_l() {
Eric Laurentb0463942022-12-20 16:31:10 +01006346 // Only handle latency mode if:
6347 // - mBluetoothLatencyModesEnabled is true
6348 // - the HAL supports latency modes
6349 // - the selected device is Bluetooth LE or A2DP
6350 if (!mBluetoothLatencyModesEnabled.load() || mSupportedLatencyModes.empty()) {
6351 return;
6352 }
6353 if (mOutDeviceTypeAddrs.size() != 1
6354 || !(audio_is_a2dp_out_device(mOutDeviceTypeAddrs[0].mType)
6355 || audio_is_ble_out_device(mOutDeviceTypeAddrs[0].mType))) {
6356 return;
6357 }
6358
6359 audio_latency_mode_t latencyMode = AUDIO_LATENCY_MODE_FREE;
6360 if (mSupportedLatencyModes.size() == 1) {
6361 // If the HAL only support one latency mode currently, confirm the choice
6362 latencyMode = mSupportedLatencyModes[0];
6363 } else if (mSupportedLatencyModes.size() > 1) {
6364 // Request low latency if:
6365 // - At least one active track is either:
6366 // - a fast track with gaming usage or
6367 // - a track with acessibility usage
6368 for (const auto& track : mActiveTracks) {
6369 if ((track->isFastTrack() && track->attributes().usage == AUDIO_USAGE_GAME)
6370 || track->attributes().usage == AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY) {
6371 latencyMode = AUDIO_LATENCY_MODE_LOW;
6372 break;
6373 }
6374 }
6375 }
6376
6377 if (latencyMode != mSetLatencyMode) {
6378 status_t status = mOutput->stream->setLatencyMode(latencyMode);
6379 ALOGD("%s: thread(%d) setLatencyMode(%s) returned %d",
6380 __func__, mId, toString(latencyMode).c_str(), status);
6381 if (status == NO_ERROR) {
6382 mSetLatencyMode = latencyMode;
6383 }
6384 }
6385}
6386
Andy Hung71742ab2023-07-07 13:47:37 -07006387void MixerThread::updateHalSupportedLatencyModes_l() {
Eric Laurentb0463942022-12-20 16:31:10 +01006388
6389 if (mOutput == nullptr || mOutput->stream == nullptr) {
6390 return;
6391 }
6392 std::vector<audio_latency_mode_t> latencyModes;
6393 const status_t status = mOutput->stream->getRecommendedLatencyModes(&latencyModes);
6394 if (status != NO_ERROR) {
6395 latencyModes.clear();
6396 }
6397 if (latencyModes != mSupportedLatencyModes) {
6398 ALOGD("%s: thread(%d) status %d supported latency modes: %s",
6399 __func__, mId, status, toString(latencyModes).c_str());
6400 mSupportedLatencyModes.swap(latencyModes);
6401 sendHalLatencyModesChangedEvent_l();
6402 }
6403}
6404
Andy Hung71742ab2023-07-07 13:47:37 -07006405status_t MixerThread::getSupportedLatencyModes(
Eric Laurentb0463942022-12-20 16:31:10 +01006406 std::vector<audio_latency_mode_t>* modes) {
6407 if (modes == nullptr) {
6408 return BAD_VALUE;
6409 }
6410 Mutex::Autolock _l(mLock);
6411 *modes = mSupportedLatencyModes;
6412 return NO_ERROR;
6413}
6414
Andy Hung71742ab2023-07-07 13:47:37 -07006415void MixerThread::onRecommendedLatencyModeChanged(
Eric Laurentb0463942022-12-20 16:31:10 +01006416 std::vector<audio_latency_mode_t> modes) {
6417 Mutex::Autolock _l(mLock);
6418 if (modes != mSupportedLatencyModes) {
6419 ALOGD("%s: thread(%d) supported latency modes: %s",
6420 __func__, mId, toString(modes).c_str());
6421 mSupportedLatencyModes.swap(modes);
6422 sendHalLatencyModesChangedEvent_l();
6423 }
6424}
6425
Andy Hung71742ab2023-07-07 13:47:37 -07006426status_t MixerThread::setBluetoothVariableLatencyEnabled(bool enabled) {
Eric Laurentb0463942022-12-20 16:31:10 +01006427 if (mOutput == nullptr || mOutput->audioHwDev == nullptr
6428 || !mOutput->audioHwDev->supportsBluetoothVariableLatency()) {
6429 return INVALID_OPERATION;
6430 }
6431 mBluetoothLatencyModesEnabled.store(enabled);
6432 return NO_ERROR;
6433}
6434
Eric Laurent81784c32012-11-19 14:55:58 -08006435// ----------------------------------------------------------------------------
6436
Andy Hung71742ab2023-07-07 13:47:37 -07006437/* static */
6438sp<IAfPlaybackThread> IAfPlaybackThread::createDirectOutputThread(
Andy Hung2cbc2722023-07-17 17:05:00 -07006439 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hung71742ab2023-07-07 13:47:37 -07006440 AudioStreamOut* output, audio_io_handle_t id, bool systemReady,
6441 const audio_offload_info_t& offloadInfo) {
6442 return sp<DirectOutputThread>::make(
Andy Hung2cbc2722023-07-17 17:05:00 -07006443 afThreadCallback, output, id, systemReady, offloadInfo);
Andy Hung71742ab2023-07-07 13:47:37 -07006444}
6445
Andy Hung2cbc2722023-07-17 17:05:00 -07006446DirectOutputThread::DirectOutputThread(const sp<IAfThreadCallback>& afThreadCallback,
Gareth Fenn56576722022-10-05 13:42:36 -07006447 AudioStreamOut* output, audio_io_handle_t id, ThreadBase::type_t type, bool systemReady,
6448 const audio_offload_info_t& offloadInfo)
Andy Hung2cbc2722023-07-17 17:05:00 -07006449 : PlaybackThread(afThreadCallback, output, id, type, systemReady)
Gareth Fenn56576722022-10-05 13:42:36 -07006450 , mOffloadInfo(offloadInfo)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006451{
Andy Hung2cbc2722023-07-17 17:05:00 -07006452 setMasterBalance(afThreadCallback->getMasterBalance_l());
Eric Laurentbfb1b832013-01-07 09:53:42 -08006453}
6454
Andy Hung71742ab2023-07-07 13:47:37 -07006455DirectOutputThread::~DirectOutputThread()
Eric Laurent81784c32012-11-19 14:55:58 -08006456{
6457}
6458
Andy Hung71742ab2023-07-07 13:47:37 -07006459void DirectOutputThread::dumpInternals_l(int fd, const Vector<String16>& args)
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006460{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07006461 PlaybackThread::dumpInternals_l(fd, args);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006462 dprintf(fd, " Master balance: %f Left: %f Right: %f\n",
6463 mMasterBalance.load(), mMasterBalanceLeft, mMasterBalanceRight);
6464}
6465
Andy Hung71742ab2023-07-07 13:47:37 -07006466void DirectOutputThread::setMasterBalance(float balance)
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006467{
6468 Mutex::Autolock _l(mLock);
6469 if (mMasterBalance != balance) {
6470 mMasterBalance.store(balance);
6471 mBalance.computeStereoBalance(balance, &mMasterBalanceLeft, &mMasterBalanceRight);
6472 broadcast_l();
6473 }
6474}
6475
Andy Hung71742ab2023-07-07 13:47:37 -07006476void DirectOutputThread::processVolume_l(IAfTrack* track, bool lastTrack)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006477{
Eric Laurentbfb1b832013-01-07 09:53:42 -08006478 float left, right;
6479
Andy Hung333ab962019-05-28 20:23:35 -07006480 // Ensure volumeshaper state always advances even when muted.
Andy Hung3ff4b552023-06-26 19:20:57 -07006481 const sp<AudioTrackServerProxy> proxy = track->audioTrackServerProxy();
Andy Hungee86cee2022-12-13 19:19:53 -08006482
Andy Hungee86cee2022-12-13 19:19:53 -08006483 const int64_t frames = mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
6484 const int64_t time = mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
6485
Dean Wheatleyb11b0022023-09-12 04:07:35 +10006486 ALOGVV("%s: Direct/Offload bufferConsumed:%zu timestamp frames:%lld time:%lld",
6487 __func__, proxy->framesReleased(), (long long)frames, (long long)time);
Andy Hungee86cee2022-12-13 19:19:53 -08006488
6489 const int64_t volumeShaperFrames =
6490 mMonotonicFrameCounter.updateAndGetMonotonicFrameCount(frames, time);
6491 const auto [shaperVolume, shaperActive] =
6492 track->getVolumeHandler()->getVolume(volumeShaperFrames);
Andy Hung333ab962019-05-28 20:23:35 -07006493 mVolumeShaperActive = shaperActive;
6494
Vlad Popae2f5aef2022-07-25 16:00:20 +02006495 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
6496 left = float_from_gain(gain_minifloat_unpack_left(vlr));
6497 right = float_from_gain(gain_minifloat_unpack_right(vlr));
6498
6499 const bool clientVolumeMute = (left == 0.f && right == 0.f);
6500
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08006501 if (mMasterMute || mStreamTypes[track->streamType()].mute || track->isPlaybackRestricted()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08006502 left = right = 0;
6503 } else {
6504 float typeVolume = mStreamTypes[track->streamType()].volume;
Andy Hung333ab962019-05-28 20:23:35 -07006505 const float v = mMasterVolume * typeVolume * shaperVolume;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08006506
Glenn Kastenc56f3422014-03-21 17:53:17 -07006507 if (left > GAIN_FLOAT_UNITY) {
6508 left = GAIN_FLOAT_UNITY;
6509 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07006510 if (right > GAIN_FLOAT_UNITY) {
6511 right = GAIN_FLOAT_UNITY;
6512 }
zhangjincheng73e73872023-01-16 17:17:38 +08006513 left *= v;
6514 right *= v;
Andy Hung2cbc2722023-07-17 17:05:00 -07006515 if (mAfThreadCallback->getMode() != AUDIO_MODE_IN_COMMUNICATION
zhangjincheng73e73872023-01-16 17:17:38 +08006516 || audio_channel_count_from_out_mask(mChannelMask) > 1) {
6517 left *= mMasterBalanceLeft; // DirectOutputThread balance applied as track volume
6518 right *= mMasterBalanceRight;
6519 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006520 }
6521
Andy Hung2cbc2722023-07-17 17:05:00 -07006522 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
Vlad Popae8d99472022-06-30 16:02:48 +02006523 /*muteState=*/{mMasterMute,
6524 mStreamTypes[track->streamType()].volume == 0.f,
6525 mStreamTypes[track->streamType()].mute,
Vlad Popae2f5aef2022-07-25 16:00:20 +02006526 track->isPlaybackRestricted(),
Vlad Popa436c9172022-08-02 15:25:08 +02006527 clientVolumeMute,
6528 shaperVolume == 0.f});
Vlad Popae8d99472022-06-30 16:02:48 +02006529
Eric Laurentbfb1b832013-01-07 09:53:42 -08006530 if (lastTrack) {
jiabin76d94692022-12-15 21:51:21 +00006531 track->setFinalVolume(left, right);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006532 if (left != mLeftVolFloat || right != mRightVolFloat) {
6533 mLeftVolFloat = left;
6534 mRightVolFloat = right;
6535
Eric Laurentbfb1b832013-01-07 09:53:42 -08006536 // Delegate volume control to effect in track effect chain if needed
6537 // only one effect chain can be present on DirectOutputThread, so if
6538 // there is one, the track is connected to it
6539 if (!mEffectChains.isEmpty()) {
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09006540 // if effect chain exists, volume is handled by it.
6541 // Convert volumes from float to 8.24
6542 uint32_t vl = (uint32_t)(left * (1 << 24));
6543 uint32_t vr = (uint32_t)(right * (1 << 24));
6544 // Direct/Offload effect chains set output volume in setVolume_l().
6545 (void)mEffectChains[0]->setVolume_l(&vl, &vr);
6546 } else {
6547 // otherwise we directly set the volume.
6548 setVolumeForOutput_l(left, right);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006549 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006550 }
6551 }
6552}
6553
Andy Hung71742ab2023-07-07 13:47:37 -07006554void DirectOutputThread::onAddNewTrack_l()
Phil Burk43b4dcc2015-06-09 16:53:44 -07006555{
Andy Hung3ff4b552023-06-26 19:20:57 -07006556 sp<IAfTrack> previousTrack = mPreviousTrack.promote();
6557 sp<IAfTrack> latestTrack = mActiveTracks.getLatest();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006558
Eric Laurent0f0631e2015-07-06 18:01:25 -07006559 if (previousTrack != 0 && latestTrack != 0) {
6560 if (mType == DIRECT) {
6561 if (previousTrack.get() != latestTrack.get()) {
6562 mFlushPending = true;
6563 }
6564 } else /* mType == OFFLOAD */ {
Dean Wheatley0f51fd02022-08-31 16:41:40 +10006565 if (previousTrack->sessionId() != latestTrack->sessionId() ||
6566 previousTrack->isFlushPending()) {
Eric Laurent0f0631e2015-07-06 18:01:25 -07006567 mFlushPending = true;
6568 }
6569 }
Revathi Uddaraju20413a92016-10-13 17:16:14 +08006570 } else if (previousTrack == 0) {
6571 // there could be an old track added back during track transition for direct
6572 // output, so always issues flush to flush data of the previous track if it
6573 // was already destroyed with HAL paused, then flush can resume the playback
6574 mFlushPending = true;
Phil Burk43b4dcc2015-06-09 16:53:44 -07006575 }
6576 PlaybackThread::onAddNewTrack_l();
6577}
Eric Laurentbfb1b832013-01-07 09:53:42 -08006578
Andy Hung71742ab2023-07-07 13:47:37 -07006579PlaybackThread::mixer_state DirectOutputThread::prepareTracks_l(
Andy Hung3ff4b552023-06-26 19:20:57 -07006580 Vector<sp<IAfTrack>>* tracksToRemove
Eric Laurent81784c32012-11-19 14:55:58 -08006581)
6582{
Eric Laurentd595b7c2013-04-03 17:27:56 -07006583 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08006584 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006585 bool doHwPause = false;
6586 bool doHwResume = false;
Eric Laurent81784c32012-11-19 14:55:58 -08006587
6588 // find out which tracks need to be processed
Andy Hung3ff4b552023-06-26 19:20:57 -07006589 for (const sp<IAfTrack>& t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08006590 if (t->isInvalid()) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07006591 ALOGW("An invalidated track shouldn't be in active list");
Eric Laurent5850c4c2016-11-10 13:04:31 -08006592 tracksToRemove->add(t);
Phil Burk43b4dcc2015-06-09 16:53:44 -07006593 continue;
6594 }
6595
Andy Hung3ff4b552023-06-26 19:20:57 -07006596 IAfTrack* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006597#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurent81784c32012-11-19 14:55:58 -08006598 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006599#endif
Eric Laurentfd477972013-10-25 18:10:40 -07006600 // Only consider last track started for volume and mixer state control.
6601 // In theory an older track could underrun and restart after the new one starts
6602 // but as we only care about the transition phase between two tracks on a
6603 // direct output, it is not a problem to ignore the underrun case.
Andy Hung3ff4b552023-06-26 19:20:57 -07006604 sp<IAfTrack> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08006605 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08006606
Kuowei Li23666472021-01-20 10:23:25 +08006607 if (track->isPausePending()) {
6608 track->pauseAck();
6609 // It is possible a track might have been flushed or stopped.
6610 // Other operations such as flush pending might occur on the next prepare.
6611 if (track->isPausing()) {
6612 track->setPaused();
6613 }
6614 // Always perform pause, as an immediate flush will change
6615 // the pause state to be no longer isPausing().
Phil Burk6fc2a7c2015-04-30 16:08:10 -07006616 if (mHwSupportsPause && last && !mHwPaused) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006617 doHwPause = true;
6618 mHwPaused = true;
6619 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08006620 } else if (track->isFlushPending()) {
6621 track->flushAck();
6622 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07006623 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006624 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07006625 } else if (track->isResumePending()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006626 track->resumeAck();
Eric Laurent3df841a2016-07-15 15:15:40 -07006627 if (last) {
6628 mLeftVolFloat = mRightVolFloat = -1.0;
6629 if (mHwPaused) {
6630 doHwResume = true;
6631 mHwPaused = false;
6632 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08006633 }
6634 }
6635
Eric Laurent81784c32012-11-19 14:55:58 -08006636 // The first time a track is added we wait
Phil Burk99adee32014-12-10 16:46:30 -08006637 // for all its buffers to be filled before processing it.
6638 // Allow draining the buffer in case the client
6639 // app does not call stop() and relies on underrun to stop:
Andy Hung3ff4b552023-06-26 19:20:57 -07006640 // hence the test on (track->retryCount() > 1).
6641 // If track->retryCount() <= 1 then track is about to be disabled, paused, removed,
Andy Hung455982f2021-04-27 17:46:12 -07006642 // so we accept any nonzero amount of data delivered by the AudioTrack (which will
6643 // reset the retry counter).
Phil Burkca5e6142015-07-14 09:42:29 -07006644 // Do not use a high threshold for compressed audio.
Andy Hung455982f2021-04-27 17:46:12 -07006645
6646 // target retry count that we will use is based on the time we wait for retries.
6647 const int32_t targetRetryCount = kMaxTrackRetriesDirectMs * 1000 / mActiveSleepTimeUs;
6648 // the retry threshold is when we accept any size for PCM data. This is slightly
6649 // smaller than the retry count so we can push small bits of data without a glitch.
6650 const int32_t retryThreshold = targetRetryCount > 2 ? targetRetryCount - 1 : 1;
Eric Laurent81784c32012-11-19 14:55:58 -08006651 uint32_t minFrames;
Phil Burk99adee32014-12-10 16:46:30 -08006652 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
Andy Hung3ff4b552023-06-26 19:20:57 -07006653 && (track->retryCount() > retryThreshold) && audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006654 minFrames = mNormalFrameCount;
6655 } else {
6656 minFrames = 1;
6657 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006658
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07006659 const size_t framesReady = track->framesReady();
6660 const int trackId = track->id();
6661 if (ATRACE_ENABLED()) {
6662 std::string traceName("nRdy");
6663 traceName += std::to_string(trackId);
6664 ATRACE_INT(traceName.c_str(), framesReady);
6665 }
6666 if ((framesReady >= minFrames) && track->isReady() && !track->isPaused() &&
Eric Laurentab5cdba2014-06-09 17:22:27 -07006667 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08006668 {
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07006669 ALOGVV("track(%d) s=%08x [OK]", trackId, cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08006670
Andy Hung3ff4b552023-06-26 19:20:57 -07006671 if (track->fillingStatus() == IAfTrack::FS_FILLED) {
6672 track->fillingStatus() = IAfTrack::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07006673 if (last) {
6674 // make sure processVolume_l() will apply new volume even if 0
6675 mLeftVolFloat = mRightVolFloat = -1.0;
6676 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08006677 if (!mHwSupportsPause) {
6678 track->resumeAck();
Eric Laurent81784c32012-11-19 14:55:58 -08006679 }
6680 }
6681
6682 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08006683 processVolume_l(track, last);
6684 if (last) {
Andy Hung3ff4b552023-06-26 19:20:57 -07006685 sp<IAfTrack> previousTrack = mPreviousTrack.promote();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006686 if (previousTrack != 0) {
6687 if (track != previousTrack.get()) {
6688 // Flush any data still being written from last track
6689 mBytesRemaining = 0;
Eric Laurent0f0631e2015-07-06 18:01:25 -07006690 // Invalidate previous track to force a seek when resuming.
6691 previousTrack->invalidate();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006692 }
6693 }
6694 mPreviousTrack = track;
6695
Eric Laurentd595b7c2013-04-03 17:27:56 -07006696 // reset retry count
Andy Hung3ff4b552023-06-26 19:20:57 -07006697 track->retryCount() = targetRetryCount;
Eric Laurent5850c4c2016-11-10 13:04:31 -08006698 mActiveTrack = t;
Eric Laurentd595b7c2013-04-03 17:27:56 -07006699 mixerStatus = MIXER_TRACKS_READY;
Eric Laurent5cff4032015-05-26 13:49:58 -07006700 if (mHwPaused) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08006701 doHwResume = true;
6702 mHwPaused = false;
6703 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07006704 }
Eric Laurent81784c32012-11-19 14:55:58 -08006705 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07006706 // clear effect chain input buffer if the last active track started underruns
6707 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07006708 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08006709 mEffectChains[0]->clearInputBuffer();
6710 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07006711 if (track->isStopping_1()) {
Andy Hung3ff4b552023-06-26 19:20:57 -07006712 track->setState(IAfTrackBase::STOPPING_2);
Eric Laurentb369caf2015-03-30 20:51:47 -07006713 if (last && mHwPaused) {
6714 doHwResume = true;
6715 mHwPaused = false;
6716 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07006717 }
6718 if ((track->sharedBuffer() != 0) || track->isStopped() ||
6719 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08006720 // We have consumed all the buffers of this track.
6721 // Remove it from the list of active tracks.
Atneya Nair0cae0432022-05-10 18:12:12 -04006722 bool presComplete = false;
Eric Laurentfd477972013-10-25 18:10:40 -07006723 if (mStandby || !last ||
Atneya Nair0cae0432022-05-10 18:12:12 -04006724 (presComplete = track->presentationComplete(latency_l())) ||
Jindong32dc26e2019-11-11 18:10:01 +08006725 track->isPaused() || mHwPaused) {
Atneya Nair0cae0432022-05-10 18:12:12 -04006726 if (presComplete) {
6727 mOutput->presentationComplete();
6728 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07006729 if (track->isStopping_2()) {
Andy Hung3ff4b552023-06-26 19:20:57 -07006730 track->setState(IAfTrackBase::STOPPED);
Eric Laurentab5cdba2014-06-09 17:22:27 -07006731 }
Eric Laurent81784c32012-11-19 14:55:58 -08006732 if (track->isStopped()) {
6733 track->reset();
6734 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07006735 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08006736 }
6737 } else {
6738 // No buffers for this track. Give it a few chances to
6739 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07006740 // Only consider last track started for mixer state control
Brian Lindahl9e661ad2022-07-27 18:01:07 +02006741 bool isTimestampAdvancing = mIsTimestampAdvancing.check(mOutput);
Gareth Fenn56576722022-10-05 13:42:36 -07006742 if (!isTunerStream() // tuner streams remain active in underrun
Andy Hung3ff4b552023-06-26 19:20:57 -07006743 && --(track->retryCount()) <= 0) {
Brian Lindahl9e661ad2022-07-27 18:01:07 +02006744 if (isTimestampAdvancing) { // HAL is still playing audio, give us more time.
Andy Hung3ff4b552023-06-26 19:20:57 -07006745 track->retryCount() = kMaxTrackRetriesOffload;
ziyangch8f194f12021-12-01 13:48:04 -08006746 } else {
6747 ALOGV("BUFFER TIMEOUT: remove track(%d) from active list", trackId);
6748 tracksToRemove->add(track);
6749 // indicate to client process that the track was disabled because of
6750 // underrun; it will then automatically call start() when data is available
6751 track->disable();
6752 // only do hw pause when track is going to be removed due to BUFFER TIMEOUT.
6753 // unlike mixerthread, HAL can be paused for direct output
6754 ALOGW("pause because of UNDERRUN, framesReady = %zu,"
6755 "minFrames = %u, mFormat = %#x",
6756 framesReady, minFrames, mFormat);
6757 if (last && mHwSupportsPause && !mHwPaused && !mStandby) {
6758 doHwPause = true;
6759 mHwPaused = true;
6760 }
Eric Laurent0f7b5f22014-12-19 10:43:21 -08006761 }
Haynes Mathew George5c6daae2017-01-24 20:06:05 -08006762 } else if (last) {
6763 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurent81784c32012-11-19 14:55:58 -08006764 }
6765 }
6766 }
6767 }
6768
Eric Laurentd1f69b02014-12-15 14:33:13 -08006769 // if an active track did not command a flush, check for pending flush on stopped tracks
Phil Burk43b4dcc2015-06-09 16:53:44 -07006770 if (!mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006771 for (size_t i = 0; i < mTracks.size(); i++) {
6772 if (mTracks[i]->isFlushPending()) {
6773 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006774 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006775 }
6776 }
6777 }
6778
6779 // make sure the pause/flush/resume sequence is executed in the right order.
6780 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
6781 // before flush and then resume HW. This can happen in case of pause/flush/resume
6782 // if resume is received before pause is executed.
6783 if (mHwSupportsPause && !mStandby &&
Phil Burk43b4dcc2015-06-09 16:53:44 -07006784 (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006785 status_t result = mOutput->stream->pause();
6786 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Gareth Fenncd1e1622022-10-05 11:45:45 -07006787 doHwResume = !doHwPause; // resume if pause is due to flush.
Eric Laurentd1f69b02014-12-15 14:33:13 -08006788 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07006789 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006790 flushHw_l();
6791 }
6792 if (mHwSupportsPause && !mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006793 status_t result = mOutput->stream->resume();
6794 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08006795 }
Eric Laurent81784c32012-11-19 14:55:58 -08006796 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08006797 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08006798
6799 return mixerStatus;
6800}
6801
Andy Hung71742ab2023-07-07 13:47:37 -07006802void DirectOutputThread::threadLoop_mix()
Eric Laurent81784c32012-11-19 14:55:58 -08006803{
Eric Laurent81784c32012-11-19 14:55:58 -08006804 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08006805 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08006806 // output audio to hardware
6807 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07006808 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08006809 buffer.frameCount = frameCount;
Phil Burk062e67a2015-02-11 13:40:50 -08006810 status_t status = mActiveTrack->getNextBuffer(&buffer);
6811 if (status != NO_ERROR || buffer.raw == NULL) {
Eric Laurent51716182016-02-29 18:00:56 -08006812 // no need to pad with 0 for compressed audio
6813 if (audio_has_proportional_frames(mFormat)) {
6814 memset(curBuf, 0, frameCount * mFrameSize);
6815 }
Eric Laurent81784c32012-11-19 14:55:58 -08006816 break;
6817 }
6818 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
6819 frameCount -= buffer.frameCount;
6820 curBuf += buffer.frameCount * mFrameSize;
6821 mActiveTrack->releaseBuffer(&buffer);
6822 }
Andy Hung2098f272014-02-27 14:00:06 -08006823 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006824 mSleepTimeUs = 0;
6825 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08006826 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08006827}
6828
Andy Hung71742ab2023-07-07 13:47:37 -07006829void DirectOutputThread::threadLoop_sleepTime()
Eric Laurent81784c32012-11-19 14:55:58 -08006830{
Eric Laurentd1f69b02014-12-15 14:33:13 -08006831 // do not write to HAL when paused
Eric Laurent0f7b5f22014-12-19 10:43:21 -08006832 if (mHwPaused || (usesHwAvSync() && mStandby)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006833 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006834 return;
6835 }
Andy Hung85ba3332021-04-27 17:40:26 -07006836 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
6837 mSleepTimeUs = mActiveSleepTimeUs;
6838 } else {
6839 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006840 }
Andy Hung85ba3332021-04-27 17:40:26 -07006841 // Note: In S or later, we do not write zeroes for
6842 // linear or proportional PCM direct tracks in underrun.
Eric Laurent81784c32012-11-19 14:55:58 -08006843}
6844
Andy Hung71742ab2023-07-07 13:47:37 -07006845void DirectOutputThread::threadLoop_exit()
Eric Laurentd1f69b02014-12-15 14:33:13 -08006846{
6847 {
6848 Mutex::Autolock _l(mLock);
Eric Laurentd1f69b02014-12-15 14:33:13 -08006849 for (size_t i = 0; i < mTracks.size(); i++) {
6850 if (mTracks[i]->isFlushPending()) {
6851 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006852 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006853 }
6854 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07006855 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006856 flushHw_l();
6857 }
6858 }
6859 PlaybackThread::threadLoop_exit();
6860}
6861
6862// must be called with thread mutex locked
Andy Hung71742ab2023-07-07 13:47:37 -07006863bool DirectOutputThread::shouldStandby_l()
Eric Laurentd1f69b02014-12-15 14:33:13 -08006864{
6865 bool trackPaused = false;
Eric Laurentb369caf2015-03-30 20:51:47 -07006866 bool trackStopped = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006867
6868 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
6869 // after a timeout and we will enter standby then.
6870 if (mTracks.size() > 0) {
6871 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
Eric Laurentb369caf2015-03-30 20:51:47 -07006872 trackStopped = mTracks[mTracks.size() - 1]->isStopped() ||
Andy Hung3ff4b552023-06-26 19:20:57 -07006873 mTracks[mTracks.size() - 1]->state() == IAfTrackBase::IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006874 }
6875
Eric Laurent5cff4032015-05-26 13:49:58 -07006876 return !mStandby && !(trackPaused || (mHwPaused && !trackStopped));
Eric Laurentd1f69b02014-12-15 14:33:13 -08006877}
6878
Eric Laurent10351942014-05-08 18:49:52 -07006879// checkForNewParameter_l() must be called with ThreadBase::mLock held
Andy Hung71742ab2023-07-07 13:47:37 -07006880bool DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
Eric Laurent10351942014-05-08 18:49:52 -07006881 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08006882{
6883 bool reconfig = false;
Eric Laurent10351942014-05-08 18:49:52 -07006884 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006885
Eric Laurent10351942014-05-08 18:49:52 -07006886 AudioParameter param = AudioParameter(keyValuePair);
6887 int value;
6888 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07006889 LOG_FATAL("Should not set routing device in DirectOutputThread");
Eric Laurent81784c32012-11-19 14:55:58 -08006890 }
Eric Laurent10351942014-05-08 18:49:52 -07006891 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6892 // do not accept frame count changes if tracks are open as the track buffer
6893 // size depends on frame count and correct behavior would not be garantied
6894 // if frame count is changed after track creation
6895 if (!mTracks.isEmpty()) {
6896 status = INVALID_OPERATION;
6897 } else {
6898 reconfig = true;
6899 }
6900 }
6901 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006902 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07006903 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08006904 mOutput->standby();
Andy Hungcf10d742020-04-28 15:38:24 -07006905 if (!mStandby) {
6906 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07006907 mThreadSnapshot.onEnd();
Eric Laurent19952e12023-04-20 10:08:29 +02006908 setStandby_l();
Andy Hungcf10d742020-04-28 15:38:24 -07006909 }
Eric Laurent10351942014-05-08 18:49:52 -07006910 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006911 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07006912 }
6913 if (status == NO_ERROR && reconfig) {
6914 readOutputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07006915 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07006916 }
6917 }
6918
Dean Wheatley68918102021-03-19 22:09:19 +11006919 return reconfig;
Eric Laurent81784c32012-11-19 14:55:58 -08006920}
6921
Andy Hung71742ab2023-07-07 13:47:37 -07006922uint32_t DirectOutputThread::activeSleepTimeUs() 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 = PlaybackThread::activeSleepTimeUs();
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 Hung71742ab2023-07-07 13:47:37 -07006933uint32_t DirectOutputThread::idleSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08006934{
6935 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08006936 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006937 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
6938 } else {
Eric Laurent51716182016-02-29 18:00:56 -08006939 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006940 }
6941 return time;
6942}
6943
Andy Hung71742ab2023-07-07 13:47:37 -07006944uint32_t DirectOutputThread::suspendSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08006945{
6946 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08006947 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006948 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
6949 } else {
Eric Laurent51716182016-02-29 18:00:56 -08006950 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006951 }
6952 return time;
6953}
6954
Andy Hung71742ab2023-07-07 13:47:37 -07006955void DirectOutputThread::cacheParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08006956{
6957 PlaybackThread::cacheParameters_l();
6958
6959 // use shorter standby delay as on normal output to release
6960 // hardware resources as soon as possible
Eric Laurentb369caf2015-03-30 20:51:47 -07006961 // no delay on outputs with HW A/V sync
6962 if (usesHwAvSync()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006963 mStandbyDelayNs = 0;
Phil Burkfdb3c072016-02-09 10:47:02 -08006964 } else if ((mType == OFFLOAD) && !audio_has_proportional_frames(mFormat)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006965 mStandbyDelayNs = kOffloadStandbyDelayNs;
Eric Laurent5cff4032015-05-26 13:49:58 -07006966 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006967 mStandbyDelayNs = microseconds(mActiveSleepTimeUs*2);
Eric Laurent972a1732013-09-04 09:42:59 -07006968 }
Eric Laurent81784c32012-11-19 14:55:58 -08006969}
6970
Andy Hung71742ab2023-07-07 13:47:37 -07006971void DirectOutputThread::flushHw_l()
Eric Laurente659ef42014-09-29 13:06:46 -07006972{
ziyangch8f194f12021-12-01 13:48:04 -08006973 PlaybackThread::flushHw_l();
Phil Burk062e67a2015-02-11 13:40:50 -08006974 mOutput->flush();
Eric Laurentd1f69b02014-12-15 14:33:13 -08006975 mHwPaused = false;
Phil Burk43b4dcc2015-06-09 16:53:44 -07006976 mFlushPending = false;
Dean Wheatley12473e92021-03-18 23:00:55 +11006977 mTimestampVerifier.discontinuity(discontinuityForStandbyOrFlush());
Sampath Shetty999f0e82020-01-15 10:19:06 +11006978 mTimestamp.clear();
Andy Hungee86cee2022-12-13 19:19:53 -08006979 mMonotonicFrameCounter.onFlush();
Eric Laurente659ef42014-09-29 13:06:46 -07006980}
6981
Andy Hung71742ab2023-07-07 13:47:37 -07006982int64_t DirectOutputThread::computeWaitTimeNs_l() const {
Andy Hung10cbff12017-02-21 17:30:14 -08006983 // If a VolumeShaper is active, we must wake up periodically to update volume.
6984 const int64_t NS_PER_MS = 1000000;
6985 return mVolumeShaperActive ?
6986 kMinNormalSinkBufferSizeMs * NS_PER_MS : PlaybackThread::computeWaitTimeNs_l();
6987}
6988
Eric Laurent81784c32012-11-19 14:55:58 -08006989// ----------------------------------------------------------------------------
6990
Andy Hung71742ab2023-07-07 13:47:37 -07006991AsyncCallbackThread::AsyncCallbackThread(
6992 const wp<PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006993 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07006994 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07006995 mWriteAckSequence(0),
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006996 mDrainSequence(0),
6997 mAsyncError(false)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006998{
6999}
7000
Andy Hung71742ab2023-07-07 13:47:37 -07007001void AsyncCallbackThread::onFirstRef()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007002{
7003 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
7004}
7005
Andy Hung71742ab2023-07-07 13:47:37 -07007006bool AsyncCallbackThread::threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007007{
7008 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07007009 uint32_t writeAckSequence;
7010 uint32_t drainSequence;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007011 bool asyncError;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007012
7013 {
7014 Mutex::Autolock _l(mLock);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08007015 while (!((mWriteAckSequence & 1) ||
7016 (mDrainSequence & 1) ||
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007017 mAsyncError ||
Haynes Mathew George24a325d2013-12-03 21:26:02 -08007018 exitPending())) {
7019 mWaitWorkCV.wait(mLock);
7020 }
7021
Eric Laurentbfb1b832013-01-07 09:53:42 -08007022 if (exitPending()) {
7023 break;
7024 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07007025 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
7026 mWriteAckSequence, mDrainSequence);
7027 writeAckSequence = mWriteAckSequence;
7028 mWriteAckSequence &= ~1;
7029 drainSequence = mDrainSequence;
7030 mDrainSequence &= ~1;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007031 asyncError = mAsyncError;
7032 mAsyncError = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007033 }
7034 {
Andy Hung71742ab2023-07-07 13:47:37 -07007035 const sp<PlaybackThread> playbackThread = mPlaybackThread.promote();
Eric Laurent4de95592013-09-26 15:28:21 -07007036 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07007037 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07007038 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007039 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07007040 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07007041 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007042 }
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007043 if (asyncError) {
7044 playbackThread->onAsyncError();
7045 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007046 }
7047 }
7048 }
7049 return false;
7050}
7051
Andy Hung71742ab2023-07-07 13:47:37 -07007052void AsyncCallbackThread::exit()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007053{
7054 ALOGV("AsyncCallbackThread::exit");
7055 Mutex::Autolock _l(mLock);
7056 requestExit();
7057 mWaitWorkCV.broadcast();
7058}
7059
Andy Hung71742ab2023-07-07 13:47:37 -07007060void AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08007061{
7062 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07007063 // bit 0 is cleared
7064 mWriteAckSequence = sequence << 1;
7065}
7066
Andy Hung71742ab2023-07-07 13:47:37 -07007067void AsyncCallbackThread::resetWriteBlocked()
Eric Laurent3b4529e2013-09-05 18:09:19 -07007068{
7069 Mutex::Autolock _l(mLock);
7070 // ignore unexpected callbacks
7071 if (mWriteAckSequence & 2) {
7072 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007073 mWaitWorkCV.signal();
7074 }
7075}
7076
Andy Hung71742ab2023-07-07 13:47:37 -07007077void AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08007078{
7079 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07007080 // bit 0 is cleared
7081 mDrainSequence = sequence << 1;
7082}
7083
Andy Hung71742ab2023-07-07 13:47:37 -07007084void AsyncCallbackThread::resetDraining()
Eric Laurent3b4529e2013-09-05 18:09:19 -07007085{
7086 Mutex::Autolock _l(mLock);
7087 // ignore unexpected callbacks
7088 if (mDrainSequence & 2) {
7089 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007090 mWaitWorkCV.signal();
7091 }
7092}
7093
Andy Hung71742ab2023-07-07 13:47:37 -07007094void AsyncCallbackThread::setAsyncError()
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007095{
7096 Mutex::Autolock _l(mLock);
7097 mAsyncError = true;
7098 mWaitWorkCV.signal();
7099}
7100
Eric Laurentbfb1b832013-01-07 09:53:42 -08007101
7102// ----------------------------------------------------------------------------
Andy Hung71742ab2023-07-07 13:47:37 -07007103
7104/* static */
7105sp<IAfPlaybackThread> IAfPlaybackThread::createOffloadThread(
Andy Hung2cbc2722023-07-17 17:05:00 -07007106 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hung71742ab2023-07-07 13:47:37 -07007107 AudioStreamOut* output, audio_io_handle_t id, bool systemReady,
7108 const audio_offload_info_t& offloadInfo) {
Andy Hung2cbc2722023-07-17 17:05:00 -07007109 return sp<OffloadThread>::make(afThreadCallback, output, id, systemReady, offloadInfo);
Andy Hung71742ab2023-07-07 13:47:37 -07007110}
7111
Andy Hung2cbc2722023-07-17 17:05:00 -07007112OffloadThread::OffloadThread(const sp<IAfThreadCallback>& afThreadCallback,
Gareth Fenn56576722022-10-05 13:42:36 -07007113 AudioStreamOut* output, audio_io_handle_t id, bool systemReady,
7114 const audio_offload_info_t& offloadInfo)
Andy Hung2cbc2722023-07-17 17:05:00 -07007115 : DirectOutputThread(afThreadCallback, output, id, OFFLOAD, systemReady, offloadInfo),
ziyangch8f194f12021-12-01 13:48:04 -08007116 mPausedWriteLength(0), mPausedBytesRemaining(0), mKeepWakeLock(true)
Eric Laurentbfb1b832013-01-07 09:53:42 -08007117{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07007118 //FIXME: mStandby should be set to true by ThreadBase constructo
Eric Laurentfd477972013-10-25 18:10:40 -07007119 mStandby = true;
Eric Laurent64667972016-03-30 18:19:46 -07007120 mKeepWakeLock = property_get_bool("ro.audio.offload_wakelock", true /* default_value */);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007121}
7122
Andy Hung71742ab2023-07-07 13:47:37 -07007123void OffloadThread::threadLoop_exit()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007124{
7125 if (mFlushPending || mHwPaused) {
7126 // If a flush is pending or track was paused, just discard buffered data
7127 flushHw_l();
7128 } else {
7129 mMixerStatus = MIXER_DRAIN_ALL;
7130 threadLoop_drain();
7131 }
Uday Gupta56604aa2014-05-13 11:19:17 -07007132 if (mUseAsyncWrite) {
7133 ALOG_ASSERT(mCallbackThread != 0);
7134 mCallbackThread->exit();
7135 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007136 PlaybackThread::threadLoop_exit();
7137}
7138
Andy Hung71742ab2023-07-07 13:47:37 -07007139PlaybackThread::mixer_state OffloadThread::prepareTracks_l(
Andy Hung3ff4b552023-06-26 19:20:57 -07007140 Vector<sp<IAfTrack>>* tracksToRemove
Eric Laurentbfb1b832013-01-07 09:53:42 -08007141)
7142{
Eric Laurentbfb1b832013-01-07 09:53:42 -08007143 size_t count = mActiveTracks.size();
7144
7145 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07007146 bool doHwPause = false;
7147 bool doHwResume = false;
7148
Glenn Kastenc42e9b42016-03-21 11:35:03 -07007149 ALOGV("OffloadThread::prepareTracks_l active tracks %zu", count);
Eric Laurentede6c3b2013-09-19 14:37:46 -07007150
Eric Laurentbfb1b832013-01-07 09:53:42 -08007151 // find out which tracks need to be processed
Andy Hung3ff4b552023-06-26 19:20:57 -07007152 for (const sp<IAfTrack>& t : mActiveTracks) {
7153 IAfTrack* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07007154#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurentbfb1b832013-01-07 09:53:42 -08007155 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07007156#endif
Eric Laurentfd477972013-10-25 18:10:40 -07007157 // Only consider last track started for volume and mixer state control.
7158 // In theory an older track could underrun and restart after the new one starts
7159 // but as we only care about the transition phase between two tracks on a
7160 // direct output, it is not a problem to ignore the underrun case.
Andy Hung3ff4b552023-06-26 19:20:57 -07007161 sp<IAfTrack> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08007162 bool last = l.get() == track;
Eric Laurentfd477972013-10-25 18:10:40 -07007163
Haynes Mathew George7844f672014-01-15 12:32:55 -08007164 if (track->isInvalid()) {
7165 ALOGW("An invalidated track shouldn't be in active list");
7166 tracksToRemove->add(track);
7167 continue;
7168 }
7169
Andy Hung3ff4b552023-06-26 19:20:57 -07007170 if (track->state() == IAfTrackBase::IDLE) {
Haynes Mathew George7844f672014-01-15 12:32:55 -08007171 ALOGW("An idle track shouldn't be in active list");
7172 continue;
7173 }
7174
Kuowei Li23666472021-01-20 10:23:25 +08007175 if (track->isPausePending()) {
7176 track->pauseAck();
7177 // It is possible a track might have been flushed or stopped.
7178 // Other operations such as flush pending might occur on the next prepare.
7179 if (track->isPausing()) {
7180 track->setPaused();
7181 }
7182 // Always perform pause if last, as an immediate flush will change
7183 // the pause state to be no longer isPausing().
Eric Laurentbfb1b832013-01-07 09:53:42 -08007184 if (last) {
Eric Laurent5cff4032015-05-26 13:49:58 -07007185 if (mHwSupportsPause && !mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07007186 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007187 mHwPaused = true;
7188 }
7189 // If we were part way through writing the mixbuffer to
7190 // the HAL we must save this until we resume
7191 // BUG - this will be wrong if a different track is made active,
7192 // in that case we want to discard the pending data in the
7193 // mixbuffer and tell the client to present it again when the
7194 // track is resumed
7195 mPausedWriteLength = mCurrentWriteLength;
7196 mPausedBytesRemaining = mBytesRemaining;
7197 mBytesRemaining = 0; // stop writing
7198 }
7199 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08007200 } else if (track->isFlushPending()) {
Eric Laurente93cc032016-05-05 10:15:10 -07007201 if (track->isStopping_1()) {
Andy Hung3ff4b552023-06-26 19:20:57 -07007202 track->retryCount() = kMaxTrackStopRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07007203 } else {
Andy Hung3ff4b552023-06-26 19:20:57 -07007204 track->retryCount() = kMaxTrackRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07007205 }
Haynes Mathew George7844f672014-01-15 12:32:55 -08007206 track->flushAck();
7207 if (last) {
7208 mFlushPending = true;
7209 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08007210 } else if (track->isResumePending()){
7211 track->resumeAck();
7212 if (last) {
7213 if (mPausedBytesRemaining) {
7214 // Need to continue write that was interrupted
7215 mCurrentWriteLength = mPausedWriteLength;
7216 mBytesRemaining = mPausedBytesRemaining;
7217 mPausedBytesRemaining = 0;
7218 }
7219 if (mHwPaused) {
7220 doHwResume = true;
7221 mHwPaused = false;
7222 // threadLoop_mix() will handle the case that we need to
7223 // resume an interrupted write
7224 }
7225 // enable write to audio HAL
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007226 mSleepTimeUs = 0;
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08007227
Eric Laurent3df841a2016-07-15 15:15:40 -07007228 mLeftVolFloat = mRightVolFloat = -1.0;
7229
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08007230 // Do not handle new data in this iteration even if track->framesReady()
7231 mixerStatus = MIXER_TRACKS_ENABLED;
7232 }
7233 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07007234 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Andy Hungc0691382018-09-12 18:01:57 -07007235 ALOGVV("OffloadThread: track(%d) s=%08x [OK]", track->id(), cblk->mServer);
Andy Hung3ff4b552023-06-26 19:20:57 -07007236 if (track->fillingStatus() == IAfTrack::FS_FILLED) {
7237 track->fillingStatus() = IAfTrack::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07007238 if (last) {
7239 // make sure processVolume_l() will apply new volume even if 0
7240 mLeftVolFloat = mRightVolFloat = -1.0;
7241 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007242 }
7243
7244 if (last) {
Andy Hung3ff4b552023-06-26 19:20:57 -07007245 sp<IAfTrack> previousTrack = mPreviousTrack.promote();
Eric Laurentd7e59222013-11-15 12:02:28 -08007246 if (previousTrack != 0) {
7247 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08007248 // Flush any data still being written from last track
7249 mBytesRemaining = 0;
7250 if (mPausedBytesRemaining) {
7251 // Last track was paused so we also need to flush saved
7252 // mixbuffer state and invalidate track so that it will
7253 // re-submit that unwritten data when it is next resumed
7254 mPausedBytesRemaining = 0;
7255 // Invalidate is a bit drastic - would be more efficient
7256 // to have a flag to tell client that some of the
7257 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08007258 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08007259 }
7260 // flush data already sent to the DSP if changing audio session as audio
7261 // comes from a different source. Also invalidate previous track to force a
7262 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08007263 if (previousTrack->sessionId() != track->sessionId()) {
7264 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08007265 }
7266 }
7267 }
7268 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007269 // reset retry count
Eric Laurente93cc032016-05-05 10:15:10 -07007270 if (track->isStopping_1()) {
Andy Hung3ff4b552023-06-26 19:20:57 -07007271 track->retryCount() = kMaxTrackStopRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07007272 } else {
Andy Hung3ff4b552023-06-26 19:20:57 -07007273 track->retryCount() = kMaxTrackRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07007274 }
Eric Laurent5850c4c2016-11-10 13:04:31 -08007275 mActiveTrack = t;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007276 mixerStatus = MIXER_TRACKS_READY;
7277 }
7278 } else {
Andy Hungc0691382018-09-12 18:01:57 -07007279 ALOGVV("OffloadThread: track(%d) s=%08x [NOT READY]", track->id(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007280 if (track->isStopping_1()) {
Andy Hung3ff4b552023-06-26 19:20:57 -07007281 if (--(track->retryCount()) <= 0) {
Eric Laurente93cc032016-05-05 10:15:10 -07007282 // Hardware buffer can hold a large amount of audio so we must
7283 // wait for all current track's data to drain before we say
7284 // that the track is stopped.
7285 if (mBytesRemaining == 0) {
7286 // Only start draining when all data in mixbuffer
7287 // has been written
7288 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
Andy Hung3ff4b552023-06-26 19:20:57 -07007289 track->setState(IAfTrackBase::STOPPING_2);
7290 // so presentation completes after
Eric Laurente93cc032016-05-05 10:15:10 -07007291 // drain do not drain if no data was ever sent to HAL (mStandby == true)
7292 if (last && !mStandby) {
7293 // do not modify drain sequence if we are already draining. This happens
7294 // when resuming from pause after drain.
7295 if ((mDrainSequence & 1) == 0) {
7296 mSleepTimeUs = 0;
7297 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
7298 mixerStatus = MIXER_DRAIN_TRACK;
7299 mDrainSequence += 2;
7300 }
7301 if (mHwPaused) {
7302 // It is possible to move from PAUSED to STOPPING_1 without
7303 // a resume so we must ensure hardware is running
7304 doHwResume = true;
7305 mHwPaused = false;
7306 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007307 }
7308 }
Eric Laurente93cc032016-05-05 10:15:10 -07007309 } else if (last) {
Andy Hung3ff4b552023-06-26 19:20:57 -07007310 ALOGV("stopping1 underrun retries left %d", track->retryCount());
Eric Laurente93cc032016-05-05 10:15:10 -07007311 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007312 }
7313 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07007314 // Drain has completed or we are in standby, signal presentation complete
7315 if (!(mDrainSequence & 1) || !last || mStandby) {
Andy Hung3ff4b552023-06-26 19:20:57 -07007316 track->setState(IAfTrackBase::STOPPED);
Atneya Nair0cae0432022-05-10 18:12:12 -04007317 mOutput->presentationComplete();
7318 track->presentationComplete(latency_l()); // always returns true
Eric Laurentbfb1b832013-01-07 09:53:42 -08007319 track->reset();
7320 tracksToRemove->add(track);
Dean Wheatley12473e92021-03-18 23:00:55 +11007321 // OFFLOADED stop resets frame counts.
Andy Hungf3234512018-07-03 14:51:47 -07007322 if (!mUseAsyncWrite) {
7323 // If we don't get explicit drain notification we must
7324 // register discontinuity regardless of whether this is
7325 // the previous (!last) or the upcoming (last) track
7326 // to avoid skipping the discontinuity.
Dean Wheatley12473e92021-03-18 23:00:55 +11007327 mTimestampVerifier.discontinuity(
7328 mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Andy Hungf3234512018-07-03 14:51:47 -07007329 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007330 }
7331 } else {
7332 // No buffers for this track. Give it a few chances to
7333 // fill a buffer, then remove it from active list.
Brian Lindahl9e661ad2022-07-27 18:01:07 +02007334 bool isTimestampAdvancing = mIsTimestampAdvancing.check(mOutput);
Gareth Fenn56576722022-10-05 13:42:36 -07007335 if (!isTunerStream() // tuner streams remain active in underrun
Andy Hung3ff4b552023-06-26 19:20:57 -07007336 && --(track->retryCount()) <= 0) {
Brian Lindahl9e661ad2022-07-27 18:01:07 +02007337 if (isTimestampAdvancing) { // HAL is still playing audio, give us more time.
Andy Hung3ff4b552023-06-26 19:20:57 -07007338 track->retryCount() = kMaxTrackRetriesOffload;
Andy Hungf8044752016-07-27 14:58:11 -07007339 } else {
Andy Hungc0691382018-09-12 18:01:57 -07007340 ALOGV("OffloadThread: BUFFER TIMEOUT: remove track(%d) from active list",
7341 track->id());
Andy Hungf8044752016-07-27 14:58:11 -07007342 tracksToRemove->add(track);
Glenn Kastend3bb6452016-12-05 18:14:37 -08007343 // tell client process that the track was disabled because of underrun;
Andy Hungf8044752016-07-27 14:58:11 -07007344 // it will then automatically call start() when data is available
7345 track->disable();
7346 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007347 } else if (last){
7348 mixerStatus = MIXER_TRACKS_ENABLED;
7349 }
7350 }
7351 }
7352 // compute volume for this track
Wenfeng Sun79458332019-05-29 20:12:43 +08007353 if (track->isReady()) { // check ready to prevent premature start.
7354 processVolume_l(track, last);
7355 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007356 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007357
Eric Laurentea0fade2013-10-04 16:23:48 -07007358 // make sure the pause/flush/resume sequence is executed in the right order.
7359 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
7360 // before flush and then resume HW. This can happen in case of pause/flush/resume
7361 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07007362 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007363 status_t result = mOutput->stream->pause();
7364 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Gareth Fenncd1e1622022-10-05 11:45:45 -07007365 doHwResume = !doHwPause; // resume if pause is due to flush.
Eric Laurent972a1732013-09-04 09:42:59 -07007366 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007367 if (mFlushPending) {
7368 flushHw_l();
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007369 }
Eric Laurentfd477972013-10-25 18:10:40 -07007370 if (!mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007371 status_t result = mOutput->stream->resume();
7372 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07007373 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007374
Eric Laurentbfb1b832013-01-07 09:53:42 -08007375 // remove all the tracks that need to be...
7376 removeTracks_l(*tracksToRemove);
7377
7378 return mixerStatus;
7379}
7380
Eric Laurentbfb1b832013-01-07 09:53:42 -08007381// must be called with thread mutex locked
Andy Hung71742ab2023-07-07 13:47:37 -07007382bool OffloadThread::waitingAsyncCallback_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007383{
Eric Laurent3b4529e2013-09-05 18:09:19 -07007384 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
7385 mWriteAckSequence, mDrainSequence);
7386 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08007387 return true;
7388 }
7389 return false;
7390}
7391
Andy Hung71742ab2023-07-07 13:47:37 -07007392bool OffloadThread::waitingAsyncCallback()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007393{
7394 Mutex::Autolock _l(mLock);
7395 return waitingAsyncCallback_l();
7396}
7397
Andy Hung71742ab2023-07-07 13:47:37 -07007398void OffloadThread::flushHw_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007399{
Eric Laurente659ef42014-09-29 13:06:46 -07007400 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08007401 // Flush anything still waiting in the mixbuffer
7402 mCurrentWriteLength = 0;
7403 mBytesRemaining = 0;
7404 mPausedWriteLength = 0;
7405 mPausedBytesRemaining = 0;
Eric Laurent3eaf66b2016-04-01 14:44:17 -07007406 // reset bytes written count to reflect that DSP buffers are empty after flush.
7407 mBytesWritten = 0;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08007408
Eric Laurentbfb1b832013-01-07 09:53:42 -08007409 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07007410 // discard any pending drain or write ack by incrementing sequence
7411 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
7412 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007413 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07007414 mCallbackThread->setWriteBlocked(mWriteAckSequence);
7415 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007416 }
7417}
7418
Andy Hung71742ab2023-07-07 13:47:37 -07007419void OffloadThread::invalidateTracks(audio_stream_type_t streamType)
Haynes Mathew George05317d22016-05-03 16:34:26 -07007420{
7421 Mutex::Autolock _l(mLock);
Eric Laurent13084622016-05-17 10:51:49 -07007422 if (PlaybackThread::invalidateTracks_l(streamType)) {
7423 mFlushPending = true;
7424 }
Haynes Mathew George05317d22016-05-03 16:34:26 -07007425}
7426
Andy Hung71742ab2023-07-07 13:47:37 -07007427void OffloadThread::invalidateTracks(std::set<audio_port_handle_t>& portIds) {
jiabinc44b3462022-12-08 12:52:31 -08007428 Mutex::Autolock _l(mLock);
7429 if (PlaybackThread::invalidateTracks_l(portIds)) {
7430 mFlushPending = true;
7431 }
7432}
7433
Eric Laurentbfb1b832013-01-07 09:53:42 -08007434// ----------------------------------------------------------------------------
7435
Andy Hung71742ab2023-07-07 13:47:37 -07007436/* static */
7437sp<IAfDuplicatingThread> IAfDuplicatingThread::create(
Andy Hung2cbc2722023-07-17 17:05:00 -07007438 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hung71742ab2023-07-07 13:47:37 -07007439 IAfPlaybackThread* mainThread, audio_io_handle_t id, bool systemReady) {
Andy Hung2cbc2722023-07-17 17:05:00 -07007440 return sp<DuplicatingThread>::make(afThreadCallback, mainThread, id, systemReady);
Andy Hung71742ab2023-07-07 13:47:37 -07007441}
7442
Andy Hung2cbc2722023-07-17 17:05:00 -07007443DuplicatingThread::DuplicatingThread(const sp<IAfThreadCallback>& afThreadCallback,
Andy Hung44f27182023-07-06 20:56:16 -07007444 IAfPlaybackThread* mainThread, audio_io_handle_t id, bool systemReady)
Andy Hung2cbc2722023-07-17 17:05:00 -07007445 : MixerThread(afThreadCallback, mainThread->getOutput(), id,
Eric Laurent72e3f392015-05-20 14:43:50 -07007446 systemReady, DUPLICATING),
Eric Laurent81784c32012-11-19 14:55:58 -08007447 mWaitTimeMs(UINT_MAX)
7448{
7449 addOutputTrack(mainThread);
7450}
7451
Andy Hung71742ab2023-07-07 13:47:37 -07007452DuplicatingThread::~DuplicatingThread()
Eric Laurent81784c32012-11-19 14:55:58 -08007453{
7454 for (size_t i = 0; i < mOutputTracks.size(); i++) {
7455 mOutputTracks[i]->destroy();
7456 }
7457}
7458
Andy Hung71742ab2023-07-07 13:47:37 -07007459void DuplicatingThread::threadLoop_mix()
Eric Laurent81784c32012-11-19 14:55:58 -08007460{
7461 // mix buffers...
Andy Hung71ba4b32022-10-06 12:09:49 -07007462 if (outputsReady()) {
Glenn Kastend79072e2016-01-06 08:41:20 -08007463 mAudioMixer->process();
Eric Laurent81784c32012-11-19 14:55:58 -08007464 } else {
Eric Laurent02b57082014-11-07 17:28:28 -08007465 if (mMixerBufferValid) {
7466 memset(mMixerBuffer, 0, mMixerBufferSize);
7467 } else {
7468 memset(mSinkBuffer, 0, mSinkBufferSize);
7469 }
Eric Laurent81784c32012-11-19 14:55:58 -08007470 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007471 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007472 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08007473 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007474 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08007475}
7476
Andy Hung71742ab2023-07-07 13:47:37 -07007477void DuplicatingThread::threadLoop_sleepTime()
Eric Laurent81784c32012-11-19 14:55:58 -08007478{
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007479 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08007480 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007481 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007482 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007483 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007484 }
7485 } else if (mBytesWritten != 0) {
7486 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
7487 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08007488 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08007489 } else {
7490 // flush remaining overflow buffers in output tracks
7491 writeFrames = 0;
7492 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007493 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007494 }
7495}
7496
Andy Hung71742ab2023-07-07 13:47:37 -07007497ssize_t DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08007498{
7499 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hung1c86ebe2018-05-29 20:29:08 -07007500 const ssize_t actualWritten = outputTracks[i]->write(mSinkBuffer, writeFrames);
7501
7502 // Consider the first OutputTrack for timestamp and frame counting.
7503
7504 // The threadLoop() generally assumes writing a full sink buffer size at a time.
7505 // Here, we correct for writeFrames of 0 (a stop) or underruns because
7506 // we always claim success.
7507 if (i == 0) {
7508 const ssize_t correction = mSinkBufferSize / mFrameSize - actualWritten;
7509 ALOGD_IF(correction != 0 && writeFrames != 0,
7510 "%s: writeFrames:%u actualWritten:%zd correction:%zd mFramesWritten:%lld",
7511 __func__, writeFrames, actualWritten, correction, (long long)mFramesWritten);
7512 mFramesWritten -= correction;
7513 }
7514
7515 // TODO: Report correction for the other output tracks and show in the dump.
Eric Laurent81784c32012-11-19 14:55:58 -08007516 }
Andy Hungcf10d742020-04-28 15:38:24 -07007517 if (mStandby) {
7518 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07007519 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -07007520 mStandby = false;
7521 }
Andy Hung25c2dac2014-02-27 14:56:00 -08007522 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08007523}
7524
Andy Hung71742ab2023-07-07 13:47:37 -07007525void DuplicatingThread::threadLoop_standby()
Eric Laurent81784c32012-11-19 14:55:58 -08007526{
7527 // DuplicatingThread implements standby by stopping all tracks
7528 for (size_t i = 0; i < outputTracks.size(); i++) {
7529 outputTracks[i]->stop();
7530 }
7531}
7532
Andy Hung71742ab2023-07-07 13:47:37 -07007533void DuplicatingThread::dumpInternals_l(int fd, const Vector<String16>& args)
Andy Hung1bc088a2018-02-09 15:57:31 -08007534{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07007535 MixerThread::dumpInternals_l(fd, args);
Andy Hung1bc088a2018-02-09 15:57:31 -08007536
7537 std::stringstream ss;
7538 const size_t numTracks = mOutputTracks.size();
7539 ss << " " << numTracks << " OutputTracks";
7540 if (numTracks > 0) {
7541 ss << ":";
7542 for (const auto &track : mOutputTracks) {
Andy Hung44f27182023-07-06 20:56:16 -07007543 const auto thread = track->thread().promote();
Andy Hungc0691382018-09-12 18:01:57 -07007544 ss << " (" << track->id() << " : ";
Andy Hung1bc088a2018-02-09 15:57:31 -08007545 if (thread.get() != nullptr) {
7546 ss << thread.get() << ", " << thread->id();
7547 } else {
7548 ss << "null";
7549 }
7550 ss << ")";
7551 }
7552 }
7553 ss << "\n";
7554 std::string result = ss.str();
7555 write(fd, result.c_str(), result.size());
7556}
7557
Andy Hung71742ab2023-07-07 13:47:37 -07007558void DuplicatingThread::saveOutputTracks()
Eric Laurent81784c32012-11-19 14:55:58 -08007559{
7560 outputTracks = mOutputTracks;
7561}
7562
Andy Hung71742ab2023-07-07 13:47:37 -07007563void DuplicatingThread::clearOutputTracks()
Eric Laurent81784c32012-11-19 14:55:58 -08007564{
7565 outputTracks.clear();
7566}
7567
Andy Hung71742ab2023-07-07 13:47:37 -07007568void DuplicatingThread::addOutputTrack(IAfPlaybackThread* thread)
Eric Laurent81784c32012-11-19 14:55:58 -08007569{
7570 Mutex::Autolock _l(mLock);
Andy Hungc25b84a2015-01-14 19:04:10 -08007571 // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
7572 // Adjust for thread->sampleRate() to determine minimum buffer frame count.
7573 // Then triple buffer because Threads do not run synchronously and may not be clock locked.
7574 const size_t frameCount =
7575 3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
7576 // TODO: Consider asynchronous sample rate conversion to handle clock disparity
7577 // from different OutputTracks and their associated MixerThreads (e.g. one may
7578 // nearly empty and the other may be dropping data).
7579
Svet Ganov33761132021-05-13 22:51:08 +00007580 // TODO b/182392769: use attribution source util, move to server edge
7581 AttributionSourceState attributionSource = AttributionSourceState();
7582 attributionSource.uid = VALUE_OR_FATAL(legacy2aidl_uid_t_int32_t(
Philip P. Moltmannbda45752020-07-17 16:41:18 -07007583 IPCThreadState::self()->getCallingUid()));
Svet Ganov33761132021-05-13 22:51:08 +00007584 attributionSource.pid = VALUE_OR_FATAL(legacy2aidl_pid_t_int32_t(
Philip P. Moltmannbda45752020-07-17 16:41:18 -07007585 IPCThreadState::self()->getCallingPid()));
Svet Ganov33761132021-05-13 22:51:08 +00007586 attributionSource.token = sp<BBinder>::make();
Andy Hung3ff4b552023-06-26 19:20:57 -07007587 sp<IAfOutputTrack> outputTrack = IAfOutputTrack::create(thread,
Eric Laurent81784c32012-11-19 14:55:58 -08007588 this,
7589 mSampleRate,
Andy Hungc25b84a2015-01-14 19:04:10 -08007590 mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08007591 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08007592 frameCount,
Svet Ganov33761132021-05-13 22:51:08 +00007593 attributionSource);
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07007594 status_t status = outputTrack != 0 ? outputTrack->initCheck() : (status_t) NO_MEMORY;
7595 if (status != NO_ERROR) {
7596 ALOGE("addOutputTrack() initCheck failed %d", status);
7597 return;
Eric Laurent81784c32012-11-19 14:55:58 -08007598 }
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07007599 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
7600 mOutputTracks.add(outputTrack);
7601 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
7602 updateWaitTime_l();
Eric Laurent81784c32012-11-19 14:55:58 -08007603}
7604
Andy Hung71742ab2023-07-07 13:47:37 -07007605void DuplicatingThread::removeOutputTrack(IAfPlaybackThread* thread)
Eric Laurent81784c32012-11-19 14:55:58 -08007606{
7607 Mutex::Autolock _l(mLock);
7608 for (size_t i = 0; i < mOutputTracks.size(); i++) {
7609 if (mOutputTracks[i]->thread() == thread) {
7610 mOutputTracks[i]->destroy();
7611 mOutputTracks.removeAt(i);
7612 updateWaitTime_l();
Eric Laurentf6870ae2015-05-08 10:50:03 -07007613 if (thread->getOutput() == mOutput) {
7614 mOutput = NULL;
7615 }
Eric Laurent81784c32012-11-19 14:55:58 -08007616 return;
7617 }
7618 }
Eric Laurentf6870ae2015-05-08 10:50:03 -07007619 ALOGV("removeOutputTrack(): unknown thread: %p", thread);
Eric Laurent81784c32012-11-19 14:55:58 -08007620}
7621
7622// caller must hold mLock
Andy Hung71742ab2023-07-07 13:47:37 -07007623void DuplicatingThread::updateWaitTime_l()
Eric Laurent81784c32012-11-19 14:55:58 -08007624{
7625 mWaitTimeMs = UINT_MAX;
7626 for (size_t i = 0; i < mOutputTracks.size(); i++) {
Andy Hung44f27182023-07-06 20:56:16 -07007627 const auto strong = mOutputTracks[i]->thread().promote();
Eric Laurent81784c32012-11-19 14:55:58 -08007628 if (strong != 0) {
7629 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
7630 if (waitTimeMs < mWaitTimeMs) {
7631 mWaitTimeMs = waitTimeMs;
7632 }
7633 }
7634 }
7635}
7636
Andy Hung71742ab2023-07-07 13:47:37 -07007637bool DuplicatingThread::outputsReady()
Eric Laurent81784c32012-11-19 14:55:58 -08007638{
7639 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hung44f27182023-07-06 20:56:16 -07007640 const auto thread = outputTracks[i]->thread().promote();
Eric Laurent81784c32012-11-19 14:55:58 -08007641 if (thread == 0) {
7642 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
7643 outputTracks[i].get());
7644 return false;
7645 }
Andy Hung44f27182023-07-06 20:56:16 -07007646 IAfPlaybackThread* const playbackThread = thread->asIAfPlaybackThread().get();
Eric Laurent81784c32012-11-19 14:55:58 -08007647 // see note at standby() declaration
Andy Hung4989d312023-06-29 21:19:25 -07007648 if (playbackThread->inStandby() && !playbackThread->isSuspended()) {
Eric Laurent81784c32012-11-19 14:55:58 -08007649 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
7650 thread.get());
7651 return false;
7652 }
7653 }
7654 return true;
7655}
7656
Andy Hung71742ab2023-07-07 13:47:37 -07007657void DuplicatingThread::sendMetadataToBackend_l(
Kevin Rocard12381092018-04-11 09:19:59 -07007658 const StreamOutHalInterface::SourceMetadata& metadata)
Kevin Rocard069c2712018-03-29 19:09:14 -07007659{
Kevin Rocard12381092018-04-11 09:19:59 -07007660 for (auto& outputTrack : outputTracks) { // not mOutputTracks
7661 outputTrack->setMetadatas(metadata.tracks);
7662 }
Kevin Rocard069c2712018-03-29 19:09:14 -07007663}
7664
Andy Hung71742ab2023-07-07 13:47:37 -07007665uint32_t DuplicatingThread::activeSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08007666{
7667 return (mWaitTimeMs * 1000) / 2;
7668}
7669
Andy Hung71742ab2023-07-07 13:47:37 -07007670void DuplicatingThread::cacheParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08007671{
7672 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
7673 updateWaitTime_l();
7674
7675 MixerThread::cacheParameters_l();
7676}
7677
Eric Laurentb3f315a2021-07-13 15:09:05 +02007678// ----------------------------------------------------------------------------
7679
Andy Hung71742ab2023-07-07 13:47:37 -07007680/* static */
7681sp<IAfPlaybackThread> IAfPlaybackThread::createSpatializerThread(
Andy Hung2cbc2722023-07-17 17:05:00 -07007682 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hung71742ab2023-07-07 13:47:37 -07007683 AudioStreamOut* output,
7684 audio_io_handle_t id,
7685 bool systemReady,
7686 audio_config_base_t* mixerConfig) {
Andy Hung2cbc2722023-07-17 17:05:00 -07007687 return sp<SpatializerThread>::make(afThreadCallback, output, id, systemReady, mixerConfig);
Andy Hung71742ab2023-07-07 13:47:37 -07007688}
7689
Andy Hung2cbc2722023-07-17 17:05:00 -07007690SpatializerThread::SpatializerThread(const sp<IAfThreadCallback>& afThreadCallback,
Eric Laurentb3f315a2021-07-13 15:09:05 +02007691 AudioStreamOut* output,
7692 audio_io_handle_t id,
7693 bool systemReady,
7694 audio_config_base_t *mixerConfig)
Andy Hung2cbc2722023-07-17 17:05:00 -07007695 : MixerThread(afThreadCallback, output, id, systemReady, SPATIALIZER, mixerConfig)
Eric Laurentb3f315a2021-07-13 15:09:05 +02007696{
7697}
7698
Andy Hung71742ab2023-07-07 13:47:37 -07007699void SpatializerThread::onFirstRef() {
Eric Laurentb0463942022-12-20 16:31:10 +01007700 MixerThread::onFirstRef();
Andy Hungfeb4e5c2022-10-17 19:10:02 -07007701
Andy Hung41ccf7f2022-12-14 14:25:49 -08007702 const pid_t tid = getTid();
7703 if (tid == -1) {
7704 // Unusual: PlaybackThread::onFirstRef() should set the threadLoop running.
7705 ALOGW("%s: Cannot update Spatializer mixer thread priority, not running", __func__);
7706 } else {
7707 const int priorityBoost = requestSpatializerPriority(getpid(), tid);
7708 if (priorityBoost > 0) {
Andy Hungfeb4e5c2022-10-17 19:10:02 -07007709 stream()->setHalThreadPriority(priorityBoost);
7710 }
7711 }
Eric Laurent6f9534f2022-05-03 18:15:04 +02007712}
7713
Andy Hung71742ab2023-07-07 13:47:37 -07007714void SpatializerThread::setHalLatencyMode_l() {
Eric Laurent6f9534f2022-05-03 18:15:04 +02007715 // if mSupportedLatencyModes is empty, the HAL stream does not support
7716 // latency mode control and we can exit.
7717 if (mSupportedLatencyModes.empty()) {
7718 return;
7719 }
7720 audio_latency_mode_t latencyMode = AUDIO_LATENCY_MODE_FREE;
7721 if (mSupportedLatencyModes.size() == 1) {
7722 // If the HAL only support one latency mode currently, confirm the choice
7723 latencyMode = mSupportedLatencyModes[0];
7724 } else if (mSupportedLatencyModes.size() > 1) {
7725 // Request low latency if:
7726 // - The low latency mode is requested by the spatializer controller
7727 // (mRequestedLatencyMode = AUDIO_LATENCY_MODE_LOW)
7728 // AND
7729 // - At least one active track is spatialized
7730 bool hasSpatializedActiveTrack = false;
7731 for (const auto& track : mActiveTracks) {
7732 if (track->isSpatialized()) {
7733 hasSpatializedActiveTrack = true;
7734 break;
7735 }
7736 }
7737 if (hasSpatializedActiveTrack && mRequestedLatencyMode == AUDIO_LATENCY_MODE_LOW) {
7738 latencyMode = AUDIO_LATENCY_MODE_LOW;
7739 }
7740 }
7741
7742 if (latencyMode != mSetLatencyMode) {
7743 status_t status = mOutput->stream->setLatencyMode(latencyMode);
Andy Hung4bd53e72022-11-17 17:21:45 -08007744 ALOGD("%s: thread(%d) setLatencyMode(%s) returned %d",
7745 __func__, mId, toString(latencyMode).c_str(), status);
Eric Laurent6f9534f2022-05-03 18:15:04 +02007746 if (status == NO_ERROR) {
7747 mSetLatencyMode = latencyMode;
7748 }
7749 }
7750}
7751
Andy Hung71742ab2023-07-07 13:47:37 -07007752status_t SpatializerThread::setRequestedLatencyMode(audio_latency_mode_t mode) {
Eric Laurent6f9534f2022-05-03 18:15:04 +02007753 if (mode != AUDIO_LATENCY_MODE_LOW && mode != AUDIO_LATENCY_MODE_FREE) {
7754 return BAD_VALUE;
7755 }
7756 Mutex::Autolock _l(mLock);
7757 mRequestedLatencyMode = mode;
7758 return NO_ERROR;
7759}
7760
Andy Hung71742ab2023-07-07 13:47:37 -07007761void SpatializerThread::checkOutputStageEffects()
Eric Laurentb3f315a2021-07-13 15:09:05 +02007762{
7763 bool hasVirtualizer = false;
7764 bool hasDownMixer = false;
Andy Hungbd72c542023-06-20 18:56:17 -07007765 sp<IAfEffectHandle> finalDownMixer;
Eric Laurentb3f315a2021-07-13 15:09:05 +02007766 {
7767 Mutex::Autolock _l(mLock);
Andy Hungbd72c542023-06-20 18:56:17 -07007768 sp<IAfEffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_STAGE);
Eric Laurentb3f315a2021-07-13 15:09:05 +02007769 if (chain != 0) {
Eric Laurent1c5e2e32021-08-18 18:50:28 +02007770 hasVirtualizer = chain->getEffectFromType_l(FX_IID_SPATIALIZER) != nullptr;
Eric Laurentb3f315a2021-07-13 15:09:05 +02007771 hasDownMixer = chain->getEffectFromType_l(EFFECT_UIID_DOWNMIX) != nullptr;
7772 }
7773
7774 finalDownMixer = mFinalDownMixer;
7775 mFinalDownMixer.clear();
7776 }
7777
7778 if (hasVirtualizer) {
7779 if (finalDownMixer != nullptr) {
7780 int32_t ret;
Andy Hungbd72c542023-06-20 18:56:17 -07007781 finalDownMixer->asIEffect()->disable(&ret);
Eric Laurentb3f315a2021-07-13 15:09:05 +02007782 }
7783 finalDownMixer.clear();
7784 } else if (!hasDownMixer) {
7785 std::vector<effect_descriptor_t> descriptors;
Andy Hung2cbc2722023-07-17 17:05:00 -07007786 status_t status = mAfThreadCallback->getEffectsFactoryHal()->getDescriptors(
Eric Laurentb3f315a2021-07-13 15:09:05 +02007787 EFFECT_UIID_DOWNMIX, &descriptors);
7788 if (status != NO_ERROR) {
7789 return;
7790 }
7791 ALOG_ASSERT(!descriptors.empty(),
7792 "%s getDescriptors() returned no error but empty list", __func__);
7793
7794 finalDownMixer = createEffect_l(nullptr /*client*/, nullptr /*effectClient*/,
7795 0 /*priority*/, AUDIO_SESSION_OUTPUT_STAGE, &descriptors[0], nullptr /*enabled*/,
Eric Laurentde8caf42021-08-11 17:19:25 +02007796 &status, false /*pinned*/, false /*probe*/, false /*notifyFramesProcessed*/);
Eric Laurentb3f315a2021-07-13 15:09:05 +02007797
7798 if (finalDownMixer == nullptr || (status != NO_ERROR && status != ALREADY_EXISTS)) {
7799 ALOGW("%s error creating downmixer %d", __func__, status);
7800 finalDownMixer.clear();
7801 } else {
7802 int32_t ret;
Andy Hungbd72c542023-06-20 18:56:17 -07007803 finalDownMixer->asIEffect()->enable(&ret);
Eric Laurentb3f315a2021-07-13 15:09:05 +02007804 }
7805 }
7806
7807 {
7808 Mutex::Autolock _l(mLock);
7809 mFinalDownMixer = finalDownMixer;
7810 }
7811}
7812
Eric Laurent81784c32012-11-19 14:55:58 -08007813// ----------------------------------------------------------------------------
7814// Record
7815// ----------------------------------------------------------------------------
7816
Andy Hung2cbc2722023-07-17 17:05:00 -07007817sp<IAfRecordThread> IAfRecordThread::create(const sp<IAfThreadCallback>& afThreadCallback,
Andy Hung44f27182023-07-06 20:56:16 -07007818 AudioStreamIn* input,
7819 audio_io_handle_t id,
7820 bool systemReady) {
Andy Hung2cbc2722023-07-17 17:05:00 -07007821 return sp<RecordThread>::make(afThreadCallback, input, id, systemReady);
Andy Hung44f27182023-07-06 20:56:16 -07007822}
7823
Andy Hung2cbc2722023-07-17 17:05:00 -07007824RecordThread::RecordThread(const sp<IAfThreadCallback>& afThreadCallback,
Eric Laurent81784c32012-11-19 14:55:58 -08007825 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08007826 audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -07007827 bool systemReady
Glenn Kasten46909e72013-02-26 09:20:22 -08007828 ) :
Andy Hung2cbc2722023-07-17 17:05:00 -07007829 ThreadBase(afThreadCallback, id, RECORD, systemReady, false /* isOut */),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007830 mInput(input),
Mikhail Naganov2534b382019-09-25 13:05:02 -07007831 mSource(mInput),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007832 mActiveTracks(&this->mLocalLog),
7833 mRsmpInBuffer(NULL),
Glenn Kasten1b291842016-07-18 14:55:21 -07007834 // mRsmpInFrames, mRsmpInFramesP2, and mRsmpInFramesOA are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007835 mRsmpInRear(0)
Glenn Kastenb880f5e2014-05-07 08:43:45 -07007836 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
7837 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007838 // mFastCapture below
7839 , mFastCaptureFutex(0)
7840 // mInputSource
7841 // mPipeSink
7842 // mPipeSource
7843 , mPipeFramesP2(0)
7844 // mPipeMemory
7845 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07007846 , mFastTrackAvail(false)
Eric Laurentd8365c52017-07-16 15:27:05 -07007847 , mBtNrecSuspended(false)
Eric Laurent81784c32012-11-19 14:55:58 -08007848{
Glenn Kastend7dca052015-03-05 16:05:54 -08007849 snprintf(mThreadName, kThreadNameLength, "AudioIn_%X", id);
Andy Hung2cbc2722023-07-17 17:05:00 -07007850 mNBLogWriter = afThreadCallback->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08007851
George Burgess IVa8f90c12020-05-14 11:27:19 -07007852 if (mInput->audioHwDev != nullptr) {
Andy Hungc8fddf32018-08-08 18:32:37 -07007853 mIsMsdDevice = strcmp(
7854 mInput->audioHwDev->moduleName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0;
7855 }
7856
Glenn Kastendeca2ae2014-02-07 10:25:56 -08007857 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007858
Andy Hungc8fddf32018-08-08 18:32:37 -07007859 // TODO: We may also match on address as well as device type for
7860 // AUDIO_DEVICE_IN_BUS, AUDIO_DEVICE_IN_BLUETOOTH_A2DP, AUDIO_DEVICE_IN_REMOTE_SUBMIX
jiabinc52b1ff2019-10-31 17:20:42 -07007861 // TODO: This property should be ensure that only contains one single device type.
7862 mTimestampCorrectedDevice = (audio_devices_t)property_get_int64(
7863 "audio.timestamp.corrected_input_device",
Andy Hungc8fddf32018-08-08 18:32:37 -07007864 (int64_t)(mIsMsdDevice ? AUDIO_DEVICE_IN_BUS // turn on by default for MSD
7865 : AUDIO_DEVICE_NONE));
7866
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007867 // create an NBAIO source for the HAL input stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07007868 mInputSource = new AudioStreamInSource(input->stream);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007869 size_t numCounterOffers = 0;
7870 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07007871#if !LOG_NDEBUG
Jing Mike537412f2023-03-12 11:01:47 +08007872 [[maybe_unused]] ssize_t index =
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07007873#else
7874 (void)
7875#endif
7876 mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007877 ALOG_ASSERT(index == 0);
7878
7879 // initialize fast capture depending on configuration
7880 bool initFastCapture;
7881 switch (kUseFastCapture) {
7882 case FastCapture_Never:
7883 initFastCapture = false;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007884 ALOGV("%p kUseFastCapture = Never, initFastCapture = false", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007885 break;
7886 case FastCapture_Always:
7887 initFastCapture = true;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007888 ALOGV("%p kUseFastCapture = Always, initFastCapture = true", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007889 break;
7890 case FastCapture_Static:
Sampath6fac2332022-12-16 17:34:37 +11007891 initFastCapture = !mIsMsdDevice // Disable fast capture for MSD BUS devices.
7892 && (mFrameCount * 1000) / mSampleRate < kMinNormalCaptureBufferSizeMs;
7893 ALOGV("%p kUseFastCapture = Static, (%lld * 1000) / %u vs %u, initFastCapture = %d "
7894 "mIsMsdDevice = %d", this, (long long)mFrameCount, mSampleRate,
7895 kMinNormalCaptureBufferSizeMs, initFastCapture, mIsMsdDevice);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007896 break;
7897 // case FastCapture_Dynamic:
7898 }
7899
7900 if (initFastCapture) {
Glenn Kastend198b852015-03-16 14:55:53 -07007901 // create a Pipe for FastCapture to write to, and for us and fast tracks to read from
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007902 NBAIO_Format format = mInputSource->format();
Glenn Kasten1b291842016-07-18 14:55:21 -07007903 // quadruple-buffering of 20 ms each; this ensures we can sleep for 20ms in RecordThread
7904 size_t pipeFramesP2 = roundup(4 * FMS_20 * mSampleRate / 1000);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007905 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007906 void *pipeBuffer = nullptr;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007907 const sp<MemoryDealer> roHeap(readOnlyHeap());
7908 sp<IMemory> pipeMemory;
7909 if ((roHeap == 0) ||
7910 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07007911 (pipeBuffer = pipeMemory->unsecurePointer()) == nullptr) {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007912 ALOGE("not enough memory for pipe buffer size=%zu; "
7913 "roHeap=%p, pipeMemory=%p, pipeBuffer=%p; roHeapSize: %lld",
7914 pipeSize, roHeap.get(), pipeMemory.get(), pipeBuffer,
7915 (long long)kRecordThreadReadOnlyHeapSize);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007916 goto failed;
7917 }
7918 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
7919 memset(pipeBuffer, 0, pipeSize);
7920 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
Andy Hung71ba4b32022-10-06 12:09:49 -07007921 const NBAIO_Format offersFast[1] = {format};
7922 size_t numCounterOffersFast = 0;
Eric Laurent1e28aaa2023-04-16 19:34:23 +02007923 [[maybe_unused]] ssize_t index2 = pipe->negotiate(offersFast, std::size(offersFast),
Andy Hung71ba4b32022-10-06 12:09:49 -07007924 nullptr /* counterOffers */, numCounterOffersFast);
Eric Laurent1e28aaa2023-04-16 19:34:23 +02007925 ALOG_ASSERT(index2 == 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007926 mPipeSink = pipe;
7927 PipeReader *pipeReader = new PipeReader(*pipe);
Andy Hung71ba4b32022-10-06 12:09:49 -07007928 numCounterOffersFast = 0;
Eric Laurent1e28aaa2023-04-16 19:34:23 +02007929 index2 = pipeReader->negotiate(offersFast, std::size(offersFast),
Andy Hung71ba4b32022-10-06 12:09:49 -07007930 nullptr /* counterOffers */, numCounterOffersFast);
Eric Laurent1e28aaa2023-04-16 19:34:23 +02007931 ALOG_ASSERT(index2 == 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007932 mPipeSource = pipeReader;
7933 mPipeFramesP2 = pipeFramesP2;
7934 mPipeMemory = pipeMemory;
7935
7936 // create fast capture
7937 mFastCapture = new FastCapture();
7938 FastCaptureStateQueue *sq = mFastCapture->sq();
7939#ifdef STATE_QUEUE_DUMP
7940 // FIXME
7941#endif
7942 FastCaptureState *state = sq->begin();
7943 state->mCblk = NULL;
7944 state->mInputSource = mInputSource.get();
7945 state->mInputSourceGen++;
7946 state->mPipeSink = pipe;
7947 state->mPipeSinkGen++;
7948 state->mFrameCount = mFrameCount;
7949 state->mCommand = FastCaptureState::COLD_IDLE;
7950 // already done in constructor initialization list
7951 //mFastCaptureFutex = 0;
7952 state->mColdFutexAddr = &mFastCaptureFutex;
7953 state->mColdGen++;
7954 state->mDumpState = &mFastCaptureDumpState;
7955#ifdef TEE_SINK
7956 // FIXME
7957#endif
Andy Hung2cbc2722023-07-17 17:05:00 -07007958 mFastCaptureNBLogWriter =
7959 afThreadCallback->newWriter_l(kFastCaptureLogSize, "FastCapture");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007960 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
7961 sq->end();
7962 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
7963
7964 // start the fast capture
7965 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
7966 pid_t tid = mFastCapture->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07007967 sendPrioConfigEvent(getpid(), tid, kPriorityFastCapture, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08007968 stream()->setHalThreadPriority(kPriorityFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007969#ifdef AUDIO_WATCHDOG
7970 // FIXME
7971#endif
7972
Glenn Kasten6e6704c2014-07-03 10:20:00 -07007973 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007974 }
Andy Hung8946a282018-04-19 20:04:56 -07007975#ifdef TEE_SINK
7976 mTee.set(mInputSource->format(), NBAIO_Tee::TEE_FLAG_INPUT_THREAD);
7977 mTee.setId(std::string("_") + std::to_string(mId) + "_C");
7978#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007979failed: ;
7980
7981 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08007982}
7983
Andy Hung71742ab2023-07-07 13:47:37 -07007984RecordThread::~RecordThread()
Eric Laurent81784c32012-11-19 14:55:58 -08007985{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007986 if (mFastCapture != 0) {
7987 FastCaptureStateQueue *sq = mFastCapture->sq();
7988 FastCaptureState *state = sq->begin();
7989 if (state->mCommand == FastCaptureState::COLD_IDLE) {
7990 int32_t old = android_atomic_inc(&mFastCaptureFutex);
7991 if (old == -1) {
7992 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
7993 }
7994 }
7995 state->mCommand = FastCaptureState::EXIT;
7996 sq->end();
7997 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
7998 mFastCapture->join();
7999 mFastCapture.clear();
8000 }
Andy Hung2cbc2722023-07-17 17:05:00 -07008001 mAfThreadCallback->unregisterWriter(mFastCaptureNBLogWriter);
8002 mAfThreadCallback->unregisterWriter(mNBLogWriter);
Andy Hung57446612015-04-19 23:56:46 -07008003 free(mRsmpInBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08008004}
8005
Andy Hung71742ab2023-07-07 13:47:37 -07008006void RecordThread::onFirstRef()
Eric Laurent81784c32012-11-19 14:55:58 -08008007{
Glenn Kastend7dca052015-03-05 16:05:54 -08008008 run(mThreadName, PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08008009}
8010
Andy Hung71742ab2023-07-07 13:47:37 -07008011void RecordThread::preExit()
Eric Laurent555530a2017-02-07 18:17:24 -08008012{
8013 ALOGV(" preExit()");
8014 Mutex::Autolock _l(mLock);
8015 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung3ff4b552023-06-26 19:20:57 -07008016 sp<IAfRecordTrack> track = mTracks[i];
Eric Laurent555530a2017-02-07 18:17:24 -08008017 track->invalidate();
8018 }
8019 mActiveTracks.clear();
8020 mStartStopCond.broadcast();
8021}
8022
Andy Hung71742ab2023-07-07 13:47:37 -07008023bool RecordThread::threadLoop()
Eric Laurent81784c32012-11-19 14:55:58 -08008024{
Eric Laurent81784c32012-11-19 14:55:58 -08008025 nsecs_t lastWarning = 0;
8026
8027 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08008028
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008029reacquire_wakelock:
Andy Hung3ff4b552023-06-26 19:20:57 -07008030 sp<IAfRecordTrack> activeTrack;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008031 {
8032 Mutex::Autolock _l(mLock);
Andy Hungdae27702016-10-31 14:01:16 -07008033 acquireWakeLock_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008034 }
8035
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008036 // used to request a deferred sleep, to be executed later while mutex is unlocked
8037 uint32_t sleepUs = 0;
8038
Andy Hung446f4df2019-02-21 12:26:41 -08008039 int64_t lastLoopCountRead = -2; // never matches "previous" loop, when loopCount = 0.
8040
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008041 // loop while there is work to do
Andy Hung446f4df2019-02-21 12:26:41 -08008042 for (int64_t loopCount = 0;; ++loopCount) { // loopCount used for statistics tracking
Andy Hungbd72c542023-06-20 18:56:17 -07008043 Vector<sp<IAfEffectChain>> effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07008044
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008045 // activeTracks accumulates a copy of a subset of mActiveTracks
Andy Hung3ff4b552023-06-26 19:20:57 -07008046 Vector<sp<IAfRecordTrack>> activeTracks;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008047
Glenn Kasten735f45f2014-08-18 15:51:59 -07008048 // reference to the (first and only) active fast track
Andy Hung3ff4b552023-06-26 19:20:57 -07008049 sp<IAfRecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07008050
Glenn Kasten735f45f2014-08-18 15:51:59 -07008051 // reference to a fast track which is about to be removed
Andy Hung3ff4b552023-06-26 19:20:57 -07008052 sp<IAfRecordTrack> fastTrackToRemove;
Glenn Kasten735f45f2014-08-18 15:51:59 -07008053
Eric Laurent33403f02020-05-29 18:35:06 -07008054 bool silenceFastCapture = false;
8055
Eric Laurent81784c32012-11-19 14:55:58 -08008056 { // scope for mLock
8057 Mutex::Autolock _l(mLock);
Eric Laurent000a4192014-01-29 15:17:32 -08008058
Eric Laurent021cf962014-05-13 10:18:14 -07008059 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008060
Eric Laurent000a4192014-01-29 15:17:32 -08008061 // check exitPending here because checkForNewParameters_l() and
8062 // checkForNewParameters_l() can temporarily release mLock
8063 if (exitPending()) {
8064 break;
8065 }
8066
Eric Laurent5c25d562016-07-13 17:17:45 -07008067 // sleep with mutex unlocked
8068 if (sleepUs > 0) {
Glenn Kastenf9715e42016-07-13 14:02:03 -07008069 ATRACE_BEGIN("sleepC");
Eric Laurent5c25d562016-07-13 17:17:45 -07008070 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)sleepUs));
8071 ATRACE_END();
8072 sleepUs = 0;
8073 continue;
8074 }
8075
Glenn Kasten2b806402013-11-20 16:37:38 -08008076 // if no active track(s), then standby and release wakelock
8077 size_t size = mActiveTracks.size();
8078 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07008079 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07008080 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08008081 releaseWakeLock_l();
8082 ALOGV("RecordThread: loop stopping");
8083 // go to sleep
8084 mWaitWorkCV.wait(mLock);
8085 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008086 goto reacquire_wakelock;
8087 }
8088
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008089 bool doBroadcast = false;
Eric Laurent5c25d562016-07-13 17:17:45 -07008090 bool allStopped = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008091 for (size_t i = 0; i < size; ) {
Glenn Kasten9e982352013-08-14 14:39:50 -07008092
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008093 activeTrack = mActiveTracks[i];
8094 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07008095 if (activeTrack->isFastTrack()) {
8096 ALOG_ASSERT(fastTrackToRemove == 0);
8097 fastTrackToRemove = activeTrack;
8098 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008099 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08008100 mActiveTracks.remove(activeTrack);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008101 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07008102 continue;
8103 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008104
Andy Hung3ff4b552023-06-26 19:20:57 -07008105 IAfTrackBase::track_state activeTrackState = activeTrack->state();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008106 switch (activeTrackState) {
8107
Andy Hung3ff4b552023-06-26 19:20:57 -07008108 case IAfTrackBase::PAUSING:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008109 mActiveTracks.remove(activeTrack);
Andy Hung3ff4b552023-06-26 19:20:57 -07008110 activeTrack->setState(IAfTrackBase::PAUSED);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008111 doBroadcast = true;
8112 size--;
8113 continue;
8114
Andy Hung3ff4b552023-06-26 19:20:57 -07008115 case IAfTrackBase::STARTING_1:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008116 sleepUs = 10000;
8117 i++;
Eric Laurent5c25d562016-07-13 17:17:45 -07008118 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008119 continue;
8120
Andy Hung3ff4b552023-06-26 19:20:57 -07008121 case IAfTrackBase::STARTING_2:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008122 doBroadcast = true;
Andy Hungcf10d742020-04-28 15:38:24 -07008123 if (mStandby) {
8124 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07008125 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -07008126 mStandby = false;
8127 }
Andy Hung3ff4b552023-06-26 19:20:57 -07008128 activeTrack->setState(IAfTrackBase::ACTIVE);
Eric Laurent5c25d562016-07-13 17:17:45 -07008129 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008130 break;
8131
Andy Hung3ff4b552023-06-26 19:20:57 -07008132 case IAfTrackBase::ACTIVE:
Eric Laurent5c25d562016-07-13 17:17:45 -07008133 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008134 break;
8135
Andy Hung3ff4b552023-06-26 19:20:57 -07008136 case IAfTrackBase::IDLE: // cannot be on ActiveTracks if idle
8137 case IAfTrackBase::PAUSED: // cannot be on ActiveTracks if paused
8138 case IAfTrackBase::STOPPED: // cannot be on ActiveTracks if destroyed/terminated
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008139 default:
Andy Hungce685402018-10-05 17:23:27 -07008140 LOG_ALWAYS_FATAL("%s: Unexpected active track state:%d, id:%d, tracks:%zu",
8141 __func__, activeTrackState, activeTrack->id(), size);
Glenn Kasten9e982352013-08-14 14:39:50 -07008142 }
Glenn Kasten9e982352013-08-14 14:39:50 -07008143
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008144 if (activeTrack->isFastTrack()) {
8145 ALOG_ASSERT(!mFastTrackAvail);
8146 ALOG_ASSERT(fastTrack == 0);
Eric Laurent33403f02020-05-29 18:35:06 -07008147 // if the active fast track is silenced either:
8148 // 1) silence the whole capture from fast capture buffer if this is
8149 // the only active track
8150 // 2) invalidate this track: this will cause the client to reconnect and possibly
8151 // be invalidated again until unsilenced
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008152 bool invalidate = false;
Eric Laurent33403f02020-05-29 18:35:06 -07008153 if (activeTrack->isSilenced()) {
8154 if (size > 1) {
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008155 invalidate = true;
Eric Laurent33403f02020-05-29 18:35:06 -07008156 } else {
8157 silenceFastCapture = true;
8158 }
8159 }
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008160 // Invalidate fast tracks if access to audio history is required as this is not
8161 // possible with fast tracks. Once the fast track has been invalidated, no new
8162 // fast track will be created until mMaxSharedAudioHistoryMs is cleared.
8163 if (mMaxSharedAudioHistoryMs != 0) {
8164 invalidate = true;
8165 }
8166 if (invalidate) {
8167 activeTrack->invalidate();
8168 ALOG_ASSERT(fastTrackToRemove == 0);
8169 fastTrackToRemove = activeTrack;
8170 removeTrack_l(activeTrack);
8171 mActiveTracks.remove(activeTrack);
8172 size--;
8173 continue;
8174 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008175 fastTrack = activeTrack;
8176 }
Eric Laurent33403f02020-05-29 18:35:06 -07008177
8178 activeTracks.add(activeTrack);
8179 i++;
8180
Glenn Kasten9e982352013-08-14 14:39:50 -07008181 }
Eric Laurent5c25d562016-07-13 17:17:45 -07008182
Andy Hungdae27702016-10-31 14:01:16 -07008183 mActiveTracks.updatePowerState(this);
8184
Kevin Rocard069c2712018-03-29 19:09:14 -07008185 updateMetadata_l();
8186
Eric Laurent5c25d562016-07-13 17:17:45 -07008187 if (allStopped) {
8188 standbyIfNotAlreadyInStandby();
8189 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008190 if (doBroadcast) {
8191 mStartStopCond.broadcast();
8192 }
8193
8194 // sleep if there are no active tracks to process
Eric Tan39ec8d62018-07-24 09:49:29 -07008195 if (activeTracks.isEmpty()) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008196 if (sleepUs == 0) {
8197 sleepUs = kRecordThreadSleepUs;
8198 }
8199 continue;
8200 }
8201 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07008202
Eric Laurent81784c32012-11-19 14:55:58 -08008203 lockEffectChains_l(effectChains);
8204 }
8205
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008206 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07008207
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008208 size_t size = effectChains.size();
8209 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008210 // thread mutex is not locked, but effect chain is locked
8211 effectChains[i]->process_l();
8212 }
8213
Glenn Kasten735f45f2014-08-18 15:51:59 -07008214 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008215 if (mFastCapture != 0) {
8216 FastCaptureStateQueue *sq = mFastCapture->sq();
8217 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07008218 bool didModify = false;
8219 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008220 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
8221 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
8222 if (state->mCommand == FastCaptureState::COLD_IDLE) {
8223 int32_t old = android_atomic_inc(&mFastCaptureFutex);
8224 if (old == -1) {
8225 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
8226 }
8227 }
8228 state->mCommand = FastCaptureState::READ_WRITE;
8229#if 0 // FIXME
Andy Hung2cbc2722023-07-17 17:05:00 -07008230 mFastCaptureDumpState.increaseSamplingN(mAfThreadCallback->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08008231 FastThreadDumpState::kSamplingNforLowRamDevice :
8232 FastThreadDumpState::kSamplingN);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008233#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07008234 didModify = true;
8235 }
8236 audio_track_cblk_t *cblkOld = state->mCblk;
8237 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
8238 if (cblkNew != cblkOld) {
8239 state->mCblk = cblkNew;
8240 // block until acked if removing a fast track
8241 if (cblkOld != NULL) {
8242 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
8243 }
8244 didModify = true;
8245 }
jiabin01c8f562018-07-19 17:47:28 -07008246 AudioBufferProvider* abp = (fastTrack != 0 && fastTrack->isPatchTrack()) ?
8247 reinterpret_cast<AudioBufferProvider*>(fastTrack.get()) : nullptr;
8248 if (state->mFastPatchRecordBufferProvider != abp) {
8249 state->mFastPatchRecordBufferProvider = abp;
8250 state->mFastPatchRecordFormat = fastTrack == 0 ?
8251 AUDIO_FORMAT_INVALID : fastTrack->format();
8252 didModify = true;
8253 }
Eric Laurent33403f02020-05-29 18:35:06 -07008254 if (state->mSilenceCapture != silenceFastCapture) {
8255 state->mSilenceCapture = silenceFastCapture;
8256 didModify = true;
8257 }
Glenn Kasten735f45f2014-08-18 15:51:59 -07008258 sq->end(didModify);
8259 if (didModify) {
8260 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008261#if 0
8262 if (kUseFastCapture == FastCapture_Dynamic) {
8263 mNormalSource = mPipeSource;
8264 }
8265#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008266 }
8267 }
8268
Glenn Kasten735f45f2014-08-18 15:51:59 -07008269 // now run the fast track destructor with thread mutex unlocked
8270 fastTrackToRemove.clear();
8271
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008272 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
8273 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
8274 // slow, then this RecordThread will overrun by not calling HAL read often enough.
8275 // If destination is non-contiguous, first read past the nominal end of buffer, then
8276 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008277
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008278 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Andy Hung71ba4b32022-10-06 12:09:49 -07008279 ssize_t framesRead = 0; // not needed, remove clang-tidy warning.
Andy Hung446f4df2019-02-21 12:26:41 -08008280 const int64_t lastIoBeginNs = systemTime(); // start IO timing
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008281
8282 // If an NBAIO source is present, use it to read the normal capture's data
8283 if (mPipeSource != 0) {
Andy Hung156317a2018-08-02 11:49:29 -07008284 size_t framesToRead = min(mRsmpInFramesOA - rear, mRsmpInFramesP2 / 2);
Andy Hungd5b638f2018-04-30 13:56:10 -07008285
8286 // The audio fifo read() returns OVERRUN on overflow, and advances the read pointer
8287 // to the full buffer point (clearing the overflow condition). Upon OVERRUN error,
8288 // we immediately retry the read() to get data and prevent another overflow.
8289 for (int retries = 0; retries <= 2; ++retries) {
8290 ALOGW_IF(retries > 0, "overrun on read from pipe, retry #%d", retries);
8291 framesRead = mPipeSource->read((uint8_t*)mRsmpInBuffer + rear * mFrameSize,
8292 framesToRead);
8293 if (framesRead != OVERRUN) break;
8294 }
8295
Andy Hung7a3dc6b2018-05-01 16:39:51 -07008296 const ssize_t availableToRead = mPipeSource->availableToRead();
8297 if (availableToRead >= 0) {
Robert Wu06db0a32021-08-10 19:05:34 +00008298 mMonopipePipeDepthStats.add(availableToRead);
Glenn Kastena2f59b32020-08-03 16:37:24 -07008299 // PipeSource is the primary clock. It is up to the AudioRecord client to keep up.
Andy Hung7a3dc6b2018-05-01 16:39:51 -07008300 LOG_ALWAYS_FATAL_IF((size_t)availableToRead > mPipeFramesP2,
8301 "more frames to read than fifo size, %zd > %zu",
8302 availableToRead, mPipeFramesP2);
8303 const size_t pipeFramesFree = mPipeFramesP2 - availableToRead;
8304 const size_t sleepFrames = min(pipeFramesFree, mRsmpInFramesP2) / 2;
8305 ALOGVV("mPipeFramesP2:%zu mRsmpInFramesP2:%zu sleepFrames:%zu availableToRead:%zd",
8306 mPipeFramesP2, mRsmpInFramesP2, sleepFrames, availableToRead);
Glenn Kasten1b291842016-07-18 14:55:21 -07008307 sleepUs = (sleepFrames * 1000000LL) / mSampleRate;
8308 }
8309 if (framesRead < 0) {
8310 status_t status = (status_t) framesRead;
8311 switch (status) {
8312 case OVERRUN:
8313 ALOGW("overrun on read from pipe");
8314 framesRead = 0;
8315 break;
8316 case NEGOTIATE:
8317 ALOGE("re-negotiation is needed");
8318 framesRead = -1; // Will cause an attempt to recover.
8319 break;
8320 default:
8321 ALOGE("unknown error %d on read from pipe", status);
8322 break;
8323 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008324 }
8325 // otherwise use the HAL / AudioStreamIn directly
8326 } else {
Glenn Kastenec6a7032016-03-14 07:40:23 -07008327 ATRACE_BEGIN("read");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008328 size_t bytesRead;
Mikhail Naganov2534b382019-09-25 13:05:02 -07008329 status_t result = mSource->read(
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008330 (uint8_t*)mRsmpInBuffer + rear * mFrameSize, mBufferSize, &bytesRead);
Glenn Kastenec6a7032016-03-14 07:40:23 -07008331 ATRACE_END();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008332 if (result < 0) {
8333 framesRead = result;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008334 } else {
8335 framesRead = bytesRead / mFrameSize;
8336 }
8337 }
8338
Andy Hung446f4df2019-02-21 12:26:41 -08008339 const int64_t lastIoEndNs = systemTime(); // end IO timing
8340
Andy Hung3f0c9022016-01-15 17:49:46 -08008341 // Update server timestamp with server stats
8342 // systemTime() is optional if the hardware supports timestamps.
Andy Hung743f6402020-06-03 13:17:04 -07008343 if (framesRead >= 0) {
8344 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += framesRead;
8345 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = lastIoEndNs;
8346 }
Andy Hung3f0c9022016-01-15 17:49:46 -08008347
8348 // Update server timestamp with kernel stats
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008349 if (mPipeSource.get() == nullptr /* don't obtain for FastCapture, could block */) {
Andy Hung3f0c9022016-01-15 17:49:46 -08008350 int64_t position, time;
Andy Hung2e2c0bb2018-06-11 19:13:11 -07008351 if (mStandby) {
Dean Wheatley12473e92021-03-18 23:00:55 +11008352 mTimestampVerifier.discontinuity(audio_is_linear_pcm(mFormat) ?
8353 mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS :
8354 mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Mikhail Naganov2534b382019-09-25 13:05:02 -07008355 } else if (mSource->getCapturePosition(&position, &time) == NO_ERROR
Andy Hungc8fddf32018-08-08 18:32:37 -07008356 && time > mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]) {
8357
8358 mTimestampVerifier.add(position, time, mSampleRate);
8359
8360 // Correct timestamps
8361 if (isTimestampCorrectionEnabled()) {
Dean Wheatley56a583e2020-05-08 15:12:17 +10008362 ALOGVV("TS_BEFORE: %d %lld %lld",
Andy Hungc8fddf32018-08-08 18:32:37 -07008363 id(), (long long)time, (long long)position);
8364 auto correctedTimestamp = mTimestampVerifier.getLastCorrectedTimestamp();
8365 position = correctedTimestamp.mFrames;
8366 time = correctedTimestamp.mTimeNs;
Dean Wheatley56a583e2020-05-08 15:12:17 +10008367 ALOGVV("TS_AFTER: %d %lld %lld",
Andy Hungc8fddf32018-08-08 18:32:37 -07008368 id(), (long long)time, (long long)position);
8369 }
8370
Andy Hung3f0c9022016-01-15 17:49:46 -08008371 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = position;
8372 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] = time;
8373 // Note: In general record buffers should tend to be empty in
8374 // a properly running pipeline.
8375 //
8376 // Also, it is not advantageous to call get_presentation_position during the read
8377 // as the read obtains a lock, preventing the timestamp call from executing.
Andy Hung2e2c0bb2018-06-11 19:13:11 -07008378 } else {
8379 mTimestampVerifier.error();
Andy Hung3f0c9022016-01-15 17:49:46 -08008380 }
8381 }
Andy Hunge6c37112019-02-26 17:38:10 -08008382
8383 // From the timestamp, input read latency is negative output write latency.
8384 const audio_input_flags_t flags = mInput != NULL ? mInput->flags : AUDIO_INPUT_FLAG_NONE;
Andy Hung3ff4b552023-06-26 19:20:57 -07008385 const double latencyMs = IAfRecordTrack::checkServerLatencySupported(mFormat, flags)
Andy Hunge6c37112019-02-26 17:38:10 -08008386 ? - mTimestamp.getOutputServerLatencyMs(mSampleRate) : 0.;
8387 if (latencyMs != 0.) { // note 0. means timestamp is empty.
8388 mLatencyMs.add(latencyMs);
8389 }
8390
Andy Hung3f0c9022016-01-15 17:49:46 -08008391 // Use this to track timestamp information
8392 // ALOGD("%s", mTimestamp.toString().c_str());
8393
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008394 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07008395 ALOGE("read failed: framesRead=%zd", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008396 // Force input into standby so that it tries to recover at next read attempt
8397 inputStandBy();
8398 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008399 }
8400 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008401 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008402 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008403 ALOG_ASSERT(framesRead > 0);
Andy Hung6427e442018-08-09 12:51:02 -07008404 mFramesRead += framesRead;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008405
Andy Hung8946a282018-04-19 20:04:56 -07008406#ifdef TEE_SINK
8407 (void)mTee.write((uint8_t*)mRsmpInBuffer + rear * mFrameSize, framesRead);
8408#endif
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008409 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008410 {
8411 size_t part1 = mRsmpInFramesP2 - rear;
8412 if ((size_t) framesRead > part1) {
Andy Hung57446612015-04-19 23:56:46 -07008413 memcpy(mRsmpInBuffer, (uint8_t*)mRsmpInBuffer + mRsmpInFramesP2 * mFrameSize,
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008414 (framesRead - part1) * mFrameSize);
8415 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008416 }
Dean Wheatleyfd56e812020-11-06 22:32:21 +11008417 mRsmpInRear = audio_utils::safe_add_overflow(mRsmpInRear, (int32_t)framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008418
8419 size = activeTracks.size();
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008420
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008421 // loop over each active track
8422 for (size_t i = 0; i < size; i++) {
8423 activeTrack = activeTracks[i];
8424
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008425 // skip fast tracks, as those are handled directly by FastCapture
8426 if (activeTrack->isFastTrack()) {
8427 continue;
8428 }
8429
Andy Hung73c02e42015-03-29 01:13:58 -07008430 // TODO: This code probably should be moved to RecordTrack.
Andy Hung97a893e2015-03-29 01:03:07 -07008431 // TODO: Update the activeTrack buffer converter in case of reconfigure.
8432
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008433 enum {
8434 OVERRUN_UNKNOWN,
8435 OVERRUN_TRUE,
8436 OVERRUN_FALSE
8437 } overrun = OVERRUN_UNKNOWN;
8438
8439 // loop over getNextBuffer to handle circular sink
8440 for (;;) {
8441
Andy Hung3ff4b552023-06-26 19:20:57 -07008442 activeTrack->sinkBuffer().frameCount = ~0;
8443 status_t status = activeTrack->getNextBuffer(&activeTrack->sinkBuffer());
8444 size_t framesOut = activeTrack->sinkBuffer().frameCount;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008445 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
8446
Andy Hung73c02e42015-03-29 01:13:58 -07008447 // check available frames and handle overrun conditions
8448 // if the record track isn't draining fast enough.
8449 bool hasOverrun;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008450 size_t framesIn;
Andy Hung3ff4b552023-06-26 19:20:57 -07008451 activeTrack->resamplerBufferProvider()->sync(&framesIn, &hasOverrun);
Andy Hung73c02e42015-03-29 01:13:58 -07008452 if (hasOverrun) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008453 overrun = OVERRUN_TRUE;
8454 }
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08008455 if (framesOut == 0 || framesIn == 0) {
8456 break;
8457 }
8458
Andy Hung6770c6f2015-04-07 13:43:36 -07008459 // Don't allow framesOut to be larger than what is possible with resampling
8460 // from framesIn.
8461 // This isn't strictly necessary but helps limit buffer resizing in
8462 // RecordBufferConverter. TODO: remove when no longer needed.
8463 framesOut = min(framesOut,
8464 destinationFramesPossible(
Andy Hung3ff4b552023-06-26 19:20:57 -07008465 framesIn, mSampleRate, activeTrack->sampleRate()));
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008466
8467 if (activeTrack->isDirect()) {
Daniel Van Veen9e2376e2018-09-27 14:37:58 +10008468 // No RecordBufferConverter used for direct streams. Pass
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008469 // straight from RecordThread buffer to RecordTrack buffer.
8470 AudioBufferProvider::Buffer buffer;
8471 buffer.frameCount = framesOut;
Andy Hung71ba4b32022-10-06 12:09:49 -07008472 const status_t getNextBufferStatus =
Andy Hung3ff4b552023-06-26 19:20:57 -07008473 activeTrack->resamplerBufferProvider()->getNextBuffer(&buffer);
Andy Hung71ba4b32022-10-06 12:09:49 -07008474 if (getNextBufferStatus == OK && buffer.frameCount != 0) {
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008475 ALOGV_IF(buffer.frameCount != framesOut,
8476 "%s() read less than expected (%zu vs %zu)",
8477 __func__, buffer.frameCount, framesOut);
8478 framesOut = buffer.frameCount;
Andy Hung3ff4b552023-06-26 19:20:57 -07008479 memcpy(activeTrack->sinkBuffer().raw,
8480 buffer.raw, buffer.frameCount * mFrameSize);
8481 activeTrack->resamplerBufferProvider()->releaseBuffer(&buffer);
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008482 } else {
8483 framesOut = 0;
8484 ALOGE("%s() cannot fill request, status: %d, frameCount: %zu",
Andy Hung71ba4b32022-10-06 12:09:49 -07008485 __func__, getNextBufferStatus, buffer.frameCount);
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008486 }
8487 } else {
8488 // process frames from the RecordThread buffer provider to the RecordTrack
8489 // buffer
Andy Hung3ff4b552023-06-26 19:20:57 -07008490 framesOut = activeTrack->recordBufferConverter()->convert(
8491 activeTrack->sinkBuffer().raw,
8492 activeTrack->resamplerBufferProvider(),
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008493 framesOut);
8494 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008495
8496 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
8497 overrun = OVERRUN_FALSE;
8498 }
8499
Andy Hung93bb5732023-05-04 21:16:34 -07008500 // MediaSyncEvent handling: Synchronize AudioRecord to AudioTrack completion.
8501 const ssize_t framesToDrop =
Andy Hung3ff4b552023-06-26 19:20:57 -07008502 activeTrack->synchronizedRecordState().updateRecordFrames(framesOut);
Andy Hung93bb5732023-05-04 21:16:34 -07008503 if (framesToDrop == 0) {
8504 // no sync event, process normally, otherwise ignore.
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008505 if (framesOut > 0) {
Andy Hung3ff4b552023-06-26 19:20:57 -07008506 activeTrack->sinkBuffer().frameCount = framesOut;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008507 // Sanitize before releasing if the track has no access to the source data
8508 // An idle UID receives silence from non virtual devices until active
8509 if (activeTrack->isSilenced()) {
Andy Hung3ff4b552023-06-26 19:20:57 -07008510 memset(activeTrack->sinkBuffer().raw,
8511 0, framesOut * activeTrack->frameSize());
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008512 }
Andy Hung3ff4b552023-06-26 19:20:57 -07008513 activeTrack->releaseBuffer(&activeTrack->sinkBuffer());
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008514 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008515 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008516 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008517 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008518 }
8519 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008520
8521 switch (overrun) {
8522 case OVERRUN_TRUE:
8523 // client isn't retrieving buffers fast enough
8524 if (!activeTrack->setOverflow()) {
8525 nsecs_t now = systemTime();
8526 // FIXME should lastWarning per track?
8527 if ((now - lastWarning) > kWarningThrottleNs) {
8528 ALOGW("RecordThread: buffer overflow");
8529 lastWarning = now;
8530 }
8531 }
8532 break;
8533 case OVERRUN_FALSE:
8534 activeTrack->clearOverflow();
8535 break;
8536 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008537 break;
8538 }
8539
Andy Hung3f0c9022016-01-15 17:49:46 -08008540 // update frame information and push timestamp out
8541 activeTrack->updateTrackFrameInfo(
Andy Hung3ff4b552023-06-26 19:20:57 -07008542 activeTrack->serverProxy()->framesReleased(),
Andy Hung3f0c9022016-01-15 17:49:46 -08008543 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER],
8544 mSampleRate, mTimestamp);
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008545 }
8546
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008547unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08008548 // enable changes in effect chain
8549 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07008550 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurentcccbc762019-04-05 14:20:05 -07008551 if (audio_has_proportional_frames(mFormat)
8552 && loopCount == lastLoopCountRead + 1) {
8553 const int64_t readPeriodNs = lastIoEndNs - mLastIoEndNs;
8554 const double jitterMs =
8555 TimestampVerifier<int64_t, int64_t>::computeJitterMs(
8556 {framesRead, readPeriodNs},
8557 {0, 0} /* lastTimestamp */, mSampleRate);
8558 const double processMs = (lastIoBeginNs - mLastIoEndNs) * 1e-6;
8559
8560 Mutex::Autolock _l(mLock);
8561 mIoJitterMs.add(jitterMs);
8562 mProcessTimeMs.add(processMs);
8563 }
8564 // update timing info.
8565 mLastIoBeginNs = lastIoBeginNs;
8566 mLastIoEndNs = lastIoEndNs;
8567 lastLoopCountRead = loopCount;
Eric Laurent81784c32012-11-19 14:55:58 -08008568 }
8569
Glenn Kasten93e471f2013-08-19 08:40:07 -07008570 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08008571
8572 {
8573 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07008574 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung3ff4b552023-06-26 19:20:57 -07008575 sp<IAfRecordTrack> track = mTracks[i];
Eric Laurent9a54bc22013-09-09 09:08:44 -07008576 track->invalidate();
8577 }
Glenn Kasten2b806402013-11-20 16:37:38 -08008578 mActiveTracks.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08008579 mStartStopCond.broadcast();
8580 }
8581
8582 releaseWakeLock();
8583
8584 ALOGV("RecordThread %p exiting", this);
8585 return false;
8586}
8587
Andy Hung71742ab2023-07-07 13:47:37 -07008588void RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08008589{
8590 if (!mStandby) {
8591 inputStandBy();
Andy Hungcf10d742020-04-28 15:38:24 -07008592 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07008593 mThreadSnapshot.onEnd();
Eric Laurent81784c32012-11-19 14:55:58 -08008594 mStandby = true;
8595 }
8596}
8597
Andy Hung71742ab2023-07-07 13:47:37 -07008598void RecordThread::inputStandBy()
Eric Laurent81784c32012-11-19 14:55:58 -08008599{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008600 // Idle the fast capture if it's currently running
8601 if (mFastCapture != 0) {
8602 FastCaptureStateQueue *sq = mFastCapture->sq();
8603 FastCaptureState *state = sq->begin();
8604 if (!(state->mCommand & FastCaptureState::IDLE)) {
8605 state->mCommand = FastCaptureState::COLD_IDLE;
8606 state->mColdFutexAddr = &mFastCaptureFutex;
8607 state->mColdGen++;
8608 mFastCaptureFutex = 0;
8609 sq->end();
8610 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
8611 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
8612#if 0
8613 if (kUseFastCapture == FastCapture_Dynamic) {
8614 // FIXME
8615 }
8616#endif
8617#ifdef AUDIO_WATCHDOG
8618 // FIXME
8619#endif
8620 } else {
8621 sq->end(false /*didModify*/);
8622 }
8623 }
Mikhail Naganov2534b382019-09-25 13:05:02 -07008624 status_t result = mSource->standby();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008625 ALOGE_IF(result != OK, "Error when putting input stream into standby: %d", result);
Andy Hungad6d52d2016-07-18 13:42:03 -07008626
8627 // If going into standby, flush the pipe source.
8628 if (mPipeSource.get() != nullptr) {
8629 const ssize_t flushed = mPipeSource->flush();
8630 if (flushed > 0) {
8631 ALOGV("Input standby flushed PipeSource %zd frames", flushed);
8632 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += flushed;
8633 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
8634 }
8635 }
Eric Laurent81784c32012-11-19 14:55:58 -08008636}
8637
Glenn Kasten05997e22014-03-13 15:08:33 -07008638// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held
Andy Hung71742ab2023-07-07 13:47:37 -07008639sp<IAfRecordTrack> RecordThread::createRecordTrack_l(
Andy Hungd65869f2023-06-27 17:05:02 -07008640 const sp<Client>& client,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07008641 const audio_attributes_t& attr,
Eric Laurentf14db3c2017-12-08 14:20:36 -08008642 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08008643 audio_format_t format,
8644 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08008645 size_t *pFrameCount,
Glenn Kastend848eb42016-03-08 13:42:11 -08008646 audio_session_t sessionId,
Eric Laurentf14db3c2017-12-08 14:20:36 -08008647 size_t *pNotificationFrameCount,
Eric Laurent09f1ed22019-04-24 17:45:17 -07008648 pid_t creatorPid,
Svet Ganov33761132021-05-13 22:51:08 +00008649 const AttributionSourceState& attributionSource,
Eric Laurent05067782016-06-01 18:27:28 -07008650 audio_input_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08008651 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08008652 status_t *status,
Eric Laurentec376dc2021-04-08 20:41:22 +02008653 audio_port_handle_t portId,
8654 int32_t maxSharedAudioHistoryMs)
Eric Laurent81784c32012-11-19 14:55:58 -08008655{
Glenn Kasten74935e42013-12-19 08:56:45 -08008656 size_t frameCount = *pFrameCount;
Eric Laurentf14db3c2017-12-08 14:20:36 -08008657 size_t notificationFrameCount = *pNotificationFrameCount;
Andy Hung3ff4b552023-06-26 19:20:57 -07008658 sp<IAfRecordTrack> track;
Eric Laurent81784c32012-11-19 14:55:58 -08008659 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07008660 audio_input_flags_t inputFlags = mInput->flags;
Eric Laurentf14db3c2017-12-08 14:20:36 -08008661 audio_input_flags_t requestedFlags = *flags;
8662 uint32_t sampleRate;
8663
8664 lStatus = initCheck();
8665 if (lStatus != NO_ERROR) {
8666 ALOGE("createRecordTrack_l() audio driver not initialized");
8667 goto Exit;
8668 }
8669
Mikhail Naganovce9f2652018-07-16 11:09:24 -07008670 if (!audio_is_linear_pcm(mFormat) && (*flags & AUDIO_INPUT_FLAG_DIRECT) == 0) {
8671 ALOGE("createRecordTrack_l() on an encoded stream requires AUDIO_INPUT_FLAG_DIRECT");
8672 lStatus = BAD_VALUE;
8673 goto Exit;
8674 }
8675
Eric Laurentec376dc2021-04-08 20:41:22 +02008676 if (maxSharedAudioHistoryMs != 0) {
Eric Laurent9ff3e532022-11-10 16:04:44 +01008677 if (!captureHotwordAllowed(attributionSource)) {
Eric Laurentec376dc2021-04-08 20:41:22 +02008678 lStatus = PERMISSION_DENIED;
8679 goto Exit;
8680 }
Eric Laurentec376dc2021-04-08 20:41:22 +02008681 if (maxSharedAudioHistoryMs < 0
8682 || maxSharedAudioHistoryMs > AudioFlinger::kMaxSharedAudioHistoryMs) {
8683 lStatus = BAD_VALUE;
8684 goto Exit;
8685 }
8686 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08008687 if (*pSampleRate == 0) {
8688 *pSampleRate = mSampleRate;
8689 }
8690 sampleRate = *pSampleRate;
Eric Laurent05067782016-06-01 18:27:28 -07008691
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008692 // special case for FAST flag considered OK if fast capture is present and access to
8693 // audio history is not required
8694 if (hasFastCapture() && mMaxSharedAudioHistoryMs == 0) {
Eric Laurent05067782016-06-01 18:27:28 -07008695 inputFlags = (audio_input_flags_t)(inputFlags | AUDIO_INPUT_FLAG_FAST);
8696 }
8697
Eric Laurentf14db3c2017-12-08 14:20:36 -08008698 // Check if requested flags are compatible with input stream flags
Eric Laurent05067782016-06-01 18:27:28 -07008699 if ((*flags & inputFlags) != *flags) {
8700 ALOGW("createRecordTrack_l(): mismatch between requested flags (%08x) and"
8701 " input flags (%08x)",
8702 *flags, inputFlags);
8703 *flags = (audio_input_flags_t)(*flags & inputFlags);
8704 }
Eric Laurent81784c32012-11-19 14:55:58 -08008705
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008706 // client expresses a preference for FAST and no access to audio history,
8707 // but we get the final say
8708 if (*flags & AUDIO_INPUT_FLAG_FAST && maxSharedAudioHistoryMs == 0) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07008709 if (
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07008710 // we formerly checked for a callback handler (non-0 tid),
8711 // but that is no longer required for TRANSFER_OBTAIN mode
jiabinb00edc32021-08-16 16:27:54 +00008712 // No need to match hardware format, format conversion will be done in client side.
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07008713 //
Phil Burk7ed66a12019-04-18 13:20:30 -07008714 // Frame count is not specified (0), or is less than or equal the pipe depth.
8715 // It is OK to provide a higher capacity than requested.
8716 // We will force it to mPipeFramesP2 below.
8717 (frameCount <= mPipeFramesP2) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07008718 // PCM data
8719 audio_is_linear_pcm(format) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08008720 // hardware channel mask
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008721 (channelMask == mChannelMask) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08008722 // hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07008723 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07008724 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008725 hasFastCapture() &&
8726 // there are sufficient fast track slots available
8727 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07008728 ) {
Eric Laurent4c415062016-06-17 16:14:16 -07008729 // check compatibility with audio effects.
8730 Mutex::Autolock _l(mLock);
8731 // Do not accept FAST flag if the session has software effects
Andy Hungbd72c542023-06-20 18:56:17 -07008732 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent4c415062016-06-17 16:14:16 -07008733 if (chain != 0) {
Andy Hungd3bb0ad2016-10-11 17:16:43 -07008734 audio_input_flags_t old = *flags;
8735 chain->checkInputFlagCompatibility(flags);
8736 if (old != *flags) {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008737 ALOGV("%p AUDIO_INPUT_FLAGS denied by effect old=%#x new=%#x",
8738 this, (int)old, (int)*flags);
Eric Laurent4c415062016-06-17 16:14:16 -07008739 }
8740 }
Eric Laurent122f7e72016-06-29 11:53:29 -07008741 ALOGV_IF((*flags & AUDIO_INPUT_FLAG_FAST) != 0,
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008742 "%p AUDIO_INPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
8743 this, frameCount, mFrameCount);
Glenn Kasten90e58b12013-07-31 16:16:02 -07008744 } else {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008745 ALOGV("%p AUDIO_INPUT_FLAG_FAST denied: frameCount=%zu mFrameCount=%zu mPipeFramesP2=%zu "
8746 "format=%#x isLinear=%d mFormat=%#x channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008747 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008748 this, frameCount, mFrameCount, mPipeFramesP2,
8749 format, audio_is_linear_pcm(format), mFormat, channelMask, sampleRate, mSampleRate,
Glenn Kasten74105912014-07-03 12:28:53 -07008750 hasFastCapture(), tid, mFastTrackAvail);
Eric Laurent05067782016-06-01 18:27:28 -07008751 *flags = (audio_input_flags_t)(*flags & ~AUDIO_INPUT_FLAG_FAST);
Glenn Kasten74105912014-07-03 12:28:53 -07008752 }
8753 }
8754
Eric Laurentf14db3c2017-12-08 14:20:36 -08008755 // If FAST or RAW flags were corrected, ask caller to request new input from audio policy
8756 if ((*flags & AUDIO_INPUT_FLAG_FAST) !=
8757 (requestedFlags & AUDIO_INPUT_FLAG_FAST)) {
8758 *flags = (audio_input_flags_t) (*flags & ~(AUDIO_INPUT_FLAG_FAST | AUDIO_INPUT_FLAG_RAW));
8759 lStatus = BAD_TYPE;
8760 goto Exit;
8761 }
8762
Glenn Kasten74105912014-07-03 12:28:53 -07008763 // compute track buffer size in frames, and suggest the notification frame count
Eric Laurent05067782016-06-01 18:27:28 -07008764 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten74105912014-07-03 12:28:53 -07008765 // fast track: frame count is exactly the pipe depth
8766 frameCount = mPipeFramesP2;
8767 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
Eric Laurentf14db3c2017-12-08 14:20:36 -08008768 notificationFrameCount = mFrameCount;
Glenn Kasten74105912014-07-03 12:28:53 -07008769 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07008770 // not fast track: max notification period is resampled equivalent of one HAL buffer time
8771 // or 20 ms if there is a fast capture
8772 // TODO This could be a roundupRatio inline, and const
8773 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
8774 * sampleRate + mSampleRate - 1) / mSampleRate;
8775 // minimum number of notification periods is at least kMinNotifications,
8776 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
8777 static const size_t kMinNotifications = 3;
8778 static const uint32_t kMinMs = 30;
8779 // TODO This could be a roundupRatio inline
8780 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
8781 // TODO This could be a roundupRatio inline
8782 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
8783 maxNotificationFrames;
8784 const size_t minFrameCount = maxNotificationFrames *
8785 max(kMinNotifications, minNotificationsByMs);
8786 frameCount = max(frameCount, minFrameCount);
Eric Laurentf14db3c2017-12-08 14:20:36 -08008787 if (notificationFrameCount == 0 || notificationFrameCount > maxNotificationFrames) {
8788 notificationFrameCount = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07008789 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07008790 }
Glenn Kasten74935e42013-12-19 08:56:45 -08008791 *pFrameCount = frameCount;
Eric Laurentf14db3c2017-12-08 14:20:36 -08008792 *pNotificationFrameCount = notificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08008793
8794 { // scope for mLock
8795 Mutex::Autolock _l(mLock);
Eric Laurent2407ce32021-04-26 14:56:03 +02008796 int32_t startFrames = -1;
Eric Laurentec376dc2021-04-08 20:41:22 +02008797 if (!mSharedAudioPackageName.empty()
Eric Laurent9ff3e532022-11-10 16:04:44 +01008798 && mSharedAudioPackageName == attributionSource.packageName
Eric Laurentec376dc2021-04-08 20:41:22 +02008799 && mSharedAudioSessionId == sessionId
Eric Laurent9ff3e532022-11-10 16:04:44 +01008800 && captureHotwordAllowed(attributionSource)) {
Eric Laurent2407ce32021-04-26 14:56:03 +02008801 startFrames = mSharedAudioStartFrames;
Eric Laurentec376dc2021-04-08 20:41:22 +02008802 }
Eric Laurent81784c32012-11-19 14:55:58 -08008803
Andy Hung3ff4b552023-06-26 19:20:57 -07008804 track = IAfRecordTrack::create(this, client, attr, sampleRate,
Andy Hung8fe68032017-06-05 16:17:51 -07008805 format, channelMask, frameCount,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07008806 nullptr /* buffer */, (size_t)0 /* bufferSize */, sessionId, creatorPid,
Andy Hung3ff4b552023-06-26 19:20:57 -07008807 attributionSource, *flags, IAfTrackBase::TYPE_DEFAULT, portId,
Svet Ganov33761132021-05-13 22:51:08 +00008808 startFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08008809
Glenn Kasten03003332013-08-06 15:40:54 -07008810 lStatus = track->initCheck();
8811 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07008812 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08008813 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08008814 goto Exit;
8815 }
8816 mTracks.add(track);
8817
Eric Laurent05067782016-06-01 18:27:28 -07008818 if ((*flags & AUDIO_INPUT_FLAG_FAST) && (tid != -1)) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07008819 pid_t callingPid = IPCThreadState::self()->getCallingPid();
8820 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
8821 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07008822 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Glenn Kasten90e58b12013-07-31 16:16:02 -07008823 }
Eric Laurentec376dc2021-04-08 20:41:22 +02008824
8825 if (maxSharedAudioHistoryMs != 0) {
8826 sendResizeBufferConfigEvent_l(maxSharedAudioHistoryMs);
8827 }
Eric Laurent81784c32012-11-19 14:55:58 -08008828 }
Glenn Kasten05997e22014-03-13 15:08:33 -07008829
Eric Laurent81784c32012-11-19 14:55:58 -08008830 lStatus = NO_ERROR;
8831
8832Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07008833 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08008834 return track;
8835}
8836
Andy Hung71742ab2023-07-07 13:47:37 -07008837status_t RecordThread::start(IAfRecordTrack* recordTrack,
Eric Laurent81784c32012-11-19 14:55:58 -08008838 AudioSystem::sync_event_t event,
Glenn Kastend848eb42016-03-08 13:42:11 -08008839 audio_session_t triggerSession)
Eric Laurent81784c32012-11-19 14:55:58 -08008840{
8841 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
8842 sp<ThreadBase> strongMe = this;
8843 status_t status = NO_ERROR;
8844
8845 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08008846 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08008847 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Andy Hung3ff4b552023-06-26 19:20:57 -07008848 recordTrack->synchronizedRecordState().startRecording(
Andy Hung2cbc2722023-07-17 17:05:00 -07008849 mAfThreadCallback->createSyncEvent(
Andy Hung93bb5732023-05-04 21:16:34 -07008850 event, triggerSession,
8851 recordTrack->sessionId(), syncStartEventCallback, recordTrack));
Eric Laurent81784c32012-11-19 14:55:58 -08008852 }
8853
8854 {
Glenn Kasten47c20702013-08-13 15:37:35 -07008855 // This section is a rendezvous between binder thread executing start() and RecordThread
Eric Laurent81784c32012-11-19 14:55:58 -08008856 AutoMutex lock(mLock);
Andy Hungce685402018-10-05 17:23:27 -07008857 if (recordTrack->isInvalid()) {
8858 recordTrack->clearSyncStartEvent();
Eric Laurentd52a28c2020-08-21 17:10:39 -07008859 ALOGW("%s track %d: invalidated before startInput", __func__, recordTrack->portId());
8860 return DEAD_OBJECT;
Andy Hungce685402018-10-05 17:23:27 -07008861 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008862 if (mActiveTracks.indexOf(recordTrack) >= 0) {
Andy Hung3ff4b552023-06-26 19:20:57 -07008863 if (recordTrack->state() == IAfTrackBase::PAUSING) {
Andy Hungce685402018-10-05 17:23:27 -07008864 // We haven't stopped yet (moved to PAUSED and not in mActiveTracks)
8865 // so no need to startInput().
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008866 ALOGV("active record track PAUSING -> ACTIVE");
Andy Hung3ff4b552023-06-26 19:20:57 -07008867 recordTrack->setState(IAfTrackBase::ACTIVE);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008868 } else {
Andy Hung3ff4b552023-06-26 19:20:57 -07008869 ALOGV("active record track state %d", (int)recordTrack->state());
Eric Laurent81784c32012-11-19 14:55:58 -08008870 }
8871 return status;
8872 }
8873
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08008874 // TODO consider other ways of handling this, such as changing the state to :STARTING and
8875 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
8876 // or using a separate command thread
Andy Hung3ff4b552023-06-26 19:20:57 -07008877 recordTrack->setState(IAfTrackBase::STARTING_1);
Glenn Kasten2b806402013-11-20 16:37:38 -08008878 mActiveTracks.add(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07008879 if (recordTrack->isExternalTrack()) {
8880 mLock.unlock();
Eric Laurent4eb58f12018-12-07 16:41:02 -08008881 status = AudioSystem::startInput(recordTrack->portId());
Eric Laurent83b88082014-06-20 18:31:16 -07008882 mLock.lock();
Andy Hungce685402018-10-05 17:23:27 -07008883 if (recordTrack->isInvalid()) {
8884 recordTrack->clearSyncStartEvent();
Andy Hung3ff4b552023-06-26 19:20:57 -07008885 if (status == NO_ERROR && recordTrack->state() == IAfTrackBase::STARTING_1) {
8886 recordTrack->setState(IAfTrackBase::STARTING_2);
Andy Hungce685402018-10-05 17:23:27 -07008887 // STARTING_2 forces destroy to call stopInput.
8888 }
Eric Laurentd52a28c2020-08-21 17:10:39 -07008889 ALOGW("%s track %d: invalidated after startInput", __func__, recordTrack->portId());
8890 return DEAD_OBJECT;
Andy Hungce685402018-10-05 17:23:27 -07008891 }
Andy Hung3ff4b552023-06-26 19:20:57 -07008892 if (recordTrack->state() != IAfTrackBase::STARTING_1) {
Andy Hungce685402018-10-05 17:23:27 -07008893 ALOGW("%s(%d): unsynchronized mState:%d change",
Andy Hung3ff4b552023-06-26 19:20:57 -07008894 __func__, recordTrack->id(), (int)recordTrack->state());
Andy Hungce685402018-10-05 17:23:27 -07008895 // Someone else has changed state, let them take over,
8896 // leave mState in the new state.
8897 recordTrack->clearSyncStartEvent();
8898 return INVALID_OPERATION;
8899 }
8900 // we're ok, but perhaps startInput has failed
Eric Laurent83b88082014-06-20 18:31:16 -07008901 if (status != NO_ERROR) {
Andy Hungce685402018-10-05 17:23:27 -07008902 ALOGW("%s(%d): startInput failed, status %d",
8903 __func__, recordTrack->id(), status);
8904 // We are in ActiveTracks if STARTING_1 and valid, so remove from ActiveTracks,
8905 // leave in STARTING_1, so destroy() will not call stopInput.
Eric Laurent83b88082014-06-20 18:31:16 -07008906 mActiveTracks.remove(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07008907 recordTrack->clearSyncStartEvent();
Eric Laurent83b88082014-06-20 18:31:16 -07008908 return status;
8909 }
Eric Laurent09f1ed22019-04-24 17:45:17 -07008910 sendIoConfigEvent_l(
8911 AUDIO_CLIENT_STARTED, recordTrack->creatorPid(), recordTrack->portId());
Eric Laurent81784c32012-11-19 14:55:58 -08008912 }
Andy Hungc2b11cb2020-04-22 09:04:01 -07008913
8914 recordTrack->logBeginInterval(patchSourcesToString(&mPatch)); // log to MediaMetrics
8915
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008916 // Catch up with current buffer indices if thread is already running.
8917 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
8918 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
8919 // see previously buffered data before it called start(), but with greater risk of overrun.
8920
Andy Hung3ff4b552023-06-26 19:20:57 -07008921 recordTrack->resamplerBufferProvider()->reset();
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008922 if (!recordTrack->isDirect()) {
8923 // clear any converter state as new data will be discontinuous
Andy Hung3ff4b552023-06-26 19:20:57 -07008924 recordTrack->recordBufferConverter()->reset();
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008925 }
Andy Hung3ff4b552023-06-26 19:20:57 -07008926 recordTrack->setState(IAfTrackBase::STARTING_2);
Eric Laurent81784c32012-11-19 14:55:58 -08008927 // signal thread to start
Eric Laurent81784c32012-11-19 14:55:58 -08008928 mWaitWorkCV.broadcast();
Eric Laurent81784c32012-11-19 14:55:58 -08008929 return status;
8930 }
Eric Laurent81784c32012-11-19 14:55:58 -08008931}
8932
Andy Hung71742ab2023-07-07 13:47:37 -07008933void RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
Eric Laurent81784c32012-11-19 14:55:58 -08008934{
Andy Hung71742ab2023-07-07 13:47:37 -07008935 const sp<SyncEvent> strongEvent = event.promote();
Eric Laurent81784c32012-11-19 14:55:58 -08008936
8937 if (strongEvent != 0) {
Andy Hung02a6c4e2023-06-23 19:27:19 -07008938 sp<IAfTrackBase> ptr =
8939 std::any_cast<const wp<IAfTrackBase>>(strongEvent->cookie()).promote();
8940 if (ptr != nullptr) {
Andy Hung56126702023-07-14 11:00:08 -07008941 // TODO(b/291317898) handleSyncStartEvent is in IAfTrackBase not IAfRecordTrack.
Andy Hung02a6c4e2023-06-23 19:27:19 -07008942 ptr->handleSyncStartEvent(strongEvent);
Eric Laurent8ea16e42014-02-20 16:26:11 -08008943 }
Eric Laurent81784c32012-11-19 14:55:58 -08008944 }
8945}
8946
Andy Hung71742ab2023-07-07 13:47:37 -07008947bool RecordThread::stop(IAfRecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08008948 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07008949 AutoMutex _l(mLock);
Andy Hungce685402018-10-05 17:23:27 -07008950 // if we're invalid, we can't be on the ActiveTracks.
Andy Hung3ff4b552023-06-26 19:20:57 -07008951 if (mActiveTracks.indexOf(recordTrack) < 0 || recordTrack->state() == IAfTrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08008952 return false;
8953 }
Glenn Kasten47c20702013-08-13 15:37:35 -07008954 // note that threadLoop may still be processing the track at this point [without lock]
Andy Hung3ff4b552023-06-26 19:20:57 -07008955 recordTrack->setState(IAfTrackBase::PAUSING);
Andy Hungce685402018-10-05 17:23:27 -07008956
Andy Hungabfab202019-03-07 19:45:54 -08008957 // NOTE: Waiting here is important to keep stop synchronous.
8958 // This is needed for proper patchRecord peer release.
Andy Hung3ff4b552023-06-26 19:20:57 -07008959 while (recordTrack->state() == IAfTrackBase::PAUSING && !recordTrack->isInvalid()) {
Andy Hungce685402018-10-05 17:23:27 -07008960 mWaitWorkCV.broadcast(); // signal thread to stop
8961 mStartStopCond.wait(mLock);
Eric Laurent81784c32012-11-19 14:55:58 -08008962 }
Andy Hungce685402018-10-05 17:23:27 -07008963
Andy Hung3ff4b552023-06-26 19:20:57 -07008964 if (recordTrack->state() == IAfTrackBase::PAUSED) { // successful stop
Eric Laurent81784c32012-11-19 14:55:58 -08008965 ALOGV("Record stopped OK");
8966 return true;
8967 }
Andy Hungce685402018-10-05 17:23:27 -07008968
8969 // don't handle anything - we've been invalidated or restarted and in a different state
8970 ALOGW_IF("%s(%d): unsynchronized stop, state: %d",
Andy Hung3ff4b552023-06-26 19:20:57 -07008971 __func__, recordTrack->id(), recordTrack->state());
Eric Laurent81784c32012-11-19 14:55:58 -08008972 return false;
8973}
8974
Andy Hung71742ab2023-07-07 13:47:37 -07008975bool RecordThread::isValidSyncEvent(const sp<SyncEvent>& /* event */) const
Eric Laurent81784c32012-11-19 14:55:58 -08008976{
8977 return false;
8978}
8979
Andy Hung71742ab2023-07-07 13:47:37 -07008980status_t RecordThread::setSyncEvent(const sp<SyncEvent>& /* event */)
Eric Laurent81784c32012-11-19 14:55:58 -08008981{
8982#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
8983 if (!isValidSyncEvent(event)) {
8984 return BAD_VALUE;
8985 }
8986
Glenn Kastend848eb42016-03-08 13:42:11 -08008987 audio_session_t eventSession = event->triggerSession();
Eric Laurent81784c32012-11-19 14:55:58 -08008988 status_t ret = NAME_NOT_FOUND;
8989
8990 Mutex::Autolock _l(mLock);
8991
8992 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung3ff4b552023-06-26 19:20:57 -07008993 sp<IAfRecordTrack> track = mTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08008994 if (eventSession == track->sessionId()) {
8995 (void) track->setSyncEvent(event);
8996 ret = NO_ERROR;
8997 }
8998 }
8999 return ret;
9000#else
9001 return BAD_VALUE;
9002#endif
9003}
9004
Andy Hung71742ab2023-07-07 13:47:37 -07009005status_t RecordThread::getActiveMicrophones(
Andy Hung44f27182023-07-06 20:56:16 -07009006 std::vector<media::MicrophoneInfoFw>* activeMicrophones) const
jiabin653cc0a2018-01-17 17:54:10 -08009007{
9008 ALOGV("RecordThread::getActiveMicrophones");
9009 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 }
jiabin9ff780e2018-03-19 18:19:52 -07009013 status_t status = mInput->stream->getActiveMicrophones(activeMicrophones);
9014 return status;
jiabin653cc0a2018-01-17 17:54:10 -08009015}
9016
Andy Hung71742ab2023-07-07 13:47:37 -07009017status_t RecordThread::setPreferredMicrophoneDirection(
Paul McLean12340082019-03-19 09:35:05 -06009018 audio_microphone_direction_t direction)
Paul McLean03a6e6a2018-12-04 10:54:13 -07009019{
Paul McLean12340082019-03-19 09:35:05 -06009020 ALOGV("setPreferredMicrophoneDirection(%d)", direction);
Paul McLean03a6e6a2018-12-04 10:54:13 -07009021 AutoMutex _l(mLock);
Jasmine Chaeaa10e42021-05-11 10:11:14 +08009022 if (!isStreamInitialized()) {
Paul McLean8a661a32021-04-12 10:21:42 -06009023 return NO_INIT;
9024 }
Paul McLean12340082019-03-19 09:35:05 -06009025 return mInput->stream->setPreferredMicrophoneDirection(direction);
Paul McLean03a6e6a2018-12-04 10:54:13 -07009026}
9027
Andy Hung71742ab2023-07-07 13:47:37 -07009028status_t RecordThread::setPreferredMicrophoneFieldDimension(float zoom)
Paul McLean03a6e6a2018-12-04 10:54:13 -07009029{
Paul McLean12340082019-03-19 09:35:05 -06009030 ALOGV("setPreferredMicrophoneFieldDimension(%f)", zoom);
Paul McLean03a6e6a2018-12-04 10:54:13 -07009031 AutoMutex _l(mLock);
Jasmine Chaeaa10e42021-05-11 10:11:14 +08009032 if (!isStreamInitialized()) {
Paul McLean8a661a32021-04-12 10:21:42 -06009033 return NO_INIT;
9034 }
Paul McLean12340082019-03-19 09:35:05 -06009035 return mInput->stream->setPreferredMicrophoneFieldDimension(zoom);
Paul McLean03a6e6a2018-12-04 10:54:13 -07009036}
9037
Andy Hung71742ab2023-07-07 13:47:37 -07009038status_t RecordThread::shareAudioHistory(
Eric Laurentec376dc2021-04-08 20:41:22 +02009039 const std::string& sharedAudioPackageName, audio_session_t sharedSessionId,
9040 int64_t sharedAudioStartMs) {
9041 AutoMutex _l(mLock);
9042 return shareAudioHistory_l(sharedAudioPackageName, sharedSessionId, sharedAudioStartMs);
9043}
9044
Andy Hung71742ab2023-07-07 13:47:37 -07009045status_t RecordThread::shareAudioHistory_l(
Eric Laurentec376dc2021-04-08 20:41:22 +02009046 const std::string& sharedAudioPackageName, audio_session_t sharedSessionId,
9047 int64_t sharedAudioStartMs) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009048
Eric Laurentec376dc2021-04-08 20:41:22 +02009049 if ((hasAudioSession_l(sharedSessionId) & ThreadBase::TRACK_SESSION) == 0) {
9050 return BAD_VALUE;
9051 }
Eric Laurent2407ce32021-04-26 14:56:03 +02009052
9053 if (sharedAudioStartMs < 0
9054 || sharedAudioStartMs > INT64_MAX / mSampleRate) {
Eric Laurentec376dc2021-04-08 20:41:22 +02009055 return BAD_VALUE;
9056 }
9057
Eric Laurent2407ce32021-04-26 14:56:03 +02009058 // Current implementation of the input resampling buffer wraps around indexes at 32 bit.
9059 // As we cannot detect more than one wraparound, only accept values up current write position
9060 // after one wraparound
9061 // We assume recent wraparounds on mRsmpInRear only given it is unlikely that the requesting
9062 // app waits several hours after the start time was computed.
Eric Laurent92d0a322021-07-16 15:32:33 +02009063 int64_t sharedAudioStartFrames = sharedAudioStartMs * mSampleRate / 1000;
Eric Laurent2407ce32021-04-26 14:56:03 +02009064 const int32_t sharedOffset = audio_utils::safe_sub_overflow(mRsmpInRear,
9065 (int32_t)sharedAudioStartFrames);
Eric Laurent92d0a322021-07-16 15:32:33 +02009066 // Bring the start frame position within the input buffer to match the documented
9067 // "best effort" behavior of the API.
9068 if (sharedOffset < 0) {
9069 sharedAudioStartFrames = mRsmpInRear;
Andy Hung71ba4b32022-10-06 12:09:49 -07009070 } else if (sharedOffset > static_cast<signed>(mRsmpInFrames)) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009071 sharedAudioStartFrames =
9072 audio_utils::safe_sub_overflow(mRsmpInRear, (int32_t)mRsmpInFrames);
Eric Laurent2407ce32021-04-26 14:56:03 +02009073 }
9074
Eric Laurentec376dc2021-04-08 20:41:22 +02009075 mSharedAudioPackageName = sharedAudioPackageName;
9076 if (mSharedAudioPackageName.empty()) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009077 resetAudioHistory_l();
Eric Laurentec376dc2021-04-08 20:41:22 +02009078 } else {
9079 mSharedAudioSessionId = sharedSessionId;
Eric Laurent2407ce32021-04-26 14:56:03 +02009080 mSharedAudioStartFrames = (int32_t)sharedAudioStartFrames;
Eric Laurentec376dc2021-04-08 20:41:22 +02009081 }
9082 return NO_ERROR;
9083}
9084
Andy Hung71742ab2023-07-07 13:47:37 -07009085void RecordThread::resetAudioHistory_l() {
Eric Laurent92d0a322021-07-16 15:32:33 +02009086 mSharedAudioSessionId = AUDIO_SESSION_NONE;
9087 mSharedAudioStartFrames = -1;
9088 mSharedAudioPackageName = "";
9089}
9090
Andy Hung71742ab2023-07-07 13:47:37 -07009091ThreadBase::MetadataUpdate RecordThread::updateMetadata_l()
Kevin Rocard069c2712018-03-29 19:09:14 -07009092{
Jasmine Chaeaa10e42021-05-11 10:11:14 +08009093 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
Vlad Popa7e81cea2023-01-19 16:34:16 +01009094 return {}; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -07009095 }
9096 StreamInHalInterface::SinkMetadata metadata;
Eric Laurent78b07302022-10-07 16:20:34 +02009097 auto backInserter = std::back_inserter(metadata.tracks);
Andy Hung3ff4b552023-06-26 19:20:57 -07009098 for (const sp<IAfRecordTrack>& track : mActiveTracks) {
Eric Laurent78b07302022-10-07 16:20:34 +02009099 track->copyMetadataTo(backInserter);
Kevin Rocard069c2712018-03-29 19:09:14 -07009100 }
9101 mInput->stream->updateSinkMetadata(metadata);
Vlad Popa7e81cea2023-01-19 16:34:16 +01009102 MetadataUpdate change;
9103 change.recordMetadataUpdate = metadata.tracks;
9104 return change;
Kevin Rocard069c2712018-03-29 19:09:14 -07009105}
9106
Eric Laurent81784c32012-11-19 14:55:58 -08009107// destroyTrack_l() must be called with ThreadBase::mLock held
Andy Hung71742ab2023-07-07 13:47:37 -07009108void RecordThread::destroyTrack_l(const sp<IAfRecordTrack>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08009109{
Eric Laurentbfb1b832013-01-07 09:53:42 -08009110 track->terminate();
Andy Hung3ff4b552023-06-26 19:20:57 -07009111 track->setState(IAfTrackBase::STOPPED);
Eric Laurentec376dc2021-04-08 20:41:22 +02009112
Eric Laurent81784c32012-11-19 14:55:58 -08009113 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08009114 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08009115 removeTrack_l(track);
9116 }
9117}
9118
Andy Hung71742ab2023-07-07 13:47:37 -07009119void RecordThread::removeTrack_l(const sp<IAfRecordTrack>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08009120{
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009121 String8 result;
9122 track->appendDump(result, false /* active */);
Tomasz Wasilczyk8f36f6e2023-08-15 20:59:35 +00009123 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.c_str());
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009124
Eric Laurent81784c32012-11-19 14:55:58 -08009125 mTracks.remove(track);
9126 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07009127 if (track->isFastTrack()) {
9128 ALOG_ASSERT(!mFastTrackAvail);
9129 mFastTrackAvail = true;
9130 }
Eric Laurent81784c32012-11-19 14:55:58 -08009131}
9132
Andy Hung71742ab2023-07-07 13:47:37 -07009133void RecordThread::dumpInternals_l(int fd, const Vector<String16>& /* args */)
Eric Laurent81784c32012-11-19 14:55:58 -08009134{
Mikhail Naganov913d06c2016-11-01 12:49:22 -07009135 AudioStreamIn *input = mInput;
9136 audio_input_flags_t flags = input != NULL ? input->flags : AUDIO_INPUT_FLAG_NONE;
9137 dprintf(fd, " AudioStreamIn: %p flags %#x (%s)\n",
Andy Hung9b181952019-02-25 14:53:36 -08009138 input, flags, toString(flags).c_str());
Andy Hung6427e442018-08-09 12:51:02 -07009139 dprintf(fd, " Frames read: %lld\n", (long long)mFramesRead);
Eric Tan39ec8d62018-07-24 09:49:29 -07009140 if (mActiveTracks.isEmpty()) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07009141 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08009142 }
Andy Hungbfa64962017-06-12 14:43:19 -07009143
9144 if (input != nullptr) {
9145 dprintf(fd, " Hal stream dump:\n");
9146 (void)input->stream->dump(fd);
9147 }
9148
Glenn Kasten6e6704c2014-07-03 10:20:00 -07009149 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07009150 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Glenn Kasten17c9c992015-03-02 15:53:01 -08009151
Glenn Kasten2f90c512015-12-02 11:40:09 -08009152 // Make a non-atomic copy of fast capture dump state so it won't change underneath us
9153 // while we are dumping it. It may be inconsistent, but it won't mutate!
9154 // This is a large object so we place it on the heap.
9155 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
Eric Tan2942a4e2018-09-12 17:41:27 -07009156 const std::unique_ptr<FastCaptureDumpState> copy =
9157 std::make_unique<FastCaptureDumpState>(mFastCaptureDumpState);
Glenn Kasten2f90c512015-12-02 11:40:09 -08009158 copy->dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08009159}
9160
Andy Hung71742ab2023-07-07 13:47:37 -07009161void RecordThread::dumpTracks_l(int fd, const Vector<String16>& /* args */)
Eric Laurent81784c32012-11-19 14:55:58 -08009162{
Eric Laurent81784c32012-11-19 14:55:58 -08009163 String8 result;
Marco Nelissenb2208842014-02-07 14:00:50 -08009164 size_t numtracks = mTracks.size();
9165 size_t numactive = mActiveTracks.size();
9166 size_t numactiveseen = 0;
Glenn Kastenc42e9b42016-03-21 11:35:03 -07009167 dprintf(fd, " %zu Tracks", numtracks);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009168 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08009169 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07009170 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009171 result.append(prefix);
Andy Hung000adb52018-06-01 15:43:26 -07009172 mTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08009173 for (size_t i = 0; i < numtracks ; ++i) {
Andy Hung3ff4b552023-06-26 19:20:57 -07009174 sp<IAfRecordTrack> track = mTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08009175 if (track != 0) {
9176 bool active = mActiveTracks.indexOf(track) >= 0;
9177 if (active) {
9178 numactiveseen++;
9179 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009180 result.append(prefix);
9181 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08009182 }
Eric Laurent81784c32012-11-19 14:55:58 -08009183 }
Marco Nelissenb2208842014-02-07 14:00:50 -08009184 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07009185 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08009186 }
9187
Marco Nelissenb2208842014-02-07 14:00:50 -08009188 if (numactiveseen != numactive) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009189 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08009190 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009191 result.append(prefix);
Andy Hung000adb52018-06-01 15:43:26 -07009192 mActiveTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08009193 for (size_t i = 0; i < numactive; ++i) {
Andy Hung3ff4b552023-06-26 19:20:57 -07009194 sp<IAfRecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08009195 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009196 result.append(prefix);
9197 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08009198 }
Glenn Kasten2b806402013-11-20 16:37:38 -08009199 }
Eric Laurent81784c32012-11-19 14:55:58 -08009200
9201 }
Tomasz Wasilczyk8f36f6e2023-08-15 20:59:35 +00009202 write(fd, result.c_str(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08009203}
9204
Andy Hung71742ab2023-07-07 13:47:37 -07009205void RecordThread::setRecordSilenced(audio_port_handle_t portId, bool silenced)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08009206{
9207 Mutex::Autolock _l(mLock);
9208 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hung3ff4b552023-06-26 19:20:57 -07009209 sp<IAfRecordTrack> track = mTracks[i];
Eric Laurent5ada82e2019-08-29 17:53:54 -07009210 if (track != 0 && track->portId() == portId) {
Svet Ganovf4ddfef2018-01-16 07:37:58 -08009211 track->setSilenced(silenced);
9212 }
9213 }
9214}
Andy Hung73c02e42015-03-29 01:13:58 -07009215
Andy Hung3ff4b552023-06-26 19:20:57 -07009216void ResamplerBufferProvider::reset()
Andy Hung73c02e42015-03-29 01:13:58 -07009217{
Andy Hung44f27182023-07-06 20:56:16 -07009218 const auto threadBase = mRecordTrack->thread().promote();
Andy Hung71742ab2023-07-07 13:47:37 -07009219 auto* const recordThread = static_cast<RecordThread *>(threadBase->asIAfRecordThread().get());
Andy Hung73c02e42015-03-29 01:13:58 -07009220 mRsmpInUnrel = 0;
Eric Laurentec376dc2021-04-08 20:41:22 +02009221 const int32_t rear = recordThread->mRsmpInRear;
9222 ssize_t deltaFrames = 0;
Eric Laurent2407ce32021-04-26 14:56:03 +02009223 if (mRecordTrack->startFrames() >= 0) {
9224 int32_t startFrames = mRecordTrack->startFrames();
9225 // Accept a recent wraparound of mRsmpInRear
9226 if (startFrames <= rear) {
9227 deltaFrames = rear - startFrames;
9228 } else {
9229 deltaFrames = (int32_t)((int64_t)rear + UINT32_MAX + 1 - startFrames);
Eric Laurentec376dc2021-04-08 20:41:22 +02009230 }
Eric Laurentec376dc2021-04-08 20:41:22 +02009231 // start frame cannot be further in the past than start of resampling buffer
9232 if ((size_t) deltaFrames > recordThread->mRsmpInFrames) {
9233 deltaFrames = recordThread->mRsmpInFrames;
9234 }
9235 }
9236 mRsmpInFront = audio_utils::safe_sub_overflow(rear, static_cast<int32_t>(deltaFrames));
Andy Hung73c02e42015-03-29 01:13:58 -07009237}
9238
Andy Hung3ff4b552023-06-26 19:20:57 -07009239void ResamplerBufferProvider::sync(
Andy Hung73c02e42015-03-29 01:13:58 -07009240 size_t *framesAvailable, bool *hasOverrun)
9241{
Andy Hung44f27182023-07-06 20:56:16 -07009242 const auto threadBase = mRecordTrack->thread().promote();
Andy Hung71742ab2023-07-07 13:47:37 -07009243 auto* const recordThread = static_cast<RecordThread *>(threadBase->asIAfRecordThread().get());
Andy Hung73c02e42015-03-29 01:13:58 -07009244 const int32_t rear = recordThread->mRsmpInRear;
9245 const int32_t front = mRsmpInFront;
Hongwei Wang95e37682019-04-12 11:13:36 -07009246 const ssize_t filled = audio_utils::safe_sub_overflow(rear, front);
Andy Hung73c02e42015-03-29 01:13:58 -07009247
9248 size_t framesIn;
9249 bool overrun = false;
9250 if (filled < 0) {
9251 // should not happen, but treat like a massive overrun and re-sync
9252 framesIn = 0;
9253 mRsmpInFront = rear;
9254 overrun = true;
9255 } else if ((size_t) filled <= recordThread->mRsmpInFrames) {
9256 framesIn = (size_t) filled;
9257 } else {
9258 // client is not keeping up with server, but give it latest data
9259 framesIn = recordThread->mRsmpInFrames;
Hongwei Wang95e37682019-04-12 11:13:36 -07009260 mRsmpInFront = /* front = */ audio_utils::safe_sub_overflow(
9261 rear, static_cast<int32_t>(framesIn));
Andy Hung73c02e42015-03-29 01:13:58 -07009262 overrun = true;
9263 }
9264 if (framesAvailable != NULL) {
9265 *framesAvailable = framesIn;
9266 }
9267 if (hasOverrun != NULL) {
9268 *hasOverrun = overrun;
9269 }
9270}
9271
Eric Laurent81784c32012-11-19 14:55:58 -08009272// AudioBufferProvider interface
Andy Hung3ff4b552023-06-26 19:20:57 -07009273status_t ResamplerBufferProvider::getNextBuffer(
Glenn Kastend79072e2016-01-06 08:41:20 -08009274 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08009275{
Andy Hung44f27182023-07-06 20:56:16 -07009276 const auto threadBase = mRecordTrack->thread().promote();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009277 if (threadBase == 0) {
9278 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08009279 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009280 return NOT_ENOUGH_DATA;
9281 }
Andy Hung71742ab2023-07-07 13:47:37 -07009282 auto* const recordThread = static_cast<RecordThread *>(threadBase->asIAfRecordThread().get());
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009283 int32_t rear = recordThread->mRsmpInRear;
Andy Hung73c02e42015-03-29 01:13:58 -07009284 int32_t front = mRsmpInFront;
Hongwei Wang95e37682019-04-12 11:13:36 -07009285 ssize_t filled = audio_utils::safe_sub_overflow(rear, front);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009286 // FIXME should not be P2 (don't want to increase latency)
9287 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08009288 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07009289 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009290
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009291 front &= recordThread->mRsmpInFramesP2 - 1;
9292 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07009293 if (part1 > (size_t) filled) {
9294 part1 = filled;
9295 }
9296 size_t ask = buffer->frameCount;
9297 ALOG_ASSERT(ask > 0);
9298 if (part1 > ask) {
9299 part1 = ask;
9300 }
9301 if (part1 == 0) {
Andy Hung73c02e42015-03-29 01:13:58 -07009302 // out of data is fine since the resampler will return a short-count.
Glenn Kasten85948432013-08-19 12:09:05 -07009303 buffer->raw = NULL;
9304 buffer->frameCount = 0;
Andy Hung73c02e42015-03-29 01:13:58 -07009305 mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07009306 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08009307 }
9308
Andy Hung57446612015-04-19 23:56:46 -07009309 buffer->raw = (uint8_t*)recordThread->mRsmpInBuffer + front * recordThread->mFrameSize;
Glenn Kasten85948432013-08-19 12:09:05 -07009310 buffer->frameCount = part1;
Andy Hung73c02e42015-03-29 01:13:58 -07009311 mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08009312 return NO_ERROR;
9313}
9314
9315// AudioBufferProvider interface
Andy Hung3ff4b552023-06-26 19:20:57 -07009316void ResamplerBufferProvider::releaseBuffer(
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009317 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08009318{
Hongwei Wang95e37682019-04-12 11:13:36 -07009319 int32_t stepCount = static_cast<int32_t>(buffer->frameCount);
Glenn Kasten85948432013-08-19 12:09:05 -07009320 if (stepCount == 0) {
9321 return;
9322 }
Eric Laurent1e28aaa2023-04-16 19:34:23 +02009323 ALOG_ASSERT(stepCount <= (int32_t)mRsmpInUnrel);
Andy Hung73c02e42015-03-29 01:13:58 -07009324 mRsmpInUnrel -= stepCount;
Hongwei Wang95e37682019-04-12 11:13:36 -07009325 mRsmpInFront = audio_utils::safe_add_overflow(mRsmpInFront, stepCount);
Glenn Kasten85948432013-08-19 12:09:05 -07009326 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08009327 buffer->frameCount = 0;
9328}
9329
Andy Hung71742ab2023-07-07 13:47:37 -07009330void RecordThread::checkBtNrec()
Eric Laurentd8365c52017-07-16 15:27:05 -07009331{
9332 Mutex::Autolock _l(mLock);
9333 checkBtNrec_l();
9334}
9335
Andy Hung71742ab2023-07-07 13:47:37 -07009336void RecordThread::checkBtNrec_l()
Eric Laurentd8365c52017-07-16 15:27:05 -07009337{
9338 // disable AEC and NS if the device is a BT SCO headset supporting those
9339 // pre processings
jiabinc52b1ff2019-10-31 17:20:42 -07009340 bool suspend = audio_is_bluetooth_sco_device(inDeviceType()) &&
Andy Hung2cbc2722023-07-17 17:05:00 -07009341 mAfThreadCallback->btNrecIsOff();
Eric Laurentd8365c52017-07-16 15:27:05 -07009342 if (mBtNrecSuspended.exchange(suspend) != suspend) {
9343 for (size_t i = 0; i < mEffectChains.size(); i++) {
9344 setEffectSuspended_l(FX_IID_AEC, suspend, mEffectChains[i]->sessionId());
9345 setEffectSuspended_l(FX_IID_NS, suspend, mEffectChains[i]->sessionId());
9346 }
9347 }
9348}
9349
Andy Hung97a893e2015-03-29 01:03:07 -07009350
Andy Hung71742ab2023-07-07 13:47:37 -07009351bool RecordThread::checkForNewParameter_l(const String8& keyValuePair,
Eric Laurent10351942014-05-08 18:49:52 -07009352 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08009353{
9354 bool reconfig = false;
9355
Eric Laurent10351942014-05-08 18:49:52 -07009356 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08009357
Eric Laurent10351942014-05-08 18:49:52 -07009358 audio_format_t reqFormat = mFormat;
9359 uint32_t samplingRate = mSampleRate;
Glenn Kastene1635ec2015-06-08 15:46:49 -07009360 // 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 +08009361 [[maybe_unused]] audio_channel_mask_t channelMask =
9362 audio_channel_in_mask_from_count(mChannelCount);
Eric Laurent10351942014-05-08 18:49:52 -07009363
9364 AudioParameter param = AudioParameter(keyValuePair);
9365 int value;
Haynes Mathew George9ce67b52015-09-30 11:40:47 -07009366
9367 // scope for AutoPark extends to end of method
9368 AutoPark<FastCapture> park(mFastCapture);
9369
Eric Laurent10351942014-05-08 18:49:52 -07009370 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
9371 // channel count change can be requested. Do we mandate the first client defines the
9372 // HAL sampling rate and channel count or do we allow changes on the fly?
9373 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
9374 samplingRate = value;
9375 reconfig = true;
9376 }
9377 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung97a893e2015-03-29 01:03:07 -07009378 if (!audio_is_linear_pcm((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07009379 status = BAD_VALUE;
9380 } else {
9381 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08009382 reconfig = true;
9383 }
Eric Laurent10351942014-05-08 18:49:52 -07009384 }
9385 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
9386 audio_channel_mask_t mask = (audio_channel_mask_t) value;
Andy Hungd330ee42015-04-20 13:23:41 -07009387 if (!audio_is_input_channel(mask) ||
Andy Hung936845a2021-06-08 00:09:06 -07009388 audio_channel_count_from_in_mask(mask) > FCC_LIMIT) {
Eric Laurent10351942014-05-08 18:49:52 -07009389 status = BAD_VALUE;
9390 } else {
9391 channelMask = mask;
9392 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08009393 }
Eric Laurent10351942014-05-08 18:49:52 -07009394 }
9395 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
9396 // do not accept frame count changes if tracks are open as the track buffer
9397 // size depends on frame count and correct behavior would not be guaranteed
9398 // if frame count is changed after track creation
9399 if (mActiveTracks.size() > 0) {
9400 status = INVALID_OPERATION;
9401 } else {
9402 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08009403 }
Eric Laurent10351942014-05-08 18:49:52 -07009404 }
9405 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07009406 LOG_FATAL("Should not set routing device in RecordThread");
Eric Laurent10351942014-05-08 18:49:52 -07009407 }
9408 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
9409 mAudioSource != (audio_source_t)value) {
jiabinc52b1ff2019-10-31 17:20:42 -07009410 LOG_FATAL("Should not set audio source in RecordThread");
Eric Laurent10351942014-05-08 18:49:52 -07009411 }
Glenn Kastene198c362013-08-13 09:13:36 -07009412
Eric Laurent10351942014-05-08 18:49:52 -07009413 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009414 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07009415 if (status == INVALID_OPERATION) {
9416 inputStandBy();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009417 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07009418 }
9419 if (reconfig) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009420 if (status == BAD_VALUE) {
Mikhail Naganov560637e2021-03-31 22:40:13 +00009421 audio_config_base_t config = AUDIO_CONFIG_BASE_INITIALIZER;
9422 if (mInput->stream->getAudioProperties(&config) == OK &&
9423 audio_is_linear_pcm(config.format) && audio_is_linear_pcm(reqFormat) &&
9424 config.sample_rate <= (AUDIO_RESAMPLER_DOWN_RATIO_MAX * samplingRate) &&
Andy Hung936845a2021-06-08 00:09:06 -07009425 audio_channel_count_from_in_mask(config.channel_mask) <= FCC_LIMIT) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009426 status = NO_ERROR;
9427 }
Eric Laurent81784c32012-11-19 14:55:58 -08009428 }
Eric Laurent10351942014-05-08 18:49:52 -07009429 if (status == NO_ERROR) {
9430 readInputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07009431 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08009432 }
9433 }
Eric Laurent81784c32012-11-19 14:55:58 -08009434 }
Eric Laurent10351942014-05-08 18:49:52 -07009435
Eric Laurent81784c32012-11-19 14:55:58 -08009436 return reconfig;
9437}
9438
Andy Hung71742ab2023-07-07 13:47:37 -07009439String8 RecordThread::getParameters(const String8& keys)
Eric Laurent81784c32012-11-19 14:55:58 -08009440{
Eric Laurent81784c32012-11-19 14:55:58 -08009441 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009442 if (initCheck() == NO_ERROR) {
9443 String8 out_s8;
9444 if (mInput->stream->getParameters(keys, &out_s8) == OK) {
9445 return out_s8;
9446 }
Eric Laurent81784c32012-11-19 14:55:58 -08009447 }
Andy Hung71ba4b32022-10-06 12:09:49 -07009448 return {};
Eric Laurent81784c32012-11-19 14:55:58 -08009449}
9450
Andy Hung71742ab2023-07-07 13:47:37 -07009451void RecordThread::ioConfigChanged(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -07009452 audio_port_handle_t portId) {
Mikhail Naganov88536df2021-07-26 17:30:29 -07009453 sp<AudioIoDescriptor> desc;
Eric Laurent81784c32012-11-19 14:55:58 -08009454 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07009455 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07009456 case AUDIO_INPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07009457 case AUDIO_INPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07009458 desc = sp<AudioIoDescriptor>::make(mId, mPatch, true /*isInput*/,
9459 mSampleRate, mFormat, mChannelMask, mFrameCount, mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08009460 break;
Eric Laurent09f1ed22019-04-24 17:45:17 -07009461 case AUDIO_CLIENT_STARTED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07009462 desc = sp<AudioIoDescriptor>::make(mId, mPatch, portId);
Eric Laurent09f1ed22019-04-24 17:45:17 -07009463 break;
Eric Laurent73e26b62015-04-27 16:55:58 -07009464 case AUDIO_INPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08009465 default:
Mikhail Naganov88536df2021-07-26 17:30:29 -07009466 desc = sp<AudioIoDescriptor>::make(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08009467 break;
9468 }
Andy Hung2cbc2722023-07-17 17:05:00 -07009469 mAfThreadCallback->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08009470}
9471
Andy Hung71742ab2023-07-07 13:47:37 -07009472void RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08009473{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009474 status_t result = mInput->stream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
9475 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
Andy Hung463be252014-07-10 16:56:07 -07009476 mFormat = mHALFormat;
Mikhail Naganovce9f2652018-07-16 11:09:24 -07009477 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
9478 if (audio_is_linear_pcm(mFormat)) {
Andy Hung936845a2021-06-08 00:09:06 -07009479 LOG_ALWAYS_FATAL_IF(mChannelCount > FCC_LIMIT, "HAL channel count %d > %d",
9480 mChannelCount, FCC_LIMIT);
Mikhail Naganovce9f2652018-07-16 11:09:24 -07009481 } else {
Andy Hung936845a2021-06-08 00:09:06 -07009482 // Can have more that FCC_LIMIT channels in encoded streams.
Mikhail Naganovce9f2652018-07-16 11:09:24 -07009483 ALOGI("HAL format %#x is not linear pcm", mFormat);
9484 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009485 result = mInput->stream->getFrameSize(&mFrameSize);
9486 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
Hayden Gomes1a89ab32020-06-12 11:05:47 -07009487 LOG_ALWAYS_FATAL_IF(mFrameSize <= 0, "Error frame size was %zu but must be greater than zero",
9488 mFrameSize);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009489 result = mInput->stream->getBufferSize(&mBufferSize);
9490 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
Glenn Kasten548efc92012-11-29 08:48:51 -08009491 mFrameCount = mBufferSize / mFrameSize;
Hayden Gomes1a89ab32020-06-12 11:05:47 -07009492 ALOGV("%p RecordThread params: mChannelCount=%u, mFormat=%#x, mFrameSize=%zu, "
9493 "mBufferSize=%zu, mFrameCount=%zu",
9494 this, mChannelCount, mFormat, mFrameSize, mBufferSize, mFrameCount);
Glenn Kasten49d00ad2014-07-21 11:22:03 -07009495
Eric Laurentec376dc2021-04-08 20:41:22 +02009496 // mRsmpInFrames must be 0 before calling resizeInputBuffer_l for the first time
9497 mRsmpInFrames = 0;
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009498 resizeInputBuffer_l(0 /*maxSharedAudioHistoryMs*/);
Eric Laurent81784c32012-11-19 14:55:58 -08009499
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08009500 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
9501 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Andy Hungea840382020-05-05 21:50:17 -07009502
9503 audio_input_flags_t flags = mInput->flags;
9504 mediametrics::LogItem item(mThreadMetrics.getMetricsId());
9505 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
9506 .set(AMEDIAMETRICS_PROP_ENCODING, formatToString(mFormat).c_str())
9507 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
9508 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
9509 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
9510 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
9511 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mFrameCount)
9512 .record();
Eric Laurent81784c32012-11-19 14:55:58 -08009513}
9514
Andy Hung71742ab2023-07-07 13:47:37 -07009515uint32_t RecordThread::getInputFramesLost() const
Eric Laurent81784c32012-11-19 14:55:58 -08009516{
9517 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009518 uint32_t result;
9519 if (initCheck() == NO_ERROR && mInput->stream->getInputFramesLost(&result) == OK) {
9520 return result;
Eric Laurent81784c32012-11-19 14:55:58 -08009521 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009522 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08009523}
9524
Andy Hung71742ab2023-07-07 13:47:37 -07009525KeyedVector<audio_session_t, bool> RecordThread::sessionIds() const
Eric Laurent81784c32012-11-19 14:55:58 -08009526{
Glenn Kastend848eb42016-03-08 13:42:11 -08009527 KeyedVector<audio_session_t, bool> ids;
Eric Laurent81784c32012-11-19 14:55:58 -08009528 Mutex::Autolock _l(mLock);
9529 for (size_t j = 0; j < mTracks.size(); ++j) {
Andy Hung3ff4b552023-06-26 19:20:57 -07009530 sp<IAfRecordTrack> track = mTracks[j];
Glenn Kastend848eb42016-03-08 13:42:11 -08009531 audio_session_t sessionId = track->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08009532 if (ids.indexOfKey(sessionId) < 0) {
9533 ids.add(sessionId, true);
9534 }
9535 }
9536 return ids;
9537}
9538
Andy Hung71742ab2023-07-07 13:47:37 -07009539AudioStreamIn* RecordThread::clearInput()
Eric Laurent81784c32012-11-19 14:55:58 -08009540{
9541 Mutex::Autolock _l(mLock);
9542 AudioStreamIn *input = mInput;
9543 mInput = NULL;
Mikhail Naganov49aecf02023-09-08 15:14:34 -07009544 mInputSource.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08009545 return input;
9546}
9547
9548// this method must always be called either with ThreadBase mLock held or inside the thread loop
Andy Hung71742ab2023-07-07 13:47:37 -07009549sp<StreamHalInterface> RecordThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08009550{
9551 if (mInput == NULL) {
9552 return NULL;
9553 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009554 return mInput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08009555}
9556
Andy Hung71742ab2023-07-07 13:47:37 -07009557status_t RecordThread::addEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08009558{
Eric Laurent81784c32012-11-19 14:55:58 -08009559 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurentaaa44472014-09-12 17:41:50 -07009560 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08009561 chain->setInBuffer(NULL);
9562 chain->setOutBuffer(NULL);
9563
9564 checkSuspendOnAddEffectChain_l(chain);
9565
Eric Laurent1b928682014-10-02 19:41:47 -07009566 // make sure enabled pre processing effects state is communicated to the HAL as we
9567 // just moved them to a new input stream.
9568 chain->syncHalEffectsState();
9569
Eric Laurent81784c32012-11-19 14:55:58 -08009570 mEffectChains.add(chain);
9571
9572 return NO_ERROR;
9573}
9574
Andy Hung71742ab2023-07-07 13:47:37 -07009575size_t RecordThread::removeEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08009576{
9577 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
Eric Laurentb20cf7d2019-04-05 19:37:34 -07009578
9579 for (size_t i = 0; i < mEffectChains.size(); i++) {
9580 if (chain == mEffectChains[i]) {
9581 mEffectChains.removeAt(i);
9582 break;
9583 }
Eric Laurent81784c32012-11-19 14:55:58 -08009584 }
Eric Laurentb20cf7d2019-04-05 19:37:34 -07009585 return mEffectChains.size();
Eric Laurent81784c32012-11-19 14:55:58 -08009586}
9587
Andy Hung71742ab2023-07-07 13:47:37 -07009588status_t RecordThread::createAudioPatch_l(const struct audio_patch* patch,
Eric Laurent1c333e22014-05-20 10:48:17 -07009589 audio_patch_handle_t *handle)
9590{
9591 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07009592
9593 // store new device and send to effects
jiabinc52b1ff2019-10-31 17:20:42 -07009594 mInDeviceTypeAddr.mType = patch->sources[0].ext.device.type;
jiabin0a488932020-08-07 17:32:40 -07009595 mInDeviceTypeAddr.setAddress(patch->sources[0].ext.device.address);
François Gaffie0c280aa2018-07-25 10:02:15 +02009596 audio_port_handle_t deviceId = patch->sources[0].id;
Eric Laurent054d9d32015-04-24 08:48:48 -07009597 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08009598 mEffectChains[i]->setInputDevice_l(inDeviceTypeAddr());
Eric Laurent054d9d32015-04-24 08:48:48 -07009599 }
9600
Eric Laurentd8365c52017-07-16 15:27:05 -07009601 checkBtNrec_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07009602
9603 // store new source and send to effects
9604 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
9605 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent1c333e22014-05-20 10:48:17 -07009606 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent054d9d32015-04-24 08:48:48 -07009607 mEffectChains[i]->setAudioSource_l(mAudioSource);
Eric Laurent1c333e22014-05-20 10:48:17 -07009608 }
Eric Laurent054d9d32015-04-24 08:48:48 -07009609 }
Eric Laurent1c333e22014-05-20 10:48:17 -07009610
Mikhail Naganov9ee05402016-10-13 15:58:17 -07009611 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07009612 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
9613 status = hwDevice->createAudioPatch(patch->num_sources,
9614 patch->sources,
9615 patch->num_sinks,
9616 patch->sinks,
9617 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07009618 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08009619 status = mInput->stream->legacyCreateAudioPatch(patch->sources[0],
9620 patch->sinks[0].ext.mix.usecase.source,
9621 patch->sources[0].ext.device.type);
Eric Laurent054d9d32015-04-24 08:48:48 -07009622 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07009623 }
Eric Laurent054d9d32015-04-24 08:48:48 -07009624
jiabinc52b1ff2019-10-31 17:20:42 -07009625 if ((mPatch.num_sources == 0) || (mPatch.sources[0].id != deviceId)) {
Eric Laurente8726fe2015-06-26 09:39:24 -07009626 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
jiabinc52b1ff2019-10-31 17:20:42 -07009627 mPatch = *patch;
Eric Laurente8726fe2015-06-26 09:39:24 -07009628 }
Eric Laurent296fb132015-05-01 11:38:42 -07009629
Andy Hungc2b11cb2020-04-22 09:04:01 -07009630 const std::string pathSourcesAsString = patchSourcesToString(patch);
Andy Hungcf10d742020-04-28 15:38:24 -07009631 mThreadMetrics.logEndInterval();
Andy Hungea840382020-05-05 21:50:17 -07009632 mThreadMetrics.logCreatePatch(pathSourcesAsString, /* outDevices */ {});
Andy Hungcf10d742020-04-28 15:38:24 -07009633 mThreadMetrics.logBeginInterval();
Andy Hungc2b11cb2020-04-22 09:04:01 -07009634 // also dispatch to active AudioRecords
9635 for (const auto &track : mActiveTracks) {
9636 track->logEndInterval();
9637 track->logBeginInterval(pathSourcesAsString);
9638 }
Eric Laurentdda206a2022-07-08 17:28:35 +02009639 // Force meteadata update after a route change
9640 mActiveTracks.setHasChanged();
9641
Eric Laurent1c333e22014-05-20 10:48:17 -07009642 return status;
9643}
9644
Andy Hung71742ab2023-07-07 13:47:37 -07009645status_t RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
Eric Laurent1c333e22014-05-20 10:48:17 -07009646{
9647 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07009648
jiabinc52b1ff2019-10-31 17:20:42 -07009649 mPatch = audio_patch{};
9650 mInDeviceTypeAddr.reset();
Eric Laurent054d9d32015-04-24 08:48:48 -07009651
Mikhail Naganov9ee05402016-10-13 15:58:17 -07009652 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07009653 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
9654 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07009655 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08009656 status = mInput->stream->legacyReleaseAudioPatch();
Eric Laurent1c333e22014-05-20 10:48:17 -07009657 }
Eric Laurentdda206a2022-07-08 17:28:35 +02009658 // Force meteadata update after a route change
9659 mActiveTracks.setHasChanged();
9660
Eric Laurent1c333e22014-05-20 10:48:17 -07009661 return status;
9662}
9663
Andy Hung71742ab2023-07-07 13:47:37 -07009664void RecordThread::updateOutDevices(const DeviceDescriptorBaseVector& outDevices)
jiabinc52b1ff2019-10-31 17:20:42 -07009665{
wendy lin56aa82b2020-12-02 15:19:55 +08009666 Mutex::Autolock _l(mLock);
jiabinc52b1ff2019-10-31 17:20:42 -07009667 mOutDevices = outDevices;
9668 mOutDeviceTypeAddrs = deviceTypeAddrsFromDescriptors(mOutDevices);
9669 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08009670 mEffectChains[i]->setDevices_l(outDeviceTypeAddrs());
jiabinc52b1ff2019-10-31 17:20:42 -07009671 }
9672}
9673
Andy Hung71742ab2023-07-07 13:47:37 -07009674int32_t RecordThread::getOldestFront_l()
Eric Laurentec376dc2021-04-08 20:41:22 +02009675{
9676 if (mTracks.size() == 0) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009677 return mRsmpInRear;
Eric Laurentec376dc2021-04-08 20:41:22 +02009678 }
Eric Laurent2407ce32021-04-26 14:56:03 +02009679 int32_t oldestFront = mRsmpInRear;
9680 int32_t maxFilled = 0;
Eric Laurentec376dc2021-04-08 20:41:22 +02009681 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung3ff4b552023-06-26 19:20:57 -07009682 int32_t front = mTracks[i]->resamplerBufferProvider()->getFront();
Eric Laurent2407ce32021-04-26 14:56:03 +02009683 int32_t filled;
Eric Laurent92d0a322021-07-16 15:32:33 +02009684 (void)__builtin_sub_overflow(mRsmpInRear, front, &filled);
Eric Laurent2407ce32021-04-26 14:56:03 +02009685 if (filled > maxFilled) {
9686 oldestFront = front;
9687 maxFilled = filled;
9688 }
Eric Laurentec376dc2021-04-08 20:41:22 +02009689 }
Andy Hung71ba4b32022-10-06 12:09:49 -07009690 if (maxFilled > static_cast<signed>(mRsmpInFrames)) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009691 (void)__builtin_sub_overflow(mRsmpInRear, mRsmpInFrames, &oldestFront);
9692 }
Eric Laurent2407ce32021-04-26 14:56:03 +02009693 return oldestFront;
Eric Laurentec376dc2021-04-08 20:41:22 +02009694}
9695
Andy Hung71742ab2023-07-07 13:47:37 -07009696void RecordThread::updateFronts_l(int32_t offset)
Eric Laurentec376dc2021-04-08 20:41:22 +02009697{
9698 if (offset == 0) {
9699 return;
9700 }
9701 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung3ff4b552023-06-26 19:20:57 -07009702 int32_t front = mTracks[i]->resamplerBufferProvider()->getFront();
Eric Laurentec376dc2021-04-08 20:41:22 +02009703 front = audio_utils::safe_sub_overflow(front, offset);
Andy Hung3ff4b552023-06-26 19:20:57 -07009704 mTracks[i]->resamplerBufferProvider()->setFront(front);
Eric Laurentec376dc2021-04-08 20:41:22 +02009705 }
9706}
9707
Andy Hung71742ab2023-07-07 13:47:37 -07009708void RecordThread::resizeInputBuffer_l(int32_t maxSharedAudioHistoryMs)
Eric Laurentec376dc2021-04-08 20:41:22 +02009709{
9710 // This is the formula for calculating the temporary buffer size.
9711 // With 7 HAL buffers, we can guarantee ability to down-sample the input by ratio of 6:1 to
9712 // 1 full output buffer, regardless of the alignment of the available input.
9713 // The value is somewhat arbitrary, and could probably be even larger.
9714 // A larger value should allow more old data to be read after a track calls start(),
9715 // without increasing latency.
9716 //
9717 // Note this is independent of the maximum downsampling ratio permitted for capture.
9718 size_t minRsmpInFrames = mFrameCount * 7;
9719
9720 // maxSharedAudioHistoryMs != 0 indicates a request to possibly make some part of the audio
9721 // capture history available to another client using the same session ID:
9722 // dimension the resampler input buffer accordingly.
9723
9724 // Get oldest client read position: getOldestFront_l() must be called before altering
9725 // mRsmpInRear, or mRsmpInFrames
9726 int32_t previousFront = getOldestFront_l();
9727 size_t previousRsmpInFramesP2 = mRsmpInFramesP2;
9728 int32_t previousRear = mRsmpInRear;
9729 mRsmpInRear = 0;
9730
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009731 ALOG_ASSERT(maxSharedAudioHistoryMs >= 0
Andy Hung71742ab2023-07-07 13:47:37 -07009732 && maxSharedAudioHistoryMs <= kMaxSharedAudioHistoryMs,
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009733 "resizeInputBuffer_l() called with invalid max shared history %d",
9734 maxSharedAudioHistoryMs);
Eric Laurentec376dc2021-04-08 20:41:22 +02009735 if (maxSharedAudioHistoryMs != 0) {
9736 // resizeInputBuffer_l should never be called with a non zero shared history if the
9737 // buffer was not already allocated
9738 ALOG_ASSERT(mRsmpInBuffer != nullptr && mRsmpInFrames != 0,
9739 "resizeInputBuffer_l() called with shared history and unallocated buffer");
9740 size_t rsmpInFrames = (size_t)maxSharedAudioHistoryMs * mSampleRate / 1000;
9741 // never reduce resampler input buffer size
Eric Laurent92d0a322021-07-16 15:32:33 +02009742 if (rsmpInFrames <= mRsmpInFrames) {
Eric Laurentec376dc2021-04-08 20:41:22 +02009743 return;
9744 }
9745 mRsmpInFrames = rsmpInFrames;
9746 }
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009747 mMaxSharedAudioHistoryMs = maxSharedAudioHistoryMs;
Eric Laurentec376dc2021-04-08 20:41:22 +02009748 // Note: mRsmpInFrames is 0 when called with maxSharedAudioHistoryMs equals to 0 so it is always
9749 // initialized
9750 if (mRsmpInFrames < minRsmpInFrames) {
9751 mRsmpInFrames = minRsmpInFrames;
9752 }
9753 mRsmpInFramesP2 = roundup(mRsmpInFrames);
9754
9755 // TODO optimize audio capture buffer sizes ...
9756 // Here we calculate the size of the sliding buffer used as a source
9757 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
9758 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
9759 // be better to have it derived from the pipe depth in the long term.
9760 // The current value is higher than necessary. However it should not add to latency.
9761
9762 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
9763 mRsmpInFramesOA = mRsmpInFramesP2 + mFrameCount - 1;
9764
9765 void *rsmpInBuffer;
9766 (void)posix_memalign(&rsmpInBuffer, 32, mRsmpInFramesOA * mFrameSize);
9767 // if posix_memalign fails, will segv here.
9768 memset(rsmpInBuffer, 0, mRsmpInFramesOA * mFrameSize);
9769
9770 // Copy audio history if any from old buffer before freeing it
9771 if (previousRear != 0) {
9772 ALOG_ASSERT(mRsmpInBuffer != nullptr,
9773 "resizeInputBuffer_l() called with null buffer but frames already read from HAL");
9774
9775 ssize_t unread = audio_utils::safe_sub_overflow(previousRear, previousFront);
9776 previousFront &= previousRsmpInFramesP2 - 1;
9777 size_t part1 = previousRsmpInFramesP2 - previousFront;
9778 if (part1 > (size_t) unread) {
9779 part1 = unread;
9780 }
9781 if (part1 != 0) {
9782 memcpy(rsmpInBuffer, (const uint8_t*)mRsmpInBuffer + previousFront * mFrameSize,
9783 part1 * mFrameSize);
9784 mRsmpInRear = part1;
9785 part1 = unread - part1;
9786 if (part1 != 0) {
9787 memcpy((uint8_t*)rsmpInBuffer + mRsmpInRear * mFrameSize,
9788 (const uint8_t*)mRsmpInBuffer, part1 * mFrameSize);
9789 mRsmpInRear += part1;
9790 }
9791 }
9792 // Update front for all clients according to new rear
9793 updateFronts_l(audio_utils::safe_sub_overflow(previousRear, mRsmpInRear));
9794 } else {
9795 mRsmpInRear = 0;
9796 }
9797 free(mRsmpInBuffer);
9798 mRsmpInBuffer = rsmpInBuffer;
9799}
9800
Andy Hung71742ab2023-07-07 13:47:37 -07009801void RecordThread::addPatchTrack(const sp<IAfPatchRecord>& record)
Eric Laurent83b88082014-06-20 18:31:16 -07009802{
9803 Mutex::Autolock _l(mLock);
9804 mTracks.add(record);
Mikhail Naganov2534b382019-09-25 13:05:02 -07009805 if (record->getSource()) {
9806 mSource = record->getSource();
9807 }
Eric Laurent83b88082014-06-20 18:31:16 -07009808}
9809
Andy Hung71742ab2023-07-07 13:47:37 -07009810void RecordThread::deletePatchTrack(const sp<IAfPatchRecord>& record)
Eric Laurent83b88082014-06-20 18:31:16 -07009811{
9812 Mutex::Autolock _l(mLock);
Mikhail Naganov2534b382019-09-25 13:05:02 -07009813 if (mSource == record->getSource()) {
9814 mSource = mInput;
9815 }
Eric Laurent83b88082014-06-20 18:31:16 -07009816 destroyTrack_l(record);
9817}
9818
Andy Hung71742ab2023-07-07 13:47:37 -07009819void RecordThread::toAudioPortConfig(struct audio_port_config* config)
Eric Laurent83b88082014-06-20 18:31:16 -07009820{
Mikhail Naganovdc769682018-05-04 15:34:08 -07009821 ThreadBase::toAudioPortConfig(config);
Eric Laurent83b88082014-06-20 18:31:16 -07009822 config->role = AUDIO_PORT_ROLE_SINK;
9823 config->ext.mix.hw_module = mInput->audioHwDev->handle();
9824 config->ext.mix.usecase.source = mAudioSource;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07009825 if (mInput && mInput->flags != AUDIO_INPUT_FLAG_NONE) {
9826 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
9827 config->flags.input = mInput->flags;
9828 }
Eric Laurent83b88082014-06-20 18:31:16 -07009829}
Eric Laurent1c333e22014-05-20 10:48:17 -07009830
Eric Laurent6acd1d42017-01-04 14:23:29 -08009831// ----------------------------------------------------------------------------
9832// Mmap
9833// ----------------------------------------------------------------------------
9834
Andy Hung667dec42023-07-07 15:58:48 -07009835// Mmap stream control interface implementation. Each MmapThreadHandle controls one
9836// MmapPlaybackThread or MmapCaptureThread instance.
9837class MmapThreadHandle : public MmapStreamInterface {
9838public:
9839 explicit MmapThreadHandle(const sp<IAfMmapThread>& thread);
9840 ~MmapThreadHandle() override;
9841
9842 // MmapStreamInterface virtuals
9843 status_t createMmapBuffer(int32_t minSizeFrames,
9844 struct audio_mmap_buffer_info* info) final;
9845 status_t getMmapPosition(struct audio_mmap_position* position) final;
9846 status_t getExternalPosition(uint64_t* position, int64_t* timeNanos) final;
9847 status_t start(const AudioClient& client,
9848 const audio_attributes_t* attr, audio_port_handle_t* handle) final;
9849 status_t stop(audio_port_handle_t handle) final;
9850 status_t standby() final;
9851 status_t reportData(const void* buffer, size_t frameCount) final;
9852private:
9853 const sp<IAfMmapThread> mThread;
9854};
9855
9856/* static */
9857sp<MmapStreamInterface> IAfMmapThread::createMmapStreamInterfaceAdapter(
9858 const sp<IAfMmapThread>& mmapThread) {
9859 return sp<MmapThreadHandle>::make(mmapThread);
9860}
9861
9862MmapThreadHandle::MmapThreadHandle(const sp<IAfMmapThread>& thread)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009863 : mThread(thread)
9864{
Phil Burk9fabbf82017-08-03 12:02:00 -07009865 assert(thread != 0); // thread must start non-null and stay non-null
Eric Laurent6acd1d42017-01-04 14:23:29 -08009866}
9867
Andy Hung667dec42023-07-07 15:58:48 -07009868// MmapStreamInterface could be directly implemented by MmapThread excepting this
9869// special handling on adapter dtor.
9870MmapThreadHandle::~MmapThreadHandle()
Eric Laurent6acd1d42017-01-04 14:23:29 -08009871{
Phil Burk9fabbf82017-08-03 12:02:00 -07009872 mThread->disconnect();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009873}
9874
Andy Hung667dec42023-07-07 15:58:48 -07009875status_t MmapThreadHandle::createMmapBuffer(int32_t minSizeFrames,
Eric Laurent6acd1d42017-01-04 14:23:29 -08009876 struct audio_mmap_buffer_info *info)
9877{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009878 return mThread->createMmapBuffer(minSizeFrames, info);
9879}
9880
Andy Hung667dec42023-07-07 15:58:48 -07009881status_t MmapThreadHandle::getMmapPosition(struct audio_mmap_position* position)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009882{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009883 return mThread->getMmapPosition(position);
9884}
9885
Andy Hung667dec42023-07-07 15:58:48 -07009886status_t MmapThreadHandle::getExternalPosition(uint64_t* position,
jiabinb7d8c5a2020-08-26 17:24:52 -07009887 int64_t *timeNanos) {
9888 return mThread->getExternalPosition(position, timeNanos);
9889}
9890
Andy Hung667dec42023-07-07 15:58:48 -07009891status_t MmapThreadHandle::start(const AudioClient& client,
jiabind1f1cb62020-03-24 11:57:57 -07009892 const audio_attributes_t *attr, audio_port_handle_t *handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009893{
jiabind1f1cb62020-03-24 11:57:57 -07009894 return mThread->start(client, attr, handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009895}
9896
Andy Hung667dec42023-07-07 15:58:48 -07009897status_t MmapThreadHandle::stop(audio_port_handle_t handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009898{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009899 return mThread->stop(handle);
9900}
9901
Andy Hung667dec42023-07-07 15:58:48 -07009902status_t MmapThreadHandle::standby()
Eric Laurent18b57012017-02-13 16:23:52 -08009903{
Eric Laurent18b57012017-02-13 16:23:52 -08009904 return mThread->standby();
9905}
9906
Andy Hung667dec42023-07-07 15:58:48 -07009907status_t MmapThreadHandle::reportData(const void* buffer, size_t frameCount)
9908{
jiabinfc791ee2023-02-15 19:43:40 +00009909 return mThread->reportData(buffer, frameCount);
9910}
9911
Eric Laurent6acd1d42017-01-04 14:23:29 -08009912
Andy Hung71742ab2023-07-07 13:47:37 -07009913MmapThread::MmapThread(
Andy Hung2cbc2722023-07-17 17:05:00 -07009914 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
Andy Hung71ba4b32022-10-06 12:09:49 -07009915 AudioHwDevice *hwDev, const sp<StreamHalInterface>& stream, bool systemReady, bool isOut)
Andy Hung2cbc2722023-07-17 17:05:00 -07009916 : ThreadBase(afThreadCallback, id, (isOut ? MMAP_PLAYBACK : MMAP_CAPTURE), systemReady, isOut),
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009917 mSessionId(AUDIO_SESSION_NONE),
François Gaffie0c280aa2018-07-25 10:02:15 +02009918 mPortId(AUDIO_PORT_HANDLE_NONE),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009919 mHalStream(stream), mHalDevice(hwDev->hwDevice()), mAudioHwDev(hwDev),
Eric Laurent67f97292018-04-20 18:05:41 -07009920 mActiveTracks(&this->mLocalLog),
9921 mHalVolFloat(-1.0f), // Initialize to illegal value so it always gets set properly later.
9922 mNoCallbackWarningCount(0)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009923{
Eric Laurent18b57012017-02-13 16:23:52 -08009924 mStandby = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009925 readHalParameters_l();
9926}
9927
Andy Hung71742ab2023-07-07 13:47:37 -07009928void MmapThread::onFirstRef()
Eric Laurent6acd1d42017-01-04 14:23:29 -08009929{
9930 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
9931}
9932
Andy Hung71742ab2023-07-07 13:47:37 -07009933void MmapThread::disconnect()
Eric Laurent6acd1d42017-01-04 14:23:29 -08009934{
Andy Hung3ff4b552023-06-26 19:20:57 -07009935 ActiveTracks<IAfMmapTrack> activeTracks;
Eric Laurent331679c2018-04-16 17:03:16 -07009936 {
9937 Mutex::Autolock _l(mLock);
Andy Hung3ff4b552023-06-26 19:20:57 -07009938 for (const sp<IAfMmapTrack>& t : mActiveTracks) {
Eric Laurent331679c2018-04-16 17:03:16 -07009939 activeTracks.add(t);
9940 }
9941 }
Andy Hung3ff4b552023-06-26 19:20:57 -07009942 for (const sp<IAfMmapTrack>& t : activeTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08009943 stop(t->portId());
9944 }
Phil Burk9fabbf82017-08-03 12:02:00 -07009945 // This will decrement references and may cause the destruction of this thread.
Eric Laurent6acd1d42017-01-04 14:23:29 -08009946 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07009947 AudioSystem::releaseOutput(mPortId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009948 } else {
Eric Laurentfee19762018-01-29 18:44:13 -08009949 AudioSystem::releaseInput(mPortId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009950 }
9951}
9952
9953
Andy Hung71742ab2023-07-07 13:47:37 -07009954void MmapThread::configure(const audio_attributes_t* attr,
Eric Laurent6acd1d42017-01-04 14:23:29 -08009955 audio_stream_type_t streamType __unused,
9956 audio_session_t sessionId,
9957 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009958 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -08009959 audio_port_handle_t portId)
9960{
9961 mAttr = *attr;
9962 mSessionId = sessionId;
9963 mCallback = callback;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009964 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009965 mPortId = portId;
9966}
9967
Andy Hung71742ab2023-07-07 13:47:37 -07009968status_t MmapThread::createMmapBuffer(int32_t minSizeFrames,
Eric Laurent6acd1d42017-01-04 14:23:29 -08009969 struct audio_mmap_buffer_info *info)
9970{
9971 if (mHalStream == 0) {
9972 return NO_INIT;
9973 }
Eric Laurent18b57012017-02-13 16:23:52 -08009974 mStandby = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009975 return mHalStream->createMmapBuffer(minSizeFrames, info);
9976}
9977
Andy Hung71742ab2023-07-07 13:47:37 -07009978status_t MmapThread::getMmapPosition(struct audio_mmap_position* position) const
Eric Laurent6acd1d42017-01-04 14:23:29 -08009979{
9980 if (mHalStream == 0) {
9981 return NO_INIT;
9982 }
9983 return mHalStream->getMmapPosition(position);
9984}
9985
Andy Hung71742ab2023-07-07 13:47:37 -07009986status_t MmapThread::exitStandby_l()
Eric Laurent331679c2018-04-16 17:03:16 -07009987{
Eric Laurentdda206a2022-07-08 17:28:35 +02009988 // The HAL must receive track metadata before starting the stream
9989 updateMetadata_l();
Eric Laurent331679c2018-04-16 17:03:16 -07009990 status_t ret = mHalStream->start();
9991 if (ret != NO_ERROR) {
9992 ALOGE("%s: error mHalStream->start() = %d for first track", __FUNCTION__, ret);
9993 return ret;
9994 }
Andy Hungcf10d742020-04-28 15:38:24 -07009995 if (mStandby) {
9996 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07009997 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -07009998 mStandby = false;
9999 }
Eric Laurent331679c2018-04-16 17:03:16 -070010000 return NO_ERROR;
10001}
10002
Andy Hung71742ab2023-07-07 13:47:37 -070010003status_t MmapThread::start(const AudioClient& client,
jiabind1f1cb62020-03-24 11:57:57 -070010004 const audio_attributes_t *attr,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010005 audio_port_handle_t *handle)
10006{
Eric Laurenta54f1282017-07-01 19:39:32 -070010007 ALOGV("%s clientUid %d mStandby %d mPortId %d *handle %d", __FUNCTION__,
Svet Ganov33761132021-05-13 22:51:08 +000010008 client.attributionSource.uid, mStandby, mPortId, *handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010009 if (mHalStream == 0) {
10010 return NO_INIT;
10011 }
10012
10013 status_t ret;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010014
Eric Laurentdda206a2022-07-08 17:28:35 +020010015 // For the first track, reuse portId and session allocated when the stream was opened.
Eric Laurenta54f1282017-07-01 19:39:32 -070010016 if (*handle == mPortId) {
Eric Laurentdda206a2022-07-08 17:28:35 +020010017 acquireWakeLock();
10018 return NO_ERROR;
Eric Laurenta54f1282017-07-01 19:39:32 -070010019 }
10020
10021 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
10022
10023 audio_io_handle_t io = mId;
Andy Hungc5106312023-07-19 16:56:19 -070010024 const AttributionSourceState adjAttributionSource = afutils::checkAttributionSourcePackage(
Atneya Nairf59db5c2023-05-10 21:37:41 -070010025 client.attributionSource);
10026
Eric Laurenta54f1282017-07-01 19:39:32 -070010027 if (isOutput()) {
10028 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
10029 config.sample_rate = mSampleRate;
10030 config.channel_mask = mChannelMask;
10031 config.format = mFormat;
10032 audio_stream_type_t stream = streamType();
10033 audio_output_flags_t flags =
10034 (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010035 audio_port_handle_t deviceId = mDeviceId;
Kevin Rocard153f92d2018-12-18 18:33:28 -080010036 std::vector<audio_io_handle_t> secondaryOutputs;
Eric Laurentb0a7bc92022-04-05 15:06:08 +020010037 bool isSpatialized;
jiabinc658e452022-10-21 20:52:21 +000010038 bool isBitPerfect;
Eric Laurenta54f1282017-07-01 19:39:32 -070010039 ret = AudioSystem::getOutputForAttr(&mAttr, &io,
10040 mSessionId,
10041 &stream,
Atneya Nairf59db5c2023-05-10 21:37:41 -070010042 adjAttributionSource,
Eric Laurenta54f1282017-07-01 19:39:32 -070010043 &config,
10044 flags,
10045 &deviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -080010046 &portId,
Eric Laurentb0a7bc92022-04-05 15:06:08 +020010047 &secondaryOutputs,
jiabinc658e452022-10-21 20:52:21 +000010048 &isSpatialized,
10049 &isBitPerfect);
Kevin Rocard153f92d2018-12-18 18:33:28 -080010050 ALOGD_IF(!secondaryOutputs.empty(),
10051 "MmapThread::start does not support secondary outputs, ignoring them");
Eric Laurent6acd1d42017-01-04 14:23:29 -080010052 } else {
Eric Laurenta54f1282017-07-01 19:39:32 -070010053 audio_config_base_t config;
10054 config.sample_rate = mSampleRate;
10055 config.channel_mask = mChannelMask;
10056 config.format = mFormat;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010057 audio_port_handle_t deviceId = mDeviceId;
Eric Laurenta54f1282017-07-01 19:39:32 -070010058 ret = AudioSystem::getInputForAttr(&mAttr, &io,
Mikhail Naganov2996f672019-04-18 12:29:59 -070010059 RECORD_RIID_INVALID,
Eric Laurenta54f1282017-07-01 19:39:32 -070010060 mSessionId,
Atneya Nairf59db5c2023-05-10 21:37:41 -070010061 adjAttributionSource,
Eric Laurenta54f1282017-07-01 19:39:32 -070010062 &config,
10063 AUDIO_INPUT_FLAG_MMAP_NOIRQ,
10064 &deviceId,
10065 &portId);
10066 }
10067 // APM should not chose a different input or output stream for the same set of attributes
10068 // and audo configuration
10069 if (ret != NO_ERROR || io != mId) {
10070 ALOGE("%s: error getting output or input from APM (error %d, io %d expected io %d)",
10071 __FUNCTION__, ret, io, mId);
10072 return BAD_VALUE;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010073 }
10074
10075 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -070010076 ret = AudioSystem::startOutput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010077 } else {
jiabincfc10a42022-06-15 19:26:01 +000010078 {
10079 // Add the track record before starting input so that the silent status for the
10080 // client can be cached.
10081 Mutex::Autolock _l(mLock);
10082 setClientSilencedState_l(portId, false /*silenced*/);
10083 }
Eric Laurent4eb58f12018-12-07 16:41:02 -080010084 ret = AudioSystem::startInput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010085 }
10086
Eric Laurent331679c2018-04-16 17:03:16 -070010087 Mutex::Autolock _l(mLock);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010088 // abort if start is rejected by audio policy manager
10089 if (ret != NO_ERROR) {
Phil Burk7f6b40d2017-02-09 13:18:38 -080010090 ALOGE("%s: error start rejected by AudioPolicyManager = %d", __FUNCTION__, ret);
Eric Tan39ec8d62018-07-24 09:49:29 -070010091 if (!mActiveTracks.isEmpty()) {
Eric Laurent331679c2018-04-16 17:03:16 -070010092 mLock.unlock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010093 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -070010094 AudioSystem::releaseOutput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010095 } else {
Eric Laurentfee19762018-01-29 18:44:13 -080010096 AudioSystem::releaseInput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010097 }
Eric Laurent331679c2018-04-16 17:03:16 -070010098 mLock.lock();
Eric Laurent18b57012017-02-13 16:23:52 -080010099 } else {
10100 mHalStream->stop();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010101 }
jiabincfc10a42022-06-15 19:26:01 +000010102 eraseClientSilencedState_l(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010103 return PERMISSION_DENIED;
10104 }
10105
Kevin Rocard1f564ac2018-03-29 13:53:10 -070010106 // Given that MmapThread::mAttr is mutable, should a MmapTrack have attributes ?
Andy Hung3ff4b552023-06-26 19:20:57 -070010107 sp<IAfMmapTrack> track = IAfMmapTrack::create(
10108 this, attr == nullptr ? mAttr : *attr, mSampleRate, mFormat,
Svet Ganov33761132021-05-13 22:51:08 +000010109 mChannelMask, mSessionId, isOutput(),
10110 client.attributionSource,
Philip P. Moltmannbda45752020-07-17 16:41:18 -070010111 IPCThreadState::self()->getCallingPid(), portId);
jiabincfc10a42022-06-15 19:26:01 +000010112 if (!isOutput()) {
10113 track->setSilenced_l(isClientSilenced_l(portId));
10114 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010115
Eric Laurent4eb58f12018-12-07 16:41:02 -080010116 if (isOutput()) {
10117 // force volume update when a new track is added
10118 mHalVolFloat = -1.0f;
10119 } else if (!track->isSilenced_l()) {
Andy Hung3ff4b552023-06-26 19:20:57 -070010120 for (const sp<IAfMmapTrack>& t : mActiveTracks) {
Andy Hung71ba4b32022-10-06 12:09:49 -070010121 if (t->isSilenced_l()
10122 && t->uid() != static_cast<uid_t>(client.attributionSource.uid)) {
Eric Laurent4eb58f12018-12-07 16:41:02 -080010123 t->invalidate();
Andy Hung71ba4b32022-10-06 12:09:49 -070010124 }
Eric Laurent4eb58f12018-12-07 16:41:02 -080010125 }
10126 }
10127
Eric Laurent6acd1d42017-01-04 14:23:29 -080010128 mActiveTracks.add(track);
Andy Hungbd72c542023-06-20 18:56:17 -070010129 sp<IAfEffectChain> chain = getEffectChain_l(mSessionId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010130 if (chain != 0) {
Eric Laurentd66d7a12021-07-13 13:35:32 +020010131 chain->setStrategy(getStrategyForStream(streamType()));
Eric Laurent6acd1d42017-01-04 14:23:29 -080010132 chain->incTrackCnt();
10133 chain->incActiveTrackCnt();
10134 }
10135
Andy Hungc2b11cb2020-04-22 09:04:01 -070010136 track->logBeginInterval(patchSinksToString(&mPatch)); // log to MediaMetrics
Eric Laurent6acd1d42017-01-04 14:23:29 -080010137 *handle = portId;
Eric Laurentdda206a2022-07-08 17:28:35 +020010138
10139 if (mActiveTracks.size() == 1) {
10140 ret = exitStandby_l();
10141 }
10142
Eric Laurent6acd1d42017-01-04 14:23:29 -080010143 broadcast_l();
10144
Eric Laurentdda206a2022-07-08 17:28:35 +020010145 ALOGV("%s DONE status %d handle %d stream %p", __FUNCTION__, ret, *handle, mHalStream.get());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010146
Eric Laurentdda206a2022-07-08 17:28:35 +020010147 return ret;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010148}
10149
Andy Hung71742ab2023-07-07 13:47:37 -070010150status_t MmapThread::stop(audio_port_handle_t handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010151{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010152 ALOGV("%s handle %d", __FUNCTION__, handle);
10153
10154 if (mHalStream == 0) {
10155 return NO_INIT;
10156 }
10157
Eric Laurenta54f1282017-07-01 19:39:32 -070010158 if (handle == mPortId) {
Phil Burk98ab4082020-09-25 21:46:34 +000010159 releaseWakeLock();
Eric Laurenta54f1282017-07-01 19:39:32 -070010160 return NO_ERROR;
10161 }
10162
Eric Laurent331679c2018-04-16 17:03:16 -070010163 Mutex::Autolock _l(mLock);
10164
Andy Hung3ff4b552023-06-26 19:20:57 -070010165 sp<IAfMmapTrack> track;
10166 for (const sp<IAfMmapTrack>& t : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010167 if (handle == t->portId()) {
10168 track = t;
10169 break;
10170 }
10171 }
10172 if (track == 0) {
10173 return BAD_VALUE;
10174 }
10175
10176 mActiveTracks.remove(track);
jiabincfc10a42022-06-15 19:26:01 +000010177 eraseClientSilencedState_l(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010178
Eric Laurent331679c2018-04-16 17:03:16 -070010179 mLock.unlock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010180 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -070010181 AudioSystem::stopOutput(track->portId());
10182 AudioSystem::releaseOutput(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010183 } else {
Eric Laurentfee19762018-01-29 18:44:13 -080010184 AudioSystem::stopInput(track->portId());
10185 AudioSystem::releaseInput(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010186 }
Eric Laurent331679c2018-04-16 17:03:16 -070010187 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010188
Andy Hungbd72c542023-06-20 18:56:17 -070010189 sp<IAfEffectChain> chain = getEffectChain_l(track->sessionId());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010190 if (chain != 0) {
10191 chain->decActiveTrackCnt();
10192 chain->decTrackCnt();
10193 }
10194
Eric Laurentdda206a2022-07-08 17:28:35 +020010195 if (mActiveTracks.isEmpty()) {
10196 mHalStream->stop();
10197 }
10198
Eric Laurent6acd1d42017-01-04 14:23:29 -080010199 broadcast_l();
10200
Eric Laurent6acd1d42017-01-04 14:23:29 -080010201 return NO_ERROR;
10202}
10203
Andy Hung71742ab2023-07-07 13:47:37 -070010204status_t MmapThread::standby()
Eric Laurent18b57012017-02-13 16:23:52 -080010205{
10206 ALOGV("%s", __FUNCTION__);
10207
10208 if (mHalStream == 0) {
10209 return NO_INIT;
10210 }
Eric Tan39ec8d62018-07-24 09:49:29 -070010211 if (!mActiveTracks.isEmpty()) {
Eric Laurent18b57012017-02-13 16:23:52 -080010212 return INVALID_OPERATION;
10213 }
10214 mHalStream->standby();
Andy Hungcf10d742020-04-28 15:38:24 -070010215 if (!mStandby) {
10216 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -070010217 mThreadSnapshot.onEnd();
Andy Hungcf10d742020-04-28 15:38:24 -070010218 mStandby = true;
10219 }
Eric Laurent18b57012017-02-13 16:23:52 -080010220 releaseWakeLock();
10221 return NO_ERROR;
10222}
10223
Andy Hung71742ab2023-07-07 13:47:37 -070010224status_t MmapThread::reportData(const void* /*buffer*/, size_t /*frameCount*/) {
jiabinfc791ee2023-02-15 19:43:40 +000010225 // This is a stub implementation. The MmapPlaybackThread overrides this function.
10226 return INVALID_OPERATION;
10227}
Eric Laurent6acd1d42017-01-04 14:23:29 -080010228
Andy Hung71742ab2023-07-07 13:47:37 -070010229void MmapThread::readHalParameters_l()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010230{
10231 status_t result = mHalStream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
10232 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
10233 mFormat = mHALFormat;
10234 LOG_ALWAYS_FATAL_IF(!audio_is_linear_pcm(mFormat), "HAL format %#x is not linear pcm", mFormat);
10235 result = mHalStream->getFrameSize(&mFrameSize);
10236 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
Hayden Gomes1a89ab32020-06-12 11:05:47 -070010237 LOG_ALWAYS_FATAL_IF(mFrameSize <= 0, "Error frame size was %zu but must be greater than zero",
10238 mFrameSize);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010239 result = mHalStream->getBufferSize(&mBufferSize);
10240 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
10241 mFrameCount = mBufferSize / mFrameSize;
Andy Hungc2b11cb2020-04-22 09:04:01 -070010242
Andy Hungcf10d742020-04-28 15:38:24 -070010243 // TODO: make a readHalParameters call?
10244 mediametrics::LogItem item(mThreadMetrics.getMetricsId());
Andy Hungc2b11cb2020-04-22 09:04:01 -070010245 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
10246 .set(AMEDIAMETRICS_PROP_ENCODING, formatToString(mFormat).c_str())
10247 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
10248 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
10249 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
10250 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mFrameCount)
10251 /*
10252 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
10253 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELMASK,
10254 (int32_t)mHapticChannelMask)
10255 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELCOUNT,
10256 (int32_t)mHapticChannelCount)
10257 */
10258 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_ENCODING,
10259 formatToString(mHALFormat).c_str())
10260 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_FRAMECOUNT,
10261 (int32_t)mFrameCount) // sic - added HAL
10262 .record();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010263}
10264
Andy Hung71742ab2023-07-07 13:47:37 -070010265bool MmapThread::threadLoop()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010266{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010267 checkSilentMode_l();
10268
10269 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
10270
10271 while (!exitPending())
10272 {
Andy Hungbd72c542023-06-20 18:56:17 -070010273 Vector<sp<IAfEffectChain>> effectChains;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010274
Andy Hung13850be2019-03-14 11:33:09 -070010275 { // under Thread lock
10276 Mutex::Autolock _l(mLock);
10277
Eric Laurent6acd1d42017-01-04 14:23:29 -080010278 if (mSignalPending) {
10279 // A signal was raised while we were unlocked
10280 mSignalPending = false;
10281 } else {
10282 if (mConfigEvents.isEmpty()) {
10283 // we're about to wait, flush the binder command buffer
10284 IPCThreadState::self()->flushCommands();
10285
10286 if (exitPending()) {
10287 break;
10288 }
10289
Eric Laurent6acd1d42017-01-04 14:23:29 -080010290 // wait until we have something to do...
Tomasz Wasilczyk8f36f6e2023-08-15 20:59:35 +000010291 ALOGV("%s going to sleep", myName.c_str());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010292 mWaitWorkCV.wait(mLock);
Tomasz Wasilczyk8f36f6e2023-08-15 20:59:35 +000010293 ALOGV("%s waking up", myName.c_str());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010294
10295 checkSilentMode_l();
10296
10297 continue;
10298 }
10299 }
10300
10301 processConfigEvents_l();
10302
10303 processVolume_l();
10304
10305 checkInvalidTracks_l();
10306
10307 mActiveTracks.updatePowerState(this);
10308
Kevin Rocard069c2712018-03-29 19:09:14 -070010309 updateMetadata_l();
10310
Eric Laurent6acd1d42017-01-04 14:23:29 -080010311 lockEffectChains_l(effectChains);
Andy Hung13850be2019-03-14 11:33:09 -070010312 } // release Thread lock
10313
Eric Laurent6acd1d42017-01-04 14:23:29 -080010314 for (size_t i = 0; i < effectChains.size(); i ++) {
Andy Hung13850be2019-03-14 11:33:09 -070010315 effectChains[i]->process_l(); // Thread is not locked, but effect chain is locked
Eric Laurent6acd1d42017-01-04 14:23:29 -080010316 }
Andy Hung13850be2019-03-14 11:33:09 -070010317
10318 // enable changes in effect chain, including moving to another thread.
Eric Laurent6acd1d42017-01-04 14:23:29 -080010319 unlockEffectChains(effectChains);
10320 // Effect chains will be actually deleted here if they were removed from
10321 // mEffectChains list during mixing or effects processing
10322 }
10323
10324 threadLoop_exit();
10325
10326 if (!mStandby) {
10327 threadLoop_standby();
10328 mStandby = true;
10329 }
10330
Eric Laurent6acd1d42017-01-04 14:23:29 -080010331 ALOGV("Thread %p type %d exiting", this, mType);
10332 return false;
10333}
10334
10335// checkForNewParameter_l() must be called with ThreadBase::mLock held
Andy Hung71742ab2023-07-07 13:47:37 -070010336bool MmapThread::checkForNewParameter_l(const String8& keyValuePair,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010337 status_t& status)
10338{
10339 AudioParameter param = AudioParameter(keyValuePair);
10340 int value;
Eric Laurente6e9a482017-07-25 19:26:02 -070010341 bool sendToHal = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010342 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -070010343 LOG_FATAL("Should not happen set routing device in MmapThread");
Eric Laurent6acd1d42017-01-04 14:23:29 -080010344 }
Eric Laurente6e9a482017-07-25 19:26:02 -070010345 if (sendToHal) {
10346 status = mHalStream->setParameters(keyValuePair);
10347 } else {
10348 status = NO_ERROR;
10349 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010350
10351 return false;
10352}
10353
Andy Hung71742ab2023-07-07 13:47:37 -070010354String8 MmapThread::getParameters(const String8& keys)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010355{
10356 Mutex::Autolock _l(mLock);
10357 String8 out_s8;
10358 if (initCheck() == NO_ERROR && mHalStream->getParameters(keys, &out_s8) == OK) {
10359 return out_s8;
10360 }
Andy Hung71ba4b32022-10-06 12:09:49 -070010361 return {};
Eric Laurent6acd1d42017-01-04 14:23:29 -080010362}
10363
Andy Hung71742ab2023-07-07 13:47:37 -070010364void MmapThread::ioConfigChanged(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -070010365 audio_port_handle_t portId __unused) {
Mikhail Naganov88536df2021-07-26 17:30:29 -070010366 sp<AudioIoDescriptor> desc;
10367 bool isInput = false;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010368 switch (event) {
10369 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -070010370 case AUDIO_INPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -080010371 case AUDIO_INPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -070010372 isInput = true;
10373 FALLTHROUGH_INTENDED;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010374 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -070010375 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -080010376 case AUDIO_OUTPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -070010377 desc = sp<AudioIoDescriptor>::make(mId, mPatch, isInput,
10378 mSampleRate, mFormat, mChannelMask, mFrameCount, mFrameCount);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010379 break;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010380 case AUDIO_INPUT_CLOSED:
10381 case AUDIO_OUTPUT_CLOSED:
10382 default:
Mikhail Naganov88536df2021-07-26 17:30:29 -070010383 desc = sp<AudioIoDescriptor>::make(mId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010384 break;
10385 }
Andy Hung2cbc2722023-07-17 17:05:00 -070010386 mAfThreadCallback->ioConfigChanged(event, desc, pid);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010387}
10388
Andy Hung71742ab2023-07-07 13:47:37 -070010389status_t MmapThread::createAudioPatch_l(const struct audio_patch* patch,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010390 audio_patch_handle_t *handle)
Andy Hung71ba4b32022-10-06 12:09:49 -070010391NO_THREAD_SAFETY_ANALYSIS // elease and re-acquire mLock
Eric Laurent6acd1d42017-01-04 14:23:29 -080010392{
10393 status_t status = NO_ERROR;
10394
10395 // store new device and send to effects
10396 audio_devices_t type = AUDIO_DEVICE_NONE;
10397 audio_port_handle_t deviceId;
jiabinc52b1ff2019-10-31 17:20:42 -070010398 AudioDeviceTypeAddrVector sinkDeviceTypeAddrs;
10399 AudioDeviceTypeAddr sourceDeviceTypeAddr;
10400 uint32_t numDevices = 0;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010401 if (isOutput()) {
10402 for (unsigned int i = 0; i < patch->num_sinks; i++) {
jiabinc52b1ff2019-10-31 17:20:42 -070010403 LOG_ALWAYS_FATAL_IF(popcount(patch->sinks[i].ext.device.type) > 1
10404 && !mAudioHwDev->supportsAudioPatches(),
10405 "Enumerated device type(%#x) must not be used "
10406 "as it does not support audio patches",
10407 patch->sinks[i].ext.device.type);
Mikhail Naganov55773032020-10-01 15:08:13 -070010408 type = static_cast<audio_devices_t>(type | patch->sinks[i].ext.device.type);
Andy Hung71ba4b32022-10-06 12:09:49 -070010409 sinkDeviceTypeAddrs.emplace_back(patch->sinks[i].ext.device.type,
10410 patch->sinks[i].ext.device.address);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010411 }
10412 deviceId = patch->sinks[0].id;
jiabinc52b1ff2019-10-31 17:20:42 -070010413 numDevices = mPatch.num_sinks;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010414 } else {
10415 type = patch->sources[0].ext.device.type;
10416 deviceId = patch->sources[0].id;
jiabinc52b1ff2019-10-31 17:20:42 -070010417 numDevices = mPatch.num_sources;
10418 sourceDeviceTypeAddr.mType = patch->sources[0].ext.device.type;
jiabin0a488932020-08-07 17:32:40 -070010419 sourceDeviceTypeAddr.setAddress(patch->sources[0].ext.device.address);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010420 }
10421
10422 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -080010423 if (isOutput()) {
10424 mEffectChains[i]->setDevices_l(sinkDeviceTypeAddrs);
10425 } else {
10426 mEffectChains[i]->setInputDevice_l(sourceDeviceTypeAddr);
10427 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010428 }
10429
jiabinc52b1ff2019-10-31 17:20:42 -070010430 if (!isOutput()) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010431 // store new source and send to effects
10432 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
10433 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
10434 for (size_t i = 0; i < mEffectChains.size(); i++) {
10435 mEffectChains[i]->setAudioSource_l(mAudioSource);
10436 }
10437 }
10438 }
10439
10440 if (mAudioHwDev->supportsAudioPatches()) {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010441 status = mHalDevice->createAudioPatch(patch->num_sources, patch->sources, patch->num_sinks,
10442 patch->sinks, handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010443 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010444 audio_port_config port;
10445 std::optional<audio_source_t> source;
10446 if (isOutput()) {
10447 port = patch->sinks[0];
Eric Laurent6acd1d42017-01-04 14:23:29 -080010448 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010449 port = patch->sources[0];
10450 source = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010451 }
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010452 status = mHalStream->legacyCreateAudioPatch(port, source, type);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010453 *handle = AUDIO_PATCH_HANDLE_NONE;
10454 }
10455
jiabinc52b1ff2019-10-31 17:20:42 -070010456 if (numDevices == 0 || mDeviceId != deviceId) {
10457 if (isOutput()) {
10458 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
10459 mOutDeviceTypeAddrs = sinkDeviceTypeAddrs;
jiabin0a957d32020-04-29 10:56:20 -070010460 checkSilentMode_l();
jiabinc52b1ff2019-10-31 17:20:42 -070010461 } else {
10462 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
10463 mInDeviceTypeAddr = sourceDeviceTypeAddr;
10464 }
Phil Burk7f6b40d2017-02-09 13:18:38 -080010465 sp<MmapStreamCallback> callback = mCallback.promote();
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010466 if (mDeviceId != deviceId && callback != 0) {
Eric Laurent734046e2018-04-16 14:50:52 -070010467 mLock.unlock();
Phil Burk7f6b40d2017-02-09 13:18:38 -080010468 callback->onRoutingChanged(deviceId);
Eric Laurent734046e2018-04-16 14:50:52 -070010469 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010470 }
jiabinc52b1ff2019-10-31 17:20:42 -070010471 mPatch = *patch;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010472 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010473 }
Eric Laurentdda206a2022-07-08 17:28:35 +020010474 // Force meteadata update after a route change
10475 mActiveTracks.setHasChanged();
10476
Eric Laurent6acd1d42017-01-04 14:23:29 -080010477 return status;
10478}
10479
Andy Hung71742ab2023-07-07 13:47:37 -070010480status_t MmapThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010481{
10482 status_t status = NO_ERROR;
10483
jiabinc52b1ff2019-10-31 17:20:42 -070010484 mPatch = audio_patch{};
10485 mOutDeviceTypeAddrs.clear();
10486 mInDeviceTypeAddr.reset();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010487
10488 bool supportsAudioPatches = mHalDevice->supportsAudioPatches(&supportsAudioPatches) == OK ?
10489 supportsAudioPatches : false;
10490
10491 if (supportsAudioPatches) {
10492 status = mHalDevice->releaseAudioPatch(handle);
10493 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010494 status = mHalStream->legacyReleaseAudioPatch();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010495 }
Eric Laurentdda206a2022-07-08 17:28:35 +020010496 // Force meteadata update after a route change
10497 mActiveTracks.setHasChanged();
10498
Eric Laurent6acd1d42017-01-04 14:23:29 -080010499 return status;
10500}
10501
Andy Hung71742ab2023-07-07 13:47:37 -070010502void MmapThread::toAudioPortConfig(struct audio_port_config* config)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010503{
Mikhail Naganovdc769682018-05-04 15:34:08 -070010504 ThreadBase::toAudioPortConfig(config);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010505 if (isOutput()) {
10506 config->role = AUDIO_PORT_ROLE_SOURCE;
10507 config->ext.mix.hw_module = mAudioHwDev->handle();
10508 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
10509 } else {
10510 config->role = AUDIO_PORT_ROLE_SINK;
10511 config->ext.mix.hw_module = mAudioHwDev->handle();
10512 config->ext.mix.usecase.source = mAudioSource;
10513 }
10514}
10515
Andy Hung71742ab2023-07-07 13:47:37 -070010516status_t MmapThread::addEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010517{
10518 audio_session_t session = chain->sessionId();
10519
10520 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
10521 // Attach all tracks with same session ID to this chain.
10522 // indicate all active tracks in the chain
Andy Hung3ff4b552023-06-26 19:20:57 -070010523 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010524 if (session == track->sessionId()) {
10525 chain->incTrackCnt();
10526 chain->incActiveTrackCnt();
10527 }
10528 }
10529
10530 chain->setThread(this);
10531 chain->setInBuffer(nullptr);
10532 chain->setOutBuffer(nullptr);
10533 chain->syncHalEffectsState();
10534
10535 mEffectChains.add(chain);
10536 checkSuspendOnAddEffectChain_l(chain);
10537 return NO_ERROR;
10538}
10539
Andy Hung71742ab2023-07-07 13:47:37 -070010540size_t MmapThread::removeEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010541{
10542 audio_session_t session = chain->sessionId();
10543
10544 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
10545
10546 for (size_t i = 0; i < mEffectChains.size(); i++) {
10547 if (chain == mEffectChains[i]) {
10548 mEffectChains.removeAt(i);
10549 // detach all active tracks from the chain
10550 // detach all tracks with same session ID from this chain
Andy Hung3ff4b552023-06-26 19:20:57 -070010551 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010552 if (session == track->sessionId()) {
10553 chain->decActiveTrackCnt();
10554 chain->decTrackCnt();
10555 }
10556 }
10557 break;
10558 }
10559 }
10560 return mEffectChains.size();
10561}
10562
Andy Hung71742ab2023-07-07 13:47:37 -070010563void MmapThread::threadLoop_standby()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010564{
10565 mHalStream->standby();
10566}
10567
Andy Hung71742ab2023-07-07 13:47:37 -070010568void MmapThread::threadLoop_exit()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010569{
Phil Burk7dce7282017-09-27 13:51:41 -070010570 // Do not call callback->onTearDown() because it is redundant for thread exit
10571 // and because it can cause a recursive mutex lock on stop().
Eric Laurent6acd1d42017-01-04 14:23:29 -080010572}
10573
Andy Hung71742ab2023-07-07 13:47:37 -070010574status_t MmapThread::setSyncEvent(const sp<SyncEvent>& /* event */)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010575{
10576 return BAD_VALUE;
10577}
10578
Andy Hung71742ab2023-07-07 13:47:37 -070010579bool MmapThread::isValidSyncEvent(
10580 const sp<SyncEvent>& /* event */) const
Eric Laurent6acd1d42017-01-04 14:23:29 -080010581{
10582 return false;
10583}
10584
Andy Hung71742ab2023-07-07 13:47:37 -070010585status_t MmapThread::checkEffectCompatibility_l(
Eric Laurent6acd1d42017-01-04 14:23:29 -080010586 const effect_descriptor_t *desc, audio_session_t sessionId)
10587{
10588 // No global effect sessions on mmap threads
Eric Laurent3f75a5b2019-11-12 15:55:51 -080010589 if (audio_is_global_session(sessionId)) {
10590 ALOGW("checkEffectCompatibility_l(): global effect %s on MMAP thread %s",
Eric Laurent6acd1d42017-01-04 14:23:29 -080010591 desc->name, mThreadName);
10592 return BAD_VALUE;
10593 }
10594
10595 if (!isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC)) {
10596 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on capture mmap thread",
10597 desc->name);
10598 return BAD_VALUE;
10599 }
10600 if (isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Glenn Kastend3bb6452016-12-05 18:14:37 -080010601 ALOGW("checkEffectCompatibility_l(): pre processing effect %s created on playback mmap "
10602 "thread", desc->name);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010603 return BAD_VALUE;
10604 }
10605
10606 // Only allow effects without processing load or latency
10607 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) != EFFECT_FLAG_NO_PROCESS) {
10608 return BAD_VALUE;
10609 }
10610
Andy Hungbd72c542023-06-20 18:56:17 -070010611 if (IAfEffectModule::isHapticGenerator(&desc->type)) {
jiabineb3bda02020-06-30 14:07:03 -070010612 ALOGE("%s(): HapticGenerator is not supported for MmapThread", __func__);
10613 return BAD_VALUE;
10614 }
10615
Eric Laurent6acd1d42017-01-04 14:23:29 -080010616 return NO_ERROR;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010617}
10618
Andy Hung71742ab2023-07-07 13:47:37 -070010619void MmapThread::checkInvalidTracks_l()
Andy Hung71ba4b32022-10-06 12:09:49 -070010620NO_THREAD_SAFETY_ANALYSIS // release and re-acquire mLock
Eric Laurent6acd1d42017-01-04 14:23:29 -080010621{
Eric Laurentc9ac46b2022-10-07 14:01:59 +020010622 sp<MmapStreamCallback> callback;
Andy Hung3ff4b552023-06-26 19:20:57 -070010623 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010624 if (track->isInvalid()) {
Eric Laurentc9ac46b2022-10-07 14:01:59 +020010625 callback = mCallback.promote();
10626 if (callback == nullptr && mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
10627 ALOGW("Could not notify MMAP stream tear down: no onRoutingChanged callback!");
Eric Laurent331679c2018-04-16 17:03:16 -070010628 mNoCallbackWarningCount++;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010629 }
Eric Laurentc9ac46b2022-10-07 14:01:59 +020010630 break;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010631 }
10632 }
Eric Laurentc9ac46b2022-10-07 14:01:59 +020010633 if (callback != 0) {
10634 mLock.unlock();
10635 callback->onRoutingChanged(AUDIO_PORT_HANDLE_NONE);
10636 mLock.lock();
10637 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010638}
10639
Andy Hung71742ab2023-07-07 13:47:37 -070010640void MmapThread::dumpInternals_l(int fd, const Vector<String16>& /* args */)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010641{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010642 dprintf(fd, " Attributes: content type %d usage %d source %d\n",
10643 mAttr.content_type, mAttr.usage, mAttr.source);
10644 dprintf(fd, " Session: %d port Id: %d\n", mSessionId, mPortId);
Eric Tan39ec8d62018-07-24 09:49:29 -070010645 if (mActiveTracks.isEmpty()) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010646 dprintf(fd, " No active clients\n");
10647 }
10648}
10649
Andy Hung71742ab2023-07-07 13:47:37 -070010650void MmapThread::dumpTracks_l(int fd, const Vector<String16>& /* args */)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010651{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010652 String8 result;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010653 size_t numtracks = mActiveTracks.size();
Andy Hung2c6c3bb2017-06-16 14:01:45 -070010654 dprintf(fd, " %zu Tracks\n", numtracks);
10655 const char *prefix = " ";
Eric Laurent6acd1d42017-01-04 14:23:29 -080010656 if (numtracks) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -070010657 result.append(prefix);
Kevin Rocard5f2136e2018-05-11 22:03:00 -070010658 mActiveTracks[0]->appendDumpHeader(result);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010659 for (size_t i = 0; i < numtracks ; ++i) {
Andy Hung3ff4b552023-06-26 19:20:57 -070010660 sp<IAfMmapTrack> track = mActiveTracks[i];
Andy Hung2c6c3bb2017-06-16 14:01:45 -070010661 result.append(prefix);
10662 track->appendDump(result, true /* active */);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010663 }
10664 } else {
10665 dprintf(fd, "\n");
10666 }
Tomasz Wasilczyk8f36f6e2023-08-15 20:59:35 +000010667 write(fd, result.c_str(), result.size());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010668}
10669
Andy Hung71742ab2023-07-07 13:47:37 -070010670/* static */
10671sp<IAfMmapPlaybackThread> IAfMmapPlaybackThread::create(
Andy Hung2cbc2722023-07-17 17:05:00 -070010672 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
Andy Hung71742ab2023-07-07 13:47:37 -070010673 AudioHwDevice* hwDev, AudioStreamOut* output, bool systemReady) {
Andy Hung2cbc2722023-07-17 17:05:00 -070010674 return sp<MmapPlaybackThread>::make(afThreadCallback, id, hwDev, output, systemReady);
Andy Hung71742ab2023-07-07 13:47:37 -070010675}
10676
10677MmapPlaybackThread::MmapPlaybackThread(
Andy Hung2cbc2722023-07-17 17:05:00 -070010678 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
jiabinc52b1ff2019-10-31 17:20:42 -070010679 AudioHwDevice *hwDev, AudioStreamOut *output, bool systemReady)
Andy Hung2cbc2722023-07-17 17:05:00 -070010680 : MmapThread(afThreadCallback, id, hwDev, output->stream, systemReady, true /* isOut */),
Eric Laurent6acd1d42017-01-04 14:23:29 -080010681 mStreamType(AUDIO_STREAM_MUSIC),
Phil Burk56ecf3e2018-03-12 15:38:17 -070010682 mStreamVolume(1.0),
10683 mStreamMute(false),
Phil Burk56ecf3e2018-03-12 15:38:17 -070010684 mOutput(output)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010685{
10686 snprintf(mThreadName, kThreadNameLength, "AudioMmapOut_%X", id);
10687 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Andy Hung2cbc2722023-07-17 17:05:00 -070010688 mMasterVolume = afThreadCallback->masterVolume_l();
10689 mMasterMute = afThreadCallback->masterMute_l();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010690 if (mAudioHwDev) {
10691 if (mAudioHwDev->canSetMasterVolume()) {
10692 mMasterVolume = 1.0;
10693 }
10694
10695 if (mAudioHwDev->canSetMasterMute()) {
10696 mMasterMute = false;
10697 }
10698 }
10699}
10700
Andy Hung71742ab2023-07-07 13:47:37 -070010701void MmapPlaybackThread::configure(const audio_attributes_t* attr,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010702 audio_stream_type_t streamType,
10703 audio_session_t sessionId,
10704 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010705 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010706 audio_port_handle_t portId)
10707{
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010708 MmapThread::configure(attr, streamType, sessionId, callback, deviceId, portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010709 mStreamType = streamType;
10710}
10711
Andy Hung71742ab2023-07-07 13:47:37 -070010712AudioStreamOut* MmapPlaybackThread::clearOutput()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010713{
10714 Mutex::Autolock _l(mLock);
10715 AudioStreamOut *output = mOutput;
10716 mOutput = NULL;
10717 return output;
10718}
10719
Andy Hung71742ab2023-07-07 13:47:37 -070010720void MmapPlaybackThread::setMasterVolume(float value)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010721{
10722 Mutex::Autolock _l(mLock);
10723 // Don't apply master volume in SW if our HAL can do it for us.
10724 if (mAudioHwDev &&
10725 mAudioHwDev->canSetMasterVolume()) {
10726 mMasterVolume = 1.0;
10727 } else {
10728 mMasterVolume = value;
10729 }
10730}
10731
Andy Hung71742ab2023-07-07 13:47:37 -070010732void MmapPlaybackThread::setMasterMute(bool muted)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010733{
10734 Mutex::Autolock _l(mLock);
10735 // Don't apply master mute in SW if our HAL can do it for us.
10736 if (mAudioHwDev && mAudioHwDev->canSetMasterMute()) {
10737 mMasterMute = false;
10738 } else {
10739 mMasterMute = muted;
10740 }
10741}
10742
Andy Hung71742ab2023-07-07 13:47:37 -070010743void MmapPlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010744{
10745 Mutex::Autolock _l(mLock);
10746 if (stream == mStreamType) {
10747 mStreamVolume = value;
10748 broadcast_l();
10749 }
10750}
10751
Andy Hung71742ab2023-07-07 13:47:37 -070010752float MmapPlaybackThread::streamVolume(audio_stream_type_t stream) const
Eric Laurent6acd1d42017-01-04 14:23:29 -080010753{
10754 Mutex::Autolock _l(mLock);
10755 if (stream == mStreamType) {
10756 return mStreamVolume;
10757 }
10758 return 0.0f;
10759}
10760
Andy Hung71742ab2023-07-07 13:47:37 -070010761void MmapPlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010762{
10763 Mutex::Autolock _l(mLock);
10764 if (stream == mStreamType) {
10765 mStreamMute= muted;
10766 broadcast_l();
10767 }
10768}
10769
Andy Hung71742ab2023-07-07 13:47:37 -070010770void MmapPlaybackThread::invalidateTracks(audio_stream_type_t streamType)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010771{
10772 Mutex::Autolock _l(mLock);
10773 if (streamType == mStreamType) {
Andy Hung3ff4b552023-06-26 19:20:57 -070010774 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010775 track->invalidate();
10776 }
10777 broadcast_l();
10778 }
10779}
10780
Andy Hung71742ab2023-07-07 13:47:37 -070010781void MmapPlaybackThread::invalidateTracks(std::set<audio_port_handle_t>& portIds)
jiabinc44b3462022-12-08 12:52:31 -080010782{
10783 Mutex::Autolock _l(mLock);
10784 bool trackMatch = false;
Andy Hung3ff4b552023-06-26 19:20:57 -070010785 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
jiabinc44b3462022-12-08 12:52:31 -080010786 if (portIds.find(track->portId()) != portIds.end()) {
10787 track->invalidate();
10788 trackMatch = true;
10789 portIds.erase(track->portId());
10790 }
10791 if (portIds.empty()) {
10792 break;
10793 }
10794 }
10795 if (trackMatch) {
10796 broadcast_l();
10797 }
10798}
10799
Andy Hung71742ab2023-07-07 13:47:37 -070010800void MmapPlaybackThread::processVolume_l()
Andy Hung71ba4b32022-10-06 12:09:49 -070010801NO_THREAD_SAFETY_ANALYSIS // access of track->processMuteEvent_l
Eric Laurent6acd1d42017-01-04 14:23:29 -080010802{
10803 float volume;
10804
10805 if (mMasterMute || mStreamMute) {
10806 volume = 0;
10807 } else {
10808 volume = mMasterVolume * mStreamVolume;
10809 }
10810
10811 if (volume != mHalVolFloat) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010812
10813 // Convert volumes from float to 8.24
10814 uint32_t vol = (uint32_t)(volume * (1 << 24));
10815
10816 // Delegate volume control to effect in track effect chain if needed
10817 // only one effect chain can be present on DirectOutputThread, so if
10818 // there is one, the track is connected to it
10819 if (!mEffectChains.isEmpty()) {
10820 mEffectChains[0]->setVolume_l(&vol, &vol);
10821 volume = (float)vol / (1 << 24);
10822 }
Eric Laurentdff774a2017-04-21 15:29:38 -070010823 // Try to use HW volume control and fall back to SW control if not implemented
Phil Burk56ecf3e2018-03-12 15:38:17 -070010824 if (mOutput->stream->setVolume(volume, volume) == NO_ERROR) {
10825 mHalVolFloat = volume; // HW volume control worked, so update value.
10826 mNoCallbackWarningCount = 0;
10827 } else {
Eric Laurentdff774a2017-04-21 15:29:38 -070010828 sp<MmapStreamCallback> callback = mCallback.promote();
10829 if (callback != 0) {
Phil Burk56ecf3e2018-03-12 15:38:17 -070010830 mHalVolFloat = volume; // SW volume control worked, so update value.
10831 mNoCallbackWarningCount = 0;
Eric Laurent734046e2018-04-16 14:50:52 -070010832 mLock.unlock();
Robert Wu4389ae62022-02-17 18:39:41 +000010833 callback->onVolumeChanged(volume);
Eric Laurent734046e2018-04-16 14:50:52 -070010834 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010835 } else {
Phil Burk56ecf3e2018-03-12 15:38:17 -070010836 if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
10837 ALOGW("Could not set MMAP stream volume: no volume callback!");
10838 mNoCallbackWarningCount++;
10839 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010840 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010841 }
Andy Hung3ff4b552023-06-26 19:20:57 -070010842 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Jasmine Chaeaa10e42021-05-11 10:11:14 +080010843 track->setMetadataHasChanged();
Andy Hung2cbc2722023-07-17 17:05:00 -070010844 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
Vlad Popaec1788e2022-08-04 11:23:30 +020010845 /*muteState=*/{mMasterMute,
10846 mStreamVolume == 0.f,
10847 mStreamMute,
10848 // TODO(b/241533526): adjust logic to include mute from AppOps
10849 false /*muteFromPlaybackRestricted*/,
10850 false /*muteFromClientVolume*/,
10851 false /*muteFromVolumeShaper*/});
Jasmine Chaeaa10e42021-05-11 10:11:14 +080010852 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010853 }
10854}
10855
Andy Hung71742ab2023-07-07 13:47:37 -070010856ThreadBase::MetadataUpdate MmapPlaybackThread::updateMetadata_l()
Kevin Rocard069c2712018-03-29 19:09:14 -070010857{
Jasmine Chaeaa10e42021-05-11 10:11:14 +080010858 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
Vlad Popa7e81cea2023-01-19 16:34:16 +010010859 return {}; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -070010860 }
10861 StreamOutHalInterface::SourceMetadata metadata;
Andy Hung3ff4b552023-06-26 19:20:57 -070010862 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Kevin Rocard069c2712018-03-29 19:09:14 -070010863 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurent94579172020-11-20 18:41:04 +010010864 playback_track_metadata_v7_t trackMetadata;
10865 trackMetadata.base = {
Kevin Rocard069c2712018-03-29 19:09:14 -070010866 .usage = track->attributes().usage,
10867 .content_type = track->attributes().content_type,
10868 .gain = mHalVolFloat, // TODO: propagate from aaudio pre-mix volume
Eric Laurent94579172020-11-20 18:41:04 +010010869 };
10870 trackMetadata.channel_mask = track->channelMask(),
10871 strncpy(trackMetadata.tags, track->attributes().tags, AUDIO_ATTRIBUTES_TAGS_MAX_SIZE);
10872 metadata.tracks.push_back(trackMetadata);
Kevin Rocard069c2712018-03-29 19:09:14 -070010873 }
10874 mOutput->stream->updateSourceMetadata(metadata);
Vlad Popa7e81cea2023-01-19 16:34:16 +010010875
10876 MetadataUpdate change;
10877 change.playbackMetadataUpdate = metadata.tracks;
10878 return change;
10879};
Kevin Rocard069c2712018-03-29 19:09:14 -070010880
Andy Hung71742ab2023-07-07 13:47:37 -070010881void MmapPlaybackThread::checkSilentMode_l()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010882{
10883 if (!mMasterMute) {
10884 char value[PROPERTY_VALUE_MAX];
10885 if (property_get("ro.audio.silent", value, "0") > 0) {
10886 char *endptr;
10887 unsigned long ul = strtoul(value, &endptr, 0);
10888 if (*endptr == '\0' && ul != 0) {
10889 ALOGD("Silence is golden");
10890 // The setprop command will not allow a property to be changed after
10891 // the first time it is set, so we don't have to worry about un-muting.
10892 setMasterMute_l(true);
10893 }
10894 }
10895 }
10896}
10897
Andy Hung71742ab2023-07-07 13:47:37 -070010898void MmapPlaybackThread::toAudioPortConfig(struct audio_port_config* config)
Mikhail Naganov32abc2b2018-05-24 12:57:11 -070010899{
10900 MmapThread::toAudioPortConfig(config);
10901 if (mOutput && mOutput->flags != AUDIO_OUTPUT_FLAG_NONE) {
10902 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
10903 config->flags.output = mOutput->flags;
10904 }
10905}
10906
Andy Hung71742ab2023-07-07 13:47:37 -070010907status_t MmapPlaybackThread::getExternalPosition(uint64_t* position,
Andy Hung4989d312023-06-29 21:19:25 -070010908 int64_t* timeNanos) const
jiabinb7d8c5a2020-08-26 17:24:52 -070010909{
10910 if (mOutput == nullptr) {
10911 return NO_INIT;
10912 }
10913 struct timespec timestamp;
10914 status_t status = mOutput->getPresentationPosition(position, &timestamp);
10915 if (status == NO_ERROR) {
10916 *timeNanos = timestamp.tv_sec * NANOS_PER_SECOND + timestamp.tv_nsec;
10917 }
10918 return status;
10919}
10920
Andy Hung71742ab2023-07-07 13:47:37 -070010921status_t MmapPlaybackThread::reportData(const void* buffer, size_t frameCount) {
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010010922 // Send to MelProcessor for sound dose measurement.
10923 auto processor = mMelProcessor.load();
10924 if (processor) {
10925 processor->process(buffer, frameCount * mFrameSize);
10926 }
10927
jiabinfc791ee2023-02-15 19:43:40 +000010928 return NO_ERROR;
10929}
10930
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010010931// startMelComputation_l() must be called with AudioFlinger::mLock held
Andy Hung71742ab2023-07-07 13:47:37 -070010932void MmapPlaybackThread::startMelComputation_l(
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010010933 const sp<audio_utils::MelProcessor>& processor)
10934{
10935 ALOGV("%s: starting mel processor for thread %d", __func__, id());
Vlad Popa1c2f7e12023-03-28 02:08:56 +020010936 mMelProcessor.store(processor);
10937 if (processor) {
10938 processor->resume();
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010010939 }
Vlad Popa1c2f7e12023-03-28 02:08:56 +020010940
10941 // no need to update output format for MMapPlaybackThread since it is
10942 // assigned constant for each thread
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010010943}
10944
10945// stopMelComputation_l() must be called with AudioFlinger::mLock held
Andy Hung71742ab2023-07-07 13:47:37 -070010946void MmapPlaybackThread::stopMelComputation_l()
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010010947{
Vlad Popa1c2f7e12023-03-28 02:08:56 +020010948 ALOGV("%s: pausing mel processor for thread %d", __func__, id());
10949 auto melProcessor = mMelProcessor.load();
10950 if (melProcessor != nullptr) {
10951 melProcessor->pause();
10952 }
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010010953}
10954
Andy Hung71742ab2023-07-07 13:47:37 -070010955void MmapPlaybackThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010956{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -070010957 MmapThread::dumpInternals_l(fd, args);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010958
Glenn Kastend3bb6452016-12-05 18:14:37 -080010959 dprintf(fd, " Stream type: %d Stream volume: %f HAL volume: %f Stream mute %d\n",
10960 mStreamType, mStreamVolume, mHalVolFloat, mStreamMute);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010961 dprintf(fd, " Master volume: %f Master mute %d\n", mMasterVolume, mMasterMute);
10962}
10963
Andy Hung71742ab2023-07-07 13:47:37 -070010964/* static */
10965sp<IAfMmapCaptureThread> IAfMmapCaptureThread::create(
Andy Hung2cbc2722023-07-17 17:05:00 -070010966 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
Andy Hung71742ab2023-07-07 13:47:37 -070010967 AudioHwDevice* hwDev, AudioStreamIn* input, bool systemReady) {
Andy Hung2cbc2722023-07-17 17:05:00 -070010968 return sp<MmapCaptureThread>::make(afThreadCallback, id, hwDev, input, systemReady);
Andy Hung71742ab2023-07-07 13:47:37 -070010969}
10970
10971MmapCaptureThread::MmapCaptureThread(
Andy Hung2cbc2722023-07-17 17:05:00 -070010972 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
jiabinc52b1ff2019-10-31 17:20:42 -070010973 AudioHwDevice *hwDev, AudioStreamIn *input, bool systemReady)
Andy Hung2cbc2722023-07-17 17:05:00 -070010974 : MmapThread(afThreadCallback, id, hwDev, input->stream, systemReady, false /* isOut */),
Eric Laurent6acd1d42017-01-04 14:23:29 -080010975 mInput(input)
10976{
10977 snprintf(mThreadName, kThreadNameLength, "AudioMmapIn_%X", id);
10978 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
10979}
10980
Andy Hung71742ab2023-07-07 13:47:37 -070010981status_t MmapCaptureThread::exitStandby_l()
Eric Laurent331679c2018-04-16 17:03:16 -070010982{
Phil Burkf054fc32018-12-06 09:45:59 -080010983 {
10984 // mInput might have been cleared by clearInput()
Phil Burkf054fc32018-12-06 09:45:59 -080010985 if (mInput != nullptr && mInput->stream != nullptr) {
10986 mInput->stream->setGain(1.0f);
10987 }
10988 }
Eric Laurentdda206a2022-07-08 17:28:35 +020010989 return MmapThread::exitStandby_l();
Eric Laurent331679c2018-04-16 17:03:16 -070010990}
10991
Andy Hung71742ab2023-07-07 13:47:37 -070010992AudioStreamIn* MmapCaptureThread::clearInput()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010993{
10994 Mutex::Autolock _l(mLock);
10995 AudioStreamIn *input = mInput;
10996 mInput = NULL;
10997 return input;
10998}
Kevin Rocard069c2712018-03-29 19:09:14 -070010999
Andy Hung71742ab2023-07-07 13:47:37 -070011000void MmapCaptureThread::processVolume_l()
Eric Laurent331679c2018-04-16 17:03:16 -070011001{
11002 bool changed = false;
11003 bool silenced = false;
11004
11005 sp<MmapStreamCallback> callback = mCallback.promote();
11006 if (callback == 0) {
11007 if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
11008 ALOGW("Could not set MMAP stream silenced: no onStreamSilenced callback!");
11009 mNoCallbackWarningCount++;
11010 }
11011 }
11012
11013 // After a change occurred in track silenced state, mute capture in audio DSP if at least one
11014 // track is silenced and unmute otherwise
11015 for (size_t i = 0; i < mActiveTracks.size() && !silenced; i++) {
11016 if (!mActiveTracks[i]->getAndSetSilencedNotified_l()) {
11017 changed = true;
11018 silenced = mActiveTracks[i]->isSilenced_l();
11019 }
11020 }
11021
11022 if (changed) {
11023 mInput->stream->setGain(silenced ? 0.0f: 1.0f);
11024 }
11025}
11026
Andy Hung71742ab2023-07-07 13:47:37 -070011027ThreadBase::MetadataUpdate MmapCaptureThread::updateMetadata_l()
Kevin Rocard069c2712018-03-29 19:09:14 -070011028{
Jasmine Chaeaa10e42021-05-11 10:11:14 +080011029 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
Vlad Popa7e81cea2023-01-19 16:34:16 +010011030 return {}; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -070011031 }
11032 StreamInHalInterface::SinkMetadata metadata;
Andy Hung3ff4b552023-06-26 19:20:57 -070011033 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Kevin Rocard069c2712018-03-29 19:09:14 -070011034 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurent94579172020-11-20 18:41:04 +010011035 record_track_metadata_v7_t trackMetadata;
11036 trackMetadata.base = {
Kevin Rocard069c2712018-03-29 19:09:14 -070011037 .source = track->attributes().source,
11038 .gain = 1, // capture tracks do not have volumes
Eric Laurent94579172020-11-20 18:41:04 +010011039 };
11040 trackMetadata.channel_mask = track->channelMask(),
11041 strncpy(trackMetadata.tags, track->attributes().tags, AUDIO_ATTRIBUTES_TAGS_MAX_SIZE);
11042 metadata.tracks.push_back(trackMetadata);
Kevin Rocard069c2712018-03-29 19:09:14 -070011043 }
11044 mInput->stream->updateSinkMetadata(metadata);
Vlad Popa7e81cea2023-01-19 16:34:16 +010011045 MetadataUpdate change;
11046 change.recordMetadataUpdate = metadata.tracks;
11047 return change;
Kevin Rocard069c2712018-03-29 19:09:14 -070011048}
11049
Andy Hung71742ab2023-07-07 13:47:37 -070011050void MmapCaptureThread::setRecordSilenced(audio_port_handle_t portId, bool silenced)
Eric Laurent331679c2018-04-16 17:03:16 -070011051{
11052 Mutex::Autolock _l(mLock);
11053 for (size_t i = 0; i < mActiveTracks.size() ; i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -070011054 if (mActiveTracks[i]->portId() == portId) {
Eric Laurent331679c2018-04-16 17:03:16 -070011055 mActiveTracks[i]->setSilenced_l(silenced);
11056 broadcast_l();
11057 }
11058 }
jiabincfc10a42022-06-15 19:26:01 +000011059 setClientSilencedIfExists_l(portId, silenced);
Eric Laurent331679c2018-04-16 17:03:16 -070011060}
11061
Andy Hung71742ab2023-07-07 13:47:37 -070011062void MmapCaptureThread::toAudioPortConfig(struct audio_port_config* config)
Mikhail Naganov32abc2b2018-05-24 12:57:11 -070011063{
11064 MmapThread::toAudioPortConfig(config);
11065 if (mInput && mInput->flags != AUDIO_INPUT_FLAG_NONE) {
11066 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
11067 config->flags.input = mInput->flags;
11068 }
11069}
11070
Andy Hung71742ab2023-07-07 13:47:37 -070011071status_t MmapCaptureThread::getExternalPosition(
Andy Hung4989d312023-06-29 21:19:25 -070011072 uint64_t* position, int64_t* timeNanos) const
jiabinb7d8c5a2020-08-26 17:24:52 -070011073{
11074 if (mInput == nullptr) {
11075 return NO_INIT;
11076 }
11077 return mInput->getCapturePosition((int64_t*)position, timeNanos);
11078}
11079
jiabinc658e452022-10-21 20:52:21 +000011080// ----------------------------------------------------------------------------
11081
Andy Hung71742ab2023-07-07 13:47:37 -070011082/* static */
11083sp<IAfPlaybackThread> IAfPlaybackThread::createBitPerfectThread(
Andy Hung2cbc2722023-07-17 17:05:00 -070011084 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hung71742ab2023-07-07 13:47:37 -070011085 AudioStreamOut* output, audio_io_handle_t id, bool systemReady) {
Andy Hung2cbc2722023-07-17 17:05:00 -070011086 return sp<BitPerfectThread>::make(afThreadCallback, output, id, systemReady);
Andy Hung71742ab2023-07-07 13:47:37 -070011087}
11088
Andy Hung2cbc2722023-07-17 17:05:00 -070011089BitPerfectThread::BitPerfectThread(const sp<IAfThreadCallback> &afThreadCallback,
jiabinc658e452022-10-21 20:52:21 +000011090 AudioStreamOut *output, audio_io_handle_t id, bool systemReady)
Andy Hung2cbc2722023-07-17 17:05:00 -070011091 : MixerThread(afThreadCallback, output, id, systemReady, BIT_PERFECT) {}
jiabinc658e452022-10-21 20:52:21 +000011092
Andy Hung71742ab2023-07-07 13:47:37 -070011093PlaybackThread::mixer_state BitPerfectThread::prepareTracks_l(
Andy Hung3ff4b552023-06-26 19:20:57 -070011094 Vector<sp<IAfTrack>>* tracksToRemove) {
jiabinc658e452022-10-21 20:52:21 +000011095 mixer_state result = MixerThread::prepareTracks_l(tracksToRemove);
11096 // If there is only one active track and it is bit-perfect, enable tee buffer.
jiabin76d94692022-12-15 21:51:21 +000011097 float volumeLeft = 1.0f;
11098 float volumeRight = 1.0f;
jiabinc658e452022-10-21 20:52:21 +000011099 if (mActiveTracks.size() == 1 && mActiveTracks[0]->isBitPerfect()) {
11100 const int trackId = mActiveTracks[0]->id();
11101 mAudioMixer->setParameter(
11102 trackId, AudioMixer::TRACK, AudioMixer::TEE_BUFFER, (void *)mSinkBuffer);
11103 mAudioMixer->setParameter(
11104 trackId, AudioMixer::TRACK, AudioMixer::TEE_BUFFER_FRAME_COUNT,
11105 (void *)(uintptr_t)mNormalFrameCount);
jiabin76d94692022-12-15 21:51:21 +000011106 mActiveTracks[0]->getFinalVolume(&volumeLeft, &volumeRight);
jiabinc658e452022-10-21 20:52:21 +000011107 mIsBitPerfect = true;
11108 } else {
11109 mIsBitPerfect = false;
11110 // No need to copy bit-perfect data directly to sink buffer given there are multiple tracks
11111 // active.
11112 for (const auto& track : mActiveTracks) {
11113 const int trackId = track->id();
11114 mAudioMixer->setParameter(
11115 trackId, AudioMixer::TRACK, AudioMixer::TEE_BUFFER, nullptr);
11116 }
11117 }
jiabin76d94692022-12-15 21:51:21 +000011118 if (mVolumeLeft != volumeLeft || mVolumeRight != volumeRight) {
11119 mVolumeLeft = volumeLeft;
11120 mVolumeRight = volumeRight;
11121 setVolumeForOutput_l(volumeLeft, volumeRight);
11122 }
jiabinc658e452022-10-21 20:52:21 +000011123 return result;
11124}
11125
Andy Hung71742ab2023-07-07 13:47:37 -070011126void BitPerfectThread::threadLoop_mix() {
jiabinc658e452022-10-21 20:52:21 +000011127 MixerThread::threadLoop_mix();
11128 mHasDataCopiedToSinkBuffer = mIsBitPerfect;
11129}
11130
Glenn Kasten63238ef2015-03-02 15:50:29 -080011131} // namespace android