blob: bc9fa8aea6ecdeb268df1dd23e36d1479f45264e [file] [log] [blame]
Eric Laurent81784c32012-11-19 14:55:58 -08001/*
2**
3** Copyright 2012, The Android Open Source Project
4**
5** Licensed under the Apache License, Version 2.0 (the "License");
6** you may not use this file except in compliance with the License.
7** You may obtain a copy of the License at
8**
9** http://www.apache.org/licenses/LICENSE-2.0
10**
11** Unless required by applicable law or agreed to in writing, software
12** distributed under the License is distributed on an "AS IS" BASIS,
13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14** See the License for the specific language governing permissions and
15** limitations under the License.
16*/
17
18
19#define LOG_TAG "AudioFlinger"
Vlad Popab042ee62022-10-20 18:05:00 +020020// #define LOG_NDEBUG 0
Alex Ray371eb972012-11-30 11:11:54 -080021#define ATRACE_TAG ATRACE_TAG_AUDIO
Eric Laurent81784c32012-11-19 14:55:58 -080022
Glenn Kasten153b9fe2013-07-15 11:23:36 -070023#include "Configuration.h"
Eric Laurent81784c32012-11-19 14:55:58 -080024#include <math.h>
25#include <fcntl.h>
Eric Tan7b651152018-07-13 10:17:19 -070026#include <memory>
Andy Hungb68f5eb2019-12-03 16:49:17 -080027#include <sstream>
Eric Tan7b651152018-07-13 10:17:19 -070028#include <string>
Glenn Kastenad8510a2015-02-17 16:24:07 -080029#include <linux/futex.h>
Eric Laurent81784c32012-11-19 14:55:58 -080030#include <sys/stat.h>
Glenn Kastenad8510a2015-02-17 16:24:07 -080031#include <sys/syscall.h>
Glenn Kastenc9a23672020-06-30 12:12:42 -070032#include <cutils/bitops.h>
Eric Laurent81784c32012-11-19 14:55:58 -080033#include <cutils/properties.h>
Vlad Popae8d99472022-06-30 16:02:48 +020034#include <binder/PersistableBundle.h>
jiabinc52b1ff2019-10-31 17:20:42 -070035#include <media/AudioContainers.h>
36#include <media/AudioDeviceTypeAddr.h>
Glenn Kasten1ab85ec2013-05-31 09:18:43 -070037#include <media/AudioParameter.h>
Andy Hungcd044842014-08-07 11:04:34 -070038#include <media/AudioResamplerPublic.h>
Andy Hung89816052017-01-11 17:08:23 -080039#include <media/RecordBufferConverter.h>
Mikhail Naganov913d06c2016-11-01 12:49:22 -070040#include <media/TypeConverter.h>
Eric Laurent81784c32012-11-19 14:55:58 -080041#include <utils/Log.h>
Alex Ray371eb972012-11-30 11:11:54 -080042#include <utils/Trace.h>
Eric Laurent81784c32012-11-19 14:55:58 -080043
44#include <private/media/AudioTrackShared.h>
Wei Jiaf2ae3e12016-10-27 17:10:59 -070045#include <private/android_filesystem_config.h>
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +010046#include <audio_utils/Balance.h>
Vlad Popab042ee62022-10-20 18:05:00 +020047#include <audio_utils/MelProcessor.h>
jiabinf6eb4c32020-02-25 14:06:25 -080048#include <audio_utils/Metadata.h>
jiabin245cdd92018-12-07 17:55:15 -080049#include <audio_utils/channels.h>
Glenn Kasten6bf707f2017-02-23 16:53:58 -080050#include <audio_utils/mono_blend.h>
Eric Laurent81784c32012-11-19 14:55:58 -080051#include <audio_utils/primitives.h>
Andy Hung98ef9782014-03-04 14:46:50 -080052#include <audio_utils/format.h>
Glenn Kastenc56f3422014-03-21 17:53:17 -070053#include <audio_utils/minifloat.h>
Hongwei Wang95e37682019-04-12 11:13:36 -070054#include <audio_utils/safe_math.h>
Mikhail Naganov9fe94012016-10-14 14:57:40 -070055#include <system/audio_effects/effect_aec.h>
Eric Laurentb3f315a2021-07-13 15:09:05 +020056#include <system/audio_effects/effect_downmix.h>
57#include <system/audio_effects/effect_ns.h>
Eric Laurent1c5e2e32021-08-18 18:50:28 +020058#include <system/audio_effects/effect_spatializer.h>
Mikhail Naganovcbc8f612016-10-11 18:05:13 -070059#include <system/audio.h>
Eric Laurent81784c32012-11-19 14:55:58 -080060
61// NBAIO implementations
Glenn Kasten6dbb5e32014-05-13 10:38:42 -070062#include <media/nbaio/AudioStreamInSource.h>
Eric Laurent81784c32012-11-19 14:55:58 -080063#include <media/nbaio/AudioStreamOutSink.h>
64#include <media/nbaio/MonoPipe.h>
65#include <media/nbaio/MonoPipeReader.h>
66#include <media/nbaio/Pipe.h>
67#include <media/nbaio/PipeReader.h>
68#include <media/nbaio/SourceAudioBufferProvider.h>
Wei Jia3f273d12015-11-24 09:06:49 -080069#include <mediautils/BatteryNotifier.h>
Andy Hungafc51db2022-04-08 17:33:40 -070070#include <mediautils/Process.h>
Eric Laurent81784c32012-11-19 14:55:58 -080071
Mikhail Naganov2996f672019-04-18 12:29:59 -070072#include <audiomanager/AudioManager.h>
Eric Laurent81784c32012-11-19 14:55:58 -080073#include <powermanager/PowerManager.h>
74
Kevin Rocard7588ff42018-01-08 11:11:30 -080075#include <media/audiohal/EffectsFactoryHalInterface.h>
Kevin Rocard069c2712018-03-29 19:09:14 -070076#include <media/audiohal/StreamHalInterface.h>
Kevin Rocard7588ff42018-01-08 11:11:30 -080077
Eric Laurent81784c32012-11-19 14:55:58 -080078#include "AudioFlinger.h"
Andy Hungee58e4a2023-07-07 13:47:37 -070079#include "Threads.h"
80
Andy Hungab7ef302018-05-15 19:35:29 -070081#include <mediautils/SchedulingPolicyService.h>
82#include <mediautils/ServiceUtilities.h>
Eric Laurent81784c32012-11-19 14:55:58 -080083
Eric Laurent81784c32012-11-19 14:55:58 -080084#ifdef ADD_BATTERY_DATA
85#include <media/IMediaPlayerService.h>
86#include <media/IMediaDeathNotifier.h>
87#endif
88
Eric Laurent81784c32012-11-19 14:55:58 -080089#ifdef DEBUG_CPU_USAGE
Eric Tan5b13ff82018-07-27 11:20:17 -070090#include <audio_utils/Statistics.h>
Eric Laurent81784c32012-11-19 14:55:58 -080091#include <cpustats/ThreadCpuUsage.h>
92#endif
93
Andy Hungd69d9f12023-05-23 17:36:46 -070094#include <fastpath/AutoPark.h>
Glenn Kastenc05b8d72016-03-24 09:48:17 -070095
Nicolas Rouletfe1e1442017-01-30 12:02:03 -080096#include <pthread.h>
Andy Hung0a51b5c2023-07-18 20:54:44 -070097#include <afutils/DumpTryLock.h>
Andy Hung6cd79802023-07-19 16:56:19 -070098#include <afutils/Permission.h>
Andy Hung0077d8c2023-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 Hungee58e4a2023-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 Lindahl65e90012022-07-27 18:01:07 +0200186// Minimum amount of time between checking to see if the timestamp is advancing
187// for underrun detection. If we check too frequently, we may not detect a
188// timestamp update and will falsely detect underrun.
189static const nsecs_t kMinimumTimeBetweenTimestampChecksNs = 150 /* ms */ * 1000;
190
Glenn Kasten1b291842016-07-18 14:55:21 -0700191// The universal constant for ubiquitous 20ms value. The value of 20ms seems to provide a good
192// balance between power consumption and latency, and allows threads to be scheduled reliably
193// by the CFS scheduler.
194// FIXME Express other hardcoded references to 20ms with references to this constant and move
195// it appropriately.
196#define FMS_20 20
Eric Laurent51716182016-02-29 18:00:56 -0800197
Eric Laurent81784c32012-11-19 14:55:58 -0800198// Whether to use fast mixer
199static const enum {
200 FastMixer_Never, // never initialize or use: for debugging only
201 FastMixer_Always, // always initialize and use, even if not needed: for debugging only
202 // normal mixer multiplier is 1
203 FastMixer_Static, // initialize if needed, then use all the time if initialized,
204 // multiplier is calculated based on min & max normal mixer buffer size
205 FastMixer_Dynamic, // initialize if needed, then use dynamically depending on track load,
206 // multiplier is calculated based on min & max normal mixer buffer size
207 // FIXME for FastMixer_Dynamic:
208 // Supporting this option will require fixing HALs that can't handle large writes.
209 // For example, one HAL implementation returns an error from a large write,
210 // and another HAL implementation corrupts memory, possibly in the sample rate converter.
211 // We could either fix the HAL implementations, or provide a wrapper that breaks
212 // up large writes into smaller ones, and the wrapper would need to deal with scheduler.
213} kUseFastMixer = FastMixer_Static;
214
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700215// Whether to use fast capture
216static const enum {
217 FastCapture_Never, // never initialize or use: for debugging only
218 FastCapture_Always, // always initialize and use, even if not needed: for debugging only
219 FastCapture_Static, // initialize if needed, then use all the time if initialized
220} kUseFastCapture = FastCapture_Static;
221
Eric Laurent81784c32012-11-19 14:55:58 -0800222// Priorities for requestPriority
223static const int kPriorityAudioApp = 2;
224static const int kPriorityFastMixer = 3;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700225static const int kPriorityFastCapture = 3;
Eric Laurent81784c32012-11-19 14:55:58 -0800226
Glenn Kastenea38ee72016-04-18 11:08:01 -0700227// IAudioFlinger::createTrack() has an in/out parameter 'pFrameCount' for the total size of the
228// track buffer in shared memory. Zero on input means to use a default value. For fast tracks,
229// AudioFlinger derives the default from HAL buffer size and 'fast track multiplier'.
Glenn Kasten03490092014-05-27 12:30:54 -0700230
231// This is the default value, if not specified by property.
Glenn Kastenb5fed682013-12-03 09:06:43 -0800232static const int kFastTrackMultiplier = 2;
Eric Laurent81784c32012-11-19 14:55:58 -0800233
Glenn Kasten03490092014-05-27 12:30:54 -0700234// The minimum and maximum allowed values
235static const int kFastTrackMultiplierMin = 1;
236static const int kFastTrackMultiplierMax = 2;
237
238// The actual value to use, which can be specified per-device via property af.fast_track_multiplier.
239static int sFastTrackMultiplier = kFastTrackMultiplier;
240
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700241// See Thread::readOnlyHeap().
242// Initially this heap is used to allocate client buffers for "fast" AudioRecord.
243// Eventually it will be the single buffer that FastCapture writes into via HAL read(),
244// and that all "fast" AudioRecord clients read from. In either case, the size can be small.
Mikhail Naganov79a77822018-05-10 15:57:25 -0700245static const size_t kRecordThreadReadOnlyHeapSize = 0xD000;
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700246
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 Naganovf53e1822022-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 Hung920f6572022-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",
498 title.string(),
499 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 Hungee58e4a2023-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 Hung583043b2023-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 Hung583043b2023-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 Hungee58e4a2023-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 Hungee58e4a2023-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 Hungee58e4a2023-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 Hungee58e4a2023-07-07 13:47:37 -0700622status_t ThreadBase::setParameters(const String8& keyValuePairs)
Eric Laurent81784c32012-11-19 14:55:58 -0800623{
Eric Laurent81784c32012-11-19 14:55:58 -0800624 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
625 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 Hungee58e4a2023-07-07 13:47:37 -0700632status_t ThreadBase::sendConfigEvent_l(sp<ConfigEvent>& event)
Andy Hung920f6572022-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 Hungee58e4a2023-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 Hungee58e4a2023-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 Hungee58e4a2023-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 Hungee58e4a2023-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 Hungee58e4a2023-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 Hungee58e4a2023-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 Hungee58e4a2023-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 Hungee58e4a2023-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 Hungee58e4a2023-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 Hungee58e4a2023-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 Hungee58e4a2023-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 Hungee58e4a2023-07-07 13:47:37 -0700774void ThreadBase::sendHalLatencyModesChangedEvent_l()
Eric Laurent68a40a82022-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 Hungee58e4a2023-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",
809 data->mKeyValuePairs.string());
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 Laurent68a40a82022-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 Hungee58e4a2023-07-07 13:47:37 -0700948void ThreadBase::dump(int fd, const Vector<String16>& args)
Andy Hung920f6572022-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 Hung0a51b5c2023-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 Hungee58e4a2023-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,
Marco Nelissenb2208842014-02-07 14:00:50 -0800996 channelMaskToString(mChannelMask, mType != RECORD).string());
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 Hungee58e4a2023-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 Hung116bc262023-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 Hungee58e4a2023-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 Hungee58e4a2023-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 Hungee58e4a2023-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 Hungee58e4a2023-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 Hungee58e4a2023-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 Hungee58e4a2023-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 Hungee58e4a2023-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 Hungee58e4a2023-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 Hungee58e4a2023-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 Hungee58e4a2023-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 Hungee58e4a2023-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 Hungee58e4a2023-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 Hung116bc262023-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 Hungee58e4a2023-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 Hung116bc262023-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 Hungee58e4a2023-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 Hung116bc262023-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 Hungee58e4a2023-07-07 13:47:37 -07001316void ThreadBase::checkSuspendOnEffectEnabled(bool enabled,
Eric Laurent6b446ce2019-12-13 10:56:31 -08001317 audio_session_t sessionId,
Andy Hung920f6572022-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 Hungee58e4a2023-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 Hung116bc262023-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 Hungee58e4a2023-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 Hung116bc262023-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 Hungee58e4a2023-07-07 13:47:37 -07001541sp<IAfEffectHandle> ThreadBase::createEffect_l(
Andy Hung88035ac2023-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 Hung116bc262023-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 Hung116bc262023-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 Hung116bc262023-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 Hung583043b2023-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 Hung583043b2023-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 Hung583043b2023-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 Hung116bc262023-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 Hungee58e4a2023-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 Hung116bc262023-06-20 18:56:17 -07001650 sp<IAfEffectModule> effect;
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001651 {
1652 Mutex::Autolock _l(mLock);
Andy Hung116bc262023-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 Hung583043b2023-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 Hungee58e4a2023-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 Hung583043b2023-07-17 17:05:00 -07001687 mAfThreadCallback->onNonOffloadableGlobalEffectEnable();
Eric Laurent6b446ce2019-12-13 10:56:31 -08001688 }
1689 }
1690}
1691
Andy Hungee58e4a2023-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 Hungee58e4a2023-07-07 13:47:37 -07001699sp<IAfEffectModule> ThreadBase::getEffect(audio_session_t sessionId,
Andy Hung440901d2023-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 Hungee58e4a2023-07-07 13:47:37 -07001706sp<IAfEffectModule> ThreadBase::getEffect_l(audio_session_t sessionId,
Andy Hung440901d2023-06-29 21:19:25 -07001707 int effectId) const
Eric Laurent81784c32012-11-19 14:55:58 -08001708{
Andy Hung116bc262023-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 Hungee58e4a2023-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 Hung116bc262023-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 Hungee58e4a2023-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 Hung116bc262023-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 Hung116bc262023-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 Hung583043b2023-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 Hungee58e4a2023-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 Hung116bc262023-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 Hungee58e4a2023-07-07 13:47:37 -07001785void ThreadBase::lockEffectChains_l(
Andy Hung116bc262023-06-20 18:56:17 -07001786 Vector<sp<IAfEffectChain>>& effectChains)
Andy Hung920f6572022-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 Hungee58e4a2023-07-07 13:47:37 -07001795void ThreadBase::unlockEffectChains(
Andy Hung116bc262023-06-20 18:56:17 -07001796 const Vector<sp<IAfEffectChain>>& effectChains)
Andy Hung920f6572022-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 Hungee58e4a2023-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 Hungee58e4a2023-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 Hungee58e4a2023-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 Hungee58e4a2023-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;
1836 config->format = mFormat;
1837 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 Hungee58e4a2023-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 Hungee58e4a2023-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;
Atneya Nair166663a2023-06-27 19:16:24 -07001866 track->beginBatteryAttribution();
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 Hungee58e4a2023-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++;
Atneya Nair166663a2023-06-27 19:16:24 -07001880 track->endBatteryAttribution();
Andy Hungdae27702016-10-31 14:01:16 -07001881 // 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 Hungee58e4a2023-07-07 13:47:37 -07001891void ThreadBase::ActiveTracks<T>::clear() {
Andy Hungdae27702016-10-31 14:01:16 -07001892 for (const sp<T> &track : mActiveTracks) {
Atneya Nair166663a2023-06-27 19:16:24 -07001893 track->endBatteryAttribution();
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();
Andy Hungdae27702016-10-31 14:01:16 -07001900}
1901
1902template <typename T>
Andy Hungee58e4a2023-07-07 13:47:37 -07001903void ThreadBase::ActiveTracks<T>::updatePowerState(
Andy Hung920f6572022-10-06 12:09:49 -07001904 const sp<ThreadBase>& thread, bool force) {
Andy Hungdae27702016-10-31 14:01:16 -07001905 // Updates ActiveTracks client uids to the thread wakelock.
1906 if (mActiveTracksGeneration != mLastActiveTracksGeneration || force) {
1907 thread->updateWakeLockUids_l(getWakeLockUids());
1908 mLastActiveTracksGeneration = mActiveTracksGeneration;
1909 }
Andy Hungdae27702016-10-31 14:01:16 -07001910}
Eric Laurent83b88082014-06-20 18:31:16 -07001911
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001912template <typename T>
Andy Hungee58e4a2023-07-07 13:47:37 -07001913bool ThreadBase::ActiveTracks<T>::readAndClearHasChanged() {
Jasmine Chaeaa10e42021-05-11 10:11:14 +08001914 bool hasChanged = mHasChanged;
Kevin Rocard069c2712018-03-29 19:09:14 -07001915 mHasChanged = false;
Jasmine Chaeaa10e42021-05-11 10:11:14 +08001916
1917 for (const sp<T> &track : mActiveTracks) {
1918 // Do not short-circuit as all hasChanged states must be reset
1919 // as all the metadata are going to be sent
1920 hasChanged |= track->readAndClearHasChanged();
1921 }
Kevin Rocard069c2712018-03-29 19:09:14 -07001922 return hasChanged;
1923}
1924
1925template <typename T>
Andy Hungee58e4a2023-07-07 13:47:37 -07001926void ThreadBase::ActiveTracks<T>::logTrack(
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001927 const char *funcName, const sp<T> &track) const {
1928 if (mLocalLog != nullptr) {
1929 String8 result;
1930 track->appendDump(result, false /* active */);
1931 mLocalLog->log("AT::%-10s(%p) %s", funcName, track.get(), result.string());
1932 }
1933}
1934
Andy Hungee58e4a2023-07-07 13:47:37 -07001935void ThreadBase::broadcast_l()
Eric Laurent6acd1d42017-01-04 14:23:29 -08001936{
1937 // Thread could be blocked waiting for async
1938 // so signal it to handle state changes immediately
1939 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
1940 // be lost so we also flag to prevent it blocking on mWaitWorkCV
1941 mSignalPending = true;
1942 mWaitWorkCV.broadcast();
1943}
1944
Andy Hungd0979812019-02-21 15:51:44 -08001945// Call only from threadLoop() or when it is idle.
1946// Do not call from high performance code as this may do binder rpc to the MediaMetrics service.
Andy Hungee58e4a2023-07-07 13:47:37 -07001947void ThreadBase::sendStatistics(bool force)
Andy Hungd0979812019-02-21 15:51:44 -08001948{
1949 // Do not log if we have no stats.
1950 // We choose the timestamp verifier because it is the most likely item to be present.
1951 const int64_t nstats = mTimestampVerifier.getN() - mLastRecordedTimestampVerifierN;
1952 if (nstats == 0) {
1953 return;
1954 }
1955
1956 // Don't log more frequently than once per 12 hours.
1957 // We use BOOTTIME to include suspend time.
1958 const int64_t timeNs = systemTime(SYSTEM_TIME_BOOTTIME);
1959 const int64_t sinceNs = timeNs - mLastRecordedTimeNs; // ok if mLastRecordedTimeNs = 0
1960 if (!force && sinceNs <= 12 * NANOS_PER_HOUR) {
1961 return;
1962 }
1963
1964 mLastRecordedTimestampVerifierN = mTimestampVerifier.getN();
1965 mLastRecordedTimeNs = timeNs;
1966
Ray Essickf27e9872019-12-07 06:28:46 -08001967 std::unique_ptr<mediametrics::Item> item(mediametrics::Item::create("audiothread"));
Andy Hungd0979812019-02-21 15:51:44 -08001968
1969#define MM_PREFIX "android.media.audiothread." // avoid cut-n-paste errors.
1970
1971 // thread configuration
1972 item->setInt32(MM_PREFIX "id", (int32_t)mId); // IO handle
1973 // item->setInt32(MM_PREFIX "portId", (int32_t)mPortId);
1974 item->setCString(MM_PREFIX "type", threadTypeToString(mType));
1975 item->setInt32(MM_PREFIX "sampleRate", (int32_t)mSampleRate);
1976 item->setInt64(MM_PREFIX "channelMask", (int64_t)mChannelMask);
1977 item->setCString(MM_PREFIX "encoding", toString(mFormat).c_str());
1978 item->setInt32(MM_PREFIX "frameCount", (int32_t)mFrameCount);
jiabinc52b1ff2019-10-31 17:20:42 -07001979 item->setCString(MM_PREFIX "outDevice", toString(outDeviceTypes()).c_str());
1980 item->setCString(MM_PREFIX "inDevice", toString(inDeviceType()).c_str());
Andy Hungd0979812019-02-21 15:51:44 -08001981
1982 // thread statistics
1983 if (mIoJitterMs.getN() > 0) {
1984 item->setDouble(MM_PREFIX "ioJitterMs.mean", mIoJitterMs.getMean());
1985 item->setDouble(MM_PREFIX "ioJitterMs.std", mIoJitterMs.getStdDev());
1986 }
1987 if (mProcessTimeMs.getN() > 0) {
1988 item->setDouble(MM_PREFIX "processTimeMs.mean", mProcessTimeMs.getMean());
1989 item->setDouble(MM_PREFIX "processTimeMs.std", mProcessTimeMs.getStdDev());
1990 }
1991 const auto tsjitter = mTimestampVerifier.getJitterMs();
1992 if (tsjitter.getN() > 0) {
1993 item->setDouble(MM_PREFIX "timestampJitterMs.mean", tsjitter.getMean());
1994 item->setDouble(MM_PREFIX "timestampJitterMs.std", tsjitter.getStdDev());
1995 }
1996 if (mLatencyMs.getN() > 0) {
1997 item->setDouble(MM_PREFIX "latencyMs.mean", mLatencyMs.getMean());
1998 item->setDouble(MM_PREFIX "latencyMs.std", mLatencyMs.getStdDev());
1999 }
Robert Wu06db0a32021-08-10 19:05:34 +00002000 if (mMonopipePipeDepthStats.getN() > 0) {
2001 item->setDouble(MM_PREFIX "monopipePipeDepthStats.mean",
2002 mMonopipePipeDepthStats.getMean());
2003 item->setDouble(MM_PREFIX "monopipePipeDepthStats.std",
2004 mMonopipePipeDepthStats.getStdDev());
2005 }
Andy Hungd0979812019-02-21 15:51:44 -08002006
2007 item->selfrecord();
2008}
2009
Andy Hungee58e4a2023-07-07 13:47:37 -07002010product_strategy_t ThreadBase::getStrategyForStream(audio_stream_type_t stream) const
Eric Laurentd66d7a12021-07-13 13:35:32 +02002011{
Andy Hung583043b2023-07-17 17:05:00 -07002012 if (!mAfThreadCallback->isAudioPolicyReady()) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02002013 return PRODUCT_STRATEGY_NONE;
2014 }
2015 return AudioSystem::getStrategyForStream(stream);
2016}
2017
Vlad Popa6fbbfbf2023-02-22 15:05:43 +01002018// startMelComputation_l() must be called with AudioFlinger::mLock held
Andy Hungee58e4a2023-07-07 13:47:37 -07002019void ThreadBase::startMelComputation_l(
Vlad Popa6fbbfbf2023-02-22 15:05:43 +01002020 const sp<audio_utils::MelProcessor>& /*processor*/)
2021{
2022 // Do nothing
2023 ALOGW("%s: ThreadBase does not support CSD", __func__);
2024}
2025
2026// stopMelComputation_l() must be called with AudioFlinger::mLock held
Andy Hungee58e4a2023-07-07 13:47:37 -07002027void ThreadBase::stopMelComputation_l()
Vlad Popa6fbbfbf2023-02-22 15:05:43 +01002028{
2029 // Do nothing
2030 ALOGW("%s: ThreadBase does not support CSD", __func__);
2031}
2032
Eric Laurent81784c32012-11-19 14:55:58 -08002033// ----------------------------------------------------------------------------
2034// Playback
2035// ----------------------------------------------------------------------------
2036
Andy Hung583043b2023-07-17 17:05:00 -07002037PlaybackThread::PlaybackThread(const sp<IAfThreadCallback>& afThreadCallback,
Eric Laurent81784c32012-11-19 14:55:58 -08002038 AudioStreamOut* output,
2039 audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -07002040 type_t type,
Eric Laurentf1f22e72021-07-13 14:04:14 +02002041 bool systemReady,
2042 audio_config_base_t *mixerConfig)
Andy Hung583043b2023-07-17 17:05:00 -07002043 : ThreadBase(afThreadCallback, id, type, systemReady, true /* isOut */),
Andy Hung2098f272014-02-27 14:00:06 -08002044 mNormalFrameCount(0), mSinkBuffer(NULL),
Eric Laurent1c5e2e32021-08-18 18:50:28 +02002045 mMixerBufferEnabled(AudioFlinger::kEnableExtendedPrecision || type == SPATIALIZER),
Andy Hung69aed5f2014-02-25 17:24:40 -08002046 mMixerBuffer(NULL),
2047 mMixerBufferSize(0),
2048 mMixerBufferFormat(AUDIO_FORMAT_INVALID),
2049 mMixerBufferValid(false),
Eric Laurent1c5e2e32021-08-18 18:50:28 +02002050 mEffectBufferEnabled(AudioFlinger::kEnableExtendedPrecision || type == SPATIALIZER),
Andy Hung98ef9782014-03-04 14:46:50 -08002051 mEffectBuffer(NULL),
2052 mEffectBufferSize(0),
2053 mEffectBufferFormat(AUDIO_FORMAT_INVALID),
2054 mEffectBufferValid(false),
Glenn Kastenc1fac192013-08-06 07:41:36 -07002055 mSuspended(0), mBytesWritten(0),
Andy Hungc54b1ff2016-02-23 14:07:07 -08002056 mFramesWritten(0),
Andy Hung238fa3d2016-07-28 10:53:22 -07002057 mSuspendedFrames(0),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002058 mActiveTracks(&this->mLocalLog),
Eric Laurent81784c32012-11-19 14:55:58 -08002059 // mStreamTypes[] initialized in constructor body
Andy Hung1bc088a2018-02-09 15:57:31 -08002060 mTracks(type == MIXER),
Eric Laurent81784c32012-11-19 14:55:58 -08002061 mOutput(output),
Andy Hung446f4df2019-02-21 12:26:41 -08002062 mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
Eric Laurent81784c32012-11-19 14:55:58 -08002063 mMixerStatus(MIXER_IDLE),
2064 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002065 mStandbyDelayNs(AudioFlinger::mStandbyTimeInNsecs),
Eric Laurentbfb1b832013-01-07 09:53:42 -08002066 mBytesRemaining(0),
2067 mCurrentWriteLength(0),
2068 mUseAsyncWrite(false),
Eric Laurent3b4529e2013-09-05 18:09:19 -07002069 mWriteAckSequence(0),
2070 mDrainSequence(0),
Andy Hung1d2d2aea2023-07-19 16:22:58 -07002071 mScreenState(mAfThreadCallback->getScreenState()),
Eric Laurent81784c32012-11-19 14:55:58 -08002072 // index 0 is reserved for normal mixer's submix
Glenn Kastendc2c50b2016-04-21 08:13:14 -07002073 mFastTrackAvailMask(((1 << FastMixerState::sMaxFastTracks) - 1) & ~1),
Eric Laurent7c29ec92017-09-20 17:54:22 -07002074 mHwSupportsPause(false), mHwPaused(false), mFlushPending(false),
Eric Laurent74c38dc2020-12-23 18:19:44 +01002075 mLeftVolFloat(-1.0), mRightVolFloat(-1.0),
Brian Lindahl65e90012022-07-27 18:01:07 +02002076 mDownStreamPatch{},
Eric Laurentb0463942022-12-20 16:31:10 +01002077 mIsTimestampAdvancing(kMinimumTimeBetweenTimestampChecksNs)
Eric Laurent81784c32012-11-19 14:55:58 -08002078{
Glenn Kastend7dca052015-03-05 16:05:54 -08002079 snprintf(mThreadName, kThreadNameLength, "AudioOut_%X", id);
Andy Hung583043b2023-07-17 17:05:00 -07002080 mNBLogWriter = afThreadCallback->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08002081
2082 // Assumes constructor is called by AudioFlinger with it's mLock held, but
2083 // it would be safer to explicitly pass initial masterVolume/masterMute as
2084 // parameter.
2085 //
2086 // If the HAL we are using has support for master volume or master mute,
2087 // then do not attenuate or mute during mixing (just leave the volume at 1.0
2088 // and the mute set to false).
Andy Hung583043b2023-07-17 17:05:00 -07002089 mMasterVolume = afThreadCallback->masterVolume_l();
2090 mMasterMute = afThreadCallback->masterMute_l();
George Burgess IV5e4d86f2020-02-18 12:55:36 -08002091 if (mOutput->audioHwDev) {
Eric Laurent81784c32012-11-19 14:55:58 -08002092 if (mOutput->audioHwDev->canSetMasterVolume()) {
2093 mMasterVolume = 1.0;
2094 }
2095
2096 if (mOutput->audioHwDev->canSetMasterMute()) {
2097 mMasterMute = false;
2098 }
Andy Hungc8fddf32018-08-08 18:32:37 -07002099 mIsMsdDevice = strcmp(
2100 mOutput->audioHwDev->moduleName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002101 }
2102
Eric Laurentf1f22e72021-07-13 14:04:14 +02002103 if (mixerConfig != nullptr && mixerConfig->channel_mask != AUDIO_CHANNEL_NONE) {
2104 mMixerChannelMask = mixerConfig->channel_mask;
2105 }
2106
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002107 readOutputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002108
Eric Laurent1c5e2e32021-08-18 18:50:28 +02002109 if (mType != SPATIALIZER
Eric Laurentb3f315a2021-07-13 15:09:05 +02002110 && mMixerChannelMask != mChannelMask) {
2111 LOG_ALWAYS_FATAL("HAL channel mask %#x does not match mixer channel mask %#x",
2112 mChannelMask, mMixerChannelMask);
2113 }
2114
Andy Hungc8fddf32018-08-08 18:32:37 -07002115 // TODO: We may also match on address as well as device type for
2116 // AUDIO_DEVICE_OUT_BUS, AUDIO_DEVICE_OUT_ALL_A2DP, AUDIO_DEVICE_OUT_REMOTE_SUBMIX
Dean Wheatleyf8726f02019-12-02 14:12:01 +11002117 if (type == MIXER || type == DIRECT || type == OFFLOAD) {
jiabinc52b1ff2019-10-31 17:20:42 -07002118 // TODO: This property should be ensure that only contains one single device type.
2119 mTimestampCorrectedDevice = (audio_devices_t)property_get_int64(
2120 "audio.timestamp.corrected_output_device",
Andy Hungc8fddf32018-08-08 18:32:37 -07002121 (int64_t)(mIsMsdDevice ? AUDIO_DEVICE_OUT_BUS // turn on by default for MSD
2122 : AUDIO_DEVICE_NONE));
2123 }
2124
Mikhail Naganovf33115d2020-09-25 23:03:05 +00002125 for (int i = AUDIO_STREAM_MIN; i < AUDIO_STREAM_FOR_POLICY_CNT; ++i) {
2126 const audio_stream_type_t stream{static_cast<audio_stream_type_t>(i)};
Eric Laurent98e38192018-02-15 18:31:53 -08002127 mStreamTypes[stream].volume = 0.0f;
Andy Hung583043b2023-07-17 17:05:00 -07002128 mStreamTypes[stream].mute = mAfThreadCallback->streamMute_l(stream);
Eric Laurent81784c32012-11-19 14:55:58 -08002129 }
Eric Laurent35f8c7c2020-02-08 11:42:35 -08002130 // Audio patch and call assistant volume are always max
Eric Laurent98e38192018-02-15 18:31:53 -08002131 mStreamTypes[AUDIO_STREAM_PATCH].volume = 1.0f;
2132 mStreamTypes[AUDIO_STREAM_PATCH].mute = false;
Eric Laurent35f8c7c2020-02-08 11:42:35 -08002133 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].volume = 1.0f;
2134 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].mute = false;
Eric Laurent81784c32012-11-19 14:55:58 -08002135}
2136
Andy Hungee58e4a2023-07-07 13:47:37 -07002137PlaybackThread::~PlaybackThread()
Eric Laurent81784c32012-11-19 14:55:58 -08002138{
Andy Hung583043b2023-07-17 17:05:00 -07002139 mAfThreadCallback->unregisterWriter(mNBLogWriter);
Andy Hung010a1a12014-03-13 13:57:33 -07002140 free(mSinkBuffer);
Andy Hung69aed5f2014-02-25 17:24:40 -08002141 free(mMixerBuffer);
Andy Hung98ef9782014-03-04 14:46:50 -08002142 free(mEffectBuffer);
Eric Laurentb62d0362021-10-26 17:40:18 +02002143 free(mPostSpatializerBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08002144}
2145
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002146// Thread virtuals
2147
Andy Hungee58e4a2023-07-07 13:47:37 -07002148void PlaybackThread::onFirstRef()
Eric Laurent81784c32012-11-19 14:55:58 -08002149{
Jasmine Chaeaa10e42021-05-11 10:11:14 +08002150 if (!isStreamInitialized()) {
jiabinf6eb4c32020-02-25 14:06:25 -08002151 ALOGE("The stream is not open yet"); // This should not happen.
2152 } else {
Mikhail Naganovaec565e2023-02-22 16:31:28 -08002153 // Callbacks take strong or weak pointers as a parameter.
2154 // Since PlaybackThread passes itself as a callback handler, it can only
2155 // be done outside of the constructor. Creating weak and especially strong
2156 // pointers to a refcounted object in its own constructor is strongly
2157 // discouraged, see comments in system/core/libutils/include/utils/RefBase.h.
2158 // Even if a function takes a weak pointer, it is possible that it will
2159 // need to convert it to a strong pointer down the line.
2160 if (mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING &&
2161 mOutput->stream->setCallback(this) == OK) {
2162 mUseAsyncWrite = true;
Andy Hungee58e4a2023-07-07 13:47:37 -07002163 mCallbackThread = sp<AsyncCallbackThread>::make(this);
Mikhail Naganovaec565e2023-02-22 16:31:28 -08002164 }
2165
jiabinf6eb4c32020-02-25 14:06:25 -08002166 if (mOutput->stream->setEventCallback(this) != OK) {
jiabinf1a36052020-08-19 14:33:31 -07002167 ALOGD("Failed to add event callback");
jiabinf6eb4c32020-02-25 14:06:25 -08002168 }
2169 }
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002170 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
Andy Hung44d648b2022-04-08 17:33:40 -07002171 mThreadSnapshot.setTid(getTid());
Eric Laurent81784c32012-11-19 14:55:58 -08002172}
2173
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002174// ThreadBase virtuals
Andy Hungee58e4a2023-07-07 13:47:37 -07002175void PlaybackThread::preExit()
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002176{
2177 ALOGV(" preExit()");
Ytai Ben-Tsvi7e0183f2022-02-04 10:49:54 -08002178 status_t result = mOutput->stream->exit();
2179 ALOGE_IF(result != OK, "Error when calling exit(): %d", result);
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002180}
2181
Andy Hungee58e4a2023-07-07 13:47:37 -07002182void PlaybackThread::dumpTracks_l(int fd, const Vector<String16>& /* args */)
Eric Laurent81784c32012-11-19 14:55:58 -08002183{
Eric Laurent81784c32012-11-19 14:55:58 -08002184 String8 result;
2185
Marco Nelissenb2208842014-02-07 14:00:50 -08002186 result.appendFormat(" Stream volumes in dB: ");
Eric Laurent81784c32012-11-19 14:55:58 -08002187 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
2188 const stream_type_t *st = &mStreamTypes[i];
2189 if (i > 0) {
2190 result.appendFormat(", ");
2191 }
2192 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
2193 if (st->mute) {
2194 result.append("M");
2195 }
2196 }
2197 result.append("\n");
2198 write(fd, result.string(), result.length());
2199 result.clear();
2200
Eric Laurent81784c32012-11-19 14:55:58 -08002201 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
2202 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
Elliott Hughes87cebad2014-05-22 10:14:43 -07002203 dprintf(fd, " Normal mixer raw underrun counters: partial=%u empty=%u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08002204 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Marco Nelissenb2208842014-02-07 14:00:50 -08002205
2206 size_t numtracks = mTracks.size();
2207 size_t numactive = mActiveTracks.size();
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002208 dprintf(fd, " %zu Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08002209 size_t numactiveseen = 0;
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002210 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08002211 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002212 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002213 result.append(prefix);
Andy Hungf6ab58d2018-05-25 12:50:39 -07002214 mTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08002215 for (size_t i = 0; i < numtracks; ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07002216 sp<IAfTrack> track = mTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08002217 if (track != 0) {
2218 bool active = mActiveTracks.indexOf(track) >= 0;
2219 if (active) {
2220 numactiveseen++;
2221 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002222 result.append(prefix);
2223 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08002224 }
2225 }
2226 } else {
2227 result.append("\n");
2228 }
2229 if (numactiveseen != numactive) {
2230 // some tracks in the active list were not in the tracks list
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002231 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08002232 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002233 result.append(prefix);
Andy Hungf6ab58d2018-05-25 12:50:39 -07002234 mActiveTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08002235 for (size_t i = 0; i < numactive; ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07002236 sp<IAfTrack> track = mActiveTracks[i];
Andy Hungdae27702016-10-31 14:01:16 -07002237 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002238 result.append(prefix);
2239 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08002240 }
2241 }
2242 }
2243
2244 write(fd, result.string(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08002245}
2246
Andy Hungee58e4a2023-07-07 13:47:37 -07002247void PlaybackThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -08002248{
Andy Hung04cb8f72020-03-20 13:44:33 -07002249 dprintf(fd, " Master volume: %f\n", mMasterVolume);
Mikhail Naganovdfb411f2018-09-11 13:39:56 -07002250 dprintf(fd, " Master mute: %s\n", mMasterMute ? "on" : "off");
Eric Laurentf1f22e72021-07-13 14:04:14 +02002251 dprintf(fd, " Mixer channel Mask: %#x (%s)\n",
2252 mMixerChannelMask, channelMaskToString(mMixerChannelMask, true /* output */).c_str());
jiabin245cdd92018-12-07 17:55:15 -08002253 if (mHapticChannelMask != AUDIO_CHANNEL_NONE) {
2254 dprintf(fd, " Haptic channel mask: %#x (%s)\n", mHapticChannelMask,
2255 channelMaskToString(mHapticChannelMask, true /* output */).c_str());
2256 }
Elliott Hughes87cebad2014-05-22 10:14:43 -07002257 dprintf(fd, " Normal frame count: %zu\n", mNormalFrameCount);
Elliott Hughes87cebad2014-05-22 10:14:43 -07002258 dprintf(fd, " Total writes: %d\n", mNumWrites);
2259 dprintf(fd, " Delayed writes: %d\n", mNumDelayedWrites);
2260 dprintf(fd, " Blocked in write: %s\n", mInWrite ? "yes" : "no");
2261 dprintf(fd, " Suspend count: %d\n", mSuspended);
2262 dprintf(fd, " Sink buffer : %p\n", mSinkBuffer);
2263 dprintf(fd, " Mixer buffer: %p\n", mMixerBuffer);
2264 dprintf(fd, " Effect buffer: %p\n", mEffectBuffer);
2265 dprintf(fd, " Fast track availMask=%#x\n", mFastTrackAvailMask);
Eric Laurent42537be2016-01-08 17:16:42 -08002266 dprintf(fd, " Standby delay ns=%lld\n", (long long)mStandbyDelayNs);
Glenn Kasten97b7b752014-09-28 13:04:24 -07002267 AudioStreamOut *output = mOutput;
2268 audio_output_flags_t flags = output != NULL ? output->flags : AUDIO_OUTPUT_FLAG_NONE;
Mikhail Naganov913d06c2016-11-01 12:49:22 -07002269 dprintf(fd, " AudioStreamOut: %p flags %#x (%s)\n",
Andy Hung9b181952019-02-25 14:53:36 -08002270 output, flags, toString(flags).c_str());
Andy Hungb54c8542016-09-21 12:55:15 -07002271 dprintf(fd, " Frames written: %lld\n", (long long)mFramesWritten);
2272 dprintf(fd, " Suspended frames: %lld\n", (long long)mSuspendedFrames);
2273 if (mPipeSink.get() != nullptr) {
2274 dprintf(fd, " PipeSink frames written: %lld\n", (long long)mPipeSink->framesWritten());
2275 }
2276 if (output != nullptr) {
2277 dprintf(fd, " Hal stream dump:\n");
Andy Hung61589a42021-06-16 09:37:53 -07002278 (void)output->stream->dump(fd, args);
Andy Hungb54c8542016-09-21 12:55:15 -07002279 }
Eric Laurent81784c32012-11-19 14:55:58 -08002280}
2281
Eric Laurent81784c32012-11-19 14:55:58 -08002282// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
Andy Hungee58e4a2023-07-07 13:47:37 -07002283sp<IAfTrack> PlaybackThread::createTrack_l(
Andy Hung88035ac2023-06-27 17:05:02 -07002284 const sp<Client>& client,
Eric Laurent81784c32012-11-19 14:55:58 -08002285 audio_stream_type_t streamType,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07002286 const audio_attributes_t& attr,
Eric Laurent21da6472017-11-09 16:29:26 -08002287 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08002288 audio_format_t format,
2289 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08002290 size_t *pFrameCount,
Eric Laurent21da6472017-11-09 16:29:26 -08002291 size_t *pNotificationFrameCount,
2292 uint32_t notificationsPerBuffer,
2293 float speed,
Eric Laurent81784c32012-11-19 14:55:58 -08002294 const sp<IMemory>& sharedBuffer,
Glenn Kastend848eb42016-03-08 13:42:11 -08002295 audio_session_t sessionId,
Eric Laurent05067782016-06-01 18:27:28 -07002296 audio_output_flags_t *flags,
Eric Laurent09f1ed22019-04-24 17:45:17 -07002297 pid_t creatorPid,
Svet Ganov33761132021-05-13 22:51:08 +00002298 const AttributionSourceState& attributionSource,
Eric Laurent81784c32012-11-19 14:55:58 -08002299 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002300 status_t *status,
jiabinf6eb4c32020-02-25 14:06:25 -08002301 audio_port_handle_t portId,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02002302 const sp<media::IAudioTrackCallback>& callback,
jiabinc658e452022-10-21 20:52:21 +00002303 bool isSpatialized,
2304 bool isBitPerfect)
Eric Laurent81784c32012-11-19 14:55:58 -08002305{
Glenn Kasten74935e42013-12-19 08:56:45 -08002306 size_t frameCount = *pFrameCount;
Eric Laurent21da6472017-11-09 16:29:26 -08002307 size_t notificationFrameCount = *pNotificationFrameCount;
Andy Hung8d31fd22023-06-26 19:20:57 -07002308 sp<IAfTrack> track;
Eric Laurent81784c32012-11-19 14:55:58 -08002309 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07002310 audio_output_flags_t outputFlags = mOutput->flags;
Eric Laurent21da6472017-11-09 16:29:26 -08002311 audio_output_flags_t requestedFlags = *flags;
Eric Laurent9b11c022018-06-06 19:19:22 -07002312 uint32_t sampleRate;
2313
2314 if (sharedBuffer != 0 && checkIMemory(sharedBuffer) != NO_ERROR) {
2315 lStatus = BAD_VALUE;
2316 goto Exit;
2317 }
Eric Laurent21da6472017-11-09 16:29:26 -08002318
2319 if (*pSampleRate == 0) {
2320 *pSampleRate = mSampleRate;
2321 }
Eric Laurent9b11c022018-06-06 19:19:22 -07002322 sampleRate = *pSampleRate;
Eric Laurent05067782016-06-01 18:27:28 -07002323
2324 // special case for FAST flag considered OK if fast mixer is present
2325 if (hasFastMixer()) {
2326 outputFlags = (audio_output_flags_t)(outputFlags | AUDIO_OUTPUT_FLAG_FAST);
2327 }
2328
2329 // Check if requested flags are compatible with output stream flags
2330 if ((*flags & outputFlags) != *flags) {
2331 ALOGW("createTrack_l(): mismatch between requested flags (%08x) and output flags (%08x)",
2332 *flags, outputFlags);
2333 *flags = (audio_output_flags_t)(*flags & outputFlags);
2334 }
Eric Laurent81784c32012-11-19 14:55:58 -08002335
jiabinc658e452022-10-21 20:52:21 +00002336 if (isBitPerfect) {
Andy Hung116bc262023-06-20 18:56:17 -07002337 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
jiabinc658e452022-10-21 20:52:21 +00002338 if (chain.get() != nullptr) {
2339 // Bit-perfect is required according to the configuration and preferred mixer
2340 // attributes, but it is not in the output flag from the client's request. Explicitly
2341 // adding bit-perfect flag to check the compatibility
2342 audio_output_flags_t flagsToCheck =
2343 (audio_output_flags_t)(*flags & AUDIO_OUTPUT_FLAG_BIT_PERFECT);
2344 chain->checkOutputFlagCompatibility(&flagsToCheck);
2345 if ((flagsToCheck & AUDIO_OUTPUT_FLAG_BIT_PERFECT) == AUDIO_OUTPUT_FLAG_NONE) {
2346 ALOGE("%s cannot create track as there is data-processing effect attached to "
2347 "given session id(%d)", __func__, sessionId);
2348 lStatus = BAD_VALUE;
2349 goto Exit;
2350 }
2351 *flags = flagsToCheck;
2352 }
2353 }
2354
Eric Laurent81784c32012-11-19 14:55:58 -08002355 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07002356 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
Eric Laurent81784c32012-11-19 14:55:58 -08002357 if (
Eric Laurent81784c32012-11-19 14:55:58 -08002358 // PCM data
2359 audio_is_linear_pcm(format) &&
Andy Hung1f439e12015-05-19 12:57:41 -07002360 // TODO: extract as a data library function that checks that a computationally
2361 // expensive downmixer is not required: isFastOutputChannelConversion()
jiabin245cdd92018-12-07 17:55:15 -08002362 (channelMask == (mChannelMask | mHapticChannelMask) ||
Andy Hung1f439e12015-05-19 12:57:41 -07002363 mChannelMask != AUDIO_CHANNEL_OUT_STEREO ||
2364 (channelMask == AUDIO_CHANNEL_OUT_MONO
2365 /* && mChannelMask == AUDIO_CHANNEL_OUT_STEREO */)) &&
Eric Laurent81784c32012-11-19 14:55:58 -08002366 // hardware sample rate
2367 (sampleRate == mSampleRate) &&
Eric Laurent81784c32012-11-19 14:55:58 -08002368 // normal mixer has an associated fast mixer
2369 hasFastMixer() &&
2370 // there are sufficient fast track slots available
2371 (mFastTrackAvailMask != 0)
2372 // FIXME test that MixerThread for this fast track has a capable output HAL
2373 // FIXME add a permission test also?
2374 ) {
Andy Hunge0a269a2016-03-23 15:13:42 -07002375 // static tracks can have any nonzero framecount, streaming tracks check against minimum.
2376 if (sharedBuffer == 0) {
Glenn Kasten03490092014-05-27 12:30:54 -07002377 // read the fast track multiplier property the first time it is needed
2378 int ok = pthread_once(&sFastTrackMultiplierOnce, sFastTrackMultiplierInit);
2379 if (ok != 0) {
2380 ALOGE("%s pthread_once failed: %d", __func__, ok);
2381 }
Andy Hunge0a269a2016-03-23 15:13:42 -07002382 frameCount = max(frameCount, mFrameCount * sFastTrackMultiplier); // incl framecount 0
Eric Laurent81784c32012-11-19 14:55:58 -08002383 }
Eric Laurent4c415062016-06-17 16:14:16 -07002384
2385 // check compatibility with audio effects.
2386 { // scope for mLock
2387 Mutex::Autolock _l(mLock);
Andy Hungd3bb0ad2016-10-11 17:16:43 -07002388 for (audio_session_t session : {
Eric Laurent3f75a5b2019-11-12 15:55:51 -08002389 AUDIO_SESSION_DEVICE,
Andy Hungd3bb0ad2016-10-11 17:16:43 -07002390 AUDIO_SESSION_OUTPUT_STAGE,
2391 AUDIO_SESSION_OUTPUT_MIX,
2392 sessionId,
2393 }) {
Andy Hung116bc262023-06-20 18:56:17 -07002394 sp<IAfEffectChain> chain = getEffectChain_l(session);
Andy Hungd3bb0ad2016-10-11 17:16:43 -07002395 if (chain.get() != nullptr) {
2396 audio_output_flags_t old = *flags;
2397 chain->checkOutputFlagCompatibility(flags);
2398 if (old != *flags) {
2399 ALOGV("AUDIO_OUTPUT_FLAGS denied by effect, session=%d old=%#x new=%#x",
2400 (int)session, (int)old, (int)*flags);
2401 }
Eric Laurent4c415062016-06-17 16:14:16 -07002402 }
2403 }
2404 }
Eric Laurent122f7e72016-06-29 11:53:29 -07002405 ALOGV_IF((*flags & AUDIO_OUTPUT_FLAG_FAST) != 0,
Eric Laurent4c415062016-06-17 16:14:16 -07002406 "AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
2407 frameCount, mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08002408 } else {
Robert Wu4c7bb7d2021-08-12 18:50:13 +00002409 ALOGD("AUDIO_OUTPUT_FLAG_FAST denied: sharedBuffer=%p frameCount=%zu "
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002410 "mFrameCount=%zu format=%#x mFormat=%#x isLinear=%d channelMask=%#x "
Andy Hung6146c082014-03-18 11:56:15 -07002411 "sampleRate=%u mSampleRate=%u "
Eric Laurent81784c32012-11-19 14:55:58 -08002412 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
Glenn Kastend79072e2016-01-06 08:41:20 -08002413 sharedBuffer.get(), frameCount, mFrameCount, format, mFormat,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07002414 audio_is_linear_pcm(format), channelMask, sampleRate,
2415 mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
Eric Laurent4c415062016-06-17 16:14:16 -07002416 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_FAST);
Andy Hung0e48d252015-01-26 11:43:15 -08002417 }
2418 }
Eric Laurent21da6472017-11-09 16:29:26 -08002419
2420 if (!audio_has_proportional_frames(format)) {
2421 if (sharedBuffer != 0) {
2422 // Same comment as below about ignoring frameCount parameter for set()
2423 frameCount = sharedBuffer->size();
2424 } else if (frameCount == 0) {
2425 frameCount = mNormalFrameCount;
2426 }
2427 if (notificationFrameCount != frameCount) {
2428 notificationFrameCount = frameCount;
2429 }
2430 } else if (sharedBuffer != 0) {
2431 // FIXME: Ensure client side memory buffers need
2432 // not have additional alignment beyond sample
2433 // (e.g. 16 bit stereo accessed as 32 bit frame).
2434 size_t alignment = audio_bytes_per_sample(format);
2435 if (alignment & 1) {
2436 // for AUDIO_FORMAT_PCM_24_BIT_PACKED (not exposed through Java).
2437 alignment = 1;
2438 }
2439 uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
2440 size_t frameSize = channelCount * audio_bytes_per_sample(format);
2441 if (channelCount > 1) {
2442 // More than 2 channels does not require stronger alignment than stereo
2443 alignment <<= 1;
2444 }
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07002445 if (((uintptr_t)sharedBuffer->unsecurePointer() & (alignment - 1)) != 0) {
Eric Laurent21da6472017-11-09 16:29:26 -08002446 ALOGE("Invalid buffer alignment: address %p, channel count %u",
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07002447 sharedBuffer->unsecurePointer(), channelCount);
Eric Laurent21da6472017-11-09 16:29:26 -08002448 lStatus = BAD_VALUE;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002449 goto Exit;
2450 }
Eric Laurent21da6472017-11-09 16:29:26 -08002451
2452 // When initializing a shared buffer AudioTrack via constructors,
2453 // there's no frameCount parameter.
2454 // But when initializing a shared buffer AudioTrack via set(),
2455 // there _is_ a frameCount parameter. We silently ignore it.
2456 frameCount = sharedBuffer->size() / frameSize;
2457 } else {
2458 size_t minFrameCount = 0;
2459 // For fast tracks we try to respect the application's request for notifications per buffer.
2460 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
2461 if (notificationsPerBuffer > 0) {
2462 // Avoid possible arithmetic overflow during multiplication.
2463 if (notificationsPerBuffer > SIZE_MAX / mFrameCount) {
2464 ALOGE("Requested notificationPerBuffer=%u ignored for HAL frameCount=%zu",
2465 notificationsPerBuffer, mFrameCount);
2466 } else {
2467 minFrameCount = mFrameCount * notificationsPerBuffer;
2468 }
2469 }
2470 } else {
2471 // For normal PCM streaming tracks, update minimum frame count.
2472 // Buffer depth is forced to be at least 2 x the normal mixer frame count and
2473 // cover audio hardware latency.
2474 // This is probably too conservative, but legacy application code may depend on it.
2475 // If you change this calculation, also review the start threshold which is related.
2476 uint32_t latencyMs = latency_l();
2477 if (latencyMs == 0) {
2478 ALOGE("Error when retrieving output stream latency");
2479 lStatus = UNKNOWN_ERROR;
2480 goto Exit;
2481 }
2482
2483 minFrameCount = AudioSystem::calculateMinFrameCount(latencyMs, mNormalFrameCount,
2484 mSampleRate, sampleRate, speed /*, 0 mNotificationsPerBufferReq*/);
2485
Eric Laurent81784c32012-11-19 14:55:58 -08002486 }
Eric Laurent21da6472017-11-09 16:29:26 -08002487 if (frameCount < minFrameCount) {
Eric Laurent81784c32012-11-19 14:55:58 -08002488 frameCount = minFrameCount;
2489 }
Eric Laurent81784c32012-11-19 14:55:58 -08002490 }
Eric Laurent21da6472017-11-09 16:29:26 -08002491
2492 // Make sure that application is notified with sufficient margin before underrun.
2493 // The client can divide the AudioTrack buffer into sub-buffers,
2494 // and expresses its desire to server as the notification frame count.
2495 if (sharedBuffer == 0 && audio_is_linear_pcm(format)) {
2496 size_t maxNotificationFrames;
2497 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
2498 // notify every HAL buffer, regardless of the size of the track buffer
2499 maxNotificationFrames = mFrameCount;
2500 } else {
Andy Hungfa117802019-04-12 13:50:39 -07002501 // Triple buffer the notification period for a triple buffered mixer period;
2502 // otherwise, double buffering for the notification period is fine.
2503 //
2504 // TODO: This should be moved to AudioTrack to modify the notification period
2505 // on AudioTrack::setBufferSizeInFrames() changes.
2506 const int nBuffering =
2507 (uint64_t{frameCount} * mSampleRate)
2508 / (uint64_t{mNormalFrameCount} * sampleRate) == 3 ? 3 : 2;
2509
Eric Laurent21da6472017-11-09 16:29:26 -08002510 maxNotificationFrames = frameCount / nBuffering;
2511 // If client requested a fast track but this was denied, then use the smaller maximum.
2512 if (requestedFlags & AUDIO_OUTPUT_FLAG_FAST) {
2513 size_t maxNotificationFramesFastDenied = FMS_20 * sampleRate / 1000;
2514 if (maxNotificationFrames > maxNotificationFramesFastDenied) {
2515 maxNotificationFrames = maxNotificationFramesFastDenied;
2516 }
2517 }
2518 }
2519 if (notificationFrameCount == 0 || notificationFrameCount > maxNotificationFrames) {
2520 if (notificationFrameCount == 0) {
2521 ALOGD("Client defaulted notificationFrames to %zu for frameCount %zu",
2522 maxNotificationFrames, frameCount);
2523 } else {
2524 ALOGW("Client adjusted notificationFrames from %zu to %zu for frameCount %zu",
2525 notificationFrameCount, maxNotificationFrames, frameCount);
2526 }
2527 notificationFrameCount = maxNotificationFrames;
2528 }
2529 }
2530
Glenn Kasten74935e42013-12-19 08:56:45 -08002531 *pFrameCount = frameCount;
Eric Laurent21da6472017-11-09 16:29:26 -08002532 *pNotificationFrameCount = notificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08002533
Glenn Kastenc3df8382014-03-13 15:05:25 -07002534 switch (mType) {
jiabinc658e452022-10-21 20:52:21 +00002535 case BIT_PERFECT:
2536 if (isBitPerfect) {
2537 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
2538 ALOGE("%s, bad parameter when request streaming bit-perfect, sampleRate=%u, "
2539 "format=%#x, channelMask=%#x, mSampleRate=%u, mFormat=%#x, mChannelMask=%#x",
2540 __func__, sampleRate, format, channelMask, mSampleRate, mFormat,
2541 mChannelMask);
2542 lStatus = BAD_VALUE;
2543 goto Exit;
2544 }
2545 }
2546 break;
Glenn Kastenc3df8382014-03-13 15:05:25 -07002547
2548 case DIRECT:
Phil Burkfdb3c072016-02-09 10:47:02 -08002549 if (audio_is_linear_pcm(format)) { // TODO maybe use audio_has_proportional_frames()?
Eric Laurent81784c32012-11-19 14:55:58 -08002550 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002551 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
2552 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08002553 sampleRate, format, channelMask, mOutput, mFormat);
2554 lStatus = BAD_VALUE;
2555 goto Exit;
2556 }
2557 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002558 break;
2559
2560 case OFFLOAD:
Eric Laurentbfb1b832013-01-07 09:53:42 -08002561 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002562 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
2563 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002564 sampleRate, format, channelMask, mOutput, mFormat);
2565 lStatus = BAD_VALUE;
2566 goto Exit;
2567 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002568 break;
2569
2570 default:
Glenn Kasten993fa062014-05-02 11:14:34 -07002571 if (!audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002572 ALOGE("createTrack_l() Bad parameter: format %#x \""
2573 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002574 format, mOutput, mFormat);
2575 lStatus = BAD_VALUE;
2576 goto Exit;
2577 }
Andy Hungcd044842014-08-07 11:04:34 -07002578 if (sampleRate > mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Eric Laurent81784c32012-11-19 14:55:58 -08002579 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
2580 lStatus = BAD_VALUE;
2581 goto Exit;
2582 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002583 break;
2584
Eric Laurent81784c32012-11-19 14:55:58 -08002585 }
2586
2587 lStatus = initCheck();
2588 if (lStatus != NO_ERROR) {
Glenn Kasten15e57982013-09-24 11:52:37 -07002589 ALOGE("createTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08002590 goto Exit;
2591 }
2592
2593 { // scope for mLock
2594 Mutex::Autolock _l(mLock);
2595
2596 // all tracks in same audio session must share the same routing strategy otherwise
2597 // conflicts will happen when tracks are moved from one output to another by audio policy
2598 // manager
Eric Laurentd66d7a12021-07-13 13:35:32 +02002599 product_strategy_t strategy = getStrategyForStream(streamType);
Eric Laurent81784c32012-11-19 14:55:58 -08002600 for (size_t i = 0; i < mTracks.size(); ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07002601 sp<IAfTrack> t = mTracks[i];
Eric Laurent83b88082014-06-20 18:31:16 -07002602 if (t != 0 && t->isExternalTrack()) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02002603 product_strategy_t actual = getStrategyForStream(t->streamType());
Eric Laurent81784c32012-11-19 14:55:58 -08002604 if (sessionId == t->sessionId() && strategy != actual) {
2605 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
2606 strategy, actual);
2607 lStatus = BAD_VALUE;
2608 goto Exit;
2609 }
2610 }
2611 }
2612
yucliuc9c49cd2020-07-13 16:25:21 -07002613 // Set DIRECT flag if current thread is DirectOutputThread. This can
2614 // happen when the playback is rerouted to direct output thread by
2615 // dynamic audio policy.
2616 // Do NOT report the flag changes back to client, since the client
2617 // doesn't explicitly request a direct flag.
2618 audio_output_flags_t trackFlags = *flags;
2619 if (mType == DIRECT) {
2620 trackFlags = static_cast<audio_output_flags_t>(trackFlags | AUDIO_OUTPUT_FLAG_DIRECT);
2621 }
2622
Andy Hung8d31fd22023-06-26 19:20:57 -07002623 track = IAfTrack::create(this, client, streamType, attr, sampleRate, format,
Andy Hung8fe68032017-06-05 16:17:51 -07002624 channelMask, frameCount,
2625 nullptr /* buffer */, (size_t)0 /* bufferSize */, sharedBuffer,
Svet Ganov33761132021-05-13 22:51:08 +00002626 sessionId, creatorPid, attributionSource, trackFlags,
Andy Hung8d31fd22023-06-26 19:20:57 -07002627 IAfTrackBase::TYPE_DEFAULT, portId, SIZE_MAX /*frameCountToBeReady*/,
jiabinc658e452022-10-21 20:52:21 +00002628 speed, isSpatialized, isBitPerfect);
Glenn Kasten03003332013-08-06 15:40:54 -07002629
Glenn Kasten03003332013-08-06 15:40:54 -07002630 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
2631 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08002632 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08002633 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08002634 goto Exit;
2635 }
2636 mTracks.add(track);
jiabinf6eb4c32020-02-25 14:06:25 -08002637 {
2638 Mutex::Autolock _atCbL(mAudioTrackCbLock);
2639 if (callback.get() != nullptr) {
jiabin18a4b1c2020-09-17 11:40:42 -07002640 mAudioTrackCallbacks.emplace(track, callback);
jiabinf6eb4c32020-02-25 14:06:25 -08002641 }
2642 }
Eric Laurent81784c32012-11-19 14:55:58 -08002643
Andy Hung116bc262023-06-20 18:56:17 -07002644 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08002645 if (chain != 0) {
2646 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
2647 track->setMainBuffer(chain->inBuffer());
Eric Laurentd66d7a12021-07-13 13:35:32 +02002648 chain->setStrategy(getStrategyForStream(track->streamType()));
Eric Laurent81784c32012-11-19 14:55:58 -08002649 chain->incTrackCnt();
2650 }
2651
Eric Laurent05067782016-06-01 18:27:28 -07002652 if ((*flags & AUDIO_OUTPUT_FLAG_FAST) && (tid != -1)) {
Eric Laurent81784c32012-11-19 14:55:58 -08002653 pid_t callingPid = IPCThreadState::self()->getCallingPid();
2654 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
2655 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07002656 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08002657 }
2658 }
2659
2660 lStatus = NO_ERROR;
2661
2662Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07002663 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08002664 return track;
2665}
2666
Andy Hung1bc088a2018-02-09 15:57:31 -08002667template<typename T>
Andy Hungee58e4a2023-07-07 13:47:37 -07002668ssize_t PlaybackThread::Tracks<T>::remove(const sp<T>& track)
Andy Hung1bc088a2018-02-09 15:57:31 -08002669{
Andy Hungc0691382018-09-12 18:01:57 -07002670 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08002671 const ssize_t index = mTracks.remove(track);
2672 if (index >= 0) {
Andy Hungc0691382018-09-12 18:01:57 -07002673 if (mSaveDeletedTrackIds) {
Andy Hung1bc088a2018-02-09 15:57:31 -08002674 // We can't directly access mAudioMixer since the caller may be outside of threadLoop.
Andy Hungc0691382018-09-12 18:01:57 -07002675 // Instead, we add to mDeletedTrackIds which is solely used for mAudioMixer update,
Andy Hung1bc088a2018-02-09 15:57:31 -08002676 // to be handled when MixerThread::prepareTracks_l() next changes mAudioMixer.
Andy Hungc0691382018-09-12 18:01:57 -07002677 mDeletedTrackIds.emplace(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08002678 }
Andy Hung1bc088a2018-02-09 15:57:31 -08002679 }
2680 return index;
2681}
2682
Andy Hungee58e4a2023-07-07 13:47:37 -07002683uint32_t PlaybackThread::correctLatency_l(uint32_t latency) const
Eric Laurent81784c32012-11-19 14:55:58 -08002684{
2685 return latency;
2686}
2687
Andy Hungee58e4a2023-07-07 13:47:37 -07002688uint32_t PlaybackThread::latency() const
Eric Laurent81784c32012-11-19 14:55:58 -08002689{
2690 Mutex::Autolock _l(mLock);
2691 return latency_l();
2692}
Andy Hungee58e4a2023-07-07 13:47:37 -07002693uint32_t PlaybackThread::latency_l() const
Eric Laurent81784c32012-11-19 14:55:58 -08002694{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002695 uint32_t latency;
2696 if (initCheck() == NO_ERROR && mOutput->stream->getLatency(&latency) == OK) {
2697 return correctLatency_l(latency);
Eric Laurent81784c32012-11-19 14:55:58 -08002698 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002699 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002700}
2701
Andy Hungee58e4a2023-07-07 13:47:37 -07002702void PlaybackThread::setMasterVolume(float value)
Eric Laurent81784c32012-11-19 14:55:58 -08002703{
2704 Mutex::Autolock _l(mLock);
2705 // Don't apply master volume in SW if our HAL can do it for us.
2706 if (mOutput && mOutput->audioHwDev &&
2707 mOutput->audioHwDev->canSetMasterVolume()) {
2708 mMasterVolume = 1.0;
2709 } else {
2710 mMasterVolume = value;
2711 }
2712}
2713
Andy Hungee58e4a2023-07-07 13:47:37 -07002714void PlaybackThread::setMasterBalance(float balance)
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01002715{
2716 mMasterBalance.store(balance);
2717}
2718
Andy Hungee58e4a2023-07-07 13:47:37 -07002719void PlaybackThread::setMasterMute(bool muted)
Eric Laurent81784c32012-11-19 14:55:58 -08002720{
Eric Laurent6acd1d42017-01-04 14:23:29 -08002721 if (isDuplicating()) {
2722 return;
2723 }
Eric Laurent81784c32012-11-19 14:55:58 -08002724 Mutex::Autolock _l(mLock);
2725 // Don't apply master mute in SW if our HAL can do it for us.
2726 if (mOutput && mOutput->audioHwDev &&
2727 mOutput->audioHwDev->canSetMasterMute()) {
2728 mMasterMute = false;
2729 } else {
2730 mMasterMute = muted;
2731 }
2732}
2733
Andy Hungee58e4a2023-07-07 13:47:37 -07002734void PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
Eric Laurent81784c32012-11-19 14:55:58 -08002735{
2736 Mutex::Autolock _l(mLock);
2737 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002738 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002739}
2740
Andy Hungee58e4a2023-07-07 13:47:37 -07002741void PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
Eric Laurent81784c32012-11-19 14:55:58 -08002742{
2743 Mutex::Autolock _l(mLock);
2744 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002745 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002746}
2747
Andy Hungee58e4a2023-07-07 13:47:37 -07002748float PlaybackThread::streamVolume(audio_stream_type_t stream) const
Eric Laurent81784c32012-11-19 14:55:58 -08002749{
2750 Mutex::Autolock _l(mLock);
2751 return mStreamTypes[stream].volume;
2752}
2753
Andy Hungee58e4a2023-07-07 13:47:37 -07002754void PlaybackThread::setVolumeForOutput_l(float left, float right) const
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09002755{
2756 mOutput->stream->setVolume(left, right);
2757}
2758
Eric Laurent81784c32012-11-19 14:55:58 -08002759// addTrack_l() must be called with ThreadBase::mLock held
Andy Hungee58e4a2023-07-07 13:47:37 -07002760status_t PlaybackThread::addTrack_l(const sp<IAfTrack>& track)
Andy Hung920f6572022-10-06 12:09:49 -07002761NO_THREAD_SAFETY_ANALYSIS // release and re-acquire mLock
Eric Laurent81784c32012-11-19 14:55:58 -08002762{
2763 status_t status = ALREADY_EXISTS;
2764
Eric Laurent81784c32012-11-19 14:55:58 -08002765 if (mActiveTracks.indexOf(track) < 0) {
2766 // the track is newly added, make sure it fills up all its
2767 // buffers before playing. This is to ensure the client will
2768 // effectively get the latency it requested.
Eric Laurent83b88082014-06-20 18:31:16 -07002769 if (track->isExternalTrack()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07002770 IAfTrackBase::track_state state = track->state();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002771 mLock.unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002772 status = AudioSystem::startOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002773 mLock.lock();
2774 // abort track was stopped/paused while we released the lock
Andy Hung8d31fd22023-06-26 19:20:57 -07002775 if (state != track->state()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002776 if (status == NO_ERROR) {
2777 mLock.unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002778 AudioSystem::stopOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002779 mLock.lock();
2780 }
2781 return INVALID_OPERATION;
2782 }
2783 // abort if start is rejected by audio policy manager
2784 if (status != NO_ERROR) {
jiabina84c3d32022-12-02 18:59:55 +00002785 // Do not replace the error if it is DEAD_OBJECT. When this happens, it indicates
2786 // current playback thread is reopened, which may happen when clients set preferred
2787 // mixer configuration. Returning DEAD_OBJECT will make the client restore track
2788 // immediately.
2789 return status == DEAD_OBJECT ? status : PERMISSION_DENIED;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002790 }
2791#ifdef ADD_BATTERY_DATA
2792 // to track the speaker usage
2793 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
2794#endif
Eric Laurent09f1ed22019-04-24 17:45:17 -07002795 sendIoConfigEvent_l(AUDIO_CLIENT_STARTED, track->creatorPid(), track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002796 }
2797
Eric Laurent51716182016-02-29 18:00:56 -08002798 // set retry count for buffer fill
2799 if (track->isOffloaded()) {
Eric Laurente93cc032016-05-05 10:15:10 -07002800 if (track->isStopping_1()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07002801 track->retryCount() = kMaxTrackStopRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07002802 } else {
Andy Hung8d31fd22023-06-26 19:20:57 -07002803 track->retryCount() = kMaxTrackStartupRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07002804 }
Andy Hung8d31fd22023-06-26 19:20:57 -07002805 track->fillingStatus() = mStandby ? IAfTrack::FS_FILLING : IAfTrack::FS_FILLED;
Eric Laurent51716182016-02-29 18:00:56 -08002806 } else {
Andy Hung8d31fd22023-06-26 19:20:57 -07002807 track->retryCount() = kMaxTrackStartupRetries;
2808 track->fillingStatus() =
2809 track->sharedBuffer() != 0 ? IAfTrack::FS_FILLED : IAfTrack::FS_FILLING;
Eric Laurent51716182016-02-29 18:00:56 -08002810 }
2811
Andy Hung116bc262023-06-20 18:56:17 -07002812 sp<IAfEffectChain> chain = getEffectChain_l(track->sessionId());
jiabineb3bda02020-06-30 14:07:03 -07002813 if (mHapticChannelMask != AUDIO_CHANNEL_NONE
2814 && ((track->channelMask() & AUDIO_CHANNEL_HAPTIC_ALL) != AUDIO_CHANNEL_NONE
2815 || (chain != nullptr && chain->containsHapticGeneratingEffect_l()))) {
jiabin57303cc2018-12-18 15:45:57 -08002816 // Unlock due to VibratorService will lock for this call and will
2817 // call Tracks.mute/unmute which also require thread's lock.
2818 mLock.unlock();
Simon Bowden62823412022-10-17 14:52:26 +00002819 const os::HapticScale intensity = AudioFlinger::onExternalVibrationStart(
jiabin57303cc2018-12-18 15:45:57 -08002820 track->getExternalVibration());
Lais Andradebc3f37a2021-07-02 00:13:19 +01002821 std::optional<media::AudioVibratorInfo> vibratorInfo;
2822 {
2823 // TODO(b/184194780): Use the vibrator information from the vibrator that will be
2824 // used to play this track.
Andy Hung583043b2023-07-17 17:05:00 -07002825 Mutex::Autolock _l(mAfThreadCallback->mutex());
2826 vibratorInfo = std::move(mAfThreadCallback->getDefaultVibratorInfo_l());
Lais Andradebc3f37a2021-07-02 00:13:19 +01002827 }
jiabin57303cc2018-12-18 15:45:57 -08002828 mLock.lock();
Simon Bowden62823412022-10-17 14:52:26 +00002829 track->setHapticIntensity(intensity);
Lais Andradebc3f37a2021-07-02 00:13:19 +01002830 if (vibratorInfo) {
2831 track->setHapticMaxAmplitude(vibratorInfo->maxAmplitude);
2832 }
2833
jiabin57303cc2018-12-18 15:45:57 -08002834 // Haptic playback should be enabled by vibrator service.
2835 if (track->getHapticPlaybackEnabled()) {
2836 // Disable haptic playback of all active track to ensure only
2837 // one track playing haptic if current track should play haptic.
2838 for (const auto &t : mActiveTracks) {
2839 t->setHapticPlaybackEnabled(false);
2840 }
jiabin245cdd92018-12-07 17:55:15 -08002841 }
jiabine70bc7f2020-06-30 22:07:55 -07002842
2843 // Set haptic intensity for effect
2844 if (chain != nullptr) {
2845 chain->setHapticIntensity_l(track->id(), intensity);
2846 }
jiabin245cdd92018-12-07 17:55:15 -08002847 }
2848
Andy Hung8d31fd22023-06-26 19:20:57 -07002849 track->setResetDone(false);
Andy Hung59de4262021-06-14 10:53:54 -07002850 track->resetPresentationComplete();
Eric Laurent81784c32012-11-19 14:55:58 -08002851 mActiveTracks.add(track);
Eric Laurentd0107bc2013-06-11 14:38:48 -07002852 if (chain != 0) {
2853 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
2854 track->sessionId());
2855 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08002856 }
2857
Andy Hungc2b11cb2020-04-22 09:04:01 -07002858 track->logBeginInterval(patchSinksToString(&mPatch)); // log to MediaMetrics
Eric Laurent81784c32012-11-19 14:55:58 -08002859 status = NO_ERROR;
2860 }
2861
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08002862 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002863 return status;
2864}
2865
Andy Hungee58e4a2023-07-07 13:47:37 -07002866bool PlaybackThread::destroyTrack_l(const sp<IAfTrack>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002867{
Eric Laurentbfb1b832013-01-07 09:53:42 -08002868 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08002869 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002870 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
Andy Hung8d31fd22023-06-26 19:20:57 -07002871 track->setState(IAfTrackBase::STOPPED);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002872 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08002873 removeTrack_l(track);
Eric Laurentab5cdba2014-06-09 17:22:27 -07002874 } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) {
Andy Hung916987e2023-03-20 19:08:16 -07002875 if (track->isPausePending()) {
2876 track->pauseAck();
2877 }
Andy Hung8d31fd22023-06-26 19:20:57 -07002878 track->setState(IAfTrackBase::STOPPING_1);
Eric Laurent81784c32012-11-19 14:55:58 -08002879 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002880
2881 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08002882}
2883
Andy Hungee58e4a2023-07-07 13:47:37 -07002884void PlaybackThread::removeTrack_l(const sp<IAfTrack>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002885{
2886 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Andy Hung2148bf02016-11-28 19:01:02 -08002887
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002888 String8 result;
2889 track->appendDump(result, false /* active */);
2890 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.string());
Andy Hung2148bf02016-11-28 19:01:02 -08002891
Eric Laurent81784c32012-11-19 14:55:58 -08002892 mTracks.remove(track);
jiabin18a4b1c2020-09-17 11:40:42 -07002893 {
2894 Mutex::Autolock _atCbL(mAudioTrackCbLock);
2895 mAudioTrackCallbacks.erase(track);
2896 }
Eric Laurent81784c32012-11-19 14:55:58 -08002897 if (track->isFastTrack()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07002898 int index = track->fastIndex();
Glenn Kastendc2c50b2016-04-21 08:13:14 -07002899 ALOG_ASSERT(0 < index && index < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08002900 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
2901 mFastTrackAvailMask |= 1 << index;
2902 // redundant as track is about to be destroyed, for dumpsys only
Andy Hung8d31fd22023-06-26 19:20:57 -07002903 track->fastIndex() = -1;
Eric Laurent81784c32012-11-19 14:55:58 -08002904 }
Andy Hung116bc262023-06-20 18:56:17 -07002905 sp<IAfEffectChain> chain = getEffectChain_l(track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08002906 if (chain != 0) {
2907 chain->decTrackCnt();
2908 }
2909}
2910
Andy Hungee58e4a2023-07-07 13:47:37 -07002911String8 PlaybackThread::getParameters(const String8& keys)
Eric Laurent81784c32012-11-19 14:55:58 -08002912{
Eric Laurent81784c32012-11-19 14:55:58 -08002913 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002914 String8 out_s8;
2915 if (initCheck() == NO_ERROR && mOutput->stream->getParameters(keys, &out_s8) == OK) {
2916 return out_s8;
Eric Laurent81784c32012-11-19 14:55:58 -08002917 }
Andy Hung920f6572022-10-06 12:09:49 -07002918 return {};
Eric Laurent81784c32012-11-19 14:55:58 -08002919}
2920
Andy Hungee58e4a2023-07-07 13:47:37 -07002921status_t DirectOutputThread::selectPresentation(int presentationId, int programId) {
Mikhail Naganovac917ac2018-11-28 14:03:52 -08002922 Mutex::Autolock _l(mLock);
Jasmine Chaeaa10e42021-05-11 10:11:14 +08002923 if (!isStreamInitialized()) {
Mikhail Naganovac917ac2018-11-28 14:03:52 -08002924 return NO_INIT;
2925 }
2926 return mOutput->stream->selectPresentation(presentationId, programId);
2927}
2928
Andy Hungee58e4a2023-07-07 13:47:37 -07002929void PlaybackThread::ioConfigChanged(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -07002930 audio_port_handle_t portId) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002931 ALOGV("PlaybackThread::ioConfigChanged, thread %p, event %d", this, event);
Mikhail Naganov88536df2021-07-26 17:30:29 -07002932 sp<AudioIoDescriptor> desc;
2933 const struct audio_patch patch = isMsdDevice() ? mDownStreamPatch : mPatch;
Eric Laurent81784c32012-11-19 14:55:58 -08002934 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002935 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07002936 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07002937 case AUDIO_OUTPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07002938 desc = sp<AudioIoDescriptor>::make(mId, patch, false /*isInput*/,
2939 mSampleRate, mFormat, mChannelMask,
2940 // FIXME AudioFlinger::frameCount(audio_io_handle_t) instead of mNormalFrameCount?
2941 mNormalFrameCount, mFrameCount, latency_l());
Eric Laurent81784c32012-11-19 14:55:58 -08002942 break;
Eric Laurent09f1ed22019-04-24 17:45:17 -07002943 case AUDIO_CLIENT_STARTED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07002944 desc = sp<AudioIoDescriptor>::make(mId, patch, portId);
Eric Laurent09f1ed22019-04-24 17:45:17 -07002945 break;
Eric Laurent73e26b62015-04-27 16:55:58 -07002946 case AUDIO_OUTPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08002947 default:
Mikhail Naganov88536df2021-07-26 17:30:29 -07002948 desc = sp<AudioIoDescriptor>::make(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08002949 break;
2950 }
Andy Hung583043b2023-07-17 17:05:00 -07002951 mAfThreadCallback->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08002952}
2953
Andy Hungee58e4a2023-07-07 13:47:37 -07002954void PlaybackThread::onWriteReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002955{
Eric Laurent3b4529e2013-09-05 18:09:19 -07002956 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002957}
2958
Andy Hungee58e4a2023-07-07 13:47:37 -07002959void PlaybackThread::onDrainReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002960{
Eric Laurent3b4529e2013-09-05 18:09:19 -07002961 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002962}
2963
Andy Hungee58e4a2023-07-07 13:47:37 -07002964void PlaybackThread::onError()
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002965{
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002966 mCallbackThread->setAsyncError();
2967}
2968
Andy Hungee58e4a2023-07-07 13:47:37 -07002969void PlaybackThread::onCodecFormatChanged(
jiabinf6eb4c32020-02-25 14:06:25 -08002970 const std::basic_string<uint8_t>& metadataBs)
2971{
Andy Hungee58e4a2023-07-07 13:47:37 -07002972 const auto weakPointerThis = wp<PlaybackThread>::fromExisting(this);
Kuowei Li9e2f6162022-11-23 16:25:26 +08002973 std::thread([this, metadataBs, weakPointerThis]() {
Andy Hungee58e4a2023-07-07 13:47:37 -07002974 const sp<PlaybackThread> playbackThread = weakPointerThis.promote();
Kuowei Li9e2f6162022-11-23 16:25:26 +08002975 if (playbackThread == nullptr) {
2976 ALOGW("PlaybackThread was destroyed, skip codec format change event");
2977 return;
2978 }
2979
jiabinf6eb4c32020-02-25 14:06:25 -08002980 audio_utils::metadata::Data metadata =
2981 audio_utils::metadata::dataFromByteString(metadataBs);
2982 if (metadata.empty()) {
2983 ALOGW("Can not transform the buffer to audio metadata, %s, %d",
2984 reinterpret_cast<char*>(const_cast<uint8_t*>(metadataBs.data())),
2985 (int)metadataBs.size());
2986 return;
2987 }
2988
2989 audio_utils::metadata::ByteString metaDataStr =
2990 audio_utils::metadata::byteStringFromData(metadata);
2991 std::vector metadataVec(metaDataStr.begin(), metaDataStr.end());
2992 Mutex::Autolock _l(mAudioTrackCbLock);
jiabin18a4b1c2020-09-17 11:40:42 -07002993 for (const auto& callbackPair : mAudioTrackCallbacks) {
2994 callbackPair.second->onCodecFormatChanged(metadataVec);
jiabinf6eb4c32020-02-25 14:06:25 -08002995 }
2996 }).detach();
2997}
2998
Andy Hungee58e4a2023-07-07 13:47:37 -07002999void PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08003000{
3001 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003002 // reject out of sequence requests
3003 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
3004 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003005 mWaitWorkCV.signal();
3006 }
3007}
3008
Andy Hungee58e4a2023-07-07 13:47:37 -07003009void PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08003010{
3011 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003012 // reject out of sequence requests
3013 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
Andy Hungf3234512018-07-03 14:51:47 -07003014 // Register discontinuity when HW drain is completed because that can cause
3015 // the timestamp frame position to reset to 0 for direct and offload threads.
3016 // (Out of sequence requests are ignored, since the discontinuity would be handled
3017 // elsewhere, e.g. in flush).
Dean Wheatley12473e92021-03-18 23:00:55 +11003018 mTimestampVerifier.discontinuity(mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003019 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003020 mWaitWorkCV.signal();
3021 }
3022}
3023
Andy Hungee58e4a2023-07-07 13:47:37 -07003024void PlaybackThread::readOutputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08003025{
Glenn Kastenadad3d72014-02-21 14:51:43 -08003026 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Mikhail Naganov560637e2021-03-31 22:40:13 +00003027 const audio_config_base_t audioConfig = mOutput->getAudioProperties();
3028 mSampleRate = audioConfig.sample_rate;
3029 mChannelMask = audioConfig.channel_mask;
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003030 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08003031 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003032 }
Andy Hungee58e4a2023-07-07 13:47:37 -07003033 if (hasMixer() && !AudioFlinger::isValidPcmSinkChannelMask(mChannelMask)) {
Andy Hung9a592762014-07-21 21:56:01 -07003034 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output",
3035 mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003036 }
Eric Laurentf1f22e72021-07-13 14:04:14 +02003037
3038 if (mMixerChannelMask == AUDIO_CHANNEL_NONE) {
3039 mMixerChannelMask = mChannelMask;
3040 }
3041
Andy Hunge5412692014-05-16 11:25:07 -07003042 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01003043 mBalance.setChannelMask(mChannelMask);
Phil Burkca5e6142015-07-14 09:42:29 -07003044
Eric Laurentf1f22e72021-07-13 14:04:14 +02003045 uint32_t mixerChannelCount = audio_channel_count_from_out_mask(mMixerChannelMask);
3046
Phil Burkca5e6142015-07-14 09:42:29 -07003047 // Get actual HAL format.
Mikhail Naganov560637e2021-03-31 22:40:13 +00003048 status_t result = mOutput->stream->getAudioProperties(nullptr, nullptr, &mHALFormat);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003049 LOG_ALWAYS_FATAL_IF(result != OK, "Error when retrieving output stream format: %d", result);
Phil Burkca5e6142015-07-14 09:42:29 -07003050 // Get format from the shim, which will be different than the HAL format
3051 // if playing compressed audio over HDMI passthrough.
Mikhail Naganov560637e2021-03-31 22:40:13 +00003052 mFormat = audioConfig.format;
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003053 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08003054 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003055 }
Andy Hungee58e4a2023-07-07 13:47:37 -07003056 if (hasMixer() && !AudioFlinger::isValidPcmSinkFormat(mFormat)) {
Andy Hung6146c082014-03-18 11:56:15 -07003057 LOG_FATAL("HAL format %#x not supported for mixed output",
3058 mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003059 }
Phil Burk062e67a2015-02-11 13:40:50 -08003060 mFrameSize = mOutput->getFrameSize();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003061 result = mOutput->stream->getBufferSize(&mBufferSize);
3062 LOG_ALWAYS_FATAL_IF(result != OK,
3063 "Error when retrieving output stream buffer size: %d", result);
Glenn Kasten70949c42013-08-06 07:40:12 -07003064 mFrameCount = mBufferSize / mFrameSize;
Eric Laurentb3f315a2021-07-13 15:09:05 +02003065 if (hasMixer() && (mFrameCount & 15)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003066 ALOGW("HAL output buffer size is %zu frames but AudioMixer requires multiples of 16 frames",
Eric Laurent81784c32012-11-19 14:55:58 -08003067 mFrameCount);
3068 }
3069
Eric Laurentd1f69b02014-12-15 14:33:13 -08003070 mHwSupportsPause = false;
3071 if (mOutput->flags & AUDIO_OUTPUT_FLAG_DIRECT) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003072 bool supportsPause = false, supportsResume = false;
3073 if (mOutput->stream->supportsPauseAndResume(&supportsPause, &supportsResume) == OK) {
3074 if (supportsPause && supportsResume) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08003075 mHwSupportsPause = true;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003076 } else if (supportsPause) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08003077 ALOGW("direct output implements pause but not resume");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003078 } else if (supportsResume) {
3079 ALOGW("direct output implements resume but not pause");
Eric Laurentd1f69b02014-12-15 14:33:13 -08003080 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08003081 }
3082 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07003083 if (!mHwSupportsPause && mOutput->flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) {
3084 LOG_ALWAYS_FATAL("HW_AV_SYNC requested but HAL does not implement pause and resume");
3085 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08003086
Andy Hungfbfc3952015-01-15 13:33:51 -08003087 if (mType == DUPLICATING && mMixerBufferEnabled && mEffectBufferEnabled) {
3088 // For best precision, we use float instead of the associated output
3089 // device format (typically PCM 16 bit).
3090
3091 mFormat = AUDIO_FORMAT_PCM_FLOAT;
3092 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
3093 mBufferSize = mFrameSize * mFrameCount;
3094
3095 // TODO: We currently use the associated output device channel mask and sample rate.
3096 // (1) Perhaps use the ORed channel mask of all downstream MixerThreads
3097 // (if a valid mask) to avoid premature downmix.
3098 // (2) Perhaps use the maximum sample rate of all downstream MixerThreads
3099 // instead of the output device sample rate to avoid loss of high frequency information.
3100 // This may need to be updated as MixerThread/OutputTracks are added and not here.
3101 }
3102
Andy Hung09a50072014-02-27 14:30:47 -08003103 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08003104 double multiplier = 1.0;
Andy Hungd3639922022-04-28 18:00:49 -07003105 // Note: mType == SPATIALIZER does not support FastMixer.
Eric Laurent81784c32012-11-19 14:55:58 -08003106 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
3107 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08003108 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
3109 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Haynes Mathew George227a14b2016-05-09 12:45:48 -07003110
Eric Laurent81784c32012-11-19 14:55:58 -08003111 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
3112 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
3113 maxNormalFrameCount = maxNormalFrameCount & ~15;
3114 if (maxNormalFrameCount < minNormalFrameCount) {
3115 maxNormalFrameCount = minNormalFrameCount;
3116 }
3117 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
3118 if (multiplier <= 1.0) {
3119 multiplier = 1.0;
3120 } else if (multiplier <= 2.0) {
3121 if (2 * mFrameCount <= maxNormalFrameCount) {
3122 multiplier = 2.0;
3123 } else {
3124 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
3125 }
3126 } else {
Haynes Mathew George227a14b2016-05-09 12:45:48 -07003127 multiplier = floor(multiplier);
Eric Laurent81784c32012-11-19 14:55:58 -08003128 }
3129 }
3130 mNormalFrameCount = multiplier * mFrameCount;
3131 // round up to nearest 16 frames to satisfy AudioMixer
Eric Laurentb3f315a2021-07-13 15:09:05 +02003132 if (hasMixer()) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07003133 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
3134 }
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003135 ALOGI("HAL output buffer size %zu frames, normal sink buffer size %zu frames", mFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08003136 mNormalFrameCount);
3137
Andy Hung08fb1742015-05-31 23:22:10 -07003138 // Check if we want to throttle the processing to no more than 2x normal rate
3139 mThreadThrottle = property_get_bool("af.thread.throttle", true /* default_value */);
Andy Hung40eb1a12015-06-18 13:42:02 -07003140 mThreadThrottleTimeMs = 0;
3141 mThreadThrottleEndMs = 0;
Andy Hung08fb1742015-05-31 23:22:10 -07003142 mHalfBufferMs = mNormalFrameCount * 1000 / (2 * mSampleRate);
3143
Andy Hung010a1a12014-03-13 13:57:33 -07003144 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
3145 // Originally this was int16_t[] array, need to remove legacy implications.
3146 free(mSinkBuffer);
3147 mSinkBuffer = NULL;
Eric Laurent39095982021-08-24 18:29:27 +02003148
Andy Hung5b10a202014-03-13 13:59:29 -07003149 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
3150 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
3151 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07003152 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08003153
Andy Hung69aed5f2014-02-25 17:24:40 -08003154 // We resize the mMixerBuffer according to the requirements of the sink buffer which
3155 // drives the output.
3156 free(mMixerBuffer);
3157 mMixerBuffer = NULL;
3158 if (mMixerBufferEnabled) {
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01003159 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // no longer valid: AUDIO_FORMAT_PCM_16_BIT.
Eric Laurentf1f22e72021-07-13 14:04:14 +02003160 mMixerBufferSize = mNormalFrameCount * mixerChannelCount
Andy Hung69aed5f2014-02-25 17:24:40 -08003161 * audio_bytes_per_sample(mMixerBufferFormat);
3162 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
3163 }
Andy Hung98ef9782014-03-04 14:46:50 -08003164 free(mEffectBuffer);
3165 mEffectBuffer = NULL;
3166 if (mEffectBufferEnabled) {
Andy Hung319587b2023-05-23 14:01:03 -07003167 mEffectBufferFormat = AUDIO_FORMAT_PCM_FLOAT;
Eric Laurentf1f22e72021-07-13 14:04:14 +02003168 mEffectBufferSize = mNormalFrameCount * mixerChannelCount
Andy Hung98ef9782014-03-04 14:46:50 -08003169 * audio_bytes_per_sample(mEffectBufferFormat);
3170 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
3171 }
Andy Hung69aed5f2014-02-25 17:24:40 -08003172
Eric Laurentb62d0362021-10-26 17:40:18 +02003173 if (mType == SPATIALIZER) {
3174 free(mPostSpatializerBuffer);
3175 mPostSpatializerBuffer = nullptr;
3176 mPostSpatializerBufferSize = mNormalFrameCount * mChannelCount
3177 * audio_bytes_per_sample(mEffectBufferFormat);
3178 (void)posix_memalign(&mPostSpatializerBuffer, 32, mPostSpatializerBufferSize);
3179 }
3180
Mikhail Naganov55773032020-10-01 15:08:13 -07003181 mHapticChannelMask = static_cast<audio_channel_mask_t>(mChannelMask & AUDIO_CHANNEL_HAPTIC_ALL);
3182 mChannelMask = static_cast<audio_channel_mask_t>(mChannelMask & ~mHapticChannelMask);
jiabin245cdd92018-12-07 17:55:15 -08003183 mHapticChannelCount = audio_channel_count_from_out_mask(mHapticChannelMask);
3184 mChannelCount -= mHapticChannelCount;
Eric Laurentf1f22e72021-07-13 14:04:14 +02003185 mMixerChannelMask = static_cast<audio_channel_mask_t>(mMixerChannelMask & ~mHapticChannelMask);
jiabin245cdd92018-12-07 17:55:15 -08003186
Eric Laurent81784c32012-11-19 14:55:58 -08003187 // force reconfiguration of effect chains and engines to take new buffer size and audio
3188 // parameters into account
Glenn Kastendeca2ae2014-02-07 10:25:56 -08003189 // Note that mLock is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08003190 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
3191 // matter.
3192 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
Andy Hung116bc262023-06-20 18:56:17 -07003193 Vector<sp<IAfEffectChain>> effectChains = mEffectChains;
Eric Laurent81784c32012-11-19 14:55:58 -08003194 for (size_t i = 0; i < effectChains.size(); i ++) {
Andy Hung583043b2023-07-17 17:05:00 -07003195 mAfThreadCallback->moveEffectChain_l(effectChains[i]->sessionId(),
Eric Laurent6c796322019-04-09 14:13:17 -07003196 this/* srcThread */, this/* dstThread */);
Eric Laurent81784c32012-11-19 14:55:58 -08003197 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08003198
George Burgess IV5e4d86f2020-02-18 12:55:36 -08003199 audio_output_flags_t flags = mOutput->flags;
Andy Hungcf10d742020-04-28 15:38:24 -07003200 mediametrics::LogItem item(mThreadMetrics.getMetricsId()); // TODO: method in ThreadMetrics?
Andy Hungb68f5eb2019-12-03 16:49:17 -08003201 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
3202 .set(AMEDIAMETRICS_PROP_ENCODING, formatToString(mFormat).c_str())
3203 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
3204 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
3205 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
3206 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mNormalFrameCount)
3207 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
3208 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELMASK,
3209 (int32_t)mHapticChannelMask)
3210 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELCOUNT,
3211 (int32_t)mHapticChannelCount)
3212 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_ENCODING,
3213 formatToString(mHALFormat).c_str())
3214 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_FRAMECOUNT,
3215 (int32_t)mFrameCount) // sic - added HAL
3216 ;
3217 uint32_t latencyMs;
3218 if (mOutput->stream->getLatency(&latencyMs) == NO_ERROR) {
3219 item.set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_LATENCYMS, (double)latencyMs);
3220 }
3221 item.record();
Eric Laurent81784c32012-11-19 14:55:58 -08003222}
3223
Andy Hungee58e4a2023-07-07 13:47:37 -07003224ThreadBase::MetadataUpdate PlaybackThread::updateMetadata_l()
Kevin Rocard069c2712018-03-29 19:09:14 -07003225{
Jasmine Chaeaa10e42021-05-11 10:11:14 +08003226 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
Vlad Popa7e81cea2023-01-19 16:34:16 +01003227 return {}; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -07003228 }
3229 StreamOutHalInterface::SourceMetadata metadata;
Kevin Rocard12381092018-04-11 09:19:59 -07003230 auto backInserter = std::back_inserter(metadata.tracks);
Andy Hung8d31fd22023-06-26 19:20:57 -07003231 for (const sp<IAfTrack>& track : mActiveTracks) {
Kevin Rocard069c2712018-03-29 19:09:14 -07003232 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurent49e39282022-06-24 18:42:45 +02003233 track->copyMetadataTo(backInserter);
Kevin Rocard069c2712018-03-29 19:09:14 -07003234 }
Kevin Rocard12381092018-04-11 09:19:59 -07003235 sendMetadataToBackend_l(metadata);
Vlad Popa7e81cea2023-01-19 16:34:16 +01003236 MetadataUpdate change;
3237 change.playbackMetadataUpdate = metadata.tracks;
3238 return change;
Kevin Rocard80ee2722018-04-11 15:53:48 +00003239}
Kevin Rocardc86a7f72018-04-03 09:00:09 -07003240
Andy Hungee58e4a2023-07-07 13:47:37 -07003241void PlaybackThread::sendMetadataToBackend_l(
Kevin Rocard12381092018-04-11 09:19:59 -07003242 const StreamOutHalInterface::SourceMetadata& metadata)
3243{
3244 mOutput->stream->updateSourceMetadata(metadata);
3245};
3246
Andy Hungee58e4a2023-07-07 13:47:37 -07003247status_t PlaybackThread::getRenderPosition(
Andy Hung440901d2023-06-29 21:19:25 -07003248 uint32_t* halFrames, uint32_t* dspFrames) const
Eric Laurent81784c32012-11-19 14:55:58 -08003249{
3250 if (halFrames == NULL || dspFrames == NULL) {
3251 return BAD_VALUE;
3252 }
3253 Mutex::Autolock _l(mLock);
3254 if (initCheck() != NO_ERROR) {
3255 return INVALID_OPERATION;
3256 }
Andy Hung818e7a32016-02-16 18:08:07 -08003257 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08003258 *halFrames = framesWritten;
3259
3260 if (isSuspended()) {
3261 // return an estimation of rendered frames when the output is suspended
3262 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08003263 *dspFrames = (uint32_t)
3264 (framesWritten >= (int64_t)latencyFrames ? framesWritten - latencyFrames : 0);
Eric Laurent81784c32012-11-19 14:55:58 -08003265 return NO_ERROR;
3266 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003267 status_t status;
3268 uint32_t frames;
Phil Burk062e67a2015-02-11 13:40:50 -08003269 status = mOutput->getRenderPosition(&frames);
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003270 *dspFrames = (size_t)frames;
3271 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08003272 }
3273}
3274
Andy Hungee58e4a2023-07-07 13:47:37 -07003275product_strategy_t PlaybackThread::getStrategyForSession_l(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08003276{
3277 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
3278 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
3279 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02003280 return getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurent81784c32012-11-19 14:55:58 -08003281 }
3282 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003283 sp<IAfTrack> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08003284 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02003285 return getStrategyForStream(track->streamType());
Eric Laurent81784c32012-11-19 14:55:58 -08003286 }
3287 }
Eric Laurentd66d7a12021-07-13 13:35:32 +02003288 return getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurent81784c32012-11-19 14:55:58 -08003289}
3290
3291
Andy Hungee58e4a2023-07-07 13:47:37 -07003292AudioStreamOut* PlaybackThread::getOutput() const
Eric Laurent81784c32012-11-19 14:55:58 -08003293{
3294 Mutex::Autolock _l(mLock);
3295 return mOutput;
3296}
3297
Andy Hungee58e4a2023-07-07 13:47:37 -07003298AudioStreamOut* PlaybackThread::clearOutput()
Eric Laurent81784c32012-11-19 14:55:58 -08003299{
3300 Mutex::Autolock _l(mLock);
3301 AudioStreamOut *output = mOutput;
3302 mOutput = NULL;
3303 // FIXME FastMixer might also have a raw ptr to mOutputSink;
3304 // must push a NULL and wait for ack
3305 mOutputSink.clear();
3306 mPipeSink.clear();
3307 mNormalSink.clear();
3308 return output;
3309}
3310
3311// this method must always be called either with ThreadBase mLock held or inside the thread loop
Andy Hungee58e4a2023-07-07 13:47:37 -07003312sp<StreamHalInterface> PlaybackThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08003313{
3314 if (mOutput == NULL) {
3315 return NULL;
3316 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003317 return mOutput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08003318}
3319
Andy Hungee58e4a2023-07-07 13:47:37 -07003320uint32_t PlaybackThread::activeSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08003321{
3322 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
3323}
3324
Andy Hungee58e4a2023-07-07 13:47:37 -07003325status_t PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
Eric Laurent81784c32012-11-19 14:55:58 -08003326{
3327 if (!isValidSyncEvent(event)) {
3328 return BAD_VALUE;
3329 }
3330
3331 Mutex::Autolock _l(mLock);
3332
3333 for (size_t i = 0; i < mTracks.size(); ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003334 sp<IAfTrack> track = mTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08003335 if (event->triggerSession() == track->sessionId()) {
3336 (void) track->setSyncEvent(event);
3337 return NO_ERROR;
3338 }
3339 }
3340
3341 return NAME_NOT_FOUND;
3342}
3343
Andy Hungee58e4a2023-07-07 13:47:37 -07003344bool PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
Eric Laurent81784c32012-11-19 14:55:58 -08003345{
3346 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
3347}
3348
Andy Hungee58e4a2023-07-07 13:47:37 -07003349void PlaybackThread::threadLoop_removeTracks(
Andy Hung8d31fd22023-06-26 19:20:57 -07003350 [[maybe_unused]] const Vector<sp<IAfTrack>>& tracksToRemove)
Eric Laurent81784c32012-11-19 14:55:58 -08003351{
Andy Hungfe726a62018-09-27 15:17:25 -07003352 // Miscellaneous track cleanup when removed from the active list,
3353 // called without Thread lock but synchronized with threadLoop processing.
Eric Laurentbfb1b832013-01-07 09:53:42 -08003354#ifdef ADD_BATTERY_DATA
Andy Hungfe726a62018-09-27 15:17:25 -07003355 for (const auto& track : tracksToRemove) {
3356 if (track->isExternalTrack()) {
3357 // to track the speaker usage
3358 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Eric Laurent81784c32012-11-19 14:55:58 -08003359 }
3360 }
Andy Hungfe726a62018-09-27 15:17:25 -07003361#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003362}
3363
Andy Hungee58e4a2023-07-07 13:47:37 -07003364void PlaybackThread::checkSilentMode_l()
Eric Laurent81784c32012-11-19 14:55:58 -08003365{
3366 if (!mMasterMute) {
3367 char value[PROPERTY_VALUE_MAX];
jiabin0a957d32020-04-29 10:56:20 -07003368 if (mOutDeviceTypeAddrs.empty()) {
3369 ALOGD("ro.audio.silent is ignored since no output device is set");
3370 return;
3371 }
jiabinc52b1ff2019-10-31 17:20:42 -07003372 if (isSingleDeviceType(outDeviceTypes(), AUDIO_DEVICE_OUT_REMOTE_SUBMIX)) {
Jean-Michel Trivi32f37c22016-03-31 16:00:32 -07003373 ALOGD("ro.audio.silent will be ignored for threads on AUDIO_DEVICE_OUT_REMOTE_SUBMIX");
3374 return;
3375 }
Eric Laurent81784c32012-11-19 14:55:58 -08003376 if (property_get("ro.audio.silent", value, "0") > 0) {
3377 char *endptr;
3378 unsigned long ul = strtoul(value, &endptr, 0);
3379 if (*endptr == '\0' && ul != 0) {
3380 ALOGD("Silence is golden");
3381 // The setprop command will not allow a property to be changed after
3382 // the first time it is set, so we don't have to worry about un-muting.
3383 setMasterMute_l(true);
3384 }
3385 }
3386 }
3387}
3388
3389// shared by MIXER and DIRECT, overridden by DUPLICATING
Andy Hungee58e4a2023-07-07 13:47:37 -07003390ssize_t PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08003391{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07003392 LOG_HIST_TS();
Eric Laurent81784c32012-11-19 14:55:58 -08003393 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003394 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07003395 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08003396
3397 // If an NBAIO sink is present, use it to write the normal mixer's submix
3398 if (mNormalSink != 0) {
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003399
Andy Hung010a1a12014-03-13 13:57:33 -07003400 const size_t count = mBytesRemaining / mFrameSize;
3401
Simon Wilson2d590962012-11-29 15:18:50 -08003402 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08003403 // update the setpoint when AudioFlinger::mScreenState changes
Andy Hung1d2d2aea2023-07-19 16:22:58 -07003404 const uint32_t screenState = mAfThreadCallback->getScreenState();
Eric Laurent81784c32012-11-19 14:55:58 -08003405 if (screenState != mScreenState) {
3406 mScreenState = screenState;
3407 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
3408 if (pipe != NULL) {
3409 pipe->setAvgFrames((mScreenState & 1) ?
3410 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
3411 }
3412 }
Andy Hung010a1a12014-03-13 13:57:33 -07003413 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08003414 ATRACE_END();
Vlad Popab042ee62022-10-20 18:05:00 +02003415
Eric Laurent81784c32012-11-19 14:55:58 -08003416 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07003417 bytesWritten = framesWritten * mFrameSize;
Andy Hung58e32872022-11-15 16:12:24 -08003418
Andy Hung8946a282018-04-19 20:04:56 -07003419#ifdef TEE_SINK
3420 mTee.write((char *)mSinkBuffer + offset, framesWritten);
3421#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003422 } else {
3423 bytesWritten = framesWritten;
3424 }
3425 // otherwise use the HAL / AudioStreamOut directly
3426 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003427 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07003428
Eric Laurentbfb1b832013-01-07 09:53:42 -08003429 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003430 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
3431 mWriteAckSequence += 2;
3432 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003433 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003434 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003435 }
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07003436 ATRACE_BEGIN("write");
Glenn Kasten767094d2013-08-23 13:51:43 -07003437 // FIXME We should have an implementation of timestamps for direct output threads.
3438 // They are used e.g for multichannel PCM playback over HDMI.
Phil Burk062e67a2015-02-11 13:40:50 -08003439 bytesWritten = mOutput->write((char *)mSinkBuffer + offset, mBytesRemaining);
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07003440 ATRACE_END();
Eric Laurent51716182016-02-29 18:00:56 -08003441
Eric Laurentbfb1b832013-01-07 09:53:42 -08003442 if (mUseAsyncWrite &&
3443 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
3444 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07003445 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003446 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003447 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003448 }
Eric Laurent81784c32012-11-19 14:55:58 -08003449 }
3450
Eric Laurent81784c32012-11-19 14:55:58 -08003451 mNumWrites++;
3452 mInWrite = false;
Andy Hungcf10d742020-04-28 15:38:24 -07003453 if (mStandby) {
3454 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07003455 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -07003456 mStandby = false;
3457 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003458 return bytesWritten;
3459}
3460
Vlad Popa6fbbfbf2023-02-22 15:05:43 +01003461// startMelComputation_l() must be called with AudioFlinger::mLock held
Andy Hungee58e4a2023-07-07 13:47:37 -07003462void PlaybackThread::startMelComputation_l(
Vlad Popaf09e93f2022-10-31 16:27:12 +01003463 const sp<audio_utils::MelProcessor>& processor)
Vlad Popab042ee62022-10-20 18:05:00 +02003464{
Vlad Popa3c7a2662023-02-14 20:09:47 +01003465 auto outputSink = static_cast<AudioStreamOutSink*>(mOutputSink.get());
Vlad Popa1a0c3ab2023-03-17 01:07:01 +01003466 if (outputSink != nullptr) {
3467 outputSink->startMelComputation(processor);
3468 }
Vlad Popab042ee62022-10-20 18:05:00 +02003469}
3470
Vlad Popa6fbbfbf2023-02-22 15:05:43 +01003471// stopMelComputation_l() must be called with AudioFlinger::mLock held
Andy Hungee58e4a2023-07-07 13:47:37 -07003472void PlaybackThread::stopMelComputation_l()
Vlad Popa3c7a2662023-02-14 20:09:47 +01003473{
3474 auto outputSink = static_cast<AudioStreamOutSink*>(mOutputSink.get());
Vlad Popa1a0c3ab2023-03-17 01:07:01 +01003475 if (outputSink != nullptr) {
3476 outputSink->stopMelComputation();
3477 }
Vlad Popab042ee62022-10-20 18:05:00 +02003478}
3479
Andy Hungee58e4a2023-07-07 13:47:37 -07003480void PlaybackThread::threadLoop_drain()
Eric Laurentbfb1b832013-01-07 09:53:42 -08003481{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003482 bool supportsDrain = false;
3483 if (mOutput->stream->supportsDrain(&supportsDrain) == OK && supportsDrain) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003484 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
3485 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003486 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
3487 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003488 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003489 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003490 }
Mikhail Naganovcbc8f612016-10-11 18:05:13 -07003491 status_t result = mOutput->stream->drain(mMixerStatus == MIXER_DRAIN_TRACK);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003492 ALOGE_IF(result != OK, "Error when draining stream: %d", result);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003493 }
3494}
3495
Andy Hungee58e4a2023-07-07 13:47:37 -07003496void PlaybackThread::threadLoop_exit()
Eric Laurentbfb1b832013-01-07 09:53:42 -08003497{
Eric Laurent275e8e92014-11-30 15:14:47 -08003498 {
3499 Mutex::Autolock _l(mLock);
3500 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003501 sp<IAfTrack> track = mTracks[i];
Eric Laurent275e8e92014-11-30 15:14:47 -08003502 track->invalidate();
3503 }
Andy Hungdae27702016-10-31 14:01:16 -07003504 // Clear ActiveTracks to update BatteryNotifier in case active tracks remain.
3505 // After we exit there are no more track changes sent to BatteryNotifier
3506 // because that requires an active threadLoop.
3507 // TODO: should we decActiveTrackCnt() of the cleared track effect chain?
3508 mActiveTracks.clear();
Eric Laurent275e8e92014-11-30 15:14:47 -08003509 }
Eric Laurent81784c32012-11-19 14:55:58 -08003510}
3511
3512/*
3513The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08003514 - mSinkBufferSize from frame count * frame size
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003515 - mActiveSleepTimeUs from activeSleepTimeUs()
3516 - mIdleSleepTimeUs from idleSleepTimeUs()
Eric Laurent42537be2016-01-08 17:16:42 -08003517 - mStandbyDelayNs from mActiveSleepTimeUs (DIRECT only) or forced to at least
3518 kDefaultStandbyTimeInNsecs when connected to an A2DP device.
Eric Laurent81784c32012-11-19 14:55:58 -08003519 - maxPeriod from frame count and sample rate (MIXER only)
3520
3521The parameters that affect these derived values are:
3522 - frame count
3523 - frame size
3524 - sample rate
3525 - device type: A2DP or not
3526 - device latency
3527 - format: PCM or not
3528 - active sleep time
3529 - idle sleep time
3530*/
3531
Andy Hungee58e4a2023-07-07 13:47:37 -07003532void PlaybackThread::cacheParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08003533{
Andy Hung25c2dac2014-02-27 14:56:00 -08003534 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003535 mActiveSleepTimeUs = activeSleepTimeUs();
3536 mIdleSleepTimeUs = idleSleepTimeUs();
Eric Laurent42537be2016-01-08 17:16:42 -08003537
Eric Laurent52568142022-10-28 11:23:28 +02003538 mStandbyDelayNs = AudioFlinger::mStandbyTimeInNsecs;
Carter Hsu0ca47c22023-06-02 18:01:45 +08003539
Eric Laurent42537be2016-01-08 17:16:42 -08003540 // make sure standby delay is not too short when connected to an A2DP sink to avoid
3541 // truncating audio when going to standby.
jiabinc52b1ff2019-10-31 17:20:42 -07003542 if (!Intersection(outDeviceTypes(), getAudioDeviceOutAllA2dpSet()).empty()) {
Eric Laurent42537be2016-01-08 17:16:42 -08003543 if (mStandbyDelayNs < kDefaultStandbyTimeInNsecs) {
3544 mStandbyDelayNs = kDefaultStandbyTimeInNsecs;
3545 }
3546 }
Eric Laurent81784c32012-11-19 14:55:58 -08003547}
3548
Andy Hungee58e4a2023-07-07 13:47:37 -07003549bool PlaybackThread::invalidateTracks_l(audio_stream_type_t streamType)
Eric Laurent81784c32012-11-19 14:55:58 -08003550{
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003551 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %zu",
Eric Laurent81784c32012-11-19 14:55:58 -08003552 this, streamType, mTracks.size());
Eric Laurent13084622016-05-17 10:51:49 -07003553 bool trackMatch = false;
Eric Laurent81784c32012-11-19 14:55:58 -08003554 size_t size = mTracks.size();
3555 for (size_t i = 0; i < size; i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003556 sp<IAfTrack> t = mTracks[i];
Eric Laurentd60560a2015-04-10 11:31:20 -07003557 if (t->streamType() == streamType && t->isExternalTrack()) {
Glenn Kasten5736c352012-12-04 12:12:34 -08003558 t->invalidate();
Eric Laurent13084622016-05-17 10:51:49 -07003559 trackMatch = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003560 }
3561 }
Eric Laurent13084622016-05-17 10:51:49 -07003562 return trackMatch;
Eric Laurent81784c32012-11-19 14:55:58 -08003563}
3564
Andy Hungee58e4a2023-07-07 13:47:37 -07003565void PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
Haynes Mathew George05317d22016-05-03 16:34:26 -07003566{
3567 Mutex::Autolock _l(mLock);
3568 invalidateTracks_l(streamType);
3569}
3570
Andy Hungee58e4a2023-07-07 13:47:37 -07003571void PlaybackThread::invalidateTracks(std::set<audio_port_handle_t>& portIds) {
jiabinc44b3462022-12-08 12:52:31 -08003572 Mutex::Autolock _l(mLock);
3573 invalidateTracks_l(portIds);
3574}
3575
Andy Hungee58e4a2023-07-07 13:47:37 -07003576bool PlaybackThread::invalidateTracks_l(std::set<audio_port_handle_t>& portIds) {
jiabinc44b3462022-12-08 12:52:31 -08003577 bool trackMatch = false;
3578 const size_t size = mTracks.size();
3579 for (size_t i = 0; i < size; i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003580 sp<IAfTrack> t = mTracks[i];
jiabinc44b3462022-12-08 12:52:31 -08003581 if (t->isExternalTrack() && portIds.find(t->portId()) != portIds.end()) {
3582 t->invalidate();
3583 portIds.erase(t->portId());
3584 trackMatch = true;
3585 }
3586 if (portIds.empty()) {
3587 break;
3588 }
3589 }
3590 return trackMatch;
3591}
3592
jiabinf042b9b2021-05-07 23:46:28 +00003593// getTrackById_l must be called with holding thread lock
Andy Hungee58e4a2023-07-07 13:47:37 -07003594IAfTrack* PlaybackThread::getTrackById_l(
jiabinf042b9b2021-05-07 23:46:28 +00003595 audio_port_handle_t trackPortId) {
3596 for (size_t i = 0; i < mTracks.size(); i++) {
3597 if (mTracks[i]->portId() == trackPortId) {
3598 return mTracks[i].get();
3599 }
3600 }
3601 return nullptr;
3602}
3603
Andy Hungee58e4a2023-07-07 13:47:37 -07003604status_t PlaybackThread::addEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08003605{
Glenn Kastend848eb42016-03-08 13:42:11 -08003606 audio_session_t session = chain->sessionId();
Mikhail Naganov022b9952017-01-04 16:36:51 -08003607 sp<EffectBufferHalInterface> halInBuffer, halOutBuffer;
Andy Hung319587b2023-05-23 14:01:03 -07003608 float *buffer = nullptr; // only used for non global sessions
Eric Laurentb62d0362021-10-26 17:40:18 +02003609
Andy Hungd3639922022-04-28 18:00:49 -07003610 if (mType == SPATIALIZER) {
Eric Laurentb62d0362021-10-26 17:40:18 +02003611 if (!audio_is_global_session(session)) {
3612 // player sessions on a spatializer output will use a dedicated input buffer and
3613 // will either output multi channel to mEffectBuffer if the track is spatilaized
3614 // or stereo to mPostSpatializerBuffer if not spatialized.
3615 uint32_t channelMask;
3616 bool isSessionSpatialized =
3617 (hasAudioSession_l(session) & ThreadBase::SPATIALIZED_SESSION) != 0;
3618 if (isSessionSpatialized) {
3619 channelMask = mMixerChannelMask;
3620 } else {
3621 channelMask = mChannelMask;
3622 }
Eric Laurentf1f22e72021-07-13 14:04:14 +02003623 size_t numSamples = mNormalFrameCount
Eric Laurentb62d0362021-10-26 17:40:18 +02003624 * (audio_channel_count_from_out_mask(channelMask) + mHapticChannelCount);
Andy Hung583043b2023-07-17 17:05:00 -07003625 status_t result = mAfThreadCallback->getEffectsFactoryHal()->allocateBuffer(
Andy Hung319587b2023-05-23 14:01:03 -07003626 numSamples * sizeof(float),
Mikhail Naganov022b9952017-01-04 16:36:51 -08003627 &halInBuffer);
3628 if (result != OK) return result;
Eric Laurentb62d0362021-10-26 17:40:18 +02003629
Andy Hung583043b2023-07-17 17:05:00 -07003630 result = mAfThreadCallback->getEffectsFactoryHal()->mirrorBuffer(
Eric Laurentb62d0362021-10-26 17:40:18 +02003631 isSessionSpatialized ? mEffectBuffer : mPostSpatializerBuffer,
3632 isSessionSpatialized ? mEffectBufferSize : mPostSpatializerBufferSize,
3633 &halOutBuffer);
3634 if (result != OK) return result;
3635
Shunkai Yao44bdbad2023-01-14 05:11:58 +00003636 buffer = halInBuffer ? halInBuffer->audioBuffer()->f32 : buffer;
Andy Hung26836922023-05-22 17:31:57 -07003637
Mikhail Naganov022b9952017-01-04 16:36:51 -08003638 ALOGV("addEffectChain_l() creating new input buffer %p session %d",
3639 buffer, session);
Eric Laurentb62d0362021-10-26 17:40:18 +02003640 } else {
3641 // A global session on a SPATIALIZER thread is either OUTPUT_STAGE or DEVICE
3642 // - OUTPUT_STAGE session uses the mEffectBuffer as input buffer and
3643 // mPostSpatializerBuffer as output buffer
3644 // - DEVICE session uses the mPostSpatializerBuffer as input and output buffer.
Andy Hung583043b2023-07-17 17:05:00 -07003645 status_t result = mAfThreadCallback->getEffectsFactoryHal()->mirrorBuffer(
Eric Laurentb62d0362021-10-26 17:40:18 +02003646 mEffectBuffer, mEffectBufferSize, &halInBuffer);
3647 if (result != OK) return result;
Andy Hung583043b2023-07-17 17:05:00 -07003648 result = mAfThreadCallback->getEffectsFactoryHal()->mirrorBuffer(
Eric Laurentb62d0362021-10-26 17:40:18 +02003649 mPostSpatializerBuffer, mPostSpatializerBufferSize, &halOutBuffer);
3650 if (result != OK) return result;
Eric Laurent81784c32012-11-19 14:55:58 -08003651
Eric Laurentb62d0362021-10-26 17:40:18 +02003652 if (session == AUDIO_SESSION_DEVICE) {
3653 halInBuffer = halOutBuffer;
3654 }
3655 }
3656 } else {
Andy Hung583043b2023-07-17 17:05:00 -07003657 status_t result = mAfThreadCallback->getEffectsFactoryHal()->mirrorBuffer(
Eric Laurentb62d0362021-10-26 17:40:18 +02003658 mEffectBufferEnabled ? mEffectBuffer : mSinkBuffer,
3659 mEffectBufferEnabled ? mEffectBufferSize : mSinkBufferSize,
3660 &halInBuffer);
3661 if (result != OK) return result;
3662 halOutBuffer = halInBuffer;
3663 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
3664 if (!audio_is_global_session(session)) {
Andy Hung319587b2023-05-23 14:01:03 -07003665 buffer = halInBuffer ? reinterpret_cast<float*>(halInBuffer->externalData())
Shunkai Yao44bdbad2023-01-14 05:11:58 +00003666 : buffer;
Eric Laurentb62d0362021-10-26 17:40:18 +02003667 // Only one effect chain can be present in direct output thread and it uses
3668 // the sink buffer as input
3669 if (mType != DIRECT) {
3670 size_t numSamples = mNormalFrameCount
3671 * (audio_channel_count_from_out_mask(mMixerChannelMask)
3672 + mHapticChannelCount);
Andy Hung583043b2023-07-17 17:05:00 -07003673 const status_t allocateStatus =
3674 mAfThreadCallback->getEffectsFactoryHal()->allocateBuffer(
Andy Hung319587b2023-05-23 14:01:03 -07003675 numSamples * sizeof(float),
Eric Laurentb62d0362021-10-26 17:40:18 +02003676 &halInBuffer);
Andy Hung920f6572022-10-06 12:09:49 -07003677 if (allocateStatus != OK) return allocateStatus;
Andy Hung26836922023-05-22 17:31:57 -07003678
Shunkai Yao44bdbad2023-01-14 05:11:58 +00003679 buffer = halInBuffer ? halInBuffer->audioBuffer()->f32 : buffer;
Eric Laurentb62d0362021-10-26 17:40:18 +02003680 ALOGV("addEffectChain_l() creating new input buffer %p session %d",
3681 buffer, session);
3682 }
3683 }
3684 }
3685
3686 if (!audio_is_global_session(session)) {
Eric Laurent81784c32012-11-19 14:55:58 -08003687 // Attach all tracks with same session ID to this chain.
3688 for (size_t i = 0; i < mTracks.size(); ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003689 sp<IAfTrack> track = mTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08003690 if (session == track->sessionId()) {
Eric Laurentb62d0362021-10-26 17:40:18 +02003691 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p",
3692 track.get(), buffer);
Eric Laurent81784c32012-11-19 14:55:58 -08003693 track->setMainBuffer(buffer);
3694 chain->incTrackCnt();
3695 }
3696 }
3697
3698 // indicate all active tracks in the chain
Andy Hung8d31fd22023-06-26 19:20:57 -07003699 for (const sp<IAfTrack>& track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08003700 if (session == track->sessionId()) {
Eric Laurentb62d0362021-10-26 17:40:18 +02003701 ALOGV("addEffectChain_l() activating track %p on session %d",
3702 track.get(), session);
Eric Laurent81784c32012-11-19 14:55:58 -08003703 chain->incActiveTrackCnt();
3704 }
3705 }
3706 }
Eric Laurentb62d0362021-10-26 17:40:18 +02003707
Eric Laurentaaa44472014-09-12 17:41:50 -07003708 chain->setThread(this);
Mikhail Naganov022b9952017-01-04 16:36:51 -08003709 chain->setInBuffer(halInBuffer);
3710 chain->setOutBuffer(halOutBuffer);
Eric Laurent3f75a5b2019-11-12 15:55:51 -08003711 // Effect chain for session AUDIO_SESSION_DEVICE is inserted at end of effect
3712 // chains list in order to be processed last as it contains output device effects.
3713 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted just before to apply post
3714 // processing effects specific to an output stream before effects applied to all streams
3715 // routed to a given device.
Eric Laurent81784c32012-11-19 14:55:58 -08003716 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
3717 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Glenn Kastend848eb42016-03-08 13:42:11 -08003718 // after track specific effects and before output stage.
Eric Laurent81784c32012-11-19 14:55:58 -08003719 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
Glenn Kastend848eb42016-03-08 13:42:11 -08003720 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX.
Eric Laurent81784c32012-11-19 14:55:58 -08003721 // Effect chain for other sessions are inserted at beginning of effect
3722 // chains list to be processed before output mix effects. Relative order between other
Glenn Kastend848eb42016-03-08 13:42:11 -08003723 // sessions is not important.
3724 static_assert(AUDIO_SESSION_OUTPUT_MIX == 0 &&
Eric Laurent3f75a5b2019-11-12 15:55:51 -08003725 AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX &&
3726 AUDIO_SESSION_DEVICE < AUDIO_SESSION_OUTPUT_STAGE,
Glenn Kastend848eb42016-03-08 13:42:11 -08003727 "audio_session_t constants misdefined");
Eric Laurent81784c32012-11-19 14:55:58 -08003728 size_t size = mEffectChains.size();
3729 size_t i = 0;
3730 for (i = 0; i < size; i++) {
3731 if (mEffectChains[i]->sessionId() < session) {
3732 break;
3733 }
3734 }
3735 mEffectChains.insertAt(chain, i);
3736 checkSuspendOnAddEffectChain_l(chain);
3737
3738 return NO_ERROR;
3739}
3740
Andy Hungee58e4a2023-07-07 13:47:37 -07003741size_t PlaybackThread::removeEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08003742{
Glenn Kastend848eb42016-03-08 13:42:11 -08003743 audio_session_t session = chain->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08003744
3745 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
3746
3747 for (size_t i = 0; i < mEffectChains.size(); i++) {
3748 if (chain == mEffectChains[i]) {
3749 mEffectChains.removeAt(i);
3750 // detach all active tracks from the chain
Andy Hung8d31fd22023-06-26 19:20:57 -07003751 for (const sp<IAfTrack>& track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08003752 if (session == track->sessionId()) {
3753 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
3754 chain.get(), session);
3755 chain->decActiveTrackCnt();
3756 }
3757 }
3758
3759 // detach all tracks with same session ID from this chain
Andy Hung920f6572022-10-06 12:09:49 -07003760 for (size_t j = 0; j < mTracks.size(); ++j) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003761 sp<IAfTrack> track = mTracks[j];
Eric Laurent81784c32012-11-19 14:55:58 -08003762 if (session == track->sessionId()) {
Andy Hung319587b2023-05-23 14:01:03 -07003763 track->setMainBuffer(reinterpret_cast<float*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08003764 chain->decTrackCnt();
3765 }
3766 }
3767 break;
3768 }
3769 }
3770 return mEffectChains.size();
3771}
3772
Andy Hungee58e4a2023-07-07 13:47:37 -07003773status_t PlaybackThread::attachAuxEffect(
Andy Hung8d31fd22023-06-26 19:20:57 -07003774 const sp<IAfTrack>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003775{
3776 Mutex::Autolock _l(mLock);
3777 return attachAuxEffect_l(track, EffectId);
3778}
3779
Andy Hungee58e4a2023-07-07 13:47:37 -07003780status_t PlaybackThread::attachAuxEffect_l(
Andy Hung8d31fd22023-06-26 19:20:57 -07003781 const sp<IAfTrack>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003782{
3783 status_t status = NO_ERROR;
3784
3785 if (EffectId == 0) {
3786 track->setAuxBuffer(0, NULL);
3787 } else {
3788 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
Andy Hung116bc262023-06-20 18:56:17 -07003789 sp<IAfEffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Eric Laurent81784c32012-11-19 14:55:58 -08003790 if (effect != 0) {
3791 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
3792 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
3793 } else {
3794 status = INVALID_OPERATION;
3795 }
3796 } else {
3797 status = BAD_VALUE;
3798 }
3799 }
3800 return status;
3801}
3802
Andy Hungee58e4a2023-07-07 13:47:37 -07003803void PlaybackThread::detachAuxEffect_l(int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003804{
3805 for (size_t i = 0; i < mTracks.size(); ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003806 sp<IAfTrack> track = mTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08003807 if (track->auxEffectId() == effectId) {
3808 attachAuxEffect_l(track, 0);
3809 }
3810 }
3811}
3812
Andy Hungee58e4a2023-07-07 13:47:37 -07003813bool PlaybackThread::threadLoop()
Andy Hung920f6572022-10-06 12:09:49 -07003814NO_THREAD_SAFETY_ANALYSIS // manual locking of AudioFlinger
Eric Laurent81784c32012-11-19 14:55:58 -08003815{
Andy Hung78d8d952023-05-30 18:10:23 -07003816 aflog::setThreadWriter(mNBLogWriter.get());
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003817
Andy Hung8d31fd22023-06-26 19:20:57 -07003818 Vector<sp<IAfTrack>> tracksToRemove;
Eric Laurent81784c32012-11-19 14:55:58 -08003819
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003820 mStandbyTimeNs = systemTime();
Andy Hung446f4df2019-02-21 12:26:41 -08003821 int64_t lastLoopCountWritten = -2; // never matches "previous" loop, when loopCount = 0.
Eric Laurent81784c32012-11-19 14:55:58 -08003822
3823 // MIXER
3824 nsecs_t lastWarning = 0;
3825
3826 // DUPLICATING
3827 // FIXME could this be made local to while loop?
3828 writeFrames = 0;
3829
3830 cacheParameters_l();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003831 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003832
Andy Hungd3639922022-04-28 18:00:49 -07003833 if (mType == MIXER || mType == SPATIALIZER) {
Eric Laurent81784c32012-11-19 14:55:58 -08003834 sleepTimeShift = 0;
3835 }
3836
3837 CpuStats cpuStats;
3838 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
3839
3840 acquireWakeLock();
3841
Glenn Kasteneef598c2017-04-03 14:41:13 -07003842 // mNBLogWriter logging APIs can only be called by a single thread, typically the
3843 // thread associated with this PlaybackThread.
3844 // If you want to share the mNBLogWriter with other threads (for example, binder threads)
3845 // then all such threads must agree to hold a common mutex before logging.
Glenn Kasten9e58b552013-01-18 15:09:48 -08003846 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
3847 // and then that string will be logged at the next convenient opportunity.
Glenn Kasteneef598c2017-04-03 14:41:13 -07003848 // See reference to logString below.
Glenn Kasten9e58b552013-01-18 15:09:48 -08003849 const char *logString = NULL;
3850
rago1bb90822017-05-02 18:31:48 -07003851 // Estimated time for next buffer to be written to hal. This is used only on
3852 // suspended mode (for now) to help schedule the wait time until next iteration.
3853 nsecs_t timeLoopNextNs = 0;
3854
Eric Laurent664539d2013-09-23 18:24:31 -07003855 checkSilentMode_l();
Glenn Kasteneef598c2017-04-03 14:41:13 -07003856
Andy Hung2dbffc22018-08-08 18:50:41 -07003857 audio_patch_handle_t lastDownstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Andy Hungf3234512018-07-03 14:51:47 -07003858
Eric Laurentb3f315a2021-07-13 15:09:05 +02003859 sendCheckOutputStageEffectsEvent();
3860
Andy Hung446f4df2019-02-21 12:26:41 -08003861 // loopCount is used for statistics and diagnostics.
3862 for (int64_t loopCount = 0; !exitPending(); ++loopCount)
Eric Laurent81784c32012-11-19 14:55:58 -08003863 {
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08003864 // Log merge requests are performed during AudioFlinger binder transactions, but
3865 // that does not cover audio playback. It's requested here for that reason.
Andy Hung583043b2023-07-17 17:05:00 -07003866 mAfThreadCallback->requestLogMerge();
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08003867
Eric Laurent81784c32012-11-19 14:55:58 -08003868 cpuStats.sample(myName);
3869
Andy Hung116bc262023-06-20 18:56:17 -07003870 Vector<sp<IAfEffectChain>> effectChains;
Andy Hung6e6a2e62019-04-30 16:38:41 -07003871 audio_session_t activeHapticSessionId = AUDIO_SESSION_NONE;
Eric Laurentb62d0362021-10-26 17:40:18 +02003872 bool isHapticSessionSpatialized = false;
Andy Hung8d31fd22023-06-26 19:20:57 -07003873 std::vector<sp<IAfTrack>> activeTracks;
Eric Laurent81784c32012-11-19 14:55:58 -08003874
Andy Hung2dbffc22018-08-08 18:50:41 -07003875 // If the device is AUDIO_DEVICE_OUT_BUS, check for downstream latency.
3876 //
jiabinc52b1ff2019-10-31 17:20:42 -07003877 // Note: we access outDeviceTypes() outside of mLock.
3878 if (isMsdDevice() && outDeviceTypes().count(AUDIO_DEVICE_OUT_BUS) != 0) {
Andy Hung2dbffc22018-08-08 18:50:41 -07003879 // Here, we try for the AF lock, but do not block on it as the latency
3880 // is more informational.
Andy Hung583043b2023-07-17 17:05:00 -07003881 if (mAfThreadCallback->mutex().tryLock() == NO_ERROR) {
Andy Hungb6692eb2023-07-13 16:52:46 -07003882 std::vector<SoftwarePatch> swPatches;
Andy Hung920f6572022-10-06 12:09:49 -07003883 double latencyMs = 0.; // not required; initialized for clang-tidy
Andy Hung2dbffc22018-08-08 18:50:41 -07003884 status_t status = INVALID_OPERATION;
3885 audio_patch_handle_t downstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Andy Hung583043b2023-07-17 17:05:00 -07003886 if (mAfThreadCallback->getPatchPanel()->getDownstreamSoftwarePatches(
Andy Hungb6692eb2023-07-13 16:52:46 -07003887 id(), &swPatches) == OK
Andy Hung2dbffc22018-08-08 18:50:41 -07003888 && swPatches.size() > 0) {
3889 status = swPatches[0].getLatencyMs_l(&latencyMs);
3890 downstreamPatchHandle = swPatches[0].getPatchHandle();
3891 }
3892 if (downstreamPatchHandle != lastDownstreamPatchHandle) {
Dean Wheatley30d28422018-11-06 10:27:40 +11003893 mDownstreamLatencyStatMs.reset();
Andy Hung2dbffc22018-08-08 18:50:41 -07003894 lastDownstreamPatchHandle = downstreamPatchHandle;
3895 }
3896 if (status == OK) {
3897 // verify downstream latency (we assume a max reasonable
Mikhail Naganov6aa0a312018-11-09 11:00:01 -08003898 // latency of 5 seconds).
3899 const double minLatency = 0., maxLatency = 5000.;
3900 if (latencyMs >= minLatency && latencyMs <= maxLatency) {
Dean Wheatley56a583e2020-05-08 15:12:17 +10003901 ALOGVV("new downstream latency %lf ms", latencyMs);
Andy Hung2dbffc22018-08-08 18:50:41 -07003902 } else {
3903 ALOGD("out of range downstream latency %lf ms", latencyMs);
Andy Hung920f6572022-10-06 12:09:49 -07003904 latencyMs = std::clamp(latencyMs, minLatency, maxLatency);
Andy Hung2dbffc22018-08-08 18:50:41 -07003905 }
Dean Wheatley30d28422018-11-06 10:27:40 +11003906 mDownstreamLatencyStatMs.add(latencyMs);
Andy Hung2dbffc22018-08-08 18:50:41 -07003907 }
Andy Hung583043b2023-07-17 17:05:00 -07003908 mAfThreadCallback->mutex().unlock();
Andy Hung2dbffc22018-08-08 18:50:41 -07003909 }
3910 } else {
3911 if (lastDownstreamPatchHandle != AUDIO_PATCH_HANDLE_NONE) {
3912 // our device is no longer AUDIO_DEVICE_OUT_BUS, reset patch handle and stats.
Dean Wheatley30d28422018-11-06 10:27:40 +11003913 mDownstreamLatencyStatMs.reset();
Andy Hung2dbffc22018-08-08 18:50:41 -07003914 lastDownstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
3915 }
3916 }
3917
Eric Laurentb3f315a2021-07-13 15:09:05 +02003918 if (mCheckOutputStageEffects.exchange(false)) {
3919 checkOutputStageEffects();
3920 }
3921
Vlad Popa7e81cea2023-01-19 16:34:16 +01003922 MetadataUpdate metadataUpdate;
Eric Laurent81784c32012-11-19 14:55:58 -08003923 { // scope for mLock
3924
3925 Mutex::Autolock _l(mLock);
3926
Eric Laurent021cf962014-05-13 10:18:14 -07003927 processConfigEvents_l();
Eric Laurentb3f315a2021-07-13 15:09:05 +02003928 if (mCheckOutputStageEffects.load()) {
3929 continue;
3930 }
Eric Laurent10351942014-05-08 18:49:52 -07003931
Glenn Kasteneef598c2017-04-03 14:41:13 -07003932 // See comment at declaration of logString for why this is done under mLock
Glenn Kasten9e58b552013-01-18 15:09:48 -08003933 if (logString != NULL) {
3934 mNBLogWriter->logTimestamp();
3935 mNBLogWriter->log(logString);
3936 logString = NULL;
3937 }
3938
Dean Wheatley12473e92021-03-18 23:00:55 +11003939 collectTimestamps_l();
Andy Hungc8fddf32018-08-08 18:32:37 -07003940
Eric Laurent81784c32012-11-19 14:55:58 -08003941 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003942 if (mSignalPending) {
3943 // A signal was raised while we were unlocked
3944 mSignalPending = false;
3945 } else if (waitingAsyncCallback_l()) {
3946 if (exitPending()) {
3947 break;
3948 }
Marco Nelissen078538c2015-05-12 09:17:57 -07003949 bool released = false;
Eric Laurent64667972016-03-30 18:19:46 -07003950 if (!keepWakeLock()) {
Marco Nelissen078538c2015-05-12 09:17:57 -07003951 releaseWakeLock_l();
3952 released = true;
3953 }
Andy Hung10cbff12017-02-21 17:30:14 -08003954
3955 const int64_t waitNs = computeWaitTimeNs_l();
3956 ALOGV("wait async completion (wait time: %lld)", (long long)waitNs);
3957 status_t status = mWaitWorkCV.waitRelative(mLock, waitNs);
3958 if (status == TIMED_OUT) {
3959 mSignalPending = true; // if timeout recheck everything
3960 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003961 ALOGV("async completion/wake");
Marco Nelissen078538c2015-05-12 09:17:57 -07003962 if (released) {
3963 acquireWakeLock_l();
3964 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003965 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3966 mSleepTimeUs = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07003967
3968 continue;
3969 }
Eric Tan39ec8d62018-07-24 09:49:29 -07003970 if ((mActiveTracks.isEmpty() && systemTime() > mStandbyTimeNs) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08003971 isSuspended()) {
3972 // put audio hardware into standby after short delay
3973 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003974
3975 threadLoop_standby();
3976
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07003977 // This is where we go into standby
3978 if (!mStandby) {
3979 LOG_AUDIO_STATE();
Andy Hungcf10d742020-04-28 15:38:24 -07003980 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07003981 mThreadSnapshot.onEnd();
Eric Laurent19952e12023-04-20 10:08:29 +02003982 setStandby_l();
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07003983 }
Andy Hungd0979812019-02-21 15:51:44 -08003984 sendStatistics(false /* force */);
Eric Laurent81784c32012-11-19 14:55:58 -08003985 }
3986
Eric Tan39ec8d62018-07-24 09:49:29 -07003987 if (mActiveTracks.isEmpty() && mConfigEvents.isEmpty()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003988 // we're about to wait, flush the binder command buffer
3989 IPCThreadState::self()->flushCommands();
3990
3991 clearOutputTracks();
3992
3993 if (exitPending()) {
3994 break;
3995 }
3996
3997 releaseWakeLock_l();
3998 // wait until we have something to do...
3999 ALOGV("%s going to sleep", myName.string());
4000 mWaitWorkCV.wait(mLock);
4001 ALOGV("%s waking up", myName.string());
4002 acquireWakeLock_l();
4003
4004 mMixerStatus = MIXER_IDLE;
4005 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
4006 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004007 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08004008 checkSilentMode_l();
4009
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004010 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
4011 mSleepTimeUs = mIdleSleepTimeUs;
Andy Hungd3639922022-04-28 18:00:49 -07004012 if (mType == MIXER || mType == SPATIALIZER) {
Eric Laurent81784c32012-11-19 14:55:58 -08004013 sleepTimeShift = 0;
4014 }
4015
4016 continue;
4017 }
4018 }
Eric Laurent81784c32012-11-19 14:55:58 -08004019 // mMixerStatusIgnoringFastTracks is also updated internally
4020 mMixerStatus = prepareTracks_l(&tracksToRemove);
4021
Andy Hungdae27702016-10-31 14:01:16 -07004022 mActiveTracks.updatePowerState(this);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08004023
Vlad Popa7e81cea2023-01-19 16:34:16 +01004024 metadataUpdate = updateMetadata_l();
Kevin Rocard069c2712018-03-29 19:09:14 -07004025
Eric Laurent81784c32012-11-19 14:55:58 -08004026 // prevent any changes in effect chain list and in each effect chain
4027 // during mixing and effect process as the audio buffers could be deleted
4028 // or modified if an effect is created or deleted
4029 lockEffectChains_l(effectChains);
Andy Hung6e6a2e62019-04-30 16:38:41 -07004030
4031 // Determine which session to pick up haptic data.
4032 // This must be done under the same lock as prepareTracks_l().
jiabineb3bda02020-06-30 14:07:03 -07004033 // The haptic data from the effect is at a higher priority than the one from track.
Andy Hung6e6a2e62019-04-30 16:38:41 -07004034 // TODO: Write haptic data directly to sink buffer when mixing.
Eric Laurentb62d0362021-10-26 17:40:18 +02004035 if (mHapticChannelCount > 0) {
Andy Hung6e6a2e62019-04-30 16:38:41 -07004036 for (const auto& track : mActiveTracks) {
Andy Hung116bc262023-06-20 18:56:17 -07004037 sp<IAfEffectChain> effectChain = getEffectChain_l(track->sessionId());
Eric Laurentb62d0362021-10-26 17:40:18 +02004038 if (effectChain != nullptr
4039 && effectChain->containsHapticGeneratingEffect_l()) {
jiabineb3bda02020-06-30 14:07:03 -07004040 activeHapticSessionId = track->sessionId();
Eric Laurentb62d0362021-10-26 17:40:18 +02004041 isHapticSessionSpatialized =
Eric Laurentb0a7bc92022-04-05 15:06:08 +02004042 mType == SPATIALIZER && track->isSpatialized();
jiabineb3bda02020-06-30 14:07:03 -07004043 break;
4044 }
Eric Laurentb62d0362021-10-26 17:40:18 +02004045 if (activeHapticSessionId == AUDIO_SESSION_NONE
4046 && track->getHapticPlaybackEnabled()) {
Andy Hung6e6a2e62019-04-30 16:38:41 -07004047 activeHapticSessionId = track->sessionId();
Eric Laurentb62d0362021-10-26 17:40:18 +02004048 isHapticSessionSpatialized =
Eric Laurentb0a7bc92022-04-05 15:06:08 +02004049 mType == SPATIALIZER && track->isSpatialized();
Andy Hung6e6a2e62019-04-30 16:38:41 -07004050 }
4051 }
4052 }
4053
Andy Hungc1646382019-04-30 16:12:10 -07004054 // Acquire a local copy of active tracks with lock (release w/o lock).
4055 //
4056 // Control methods on the track acquire the ThreadBase lock (e.g. start()
4057 // stop(), pause(), etc.), but the threadLoop is entitled to call audio
4058 // data / buffer methods on tracks from activeTracks without the ThreadBase lock.
4059 activeTracks.insert(activeTracks.end(), mActiveTracks.begin(), mActiveTracks.end());
Eric Laurent68a40a82022-05-03 18:15:04 +02004060
4061 setHalLatencyMode_l();
Eric Laurent19952e12023-04-20 10:08:29 +02004062
Jiabin Huangfb476842022-12-06 03:18:10 +00004063 for (const auto &track : mActiveTracks ) {
jiabin7434e812023-06-27 18:22:35 +00004064 track->updateTeePatches_l();
Jiabin Huangfb476842022-12-06 03:18:10 +00004065 }
4066
Eric Laurent19952e12023-04-20 10:08:29 +02004067 // signal actual start of output stream when the render position reported by the kernel
4068 // starts moving.
Eric Laurent4edbd8c2023-05-22 17:00:24 +02004069 if (!mHalStarted && ((isSuspended() && (mBytesWritten != 0)) || (!mStandby
4070 && (mKernelPositionOnStandby
4071 != mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL])))) {
Eric Laurent19952e12023-04-20 10:08:29 +02004072 mHalStarted = true;
4073 mWaitHalStartCV.broadcast();
4074 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -08004075 } // mLock scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08004076
Eric Laurentbfb1b832013-01-07 09:53:42 -08004077 if (mBytesRemaining == 0) {
4078 mCurrentWriteLength = 0;
4079 if (mMixerStatus == MIXER_TRACKS_READY) {
4080 // threadLoop_mix() sets mCurrentWriteLength
4081 threadLoop_mix();
4082 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
4083 && (mMixerStatus != MIXER_DRAIN_ALL)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004084 // threadLoop_sleepTime sets mSleepTimeUs to 0 if data
Eric Laurentbfb1b832013-01-07 09:53:42 -08004085 // must be written to HAL
4086 threadLoop_sleepTime();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004087 if (mSleepTimeUs == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08004088 mCurrentWriteLength = mSinkBufferSize;
Andy Hungc1646382019-04-30 16:12:10 -07004089
4090 // Tally underrun frames as we are inserting 0s here.
4091 for (const auto& track : activeTracks) {
Andy Hung8d31fd22023-06-26 19:20:57 -07004092 if (track->fillingStatus() == IAfTrack::FS_ACTIVE
Andy Hunge2e830f2019-12-03 12:54:46 -08004093 && !track->isStopped()
4094 && !track->isPaused()
4095 && !track->isTerminated()) {
4096 ALOGV("%s: track(%d) %s underrun due to thread sleep of %zu frames",
4097 __func__, track->id(), track->getTrackStateAsString(),
4098 mNormalFrameCount);
Andy Hung8d31fd22023-06-26 19:20:57 -07004099 track->audioTrackServerProxy()->tallyUnderrunFrames(
4100 mNormalFrameCount);
Andy Hungc1646382019-04-30 16:12:10 -07004101 }
4102 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004103 }
4104 }
Andy Hung98ef9782014-03-04 14:46:50 -08004105 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004106 // mMixerBuffer with data if mMixerBufferValid is true and mSleepTimeUs == 0.
Andy Hung98ef9782014-03-04 14:46:50 -08004107 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
jiabinc658e452022-10-21 20:52:21 +00004108 // or mSinkBuffer (if there are no effects and there is no data already copied to
4109 // mSinkBuffer).
Andy Hung98ef9782014-03-04 14:46:50 -08004110 //
4111 // This is done pre-effects computation; if effects change to
4112 // support higher precision, this needs to move.
4113 //
4114 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004115 // TODO use mSleepTimeUs == 0 as an additional condition.
Eric Laurent39095982021-08-24 18:29:27 +02004116 uint32_t mixerChannelCount = mEffectBufferValid ?
4117 audio_channel_count_from_out_mask(mMixerChannelMask) : mChannelCount;
jiabinc658e452022-10-21 20:52:21 +00004118 if (mMixerBufferValid && (mEffectBufferValid || !mHasDataCopiedToSinkBuffer)) {
Andy Hung98ef9782014-03-04 14:46:50 -08004119 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
4120 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
4121
David Li88ee0902022-06-22 10:01:21 +08004122 // Apply mono blending and balancing if the effect buffer is not valid. Otherwise,
4123 // do these processes after effects are applied.
4124 if (!mEffectBufferValid) {
4125 // mono blend occurs for mixer threads only (not direct or offloaded)
4126 // and is handled here if we're going directly to the sink.
4127 if (requireMonoBlend()) {
4128 mono_blend(mMixerBuffer, mMixerBufferFormat, mChannelCount,
4129 mNormalFrameCount, true /*limit*/);
4130 }
Andy Hung2ddee192015-12-18 17:34:44 -08004131
David Li88ee0902022-06-22 10:01:21 +08004132 if (!hasFastMixer()) {
4133 // Balance must take effect after mono conversion.
4134 // We do it here if there is no FastMixer.
4135 // mBalance detects zero balance within the class for speed
4136 // (not needed here).
4137 mBalance.setBalance(mMasterBalance.load());
4138 mBalance.process((float *)mMixerBuffer, mNormalFrameCount);
4139 }
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01004140 }
4141
Andy Hung98ef9782014-03-04 14:46:50 -08004142 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
Eric Laurent39095982021-08-24 18:29:27 +02004143 mNormalFrameCount * (mixerChannelCount + mHapticChannelCount));
jiabin245cdd92018-12-07 17:55:15 -08004144
4145 // If we're going directly to the sink and there are haptic channels,
4146 // we should adjust channels as the sample data is partially interleaved
4147 // in this case.
4148 if (!mEffectBufferValid && mHapticChannelCount > 0) {
4149 adjust_channels_non_destructive(buffer, mChannelCount, buffer,
4150 mChannelCount + mHapticChannelCount,
4151 audio_bytes_per_sample(format),
4152 audio_bytes_per_frame(mChannelCount, format) * mNormalFrameCount);
4153 }
Andy Hung98ef9782014-03-04 14:46:50 -08004154 }
4155
Eric Laurentbfb1b832013-01-07 09:53:42 -08004156 mBytesRemaining = mCurrentWriteLength;
4157 if (isSuspended()) {
Andy Hung238fa3d2016-07-28 10:53:22 -07004158 // Simulate write to HAL when suspended (e.g. BT SCO phone call).
4159 mSleepTimeUs = suspendSleepTimeUs(); // assumes full buffer.
4160 const size_t framesRemaining = mBytesRemaining / mFrameSize;
4161 mBytesWritten += mBytesRemaining;
4162 mFramesWritten += framesRemaining;
4163 mSuspendedFrames += framesRemaining; // to adjust kernel HAL position
Eric Laurentbfb1b832013-01-07 09:53:42 -08004164 mBytesRemaining = 0;
4165 }
Eric Laurent81784c32012-11-19 14:55:58 -08004166
Eric Laurentbfb1b832013-01-07 09:53:42 -08004167 // only process effects if we're going to write
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004168 if (mSleepTimeUs == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004169 for (size_t i = 0; i < effectChains.size(); i ++) {
4170 effectChains[i]->process_l();
jiabin47affe52019-04-04 18:02:07 -07004171 // TODO: Write haptic data directly to sink buffer when mixing.
Andy Hung6e6a2e62019-04-30 16:38:41 -07004172 if (activeHapticSessionId != AUDIO_SESSION_NONE
4173 && activeHapticSessionId == effectChains[i]->sessionId()) {
jiabin47affe52019-04-04 18:02:07 -07004174 // Haptic data is active in this case, copy it directly from
4175 // in buffer to out buffer.
Eric Laurentb62d0362021-10-26 17:40:18 +02004176 uint32_t hapticSessionChannelCount = mEffectBufferValid ?
4177 audio_channel_count_from_out_mask(mMixerChannelMask) :
4178 mChannelCount;
4179 if (mType == SPATIALIZER && !isHapticSessionSpatialized) {
4180 hapticSessionChannelCount = mChannelCount;
4181 }
4182
jiabin47affe52019-04-04 18:02:07 -07004183 const size_t audioBufferSize = mNormalFrameCount
Eric Laurentb62d0362021-10-26 17:40:18 +02004184 * audio_bytes_per_frame(hapticSessionChannelCount,
Andy Hung319587b2023-05-23 14:01:03 -07004185 AUDIO_FORMAT_PCM_FLOAT);
jiabin47affe52019-04-04 18:02:07 -07004186 memcpy_by_audio_format(
4187 (uint8_t*)effectChains[i]->outBuffer() + audioBufferSize,
Andy Hung319587b2023-05-23 14:01:03 -07004188 AUDIO_FORMAT_PCM_FLOAT,
jiabin47affe52019-04-04 18:02:07 -07004189 (const uint8_t*)effectChains[i]->inBuffer() + audioBufferSize,
Andy Hung319587b2023-05-23 14:01:03 -07004190 AUDIO_FORMAT_PCM_FLOAT, mNormalFrameCount * mHapticChannelCount);
jiabin47affe52019-04-04 18:02:07 -07004191 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004192 }
Eric Laurent81784c32012-11-19 14:55:58 -08004193 }
4194 }
Eric Laurent59fe0102013-09-27 18:48:26 -07004195 // Process effect chains for offloaded thread even if no audio
4196 // was read from audio track: process only updates effect state
4197 // and thus does have to be synchronized with audio writes but may have
4198 // to be called while waiting for async write callback
4199 if (mType == OFFLOAD) {
4200 for (size_t i = 0; i < effectChains.size(); i ++) {
4201 effectChains[i]->process_l();
4202 }
4203 }
Eric Laurent81784c32012-11-19 14:55:58 -08004204
Andy Hung98ef9782014-03-04 14:46:50 -08004205 // Only if the Effects buffer is enabled and there is data in the
4206 // Effects buffer (buffer valid), we need to
4207 // copy into the sink buffer.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004208 // TODO use mSleepTimeUs == 0 as an additional condition.
jiabinc658e452022-10-21 20:52:21 +00004209 if (mEffectBufferValid && !mHasDataCopiedToSinkBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08004210 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
Eric Laurentb62d0362021-10-26 17:40:18 +02004211 void *effectBuffer = (mType == SPATIALIZER) ? mPostSpatializerBuffer : mEffectBuffer;
Andy Hung2ddee192015-12-18 17:34:44 -08004212 if (requireMonoBlend()) {
Eric Laurentb62d0362021-10-26 17:40:18 +02004213 mono_blend(effectBuffer, mEffectBufferFormat, mChannelCount, mNormalFrameCount,
Glenn Kasten03c48d52016-01-27 17:25:17 -08004214 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08004215 }
4216
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01004217 if (!hasFastMixer()) {
4218 // Balance must take effect after mono conversion.
4219 // We do it here if there is no FastMixer.
4220 // mBalance detects zero balance within the class for speed (not needed here).
4221 mBalance.setBalance(mMasterBalance.load());
Eric Laurentb62d0362021-10-26 17:40:18 +02004222 mBalance.process((float *)effectBuffer, mNormalFrameCount);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01004223 }
4224
Eric Laurentb62d0362021-10-26 17:40:18 +02004225 // for SPATIALIZER thread, Move haptics channels from mEffectBuffer to
4226 // mPostSpatializerBuffer if the haptics track is spatialized.
4227 // Otherwise, the haptics channels are already in mPostSpatializerBuffer.
4228 // For other thread types, the haptics channels are already in mEffectBuffer.
4229 if (mType == SPATIALIZER && isHapticSessionSpatialized) {
4230 const size_t srcBufferSize = mNormalFrameCount *
4231 audio_bytes_per_frame(audio_channel_count_from_out_mask(mMixerChannelMask),
4232 mEffectBufferFormat);
4233 const size_t dstBufferSize = mNormalFrameCount
4234 * audio_bytes_per_frame(mChannelCount, mEffectBufferFormat);
4235
4236 memcpy_by_audio_format((uint8_t*)mPostSpatializerBuffer + dstBufferSize,
4237 mEffectBufferFormat,
4238 (uint8_t*)mEffectBuffer + srcBufferSize,
4239 mEffectBufferFormat,
4240 mNormalFrameCount * mHapticChannelCount);
Eric Laurent39095982021-08-24 18:29:27 +02004241 }
Atneya Nairba9a1072022-09-19 17:51:37 -07004242 const size_t framesToCopy = mNormalFrameCount * (mChannelCount + mHapticChannelCount);
4243 if (mFormat == AUDIO_FORMAT_PCM_FLOAT &&
4244 mEffectBufferFormat == AUDIO_FORMAT_PCM_FLOAT) {
4245 // Clamp PCM float values more than this distance from 0 to insulate
4246 // a HAL which doesn't handle NaN correctly.
4247 static constexpr float HAL_FLOAT_SAMPLE_LIMIT = 2.0f;
4248 memcpy_to_float_from_float_with_clamping(static_cast<float*>(mSinkBuffer),
4249 static_cast<const float*>(effectBuffer),
4250 framesToCopy, HAL_FLOAT_SAMPLE_LIMIT /* absMax */);
4251 } else {
4252 memcpy_by_audio_format(mSinkBuffer, mFormat,
4253 effectBuffer, mEffectBufferFormat, framesToCopy);
4254 }
jiabin245cdd92018-12-07 17:55:15 -08004255 // The sample data is partially interleaved when haptic channels exist,
4256 // we need to adjust channels here.
4257 if (mHapticChannelCount > 0) {
4258 adjust_channels_non_destructive(mSinkBuffer, mChannelCount, mSinkBuffer,
4259 mChannelCount + mHapticChannelCount,
4260 audio_bytes_per_sample(mFormat),
4261 audio_bytes_per_frame(mChannelCount, mFormat) * mNormalFrameCount);
4262 }
Andy Hung98ef9782014-03-04 14:46:50 -08004263 }
4264
Eric Laurent81784c32012-11-19 14:55:58 -08004265 // enable changes in effect chain
4266 unlockEffectChains(effectChains);
4267
Vlad Popafce10862023-02-03 10:37:07 +01004268 if (!metadataUpdate.playbackMetadataUpdate.empty()) {
Andy Hung583043b2023-07-17 17:05:00 -07004269 mAfThreadCallback->getMelReporter()->updateMetadataForCsd(id(),
Vlad Popafce10862023-02-03 10:37:07 +01004270 metadataUpdate.playbackMetadataUpdate);
4271 }
4272
Eric Laurentbfb1b832013-01-07 09:53:42 -08004273 if (!waitingAsyncCallback()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004274 // mSleepTimeUs == 0 means we must write to audio hardware
4275 if (mSleepTimeUs == 0) {
Andy Hung08fb1742015-05-31 23:22:10 -07004276 ssize_t ret = 0;
Andy Hung446f4df2019-02-21 12:26:41 -08004277 // writePeriodNs is updated >= 0 when ret > 0.
4278 int64_t writePeriodNs = -1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004279 if (mBytesRemaining) {
Andy Hung69488c42016-05-16 18:43:33 -07004280 // FIXME rewrite to reduce number of system calls
Andy Hung446f4df2019-02-21 12:26:41 -08004281 const int64_t lastIoBeginNs = systemTime();
Andy Hung08fb1742015-05-31 23:22:10 -07004282 ret = threadLoop_write();
Andy Hung446f4df2019-02-21 12:26:41 -08004283 const int64_t lastIoEndNs = systemTime();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004284 if (ret < 0) {
4285 mBytesRemaining = 0;
Andy Hung446f4df2019-02-21 12:26:41 -08004286 } else if (ret > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004287 mBytesWritten += ret;
4288 mBytesRemaining -= ret;
Andy Hung446f4df2019-02-21 12:26:41 -08004289 const int64_t frames = ret / mFrameSize;
4290 mFramesWritten += frames;
4291
4292 writePeriodNs = lastIoEndNs - mLastIoEndNs;
4293 // process information relating to write time.
4294 if (audio_has_proportional_frames(mFormat)) {
4295 // we are in a continuous mixing cycle
4296 if (mMixerStatus == MIXER_TRACKS_READY &&
4297 loopCount == lastLoopCountWritten + 1) {
4298
4299 const double jitterMs =
4300 TimestampVerifier<int64_t, int64_t>::computeJitterMs(
4301 {frames, writePeriodNs},
4302 {0, 0} /* lastTimestamp */, mSampleRate);
4303 const double processMs =
4304 (lastIoBeginNs - mLastIoEndNs) * 1e-6;
4305
4306 Mutex::Autolock _l(mLock);
4307 mIoJitterMs.add(jitterMs);
4308 mProcessTimeMs.add(processMs);
Robert Wu06db0a32021-08-10 19:05:34 +00004309
4310 if (mPipeSink.get() != nullptr) {
4311 // Using the Monopipe availableToWrite, we estimate the current
4312 // buffer size.
4313 MonoPipe* monoPipe = static_cast<MonoPipe*>(mPipeSink.get());
4314 const ssize_t
4315 availableToWrite = mPipeSink->availableToWrite();
4316 const size_t pipeFrames = monoPipe->maxFrames();
4317 const size_t
4318 remainingFrames = pipeFrames - max(availableToWrite, 0);
4319 mMonopipePipeDepthStats.add(remainingFrames);
4320 }
Andy Hung446f4df2019-02-21 12:26:41 -08004321 }
4322
4323 // write blocked detection
4324 const int64_t deltaWriteNs = lastIoEndNs - lastIoBeginNs;
Andy Hungd3639922022-04-28 18:00:49 -07004325 if ((mType == MIXER || mType == SPATIALIZER)
4326 && deltaWriteNs > maxPeriod) {
Andy Hung446f4df2019-02-21 12:26:41 -08004327 mNumDelayedWrites++;
4328 if ((lastIoEndNs - lastWarning) > kWarningThrottleNs) {
4329 ATRACE_NAME("underrun");
4330 ALOGW("write blocked for %lld msecs, "
4331 "%d delayed writes, thread %d",
4332 (long long)deltaWriteNs / NANOS_PER_MILLISECOND,
4333 mNumDelayedWrites, mId);
4334 lastWarning = lastIoEndNs;
4335 }
4336 }
4337 }
4338 // update timing info.
4339 mLastIoBeginNs = lastIoBeginNs;
4340 mLastIoEndNs = lastIoEndNs;
4341 lastLoopCountWritten = loopCount;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004342 }
4343 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
4344 (mMixerStatus == MIXER_DRAIN_ALL)) {
4345 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08004346 }
Andy Hungd3639922022-04-28 18:00:49 -07004347 if ((mType == MIXER || mType == SPATIALIZER) && !mStandby) {
Andy Hung08fb1742015-05-31 23:22:10 -07004348
4349 if (mThreadThrottle
4350 && mMixerStatus == MIXER_TRACKS_READY // we are mixing (active tracks)
Andy Hung446f4df2019-02-21 12:26:41 -08004351 && writePeriodNs > 0) { // we have write period info
Andy Hung08fb1742015-05-31 23:22:10 -07004352 // Limit MixerThread data processing to no more than twice the
4353 // expected processing rate.
4354 //
4355 // This helps prevent underruns with NuPlayer and other applications
4356 // which may set up buffers that are close to the minimum size, or use
4357 // deep buffers, and rely on a double-buffering sleep strategy to fill.
4358 //
4359 // The throttle smooths out sudden large data drains from the device,
4360 // e.g. when it comes out of standby, which often causes problems with
4361 // (1) mixer threads without a fast mixer (which has its own warm-up)
4362 // (2) minimum buffer sized tracks (even if the track is full,
4363 // the app won't fill fast enough to handle the sudden draw).
Haynes Mathew Georgef92b2172016-05-09 11:34:15 -07004364 //
4365 // Total time spent in last processing cycle equals time spent in
4366 // 1. threadLoop_write, as well as time spent in
4367 // 2. threadLoop_mix (significant for heavy mixing, especially
4368 // on low tier processors)
Andy Hung08fb1742015-05-31 23:22:10 -07004369
Andy Hung446f4df2019-02-21 12:26:41 -08004370 // it's OK if deltaMs is an overestimate.
4371
4372 const int32_t deltaMs = writePeriodNs / NANOS_PER_MILLISECOND;
Ivan Lozanoe02bc542017-10-26 09:51:54 -07004373
Ivan Lozanoea04d392017-11-07 14:37:07 -08004374 const int32_t throttleMs = (int32_t)mHalfBufferMs - deltaMs;
Andy Hung08fb1742015-05-31 23:22:10 -07004375 if ((signed)mHalfBufferMs >= throttleMs && throttleMs > 0) {
Andy Hungcf10d742020-04-28 15:38:24 -07004376 mThreadMetrics.logThrottleMs((double)throttleMs);
Andy Hungb68f5eb2019-12-03 16:49:17 -08004377
Andy Hung08fb1742015-05-31 23:22:10 -07004378 usleep(throttleMs * 1000);
Andy Hung40eb1a12015-06-18 13:42:02 -07004379 // notify of throttle start on verbose log
4380 ALOGV_IF(mThreadThrottleEndMs == mThreadThrottleTimeMs,
4381 "mixer(%p) throttle begin:"
4382 " ret(%zd) deltaMs(%d) requires sleep %d ms",
Andy Hung08fb1742015-05-31 23:22:10 -07004383 this, ret, deltaMs, throttleMs);
Andy Hung40eb1a12015-06-18 13:42:02 -07004384 mThreadThrottleTimeMs += throttleMs;
Andy Hung0a31ddd2016-07-06 19:10:29 -07004385 // Throttle must be attributed to the previous mixer loop's write time
4386 // to allow back-to-back throttling.
Andy Hung446f4df2019-02-21 12:26:41 -08004387 // This also ensures proper timing statistics.
4388 mLastIoEndNs = systemTime(); // we fetch the write end time again.
Andy Hung40eb1a12015-06-18 13:42:02 -07004389 } else {
4390 uint32_t diff = mThreadThrottleTimeMs - mThreadThrottleEndMs;
4391 if (diff > 0) {
4392 // notify of throttle end on debug log
Andy Hung3ea004d2016-05-05 16:48:37 -07004393 // but prevent spamming for bluetooth
jiabinc52b1ff2019-10-31 17:20:42 -07004394 ALOGD_IF(!isSingleDeviceType(
4395 outDeviceTypes(), audio_is_a2dp_out_device) &&
4396 !isSingleDeviceType(
4397 outDeviceTypes(), audio_is_hearing_aid_out_device),
Andy Hung3ea004d2016-05-05 16:48:37 -07004398 "mixer(%p) throttle end: throttle time(%u)", this, diff);
Andy Hung40eb1a12015-06-18 13:42:02 -07004399 mThreadThrottleEndMs = mThreadThrottleTimeMs;
4400 }
Andy Hung08fb1742015-05-31 23:22:10 -07004401 }
4402 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004403 }
Eric Laurent81784c32012-11-19 14:55:58 -08004404
Eric Laurentbfb1b832013-01-07 09:53:42 -08004405 } else {
Glenn Kastene7754022014-10-31 12:11:26 -07004406 ATRACE_BEGIN("sleep");
Eric Laurente93cc032016-05-05 10:15:10 -07004407 Mutex::Autolock _l(mLock);
rago1bb90822017-05-02 18:31:48 -07004408 // suspended requires accurate metering of sleep time.
4409 if (isSuspended()) {
4410 // advance by expected sleepTime
4411 timeLoopNextNs += microseconds((nsecs_t)mSleepTimeUs);
4412 const nsecs_t nowNs = systemTime();
4413
4414 // compute expected next time vs current time.
4415 // (negative deltas are treated as delays).
4416 nsecs_t deltaNs = timeLoopNextNs - nowNs;
4417 if (deltaNs < -kMaxNextBufferDelayNs) {
4418 // Delays longer than the max allowed trigger a reset.
4419 ALOGV("DelayNs: %lld, resetting timeLoopNextNs", (long long) deltaNs);
4420 deltaNs = microseconds((nsecs_t)mSleepTimeUs);
4421 timeLoopNextNs = nowNs + deltaNs;
4422 } else if (deltaNs < 0) {
4423 // Delays within the max delay allowed: zero the delta/sleepTime
4424 // to help the system catch up in the next iteration(s)
4425 ALOGV("DelayNs: %lld, catching-up", (long long) deltaNs);
4426 deltaNs = 0;
4427 }
4428 // update sleep time (which is >= 0)
4429 mSleepTimeUs = deltaNs / 1000;
4430 }
Eric Laurente93cc032016-05-05 10:15:10 -07004431 if (!mSignalPending && mConfigEvents.isEmpty() && !exitPending()) {
4432 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)mSleepTimeUs));
Eric Laurent51716182016-02-29 18:00:56 -08004433 }
Glenn Kastene7754022014-10-31 12:11:26 -07004434 ATRACE_END();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004435 }
Eric Laurent81784c32012-11-19 14:55:58 -08004436 }
4437
4438 // Finally let go of removed track(s), without the lock held
4439 // since we can't guarantee the destructors won't acquire that
4440 // same lock. This will also mutate and push a new fast mixer state.
4441 threadLoop_removeTracks(tracksToRemove);
4442 tracksToRemove.clear();
4443
4444 // FIXME I don't understand the need for this here;
4445 // it was in the original code but maybe the
4446 // assignment in saveOutputTracks() makes this unnecessary?
4447 clearOutputTracks();
4448
4449 // Effect chains will be actually deleted here if they were removed from
4450 // mEffectChains list during mixing or effects processing
4451 effectChains.clear();
4452
4453 // FIXME Note that the above .clear() is no longer necessary since effectChains
4454 // is now local to this block, but will keep it for now (at least until merge done).
4455 }
4456
Eric Laurentbfb1b832013-01-07 09:53:42 -08004457 threadLoop_exit();
4458
Eric Laurentcf817a22014-08-04 20:36:31 -07004459 if (!mStandby) {
4460 threadLoop_standby();
Eric Laurent19952e12023-04-20 10:08:29 +02004461 setStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08004462 }
4463
4464 releaseWakeLock();
4465
4466 ALOGV("Thread %p type %d exiting", this, mType);
4467 return false;
4468}
4469
Andy Hungee58e4a2023-07-07 13:47:37 -07004470void PlaybackThread::collectTimestamps_l()
Dean Wheatley12473e92021-03-18 23:00:55 +11004471{
Dean Wheatley12473e92021-03-18 23:00:55 +11004472 if (mStandby) {
4473 mTimestampVerifier.discontinuity(discontinuityForStandbyOrFlush());
4474 return;
4475 } else if (mHwPaused) {
4476 mTimestampVerifier.discontinuity(mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS);
4477 return;
4478 }
4479
4480 // Gather the framesReleased counters for all active tracks,
4481 // and associate with the sink frames written out. We need
4482 // this to convert the sink timestamp to the track timestamp.
4483 bool kernelLocationUpdate = false;
4484 ExtendedTimestamp timestamp; // use private copy to fetch
4485
4486 // Always query HAL timestamp and update timestamp verifier. In standby or pause,
4487 // HAL may be draining some small duration buffered data for fade out.
4488 if (threadloop_getHalTimestamp_l(&timestamp) == OK) {
4489 mTimestampVerifier.add(timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL],
4490 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4491 mSampleRate);
4492
4493 if (isTimestampCorrectionEnabled()) {
4494 ALOGVV("TS_BEFORE: %d %lld %lld", id(),
4495 (long long)timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4496 (long long)timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]);
4497 auto correctedTimestamp = mTimestampVerifier.getLastCorrectedTimestamp();
4498 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4499 = correctedTimestamp.mFrames;
4500 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]
4501 = correctedTimestamp.mTimeNs;
4502 ALOGVV("TS_AFTER: %d %lld %lld", id(),
4503 (long long)timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4504 (long long)timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]);
4505
4506 // Note: Downstream latency only added if timestamp correction enabled.
4507 if (mDownstreamLatencyStatMs.getN() > 0) { // we have latency info.
4508 const int64_t newPosition =
4509 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4510 - int64_t(mDownstreamLatencyStatMs.getMean() * mSampleRate * 1e-3);
4511 // prevent retrograde
4512 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = max(
4513 newPosition,
4514 (mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4515 - mSuspendedFrames));
4516 }
4517 }
4518
4519 // We always fetch the timestamp here because often the downstream
4520 // sink will block while writing.
4521
4522 // We keep track of the last valid kernel position in case we are in underrun
4523 // and the normal mixer period is the same as the fast mixer period, or there
4524 // is some error from the HAL.
4525 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
4526 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
4527 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
4528 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
4529 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4530
4531 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
4532 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER];
4533 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
4534 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER];
4535 }
4536
4537 if (timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
4538 kernelLocationUpdate = true;
4539 } else {
4540 ALOGVV("getTimestamp error - no valid kernel position");
4541 }
4542
4543 // copy over kernel info
4544 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] =
4545 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4546 + mSuspendedFrames; // add frames discarded when suspended
4547 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] =
4548 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4549 } else {
4550 mTimestampVerifier.error();
4551 }
4552
4553 // mFramesWritten for non-offloaded tracks are contiguous
4554 // even after standby() is called. This is useful for the track frame
4555 // to sink frame mapping.
4556 bool serverLocationUpdate = false;
4557 if (mFramesWritten != mLastFramesWritten) {
4558 serverLocationUpdate = true;
4559 mLastFramesWritten = mFramesWritten;
4560 }
4561 // Only update timestamps if there is a meaningful change.
4562 // Either the kernel timestamp must be valid or we have written something.
4563 if (kernelLocationUpdate || serverLocationUpdate) {
4564 if (serverLocationUpdate) {
4565 // use the time before we called the HAL write - it is a bit more accurate
4566 // to when the server last read data than the current time here.
4567 //
4568 // If we haven't written anything, mLastIoBeginNs will be -1
4569 // and we use systemTime().
4570 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] = mFramesWritten;
4571 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = mLastIoBeginNs == -1
4572 ? systemTime() : mLastIoBeginNs;
4573 }
4574
Andy Hung8d31fd22023-06-26 19:20:57 -07004575 for (const sp<IAfTrack>& t : mActiveTracks) {
Dean Wheatley12473e92021-03-18 23:00:55 +11004576 if (!t->isFastTrack()) {
4577 t->updateTrackFrameInfo(
Andy Hung8d31fd22023-06-26 19:20:57 -07004578 t->audioTrackServerProxy()->framesReleased(),
Dean Wheatley12473e92021-03-18 23:00:55 +11004579 mFramesWritten,
4580 mSampleRate,
4581 mTimestamp);
4582 }
4583 }
4584 }
4585
4586 if (audio_has_proportional_frames(mFormat)) {
4587 const double latencyMs = mTimestamp.getOutputServerLatencyMs(mSampleRate);
4588 if (latencyMs != 0.) { // note 0. means timestamp is empty.
4589 mLatencyMs.add(latencyMs);
4590 }
4591 }
4592#if 0
4593 // logFormat example
4594 if (z % 100 == 0) {
4595 timespec ts;
4596 clock_gettime(CLOCK_MONOTONIC, &ts);
4597 LOGT("This is an integer %d, this is a float %f, this is my "
4598 "pid %p %% %s %t", 42, 3.14, "and this is a timestamp", ts);
4599 LOGT("A deceptive null-terminated string %\0");
4600 }
4601 ++z;
4602#endif
4603}
4604
Eric Laurentbfb1b832013-01-07 09:53:42 -08004605// removeTracks_l() must be called with ThreadBase::mLock held
Andy Hungee58e4a2023-07-07 13:47:37 -07004606void PlaybackThread::removeTracks_l(const Vector<sp<IAfTrack>>& tracksToRemove)
Andy Hung920f6572022-10-06 12:09:49 -07004607NO_THREAD_SAFETY_ANALYSIS // release and re-acquire mLock
Eric Laurentbfb1b832013-01-07 09:53:42 -08004608{
Andy Hungfe726a62018-09-27 15:17:25 -07004609 for (const auto& track : tracksToRemove) {
4610 mActiveTracks.remove(track);
4611 ALOGV("%s(%d): removing track on session %d", __func__, track->id(), track->sessionId());
Andy Hung116bc262023-06-20 18:56:17 -07004612 sp<IAfEffectChain> chain = getEffectChain_l(track->sessionId());
Andy Hungfe726a62018-09-27 15:17:25 -07004613 if (chain != 0) {
4614 ALOGV("%s(%d): stopping track on chain %p for session Id: %d",
4615 __func__, track->id(), chain.get(), track->sessionId());
4616 chain->decActiveTrackCnt();
4617 }
4618 // If an external client track, inform APM we're no longer active, and remove if needed.
4619 // We do this under lock so that the state is consistent if the Track is destroyed.
4620 if (track->isExternalTrack()) {
4621 AudioSystem::stopOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08004622 if (track->isTerminated()) {
Andy Hungfe726a62018-09-27 15:17:25 -07004623 AudioSystem::releaseOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08004624 }
4625 }
Andy Hungfe726a62018-09-27 15:17:25 -07004626 if (track->isTerminated()) {
4627 // remove from our tracks vector
4628 removeTrack_l(track);
4629 }
jiabineb3bda02020-06-30 14:07:03 -07004630 if (mHapticChannelCount > 0 &&
4631 ((track->channelMask() & AUDIO_CHANNEL_HAPTIC_ALL) != AUDIO_CHANNEL_NONE
4632 || (chain != nullptr && chain->containsHapticGeneratingEffect_l()))) {
jiabin57303cc2018-12-18 15:45:57 -08004633 mLock.unlock();
4634 // Unlock due to VibratorService will lock for this call and will
4635 // call Tracks.mute/unmute which also require thread's lock.
4636 AudioFlinger::onExternalVibrationStop(track->getExternalVibration());
4637 mLock.lock();
jiabine70bc7f2020-06-30 22:07:55 -07004638
4639 // When the track is stop, set the haptic intensity as MUTE
4640 // for the HapticGenerator effect.
4641 if (chain != nullptr) {
Simon Bowden62823412022-10-17 14:52:26 +00004642 chain->setHapticIntensity_l(track->id(), os::HapticScale::MUTE);
jiabine70bc7f2020-06-30 22:07:55 -07004643 }
jiabin245cdd92018-12-07 17:55:15 -08004644 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004645 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004646}
Eric Laurent81784c32012-11-19 14:55:58 -08004647
Andy Hungee58e4a2023-07-07 13:47:37 -07004648status_t PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
Eric Laurentaccc1472013-09-20 09:36:34 -07004649{
4650 if (mNormalSink != 0) {
Andy Hung818e7a32016-02-16 18:08:07 -08004651 ExtendedTimestamp ets;
4652 status_t status = mNormalSink->getTimestamp(ets);
4653 if (status == NO_ERROR) {
4654 status = ets.getBestTimestamp(&timestamp);
4655 }
4656 return status;
Eric Laurentaccc1472013-09-20 09:36:34 -07004657 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004658 if ((mType == OFFLOAD || mType == DIRECT) && mOutput != NULL) {
Dean Wheatley12473e92021-03-18 23:00:55 +11004659 collectTimestamps_l();
4660 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] <= 0) {
4661 return INVALID_OPERATION;
Eric Laurentaccc1472013-09-20 09:36:34 -07004662 }
Dean Wheatley12473e92021-03-18 23:00:55 +11004663 timestamp.mPosition = mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
4664 const int64_t timeNs = mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4665 timestamp.mTime.tv_sec = timeNs / NANOS_PER_SECOND;
4666 timestamp.mTime.tv_nsec = timeNs - (timestamp.mTime.tv_sec * NANOS_PER_SECOND);
4667 return NO_ERROR;
Eric Laurentaccc1472013-09-20 09:36:34 -07004668 }
4669 return INVALID_OPERATION;
4670}
Eric Laurent1c333e22014-05-20 10:48:17 -07004671
Eric Laurenteab90452019-06-24 15:17:46 -07004672// For dedicated VoIP outputs, let the HAL apply the stream volume. Track volume is
4673// still applied by the mixer.
4674// All tracks attached to a mixer with flag VOIP_RX are tied to the same
4675// stream type STREAM_VOICE_CALL so this will only change the HAL volume once even
4676// if more than one track are active
Andy Hungee58e4a2023-07-07 13:47:37 -07004677status_t PlaybackThread::handleVoipVolume_l(float* volume)
Eric Laurenteab90452019-06-24 15:17:46 -07004678{
4679 status_t result = NO_ERROR;
4680 if ((mOutput->flags & AUDIO_OUTPUT_FLAG_VOIP_RX) != 0) {
4681 if (*volume != mLeftVolFloat) {
4682 result = mOutput->stream->setVolume(*volume, *volume);
Alex Leungc5dedb22023-05-10 08:00:50 -07004683 // HAL can return INVALID_OPERATION if operation is not supported.
4684 ALOGE_IF(result != OK && result != INVALID_OPERATION,
Eric Laurenteab90452019-06-24 15:17:46 -07004685 "Error when setting output stream volume: %d", result);
4686 if (result == NO_ERROR) {
4687 mLeftVolFloat = *volume;
4688 }
4689 }
4690 // if stream volume was successfully sent to the HAL, mLeftVolFloat == v here and we
4691 // remove stream volume contribution from software volume.
4692 if (mLeftVolFloat == *volume) {
4693 *volume = 1.0f;
4694 }
4695 }
4696 return result;
4697}
4698
Andy Hungee58e4a2023-07-07 13:47:37 -07004699status_t MixerThread::createAudioPatch_l(const struct audio_patch* patch,
Eric Laurent054d9d32015-04-24 08:48:48 -07004700 audio_patch_handle_t *handle)
4701{
Andy Hungf60abce2016-08-26 11:37:54 -07004702 status_t status;
4703 if (property_get_bool("af.patch_park", false /* default_value */)) {
4704 // Park FastMixer to avoid potential DOS issues with writing to the HAL
4705 // or if HAL does not properly lock against access.
4706 AutoPark<FastMixer> park(mFastMixer);
4707 status = PlaybackThread::createAudioPatch_l(patch, handle);
4708 } else {
4709 status = PlaybackThread::createAudioPatch_l(patch, handle);
4710 }
Eric Laurentb0463942022-12-20 16:31:10 +01004711
4712 updateHalSupportedLatencyModes_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07004713 return status;
4714}
4715
Andy Hungee58e4a2023-07-07 13:47:37 -07004716status_t PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
Eric Laurent1c333e22014-05-20 10:48:17 -07004717 audio_patch_handle_t *handle)
4718{
4719 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07004720
4721 // store new device and send to effects
4722 audio_devices_t type = AUDIO_DEVICE_NONE;
jiabinc52b1ff2019-10-31 17:20:42 -07004723 AudioDeviceTypeAddrVector deviceTypeAddrs;
Eric Laurent054d9d32015-04-24 08:48:48 -07004724 for (unsigned int i = 0; i < patch->num_sinks; i++) {
jiabinc52b1ff2019-10-31 17:20:42 -07004725 LOG_ALWAYS_FATAL_IF(popcount(patch->sinks[i].ext.device.type) > 1
4726 && !mOutput->audioHwDev->supportsAudioPatches(),
4727 "Enumerated device type(%#x) must not be used "
4728 "as it does not support audio patches",
4729 patch->sinks[i].ext.device.type);
Mikhail Naganov55773032020-10-01 15:08:13 -07004730 type = static_cast<audio_devices_t>(type | patch->sinks[i].ext.device.type);
Andy Hung920f6572022-10-06 12:09:49 -07004731 deviceTypeAddrs.emplace_back(patch->sinks[i].ext.device.type,
4732 patch->sinks[i].ext.device.address);
Eric Laurent054d9d32015-04-24 08:48:48 -07004733 }
4734
François Gaffie0c280aa2018-07-25 10:02:15 +02004735 audio_port_handle_t sinkPortId = patch->sinks[0].id;
Eric Laurent054d9d32015-04-24 08:48:48 -07004736#ifdef ADD_BATTERY_DATA
4737 // when changing the audio output device, call addBatteryData to notify
4738 // the change
jiabinc52b1ff2019-10-31 17:20:42 -07004739 if (outDeviceTypes() != deviceTypes) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004740 uint32_t params = 0;
4741 // check whether speaker is on
jiabinc52b1ff2019-10-31 17:20:42 -07004742 if (deviceTypes.count(AUDIO_DEVICE_OUT_SPEAKER) > 0) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004743 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent1c333e22014-05-20 10:48:17 -07004744 }
4745
Eric Laurent054d9d32015-04-24 08:48:48 -07004746 // check if any other device (except speaker) is on
jiabinc52b1ff2019-10-31 17:20:42 -07004747 if (!isSingleDeviceType(deviceTypes, AUDIO_DEVICE_OUT_SPEAKER)) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004748 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
4749 }
4750
4751 if (params != 0) {
4752 addBatteryData(params);
4753 }
4754 }
4755#endif
4756
4757 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08004758 mEffectChains[i]->setDevices_l(deviceTypeAddrs);
Eric Laurent054d9d32015-04-24 08:48:48 -07004759 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07004760
jiabinc52b1ff2019-10-31 17:20:42 -07004761 // mPatch.num_sinks is not set when the thread is created so that
4762 // the first patch creation triggers an ioConfigChanged callback
4763 bool configChanged = (mPatch.num_sinks == 0) ||
4764 (mPatch.sinks[0].id != sinkPortId);
Eric Laurent296fb132015-05-01 11:38:42 -07004765 mPatch = *patch;
jiabinc52b1ff2019-10-31 17:20:42 -07004766 mOutDeviceTypeAddrs = deviceTypeAddrs;
jiabin0a957d32020-04-29 10:56:20 -07004767 checkSilentMode_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07004768
Mikhail Naganov9ee05402016-10-13 15:58:17 -07004769 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07004770 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
4771 status = hwDevice->createAudioPatch(patch->num_sources,
4772 patch->sources,
4773 patch->num_sinks,
4774 patch->sinks,
4775 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07004776 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08004777 status = mOutput->stream->legacyCreateAudioPatch(patch->sinks[0], std::nullopt, type);
Eric Laurent054d9d32015-04-24 08:48:48 -07004778 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07004779 }
Andy Hungc2b11cb2020-04-22 09:04:01 -07004780 const std::string patchSinksAsString = patchSinksToString(patch);
Andy Hungcf10d742020-04-28 15:38:24 -07004781
4782 mThreadMetrics.logEndInterval();
Andy Hungea840382020-05-05 21:50:17 -07004783 mThreadMetrics.logCreatePatch(/* inDevices */ {}, patchSinksAsString);
Andy Hungcf10d742020-04-28 15:38:24 -07004784 mThreadMetrics.logBeginInterval();
Andy Hungc2b11cb2020-04-22 09:04:01 -07004785 // also dispatch to active AudioTracks for MediaMetrics
4786 for (const auto &track : mActiveTracks) {
4787 track->logEndInterval();
4788 track->logBeginInterval(patchSinksAsString);
4789 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08004790
Eric Laurente8726fe2015-06-26 09:39:24 -07004791 if (configChanged) {
4792 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
4793 }
Vlad Popa7e81cea2023-01-19 16:34:16 +01004794 // Force metadata update after a route change
Eric Laurentdda206a2022-07-08 17:28:35 +02004795 mActiveTracks.setHasChanged();
4796
Eric Laurent1c333e22014-05-20 10:48:17 -07004797 return status;
4798}
4799
Andy Hungee58e4a2023-07-07 13:47:37 -07004800status_t MixerThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
Eric Laurent054d9d32015-04-24 08:48:48 -07004801{
Andy Hungf60abce2016-08-26 11:37:54 -07004802 status_t status;
4803 if (property_get_bool("af.patch_park", false /* default_value */)) {
4804 // Park FastMixer to avoid potential DOS issues with writing to the HAL
4805 // or if HAL does not properly lock against access.
4806 AutoPark<FastMixer> park(mFastMixer);
4807 status = PlaybackThread::releaseAudioPatch_l(handle);
4808 } else {
4809 status = PlaybackThread::releaseAudioPatch_l(handle);
4810 }
Eric Laurent054d9d32015-04-24 08:48:48 -07004811 return status;
4812}
4813
Andy Hungee58e4a2023-07-07 13:47:37 -07004814status_t PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004815{
4816 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07004817
jiabinc52b1ff2019-10-31 17:20:42 -07004818 mPatch = audio_patch{};
4819 mOutDeviceTypeAddrs.clear();
Eric Laurent054d9d32015-04-24 08:48:48 -07004820
Mikhail Naganov9ee05402016-10-13 15:58:17 -07004821 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07004822 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
4823 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07004824 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08004825 status = mOutput->stream->legacyReleaseAudioPatch();
Eric Laurent1c333e22014-05-20 10:48:17 -07004826 }
Eric Laurentdda206a2022-07-08 17:28:35 +02004827 // Force meteadata update after a route change
4828 mActiveTracks.setHasChanged();
4829
Eric Laurent1c333e22014-05-20 10:48:17 -07004830 return status;
4831}
4832
Andy Hungee58e4a2023-07-07 13:47:37 -07004833void PlaybackThread::addPatchTrack(const sp<IAfPatchTrack>& track)
Eric Laurent83b88082014-06-20 18:31:16 -07004834{
4835 Mutex::Autolock _l(mLock);
4836 mTracks.add(track);
4837}
4838
Andy Hungee58e4a2023-07-07 13:47:37 -07004839void PlaybackThread::deletePatchTrack(const sp<IAfPatchTrack>& track)
Eric Laurent83b88082014-06-20 18:31:16 -07004840{
4841 Mutex::Autolock _l(mLock);
4842 destroyTrack_l(track);
4843}
4844
Andy Hungee58e4a2023-07-07 13:47:37 -07004845void PlaybackThread::toAudioPortConfig(struct audio_port_config* config)
Eric Laurent83b88082014-06-20 18:31:16 -07004846{
Mikhail Naganovdc769682018-05-04 15:34:08 -07004847 ThreadBase::toAudioPortConfig(config);
Eric Laurent83b88082014-06-20 18:31:16 -07004848 config->role = AUDIO_PORT_ROLE_SOURCE;
4849 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
4850 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07004851 if (mOutput && mOutput->flags != AUDIO_OUTPUT_FLAG_NONE) {
4852 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
4853 config->flags.output = mOutput->flags;
4854 }
Eric Laurent83b88082014-06-20 18:31:16 -07004855}
4856
Eric Laurent81784c32012-11-19 14:55:58 -08004857// ----------------------------------------------------------------------------
4858
Andy Hungee58e4a2023-07-07 13:47:37 -07004859/* static */
4860sp<IAfPlaybackThread> IAfPlaybackThread::createMixerThread(
Andy Hung583043b2023-07-17 17:05:00 -07004861 const sp<IAfThreadCallback>& afThreadCallback, AudioStreamOut* output,
Andy Hungee58e4a2023-07-07 13:47:37 -07004862 audio_io_handle_t id, bool systemReady, type_t type, audio_config_base_t* mixerConfig) {
Andy Hung583043b2023-07-17 17:05:00 -07004863 return sp<MixerThread>::make(afThreadCallback, output, id, systemReady, type, mixerConfig);
Andy Hungee58e4a2023-07-07 13:47:37 -07004864}
4865
Andy Hung583043b2023-07-17 17:05:00 -07004866MixerThread::MixerThread(const sp<IAfThreadCallback>& afThreadCallback, AudioStreamOut* output,
Eric Laurentf1f22e72021-07-13 14:04:14 +02004867 audio_io_handle_t id, bool systemReady, type_t type, audio_config_base_t *mixerConfig)
Andy Hung583043b2023-07-17 17:05:00 -07004868 : PlaybackThread(afThreadCallback, output, id, type, systemReady, mixerConfig),
Eric Laurent81784c32012-11-19 14:55:58 -08004869 // mAudioMixer below
4870 // mFastMixer below
Eric Laurentb0463942022-12-20 16:31:10 +01004871 mBluetoothLatencyModesEnabled(false),
Andy Hung2ddee192015-12-18 17:34:44 -08004872 mFastMixerFutex(0),
4873 mMasterMono(false)
Eric Laurent81784c32012-11-19 14:55:58 -08004874 // mOutputSink below
4875 // mPipeSink below
4876 // mNormalSink below
4877{
Andy Hung583043b2023-07-17 17:05:00 -07004878 setMasterBalance(afThreadCallback->getMasterBalance_l());
jiabinc52b1ff2019-10-31 17:20:42 -07004879 ALOGV("MixerThread() id=%d type=%d", id, type);
Glenn Kasten49f36ba2017-12-06 13:02:02 -08004880 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%#x, mFrameSize=%zu, "
Glenn Kastenc42e9b42016-03-21 11:35:03 -07004881 "mFrameCount=%zu, mNormalFrameCount=%zu",
Eric Laurent81784c32012-11-19 14:55:58 -08004882 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
4883 mNormalFrameCount);
4884 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
4885
Andy Hungfbfc3952015-01-15 13:33:51 -08004886 if (type == DUPLICATING) {
4887 // The Duplicating thread uses the AudioMixer and delivers data to OutputTracks
4888 // (downstream MixerThreads) in DuplicatingThread::threadLoop_write().
4889 // Do not create or use mFastMixer, mOutputSink, mPipeSink, or mNormalSink.
4890 return;
4891 }
Eric Laurent81784c32012-11-19 14:55:58 -08004892 // create an NBAIO sink for the HAL output stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07004893 mOutputSink = new AudioStreamOutSink(output->stream);
Eric Laurent81784c32012-11-19 14:55:58 -08004894 size_t numCounterOffers = 0;
jiabin245cdd92018-12-07 17:55:15 -08004895 const NBAIO_Format offers[1] = {Format_from_SR_C(
4896 mSampleRate, mChannelCount + mHapticChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07004897#if !LOG_NDEBUG
4898 ssize_t index =
4899#else
4900 (void)
4901#endif
4902 mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08004903 ALOG_ASSERT(index == 0);
4904
4905 // initialize fast mixer depending on configuration
4906 bool initFastMixer;
jiabinc658e452022-10-21 20:52:21 +00004907 if (mType == SPATIALIZER || mType == BIT_PERFECT) {
Eric Laurent81784c32012-11-19 14:55:58 -08004908 initFastMixer = false;
Eric Laurentb62d0362021-10-26 17:40:18 +02004909 } else {
4910 switch (kUseFastMixer) {
4911 case FastMixer_Never:
4912 initFastMixer = false;
4913 break;
4914 case FastMixer_Always:
4915 initFastMixer = true;
4916 break;
4917 case FastMixer_Static:
4918 case FastMixer_Dynamic:
4919 initFastMixer = mFrameCount < mNormalFrameCount;
4920 break;
4921 }
4922 ALOGW_IF(initFastMixer == false && mFrameCount < mNormalFrameCount,
4923 "FastMixer is preferred for this sink as frameCount %zu is less than threshold %zu",
4924 mFrameCount, mNormalFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08004925 }
4926 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07004927 audio_format_t fastMixerFormat;
4928 if (mMixerBufferEnabled && mEffectBufferEnabled) {
4929 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
4930 } else {
4931 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
4932 }
4933 if (mFormat != fastMixerFormat) {
4934 // change our Sink format to accept our intermediate precision
4935 mFormat = fastMixerFormat;
4936 free(mSinkBuffer);
jiabin245cdd92018-12-07 17:55:15 -08004937 mFrameSize = audio_bytes_per_frame(mChannelCount + mHapticChannelCount, mFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07004938 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
4939 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
4940 }
Eric Laurent81784c32012-11-19 14:55:58 -08004941
4942 // create a MonoPipe to connect our submix to FastMixer
4943 NBAIO_Format format = mOutputSink->format();
Andy Hung8946a282018-04-19 20:04:56 -07004944
Andy Hung1258c1a2014-05-23 21:22:17 -07004945 // adjust format to match that of the Fast Mixer
Glenn Kasten49f36ba2017-12-06 13:02:02 -08004946 ALOGV("format changed from %#x to %#x", format.mFormat, fastMixerFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07004947 format.mFormat = fastMixerFormat;
4948 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
4949
Eric Laurent81784c32012-11-19 14:55:58 -08004950 // This pipe depth compensates for scheduling latency of the normal mixer thread.
4951 // When it wakes up after a maximum latency, it runs a few cycles quickly before
4952 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
4953 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
Andy Hung920f6572022-10-06 12:09:49 -07004954 const NBAIO_Format offersFast[1] = {format};
4955 size_t numCounterOffersFast = 0;
Andy Hung8946a282018-04-19 20:04:56 -07004956#if !LOG_NDEBUG
Eric Laurent1e28aaa2023-04-16 19:34:23 +02004957 index =
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07004958#else
4959 (void)
4960#endif
Andy Hung920f6572022-10-06 12:09:49 -07004961 monoPipe->negotiate(offersFast, std::size(offersFast),
4962 nullptr /* counterOffers */, numCounterOffersFast);
Eric Laurent81784c32012-11-19 14:55:58 -08004963 ALOG_ASSERT(index == 0);
4964 monoPipe->setAvgFrames((mScreenState & 1) ?
4965 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
4966 mPipeSink = monoPipe;
4967
Eric Laurent81784c32012-11-19 14:55:58 -08004968 // create fast mixer and configure it initially with just one fast track for our submix
Andy Hung8946a282018-04-19 20:04:56 -07004969 mFastMixer = new FastMixer(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08004970 FastMixerStateQueue *sq = mFastMixer->sq();
4971#ifdef STATE_QUEUE_DUMP
4972 sq->setObserverDump(&mStateQueueObserverDump);
4973 sq->setMutatorDump(&mStateQueueMutatorDump);
4974#endif
4975 FastMixerState *state = sq->begin();
4976 FastTrack *fastTrack = &state->mFastTracks[0];
4977 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
4978 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
4979 fastTrack->mVolumeProvider = NULL;
Mikhail Naganov55773032020-10-01 15:08:13 -07004980 fastTrack->mChannelMask = static_cast<audio_channel_mask_t>(
4981 mChannelMask | mHapticChannelMask); // mPipeSink channel mask for
4982 // audio to FastMixer
Andy Hunge8a1ced2014-05-09 15:02:21 -07004983 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
jiabin245cdd92018-12-07 17:55:15 -08004984 fastTrack->mHapticPlaybackEnabled = mHapticChannelMask != AUDIO_CHANNEL_NONE;
jiabine70bc7f2020-06-30 22:07:55 -07004985 fastTrack->mHapticIntensity = os::HapticScale::NONE;
Lais Andradebc3f37a2021-07-02 00:13:19 +01004986 fastTrack->mHapticMaxAmplitude = NAN;
Eric Laurent81784c32012-11-19 14:55:58 -08004987 fastTrack->mGeneration++;
4988 state->mFastTracksGen++;
4989 state->mTrackMask = 1;
4990 // fast mixer will use the HAL output sink
4991 state->mOutputSink = mOutputSink.get();
4992 state->mOutputSinkGen++;
4993 state->mFrameCount = mFrameCount;
jiabin245cdd92018-12-07 17:55:15 -08004994 // specify sink channel mask when haptic channel mask present as it can not
4995 // be calculated directly from channel count
4996 state->mSinkChannelMask = mHapticChannelMask == AUDIO_CHANNEL_NONE
Mikhail Naganov55773032020-10-01 15:08:13 -07004997 ? AUDIO_CHANNEL_NONE
4998 : static_cast<audio_channel_mask_t>(mChannelMask | mHapticChannelMask);
Eric Laurent81784c32012-11-19 14:55:58 -08004999 state->mCommand = FastMixerState::COLD_IDLE;
5000 // already done in constructor initialization list
5001 //mFastMixerFutex = 0;
5002 state->mColdFutexAddr = &mFastMixerFutex;
5003 state->mColdGen++;
5004 state->mDumpState = &mFastMixerDumpState;
Andy Hung583043b2023-07-17 17:05:00 -07005005 mFastMixerNBLogWriter = afThreadCallback->newWriter_l(kFastMixerLogSize, "FastMixer");
Glenn Kasten9e58b552013-01-18 15:09:48 -08005006 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08005007 sq->end();
5008 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
5009
Eric Tan0513b5d2018-09-17 10:32:48 -07005010 NBLog::thread_info_t info;
5011 info.id = mId;
5012 info.type = NBLog::FASTMIXER;
5013 mFastMixerNBLogWriter->log<NBLog::EVENT_THREAD_INFO>(info);
5014
Eric Laurent81784c32012-11-19 14:55:58 -08005015 // start the fast mixer
5016 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
5017 pid_t tid = mFastMixer->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07005018 sendPrioConfigEvent(getpid(), tid, kPriorityFastMixer, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08005019 stream()->setHalThreadPriority(kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08005020
5021#ifdef AUDIO_WATCHDOG
5022 // create and start the watchdog
5023 mAudioWatchdog = new AudioWatchdog();
5024 mAudioWatchdog->setDump(&mAudioWatchdogDump);
5025 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
5026 tid = mAudioWatchdog->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07005027 sendPrioConfigEvent(getpid(), tid, kPriorityFastMixer, false /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08005028#endif
Andy Hung8946a282018-04-19 20:04:56 -07005029 } else {
5030#ifdef TEE_SINK
5031 // Only use the MixerThread tee if there is no FastMixer.
5032 mTee.set(mOutputSink->format(), NBAIO_Tee::TEE_FLAG_OUTPUT_THREAD);
5033 mTee.setId(std::string("_") + std::to_string(mId) + "_M");
5034#endif
Eric Laurent81784c32012-11-19 14:55:58 -08005035 }
5036
5037 switch (kUseFastMixer) {
5038 case FastMixer_Never:
5039 case FastMixer_Dynamic:
5040 mNormalSink = mOutputSink;
5041 break;
5042 case FastMixer_Always:
5043 mNormalSink = mPipeSink;
5044 break;
5045 case FastMixer_Static:
5046 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
5047 break;
5048 }
5049}
5050
Andy Hungee58e4a2023-07-07 13:47:37 -07005051MixerThread::~MixerThread()
Eric Laurent81784c32012-11-19 14:55:58 -08005052{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005053 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005054 FastMixerStateQueue *sq = mFastMixer->sq();
5055 FastMixerState *state = sq->begin();
5056 if (state->mCommand == FastMixerState::COLD_IDLE) {
5057 int32_t old = android_atomic_inc(&mFastMixerFutex);
5058 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07005059 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08005060 }
5061 }
5062 state->mCommand = FastMixerState::EXIT;
5063 sq->end();
5064 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
5065 mFastMixer->join();
5066 // Though the fast mixer thread has exited, it's state queue is still valid.
5067 // We'll use that extract the final state which contains one remaining fast track
5068 // corresponding to our sub-mix.
5069 state = sq->begin();
5070 ALOG_ASSERT(state->mTrackMask == 1);
5071 FastTrack *fastTrack = &state->mFastTracks[0];
5072 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
5073 delete fastTrack->mBufferProvider;
5074 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005075 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08005076#ifdef AUDIO_WATCHDOG
5077 if (mAudioWatchdog != 0) {
5078 mAudioWatchdog->requestExit();
5079 mAudioWatchdog->requestExitAndWait();
5080 mAudioWatchdog.clear();
5081 }
5082#endif
5083 }
Andy Hung583043b2023-07-17 17:05:00 -07005084 mAfThreadCallback->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08005085 delete mAudioMixer;
5086}
5087
Andy Hungee58e4a2023-07-07 13:47:37 -07005088void MixerThread::onFirstRef() {
Eric Laurentb0463942022-12-20 16:31:10 +01005089 PlaybackThread::onFirstRef();
5090
5091 Mutex::Autolock _l(mLock);
5092 if (mOutput != nullptr && mOutput->stream != nullptr) {
5093 status_t status = mOutput->stream->setLatencyModeCallback(this);
5094 if (status != INVALID_OPERATION) {
5095 updateHalSupportedLatencyModes_l();
5096 }
5097 // Default to enabled if the HAL supports it. This can be changed by Audioflinger after
5098 // the thread construction according to AudioFlinger::mBluetoothLatencyModesEnabled
5099 mBluetoothLatencyModesEnabled.store(
5100 mOutput->audioHwDev->supportsBluetoothVariableLatency());
5101 }
5102}
Eric Laurent81784c32012-11-19 14:55:58 -08005103
Andy Hungee58e4a2023-07-07 13:47:37 -07005104uint32_t MixerThread::correctLatency_l(uint32_t latency) const
Eric Laurent81784c32012-11-19 14:55:58 -08005105{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005106 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005107 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
5108 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
5109 }
5110 return latency;
5111}
5112
Andy Hungee58e4a2023-07-07 13:47:37 -07005113ssize_t MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08005114{
5115 // FIXME we should only do one push per cycle; confirm this is true
5116 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005117 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005118 FastMixerStateQueue *sq = mFastMixer->sq();
5119 FastMixerState *state = sq->begin();
5120 if (state->mCommand != FastMixerState::MIX_WRITE &&
5121 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
5122 if (state->mCommand == FastMixerState::COLD_IDLE) {
Eric Laurenta2ab4502015-09-09 12:25:51 -07005123
5124 // FIXME workaround for first HAL write being CPU bound on some devices
5125 ATRACE_BEGIN("write");
5126 mOutput->write((char *)mSinkBuffer, 0);
5127 ATRACE_END();
5128
Eric Laurent81784c32012-11-19 14:55:58 -08005129 int32_t old = android_atomic_inc(&mFastMixerFutex);
5130 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07005131 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08005132 }
5133#ifdef AUDIO_WATCHDOG
5134 if (mAudioWatchdog != 0) {
5135 mAudioWatchdog->resume();
5136 }
5137#endif
5138 }
5139 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kastend797a9d2015-03-02 14:19:25 -08005140#ifdef FAST_THREAD_STATISTICS
Andy Hung583043b2023-07-17 17:05:00 -07005141 mFastMixerDumpState.increaseSamplingN(mAfThreadCallback->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08005142 FastThreadDumpState::kSamplingNforLowRamDevice : FastThreadDumpState::kSamplingN);
Glenn Kastend797a9d2015-03-02 14:19:25 -08005143#endif
Eric Laurent81784c32012-11-19 14:55:58 -08005144 sq->end();
5145 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
5146 if (kUseFastMixer == FastMixer_Dynamic) {
5147 mNormalSink = mPipeSink;
5148 }
5149 } else {
5150 sq->end(false /*didModify*/);
5151 }
5152 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005153 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08005154}
5155
Andy Hungee58e4a2023-07-07 13:47:37 -07005156void MixerThread::threadLoop_standby()
Eric Laurent81784c32012-11-19 14:55:58 -08005157{
5158 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005159 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005160 FastMixerStateQueue *sq = mFastMixer->sq();
5161 FastMixerState *state = sq->begin();
5162 if (!(state->mCommand & FastMixerState::IDLE)) {
Andy Hung2148bf02016-11-28 19:01:02 -08005163 // Report any frames trapped in the Monopipe
5164 MonoPipe *monoPipe = (MonoPipe *)mPipeSink.get();
5165 const long long pipeFrames = monoPipe->maxFrames() - monoPipe->availableToWrite();
5166 mLocalLog.log("threadLoop_standby: framesWritten:%lld suspendedFrames:%lld "
5167 "monoPipeWritten:%lld monoPipeLeft:%lld",
5168 (long long)mFramesWritten, (long long)mSuspendedFrames,
5169 (long long)mPipeSink->framesWritten(), pipeFrames);
5170 mLocalLog.log("threadLoop_standby: %s", mTimestamp.toString().c_str());
5171
Eric Laurent81784c32012-11-19 14:55:58 -08005172 state->mCommand = FastMixerState::COLD_IDLE;
5173 state->mColdFutexAddr = &mFastMixerFutex;
5174 state->mColdGen++;
5175 mFastMixerFutex = 0;
5176 sq->end();
5177 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
5178 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
5179 if (kUseFastMixer == FastMixer_Dynamic) {
5180 mNormalSink = mOutputSink;
5181 }
5182#ifdef AUDIO_WATCHDOG
5183 if (mAudioWatchdog != 0) {
5184 mAudioWatchdog->pause();
5185 }
5186#endif
5187 } else {
5188 sq->end(false /*didModify*/);
5189 }
5190 }
5191 PlaybackThread::threadLoop_standby();
5192}
5193
Andy Hungee58e4a2023-07-07 13:47:37 -07005194bool PlaybackThread::waitingAsyncCallback_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08005195{
5196 return false;
5197}
5198
Andy Hungee58e4a2023-07-07 13:47:37 -07005199bool PlaybackThread::shouldStandby_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08005200{
5201 return !mStandby;
5202}
5203
Andy Hungee58e4a2023-07-07 13:47:37 -07005204bool PlaybackThread::waitingAsyncCallback()
Eric Laurentbfb1b832013-01-07 09:53:42 -08005205{
5206 Mutex::Autolock _l(mLock);
5207 return waitingAsyncCallback_l();
5208}
5209
Eric Laurent81784c32012-11-19 14:55:58 -08005210// shared by MIXER and DIRECT, overridden by DUPLICATING
Andy Hungee58e4a2023-07-07 13:47:37 -07005211void PlaybackThread::threadLoop_standby()
Eric Laurent81784c32012-11-19 14:55:58 -08005212{
5213 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
Phil Burk062e67a2015-02-11 13:40:50 -08005214 mOutput->standby();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005215 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005216 // discard any pending drain or write ack by incrementing sequence
5217 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
5218 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005219 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005220 mCallbackThread->setWriteBlocked(mWriteAckSequence);
5221 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005222 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08005223 mHwPaused = false;
Eric Laurent68a40a82022-05-03 18:15:04 +02005224 setHalLatencyMode_l();
Eric Laurent81784c32012-11-19 14:55:58 -08005225}
5226
Andy Hungee58e4a2023-07-07 13:47:37 -07005227void PlaybackThread::onAddNewTrack_l()
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08005228{
5229 ALOGV("signal playback thread");
5230 broadcast_l();
5231}
5232
Andy Hungee58e4a2023-07-07 13:47:37 -07005233void PlaybackThread::onAsyncError()
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005234{
5235 for (int i = AUDIO_STREAM_SYSTEM; i < (int)AUDIO_STREAM_CNT; i++) {
5236 invalidateTracks((audio_stream_type_t)i);
5237 }
5238}
5239
Andy Hungee58e4a2023-07-07 13:47:37 -07005240void MixerThread::threadLoop_mix()
Eric Laurent81784c32012-11-19 14:55:58 -08005241{
Eric Laurent81784c32012-11-19 14:55:58 -08005242 // mix buffers...
Glenn Kastend79072e2016-01-06 08:41:20 -08005243 mAudioMixer->process();
Andy Hung25c2dac2014-02-27 14:56:00 -08005244 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005245 // increase sleep time progressively when application underrun condition clears.
5246 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
5247 // that a steady state of alternating ready/not ready conditions keeps the sleep time
5248 // such that we would underrun the audio HAL.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005249 if ((mSleepTimeUs == 0) && (sleepTimeShift > 0)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005250 sleepTimeShift--;
5251 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005252 mSleepTimeUs = 0;
5253 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08005254 //TODO: delay standby when effects have a tail
Glenn Kasten4c053ea2014-09-28 14:41:07 -07005255
Eric Laurent81784c32012-11-19 14:55:58 -08005256}
5257
Andy Hungee58e4a2023-07-07 13:47:37 -07005258void MixerThread::threadLoop_sleepTime()
Eric Laurent81784c32012-11-19 14:55:58 -08005259{
5260 // If no tracks are ready, sleep once for the duration of an output
5261 // buffer size, then write 0s to the output
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005262 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005263 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Andy Hung06d13222018-05-03 20:13:31 -07005264 if (mPipeSink.get() != nullptr && mPipeSink == mNormalSink) {
5265 // Using the Monopipe availableToWrite, we estimate the
5266 // sleep time to retry for more data (before we underrun).
5267 MonoPipe *monoPipe = static_cast<MonoPipe *>(mPipeSink.get());
5268 const ssize_t availableToWrite = mPipeSink->availableToWrite();
5269 const size_t pipeFrames = monoPipe->maxFrames();
5270 const size_t framesLeft = pipeFrames - max(availableToWrite, 0);
5271 // HAL_framecount <= framesDelay ~ framesLeft / 2 <= Normal_Mixer_framecount
5272 const size_t framesDelay = std::min(
5273 mNormalFrameCount, max(framesLeft / 2, mFrameCount));
5274 ALOGV("pipeFrames:%zu framesLeft:%zu framesDelay:%zu",
5275 pipeFrames, framesLeft, framesDelay);
5276 mSleepTimeUs = framesDelay * MICROS_PER_SECOND / mSampleRate;
5277 } else {
5278 mSleepTimeUs = mActiveSleepTimeUs >> sleepTimeShift;
5279 if (mSleepTimeUs < kMinThreadSleepTimeUs) {
5280 mSleepTimeUs = kMinThreadSleepTimeUs;
5281 }
5282 // reduce sleep time in case of consecutive application underruns to avoid
5283 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
5284 // duration we would end up writing less data than needed by the audio HAL if
5285 // the condition persists.
5286 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
5287 sleepTimeShift++;
5288 }
Eric Laurent81784c32012-11-19 14:55:58 -08005289 }
5290 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005291 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005292 }
5293 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08005294 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
5295 // before effects processing or output.
5296 if (mMixerBufferValid) {
5297 memset(mMixerBuffer, 0, mMixerBufferSize);
Eric Laurent39095982021-08-24 18:29:27 +02005298 if (mType == SPATIALIZER) {
5299 memset(mSinkBuffer, 0, mSinkBufferSize);
5300 }
Andy Hung98ef9782014-03-04 14:46:50 -08005301 } else {
5302 memset(mSinkBuffer, 0, mSinkBufferSize);
5303 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005304 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005305 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
5306 "anticipated start");
5307 }
5308 // TODO add standby time extension fct of effect tail
5309}
5310
5311// prepareTracks_l() must be called with ThreadBase::mLock held
Andy Hungee58e4a2023-07-07 13:47:37 -07005312PlaybackThread::mixer_state MixerThread::prepareTracks_l(
Andy Hung8d31fd22023-06-26 19:20:57 -07005313 Vector<sp<IAfTrack>>* tracksToRemove)
Eric Laurent81784c32012-11-19 14:55:58 -08005314{
Andy Hungc0691382018-09-12 18:01:57 -07005315 // clean up deleted track ids in AudioMixer before allocating new tracks
5316 (void)mTracks.processDeletedTrackIds([this](int trackId) {
5317 // for each trackId, destroy it in the AudioMixer
5318 if (mAudioMixer->exists(trackId)) {
5319 mAudioMixer->destroy(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08005320 }
5321 });
Andy Hungc0691382018-09-12 18:01:57 -07005322 mTracks.clearDeletedTrackIds();
Eric Laurent81784c32012-11-19 14:55:58 -08005323
5324 mixer_state mixerStatus = MIXER_IDLE;
5325 // find out which tracks need to be processed
5326 size_t count = mActiveTracks.size();
5327 size_t mixedTracks = 0;
5328 size_t tracksWithEffect = 0;
5329 // counts only _active_ fast tracks
5330 size_t fastTracks = 0;
5331 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
5332
5333 float masterVolume = mMasterVolume;
5334 bool masterMute = mMasterMute;
5335
5336 if (masterMute) {
5337 masterVolume = 0;
5338 }
5339 // Delegate master volume control to effect in output mix effect chain if needed
Andy Hung116bc262023-06-20 18:56:17 -07005340 sp<IAfEffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Eric Laurent81784c32012-11-19 14:55:58 -08005341 if (chain != 0) {
5342 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
5343 chain->setVolume_l(&v, &v);
5344 masterVolume = (float)((v + (1 << 23)) >> 24);
5345 chain.clear();
5346 }
5347
5348 // prepare a new state to push
5349 FastMixerStateQueue *sq = NULL;
5350 FastMixerState *state = NULL;
5351 bool didModify = false;
5352 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Andy Hungf2285312017-02-14 18:31:59 -08005353 bool coldIdle = false;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005354 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005355 sq = mFastMixer->sq();
5356 state = sq->begin();
Andy Hungf2285312017-02-14 18:31:59 -08005357 coldIdle = state->mCommand == FastMixerState::COLD_IDLE;
Eric Laurent81784c32012-11-19 14:55:58 -08005358 }
5359
Andy Hung69aed5f2014-02-25 17:24:40 -08005360 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08005361 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08005362
Andy Hungbd3b2b02018-05-21 10:53:11 -07005363 // DeferredOperations handles statistics after setting mixerStatus.
5364 class DeferredOperations {
5365 public:
Andy Hungea840382020-05-05 21:50:17 -07005366 DeferredOperations(mixer_state *mixerStatus, ThreadMetrics *threadMetrics)
5367 : mMixerStatus(mixerStatus)
5368 , mThreadMetrics(threadMetrics) {}
Andy Hungbd3b2b02018-05-21 10:53:11 -07005369
5370 // when leaving scope, tally frames properly.
5371 ~DeferredOperations() {
5372 // Tally underrun frames only if we are actually mixing (MIXER_TRACKS_READY)
5373 // because that is when the underrun occurs.
5374 // We do not distinguish between FastTracks and NormalTracks here.
Andy Hungea840382020-05-05 21:50:17 -07005375 size_t maxUnderrunFrames = 0;
Andy Hungb68f5eb2019-12-03 16:49:17 -08005376 if (*mMixerStatus == MIXER_TRACKS_READY && mUnderrunFrames.size() > 0) {
Andy Hungbd3b2b02018-05-21 10:53:11 -07005377 for (const auto &underrun : mUnderrunFrames) {
Andy Hungc2b11cb2020-04-22 09:04:01 -07005378 underrun.first->tallyUnderrunFrames(underrun.second);
Andy Hungea840382020-05-05 21:50:17 -07005379 maxUnderrunFrames = max(underrun.second, maxUnderrunFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07005380 }
5381 }
Andy Hungea840382020-05-05 21:50:17 -07005382 // send the max underrun frames for this mixer period
5383 mThreadMetrics->logUnderrunFrames(maxUnderrunFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07005384 }
5385
5386 // tallyUnderrunFrames() is called to update the track counters
5387 // with the number of underrun frames for a particular mixer period.
5388 // We defer tallying until we know the final mixer status.
Andy Hung8d31fd22023-06-26 19:20:57 -07005389 void tallyUnderrunFrames(const sp<IAfTrack>& track, size_t underrunFrames) {
Andy Hungbd3b2b02018-05-21 10:53:11 -07005390 mUnderrunFrames.emplace_back(track, underrunFrames);
5391 }
5392
5393 private:
5394 const mixer_state * const mMixerStatus;
Andy Hungea840382020-05-05 21:50:17 -07005395 ThreadMetrics * const mThreadMetrics;
Andy Hung8d31fd22023-06-26 19:20:57 -07005396 std::vector<std::pair<sp<IAfTrack>, size_t>> mUnderrunFrames;
Andy Hungea840382020-05-05 21:50:17 -07005397 } deferredOperations(&mixerStatus, &mThreadMetrics);
Andy Hungb68f5eb2019-12-03 16:49:17 -08005398 // implicit nested scope for variable capture
Andy Hungbd3b2b02018-05-21 10:53:11 -07005399
jiabin245cdd92018-12-07 17:55:15 -08005400 bool noFastHapticTrack = true;
Eric Laurent81784c32012-11-19 14:55:58 -08005401 for (size_t i=0 ; i<count ; i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07005402 const sp<IAfTrack> t = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08005403
5404 // this const just means the local variable doesn't change
Andy Hung8d31fd22023-06-26 19:20:57 -07005405 IAfTrack* const track = t.get();
Eric Laurent81784c32012-11-19 14:55:58 -08005406
5407 // process fast tracks
5408 if (track->isFastTrack()) {
Andy Hungae22b482019-05-09 15:38:55 -07005409 LOG_ALWAYS_FATAL_IF(mFastMixer.get() == nullptr,
5410 "%s(%d): FastTrack(%d) present without FastMixer",
5411 __func__, id(), track->id());
5412
jiabin245cdd92018-12-07 17:55:15 -08005413 if (track->getHapticPlaybackEnabled()) {
5414 noFastHapticTrack = false;
5415 }
Eric Laurent81784c32012-11-19 14:55:58 -08005416
5417 // It's theoretically possible (though unlikely) for a fast track to be created
5418 // and then removed within the same normal mix cycle. This is not a problem, as
5419 // the track never becomes active so it's fast mixer slot is never touched.
5420 // The converse, of removing an (active) track and then creating a new track
5421 // at the identical fast mixer slot within the same normal mix cycle,
5422 // is impossible because the slot isn't marked available until the end of each cycle.
Andy Hung8d31fd22023-06-26 19:20:57 -07005423 int j = track->fastIndex();
Glenn Kastendc2c50b2016-04-21 08:13:14 -07005424 ALOG_ASSERT(0 < j && j < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08005425 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
5426 FastTrack *fastTrack = &state->mFastTracks[j];
5427
5428 // Determine whether the track is currently in underrun condition,
5429 // and whether it had a recent underrun.
5430 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
5431 FastTrackUnderruns underruns = ftDump->mUnderruns;
5432 uint32_t recentFull = (underruns.mBitFields.mFull -
Andy Hung8d31fd22023-06-26 19:20:57 -07005433 track->fastTrackUnderruns().mBitFields.mFull) & UNDERRUN_MASK;
Eric Laurent81784c32012-11-19 14:55:58 -08005434 uint32_t recentPartial = (underruns.mBitFields.mPartial -
Andy Hung8d31fd22023-06-26 19:20:57 -07005435 track->fastTrackUnderruns().mBitFields.mPartial) & UNDERRUN_MASK;
Eric Laurent81784c32012-11-19 14:55:58 -08005436 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
Andy Hung8d31fd22023-06-26 19:20:57 -07005437 track->fastTrackUnderruns().mBitFields.mEmpty) & UNDERRUN_MASK;
Eric Laurent81784c32012-11-19 14:55:58 -08005438 uint32_t recentUnderruns = recentPartial + recentEmpty;
Andy Hung8d31fd22023-06-26 19:20:57 -07005439 track->fastTrackUnderruns() = underruns;
Eric Laurent81784c32012-11-19 14:55:58 -08005440 // don't count underruns that occur while stopping or pausing
5441 // or stopped which can occur when flush() is called while active
Andy Hungbd3b2b02018-05-21 10:53:11 -07005442 size_t underrunFrames = 0;
Glenn Kasten82aaf942013-07-17 16:05:07 -07005443 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
5444 recentUnderruns > 0) {
5445 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
Andy Hungbd3b2b02018-05-21 10:53:11 -07005446 underrunFrames = recentUnderruns * mFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08005447 }
Andy Hungbd3b2b02018-05-21 10:53:11 -07005448 // Immediately account for FastTrack underruns.
Andy Hung8d31fd22023-06-26 19:20:57 -07005449 track->audioTrackServerProxy()->tallyUnderrunFrames(underrunFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08005450
5451 // This is similar to the state machine for normal tracks,
5452 // with a few modifications for fast tracks.
5453 bool isActive = true;
Andy Hung8d31fd22023-06-26 19:20:57 -07005454 switch (track->state()) {
5455 case IAfTrackBase::STOPPING_1:
Eric Laurent81784c32012-11-19 14:55:58 -08005456 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08005457 if (recentUnderruns > 0 || track->isTerminated()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07005458 track->setState(IAfTrackBase::STOPPING_2);
Eric Laurent81784c32012-11-19 14:55:58 -08005459 }
5460 break;
Andy Hung8d31fd22023-06-26 19:20:57 -07005461 case IAfTrackBase::PAUSING:
Eric Laurent81784c32012-11-19 14:55:58 -08005462 // ramp down is not yet implemented
5463 track->setPaused();
5464 break;
Andy Hung8d31fd22023-06-26 19:20:57 -07005465 case IAfTrackBase::RESUMING:
Eric Laurent81784c32012-11-19 14:55:58 -08005466 // ramp up is not yet implemented
Andy Hung8d31fd22023-06-26 19:20:57 -07005467 track->setState(IAfTrackBase::ACTIVE);
Eric Laurent81784c32012-11-19 14:55:58 -08005468 break;
Andy Hung8d31fd22023-06-26 19:20:57 -07005469 case IAfTrackBase::ACTIVE:
Eric Laurent81784c32012-11-19 14:55:58 -08005470 if (recentFull > 0 || recentPartial > 0) {
5471 // track has provided at least some frames recently: reset retry count
Andy Hung8d31fd22023-06-26 19:20:57 -07005472 track->retryCount() = kMaxTrackRetries;
Eric Laurent81784c32012-11-19 14:55:58 -08005473 }
5474 if (recentUnderruns == 0) {
5475 // no recent underruns: stay active
5476 break;
5477 }
5478 // there has recently been an underrun of some kind
5479 if (track->sharedBuffer() == 0) {
5480 // were any of the recent underruns "empty" (no frames available)?
5481 if (recentEmpty == 0) {
5482 // no, then ignore the partial underruns as they are allowed indefinitely
5483 break;
5484 }
5485 // there has recently been an "empty" underrun: decrement the retry counter
Andy Hung8d31fd22023-06-26 19:20:57 -07005486 if (--(track->retryCount()) > 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005487 break;
5488 }
5489 // indicate to client process that the track was disabled because of underrun;
5490 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08005491 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08005492 // remove from active list, but state remains ACTIVE [confusing but true]
5493 isActive = false;
5494 break;
5495 }
Chih-Hung Hsieh2b487032018-09-13 14:16:02 -07005496 FALLTHROUGH_INTENDED;
Andy Hung8d31fd22023-06-26 19:20:57 -07005497 case IAfTrackBase::STOPPING_2:
5498 case IAfTrackBase::PAUSED:
5499 case IAfTrackBase::STOPPED:
5500 case IAfTrackBase::FLUSHED: // flush() while active
Eric Laurent81784c32012-11-19 14:55:58 -08005501 // Check for presentation complete if track is inactive
5502 // We have consumed all the buffers of this track.
5503 // This would be incomplete if we auto-paused on underrun
5504 {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005505 uint32_t latency = 0;
5506 status_t result = mOutput->stream->getLatency(&latency);
5507 ALOGE_IF(result != OK,
5508 "Error when retrieving output stream latency: %d", result);
5509 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08005510 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005511 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
5512 // track stays in active list until presentation is complete
5513 break;
5514 }
5515 }
5516 if (track->isStopping_2()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07005517 track->setState(IAfTrackBase::STOPPED);
Eric Laurent81784c32012-11-19 14:55:58 -08005518 }
5519 if (track->isStopped()) {
5520 // Can't reset directly, as fast mixer is still polling this track
5521 // track->reset();
5522 // So instead mark this track as needing to be reset after push with ack
5523 resetMask |= 1 << i;
5524 }
5525 isActive = false;
5526 break;
Andy Hung8d31fd22023-06-26 19:20:57 -07005527 case IAfTrackBase::IDLE:
Eric Laurent81784c32012-11-19 14:55:58 -08005528 default:
Andy Hung8d31fd22023-06-26 19:20:57 -07005529 LOG_ALWAYS_FATAL("unexpected track state %d", (int)track->state());
Eric Laurent81784c32012-11-19 14:55:58 -08005530 }
5531
5532 if (isActive) {
5533 // was it previously inactive?
5534 if (!(state->mTrackMask & (1 << j))) {
Andy Hung8d31fd22023-06-26 19:20:57 -07005535 ExtendedAudioBufferProvider *eabp = track->asExtendedAudioBufferProvider();
5536 VolumeProvider *vp = track->asVolumeProvider();
Eric Laurent81784c32012-11-19 14:55:58 -08005537 fastTrack->mBufferProvider = eabp;
5538 fastTrack->mVolumeProvider = vp;
Andy Hung8d31fd22023-06-26 19:20:57 -07005539 fastTrack->mChannelMask = track->channelMask();
5540 fastTrack->mFormat = track->format();
jiabin245cdd92018-12-07 17:55:15 -08005541 fastTrack->mHapticPlaybackEnabled = track->getHapticPlaybackEnabled();
jiabin77270b82018-12-18 15:41:29 -08005542 fastTrack->mHapticIntensity = track->getHapticIntensity();
Lais Andradebc3f37a2021-07-02 00:13:19 +01005543 fastTrack->mHapticMaxAmplitude = track->getHapticMaxAmplitude();
Eric Laurent81784c32012-11-19 14:55:58 -08005544 fastTrack->mGeneration++;
5545 state->mTrackMask |= 1 << j;
5546 didModify = true;
5547 // no acknowledgement required for newly active tracks
5548 }
Andy Hung8d31fd22023-06-26 19:20:57 -07005549 sp<AudioTrackServerProxy> proxy = track->audioTrackServerProxy();
Eric Laurenteab90452019-06-24 15:17:46 -07005550 float volume;
5551 if (track->isPlaybackRestricted() || mStreamTypes[track->streamType()].mute) {
5552 volume = 0.f;
5553 } else {
5554 volume = masterVolume * mStreamTypes[track->streamType()].volume;
5555 }
5556
5557 handleVoipVolume_l(&volume);
5558
Eric Laurent81784c32012-11-19 14:55:58 -08005559 // cache the combined master volume and stream type volume for fast mixer; this
5560 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005561 const float vh = track->getVolumeHandler()->getVolume(
Eric Laurenteab90452019-06-24 15:17:46 -07005562 proxy->framesReleased()).first;
5563 volume *= vh;
Andy Hung8d31fd22023-06-26 19:20:57 -07005564 track->setCachedVolume(volume);
Kevin Rocard12381092018-04-11 09:19:59 -07005565 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Vlad Popae2f5aef2022-07-25 16:00:20 +02005566 float vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
5567 float vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
5568
Andy Hung583043b2023-07-17 17:05:00 -07005569 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
Vlad Popae2f5aef2022-07-25 16:00:20 +02005570 /*muteState=*/{masterVolume == 0.f,
5571 mStreamTypes[track->streamType()].volume == 0.f,
5572 mStreamTypes[track->streamType()].mute,
5573 track->isPlaybackRestricted(),
Vlad Popa436c9172022-08-02 15:25:08 +02005574 vlf == 0.f && vrf == 0.f,
5575 vh == 0.f});
Vlad Popae2f5aef2022-07-25 16:00:20 +02005576
5577 vlf *= volume;
5578 vrf *= volume;
Eric Laurenteab90452019-06-24 15:17:46 -07005579
jiabin76d94692022-12-15 21:51:21 +00005580 track->setFinalVolume(vlf, vrf);
Eric Laurent81784c32012-11-19 14:55:58 -08005581 ++fastTracks;
5582 } else {
5583 // was it previously active?
5584 if (state->mTrackMask & (1 << j)) {
5585 fastTrack->mBufferProvider = NULL;
5586 fastTrack->mGeneration++;
5587 state->mTrackMask &= ~(1 << j);
5588 didModify = true;
5589 // If any fast tracks were removed, we must wait for acknowledgement
5590 // because we're about to decrement the last sp<> on those tracks.
5591 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
5592 } else {
Glenn Kastenbf848af2017-12-22 11:55:01 -08005593 // ALOGW rather than LOG_ALWAYS_FATAL because it seems there are cases where an
5594 // AudioTrack may start (which may not be with a start() but with a write()
5595 // after underrun) and immediately paused or released. In that case the
5596 // FastTrack state hasn't had time to update.
5597 // TODO Remove the ALOGW when this theory is confirmed.
5598 ALOGW("fast track %d should have been active; "
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08005599 "mState=%d, mTrackMask=%#x, recentUnderruns=%u, isShared=%d",
Andy Hung8d31fd22023-06-26 19:20:57 -07005600 j, (int)track->state(), state->mTrackMask, recentUnderruns,
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08005601 track->sharedBuffer() != 0);
Glenn Kastenbf848af2017-12-22 11:55:01 -08005602 // Since the FastMixer state already has the track inactive, do nothing here.
Eric Laurent81784c32012-11-19 14:55:58 -08005603 }
5604 tracksToRemove->add(track);
5605 // Avoids a misleading display in dumpsys
Andy Hung8d31fd22023-06-26 19:20:57 -07005606 track->fastTrackUnderruns().mBitFields.mMostRecent = UNDERRUN_FULL;
Eric Laurent81784c32012-11-19 14:55:58 -08005607 }
jiabin245cdd92018-12-07 17:55:15 -08005608 if (fastTrack->mHapticPlaybackEnabled != track->getHapticPlaybackEnabled()) {
5609 fastTrack->mHapticPlaybackEnabled = track->getHapticPlaybackEnabled();
5610 didModify = true;
5611 }
Eric Laurent81784c32012-11-19 14:55:58 -08005612 continue;
5613 }
5614
5615 { // local variable scope to avoid goto warning
5616
5617 audio_track_cblk_t* cblk = track->cblk();
5618
5619 // The first time a track is added we wait
5620 // for all its buffers to be filled before processing it
Andy Hungc0691382018-09-12 18:01:57 -07005621 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08005622
5623 // if an active track doesn't exist in the AudioMixer, create it.
Andy Hungc0691382018-09-12 18:01:57 -07005624 // use the trackId as the AudioMixer name.
5625 if (!mAudioMixer->exists(trackId)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08005626 status_t status = mAudioMixer->create(
Andy Hungc0691382018-09-12 18:01:57 -07005627 trackId,
Andy Hung8d31fd22023-06-26 19:20:57 -07005628 track->channelMask(),
5629 track->format(),
5630 track->sessionId());
Andy Hung1bc088a2018-02-09 15:57:31 -08005631 if (status != OK) {
Andy Hungc0691382018-09-12 18:01:57 -07005632 ALOGW("%s(): AudioMixer cannot create track(%d)"
5633 " mask %#x, format %#x, sessionId %d",
5634 __func__, trackId,
Andy Hung8d31fd22023-06-26 19:20:57 -07005635 track->channelMask(), track->format(), track->sessionId());
Andy Hung1bc088a2018-02-09 15:57:31 -08005636 tracksToRemove->add(track);
5637 track->invalidate(); // consider it dead.
5638 continue;
5639 }
5640 }
5641
Eric Laurent81784c32012-11-19 14:55:58 -08005642 // make sure that we have enough frames to mix one full buffer.
5643 // enforce this condition only once to enable draining the buffer in case the client
5644 // app does not call stop() and relies on underrun to stop:
5645 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
5646 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005647 size_t desiredFrames;
Andy Hung8d31fd22023-06-26 19:20:57 -07005648 const uint32_t sampleRate = track->audioTrackServerProxy()->getSampleRate();
5649 const AudioPlaybackRate playbackRate = track->audioTrackServerProxy()->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07005650
5651 desiredFrames = sourceFramesNeededWithTimestretch(
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07005652 sampleRate, mNormalFrameCount, mSampleRate, playbackRate.mSpeed);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005653 // TODO: ONLY USED FOR LEGACY RESAMPLERS, remove when they are removed.
5654 // add frames already consumed but not yet released by the resampler
5655 // because mAudioTrackServerProxy->framesReady() will include these frames
Andy Hungc0691382018-09-12 18:01:57 -07005656 desiredFrames += mAudioMixer->getUnreleasedFrames(trackId);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005657
Eric Laurent81784c32012-11-19 14:55:58 -08005658 uint32_t minFrames = 1;
5659 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
5660 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005661 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08005662 }
Eric Laurent13e4c962013-12-20 17:36:01 -08005663
5664 size_t framesReady = track->framesReady();
Glenn Kastene7754022014-10-31 12:11:26 -07005665 if (ATRACE_ENABLED()) {
5666 // I wish we had formatted trace names
Andy Hung1bc088a2018-02-09 15:57:31 -08005667 std::string traceName("nRdy");
Andy Hungc0691382018-09-12 18:01:57 -07005668 traceName += std::to_string(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08005669 ATRACE_INT(traceName.c_str(), framesReady);
Glenn Kastene7754022014-10-31 12:11:26 -07005670 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005671 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08005672 !track->isPaused() && !track->isTerminated())
5673 {
Andy Hungc0691382018-09-12 18:01:57 -07005674 ALOGVV("track(%d) s=%08x [OK] on thread %p", trackId, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08005675
5676 mixedTracks++;
5677
Andy Hung69aed5f2014-02-25 17:24:40 -08005678 // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
5679 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08005680 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08005681 if (track->mainBuffer() != mSinkBuffer &&
5682 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08005683 if (mEffectBufferEnabled) {
5684 mEffectBufferValid = true; // Later can set directly.
5685 }
Eric Laurent81784c32012-11-19 14:55:58 -08005686 chain = getEffectChain_l(track->sessionId());
5687 // Delegate volume control to effect in track effect chain if needed
5688 if (chain != 0) {
5689 tracksWithEffect++;
5690 } else {
Andy Hungc0691382018-09-12 18:01:57 -07005691 ALOGW("prepareTracks_l(): track(%d) attached to effect but no chain found on "
Eric Laurent81784c32012-11-19 14:55:58 -08005692 "session %d",
Andy Hungc0691382018-09-12 18:01:57 -07005693 trackId, track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08005694 }
5695 }
5696
5697
5698 int param = AudioMixer::VOLUME;
Andy Hung8d31fd22023-06-26 19:20:57 -07005699 if (track->fillingStatus() == IAfTrack::FS_FILLED) {
Eric Laurent81784c32012-11-19 14:55:58 -08005700 // no ramp for the first volume setting
Andy Hung8d31fd22023-06-26 19:20:57 -07005701 track->fillingStatus() = IAfTrack::FS_ACTIVE;
5702 if (track->state() == IAfTrackBase::RESUMING) {
5703 track->setState(IAfTrackBase::ACTIVE);
Revathi Uddaraju453bcb52017-08-14 14:19:40 +08005704 // If a new track is paused immediately after start, do not ramp on resume.
5705 if (cblk->mServer != 0) {
5706 param = AudioMixer::RAMP_VOLUME;
5707 }
Eric Laurent81784c32012-11-19 14:55:58 -08005708 }
Andy Hungc0691382018-09-12 18:01:57 -07005709 mAudioMixer->setParameter(trackId, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Eric Laurent7c29ec92017-09-20 17:54:22 -07005710 mLeftVolFloat = -1.0;
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005711 // FIXME should not make a decision based on mServer
5712 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005713 // If the track is stopped before the first frame was mixed,
5714 // do not apply ramp
5715 param = AudioMixer::RAMP_VOLUME;
5716 }
5717
5718 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07005719 uint32_t vl, vr; // in U8.24 integer format
5720 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Eric Laurent7c29ec92017-09-20 17:54:22 -07005721 // read original volumes with volume control
Eric Laurenteab90452019-06-24 15:17:46 -07005722 float v = masterVolume * mStreamTypes[track->streamType()].volume;
Andy Hung333ab962019-05-28 20:23:35 -07005723 // Always fetch volumeshaper volume to ensure state is updated.
Andy Hung8d31fd22023-06-26 19:20:57 -07005724 const sp<AudioTrackServerProxy> proxy = track->audioTrackServerProxy();
Andy Hung333ab962019-05-28 20:23:35 -07005725 const float vh = track->getVolumeHandler()->getVolume(
Andy Hung8d31fd22023-06-26 19:20:57 -07005726 track->audioTrackServerProxy()->framesReleased()).first;
Eric Laurent7c29ec92017-09-20 17:54:22 -07005727
Eric Laurenteab90452019-06-24 15:17:46 -07005728 if (mStreamTypes[track->streamType()].mute || track->isPlaybackRestricted()) {
5729 v = 0;
5730 }
5731
5732 handleVoipVolume_l(&v);
5733
5734 if (track->isPausing()) {
Andy Hung6be49402014-05-30 10:42:03 -07005735 vl = vr = 0;
5736 vlf = vrf = vaf = 0.;
Eric Laurenteab90452019-06-24 15:17:46 -07005737 track->setPaused();
Eric Laurent81784c32012-11-19 14:55:58 -08005738 } else {
Glenn Kastenc56f3422014-03-21 17:53:17 -07005739 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07005740 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
5741 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08005742 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07005743 if (vlf > GAIN_FLOAT_UNITY) {
5744 ALOGV("Track left volume out of range: %.3g", vlf);
5745 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08005746 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07005747 if (vrf > GAIN_FLOAT_UNITY) {
5748 ALOGV("Track right volume out of range: %.3g", vrf);
5749 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08005750 }
Vlad Popae2f5aef2022-07-25 16:00:20 +02005751
Andy Hung583043b2023-07-17 17:05:00 -07005752 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
Vlad Popae2f5aef2022-07-25 16:00:20 +02005753 /*muteState=*/{masterVolume == 0.f,
5754 mStreamTypes[track->streamType()].volume == 0.f,
5755 mStreamTypes[track->streamType()].mute,
5756 track->isPlaybackRestricted(),
Vlad Popa436c9172022-08-02 15:25:08 +02005757 vlf == 0.f && vrf == 0.f,
5758 vh == 0.f});
Vlad Popae2f5aef2022-07-25 16:00:20 +02005759
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005760 // now apply the master volume and stream type volume and shaper volume
5761 vlf *= v * vh;
5762 vrf *= v * vh;
Eric Laurent81784c32012-11-19 14:55:58 -08005763 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07005764 // then derive vl and vr as U8.24 versions for the effect chain
5765 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
5766 vl = (uint32_t) (scaleto8_24 * vlf);
5767 vr = (uint32_t) (scaleto8_24 * vrf);
5768 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08005769 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08005770 // send level comes from shared memory and so may be corrupt
5771 if (sendLevel > MAX_GAIN_INT) {
5772 ALOGV("Track send level out of range: %04X", sendLevel);
5773 sendLevel = MAX_GAIN_INT;
5774 }
Andy Hung6be49402014-05-30 10:42:03 -07005775 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
5776 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08005777 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005778
jiabin76d94692022-12-15 21:51:21 +00005779 track->setFinalVolume(vrf, vlf);
Kevin Rocard12381092018-04-11 09:19:59 -07005780
Eric Laurent81784c32012-11-19 14:55:58 -08005781 // Delegate volume control to effect in track effect chain if needed
5782 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
5783 // Do not ramp volume if volume is controlled by effect
5784 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08005785 // Update remaining floating point volume levels
5786 vlf = (float)vl / (1 << 24);
5787 vrf = (float)vr / (1 << 24);
Andy Hung8d31fd22023-06-26 19:20:57 -07005788 track->setHasVolumeController(true);
Eric Laurent81784c32012-11-19 14:55:58 -08005789 } else {
5790 // force no volume ramp when volume controller was just disabled or removed
5791 // from effect chain to avoid volume spike
Andy Hung8d31fd22023-06-26 19:20:57 -07005792 if (track->hasVolumeController()) {
Eric Laurent81784c32012-11-19 14:55:58 -08005793 param = AudioMixer::VOLUME;
5794 }
Andy Hung8d31fd22023-06-26 19:20:57 -07005795 track->setHasVolumeController(false);
Eric Laurent81784c32012-11-19 14:55:58 -08005796 }
5797
Eric Laurent81784c32012-11-19 14:55:58 -08005798 // XXX: these things DON'T need to be done each time
Andy Hung8d31fd22023-06-26 19:20:57 -07005799 mAudioMixer->setBufferProvider(trackId, track->asExtendedAudioBufferProvider());
Andy Hungc0691382018-09-12 18:01:57 -07005800 mAudioMixer->enable(trackId);
Eric Laurent81784c32012-11-19 14:55:58 -08005801
Andy Hungc0691382018-09-12 18:01:57 -07005802 mAudioMixer->setParameter(trackId, param, AudioMixer::VOLUME0, &vlf);
5803 mAudioMixer->setParameter(trackId, param, AudioMixer::VOLUME1, &vrf);
5804 mAudioMixer->setParameter(trackId, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08005805 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005806 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005807 AudioMixer::TRACK,
5808 AudioMixer::FORMAT, (void *)track->format());
5809 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005810 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005811 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00005812 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Eric Laurent39095982021-08-24 18:29:27 +02005813
Eric Laurentb0a7bc92022-04-05 15:06:08 +02005814 if (mType == SPATIALIZER && !track->isSpatialized()) {
Eric Laurent39095982021-08-24 18:29:27 +02005815 mAudioMixer->setParameter(
5816 trackId,
5817 AudioMixer::TRACK,
5818 AudioMixer::MIXER_CHANNEL_MASK,
5819 (void *)(uintptr_t)(mChannelMask | mHapticChannelMask));
5820 } else {
5821 mAudioMixer->setParameter(
5822 trackId,
5823 AudioMixer::TRACK,
5824 AudioMixer::MIXER_CHANNEL_MASK,
5825 (void *)(uintptr_t)(mMixerChannelMask | mHapticChannelMask));
5826 }
5827
Glenn Kastene3aa6592012-12-04 12:22:46 -08005828 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07005829 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Andy Hung333ab962019-05-28 20:23:35 -07005830 uint32_t reqSampleRate = proxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08005831 if (reqSampleRate == 0) {
5832 reqSampleRate = mSampleRate;
5833 } else if (reqSampleRate > maxSampleRate) {
5834 reqSampleRate = maxSampleRate;
5835 }
Eric Laurent81784c32012-11-19 14:55:58 -08005836 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005837 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005838 AudioMixer::RESAMPLE,
5839 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00005840 (void *)(uintptr_t)reqSampleRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005841
Andy Hung8edb8dc2015-03-26 19:13:55 -07005842 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005843 trackId,
Andy Hung8edb8dc2015-03-26 19:13:55 -07005844 AudioMixer::TIMESTRETCH,
5845 AudioMixer::PLAYBACK_RATE,
Andy Hung920f6572022-10-06 12:09:49 -07005846 // cast away constness for this generic API.
5847 const_cast<void *>(reinterpret_cast<const void *>(&playbackRate)));
Andy Hung8edb8dc2015-03-26 19:13:55 -07005848
Andy Hung69aed5f2014-02-25 17:24:40 -08005849 /*
5850 * Select the appropriate output buffer for the track.
5851 *
Andy Hung98ef9782014-03-04 14:46:50 -08005852 * Tracks with effects go into their own effects chain buffer
5853 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08005854 *
5855 * Other tracks can use mMixerBuffer for higher precision
5856 * channel accumulation. If this buffer is enabled
5857 * (mMixerBufferEnabled true), then selected tracks will accumulate
5858 * into it.
5859 *
5860 */
5861 if (mMixerBufferEnabled
5862 && (track->mainBuffer() == mSinkBuffer
5863 || track->mainBuffer() == mMixerBuffer)) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02005864 if (mType == SPATIALIZER && !track->isSpatialized()) {
Eric Laurent39095982021-08-24 18:29:27 +02005865 mAudioMixer->setParameter(
5866 trackId,
5867 AudioMixer::TRACK,
Eric Laurentb62d0362021-10-26 17:40:18 +02005868 AudioMixer::MIXER_FORMAT, (void *)mEffectBufferFormat);
Eric Laurent39095982021-08-24 18:29:27 +02005869 mAudioMixer->setParameter(
5870 trackId,
5871 AudioMixer::TRACK,
Eric Laurentb62d0362021-10-26 17:40:18 +02005872 AudioMixer::MAIN_BUFFER, (void *)mPostSpatializerBuffer);
Eric Laurent39095982021-08-24 18:29:27 +02005873 } else {
5874 mAudioMixer->setParameter(
5875 trackId,
5876 AudioMixer::TRACK,
5877 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
5878 mAudioMixer->setParameter(
5879 trackId,
5880 AudioMixer::TRACK,
5881 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
5882 // TODO: override track->mainBuffer()?
5883 mMixerBufferValid = true;
5884 }
Andy Hung69aed5f2014-02-25 17:24:40 -08005885 } else {
5886 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005887 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08005888 AudioMixer::TRACK,
Andy Hung319587b2023-05-23 14:01:03 -07005889 AudioMixer::MIXER_FORMAT, (void *)AUDIO_FORMAT_PCM_FLOAT);
Andy Hung69aed5f2014-02-25 17:24:40 -08005890 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005891 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08005892 AudioMixer::TRACK,
5893 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
5894 }
Eric Laurent81784c32012-11-19 14:55:58 -08005895 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005896 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005897 AudioMixer::TRACK,
5898 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
jiabin245cdd92018-12-07 17:55:15 -08005899 mAudioMixer->setParameter(
5900 trackId,
5901 AudioMixer::TRACK,
5902 AudioMixer::HAPTIC_ENABLED, (void *)(uintptr_t)track->getHapticPlaybackEnabled());
jiabin77270b82018-12-18 15:41:29 -08005903 mAudioMixer->setParameter(
5904 trackId,
5905 AudioMixer::TRACK,
5906 AudioMixer::HAPTIC_INTENSITY, (void *)(uintptr_t)track->getHapticIntensity());
Andy Hung8d31fd22023-06-26 19:20:57 -07005907 const float hapticMaxAmplitude = track->getHapticMaxAmplitude();
Lais Andradebc3f37a2021-07-02 00:13:19 +01005908 mAudioMixer->setParameter(
5909 trackId,
5910 AudioMixer::TRACK,
Andy Hung8d31fd22023-06-26 19:20:57 -07005911 AudioMixer::HAPTIC_MAX_AMPLITUDE, (void *)&hapticMaxAmplitude);
Eric Laurent81784c32012-11-19 14:55:58 -08005912
5913 // reset retry count
Andy Hung8d31fd22023-06-26 19:20:57 -07005914 track->retryCount() = kMaxTrackRetries;
Eric Laurent81784c32012-11-19 14:55:58 -08005915
5916 // If one track is ready, set the mixer ready if:
5917 // - the mixer was not ready during previous round OR
5918 // - no other track is not ready
5919 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
5920 mixerStatus != MIXER_TRACKS_ENABLED) {
5921 mixerStatus = MIXER_TRACKS_READY;
5922 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08005923
5924 // Enable the next few lines to instrument a test for underrun log handling.
5925 // TODO: Remove when we have a better way of testing the underrun log.
5926#if 0
5927 static int i;
5928 if ((++i & 0xf) == 0) {
5929 deferredOperations.tallyUnderrunFrames(track, 10 /* underrunFrames */);
5930 }
5931#endif
Eric Laurent81784c32012-11-19 14:55:58 -08005932 } else {
Andy Hungbd3b2b02018-05-21 10:53:11 -07005933 size_t underrunFrames = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005934 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Andy Hungb68f5eb2019-12-03 16:49:17 -08005935 ALOGV("track(%d) underrun, track state %s framesReady(%zu) < framesDesired(%zd)",
5936 trackId, track->getTrackStateAsString(), framesReady, desiredFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07005937 underrunFrames = desiredFrames;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005938 }
Andy Hungbd3b2b02018-05-21 10:53:11 -07005939 deferredOperations.tallyUnderrunFrames(track, underrunFrames);
Phil Burk2812d9e2016-01-04 10:34:30 -08005940
Eric Laurent81784c32012-11-19 14:55:58 -08005941 // clear effect chain input buffer if an active track underruns to avoid sending
5942 // previous audio buffer again to effects
5943 chain = getEffectChain_l(track->sessionId());
5944 if (chain != 0) {
5945 chain->clearInputBuffer();
5946 }
5947
Andy Hungc0691382018-09-12 18:01:57 -07005948 ALOGVV("track(%d) s=%08x [NOT READY] on thread %p", trackId, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08005949 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
5950 track->isStopped() || track->isPaused()) {
5951 // We have consumed all the buffers of this track.
5952 // Remove it from the list of active tracks.
5953 // TODO: use actual buffer filling status instead of latency when available from
5954 // audio HAL
5955 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08005956 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005957 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
5958 if (track->isStopped()) {
5959 track->reset();
5960 }
5961 tracksToRemove->add(track);
5962 }
5963 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08005964 // No buffers for this track. Give it a few chances to
5965 // fill a buffer, then remove it from active list.
Andy Hung8d31fd22023-06-26 19:20:57 -07005966 if (--(track->retryCount()) <= 0) {
Andy Hungc0691382018-09-12 18:01:57 -07005967 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p",
5968 trackId, this);
Eric Laurent81784c32012-11-19 14:55:58 -08005969 tracksToRemove->add(track);
5970 // indicate to client process that the track was disabled because of underrun;
5971 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08005972 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08005973 // If one track is not ready, mark the mixer also not ready if:
5974 // - the mixer was ready during previous round OR
5975 // - no other track is ready
5976 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
5977 mixerStatus != MIXER_TRACKS_READY) {
5978 mixerStatus = MIXER_TRACKS_ENABLED;
5979 }
5980 }
Andy Hungc0691382018-09-12 18:01:57 -07005981 mAudioMixer->disable(trackId);
Eric Laurent81784c32012-11-19 14:55:58 -08005982 }
5983
5984 } // local variable scope to avoid goto warning
Eric Laurent81784c32012-11-19 14:55:58 -08005985
5986 }
5987
jiabin245cdd92018-12-07 17:55:15 -08005988 if (mHapticChannelMask != AUDIO_CHANNEL_NONE && sq != NULL) {
5989 // When there is no fast track playing haptic and FastMixer exists,
5990 // enabling the first FastTrack, which provides mixed data from normal
5991 // tracks, to play haptic data.
5992 FastTrack *fastTrack = &state->mFastTracks[0];
5993 if (fastTrack->mHapticPlaybackEnabled != noFastHapticTrack) {
5994 fastTrack->mHapticPlaybackEnabled = noFastHapticTrack;
5995 didModify = true;
5996 }
5997 }
5998
Eric Laurent81784c32012-11-19 14:55:58 -08005999 // Push the new FastMixer state if necessary
Jing Mike537412f2023-03-12 11:01:47 +08006000 [[maybe_unused]] bool pauseAudioWatchdog = false;
Eric Laurent81784c32012-11-19 14:55:58 -08006001 if (didModify) {
6002 state->mFastTracksGen++;
6003 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
6004 if (kUseFastMixer == FastMixer_Dynamic &&
6005 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
6006 state->mCommand = FastMixerState::COLD_IDLE;
6007 state->mColdFutexAddr = &mFastMixerFutex;
6008 state->mColdGen++;
6009 mFastMixerFutex = 0;
6010 if (kUseFastMixer == FastMixer_Dynamic) {
6011 mNormalSink = mOutputSink;
6012 }
6013 // If we go into cold idle, need to wait for acknowledgement
6014 // so that fast mixer stops doing I/O.
6015 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
6016 pauseAudioWatchdog = true;
6017 }
Eric Laurent81784c32012-11-19 14:55:58 -08006018 }
6019 if (sq != NULL) {
6020 sq->end(didModify);
Andy Hungf2285312017-02-14 18:31:59 -08006021 // No need to block if the FastMixer is in COLD_IDLE as the FastThread
6022 // is not active. (We BLOCK_UNTIL_ACKED when entering COLD_IDLE
6023 // when bringing the output sink into standby.)
6024 //
6025 // We will get the latest FastMixer state when we come out of COLD_IDLE.
6026 //
6027 // This occurs with BT suspend when we idle the FastMixer with
6028 // active tracks, which may be added or removed.
6029 sq->push(coldIdle ? FastMixerStateQueue::BLOCK_NEVER : block);
Eric Laurent81784c32012-11-19 14:55:58 -08006030 }
6031#ifdef AUDIO_WATCHDOG
6032 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
6033 mAudioWatchdog->pause();
6034 }
6035#endif
6036
6037 // Now perform the deferred reset on fast tracks that have stopped
6038 while (resetMask != 0) {
6039 size_t i = __builtin_ctz(resetMask);
6040 ALOG_ASSERT(i < count);
6041 resetMask &= ~(1 << i);
Andy Hung8d31fd22023-06-26 19:20:57 -07006042 sp<IAfTrack> track = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08006043 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
6044 track->reset();
6045 }
6046
Andy Hung80d03d22018-04-10 10:32:11 -07006047 // Track destruction may occur outside of threadLoop once it is removed from active tracks.
6048 // Ensure the AudioMixer doesn't have a raw "buffer provider" pointer to the track if
6049 // it ceases to be active, to allow safe removal from the AudioMixer at the start
6050 // of prepareTracks_l(); this releases any outstanding buffer back to the track.
6051 // See also the implementation of destroyTrack_l().
6052 for (const auto &track : *tracksToRemove) {
Andy Hungc0691382018-09-12 18:01:57 -07006053 const int trackId = track->id();
6054 if (mAudioMixer->exists(trackId)) { // Normal tracks here, fast tracks in FastMixer.
6055 mAudioMixer->setBufferProvider(trackId, nullptr /* bufferProvider */);
Andy Hung80d03d22018-04-10 10:32:11 -07006056 }
6057 }
6058
Eric Laurent81784c32012-11-19 14:55:58 -08006059 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08006060 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08006061
Eric Laurentb3f315a2021-07-13 15:09:05 +02006062 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0 ||
6063 getEffectChain_l(AUDIO_SESSION_OUTPUT_STAGE) != 0) {
Eric Laurent97d547d2014-09-02 14:45:53 -07006064 mEffectBufferValid = true;
Marco Nelissenac302142014-10-20 13:15:38 -07006065 }
6066
6067 if (mEffectBufferValid) {
Marco Nelissen57088b52014-10-17 16:39:39 -07006068 // as long as there are effects we should clear the effects buffer, to avoid
6069 // passing a non-clean buffer to the effect chain
6070 memset(mEffectBuffer, 0, mEffectBufferSize);
Eric Laurentb62d0362021-10-26 17:40:18 +02006071 if (mType == SPATIALIZER) {
6072 memset(mPostSpatializerBuffer, 0, mPostSpatializerBufferSize);
6073 }
Eric Laurent97d547d2014-09-02 14:45:53 -07006074 }
Andy Hung69aed5f2014-02-25 17:24:40 -08006075 // sink or mix buffer must be cleared if all tracks are connected to an
6076 // effect chain as in this case the mixer will not write to the sink or mix buffer
6077 // and track effects will accumulate into it
Eric Laurent39095982021-08-24 18:29:27 +02006078 // always clear sink buffer for spatializer output as the output of the spatializer
6079 // effect will be accumulated into it
6080 if ((mBytesRemaining == 0) && (((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
6081 (mixedTracks == 0 && fastTracks > 0)) || (mType == SPATIALIZER))) {
Eric Laurent81784c32012-11-19 14:55:58 -08006082 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08006083 if (mMixerBufferValid) {
6084 memset(mMixerBuffer, 0, mMixerBufferSize);
6085 // TODO: In testing, mSinkBuffer below need not be cleared because
6086 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
6087 // after mixing.
6088 //
6089 // To enforce this guarantee:
6090 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
6091 // (mixedTracks == 0 && fastTracks > 0))
6092 // must imply MIXER_TRACKS_READY.
6093 // Later, we may clear buffers regardless, and skip much of this logic.
6094 }
Andy Hung98ef9782014-03-04 14:46:50 -08006095 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07006096 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08006097 }
6098
6099 // if any fast tracks, then status is ready
6100 mMixerStatusIgnoringFastTracks = mixerStatus;
6101 if (fastTracks > 0) {
6102 mixerStatus = MIXER_TRACKS_READY;
6103 }
6104 return mixerStatus;
6105}
6106
Eric Laurentad7dd962016-09-22 12:38:37 -07006107// trackCountForUid_l() must be called with ThreadBase::mLock held
Andy Hungee58e4a2023-07-07 13:47:37 -07006108uint32_t PlaybackThread::trackCountForUid_l(uid_t uid) const
Eric Laurentad7dd962016-09-22 12:38:37 -07006109{
6110 uint32_t trackCount = 0;
6111 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hung1f12a8a2016-11-07 16:10:30 -08006112 if (mTracks[i]->uid() == uid) {
Eric Laurentad7dd962016-09-22 12:38:37 -07006113 trackCount++;
6114 }
6115 }
6116 return trackCount;
6117}
6118
Andy Hungee58e4a2023-07-07 13:47:37 -07006119bool PlaybackThread::IsTimestampAdvancing::check(AudioStreamOut* output)
ziyangch8f194f12021-12-01 13:48:04 -08006120{
Brian Lindahl65e90012022-07-27 18:01:07 +02006121 // Check the timestamp to see if it's advancing once every 150ms. If we check too frequently, we
6122 // could falsely detect that the frame position has stalled due to underrun because we haven't
6123 // given the Audio HAL enough time to update.
6124 const nsecs_t nowNs = systemTime();
6125 if (nowNs - mPreviousNs < mMinimumTimeBetweenChecksNs) {
6126 return mLatchedValue;
6127 }
6128 mPreviousNs = nowNs;
6129 mLatchedValue = false;
6130 // Determine if the presentation position is still advancing.
ziyangch8f194f12021-12-01 13:48:04 -08006131 uint64_t position = 0;
6132 struct timespec unused;
Brian Lindahl65e90012022-07-27 18:01:07 +02006133 const status_t ret = output->getPresentationPosition(&position, &unused);
ziyangch8f194f12021-12-01 13:48:04 -08006134 if (ret == NO_ERROR) {
Brian Lindahl65e90012022-07-27 18:01:07 +02006135 if (position != mPreviousPosition) {
6136 mPreviousPosition = position;
6137 mLatchedValue = true;
ziyangch8f194f12021-12-01 13:48:04 -08006138 }
6139 }
Brian Lindahl65e90012022-07-27 18:01:07 +02006140 return mLatchedValue;
6141}
6142
Andy Hungee58e4a2023-07-07 13:47:37 -07006143void PlaybackThread::IsTimestampAdvancing::clear()
Brian Lindahl65e90012022-07-27 18:01:07 +02006144{
6145 mLatchedValue = true;
6146 mPreviousPosition = 0;
6147 mPreviousNs = 0;
ziyangch8f194f12021-12-01 13:48:04 -08006148}
6149
Andy Hung1bc088a2018-02-09 15:57:31 -08006150// isTrackAllowed_l() must be called with ThreadBase::mLock held
Andy Hungee58e4a2023-07-07 13:47:37 -07006151bool MixerThread::isTrackAllowed_l(
Andy Hung1bc088a2018-02-09 15:57:31 -08006152 audio_channel_mask_t channelMask, audio_format_t format,
6153 audio_session_t sessionId, uid_t uid) const
Eric Laurent81784c32012-11-19 14:55:58 -08006154{
Andy Hung1bc088a2018-02-09 15:57:31 -08006155 if (!PlaybackThread::isTrackAllowed_l(channelMask, format, sessionId, uid)) {
6156 return false;
Eric Laurentad7dd962016-09-22 12:38:37 -07006157 }
Andy Hung1bc088a2018-02-09 15:57:31 -08006158 // Check validity as we don't call AudioMixer::create() here.
Mikhail Naganov7ad7a252019-07-30 14:42:32 -07006159 if (!mAudioMixer->isValidFormat(format)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08006160 ALOGW("%s: invalid format: %#x", __func__, format);
6161 return false;
6162 }
Mikhail Naganov7ad7a252019-07-30 14:42:32 -07006163 if (!mAudioMixer->isValidChannelMask(channelMask)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08006164 ALOGW("%s: invalid channelMask: %#x", __func__, channelMask);
6165 return false;
6166 }
6167 return true;
Eric Laurent81784c32012-11-19 14:55:58 -08006168}
6169
Eric Laurent10351942014-05-08 18:49:52 -07006170// checkForNewParameter_l() must be called with ThreadBase::mLock held
Andy Hungee58e4a2023-07-07 13:47:37 -07006171bool MixerThread::checkForNewParameter_l(const String8& keyValuePair,
Eric Laurent10351942014-05-08 18:49:52 -07006172 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08006173{
Eric Laurent81784c32012-11-19 14:55:58 -08006174 bool reconfig = false;
Eric Laurent10351942014-05-08 18:49:52 -07006175 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006176
Glenn Kastenc05b8d72016-03-24 09:48:17 -07006177 AutoPark<FastMixer> park(mFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08006178
Eric Laurent10351942014-05-08 18:49:52 -07006179 AudioParameter param = AudioParameter(keyValuePair);
6180 int value;
6181 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
6182 reconfig = true;
6183 }
6184 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hungee58e4a2023-07-07 13:47:37 -07006185 if (!AudioFlinger::isValidPcmSinkFormat(static_cast<audio_format_t>(value))) {
Eric Laurent10351942014-05-08 18:49:52 -07006186 status = BAD_VALUE;
6187 } else {
6188 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08006189 reconfig = true;
6190 }
Eric Laurent10351942014-05-08 18:49:52 -07006191 }
6192 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hungee58e4a2023-07-07 13:47:37 -07006193 if (!AudioFlinger::isValidPcmSinkChannelMask(static_cast<audio_channel_mask_t>(value))) {
Eric Laurent10351942014-05-08 18:49:52 -07006194 status = BAD_VALUE;
6195 } else {
6196 // no need to save value, since it's constant
6197 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006198 }
Eric Laurent10351942014-05-08 18:49:52 -07006199 }
6200 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6201 // do not accept frame count changes if tracks are open as the track buffer
6202 // size depends on frame count and correct behavior would not be guaranteed
6203 // if frame count is changed after track creation
6204 if (!mTracks.isEmpty()) {
6205 status = INVALID_OPERATION;
6206 } else {
6207 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006208 }
Eric Laurent10351942014-05-08 18:49:52 -07006209 }
6210 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07006211 LOG_FATAL("Should not set routing device in MixerThread");
Eric Laurent10351942014-05-08 18:49:52 -07006212 }
Eric Laurent81784c32012-11-19 14:55:58 -08006213
Eric Laurent10351942014-05-08 18:49:52 -07006214 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006215 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07006216 if (!mStandby && status == INVALID_OPERATION) {
Andy Hungdda7aed2023-03-27 15:53:06 -07006217 ALOGW("%s: setParameters failed with keyValuePair %s, entering standby",
6218 __func__, keyValuePair.c_str());
Phil Burk062e67a2015-02-11 13:40:50 -08006219 mOutput->standby();
Andy Hungdda7aed2023-03-27 15:53:06 -07006220 mThreadMetrics.logEndInterval();
6221 mThreadSnapshot.onEnd();
6222 setStandby_l();
Eric Laurent10351942014-05-08 18:49:52 -07006223 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006224 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent81784c32012-11-19 14:55:58 -08006225 }
Eric Laurent10351942014-05-08 18:49:52 -07006226 if (status == NO_ERROR && reconfig) {
6227 readOutputParameters_l();
6228 delete mAudioMixer;
6229 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
Andy Hung1bc088a2018-02-09 15:57:31 -08006230 for (const auto &track : mTracks) {
Andy Hungc0691382018-09-12 18:01:57 -07006231 const int trackId = track->id();
Andy Hung920f6572022-10-06 12:09:49 -07006232 const status_t createStatus = mAudioMixer->create(
Andy Hungc0691382018-09-12 18:01:57 -07006233 trackId,
Andy Hung8d31fd22023-06-26 19:20:57 -07006234 track->channelMask(),
6235 track->format(),
6236 track->sessionId());
Andy Hung920f6572022-10-06 12:09:49 -07006237 ALOGW_IF(createStatus != NO_ERROR,
Andy Hungc0691382018-09-12 18:01:57 -07006238 "%s(): AudioMixer cannot create track(%d)"
6239 " mask %#x, format %#x, sessionId %d",
Andy Hung1bc088a2018-02-09 15:57:31 -08006240 __func__,
Andy Hung8d31fd22023-06-26 19:20:57 -07006241 trackId, track->channelMask(), track->format(), track->sessionId());
Eric Laurent10351942014-05-08 18:49:52 -07006242 }
Eric Laurent73e26b62015-04-27 16:55:58 -07006243 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07006244 }
Eric Laurent81784c32012-11-19 14:55:58 -08006245 }
6246
Dean Wheatley68918102021-03-19 22:09:19 +11006247 return reconfig;
Eric Laurent81784c32012-11-19 14:55:58 -08006248}
6249
6250
Andy Hungee58e4a2023-07-07 13:47:37 -07006251void MixerThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -08006252{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07006253 PlaybackThread::dumpInternals_l(fd, args);
Andy Hung40eb1a12015-06-18 13:42:02 -07006254 dprintf(fd, " Thread throttle time (msecs): %u\n", mThreadThrottleTimeMs);
Andy Hung8ed196a2018-01-05 13:21:11 -08006255 dprintf(fd, " AudioMixer tracks: %s\n", mAudioMixer->trackNames().c_str());
Andy Hung2ddee192015-12-18 17:34:44 -08006256 dprintf(fd, " Master mono: %s\n", mMasterMono ? "on" : "off");
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006257 dprintf(fd, " Master balance: %f (%s)\n", mMasterBalance.load(),
6258 (hasFastMixer() ? std::to_string(mFastMixer->getMasterBalance())
6259 : mBalance.toString()).c_str());
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006260 if (hasFastMixer()) {
6261 dprintf(fd, " FastMixer thread %p tid=%d", mFastMixer.get(), mFastMixer->getTid());
6262
6263 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
6264 // while we are dumping it. It may be inconsistent, but it won't mutate!
6265 // This is a large object so we place it on the heap.
6266 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
Eric Tan2942a4e2018-09-12 17:41:27 -07006267 const std::unique_ptr<FastMixerDumpState> copy =
6268 std::make_unique<FastMixerDumpState>(mFastMixerDumpState);
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006269 copy->dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08006270
6271#ifdef STATE_QUEUE_DUMP
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006272 // Similar for state queue
6273 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
6274 observerCopy.dump(fd);
6275 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
6276 mutatorCopy.dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08006277#endif
6278
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006279#ifdef AUDIO_WATCHDOG
6280 if (mAudioWatchdog != 0) {
6281 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
6282 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
6283 wdCopy.dump(fd);
6284 }
6285#endif
6286
6287 } else {
6288 dprintf(fd, " No FastMixer\n");
6289 }
Eric Laurent90cea102023-05-15 15:08:27 +02006290
6291 dprintf(fd, "Bluetooth latency modes are %senabled\n",
6292 mBluetoothLatencyModesEnabled ? "" : "not ");
6293 dprintf(fd, "HAL does %ssupport Bluetooth latency modes\n", mOutput != nullptr &&
6294 mOutput->audioHwDev->supportsBluetoothVariableLatency() ? "" : "not ");
6295 dprintf(fd, "Supported latency modes: %s\n", toString(mSupportedLatencyModes).c_str());
Eric Laurent81784c32012-11-19 14:55:58 -08006296}
6297
Andy Hungee58e4a2023-07-07 13:47:37 -07006298uint32_t MixerThread::idleSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08006299{
6300 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
6301}
6302
Andy Hungee58e4a2023-07-07 13:47:37 -07006303uint32_t MixerThread::suspendSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08006304{
6305 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
6306}
6307
Andy Hungee58e4a2023-07-07 13:47:37 -07006308void MixerThread::cacheParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08006309{
6310 PlaybackThread::cacheParameters_l();
6311
6312 // FIXME: Relaxed timing because of a certain device that can't meet latency
6313 // Should be reduced to 2x after the vendor fixes the driver issue
6314 // increase threshold again due to low power audio mode. The way this warning
6315 // threshold is calculated and its usefulness should be reconsidered anyway.
6316 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
6317}
6318
Andy Hungee58e4a2023-07-07 13:47:37 -07006319void MixerThread::onHalLatencyModesChanged_l() {
Andy Hung583043b2023-07-17 17:05:00 -07006320 mAfThreadCallback->onSupportedLatencyModesChanged(mId, mSupportedLatencyModes);
Eric Laurentb0463942022-12-20 16:31:10 +01006321}
6322
Andy Hungee58e4a2023-07-07 13:47:37 -07006323void MixerThread::setHalLatencyMode_l() {
Eric Laurentb0463942022-12-20 16:31:10 +01006324 // Only handle latency mode if:
6325 // - mBluetoothLatencyModesEnabled is true
6326 // - the HAL supports latency modes
6327 // - the selected device is Bluetooth LE or A2DP
6328 if (!mBluetoothLatencyModesEnabled.load() || mSupportedLatencyModes.empty()) {
6329 return;
6330 }
6331 if (mOutDeviceTypeAddrs.size() != 1
6332 || !(audio_is_a2dp_out_device(mOutDeviceTypeAddrs[0].mType)
6333 || audio_is_ble_out_device(mOutDeviceTypeAddrs[0].mType))) {
6334 return;
6335 }
6336
6337 audio_latency_mode_t latencyMode = AUDIO_LATENCY_MODE_FREE;
6338 if (mSupportedLatencyModes.size() == 1) {
6339 // If the HAL only support one latency mode currently, confirm the choice
6340 latencyMode = mSupportedLatencyModes[0];
6341 } else if (mSupportedLatencyModes.size() > 1) {
6342 // Request low latency if:
6343 // - At least one active track is either:
6344 // - a fast track with gaming usage or
6345 // - a track with acessibility usage
6346 for (const auto& track : mActiveTracks) {
6347 if ((track->isFastTrack() && track->attributes().usage == AUDIO_USAGE_GAME)
6348 || track->attributes().usage == AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY) {
6349 latencyMode = AUDIO_LATENCY_MODE_LOW;
6350 break;
6351 }
6352 }
6353 }
6354
6355 if (latencyMode != mSetLatencyMode) {
6356 status_t status = mOutput->stream->setLatencyMode(latencyMode);
6357 ALOGD("%s: thread(%d) setLatencyMode(%s) returned %d",
6358 __func__, mId, toString(latencyMode).c_str(), status);
6359 if (status == NO_ERROR) {
6360 mSetLatencyMode = latencyMode;
6361 }
6362 }
6363}
6364
Andy Hungee58e4a2023-07-07 13:47:37 -07006365void MixerThread::updateHalSupportedLatencyModes_l() {
Eric Laurentb0463942022-12-20 16:31:10 +01006366
6367 if (mOutput == nullptr || mOutput->stream == nullptr) {
6368 return;
6369 }
6370 std::vector<audio_latency_mode_t> latencyModes;
6371 const status_t status = mOutput->stream->getRecommendedLatencyModes(&latencyModes);
6372 if (status != NO_ERROR) {
6373 latencyModes.clear();
6374 }
6375 if (latencyModes != mSupportedLatencyModes) {
6376 ALOGD("%s: thread(%d) status %d supported latency modes: %s",
6377 __func__, mId, status, toString(latencyModes).c_str());
6378 mSupportedLatencyModes.swap(latencyModes);
6379 sendHalLatencyModesChangedEvent_l();
6380 }
6381}
6382
Andy Hungee58e4a2023-07-07 13:47:37 -07006383status_t MixerThread::getSupportedLatencyModes(
Eric Laurentb0463942022-12-20 16:31:10 +01006384 std::vector<audio_latency_mode_t>* modes) {
6385 if (modes == nullptr) {
6386 return BAD_VALUE;
6387 }
6388 Mutex::Autolock _l(mLock);
6389 *modes = mSupportedLatencyModes;
6390 return NO_ERROR;
6391}
6392
Andy Hungee58e4a2023-07-07 13:47:37 -07006393void MixerThread::onRecommendedLatencyModeChanged(
Eric Laurentb0463942022-12-20 16:31:10 +01006394 std::vector<audio_latency_mode_t> modes) {
6395 Mutex::Autolock _l(mLock);
6396 if (modes != mSupportedLatencyModes) {
6397 ALOGD("%s: thread(%d) supported latency modes: %s",
6398 __func__, mId, toString(modes).c_str());
6399 mSupportedLatencyModes.swap(modes);
6400 sendHalLatencyModesChangedEvent_l();
6401 }
6402}
6403
Andy Hungee58e4a2023-07-07 13:47:37 -07006404status_t MixerThread::setBluetoothVariableLatencyEnabled(bool enabled) {
Eric Laurentb0463942022-12-20 16:31:10 +01006405 if (mOutput == nullptr || mOutput->audioHwDev == nullptr
6406 || !mOutput->audioHwDev->supportsBluetoothVariableLatency()) {
6407 return INVALID_OPERATION;
6408 }
6409 mBluetoothLatencyModesEnabled.store(enabled);
6410 return NO_ERROR;
6411}
6412
Eric Laurent81784c32012-11-19 14:55:58 -08006413// ----------------------------------------------------------------------------
6414
Andy Hungee58e4a2023-07-07 13:47:37 -07006415/* static */
6416sp<IAfPlaybackThread> IAfPlaybackThread::createDirectOutputThread(
Andy Hung583043b2023-07-17 17:05:00 -07006417 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hungee58e4a2023-07-07 13:47:37 -07006418 AudioStreamOut* output, audio_io_handle_t id, bool systemReady,
6419 const audio_offload_info_t& offloadInfo) {
6420 return sp<DirectOutputThread>::make(
Andy Hung583043b2023-07-17 17:05:00 -07006421 afThreadCallback, output, id, systemReady, offloadInfo);
Andy Hungee58e4a2023-07-07 13:47:37 -07006422}
6423
Andy Hung583043b2023-07-17 17:05:00 -07006424DirectOutputThread::DirectOutputThread(const sp<IAfThreadCallback>& afThreadCallback,
Gareth Fennb18c1a32022-10-05 13:42:36 -07006425 AudioStreamOut* output, audio_io_handle_t id, ThreadBase::type_t type, bool systemReady,
6426 const audio_offload_info_t& offloadInfo)
Andy Hung583043b2023-07-17 17:05:00 -07006427 : PlaybackThread(afThreadCallback, output, id, type, systemReady)
Gareth Fennb18c1a32022-10-05 13:42:36 -07006428 , mOffloadInfo(offloadInfo)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006429{
Andy Hung583043b2023-07-17 17:05:00 -07006430 setMasterBalance(afThreadCallback->getMasterBalance_l());
Eric Laurentbfb1b832013-01-07 09:53:42 -08006431}
6432
Andy Hungee58e4a2023-07-07 13:47:37 -07006433DirectOutputThread::~DirectOutputThread()
Eric Laurent81784c32012-11-19 14:55:58 -08006434{
6435}
6436
Andy Hungee58e4a2023-07-07 13:47:37 -07006437void DirectOutputThread::dumpInternals_l(int fd, const Vector<String16>& args)
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006438{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07006439 PlaybackThread::dumpInternals_l(fd, args);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006440 dprintf(fd, " Master balance: %f Left: %f Right: %f\n",
6441 mMasterBalance.load(), mMasterBalanceLeft, mMasterBalanceRight);
6442}
6443
Andy Hungee58e4a2023-07-07 13:47:37 -07006444void DirectOutputThread::setMasterBalance(float balance)
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006445{
6446 Mutex::Autolock _l(mLock);
6447 if (mMasterBalance != balance) {
6448 mMasterBalance.store(balance);
6449 mBalance.computeStereoBalance(balance, &mMasterBalanceLeft, &mMasterBalanceRight);
6450 broadcast_l();
6451 }
6452}
6453
Andy Hungee58e4a2023-07-07 13:47:37 -07006454void DirectOutputThread::processVolume_l(IAfTrack* track, bool lastTrack)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006455{
Eric Laurentbfb1b832013-01-07 09:53:42 -08006456 float left, right;
6457
Andy Hung333ab962019-05-28 20:23:35 -07006458 // Ensure volumeshaper state always advances even when muted.
Andy Hung8d31fd22023-06-26 19:20:57 -07006459 const sp<AudioTrackServerProxy> proxy = track->audioTrackServerProxy();
Andy Hung398ffa22022-12-13 19:19:53 -08006460
6461 const size_t framesReleased = proxy->framesReleased();
6462 const int64_t frames = mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
6463 const int64_t time = mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
6464
6465 ALOGV("%s: Direct/Offload bufferConsumed:%zu timestamp frames:%lld time:%lld",
6466 __func__, framesReleased, (long long)frames, (long long)time);
6467
6468 const int64_t volumeShaperFrames =
6469 mMonotonicFrameCounter.updateAndGetMonotonicFrameCount(frames, time);
6470 const auto [shaperVolume, shaperActive] =
6471 track->getVolumeHandler()->getVolume(volumeShaperFrames);
Andy Hung333ab962019-05-28 20:23:35 -07006472 mVolumeShaperActive = shaperActive;
6473
Vlad Popae2f5aef2022-07-25 16:00:20 +02006474 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
6475 left = float_from_gain(gain_minifloat_unpack_left(vlr));
6476 right = float_from_gain(gain_minifloat_unpack_right(vlr));
6477
6478 const bool clientVolumeMute = (left == 0.f && right == 0.f);
6479
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08006480 if (mMasterMute || mStreamTypes[track->streamType()].mute || track->isPlaybackRestricted()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08006481 left = right = 0;
6482 } else {
6483 float typeVolume = mStreamTypes[track->streamType()].volume;
Andy Hung333ab962019-05-28 20:23:35 -07006484 const float v = mMasterVolume * typeVolume * shaperVolume;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08006485
Glenn Kastenc56f3422014-03-21 17:53:17 -07006486 if (left > GAIN_FLOAT_UNITY) {
6487 left = GAIN_FLOAT_UNITY;
6488 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07006489 if (right > GAIN_FLOAT_UNITY) {
6490 right = GAIN_FLOAT_UNITY;
6491 }
zhangjincheng86cb3bc2023-01-16 17:17:38 +08006492 left *= v;
6493 right *= v;
Andy Hung583043b2023-07-17 17:05:00 -07006494 if (mAfThreadCallback->getMode() != AUDIO_MODE_IN_COMMUNICATION
zhangjincheng86cb3bc2023-01-16 17:17:38 +08006495 || audio_channel_count_from_out_mask(mChannelMask) > 1) {
6496 left *= mMasterBalanceLeft; // DirectOutputThread balance applied as track volume
6497 right *= mMasterBalanceRight;
6498 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006499 }
6500
Andy Hung583043b2023-07-17 17:05:00 -07006501 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
Vlad Popae8d99472022-06-30 16:02:48 +02006502 /*muteState=*/{mMasterMute,
6503 mStreamTypes[track->streamType()].volume == 0.f,
6504 mStreamTypes[track->streamType()].mute,
Vlad Popae2f5aef2022-07-25 16:00:20 +02006505 track->isPlaybackRestricted(),
Vlad Popa436c9172022-08-02 15:25:08 +02006506 clientVolumeMute,
6507 shaperVolume == 0.f});
Vlad Popae8d99472022-06-30 16:02:48 +02006508
Eric Laurentbfb1b832013-01-07 09:53:42 -08006509 if (lastTrack) {
jiabin76d94692022-12-15 21:51:21 +00006510 track->setFinalVolume(left, right);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006511 if (left != mLeftVolFloat || right != mRightVolFloat) {
6512 mLeftVolFloat = left;
6513 mRightVolFloat = right;
6514
Eric Laurentbfb1b832013-01-07 09:53:42 -08006515 // Delegate volume control to effect in track effect chain if needed
6516 // only one effect chain can be present on DirectOutputThread, so if
6517 // there is one, the track is connected to it
6518 if (!mEffectChains.isEmpty()) {
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09006519 // if effect chain exists, volume is handled by it.
6520 // Convert volumes from float to 8.24
6521 uint32_t vl = (uint32_t)(left * (1 << 24));
6522 uint32_t vr = (uint32_t)(right * (1 << 24));
6523 // Direct/Offload effect chains set output volume in setVolume_l().
6524 (void)mEffectChains[0]->setVolume_l(&vl, &vr);
6525 } else {
6526 // otherwise we directly set the volume.
6527 setVolumeForOutput_l(left, right);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006528 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006529 }
6530 }
6531}
6532
Andy Hungee58e4a2023-07-07 13:47:37 -07006533void DirectOutputThread::onAddNewTrack_l()
Phil Burk43b4dcc2015-06-09 16:53:44 -07006534{
Andy Hung8d31fd22023-06-26 19:20:57 -07006535 sp<IAfTrack> previousTrack = mPreviousTrack.promote();
6536 sp<IAfTrack> latestTrack = mActiveTracks.getLatest();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006537
Eric Laurent0f0631e2015-07-06 18:01:25 -07006538 if (previousTrack != 0 && latestTrack != 0) {
6539 if (mType == DIRECT) {
6540 if (previousTrack.get() != latestTrack.get()) {
6541 mFlushPending = true;
6542 }
6543 } else /* mType == OFFLOAD */ {
Dean Wheatley0f51fd02022-08-31 16:41:40 +10006544 if (previousTrack->sessionId() != latestTrack->sessionId() ||
6545 previousTrack->isFlushPending()) {
Eric Laurent0f0631e2015-07-06 18:01:25 -07006546 mFlushPending = true;
6547 }
6548 }
Revathi Uddaraju20413a92016-10-13 17:16:14 +08006549 } else if (previousTrack == 0) {
6550 // there could be an old track added back during track transition for direct
6551 // output, so always issues flush to flush data of the previous track if it
6552 // was already destroyed with HAL paused, then flush can resume the playback
6553 mFlushPending = true;
Phil Burk43b4dcc2015-06-09 16:53:44 -07006554 }
6555 PlaybackThread::onAddNewTrack_l();
6556}
Eric Laurentbfb1b832013-01-07 09:53:42 -08006557
Andy Hungee58e4a2023-07-07 13:47:37 -07006558PlaybackThread::mixer_state DirectOutputThread::prepareTracks_l(
Andy Hung8d31fd22023-06-26 19:20:57 -07006559 Vector<sp<IAfTrack>>* tracksToRemove
Eric Laurent81784c32012-11-19 14:55:58 -08006560)
6561{
Eric Laurentd595b7c2013-04-03 17:27:56 -07006562 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08006563 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006564 bool doHwPause = false;
6565 bool doHwResume = false;
Eric Laurent81784c32012-11-19 14:55:58 -08006566
6567 // find out which tracks need to be processed
Andy Hung8d31fd22023-06-26 19:20:57 -07006568 for (const sp<IAfTrack>& t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08006569 if (t->isInvalid()) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07006570 ALOGW("An invalidated track shouldn't be in active list");
Eric Laurent5850c4c2016-11-10 13:04:31 -08006571 tracksToRemove->add(t);
Phil Burk43b4dcc2015-06-09 16:53:44 -07006572 continue;
6573 }
6574
Andy Hung8d31fd22023-06-26 19:20:57 -07006575 IAfTrack* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006576#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurent81784c32012-11-19 14:55:58 -08006577 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006578#endif
Eric Laurentfd477972013-10-25 18:10:40 -07006579 // Only consider last track started for volume and mixer state control.
6580 // In theory an older track could underrun and restart after the new one starts
6581 // but as we only care about the transition phase between two tracks on a
6582 // direct output, it is not a problem to ignore the underrun case.
Andy Hung8d31fd22023-06-26 19:20:57 -07006583 sp<IAfTrack> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08006584 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08006585
Kuowei Li23666472021-01-20 10:23:25 +08006586 if (track->isPausePending()) {
6587 track->pauseAck();
6588 // It is possible a track might have been flushed or stopped.
6589 // Other operations such as flush pending might occur on the next prepare.
6590 if (track->isPausing()) {
6591 track->setPaused();
6592 }
6593 // Always perform pause, as an immediate flush will change
6594 // the pause state to be no longer isPausing().
Phil Burk6fc2a7c2015-04-30 16:08:10 -07006595 if (mHwSupportsPause && last && !mHwPaused) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006596 doHwPause = true;
6597 mHwPaused = true;
6598 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08006599 } else if (track->isFlushPending()) {
6600 track->flushAck();
6601 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07006602 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006603 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07006604 } else if (track->isResumePending()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006605 track->resumeAck();
Eric Laurent3df841a2016-07-15 15:15:40 -07006606 if (last) {
6607 mLeftVolFloat = mRightVolFloat = -1.0;
6608 if (mHwPaused) {
6609 doHwResume = true;
6610 mHwPaused = false;
6611 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08006612 }
6613 }
6614
Eric Laurent81784c32012-11-19 14:55:58 -08006615 // The first time a track is added we wait
Phil Burk99adee32014-12-10 16:46:30 -08006616 // for all its buffers to be filled before processing it.
6617 // Allow draining the buffer in case the client
6618 // app does not call stop() and relies on underrun to stop:
Andy Hung8d31fd22023-06-26 19:20:57 -07006619 // hence the test on (track->retryCount() > 1).
6620 // If track->retryCount() <= 1 then track is about to be disabled, paused, removed,
Andy Hung455982f2021-04-27 17:46:12 -07006621 // so we accept any nonzero amount of data delivered by the AudioTrack (which will
6622 // reset the retry counter).
Phil Burkca5e6142015-07-14 09:42:29 -07006623 // Do not use a high threshold for compressed audio.
Andy Hung455982f2021-04-27 17:46:12 -07006624
6625 // target retry count that we will use is based on the time we wait for retries.
6626 const int32_t targetRetryCount = kMaxTrackRetriesDirectMs * 1000 / mActiveSleepTimeUs;
6627 // the retry threshold is when we accept any size for PCM data. This is slightly
6628 // smaller than the retry count so we can push small bits of data without a glitch.
6629 const int32_t retryThreshold = targetRetryCount > 2 ? targetRetryCount - 1 : 1;
Eric Laurent81784c32012-11-19 14:55:58 -08006630 uint32_t minFrames;
Phil Burk99adee32014-12-10 16:46:30 -08006631 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
Andy Hung8d31fd22023-06-26 19:20:57 -07006632 && (track->retryCount() > retryThreshold) && audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006633 minFrames = mNormalFrameCount;
6634 } else {
6635 minFrames = 1;
6636 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006637
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07006638 const size_t framesReady = track->framesReady();
6639 const int trackId = track->id();
6640 if (ATRACE_ENABLED()) {
6641 std::string traceName("nRdy");
6642 traceName += std::to_string(trackId);
6643 ATRACE_INT(traceName.c_str(), framesReady);
6644 }
6645 if ((framesReady >= minFrames) && track->isReady() && !track->isPaused() &&
Eric Laurentab5cdba2014-06-09 17:22:27 -07006646 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08006647 {
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07006648 ALOGVV("track(%d) s=%08x [OK]", trackId, cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08006649
Andy Hung8d31fd22023-06-26 19:20:57 -07006650 if (track->fillingStatus() == IAfTrack::FS_FILLED) {
6651 track->fillingStatus() = IAfTrack::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07006652 if (last) {
6653 // make sure processVolume_l() will apply new volume even if 0
6654 mLeftVolFloat = mRightVolFloat = -1.0;
6655 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08006656 if (!mHwSupportsPause) {
6657 track->resumeAck();
Eric Laurent81784c32012-11-19 14:55:58 -08006658 }
6659 }
6660
6661 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08006662 processVolume_l(track, last);
6663 if (last) {
Andy Hung8d31fd22023-06-26 19:20:57 -07006664 sp<IAfTrack> previousTrack = mPreviousTrack.promote();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006665 if (previousTrack != 0) {
6666 if (track != previousTrack.get()) {
6667 // Flush any data still being written from last track
6668 mBytesRemaining = 0;
Eric Laurent0f0631e2015-07-06 18:01:25 -07006669 // Invalidate previous track to force a seek when resuming.
6670 previousTrack->invalidate();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006671 }
6672 }
6673 mPreviousTrack = track;
6674
Eric Laurentd595b7c2013-04-03 17:27:56 -07006675 // reset retry count
Andy Hung8d31fd22023-06-26 19:20:57 -07006676 track->retryCount() = targetRetryCount;
Eric Laurent5850c4c2016-11-10 13:04:31 -08006677 mActiveTrack = t;
Eric Laurentd595b7c2013-04-03 17:27:56 -07006678 mixerStatus = MIXER_TRACKS_READY;
Eric Laurent5cff4032015-05-26 13:49:58 -07006679 if (mHwPaused) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08006680 doHwResume = true;
6681 mHwPaused = false;
6682 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07006683 }
Eric Laurent81784c32012-11-19 14:55:58 -08006684 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07006685 // clear effect chain input buffer if the last active track started underruns
6686 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07006687 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08006688 mEffectChains[0]->clearInputBuffer();
6689 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07006690 if (track->isStopping_1()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07006691 track->setState(IAfTrackBase::STOPPING_2);
Eric Laurentb369caf2015-03-30 20:51:47 -07006692 if (last && mHwPaused) {
6693 doHwResume = true;
6694 mHwPaused = false;
6695 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07006696 }
6697 if ((track->sharedBuffer() != 0) || track->isStopped() ||
6698 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08006699 // We have consumed all the buffers of this track.
6700 // Remove it from the list of active tracks.
Atneya Nair0cae0432022-05-10 18:12:12 -04006701 bool presComplete = false;
Eric Laurentfd477972013-10-25 18:10:40 -07006702 if (mStandby || !last ||
Atneya Nair0cae0432022-05-10 18:12:12 -04006703 (presComplete = track->presentationComplete(latency_l())) ||
Jindong32dc26e2019-11-11 18:10:01 +08006704 track->isPaused() || mHwPaused) {
Atneya Nair0cae0432022-05-10 18:12:12 -04006705 if (presComplete) {
6706 mOutput->presentationComplete();
6707 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07006708 if (track->isStopping_2()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07006709 track->setState(IAfTrackBase::STOPPED);
Eric Laurentab5cdba2014-06-09 17:22:27 -07006710 }
Eric Laurent81784c32012-11-19 14:55:58 -08006711 if (track->isStopped()) {
6712 track->reset();
6713 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07006714 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08006715 }
6716 } else {
6717 // No buffers for this track. Give it a few chances to
6718 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07006719 // Only consider last track started for mixer state control
Brian Lindahl65e90012022-07-27 18:01:07 +02006720 bool isTimestampAdvancing = mIsTimestampAdvancing.check(mOutput);
Gareth Fennb18c1a32022-10-05 13:42:36 -07006721 if (!isTunerStream() // tuner streams remain active in underrun
Andy Hung8d31fd22023-06-26 19:20:57 -07006722 && --(track->retryCount()) <= 0) {
Brian Lindahl65e90012022-07-27 18:01:07 +02006723 if (isTimestampAdvancing) { // HAL is still playing audio, give us more time.
Andy Hung8d31fd22023-06-26 19:20:57 -07006724 track->retryCount() = kMaxTrackRetriesOffload;
ziyangch8f194f12021-12-01 13:48:04 -08006725 } else {
6726 ALOGV("BUFFER TIMEOUT: remove track(%d) from active list", trackId);
6727 tracksToRemove->add(track);
6728 // indicate to client process that the track was disabled because of
6729 // underrun; it will then automatically call start() when data is available
6730 track->disable();
6731 // only do hw pause when track is going to be removed due to BUFFER TIMEOUT.
6732 // unlike mixerthread, HAL can be paused for direct output
6733 ALOGW("pause because of UNDERRUN, framesReady = %zu,"
6734 "minFrames = %u, mFormat = %#x",
6735 framesReady, minFrames, mFormat);
6736 if (last && mHwSupportsPause && !mHwPaused && !mStandby) {
6737 doHwPause = true;
6738 mHwPaused = true;
6739 }
Eric Laurent0f7b5f22014-12-19 10:43:21 -08006740 }
Haynes Mathew George5c6daae2017-01-24 20:06:05 -08006741 } else if (last) {
6742 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurent81784c32012-11-19 14:55:58 -08006743 }
6744 }
6745 }
6746 }
6747
Eric Laurentd1f69b02014-12-15 14:33:13 -08006748 // if an active track did not command a flush, check for pending flush on stopped tracks
Phil Burk43b4dcc2015-06-09 16:53:44 -07006749 if (!mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006750 for (size_t i = 0; i < mTracks.size(); i++) {
6751 if (mTracks[i]->isFlushPending()) {
6752 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006753 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006754 }
6755 }
6756 }
6757
6758 // make sure the pause/flush/resume sequence is executed in the right order.
6759 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
6760 // before flush and then resume HW. This can happen in case of pause/flush/resume
6761 // if resume is received before pause is executed.
6762 if (mHwSupportsPause && !mStandby &&
Phil Burk43b4dcc2015-06-09 16:53:44 -07006763 (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006764 status_t result = mOutput->stream->pause();
6765 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Gareth Fenncd1e1622022-10-05 11:45:45 -07006766 doHwResume = !doHwPause; // resume if pause is due to flush.
Eric Laurentd1f69b02014-12-15 14:33:13 -08006767 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07006768 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006769 flushHw_l();
6770 }
6771 if (mHwSupportsPause && !mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006772 status_t result = mOutput->stream->resume();
6773 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08006774 }
Eric Laurent81784c32012-11-19 14:55:58 -08006775 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08006776 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08006777
6778 return mixerStatus;
6779}
6780
Andy Hungee58e4a2023-07-07 13:47:37 -07006781void DirectOutputThread::threadLoop_mix()
Eric Laurent81784c32012-11-19 14:55:58 -08006782{
Eric Laurent81784c32012-11-19 14:55:58 -08006783 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08006784 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08006785 // output audio to hardware
6786 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07006787 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08006788 buffer.frameCount = frameCount;
Phil Burk062e67a2015-02-11 13:40:50 -08006789 status_t status = mActiveTrack->getNextBuffer(&buffer);
6790 if (status != NO_ERROR || buffer.raw == NULL) {
Eric Laurent51716182016-02-29 18:00:56 -08006791 // no need to pad with 0 for compressed audio
6792 if (audio_has_proportional_frames(mFormat)) {
6793 memset(curBuf, 0, frameCount * mFrameSize);
6794 }
Eric Laurent81784c32012-11-19 14:55:58 -08006795 break;
6796 }
6797 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
6798 frameCount -= buffer.frameCount;
6799 curBuf += buffer.frameCount * mFrameSize;
6800 mActiveTrack->releaseBuffer(&buffer);
6801 }
Andy Hung2098f272014-02-27 14:00:06 -08006802 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006803 mSleepTimeUs = 0;
6804 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08006805 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08006806}
6807
Andy Hungee58e4a2023-07-07 13:47:37 -07006808void DirectOutputThread::threadLoop_sleepTime()
Eric Laurent81784c32012-11-19 14:55:58 -08006809{
Eric Laurentd1f69b02014-12-15 14:33:13 -08006810 // do not write to HAL when paused
Eric Laurent0f7b5f22014-12-19 10:43:21 -08006811 if (mHwPaused || (usesHwAvSync() && mStandby)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006812 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006813 return;
6814 }
Andy Hung85ba3332021-04-27 17:40:26 -07006815 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
6816 mSleepTimeUs = mActiveSleepTimeUs;
6817 } else {
6818 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006819 }
Andy Hung85ba3332021-04-27 17:40:26 -07006820 // Note: In S or later, we do not write zeroes for
6821 // linear or proportional PCM direct tracks in underrun.
Eric Laurent81784c32012-11-19 14:55:58 -08006822}
6823
Andy Hungee58e4a2023-07-07 13:47:37 -07006824void DirectOutputThread::threadLoop_exit()
Eric Laurentd1f69b02014-12-15 14:33:13 -08006825{
6826 {
6827 Mutex::Autolock _l(mLock);
Eric Laurentd1f69b02014-12-15 14:33:13 -08006828 for (size_t i = 0; i < mTracks.size(); i++) {
6829 if (mTracks[i]->isFlushPending()) {
6830 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006831 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006832 }
6833 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07006834 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006835 flushHw_l();
6836 }
6837 }
6838 PlaybackThread::threadLoop_exit();
6839}
6840
6841// must be called with thread mutex locked
Andy Hungee58e4a2023-07-07 13:47:37 -07006842bool DirectOutputThread::shouldStandby_l()
Eric Laurentd1f69b02014-12-15 14:33:13 -08006843{
6844 bool trackPaused = false;
Eric Laurentb369caf2015-03-30 20:51:47 -07006845 bool trackStopped = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006846
6847 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
6848 // after a timeout and we will enter standby then.
6849 if (mTracks.size() > 0) {
6850 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
Eric Laurentb369caf2015-03-30 20:51:47 -07006851 trackStopped = mTracks[mTracks.size() - 1]->isStopped() ||
Andy Hung8d31fd22023-06-26 19:20:57 -07006852 mTracks[mTracks.size() - 1]->state() == IAfTrackBase::IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006853 }
6854
Eric Laurent5cff4032015-05-26 13:49:58 -07006855 return !mStandby && !(trackPaused || (mHwPaused && !trackStopped));
Eric Laurentd1f69b02014-12-15 14:33:13 -08006856}
6857
Eric Laurent10351942014-05-08 18:49:52 -07006858// checkForNewParameter_l() must be called with ThreadBase::mLock held
Andy Hungee58e4a2023-07-07 13:47:37 -07006859bool DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
Eric Laurent10351942014-05-08 18:49:52 -07006860 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08006861{
6862 bool reconfig = false;
Eric Laurent10351942014-05-08 18:49:52 -07006863 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006864
Eric Laurent10351942014-05-08 18:49:52 -07006865 AudioParameter param = AudioParameter(keyValuePair);
6866 int value;
6867 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07006868 LOG_FATAL("Should not set routing device in DirectOutputThread");
Eric Laurent81784c32012-11-19 14:55:58 -08006869 }
Eric Laurent10351942014-05-08 18:49:52 -07006870 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6871 // do not accept frame count changes if tracks are open as the track buffer
6872 // size depends on frame count and correct behavior would not be garantied
6873 // if frame count is changed after track creation
6874 if (!mTracks.isEmpty()) {
6875 status = INVALID_OPERATION;
6876 } else {
6877 reconfig = true;
6878 }
6879 }
6880 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006881 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07006882 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08006883 mOutput->standby();
Andy Hungcf10d742020-04-28 15:38:24 -07006884 if (!mStandby) {
6885 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07006886 mThreadSnapshot.onEnd();
Eric Laurent19952e12023-04-20 10:08:29 +02006887 setStandby_l();
Andy Hungcf10d742020-04-28 15:38:24 -07006888 }
Eric Laurent10351942014-05-08 18:49:52 -07006889 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006890 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07006891 }
6892 if (status == NO_ERROR && reconfig) {
6893 readOutputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07006894 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07006895 }
6896 }
6897
Dean Wheatley68918102021-03-19 22:09:19 +11006898 return reconfig;
Eric Laurent81784c32012-11-19 14:55:58 -08006899}
6900
Andy Hungee58e4a2023-07-07 13:47:37 -07006901uint32_t DirectOutputThread::activeSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08006902{
6903 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08006904 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006905 time = PlaybackThread::activeSleepTimeUs();
6906 } else {
Eric Laurent51716182016-02-29 18:00:56 -08006907 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006908 }
6909 return time;
6910}
6911
Andy Hungee58e4a2023-07-07 13:47:37 -07006912uint32_t DirectOutputThread::idleSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08006913{
6914 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08006915 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006916 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
6917 } else {
Eric Laurent51716182016-02-29 18:00:56 -08006918 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006919 }
6920 return time;
6921}
6922
Andy Hungee58e4a2023-07-07 13:47:37 -07006923uint32_t DirectOutputThread::suspendSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08006924{
6925 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08006926 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006927 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
6928 } else {
Eric Laurent51716182016-02-29 18:00:56 -08006929 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006930 }
6931 return time;
6932}
6933
Andy Hungee58e4a2023-07-07 13:47:37 -07006934void DirectOutputThread::cacheParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08006935{
6936 PlaybackThread::cacheParameters_l();
6937
6938 // use shorter standby delay as on normal output to release
6939 // hardware resources as soon as possible
Eric Laurentb369caf2015-03-30 20:51:47 -07006940 // no delay on outputs with HW A/V sync
6941 if (usesHwAvSync()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006942 mStandbyDelayNs = 0;
Phil Burkfdb3c072016-02-09 10:47:02 -08006943 } else if ((mType == OFFLOAD) && !audio_has_proportional_frames(mFormat)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006944 mStandbyDelayNs = kOffloadStandbyDelayNs;
Eric Laurent5cff4032015-05-26 13:49:58 -07006945 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006946 mStandbyDelayNs = microseconds(mActiveSleepTimeUs*2);
Eric Laurent972a1732013-09-04 09:42:59 -07006947 }
Eric Laurent81784c32012-11-19 14:55:58 -08006948}
6949
Andy Hungee58e4a2023-07-07 13:47:37 -07006950void DirectOutputThread::flushHw_l()
Eric Laurente659ef42014-09-29 13:06:46 -07006951{
ziyangch8f194f12021-12-01 13:48:04 -08006952 PlaybackThread::flushHw_l();
Phil Burk062e67a2015-02-11 13:40:50 -08006953 mOutput->flush();
Eric Laurentd1f69b02014-12-15 14:33:13 -08006954 mHwPaused = false;
Phil Burk43b4dcc2015-06-09 16:53:44 -07006955 mFlushPending = false;
Dean Wheatley12473e92021-03-18 23:00:55 +11006956 mTimestampVerifier.discontinuity(discontinuityForStandbyOrFlush());
Sampath Shetty999f0e82020-01-15 10:19:06 +11006957 mTimestamp.clear();
Andy Hung398ffa22022-12-13 19:19:53 -08006958 mMonotonicFrameCounter.onFlush();
Eric Laurente659ef42014-09-29 13:06:46 -07006959}
6960
Andy Hungee58e4a2023-07-07 13:47:37 -07006961int64_t DirectOutputThread::computeWaitTimeNs_l() const {
Andy Hung10cbff12017-02-21 17:30:14 -08006962 // If a VolumeShaper is active, we must wake up periodically to update volume.
6963 const int64_t NS_PER_MS = 1000000;
6964 return mVolumeShaperActive ?
6965 kMinNormalSinkBufferSizeMs * NS_PER_MS : PlaybackThread::computeWaitTimeNs_l();
6966}
6967
Eric Laurent81784c32012-11-19 14:55:58 -08006968// ----------------------------------------------------------------------------
6969
Andy Hungee58e4a2023-07-07 13:47:37 -07006970AsyncCallbackThread::AsyncCallbackThread(
6971 const wp<PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006972 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07006973 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07006974 mWriteAckSequence(0),
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006975 mDrainSequence(0),
6976 mAsyncError(false)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006977{
6978}
6979
Andy Hungee58e4a2023-07-07 13:47:37 -07006980void AsyncCallbackThread::onFirstRef()
Eric Laurentbfb1b832013-01-07 09:53:42 -08006981{
6982 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
6983}
6984
Andy Hungee58e4a2023-07-07 13:47:37 -07006985bool AsyncCallbackThread::threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08006986{
6987 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07006988 uint32_t writeAckSequence;
6989 uint32_t drainSequence;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006990 bool asyncError;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006991
6992 {
6993 Mutex::Autolock _l(mLock);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08006994 while (!((mWriteAckSequence & 1) ||
6995 (mDrainSequence & 1) ||
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006996 mAsyncError ||
Haynes Mathew George24a325d2013-12-03 21:26:02 -08006997 exitPending())) {
6998 mWaitWorkCV.wait(mLock);
6999 }
7000
Eric Laurentbfb1b832013-01-07 09:53:42 -08007001 if (exitPending()) {
7002 break;
7003 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07007004 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
7005 mWriteAckSequence, mDrainSequence);
7006 writeAckSequence = mWriteAckSequence;
7007 mWriteAckSequence &= ~1;
7008 drainSequence = mDrainSequence;
7009 mDrainSequence &= ~1;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007010 asyncError = mAsyncError;
7011 mAsyncError = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007012 }
7013 {
Andy Hungee58e4a2023-07-07 13:47:37 -07007014 const sp<PlaybackThread> playbackThread = mPlaybackThread.promote();
Eric Laurent4de95592013-09-26 15:28:21 -07007015 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07007016 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07007017 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007018 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07007019 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07007020 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007021 }
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007022 if (asyncError) {
7023 playbackThread->onAsyncError();
7024 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007025 }
7026 }
7027 }
7028 return false;
7029}
7030
Andy Hungee58e4a2023-07-07 13:47:37 -07007031void AsyncCallbackThread::exit()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007032{
7033 ALOGV("AsyncCallbackThread::exit");
7034 Mutex::Autolock _l(mLock);
7035 requestExit();
7036 mWaitWorkCV.broadcast();
7037}
7038
Andy Hungee58e4a2023-07-07 13:47:37 -07007039void AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08007040{
7041 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07007042 // bit 0 is cleared
7043 mWriteAckSequence = sequence << 1;
7044}
7045
Andy Hungee58e4a2023-07-07 13:47:37 -07007046void AsyncCallbackThread::resetWriteBlocked()
Eric Laurent3b4529e2013-09-05 18:09:19 -07007047{
7048 Mutex::Autolock _l(mLock);
7049 // ignore unexpected callbacks
7050 if (mWriteAckSequence & 2) {
7051 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007052 mWaitWorkCV.signal();
7053 }
7054}
7055
Andy Hungee58e4a2023-07-07 13:47:37 -07007056void AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08007057{
7058 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07007059 // bit 0 is cleared
7060 mDrainSequence = sequence << 1;
7061}
7062
Andy Hungee58e4a2023-07-07 13:47:37 -07007063void AsyncCallbackThread::resetDraining()
Eric Laurent3b4529e2013-09-05 18:09:19 -07007064{
7065 Mutex::Autolock _l(mLock);
7066 // ignore unexpected callbacks
7067 if (mDrainSequence & 2) {
7068 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007069 mWaitWorkCV.signal();
7070 }
7071}
7072
Andy Hungee58e4a2023-07-07 13:47:37 -07007073void AsyncCallbackThread::setAsyncError()
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007074{
7075 Mutex::Autolock _l(mLock);
7076 mAsyncError = true;
7077 mWaitWorkCV.signal();
7078}
7079
Eric Laurentbfb1b832013-01-07 09:53:42 -08007080
7081// ----------------------------------------------------------------------------
Andy Hungee58e4a2023-07-07 13:47:37 -07007082
7083/* static */
7084sp<IAfPlaybackThread> IAfPlaybackThread::createOffloadThread(
Andy Hung583043b2023-07-17 17:05:00 -07007085 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hungee58e4a2023-07-07 13:47:37 -07007086 AudioStreamOut* output, audio_io_handle_t id, bool systemReady,
7087 const audio_offload_info_t& offloadInfo) {
Andy Hung583043b2023-07-17 17:05:00 -07007088 return sp<OffloadThread>::make(afThreadCallback, output, id, systemReady, offloadInfo);
Andy Hungee58e4a2023-07-07 13:47:37 -07007089}
7090
Andy Hung583043b2023-07-17 17:05:00 -07007091OffloadThread::OffloadThread(const sp<IAfThreadCallback>& afThreadCallback,
Gareth Fennb18c1a32022-10-05 13:42:36 -07007092 AudioStreamOut* output, audio_io_handle_t id, bool systemReady,
7093 const audio_offload_info_t& offloadInfo)
Andy Hung583043b2023-07-17 17:05:00 -07007094 : DirectOutputThread(afThreadCallback, output, id, OFFLOAD, systemReady, offloadInfo),
ziyangch8f194f12021-12-01 13:48:04 -08007095 mPausedWriteLength(0), mPausedBytesRemaining(0), mKeepWakeLock(true)
Eric Laurentbfb1b832013-01-07 09:53:42 -08007096{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07007097 //FIXME: mStandby should be set to true by ThreadBase constructo
Eric Laurentfd477972013-10-25 18:10:40 -07007098 mStandby = true;
Eric Laurent64667972016-03-30 18:19:46 -07007099 mKeepWakeLock = property_get_bool("ro.audio.offload_wakelock", true /* default_value */);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007100}
7101
Andy Hungee58e4a2023-07-07 13:47:37 -07007102void OffloadThread::threadLoop_exit()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007103{
7104 if (mFlushPending || mHwPaused) {
7105 // If a flush is pending or track was paused, just discard buffered data
7106 flushHw_l();
7107 } else {
7108 mMixerStatus = MIXER_DRAIN_ALL;
7109 threadLoop_drain();
7110 }
Uday Gupta56604aa2014-05-13 11:19:17 -07007111 if (mUseAsyncWrite) {
7112 ALOG_ASSERT(mCallbackThread != 0);
7113 mCallbackThread->exit();
7114 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007115 PlaybackThread::threadLoop_exit();
7116}
7117
Andy Hungee58e4a2023-07-07 13:47:37 -07007118PlaybackThread::mixer_state OffloadThread::prepareTracks_l(
Andy Hung8d31fd22023-06-26 19:20:57 -07007119 Vector<sp<IAfTrack>>* tracksToRemove
Eric Laurentbfb1b832013-01-07 09:53:42 -08007120)
7121{
Eric Laurentbfb1b832013-01-07 09:53:42 -08007122 size_t count = mActiveTracks.size();
7123
7124 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07007125 bool doHwPause = false;
7126 bool doHwResume = false;
7127
Glenn Kastenc42e9b42016-03-21 11:35:03 -07007128 ALOGV("OffloadThread::prepareTracks_l active tracks %zu", count);
Eric Laurentede6c3b2013-09-19 14:37:46 -07007129
Eric Laurentbfb1b832013-01-07 09:53:42 -08007130 // find out which tracks need to be processed
Andy Hung8d31fd22023-06-26 19:20:57 -07007131 for (const sp<IAfTrack>& t : mActiveTracks) {
7132 IAfTrack* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07007133#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurentbfb1b832013-01-07 09:53:42 -08007134 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07007135#endif
Eric Laurentfd477972013-10-25 18:10:40 -07007136 // Only consider last track started for volume and mixer state control.
7137 // In theory an older track could underrun and restart after the new one starts
7138 // but as we only care about the transition phase between two tracks on a
7139 // direct output, it is not a problem to ignore the underrun case.
Andy Hung8d31fd22023-06-26 19:20:57 -07007140 sp<IAfTrack> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08007141 bool last = l.get() == track;
Eric Laurentfd477972013-10-25 18:10:40 -07007142
Haynes Mathew George7844f672014-01-15 12:32:55 -08007143 if (track->isInvalid()) {
7144 ALOGW("An invalidated track shouldn't be in active list");
7145 tracksToRemove->add(track);
7146 continue;
7147 }
7148
Andy Hung8d31fd22023-06-26 19:20:57 -07007149 if (track->state() == IAfTrackBase::IDLE) {
Haynes Mathew George7844f672014-01-15 12:32:55 -08007150 ALOGW("An idle track shouldn't be in active list");
7151 continue;
7152 }
7153
Kuowei Li23666472021-01-20 10:23:25 +08007154 if (track->isPausePending()) {
7155 track->pauseAck();
7156 // It is possible a track might have been flushed or stopped.
7157 // Other operations such as flush pending might occur on the next prepare.
7158 if (track->isPausing()) {
7159 track->setPaused();
7160 }
7161 // Always perform pause if last, as an immediate flush will change
7162 // the pause state to be no longer isPausing().
Eric Laurentbfb1b832013-01-07 09:53:42 -08007163 if (last) {
Eric Laurent5cff4032015-05-26 13:49:58 -07007164 if (mHwSupportsPause && !mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07007165 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007166 mHwPaused = true;
7167 }
7168 // If we were part way through writing the mixbuffer to
7169 // the HAL we must save this until we resume
7170 // BUG - this will be wrong if a different track is made active,
7171 // in that case we want to discard the pending data in the
7172 // mixbuffer and tell the client to present it again when the
7173 // track is resumed
7174 mPausedWriteLength = mCurrentWriteLength;
7175 mPausedBytesRemaining = mBytesRemaining;
7176 mBytesRemaining = 0; // stop writing
7177 }
7178 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08007179 } else if (track->isFlushPending()) {
Eric Laurente93cc032016-05-05 10:15:10 -07007180 if (track->isStopping_1()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07007181 track->retryCount() = kMaxTrackStopRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07007182 } else {
Andy Hung8d31fd22023-06-26 19:20:57 -07007183 track->retryCount() = kMaxTrackRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07007184 }
Haynes Mathew George7844f672014-01-15 12:32:55 -08007185 track->flushAck();
7186 if (last) {
7187 mFlushPending = true;
7188 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08007189 } else if (track->isResumePending()){
7190 track->resumeAck();
7191 if (last) {
7192 if (mPausedBytesRemaining) {
7193 // Need to continue write that was interrupted
7194 mCurrentWriteLength = mPausedWriteLength;
7195 mBytesRemaining = mPausedBytesRemaining;
7196 mPausedBytesRemaining = 0;
7197 }
7198 if (mHwPaused) {
7199 doHwResume = true;
7200 mHwPaused = false;
7201 // threadLoop_mix() will handle the case that we need to
7202 // resume an interrupted write
7203 }
7204 // enable write to audio HAL
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007205 mSleepTimeUs = 0;
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08007206
Eric Laurent3df841a2016-07-15 15:15:40 -07007207 mLeftVolFloat = mRightVolFloat = -1.0;
7208
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08007209 // Do not handle new data in this iteration even if track->framesReady()
7210 mixerStatus = MIXER_TRACKS_ENABLED;
7211 }
7212 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07007213 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Andy Hungc0691382018-09-12 18:01:57 -07007214 ALOGVV("OffloadThread: track(%d) s=%08x [OK]", track->id(), cblk->mServer);
Andy Hung8d31fd22023-06-26 19:20:57 -07007215 if (track->fillingStatus() == IAfTrack::FS_FILLED) {
7216 track->fillingStatus() = IAfTrack::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07007217 if (last) {
7218 // make sure processVolume_l() will apply new volume even if 0
7219 mLeftVolFloat = mRightVolFloat = -1.0;
7220 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007221 }
7222
7223 if (last) {
Andy Hung8d31fd22023-06-26 19:20:57 -07007224 sp<IAfTrack> previousTrack = mPreviousTrack.promote();
Eric Laurentd7e59222013-11-15 12:02:28 -08007225 if (previousTrack != 0) {
7226 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08007227 // Flush any data still being written from last track
7228 mBytesRemaining = 0;
7229 if (mPausedBytesRemaining) {
7230 // Last track was paused so we also need to flush saved
7231 // mixbuffer state and invalidate track so that it will
7232 // re-submit that unwritten data when it is next resumed
7233 mPausedBytesRemaining = 0;
7234 // Invalidate is a bit drastic - would be more efficient
7235 // to have a flag to tell client that some of the
7236 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08007237 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08007238 }
7239 // flush data already sent to the DSP if changing audio session as audio
7240 // comes from a different source. Also invalidate previous track to force a
7241 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08007242 if (previousTrack->sessionId() != track->sessionId()) {
7243 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08007244 }
7245 }
7246 }
7247 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007248 // reset retry count
Eric Laurente93cc032016-05-05 10:15:10 -07007249 if (track->isStopping_1()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07007250 track->retryCount() = kMaxTrackStopRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07007251 } else {
Andy Hung8d31fd22023-06-26 19:20:57 -07007252 track->retryCount() = kMaxTrackRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07007253 }
Eric Laurent5850c4c2016-11-10 13:04:31 -08007254 mActiveTrack = t;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007255 mixerStatus = MIXER_TRACKS_READY;
7256 }
7257 } else {
Andy Hungc0691382018-09-12 18:01:57 -07007258 ALOGVV("OffloadThread: track(%d) s=%08x [NOT READY]", track->id(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007259 if (track->isStopping_1()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07007260 if (--(track->retryCount()) <= 0) {
Eric Laurente93cc032016-05-05 10:15:10 -07007261 // Hardware buffer can hold a large amount of audio so we must
7262 // wait for all current track's data to drain before we say
7263 // that the track is stopped.
7264 if (mBytesRemaining == 0) {
7265 // Only start draining when all data in mixbuffer
7266 // has been written
7267 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
Andy Hung8d31fd22023-06-26 19:20:57 -07007268 track->setState(IAfTrackBase::STOPPING_2);
7269 // so presentation completes after
Eric Laurente93cc032016-05-05 10:15:10 -07007270 // drain do not drain if no data was ever sent to HAL (mStandby == true)
7271 if (last && !mStandby) {
7272 // do not modify drain sequence if we are already draining. This happens
7273 // when resuming from pause after drain.
7274 if ((mDrainSequence & 1) == 0) {
7275 mSleepTimeUs = 0;
7276 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
7277 mixerStatus = MIXER_DRAIN_TRACK;
7278 mDrainSequence += 2;
7279 }
7280 if (mHwPaused) {
7281 // It is possible to move from PAUSED to STOPPING_1 without
7282 // a resume so we must ensure hardware is running
7283 doHwResume = true;
7284 mHwPaused = false;
7285 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007286 }
7287 }
Eric Laurente93cc032016-05-05 10:15:10 -07007288 } else if (last) {
Andy Hung8d31fd22023-06-26 19:20:57 -07007289 ALOGV("stopping1 underrun retries left %d", track->retryCount());
Eric Laurente93cc032016-05-05 10:15:10 -07007290 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007291 }
7292 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07007293 // Drain has completed or we are in standby, signal presentation complete
7294 if (!(mDrainSequence & 1) || !last || mStandby) {
Andy Hung8d31fd22023-06-26 19:20:57 -07007295 track->setState(IAfTrackBase::STOPPED);
Atneya Nair0cae0432022-05-10 18:12:12 -04007296 mOutput->presentationComplete();
7297 track->presentationComplete(latency_l()); // always returns true
Eric Laurentbfb1b832013-01-07 09:53:42 -08007298 track->reset();
7299 tracksToRemove->add(track);
Dean Wheatley12473e92021-03-18 23:00:55 +11007300 // OFFLOADED stop resets frame counts.
Andy Hungf3234512018-07-03 14:51:47 -07007301 if (!mUseAsyncWrite) {
7302 // If we don't get explicit drain notification we must
7303 // register discontinuity regardless of whether this is
7304 // the previous (!last) or the upcoming (last) track
7305 // to avoid skipping the discontinuity.
Dean Wheatley12473e92021-03-18 23:00:55 +11007306 mTimestampVerifier.discontinuity(
7307 mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Andy Hungf3234512018-07-03 14:51:47 -07007308 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007309 }
7310 } else {
7311 // No buffers for this track. Give it a few chances to
7312 // fill a buffer, then remove it from active list.
Brian Lindahl65e90012022-07-27 18:01:07 +02007313 bool isTimestampAdvancing = mIsTimestampAdvancing.check(mOutput);
Gareth Fennb18c1a32022-10-05 13:42:36 -07007314 if (!isTunerStream() // tuner streams remain active in underrun
Andy Hung8d31fd22023-06-26 19:20:57 -07007315 && --(track->retryCount()) <= 0) {
Brian Lindahl65e90012022-07-27 18:01:07 +02007316 if (isTimestampAdvancing) { // HAL is still playing audio, give us more time.
Andy Hung8d31fd22023-06-26 19:20:57 -07007317 track->retryCount() = kMaxTrackRetriesOffload;
Andy Hungf8044752016-07-27 14:58:11 -07007318 } else {
Andy Hungc0691382018-09-12 18:01:57 -07007319 ALOGV("OffloadThread: BUFFER TIMEOUT: remove track(%d) from active list",
7320 track->id());
Andy Hungf8044752016-07-27 14:58:11 -07007321 tracksToRemove->add(track);
Glenn Kastend3bb6452016-12-05 18:14:37 -08007322 // tell client process that the track was disabled because of underrun;
Andy Hungf8044752016-07-27 14:58:11 -07007323 // it will then automatically call start() when data is available
7324 track->disable();
7325 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007326 } else if (last){
7327 mixerStatus = MIXER_TRACKS_ENABLED;
7328 }
7329 }
7330 }
7331 // compute volume for this track
Wenfeng Sun79458332019-05-29 20:12:43 +08007332 if (track->isReady()) { // check ready to prevent premature start.
7333 processVolume_l(track, last);
7334 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007335 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007336
Eric Laurentea0fade2013-10-04 16:23:48 -07007337 // make sure the pause/flush/resume sequence is executed in the right order.
7338 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
7339 // before flush and then resume HW. This can happen in case of pause/flush/resume
7340 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07007341 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007342 status_t result = mOutput->stream->pause();
7343 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Gareth Fenncd1e1622022-10-05 11:45:45 -07007344 doHwResume = !doHwPause; // resume if pause is due to flush.
Eric Laurent972a1732013-09-04 09:42:59 -07007345 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007346 if (mFlushPending) {
7347 flushHw_l();
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007348 }
Eric Laurentfd477972013-10-25 18:10:40 -07007349 if (!mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007350 status_t result = mOutput->stream->resume();
7351 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07007352 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007353
Eric Laurentbfb1b832013-01-07 09:53:42 -08007354 // remove all the tracks that need to be...
7355 removeTracks_l(*tracksToRemove);
7356
7357 return mixerStatus;
7358}
7359
Eric Laurentbfb1b832013-01-07 09:53:42 -08007360// must be called with thread mutex locked
Andy Hungee58e4a2023-07-07 13:47:37 -07007361bool OffloadThread::waitingAsyncCallback_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007362{
Eric Laurent3b4529e2013-09-05 18:09:19 -07007363 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
7364 mWriteAckSequence, mDrainSequence);
7365 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08007366 return true;
7367 }
7368 return false;
7369}
7370
Andy Hungee58e4a2023-07-07 13:47:37 -07007371bool OffloadThread::waitingAsyncCallback()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007372{
7373 Mutex::Autolock _l(mLock);
7374 return waitingAsyncCallback_l();
7375}
7376
Andy Hungee58e4a2023-07-07 13:47:37 -07007377void OffloadThread::flushHw_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007378{
Eric Laurente659ef42014-09-29 13:06:46 -07007379 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08007380 // Flush anything still waiting in the mixbuffer
7381 mCurrentWriteLength = 0;
7382 mBytesRemaining = 0;
7383 mPausedWriteLength = 0;
7384 mPausedBytesRemaining = 0;
Eric Laurent3eaf66b2016-04-01 14:44:17 -07007385 // reset bytes written count to reflect that DSP buffers are empty after flush.
7386 mBytesWritten = 0;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08007387
Eric Laurentbfb1b832013-01-07 09:53:42 -08007388 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07007389 // discard any pending drain or write ack by incrementing sequence
7390 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
7391 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007392 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07007393 mCallbackThread->setWriteBlocked(mWriteAckSequence);
7394 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007395 }
7396}
7397
Andy Hungee58e4a2023-07-07 13:47:37 -07007398void OffloadThread::invalidateTracks(audio_stream_type_t streamType)
Haynes Mathew George05317d22016-05-03 16:34:26 -07007399{
7400 Mutex::Autolock _l(mLock);
Eric Laurent13084622016-05-17 10:51:49 -07007401 if (PlaybackThread::invalidateTracks_l(streamType)) {
7402 mFlushPending = true;
7403 }
Haynes Mathew George05317d22016-05-03 16:34:26 -07007404}
7405
Andy Hungee58e4a2023-07-07 13:47:37 -07007406void OffloadThread::invalidateTracks(std::set<audio_port_handle_t>& portIds) {
jiabinc44b3462022-12-08 12:52:31 -08007407 Mutex::Autolock _l(mLock);
7408 if (PlaybackThread::invalidateTracks_l(portIds)) {
7409 mFlushPending = true;
7410 }
7411}
7412
Eric Laurentbfb1b832013-01-07 09:53:42 -08007413// ----------------------------------------------------------------------------
7414
Andy Hungee58e4a2023-07-07 13:47:37 -07007415/* static */
7416sp<IAfDuplicatingThread> IAfDuplicatingThread::create(
Andy Hung583043b2023-07-17 17:05:00 -07007417 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hungee58e4a2023-07-07 13:47:37 -07007418 IAfPlaybackThread* mainThread, audio_io_handle_t id, bool systemReady) {
Andy Hung583043b2023-07-17 17:05:00 -07007419 return sp<DuplicatingThread>::make(afThreadCallback, mainThread, id, systemReady);
Andy Hungee58e4a2023-07-07 13:47:37 -07007420}
7421
Andy Hung583043b2023-07-17 17:05:00 -07007422DuplicatingThread::DuplicatingThread(const sp<IAfThreadCallback>& afThreadCallback,
Andy Hung87c693c2023-07-06 20:56:16 -07007423 IAfPlaybackThread* mainThread, audio_io_handle_t id, bool systemReady)
Andy Hung583043b2023-07-17 17:05:00 -07007424 : MixerThread(afThreadCallback, mainThread->getOutput(), id,
Eric Laurent72e3f392015-05-20 14:43:50 -07007425 systemReady, DUPLICATING),
Eric Laurent81784c32012-11-19 14:55:58 -08007426 mWaitTimeMs(UINT_MAX)
7427{
7428 addOutputTrack(mainThread);
7429}
7430
Andy Hungee58e4a2023-07-07 13:47:37 -07007431DuplicatingThread::~DuplicatingThread()
Eric Laurent81784c32012-11-19 14:55:58 -08007432{
7433 for (size_t i = 0; i < mOutputTracks.size(); i++) {
7434 mOutputTracks[i]->destroy();
7435 }
7436}
7437
Andy Hungee58e4a2023-07-07 13:47:37 -07007438void DuplicatingThread::threadLoop_mix()
Eric Laurent81784c32012-11-19 14:55:58 -08007439{
7440 // mix buffers...
Andy Hung920f6572022-10-06 12:09:49 -07007441 if (outputsReady()) {
Glenn Kastend79072e2016-01-06 08:41:20 -08007442 mAudioMixer->process();
Eric Laurent81784c32012-11-19 14:55:58 -08007443 } else {
Eric Laurent02b57082014-11-07 17:28:28 -08007444 if (mMixerBufferValid) {
7445 memset(mMixerBuffer, 0, mMixerBufferSize);
7446 } else {
7447 memset(mSinkBuffer, 0, mSinkBufferSize);
7448 }
Eric Laurent81784c32012-11-19 14:55:58 -08007449 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007450 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007451 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08007452 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007453 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08007454}
7455
Andy Hungee58e4a2023-07-07 13:47:37 -07007456void DuplicatingThread::threadLoop_sleepTime()
Eric Laurent81784c32012-11-19 14:55:58 -08007457{
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007458 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08007459 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007460 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007461 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007462 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007463 }
7464 } else if (mBytesWritten != 0) {
7465 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
7466 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08007467 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08007468 } else {
7469 // flush remaining overflow buffers in output tracks
7470 writeFrames = 0;
7471 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007472 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007473 }
7474}
7475
Andy Hungee58e4a2023-07-07 13:47:37 -07007476ssize_t DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08007477{
7478 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hung1c86ebe2018-05-29 20:29:08 -07007479 const ssize_t actualWritten = outputTracks[i]->write(mSinkBuffer, writeFrames);
7480
7481 // Consider the first OutputTrack for timestamp and frame counting.
7482
7483 // The threadLoop() generally assumes writing a full sink buffer size at a time.
7484 // Here, we correct for writeFrames of 0 (a stop) or underruns because
7485 // we always claim success.
7486 if (i == 0) {
7487 const ssize_t correction = mSinkBufferSize / mFrameSize - actualWritten;
7488 ALOGD_IF(correction != 0 && writeFrames != 0,
7489 "%s: writeFrames:%u actualWritten:%zd correction:%zd mFramesWritten:%lld",
7490 __func__, writeFrames, actualWritten, correction, (long long)mFramesWritten);
7491 mFramesWritten -= correction;
7492 }
7493
7494 // TODO: Report correction for the other output tracks and show in the dump.
Eric Laurent81784c32012-11-19 14:55:58 -08007495 }
Andy Hungcf10d742020-04-28 15:38:24 -07007496 if (mStandby) {
7497 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07007498 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -07007499 mStandby = false;
7500 }
Andy Hung25c2dac2014-02-27 14:56:00 -08007501 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08007502}
7503
Andy Hungee58e4a2023-07-07 13:47:37 -07007504void DuplicatingThread::threadLoop_standby()
Eric Laurent81784c32012-11-19 14:55:58 -08007505{
7506 // DuplicatingThread implements standby by stopping all tracks
7507 for (size_t i = 0; i < outputTracks.size(); i++) {
7508 outputTracks[i]->stop();
7509 }
7510}
7511
Andy Hungee58e4a2023-07-07 13:47:37 -07007512void DuplicatingThread::dumpInternals_l(int fd, const Vector<String16>& args)
Andy Hung1bc088a2018-02-09 15:57:31 -08007513{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07007514 MixerThread::dumpInternals_l(fd, args);
Andy Hung1bc088a2018-02-09 15:57:31 -08007515
7516 std::stringstream ss;
7517 const size_t numTracks = mOutputTracks.size();
7518 ss << " " << numTracks << " OutputTracks";
7519 if (numTracks > 0) {
7520 ss << ":";
7521 for (const auto &track : mOutputTracks) {
Andy Hung87c693c2023-07-06 20:56:16 -07007522 const auto thread = track->thread().promote();
Andy Hungc0691382018-09-12 18:01:57 -07007523 ss << " (" << track->id() << " : ";
Andy Hung1bc088a2018-02-09 15:57:31 -08007524 if (thread.get() != nullptr) {
7525 ss << thread.get() << ", " << thread->id();
7526 } else {
7527 ss << "null";
7528 }
7529 ss << ")";
7530 }
7531 }
7532 ss << "\n";
7533 std::string result = ss.str();
7534 write(fd, result.c_str(), result.size());
7535}
7536
Andy Hungee58e4a2023-07-07 13:47:37 -07007537void DuplicatingThread::saveOutputTracks()
Eric Laurent81784c32012-11-19 14:55:58 -08007538{
7539 outputTracks = mOutputTracks;
7540}
7541
Andy Hungee58e4a2023-07-07 13:47:37 -07007542void DuplicatingThread::clearOutputTracks()
Eric Laurent81784c32012-11-19 14:55:58 -08007543{
7544 outputTracks.clear();
7545}
7546
Andy Hungee58e4a2023-07-07 13:47:37 -07007547void DuplicatingThread::addOutputTrack(IAfPlaybackThread* thread)
Eric Laurent81784c32012-11-19 14:55:58 -08007548{
7549 Mutex::Autolock _l(mLock);
Andy Hungc25b84a2015-01-14 19:04:10 -08007550 // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
7551 // Adjust for thread->sampleRate() to determine minimum buffer frame count.
7552 // Then triple buffer because Threads do not run synchronously and may not be clock locked.
7553 const size_t frameCount =
7554 3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
7555 // TODO: Consider asynchronous sample rate conversion to handle clock disparity
7556 // from different OutputTracks and their associated MixerThreads (e.g. one may
7557 // nearly empty and the other may be dropping data).
7558
Svet Ganov33761132021-05-13 22:51:08 +00007559 // TODO b/182392769: use attribution source util, move to server edge
7560 AttributionSourceState attributionSource = AttributionSourceState();
7561 attributionSource.uid = VALUE_OR_FATAL(legacy2aidl_uid_t_int32_t(
Philip P. Moltmannbda45752020-07-17 16:41:18 -07007562 IPCThreadState::self()->getCallingUid()));
Svet Ganov33761132021-05-13 22:51:08 +00007563 attributionSource.pid = VALUE_OR_FATAL(legacy2aidl_pid_t_int32_t(
Philip P. Moltmannbda45752020-07-17 16:41:18 -07007564 IPCThreadState::self()->getCallingPid()));
Svet Ganov33761132021-05-13 22:51:08 +00007565 attributionSource.token = sp<BBinder>::make();
Andy Hung8d31fd22023-06-26 19:20:57 -07007566 sp<IAfOutputTrack> outputTrack = IAfOutputTrack::create(thread,
Eric Laurent81784c32012-11-19 14:55:58 -08007567 this,
7568 mSampleRate,
Andy Hungc25b84a2015-01-14 19:04:10 -08007569 mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08007570 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08007571 frameCount,
Svet Ganov33761132021-05-13 22:51:08 +00007572 attributionSource);
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07007573 status_t status = outputTrack != 0 ? outputTrack->initCheck() : (status_t) NO_MEMORY;
7574 if (status != NO_ERROR) {
7575 ALOGE("addOutputTrack() initCheck failed %d", status);
7576 return;
Eric Laurent81784c32012-11-19 14:55:58 -08007577 }
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07007578 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
7579 mOutputTracks.add(outputTrack);
7580 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
7581 updateWaitTime_l();
Eric Laurent81784c32012-11-19 14:55:58 -08007582}
7583
Andy Hungee58e4a2023-07-07 13:47:37 -07007584void DuplicatingThread::removeOutputTrack(IAfPlaybackThread* thread)
Eric Laurent81784c32012-11-19 14:55:58 -08007585{
7586 Mutex::Autolock _l(mLock);
7587 for (size_t i = 0; i < mOutputTracks.size(); i++) {
7588 if (mOutputTracks[i]->thread() == thread) {
7589 mOutputTracks[i]->destroy();
7590 mOutputTracks.removeAt(i);
7591 updateWaitTime_l();
Eric Laurentf6870ae2015-05-08 10:50:03 -07007592 if (thread->getOutput() == mOutput) {
7593 mOutput = NULL;
7594 }
Eric Laurent81784c32012-11-19 14:55:58 -08007595 return;
7596 }
7597 }
Eric Laurentf6870ae2015-05-08 10:50:03 -07007598 ALOGV("removeOutputTrack(): unknown thread: %p", thread);
Eric Laurent81784c32012-11-19 14:55:58 -08007599}
7600
7601// caller must hold mLock
Andy Hungee58e4a2023-07-07 13:47:37 -07007602void DuplicatingThread::updateWaitTime_l()
Eric Laurent81784c32012-11-19 14:55:58 -08007603{
7604 mWaitTimeMs = UINT_MAX;
7605 for (size_t i = 0; i < mOutputTracks.size(); i++) {
Andy Hung87c693c2023-07-06 20:56:16 -07007606 const auto strong = mOutputTracks[i]->thread().promote();
Eric Laurent81784c32012-11-19 14:55:58 -08007607 if (strong != 0) {
7608 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
7609 if (waitTimeMs < mWaitTimeMs) {
7610 mWaitTimeMs = waitTimeMs;
7611 }
7612 }
7613 }
7614}
7615
Andy Hungee58e4a2023-07-07 13:47:37 -07007616bool DuplicatingThread::outputsReady()
Eric Laurent81784c32012-11-19 14:55:58 -08007617{
7618 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hung87c693c2023-07-06 20:56:16 -07007619 const auto thread = outputTracks[i]->thread().promote();
Eric Laurent81784c32012-11-19 14:55:58 -08007620 if (thread == 0) {
7621 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
7622 outputTracks[i].get());
7623 return false;
7624 }
Andy Hung87c693c2023-07-06 20:56:16 -07007625 IAfPlaybackThread* const playbackThread = thread->asIAfPlaybackThread().get();
Eric Laurent81784c32012-11-19 14:55:58 -08007626 // see note at standby() declaration
Andy Hung440901d2023-06-29 21:19:25 -07007627 if (playbackThread->inStandby() && !playbackThread->isSuspended()) {
Eric Laurent81784c32012-11-19 14:55:58 -08007628 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
7629 thread.get());
7630 return false;
7631 }
7632 }
7633 return true;
7634}
7635
Andy Hungee58e4a2023-07-07 13:47:37 -07007636void DuplicatingThread::sendMetadataToBackend_l(
Kevin Rocard12381092018-04-11 09:19:59 -07007637 const StreamOutHalInterface::SourceMetadata& metadata)
Kevin Rocard069c2712018-03-29 19:09:14 -07007638{
Kevin Rocard12381092018-04-11 09:19:59 -07007639 for (auto& outputTrack : outputTracks) { // not mOutputTracks
7640 outputTrack->setMetadatas(metadata.tracks);
7641 }
Kevin Rocard069c2712018-03-29 19:09:14 -07007642}
7643
Andy Hungee58e4a2023-07-07 13:47:37 -07007644uint32_t DuplicatingThread::activeSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08007645{
7646 return (mWaitTimeMs * 1000) / 2;
7647}
7648
Andy Hungee58e4a2023-07-07 13:47:37 -07007649void DuplicatingThread::cacheParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08007650{
7651 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
7652 updateWaitTime_l();
7653
7654 MixerThread::cacheParameters_l();
7655}
7656
Eric Laurentb3f315a2021-07-13 15:09:05 +02007657// ----------------------------------------------------------------------------
7658
Andy Hungee58e4a2023-07-07 13:47:37 -07007659/* static */
7660sp<IAfPlaybackThread> IAfPlaybackThread::createSpatializerThread(
Andy Hung583043b2023-07-17 17:05:00 -07007661 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hungee58e4a2023-07-07 13:47:37 -07007662 AudioStreamOut* output,
7663 audio_io_handle_t id,
7664 bool systemReady,
7665 audio_config_base_t* mixerConfig) {
Andy Hung583043b2023-07-17 17:05:00 -07007666 return sp<SpatializerThread>::make(afThreadCallback, output, id, systemReady, mixerConfig);
Andy Hungee58e4a2023-07-07 13:47:37 -07007667}
7668
Andy Hung583043b2023-07-17 17:05:00 -07007669SpatializerThread::SpatializerThread(const sp<IAfThreadCallback>& afThreadCallback,
Eric Laurentb3f315a2021-07-13 15:09:05 +02007670 AudioStreamOut* output,
7671 audio_io_handle_t id,
7672 bool systemReady,
7673 audio_config_base_t *mixerConfig)
Andy Hung583043b2023-07-17 17:05:00 -07007674 : MixerThread(afThreadCallback, output, id, systemReady, SPATIALIZER, mixerConfig)
Eric Laurentb3f315a2021-07-13 15:09:05 +02007675{
7676}
7677
Andy Hungee58e4a2023-07-07 13:47:37 -07007678void SpatializerThread::onFirstRef() {
Eric Laurentb0463942022-12-20 16:31:10 +01007679 MixerThread::onFirstRef();
Andy Hungfeb4e5c2022-10-17 19:10:02 -07007680
Andy Hung41ccf7f2022-12-14 14:25:49 -08007681 const pid_t tid = getTid();
7682 if (tid == -1) {
7683 // Unusual: PlaybackThread::onFirstRef() should set the threadLoop running.
7684 ALOGW("%s: Cannot update Spatializer mixer thread priority, not running", __func__);
7685 } else {
7686 const int priorityBoost = requestSpatializerPriority(getpid(), tid);
7687 if (priorityBoost > 0) {
Andy Hungfeb4e5c2022-10-17 19:10:02 -07007688 stream()->setHalThreadPriority(priorityBoost);
7689 }
7690 }
Eric Laurent68a40a82022-05-03 18:15:04 +02007691}
7692
Andy Hungee58e4a2023-07-07 13:47:37 -07007693void SpatializerThread::setHalLatencyMode_l() {
Eric Laurent68a40a82022-05-03 18:15:04 +02007694 // if mSupportedLatencyModes is empty, the HAL stream does not support
7695 // latency mode control and we can exit.
7696 if (mSupportedLatencyModes.empty()) {
7697 return;
7698 }
7699 audio_latency_mode_t latencyMode = AUDIO_LATENCY_MODE_FREE;
7700 if (mSupportedLatencyModes.size() == 1) {
7701 // If the HAL only support one latency mode currently, confirm the choice
7702 latencyMode = mSupportedLatencyModes[0];
7703 } else if (mSupportedLatencyModes.size() > 1) {
7704 // Request low latency if:
7705 // - The low latency mode is requested by the spatializer controller
7706 // (mRequestedLatencyMode = AUDIO_LATENCY_MODE_LOW)
7707 // AND
7708 // - At least one active track is spatialized
7709 bool hasSpatializedActiveTrack = false;
7710 for (const auto& track : mActiveTracks) {
7711 if (track->isSpatialized()) {
7712 hasSpatializedActiveTrack = true;
7713 break;
7714 }
7715 }
7716 if (hasSpatializedActiveTrack && mRequestedLatencyMode == AUDIO_LATENCY_MODE_LOW) {
7717 latencyMode = AUDIO_LATENCY_MODE_LOW;
7718 }
7719 }
7720
7721 if (latencyMode != mSetLatencyMode) {
7722 status_t status = mOutput->stream->setLatencyMode(latencyMode);
Andy Hung4bd53e72022-11-17 17:21:45 -08007723 ALOGD("%s: thread(%d) setLatencyMode(%s) returned %d",
7724 __func__, mId, toString(latencyMode).c_str(), status);
Eric Laurent68a40a82022-05-03 18:15:04 +02007725 if (status == NO_ERROR) {
7726 mSetLatencyMode = latencyMode;
7727 }
7728 }
7729}
7730
Andy Hungee58e4a2023-07-07 13:47:37 -07007731status_t SpatializerThread::setRequestedLatencyMode(audio_latency_mode_t mode) {
Eric Laurent68a40a82022-05-03 18:15:04 +02007732 if (mode != AUDIO_LATENCY_MODE_LOW && mode != AUDIO_LATENCY_MODE_FREE) {
7733 return BAD_VALUE;
7734 }
7735 Mutex::Autolock _l(mLock);
7736 mRequestedLatencyMode = mode;
7737 return NO_ERROR;
7738}
7739
Andy Hungee58e4a2023-07-07 13:47:37 -07007740void SpatializerThread::checkOutputStageEffects()
Eric Laurentb3f315a2021-07-13 15:09:05 +02007741{
7742 bool hasVirtualizer = false;
7743 bool hasDownMixer = false;
Andy Hung116bc262023-06-20 18:56:17 -07007744 sp<IAfEffectHandle> finalDownMixer;
Eric Laurentb3f315a2021-07-13 15:09:05 +02007745 {
7746 Mutex::Autolock _l(mLock);
Andy Hung116bc262023-06-20 18:56:17 -07007747 sp<IAfEffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_STAGE);
Eric Laurentb3f315a2021-07-13 15:09:05 +02007748 if (chain != 0) {
Eric Laurent1c5e2e32021-08-18 18:50:28 +02007749 hasVirtualizer = chain->getEffectFromType_l(FX_IID_SPATIALIZER) != nullptr;
Eric Laurentb3f315a2021-07-13 15:09:05 +02007750 hasDownMixer = chain->getEffectFromType_l(EFFECT_UIID_DOWNMIX) != nullptr;
7751 }
7752
7753 finalDownMixer = mFinalDownMixer;
7754 mFinalDownMixer.clear();
7755 }
7756
7757 if (hasVirtualizer) {
7758 if (finalDownMixer != nullptr) {
7759 int32_t ret;
Andy Hung116bc262023-06-20 18:56:17 -07007760 finalDownMixer->asIEffect()->disable(&ret);
Eric Laurentb3f315a2021-07-13 15:09:05 +02007761 }
7762 finalDownMixer.clear();
7763 } else if (!hasDownMixer) {
7764 std::vector<effect_descriptor_t> descriptors;
Andy Hung583043b2023-07-17 17:05:00 -07007765 status_t status = mAfThreadCallback->getEffectsFactoryHal()->getDescriptors(
Eric Laurentb3f315a2021-07-13 15:09:05 +02007766 EFFECT_UIID_DOWNMIX, &descriptors);
7767 if (status != NO_ERROR) {
7768 return;
7769 }
7770 ALOG_ASSERT(!descriptors.empty(),
7771 "%s getDescriptors() returned no error but empty list", __func__);
7772
7773 finalDownMixer = createEffect_l(nullptr /*client*/, nullptr /*effectClient*/,
7774 0 /*priority*/, AUDIO_SESSION_OUTPUT_STAGE, &descriptors[0], nullptr /*enabled*/,
Eric Laurentde8caf42021-08-11 17:19:25 +02007775 &status, false /*pinned*/, false /*probe*/, false /*notifyFramesProcessed*/);
Eric Laurentb3f315a2021-07-13 15:09:05 +02007776
7777 if (finalDownMixer == nullptr || (status != NO_ERROR && status != ALREADY_EXISTS)) {
7778 ALOGW("%s error creating downmixer %d", __func__, status);
7779 finalDownMixer.clear();
7780 } else {
7781 int32_t ret;
Andy Hung116bc262023-06-20 18:56:17 -07007782 finalDownMixer->asIEffect()->enable(&ret);
Eric Laurentb3f315a2021-07-13 15:09:05 +02007783 }
7784 }
7785
7786 {
7787 Mutex::Autolock _l(mLock);
7788 mFinalDownMixer = finalDownMixer;
7789 }
7790}
7791
Eric Laurent81784c32012-11-19 14:55:58 -08007792// ----------------------------------------------------------------------------
7793// Record
7794// ----------------------------------------------------------------------------
7795
Andy Hung583043b2023-07-17 17:05:00 -07007796sp<IAfRecordThread> IAfRecordThread::create(const sp<IAfThreadCallback>& afThreadCallback,
Andy Hung87c693c2023-07-06 20:56:16 -07007797 AudioStreamIn* input,
7798 audio_io_handle_t id,
7799 bool systemReady) {
Andy Hung583043b2023-07-17 17:05:00 -07007800 return sp<RecordThread>::make(afThreadCallback, input, id, systemReady);
Andy Hung87c693c2023-07-06 20:56:16 -07007801}
7802
Andy Hung583043b2023-07-17 17:05:00 -07007803RecordThread::RecordThread(const sp<IAfThreadCallback>& afThreadCallback,
Eric Laurent81784c32012-11-19 14:55:58 -08007804 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08007805 audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -07007806 bool systemReady
Glenn Kasten46909e72013-02-26 09:20:22 -08007807 ) :
Andy Hung583043b2023-07-17 17:05:00 -07007808 ThreadBase(afThreadCallback, id, RECORD, systemReady, false /* isOut */),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007809 mInput(input),
Mikhail Naganov2534b382019-09-25 13:05:02 -07007810 mSource(mInput),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007811 mActiveTracks(&this->mLocalLog),
7812 mRsmpInBuffer(NULL),
Glenn Kasten1b291842016-07-18 14:55:21 -07007813 // mRsmpInFrames, mRsmpInFramesP2, and mRsmpInFramesOA are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007814 mRsmpInRear(0)
Glenn Kastenb880f5e2014-05-07 08:43:45 -07007815 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
7816 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007817 // mFastCapture below
7818 , mFastCaptureFutex(0)
7819 // mInputSource
7820 // mPipeSink
7821 // mPipeSource
7822 , mPipeFramesP2(0)
7823 // mPipeMemory
7824 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07007825 , mFastTrackAvail(false)
Eric Laurentd8365c52017-07-16 15:27:05 -07007826 , mBtNrecSuspended(false)
Eric Laurent81784c32012-11-19 14:55:58 -08007827{
Glenn Kastend7dca052015-03-05 16:05:54 -08007828 snprintf(mThreadName, kThreadNameLength, "AudioIn_%X", id);
Andy Hung583043b2023-07-17 17:05:00 -07007829 mNBLogWriter = afThreadCallback->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08007830
George Burgess IVa8f90c12020-05-14 11:27:19 -07007831 if (mInput->audioHwDev != nullptr) {
Andy Hungc8fddf32018-08-08 18:32:37 -07007832 mIsMsdDevice = strcmp(
7833 mInput->audioHwDev->moduleName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0;
7834 }
7835
Glenn Kastendeca2ae2014-02-07 10:25:56 -08007836 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007837
Andy Hungc8fddf32018-08-08 18:32:37 -07007838 // TODO: We may also match on address as well as device type for
7839 // AUDIO_DEVICE_IN_BUS, AUDIO_DEVICE_IN_BLUETOOTH_A2DP, AUDIO_DEVICE_IN_REMOTE_SUBMIX
jiabinc52b1ff2019-10-31 17:20:42 -07007840 // TODO: This property should be ensure that only contains one single device type.
7841 mTimestampCorrectedDevice = (audio_devices_t)property_get_int64(
7842 "audio.timestamp.corrected_input_device",
Andy Hungc8fddf32018-08-08 18:32:37 -07007843 (int64_t)(mIsMsdDevice ? AUDIO_DEVICE_IN_BUS // turn on by default for MSD
7844 : AUDIO_DEVICE_NONE));
7845
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007846 // create an NBAIO source for the HAL input stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07007847 mInputSource = new AudioStreamInSource(input->stream);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007848 size_t numCounterOffers = 0;
7849 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07007850#if !LOG_NDEBUG
Jing Mike537412f2023-03-12 11:01:47 +08007851 [[maybe_unused]] ssize_t index =
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07007852#else
7853 (void)
7854#endif
7855 mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007856 ALOG_ASSERT(index == 0);
7857
7858 // initialize fast capture depending on configuration
7859 bool initFastCapture;
7860 switch (kUseFastCapture) {
7861 case FastCapture_Never:
7862 initFastCapture = false;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007863 ALOGV("%p kUseFastCapture = Never, initFastCapture = false", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007864 break;
7865 case FastCapture_Always:
7866 initFastCapture = true;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007867 ALOGV("%p kUseFastCapture = Always, initFastCapture = true", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007868 break;
7869 case FastCapture_Static:
Sampath6fac2332022-12-16 17:34:37 +11007870 initFastCapture = !mIsMsdDevice // Disable fast capture for MSD BUS devices.
7871 && (mFrameCount * 1000) / mSampleRate < kMinNormalCaptureBufferSizeMs;
7872 ALOGV("%p kUseFastCapture = Static, (%lld * 1000) / %u vs %u, initFastCapture = %d "
7873 "mIsMsdDevice = %d", this, (long long)mFrameCount, mSampleRate,
7874 kMinNormalCaptureBufferSizeMs, initFastCapture, mIsMsdDevice);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007875 break;
7876 // case FastCapture_Dynamic:
7877 }
7878
7879 if (initFastCapture) {
Glenn Kastend198b852015-03-16 14:55:53 -07007880 // create a Pipe for FastCapture to write to, and for us and fast tracks to read from
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007881 NBAIO_Format format = mInputSource->format();
Glenn Kasten1b291842016-07-18 14:55:21 -07007882 // quadruple-buffering of 20 ms each; this ensures we can sleep for 20ms in RecordThread
7883 size_t pipeFramesP2 = roundup(4 * FMS_20 * mSampleRate / 1000);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007884 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007885 void *pipeBuffer = nullptr;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007886 const sp<MemoryDealer> roHeap(readOnlyHeap());
7887 sp<IMemory> pipeMemory;
7888 if ((roHeap == 0) ||
7889 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07007890 (pipeBuffer = pipeMemory->unsecurePointer()) == nullptr) {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007891 ALOGE("not enough memory for pipe buffer size=%zu; "
7892 "roHeap=%p, pipeMemory=%p, pipeBuffer=%p; roHeapSize: %lld",
7893 pipeSize, roHeap.get(), pipeMemory.get(), pipeBuffer,
7894 (long long)kRecordThreadReadOnlyHeapSize);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007895 goto failed;
7896 }
7897 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
7898 memset(pipeBuffer, 0, pipeSize);
7899 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
Andy Hung920f6572022-10-06 12:09:49 -07007900 const NBAIO_Format offersFast[1] = {format};
7901 size_t numCounterOffersFast = 0;
Eric Laurent1e28aaa2023-04-16 19:34:23 +02007902 [[maybe_unused]] ssize_t index2 = pipe->negotiate(offersFast, std::size(offersFast),
Andy Hung920f6572022-10-06 12:09:49 -07007903 nullptr /* counterOffers */, numCounterOffersFast);
Eric Laurent1e28aaa2023-04-16 19:34:23 +02007904 ALOG_ASSERT(index2 == 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007905 mPipeSink = pipe;
7906 PipeReader *pipeReader = new PipeReader(*pipe);
Andy Hung920f6572022-10-06 12:09:49 -07007907 numCounterOffersFast = 0;
Eric Laurent1e28aaa2023-04-16 19:34:23 +02007908 index2 = pipeReader->negotiate(offersFast, std::size(offersFast),
Andy Hung920f6572022-10-06 12:09:49 -07007909 nullptr /* counterOffers */, numCounterOffersFast);
Eric Laurent1e28aaa2023-04-16 19:34:23 +02007910 ALOG_ASSERT(index2 == 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007911 mPipeSource = pipeReader;
7912 mPipeFramesP2 = pipeFramesP2;
7913 mPipeMemory = pipeMemory;
7914
7915 // create fast capture
7916 mFastCapture = new FastCapture();
7917 FastCaptureStateQueue *sq = mFastCapture->sq();
7918#ifdef STATE_QUEUE_DUMP
7919 // FIXME
7920#endif
7921 FastCaptureState *state = sq->begin();
7922 state->mCblk = NULL;
7923 state->mInputSource = mInputSource.get();
7924 state->mInputSourceGen++;
7925 state->mPipeSink = pipe;
7926 state->mPipeSinkGen++;
7927 state->mFrameCount = mFrameCount;
7928 state->mCommand = FastCaptureState::COLD_IDLE;
7929 // already done in constructor initialization list
7930 //mFastCaptureFutex = 0;
7931 state->mColdFutexAddr = &mFastCaptureFutex;
7932 state->mColdGen++;
7933 state->mDumpState = &mFastCaptureDumpState;
7934#ifdef TEE_SINK
7935 // FIXME
7936#endif
Andy Hung583043b2023-07-17 17:05:00 -07007937 mFastCaptureNBLogWriter =
7938 afThreadCallback->newWriter_l(kFastCaptureLogSize, "FastCapture");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007939 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
7940 sq->end();
7941 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
7942
7943 // start the fast capture
7944 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
7945 pid_t tid = mFastCapture->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07007946 sendPrioConfigEvent(getpid(), tid, kPriorityFastCapture, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08007947 stream()->setHalThreadPriority(kPriorityFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007948#ifdef AUDIO_WATCHDOG
7949 // FIXME
7950#endif
7951
Glenn Kasten6e6704c2014-07-03 10:20:00 -07007952 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007953 }
Andy Hung8946a282018-04-19 20:04:56 -07007954#ifdef TEE_SINK
7955 mTee.set(mInputSource->format(), NBAIO_Tee::TEE_FLAG_INPUT_THREAD);
7956 mTee.setId(std::string("_") + std::to_string(mId) + "_C");
7957#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007958failed: ;
7959
7960 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08007961}
7962
Andy Hungee58e4a2023-07-07 13:47:37 -07007963RecordThread::~RecordThread()
Eric Laurent81784c32012-11-19 14:55:58 -08007964{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007965 if (mFastCapture != 0) {
7966 FastCaptureStateQueue *sq = mFastCapture->sq();
7967 FastCaptureState *state = sq->begin();
7968 if (state->mCommand == FastCaptureState::COLD_IDLE) {
7969 int32_t old = android_atomic_inc(&mFastCaptureFutex);
7970 if (old == -1) {
7971 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
7972 }
7973 }
7974 state->mCommand = FastCaptureState::EXIT;
7975 sq->end();
7976 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
7977 mFastCapture->join();
7978 mFastCapture.clear();
7979 }
Andy Hung583043b2023-07-17 17:05:00 -07007980 mAfThreadCallback->unregisterWriter(mFastCaptureNBLogWriter);
7981 mAfThreadCallback->unregisterWriter(mNBLogWriter);
Andy Hung57446612015-04-19 23:56:46 -07007982 free(mRsmpInBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08007983}
7984
Andy Hungee58e4a2023-07-07 13:47:37 -07007985void RecordThread::onFirstRef()
Eric Laurent81784c32012-11-19 14:55:58 -08007986{
Glenn Kastend7dca052015-03-05 16:05:54 -08007987 run(mThreadName, PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08007988}
7989
Andy Hungee58e4a2023-07-07 13:47:37 -07007990void RecordThread::preExit()
Eric Laurent555530a2017-02-07 18:17:24 -08007991{
7992 ALOGV(" preExit()");
7993 Mutex::Autolock _l(mLock);
7994 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07007995 sp<IAfRecordTrack> track = mTracks[i];
Eric Laurent555530a2017-02-07 18:17:24 -08007996 track->invalidate();
7997 }
7998 mActiveTracks.clear();
7999 mStartStopCond.broadcast();
8000}
8001
Andy Hungee58e4a2023-07-07 13:47:37 -07008002bool RecordThread::threadLoop()
Eric Laurent81784c32012-11-19 14:55:58 -08008003{
Eric Laurent81784c32012-11-19 14:55:58 -08008004 nsecs_t lastWarning = 0;
8005
8006 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08008007
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008008reacquire_wakelock:
Andy Hung8d31fd22023-06-26 19:20:57 -07008009 sp<IAfRecordTrack> activeTrack;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008010 {
8011 Mutex::Autolock _l(mLock);
Andy Hungdae27702016-10-31 14:01:16 -07008012 acquireWakeLock_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008013 }
8014
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008015 // used to request a deferred sleep, to be executed later while mutex is unlocked
8016 uint32_t sleepUs = 0;
8017
Andy Hung446f4df2019-02-21 12:26:41 -08008018 int64_t lastLoopCountRead = -2; // never matches "previous" loop, when loopCount = 0.
8019
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008020 // loop while there is work to do
Andy Hung446f4df2019-02-21 12:26:41 -08008021 for (int64_t loopCount = 0;; ++loopCount) { // loopCount used for statistics tracking
Andy Hung116bc262023-06-20 18:56:17 -07008022 Vector<sp<IAfEffectChain>> effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07008023
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008024 // activeTracks accumulates a copy of a subset of mActiveTracks
Andy Hung8d31fd22023-06-26 19:20:57 -07008025 Vector<sp<IAfRecordTrack>> activeTracks;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008026
Glenn Kasten735f45f2014-08-18 15:51:59 -07008027 // reference to the (first and only) active fast track
Andy Hung8d31fd22023-06-26 19:20:57 -07008028 sp<IAfRecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07008029
Glenn Kasten735f45f2014-08-18 15:51:59 -07008030 // reference to a fast track which is about to be removed
Andy Hung8d31fd22023-06-26 19:20:57 -07008031 sp<IAfRecordTrack> fastTrackToRemove;
Glenn Kasten735f45f2014-08-18 15:51:59 -07008032
Eric Laurent33403f02020-05-29 18:35:06 -07008033 bool silenceFastCapture = false;
8034
Eric Laurent81784c32012-11-19 14:55:58 -08008035 { // scope for mLock
8036 Mutex::Autolock _l(mLock);
Eric Laurent000a4192014-01-29 15:17:32 -08008037
Eric Laurent021cf962014-05-13 10:18:14 -07008038 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008039
Eric Laurent000a4192014-01-29 15:17:32 -08008040 // check exitPending here because checkForNewParameters_l() and
8041 // checkForNewParameters_l() can temporarily release mLock
8042 if (exitPending()) {
8043 break;
8044 }
8045
Eric Laurent5c25d562016-07-13 17:17:45 -07008046 // sleep with mutex unlocked
8047 if (sleepUs > 0) {
Glenn Kastenf9715e42016-07-13 14:02:03 -07008048 ATRACE_BEGIN("sleepC");
Eric Laurent5c25d562016-07-13 17:17:45 -07008049 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)sleepUs));
8050 ATRACE_END();
8051 sleepUs = 0;
8052 continue;
8053 }
8054
Glenn Kasten2b806402013-11-20 16:37:38 -08008055 // if no active track(s), then standby and release wakelock
8056 size_t size = mActiveTracks.size();
8057 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07008058 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07008059 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08008060 releaseWakeLock_l();
8061 ALOGV("RecordThread: loop stopping");
8062 // go to sleep
8063 mWaitWorkCV.wait(mLock);
8064 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008065 goto reacquire_wakelock;
8066 }
8067
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008068 bool doBroadcast = false;
Eric Laurent5c25d562016-07-13 17:17:45 -07008069 bool allStopped = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008070 for (size_t i = 0; i < size; ) {
Glenn Kasten9e982352013-08-14 14:39:50 -07008071
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008072 activeTrack = mActiveTracks[i];
8073 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07008074 if (activeTrack->isFastTrack()) {
8075 ALOG_ASSERT(fastTrackToRemove == 0);
8076 fastTrackToRemove = activeTrack;
8077 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008078 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08008079 mActiveTracks.remove(activeTrack);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008080 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07008081 continue;
8082 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008083
Andy Hung8d31fd22023-06-26 19:20:57 -07008084 IAfTrackBase::track_state activeTrackState = activeTrack->state();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008085 switch (activeTrackState) {
8086
Andy Hung8d31fd22023-06-26 19:20:57 -07008087 case IAfTrackBase::PAUSING:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008088 mActiveTracks.remove(activeTrack);
Andy Hung8d31fd22023-06-26 19:20:57 -07008089 activeTrack->setState(IAfTrackBase::PAUSED);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008090 doBroadcast = true;
8091 size--;
8092 continue;
8093
Andy Hung8d31fd22023-06-26 19:20:57 -07008094 case IAfTrackBase::STARTING_1:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008095 sleepUs = 10000;
8096 i++;
Eric Laurent5c25d562016-07-13 17:17:45 -07008097 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008098 continue;
8099
Andy Hung8d31fd22023-06-26 19:20:57 -07008100 case IAfTrackBase::STARTING_2:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008101 doBroadcast = true;
Andy Hungcf10d742020-04-28 15:38:24 -07008102 if (mStandby) {
8103 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07008104 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -07008105 mStandby = false;
8106 }
Andy Hung8d31fd22023-06-26 19:20:57 -07008107 activeTrack->setState(IAfTrackBase::ACTIVE);
Eric Laurent5c25d562016-07-13 17:17:45 -07008108 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008109 break;
8110
Andy Hung8d31fd22023-06-26 19:20:57 -07008111 case IAfTrackBase::ACTIVE:
Eric Laurent5c25d562016-07-13 17:17:45 -07008112 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008113 break;
8114
Andy Hung8d31fd22023-06-26 19:20:57 -07008115 case IAfTrackBase::IDLE: // cannot be on ActiveTracks if idle
8116 case IAfTrackBase::PAUSED: // cannot be on ActiveTracks if paused
8117 case IAfTrackBase::STOPPED: // cannot be on ActiveTracks if destroyed/terminated
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008118 default:
Andy Hungce685402018-10-05 17:23:27 -07008119 LOG_ALWAYS_FATAL("%s: Unexpected active track state:%d, id:%d, tracks:%zu",
8120 __func__, activeTrackState, activeTrack->id(), size);
Glenn Kasten9e982352013-08-14 14:39:50 -07008121 }
Glenn Kasten9e982352013-08-14 14:39:50 -07008122
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008123 if (activeTrack->isFastTrack()) {
8124 ALOG_ASSERT(!mFastTrackAvail);
8125 ALOG_ASSERT(fastTrack == 0);
Eric Laurent33403f02020-05-29 18:35:06 -07008126 // if the active fast track is silenced either:
8127 // 1) silence the whole capture from fast capture buffer if this is
8128 // the only active track
8129 // 2) invalidate this track: this will cause the client to reconnect and possibly
8130 // be invalidated again until unsilenced
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008131 bool invalidate = false;
Eric Laurent33403f02020-05-29 18:35:06 -07008132 if (activeTrack->isSilenced()) {
8133 if (size > 1) {
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008134 invalidate = true;
Eric Laurent33403f02020-05-29 18:35:06 -07008135 } else {
8136 silenceFastCapture = true;
8137 }
8138 }
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008139 // Invalidate fast tracks if access to audio history is required as this is not
8140 // possible with fast tracks. Once the fast track has been invalidated, no new
8141 // fast track will be created until mMaxSharedAudioHistoryMs is cleared.
8142 if (mMaxSharedAudioHistoryMs != 0) {
8143 invalidate = true;
8144 }
8145 if (invalidate) {
8146 activeTrack->invalidate();
8147 ALOG_ASSERT(fastTrackToRemove == 0);
8148 fastTrackToRemove = activeTrack;
8149 removeTrack_l(activeTrack);
8150 mActiveTracks.remove(activeTrack);
8151 size--;
8152 continue;
8153 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008154 fastTrack = activeTrack;
8155 }
Eric Laurent33403f02020-05-29 18:35:06 -07008156
8157 activeTracks.add(activeTrack);
8158 i++;
8159
Glenn Kasten9e982352013-08-14 14:39:50 -07008160 }
Eric Laurent5c25d562016-07-13 17:17:45 -07008161
Andy Hungdae27702016-10-31 14:01:16 -07008162 mActiveTracks.updatePowerState(this);
8163
Kevin Rocard069c2712018-03-29 19:09:14 -07008164 updateMetadata_l();
8165
Eric Laurent5c25d562016-07-13 17:17:45 -07008166 if (allStopped) {
8167 standbyIfNotAlreadyInStandby();
8168 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008169 if (doBroadcast) {
8170 mStartStopCond.broadcast();
8171 }
8172
8173 // sleep if there are no active tracks to process
Eric Tan39ec8d62018-07-24 09:49:29 -07008174 if (activeTracks.isEmpty()) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008175 if (sleepUs == 0) {
8176 sleepUs = kRecordThreadSleepUs;
8177 }
8178 continue;
8179 }
8180 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07008181
Eric Laurent81784c32012-11-19 14:55:58 -08008182 lockEffectChains_l(effectChains);
8183 }
8184
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008185 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07008186
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008187 size_t size = effectChains.size();
8188 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008189 // thread mutex is not locked, but effect chain is locked
8190 effectChains[i]->process_l();
8191 }
8192
Glenn Kasten735f45f2014-08-18 15:51:59 -07008193 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008194 if (mFastCapture != 0) {
8195 FastCaptureStateQueue *sq = mFastCapture->sq();
8196 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07008197 bool didModify = false;
8198 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008199 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
8200 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
8201 if (state->mCommand == FastCaptureState::COLD_IDLE) {
8202 int32_t old = android_atomic_inc(&mFastCaptureFutex);
8203 if (old == -1) {
8204 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
8205 }
8206 }
8207 state->mCommand = FastCaptureState::READ_WRITE;
8208#if 0 // FIXME
Andy Hung583043b2023-07-17 17:05:00 -07008209 mFastCaptureDumpState.increaseSamplingN(mAfThreadCallback->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08008210 FastThreadDumpState::kSamplingNforLowRamDevice :
8211 FastThreadDumpState::kSamplingN);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008212#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07008213 didModify = true;
8214 }
8215 audio_track_cblk_t *cblkOld = state->mCblk;
8216 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
8217 if (cblkNew != cblkOld) {
8218 state->mCblk = cblkNew;
8219 // block until acked if removing a fast track
8220 if (cblkOld != NULL) {
8221 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
8222 }
8223 didModify = true;
8224 }
jiabin01c8f562018-07-19 17:47:28 -07008225 AudioBufferProvider* abp = (fastTrack != 0 && fastTrack->isPatchTrack()) ?
8226 reinterpret_cast<AudioBufferProvider*>(fastTrack.get()) : nullptr;
8227 if (state->mFastPatchRecordBufferProvider != abp) {
8228 state->mFastPatchRecordBufferProvider = abp;
8229 state->mFastPatchRecordFormat = fastTrack == 0 ?
8230 AUDIO_FORMAT_INVALID : fastTrack->format();
8231 didModify = true;
8232 }
Eric Laurent33403f02020-05-29 18:35:06 -07008233 if (state->mSilenceCapture != silenceFastCapture) {
8234 state->mSilenceCapture = silenceFastCapture;
8235 didModify = true;
8236 }
Glenn Kasten735f45f2014-08-18 15:51:59 -07008237 sq->end(didModify);
8238 if (didModify) {
8239 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008240#if 0
8241 if (kUseFastCapture == FastCapture_Dynamic) {
8242 mNormalSource = mPipeSource;
8243 }
8244#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008245 }
8246 }
8247
Glenn Kasten735f45f2014-08-18 15:51:59 -07008248 // now run the fast track destructor with thread mutex unlocked
8249 fastTrackToRemove.clear();
8250
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008251 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
8252 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
8253 // slow, then this RecordThread will overrun by not calling HAL read often enough.
8254 // If destination is non-contiguous, first read past the nominal end of buffer, then
8255 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008256
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008257 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Andy Hung920f6572022-10-06 12:09:49 -07008258 ssize_t framesRead = 0; // not needed, remove clang-tidy warning.
Andy Hung446f4df2019-02-21 12:26:41 -08008259 const int64_t lastIoBeginNs = systemTime(); // start IO timing
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008260
8261 // If an NBAIO source is present, use it to read the normal capture's data
8262 if (mPipeSource != 0) {
Andy Hung156317a2018-08-02 11:49:29 -07008263 size_t framesToRead = min(mRsmpInFramesOA - rear, mRsmpInFramesP2 / 2);
Andy Hungd5b638f2018-04-30 13:56:10 -07008264
8265 // The audio fifo read() returns OVERRUN on overflow, and advances the read pointer
8266 // to the full buffer point (clearing the overflow condition). Upon OVERRUN error,
8267 // we immediately retry the read() to get data and prevent another overflow.
8268 for (int retries = 0; retries <= 2; ++retries) {
8269 ALOGW_IF(retries > 0, "overrun on read from pipe, retry #%d", retries);
8270 framesRead = mPipeSource->read((uint8_t*)mRsmpInBuffer + rear * mFrameSize,
8271 framesToRead);
8272 if (framesRead != OVERRUN) break;
8273 }
8274
Andy Hung7a3dc6b2018-05-01 16:39:51 -07008275 const ssize_t availableToRead = mPipeSource->availableToRead();
8276 if (availableToRead >= 0) {
Robert Wu06db0a32021-08-10 19:05:34 +00008277 mMonopipePipeDepthStats.add(availableToRead);
Glenn Kastena2f59b32020-08-03 16:37:24 -07008278 // PipeSource is the primary clock. It is up to the AudioRecord client to keep up.
Andy Hung7a3dc6b2018-05-01 16:39:51 -07008279 LOG_ALWAYS_FATAL_IF((size_t)availableToRead > mPipeFramesP2,
8280 "more frames to read than fifo size, %zd > %zu",
8281 availableToRead, mPipeFramesP2);
8282 const size_t pipeFramesFree = mPipeFramesP2 - availableToRead;
8283 const size_t sleepFrames = min(pipeFramesFree, mRsmpInFramesP2) / 2;
8284 ALOGVV("mPipeFramesP2:%zu mRsmpInFramesP2:%zu sleepFrames:%zu availableToRead:%zd",
8285 mPipeFramesP2, mRsmpInFramesP2, sleepFrames, availableToRead);
Glenn Kasten1b291842016-07-18 14:55:21 -07008286 sleepUs = (sleepFrames * 1000000LL) / mSampleRate;
8287 }
8288 if (framesRead < 0) {
8289 status_t status = (status_t) framesRead;
8290 switch (status) {
8291 case OVERRUN:
8292 ALOGW("overrun on read from pipe");
8293 framesRead = 0;
8294 break;
8295 case NEGOTIATE:
8296 ALOGE("re-negotiation is needed");
8297 framesRead = -1; // Will cause an attempt to recover.
8298 break;
8299 default:
8300 ALOGE("unknown error %d on read from pipe", status);
8301 break;
8302 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008303 }
8304 // otherwise use the HAL / AudioStreamIn directly
8305 } else {
Glenn Kastenec6a7032016-03-14 07:40:23 -07008306 ATRACE_BEGIN("read");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008307 size_t bytesRead;
Mikhail Naganov2534b382019-09-25 13:05:02 -07008308 status_t result = mSource->read(
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008309 (uint8_t*)mRsmpInBuffer + rear * mFrameSize, mBufferSize, &bytesRead);
Glenn Kastenec6a7032016-03-14 07:40:23 -07008310 ATRACE_END();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008311 if (result < 0) {
8312 framesRead = result;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008313 } else {
8314 framesRead = bytesRead / mFrameSize;
8315 }
8316 }
8317
Andy Hung446f4df2019-02-21 12:26:41 -08008318 const int64_t lastIoEndNs = systemTime(); // end IO timing
8319
Andy Hung3f0c9022016-01-15 17:49:46 -08008320 // Update server timestamp with server stats
8321 // systemTime() is optional if the hardware supports timestamps.
Andy Hung743f6402020-06-03 13:17:04 -07008322 if (framesRead >= 0) {
8323 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += framesRead;
8324 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = lastIoEndNs;
8325 }
Andy Hung3f0c9022016-01-15 17:49:46 -08008326
8327 // Update server timestamp with kernel stats
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008328 if (mPipeSource.get() == nullptr /* don't obtain for FastCapture, could block */) {
Andy Hung3f0c9022016-01-15 17:49:46 -08008329 int64_t position, time;
Andy Hung2e2c0bb2018-06-11 19:13:11 -07008330 if (mStandby) {
Dean Wheatley12473e92021-03-18 23:00:55 +11008331 mTimestampVerifier.discontinuity(audio_is_linear_pcm(mFormat) ?
8332 mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS :
8333 mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Mikhail Naganov2534b382019-09-25 13:05:02 -07008334 } else if (mSource->getCapturePosition(&position, &time) == NO_ERROR
Andy Hungc8fddf32018-08-08 18:32:37 -07008335 && time > mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]) {
8336
8337 mTimestampVerifier.add(position, time, mSampleRate);
8338
8339 // Correct timestamps
8340 if (isTimestampCorrectionEnabled()) {
Dean Wheatley56a583e2020-05-08 15:12:17 +10008341 ALOGVV("TS_BEFORE: %d %lld %lld",
Andy Hungc8fddf32018-08-08 18:32:37 -07008342 id(), (long long)time, (long long)position);
8343 auto correctedTimestamp = mTimestampVerifier.getLastCorrectedTimestamp();
8344 position = correctedTimestamp.mFrames;
8345 time = correctedTimestamp.mTimeNs;
Dean Wheatley56a583e2020-05-08 15:12:17 +10008346 ALOGVV("TS_AFTER: %d %lld %lld",
Andy Hungc8fddf32018-08-08 18:32:37 -07008347 id(), (long long)time, (long long)position);
8348 }
8349
Andy Hung3f0c9022016-01-15 17:49:46 -08008350 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = position;
8351 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] = time;
8352 // Note: In general record buffers should tend to be empty in
8353 // a properly running pipeline.
8354 //
8355 // Also, it is not advantageous to call get_presentation_position during the read
8356 // as the read obtains a lock, preventing the timestamp call from executing.
Andy Hung2e2c0bb2018-06-11 19:13:11 -07008357 } else {
8358 mTimestampVerifier.error();
Andy Hung3f0c9022016-01-15 17:49:46 -08008359 }
8360 }
Andy Hunge6c37112019-02-26 17:38:10 -08008361
8362 // From the timestamp, input read latency is negative output write latency.
8363 const audio_input_flags_t flags = mInput != NULL ? mInput->flags : AUDIO_INPUT_FLAG_NONE;
Andy Hung8d31fd22023-06-26 19:20:57 -07008364 const double latencyMs = IAfRecordTrack::checkServerLatencySupported(mFormat, flags)
Andy Hunge6c37112019-02-26 17:38:10 -08008365 ? - mTimestamp.getOutputServerLatencyMs(mSampleRate) : 0.;
8366 if (latencyMs != 0.) { // note 0. means timestamp is empty.
8367 mLatencyMs.add(latencyMs);
8368 }
8369
Andy Hung3f0c9022016-01-15 17:49:46 -08008370 // Use this to track timestamp information
8371 // ALOGD("%s", mTimestamp.toString().c_str());
8372
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008373 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07008374 ALOGE("read failed: framesRead=%zd", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008375 // Force input into standby so that it tries to recover at next read attempt
8376 inputStandBy();
8377 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008378 }
8379 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008380 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008381 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008382 ALOG_ASSERT(framesRead > 0);
Andy Hung6427e442018-08-09 12:51:02 -07008383 mFramesRead += framesRead;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008384
Andy Hung8946a282018-04-19 20:04:56 -07008385#ifdef TEE_SINK
8386 (void)mTee.write((uint8_t*)mRsmpInBuffer + rear * mFrameSize, framesRead);
8387#endif
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008388 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008389 {
8390 size_t part1 = mRsmpInFramesP2 - rear;
8391 if ((size_t) framesRead > part1) {
Andy Hung57446612015-04-19 23:56:46 -07008392 memcpy(mRsmpInBuffer, (uint8_t*)mRsmpInBuffer + mRsmpInFramesP2 * mFrameSize,
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008393 (framesRead - part1) * mFrameSize);
8394 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008395 }
Dean Wheatleyfd56e812020-11-06 22:32:21 +11008396 mRsmpInRear = audio_utils::safe_add_overflow(mRsmpInRear, (int32_t)framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008397
8398 size = activeTracks.size();
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008399
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008400 // loop over each active track
8401 for (size_t i = 0; i < size; i++) {
8402 activeTrack = activeTracks[i];
8403
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008404 // skip fast tracks, as those are handled directly by FastCapture
8405 if (activeTrack->isFastTrack()) {
8406 continue;
8407 }
8408
Andy Hung73c02e42015-03-29 01:13:58 -07008409 // TODO: This code probably should be moved to RecordTrack.
Andy Hung97a893e2015-03-29 01:03:07 -07008410 // TODO: Update the activeTrack buffer converter in case of reconfigure.
8411
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008412 enum {
8413 OVERRUN_UNKNOWN,
8414 OVERRUN_TRUE,
8415 OVERRUN_FALSE
8416 } overrun = OVERRUN_UNKNOWN;
8417
8418 // loop over getNextBuffer to handle circular sink
8419 for (;;) {
8420
Andy Hung8d31fd22023-06-26 19:20:57 -07008421 activeTrack->sinkBuffer().frameCount = ~0;
8422 status_t status = activeTrack->getNextBuffer(&activeTrack->sinkBuffer());
8423 size_t framesOut = activeTrack->sinkBuffer().frameCount;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008424 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
8425
Andy Hung73c02e42015-03-29 01:13:58 -07008426 // check available frames and handle overrun conditions
8427 // if the record track isn't draining fast enough.
8428 bool hasOverrun;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008429 size_t framesIn;
Andy Hung8d31fd22023-06-26 19:20:57 -07008430 activeTrack->resamplerBufferProvider()->sync(&framesIn, &hasOverrun);
Andy Hung73c02e42015-03-29 01:13:58 -07008431 if (hasOverrun) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008432 overrun = OVERRUN_TRUE;
8433 }
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08008434 if (framesOut == 0 || framesIn == 0) {
8435 break;
8436 }
8437
Andy Hung6770c6f2015-04-07 13:43:36 -07008438 // Don't allow framesOut to be larger than what is possible with resampling
8439 // from framesIn.
8440 // This isn't strictly necessary but helps limit buffer resizing in
8441 // RecordBufferConverter. TODO: remove when no longer needed.
8442 framesOut = min(framesOut,
8443 destinationFramesPossible(
Andy Hung8d31fd22023-06-26 19:20:57 -07008444 framesIn, mSampleRate, activeTrack->sampleRate()));
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008445
8446 if (activeTrack->isDirect()) {
Daniel Van Veen9e2376e2018-09-27 14:37:58 +10008447 // No RecordBufferConverter used for direct streams. Pass
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008448 // straight from RecordThread buffer to RecordTrack buffer.
8449 AudioBufferProvider::Buffer buffer;
8450 buffer.frameCount = framesOut;
Andy Hung920f6572022-10-06 12:09:49 -07008451 const status_t getNextBufferStatus =
Andy Hung8d31fd22023-06-26 19:20:57 -07008452 activeTrack->resamplerBufferProvider()->getNextBuffer(&buffer);
Andy Hung920f6572022-10-06 12:09:49 -07008453 if (getNextBufferStatus == OK && buffer.frameCount != 0) {
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008454 ALOGV_IF(buffer.frameCount != framesOut,
8455 "%s() read less than expected (%zu vs %zu)",
8456 __func__, buffer.frameCount, framesOut);
8457 framesOut = buffer.frameCount;
Andy Hung8d31fd22023-06-26 19:20:57 -07008458 memcpy(activeTrack->sinkBuffer().raw,
8459 buffer.raw, buffer.frameCount * mFrameSize);
8460 activeTrack->resamplerBufferProvider()->releaseBuffer(&buffer);
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008461 } else {
8462 framesOut = 0;
8463 ALOGE("%s() cannot fill request, status: %d, frameCount: %zu",
Andy Hung920f6572022-10-06 12:09:49 -07008464 __func__, getNextBufferStatus, buffer.frameCount);
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008465 }
8466 } else {
8467 // process frames from the RecordThread buffer provider to the RecordTrack
8468 // buffer
Andy Hung8d31fd22023-06-26 19:20:57 -07008469 framesOut = activeTrack->recordBufferConverter()->convert(
8470 activeTrack->sinkBuffer().raw,
8471 activeTrack->resamplerBufferProvider(),
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008472 framesOut);
8473 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008474
8475 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
8476 overrun = OVERRUN_FALSE;
8477 }
8478
Andy Hung93bb5732023-05-04 21:16:34 -07008479 // MediaSyncEvent handling: Synchronize AudioRecord to AudioTrack completion.
8480 const ssize_t framesToDrop =
Andy Hung8d31fd22023-06-26 19:20:57 -07008481 activeTrack->synchronizedRecordState().updateRecordFrames(framesOut);
Andy Hung93bb5732023-05-04 21:16:34 -07008482 if (framesToDrop == 0) {
8483 // no sync event, process normally, otherwise ignore.
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008484 if (framesOut > 0) {
Andy Hung8d31fd22023-06-26 19:20:57 -07008485 activeTrack->sinkBuffer().frameCount = framesOut;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008486 // Sanitize before releasing if the track has no access to the source data
8487 // An idle UID receives silence from non virtual devices until active
8488 if (activeTrack->isSilenced()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07008489 memset(activeTrack->sinkBuffer().raw,
8490 0, framesOut * activeTrack->frameSize());
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008491 }
Andy Hung8d31fd22023-06-26 19:20:57 -07008492 activeTrack->releaseBuffer(&activeTrack->sinkBuffer());
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008493 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008494 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008495 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008496 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008497 }
8498 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008499
8500 switch (overrun) {
8501 case OVERRUN_TRUE:
8502 // client isn't retrieving buffers fast enough
8503 if (!activeTrack->setOverflow()) {
8504 nsecs_t now = systemTime();
8505 // FIXME should lastWarning per track?
8506 if ((now - lastWarning) > kWarningThrottleNs) {
8507 ALOGW("RecordThread: buffer overflow");
8508 lastWarning = now;
8509 }
8510 }
8511 break;
8512 case OVERRUN_FALSE:
8513 activeTrack->clearOverflow();
8514 break;
8515 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008516 break;
8517 }
8518
Andy Hung3f0c9022016-01-15 17:49:46 -08008519 // update frame information and push timestamp out
8520 activeTrack->updateTrackFrameInfo(
Andy Hung8d31fd22023-06-26 19:20:57 -07008521 activeTrack->serverProxy()->framesReleased(),
Andy Hung3f0c9022016-01-15 17:49:46 -08008522 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER],
8523 mSampleRate, mTimestamp);
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008524 }
8525
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008526unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08008527 // enable changes in effect chain
8528 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07008529 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurentcccbc762019-04-05 14:20:05 -07008530 if (audio_has_proportional_frames(mFormat)
8531 && loopCount == lastLoopCountRead + 1) {
8532 const int64_t readPeriodNs = lastIoEndNs - mLastIoEndNs;
8533 const double jitterMs =
8534 TimestampVerifier<int64_t, int64_t>::computeJitterMs(
8535 {framesRead, readPeriodNs},
8536 {0, 0} /* lastTimestamp */, mSampleRate);
8537 const double processMs = (lastIoBeginNs - mLastIoEndNs) * 1e-6;
8538
8539 Mutex::Autolock _l(mLock);
8540 mIoJitterMs.add(jitterMs);
8541 mProcessTimeMs.add(processMs);
8542 }
8543 // update timing info.
8544 mLastIoBeginNs = lastIoBeginNs;
8545 mLastIoEndNs = lastIoEndNs;
8546 lastLoopCountRead = loopCount;
Eric Laurent81784c32012-11-19 14:55:58 -08008547 }
8548
Glenn Kasten93e471f2013-08-19 08:40:07 -07008549 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08008550
8551 {
8552 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07008553 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07008554 sp<IAfRecordTrack> track = mTracks[i];
Eric Laurent9a54bc22013-09-09 09:08:44 -07008555 track->invalidate();
8556 }
Glenn Kasten2b806402013-11-20 16:37:38 -08008557 mActiveTracks.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08008558 mStartStopCond.broadcast();
8559 }
8560
8561 releaseWakeLock();
8562
8563 ALOGV("RecordThread %p exiting", this);
8564 return false;
8565}
8566
Andy Hungee58e4a2023-07-07 13:47:37 -07008567void RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08008568{
8569 if (!mStandby) {
8570 inputStandBy();
Andy Hungcf10d742020-04-28 15:38:24 -07008571 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07008572 mThreadSnapshot.onEnd();
Eric Laurent81784c32012-11-19 14:55:58 -08008573 mStandby = true;
8574 }
8575}
8576
Andy Hungee58e4a2023-07-07 13:47:37 -07008577void RecordThread::inputStandBy()
Eric Laurent81784c32012-11-19 14:55:58 -08008578{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008579 // Idle the fast capture if it's currently running
8580 if (mFastCapture != 0) {
8581 FastCaptureStateQueue *sq = mFastCapture->sq();
8582 FastCaptureState *state = sq->begin();
8583 if (!(state->mCommand & FastCaptureState::IDLE)) {
8584 state->mCommand = FastCaptureState::COLD_IDLE;
8585 state->mColdFutexAddr = &mFastCaptureFutex;
8586 state->mColdGen++;
8587 mFastCaptureFutex = 0;
8588 sq->end();
8589 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
8590 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
8591#if 0
8592 if (kUseFastCapture == FastCapture_Dynamic) {
8593 // FIXME
8594 }
8595#endif
8596#ifdef AUDIO_WATCHDOG
8597 // FIXME
8598#endif
8599 } else {
8600 sq->end(false /*didModify*/);
8601 }
8602 }
Mikhail Naganov2534b382019-09-25 13:05:02 -07008603 status_t result = mSource->standby();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008604 ALOGE_IF(result != OK, "Error when putting input stream into standby: %d", result);
Andy Hungad6d52d2016-07-18 13:42:03 -07008605
8606 // If going into standby, flush the pipe source.
8607 if (mPipeSource.get() != nullptr) {
8608 const ssize_t flushed = mPipeSource->flush();
8609 if (flushed > 0) {
8610 ALOGV("Input standby flushed PipeSource %zd frames", flushed);
8611 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += flushed;
8612 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
8613 }
8614 }
Eric Laurent81784c32012-11-19 14:55:58 -08008615}
8616
Glenn Kasten05997e22014-03-13 15:08:33 -07008617// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held
Andy Hungee58e4a2023-07-07 13:47:37 -07008618sp<IAfRecordTrack> RecordThread::createRecordTrack_l(
Andy Hung88035ac2023-06-27 17:05:02 -07008619 const sp<Client>& client,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07008620 const audio_attributes_t& attr,
Eric Laurentf14db3c2017-12-08 14:20:36 -08008621 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08008622 audio_format_t format,
8623 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08008624 size_t *pFrameCount,
Glenn Kastend848eb42016-03-08 13:42:11 -08008625 audio_session_t sessionId,
Eric Laurentf14db3c2017-12-08 14:20:36 -08008626 size_t *pNotificationFrameCount,
Eric Laurent09f1ed22019-04-24 17:45:17 -07008627 pid_t creatorPid,
Svet Ganov33761132021-05-13 22:51:08 +00008628 const AttributionSourceState& attributionSource,
Eric Laurent05067782016-06-01 18:27:28 -07008629 audio_input_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08008630 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08008631 status_t *status,
Eric Laurentec376dc2021-04-08 20:41:22 +02008632 audio_port_handle_t portId,
8633 int32_t maxSharedAudioHistoryMs)
Eric Laurent81784c32012-11-19 14:55:58 -08008634{
Glenn Kasten74935e42013-12-19 08:56:45 -08008635 size_t frameCount = *pFrameCount;
Eric Laurentf14db3c2017-12-08 14:20:36 -08008636 size_t notificationFrameCount = *pNotificationFrameCount;
Andy Hung8d31fd22023-06-26 19:20:57 -07008637 sp<IAfRecordTrack> track;
Eric Laurent81784c32012-11-19 14:55:58 -08008638 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07008639 audio_input_flags_t inputFlags = mInput->flags;
Eric Laurentf14db3c2017-12-08 14:20:36 -08008640 audio_input_flags_t requestedFlags = *flags;
8641 uint32_t sampleRate;
8642
8643 lStatus = initCheck();
8644 if (lStatus != NO_ERROR) {
8645 ALOGE("createRecordTrack_l() audio driver not initialized");
8646 goto Exit;
8647 }
8648
Mikhail Naganovce9f2652018-07-16 11:09:24 -07008649 if (!audio_is_linear_pcm(mFormat) && (*flags & AUDIO_INPUT_FLAG_DIRECT) == 0) {
8650 ALOGE("createRecordTrack_l() on an encoded stream requires AUDIO_INPUT_FLAG_DIRECT");
8651 lStatus = BAD_VALUE;
8652 goto Exit;
8653 }
8654
Eric Laurentec376dc2021-04-08 20:41:22 +02008655 if (maxSharedAudioHistoryMs != 0) {
Eric Laurent9ff3e532022-11-10 16:04:44 +01008656 if (!captureHotwordAllowed(attributionSource)) {
Eric Laurentec376dc2021-04-08 20:41:22 +02008657 lStatus = PERMISSION_DENIED;
8658 goto Exit;
8659 }
Eric Laurentec376dc2021-04-08 20:41:22 +02008660 if (maxSharedAudioHistoryMs < 0
8661 || maxSharedAudioHistoryMs > AudioFlinger::kMaxSharedAudioHistoryMs) {
8662 lStatus = BAD_VALUE;
8663 goto Exit;
8664 }
8665 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08008666 if (*pSampleRate == 0) {
8667 *pSampleRate = mSampleRate;
8668 }
8669 sampleRate = *pSampleRate;
Eric Laurent05067782016-06-01 18:27:28 -07008670
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008671 // special case for FAST flag considered OK if fast capture is present and access to
8672 // audio history is not required
8673 if (hasFastCapture() && mMaxSharedAudioHistoryMs == 0) {
Eric Laurent05067782016-06-01 18:27:28 -07008674 inputFlags = (audio_input_flags_t)(inputFlags | AUDIO_INPUT_FLAG_FAST);
8675 }
8676
Eric Laurentf14db3c2017-12-08 14:20:36 -08008677 // Check if requested flags are compatible with input stream flags
Eric Laurent05067782016-06-01 18:27:28 -07008678 if ((*flags & inputFlags) != *flags) {
8679 ALOGW("createRecordTrack_l(): mismatch between requested flags (%08x) and"
8680 " input flags (%08x)",
8681 *flags, inputFlags);
8682 *flags = (audio_input_flags_t)(*flags & inputFlags);
8683 }
Eric Laurent81784c32012-11-19 14:55:58 -08008684
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008685 // client expresses a preference for FAST and no access to audio history,
8686 // but we get the final say
8687 if (*flags & AUDIO_INPUT_FLAG_FAST && maxSharedAudioHistoryMs == 0) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07008688 if (
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07008689 // we formerly checked for a callback handler (non-0 tid),
8690 // but that is no longer required for TRANSFER_OBTAIN mode
jiabinb00edc32021-08-16 16:27:54 +00008691 // No need to match hardware format, format conversion will be done in client side.
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07008692 //
Phil Burk7ed66a12019-04-18 13:20:30 -07008693 // Frame count is not specified (0), or is less than or equal the pipe depth.
8694 // It is OK to provide a higher capacity than requested.
8695 // We will force it to mPipeFramesP2 below.
8696 (frameCount <= mPipeFramesP2) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07008697 // PCM data
8698 audio_is_linear_pcm(format) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08008699 // hardware channel mask
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008700 (channelMask == mChannelMask) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08008701 // hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07008702 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07008703 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008704 hasFastCapture() &&
8705 // there are sufficient fast track slots available
8706 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07008707 ) {
Eric Laurent4c415062016-06-17 16:14:16 -07008708 // check compatibility with audio effects.
8709 Mutex::Autolock _l(mLock);
8710 // Do not accept FAST flag if the session has software effects
Andy Hung116bc262023-06-20 18:56:17 -07008711 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent4c415062016-06-17 16:14:16 -07008712 if (chain != 0) {
Andy Hungd3bb0ad2016-10-11 17:16:43 -07008713 audio_input_flags_t old = *flags;
8714 chain->checkInputFlagCompatibility(flags);
8715 if (old != *flags) {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008716 ALOGV("%p AUDIO_INPUT_FLAGS denied by effect old=%#x new=%#x",
8717 this, (int)old, (int)*flags);
Eric Laurent4c415062016-06-17 16:14:16 -07008718 }
8719 }
Eric Laurent122f7e72016-06-29 11:53:29 -07008720 ALOGV_IF((*flags & AUDIO_INPUT_FLAG_FAST) != 0,
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008721 "%p AUDIO_INPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
8722 this, frameCount, mFrameCount);
Glenn Kasten90e58b12013-07-31 16:16:02 -07008723 } else {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008724 ALOGV("%p AUDIO_INPUT_FLAG_FAST denied: frameCount=%zu mFrameCount=%zu mPipeFramesP2=%zu "
8725 "format=%#x isLinear=%d mFormat=%#x channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008726 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008727 this, frameCount, mFrameCount, mPipeFramesP2,
8728 format, audio_is_linear_pcm(format), mFormat, channelMask, sampleRate, mSampleRate,
Glenn Kasten74105912014-07-03 12:28:53 -07008729 hasFastCapture(), tid, mFastTrackAvail);
Eric Laurent05067782016-06-01 18:27:28 -07008730 *flags = (audio_input_flags_t)(*flags & ~AUDIO_INPUT_FLAG_FAST);
Glenn Kasten74105912014-07-03 12:28:53 -07008731 }
8732 }
8733
Eric Laurentf14db3c2017-12-08 14:20:36 -08008734 // If FAST or RAW flags were corrected, ask caller to request new input from audio policy
8735 if ((*flags & AUDIO_INPUT_FLAG_FAST) !=
8736 (requestedFlags & AUDIO_INPUT_FLAG_FAST)) {
8737 *flags = (audio_input_flags_t) (*flags & ~(AUDIO_INPUT_FLAG_FAST | AUDIO_INPUT_FLAG_RAW));
8738 lStatus = BAD_TYPE;
8739 goto Exit;
8740 }
8741
Glenn Kasten74105912014-07-03 12:28:53 -07008742 // compute track buffer size in frames, and suggest the notification frame count
Eric Laurent05067782016-06-01 18:27:28 -07008743 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten74105912014-07-03 12:28:53 -07008744 // fast track: frame count is exactly the pipe depth
8745 frameCount = mPipeFramesP2;
8746 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
Eric Laurentf14db3c2017-12-08 14:20:36 -08008747 notificationFrameCount = mFrameCount;
Glenn Kasten74105912014-07-03 12:28:53 -07008748 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07008749 // not fast track: max notification period is resampled equivalent of one HAL buffer time
8750 // or 20 ms if there is a fast capture
8751 // TODO This could be a roundupRatio inline, and const
8752 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
8753 * sampleRate + mSampleRate - 1) / mSampleRate;
8754 // minimum number of notification periods is at least kMinNotifications,
8755 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
8756 static const size_t kMinNotifications = 3;
8757 static const uint32_t kMinMs = 30;
8758 // TODO This could be a roundupRatio inline
8759 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
8760 // TODO This could be a roundupRatio inline
8761 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
8762 maxNotificationFrames;
8763 const size_t minFrameCount = maxNotificationFrames *
8764 max(kMinNotifications, minNotificationsByMs);
8765 frameCount = max(frameCount, minFrameCount);
Eric Laurentf14db3c2017-12-08 14:20:36 -08008766 if (notificationFrameCount == 0 || notificationFrameCount > maxNotificationFrames) {
8767 notificationFrameCount = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07008768 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07008769 }
Glenn Kasten74935e42013-12-19 08:56:45 -08008770 *pFrameCount = frameCount;
Eric Laurentf14db3c2017-12-08 14:20:36 -08008771 *pNotificationFrameCount = notificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08008772
8773 { // scope for mLock
8774 Mutex::Autolock _l(mLock);
Eric Laurent2407ce32021-04-26 14:56:03 +02008775 int32_t startFrames = -1;
Eric Laurentec376dc2021-04-08 20:41:22 +02008776 if (!mSharedAudioPackageName.empty()
Eric Laurent9ff3e532022-11-10 16:04:44 +01008777 && mSharedAudioPackageName == attributionSource.packageName
Eric Laurentec376dc2021-04-08 20:41:22 +02008778 && mSharedAudioSessionId == sessionId
Eric Laurent9ff3e532022-11-10 16:04:44 +01008779 && captureHotwordAllowed(attributionSource)) {
Eric Laurent2407ce32021-04-26 14:56:03 +02008780 startFrames = mSharedAudioStartFrames;
Eric Laurentec376dc2021-04-08 20:41:22 +02008781 }
Eric Laurent81784c32012-11-19 14:55:58 -08008782
Andy Hung8d31fd22023-06-26 19:20:57 -07008783 track = IAfRecordTrack::create(this, client, attr, sampleRate,
Andy Hung8fe68032017-06-05 16:17:51 -07008784 format, channelMask, frameCount,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07008785 nullptr /* buffer */, (size_t)0 /* bufferSize */, sessionId, creatorPid,
Andy Hung8d31fd22023-06-26 19:20:57 -07008786 attributionSource, *flags, IAfTrackBase::TYPE_DEFAULT, portId,
Svet Ganov33761132021-05-13 22:51:08 +00008787 startFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08008788
Glenn Kasten03003332013-08-06 15:40:54 -07008789 lStatus = track->initCheck();
8790 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07008791 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08008792 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08008793 goto Exit;
8794 }
8795 mTracks.add(track);
8796
Eric Laurent05067782016-06-01 18:27:28 -07008797 if ((*flags & AUDIO_INPUT_FLAG_FAST) && (tid != -1)) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07008798 pid_t callingPid = IPCThreadState::self()->getCallingPid();
8799 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
8800 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07008801 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Glenn Kasten90e58b12013-07-31 16:16:02 -07008802 }
Eric Laurentec376dc2021-04-08 20:41:22 +02008803
8804 if (maxSharedAudioHistoryMs != 0) {
8805 sendResizeBufferConfigEvent_l(maxSharedAudioHistoryMs);
8806 }
Eric Laurent81784c32012-11-19 14:55:58 -08008807 }
Glenn Kasten05997e22014-03-13 15:08:33 -07008808
Eric Laurent81784c32012-11-19 14:55:58 -08008809 lStatus = NO_ERROR;
8810
8811Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07008812 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08008813 return track;
8814}
8815
Andy Hungee58e4a2023-07-07 13:47:37 -07008816status_t RecordThread::start(IAfRecordTrack* recordTrack,
Eric Laurent81784c32012-11-19 14:55:58 -08008817 AudioSystem::sync_event_t event,
Glenn Kastend848eb42016-03-08 13:42:11 -08008818 audio_session_t triggerSession)
Eric Laurent81784c32012-11-19 14:55:58 -08008819{
8820 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
8821 sp<ThreadBase> strongMe = this;
8822 status_t status = NO_ERROR;
8823
8824 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08008825 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08008826 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Andy Hung8d31fd22023-06-26 19:20:57 -07008827 recordTrack->synchronizedRecordState().startRecording(
Andy Hung583043b2023-07-17 17:05:00 -07008828 mAfThreadCallback->createSyncEvent(
Andy Hung93bb5732023-05-04 21:16:34 -07008829 event, triggerSession,
8830 recordTrack->sessionId(), syncStartEventCallback, recordTrack));
Eric Laurent81784c32012-11-19 14:55:58 -08008831 }
8832
8833 {
Glenn Kasten47c20702013-08-13 15:37:35 -07008834 // This section is a rendezvous between binder thread executing start() and RecordThread
Eric Laurent81784c32012-11-19 14:55:58 -08008835 AutoMutex lock(mLock);
Andy Hungce685402018-10-05 17:23:27 -07008836 if (recordTrack->isInvalid()) {
8837 recordTrack->clearSyncStartEvent();
Eric Laurentd52a28c2020-08-21 17:10:39 -07008838 ALOGW("%s track %d: invalidated before startInput", __func__, recordTrack->portId());
8839 return DEAD_OBJECT;
Andy Hungce685402018-10-05 17:23:27 -07008840 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008841 if (mActiveTracks.indexOf(recordTrack) >= 0) {
Andy Hung8d31fd22023-06-26 19:20:57 -07008842 if (recordTrack->state() == IAfTrackBase::PAUSING) {
Andy Hungce685402018-10-05 17:23:27 -07008843 // We haven't stopped yet (moved to PAUSED and not in mActiveTracks)
8844 // so no need to startInput().
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008845 ALOGV("active record track PAUSING -> ACTIVE");
Andy Hung8d31fd22023-06-26 19:20:57 -07008846 recordTrack->setState(IAfTrackBase::ACTIVE);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008847 } else {
Andy Hung8d31fd22023-06-26 19:20:57 -07008848 ALOGV("active record track state %d", (int)recordTrack->state());
Eric Laurent81784c32012-11-19 14:55:58 -08008849 }
8850 return status;
8851 }
8852
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08008853 // TODO consider other ways of handling this, such as changing the state to :STARTING and
8854 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
8855 // or using a separate command thread
Andy Hung8d31fd22023-06-26 19:20:57 -07008856 recordTrack->setState(IAfTrackBase::STARTING_1);
Glenn Kasten2b806402013-11-20 16:37:38 -08008857 mActiveTracks.add(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07008858 if (recordTrack->isExternalTrack()) {
8859 mLock.unlock();
Eric Laurent4eb58f12018-12-07 16:41:02 -08008860 status = AudioSystem::startInput(recordTrack->portId());
Eric Laurent83b88082014-06-20 18:31:16 -07008861 mLock.lock();
Andy Hungce685402018-10-05 17:23:27 -07008862 if (recordTrack->isInvalid()) {
8863 recordTrack->clearSyncStartEvent();
Andy Hung8d31fd22023-06-26 19:20:57 -07008864 if (status == NO_ERROR && recordTrack->state() == IAfTrackBase::STARTING_1) {
8865 recordTrack->setState(IAfTrackBase::STARTING_2);
Andy Hungce685402018-10-05 17:23:27 -07008866 // STARTING_2 forces destroy to call stopInput.
8867 }
Eric Laurentd52a28c2020-08-21 17:10:39 -07008868 ALOGW("%s track %d: invalidated after startInput", __func__, recordTrack->portId());
8869 return DEAD_OBJECT;
Andy Hungce685402018-10-05 17:23:27 -07008870 }
Andy Hung8d31fd22023-06-26 19:20:57 -07008871 if (recordTrack->state() != IAfTrackBase::STARTING_1) {
Andy Hungce685402018-10-05 17:23:27 -07008872 ALOGW("%s(%d): unsynchronized mState:%d change",
Andy Hung8d31fd22023-06-26 19:20:57 -07008873 __func__, recordTrack->id(), (int)recordTrack->state());
Andy Hungce685402018-10-05 17:23:27 -07008874 // Someone else has changed state, let them take over,
8875 // leave mState in the new state.
8876 recordTrack->clearSyncStartEvent();
8877 return INVALID_OPERATION;
8878 }
8879 // we're ok, but perhaps startInput has failed
Eric Laurent83b88082014-06-20 18:31:16 -07008880 if (status != NO_ERROR) {
Andy Hungce685402018-10-05 17:23:27 -07008881 ALOGW("%s(%d): startInput failed, status %d",
8882 __func__, recordTrack->id(), status);
8883 // We are in ActiveTracks if STARTING_1 and valid, so remove from ActiveTracks,
8884 // leave in STARTING_1, so destroy() will not call stopInput.
Eric Laurent83b88082014-06-20 18:31:16 -07008885 mActiveTracks.remove(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07008886 recordTrack->clearSyncStartEvent();
Eric Laurent83b88082014-06-20 18:31:16 -07008887 return status;
8888 }
Eric Laurent09f1ed22019-04-24 17:45:17 -07008889 sendIoConfigEvent_l(
8890 AUDIO_CLIENT_STARTED, recordTrack->creatorPid(), recordTrack->portId());
Eric Laurent81784c32012-11-19 14:55:58 -08008891 }
Andy Hungc2b11cb2020-04-22 09:04:01 -07008892
8893 recordTrack->logBeginInterval(patchSourcesToString(&mPatch)); // log to MediaMetrics
8894
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008895 // Catch up with current buffer indices if thread is already running.
8896 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
8897 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
8898 // see previously buffered data before it called start(), but with greater risk of overrun.
8899
Andy Hung8d31fd22023-06-26 19:20:57 -07008900 recordTrack->resamplerBufferProvider()->reset();
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008901 if (!recordTrack->isDirect()) {
8902 // clear any converter state as new data will be discontinuous
Andy Hung8d31fd22023-06-26 19:20:57 -07008903 recordTrack->recordBufferConverter()->reset();
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008904 }
Andy Hung8d31fd22023-06-26 19:20:57 -07008905 recordTrack->setState(IAfTrackBase::STARTING_2);
Eric Laurent81784c32012-11-19 14:55:58 -08008906 // signal thread to start
Eric Laurent81784c32012-11-19 14:55:58 -08008907 mWaitWorkCV.broadcast();
Eric Laurent81784c32012-11-19 14:55:58 -08008908 return status;
8909 }
Eric Laurent81784c32012-11-19 14:55:58 -08008910}
8911
Andy Hungee58e4a2023-07-07 13:47:37 -07008912void RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
Eric Laurent81784c32012-11-19 14:55:58 -08008913{
Andy Hungee58e4a2023-07-07 13:47:37 -07008914 const sp<SyncEvent> strongEvent = event.promote();
Eric Laurent81784c32012-11-19 14:55:58 -08008915
8916 if (strongEvent != 0) {
Andy Hungd29af632023-06-23 19:27:19 -07008917 sp<IAfTrackBase> ptr =
8918 std::any_cast<const wp<IAfTrackBase>>(strongEvent->cookie()).promote();
8919 if (ptr != nullptr) {
Andy Hung99b1ba62023-07-14 11:00:08 -07008920 // TODO(b/291317898) handleSyncStartEvent is in IAfTrackBase not IAfRecordTrack.
Andy Hungd29af632023-06-23 19:27:19 -07008921 ptr->handleSyncStartEvent(strongEvent);
Eric Laurent8ea16e42014-02-20 16:26:11 -08008922 }
Eric Laurent81784c32012-11-19 14:55:58 -08008923 }
8924}
8925
Andy Hungee58e4a2023-07-07 13:47:37 -07008926bool RecordThread::stop(IAfRecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08008927 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07008928 AutoMutex _l(mLock);
Andy Hungce685402018-10-05 17:23:27 -07008929 // if we're invalid, we can't be on the ActiveTracks.
Andy Hung8d31fd22023-06-26 19:20:57 -07008930 if (mActiveTracks.indexOf(recordTrack) < 0 || recordTrack->state() == IAfTrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08008931 return false;
8932 }
Glenn Kasten47c20702013-08-13 15:37:35 -07008933 // note that threadLoop may still be processing the track at this point [without lock]
Andy Hung8d31fd22023-06-26 19:20:57 -07008934 recordTrack->setState(IAfTrackBase::PAUSING);
Andy Hungce685402018-10-05 17:23:27 -07008935
Andy Hungabfab202019-03-07 19:45:54 -08008936 // NOTE: Waiting here is important to keep stop synchronous.
8937 // This is needed for proper patchRecord peer release.
Andy Hung8d31fd22023-06-26 19:20:57 -07008938 while (recordTrack->state() == IAfTrackBase::PAUSING && !recordTrack->isInvalid()) {
Andy Hungce685402018-10-05 17:23:27 -07008939 mWaitWorkCV.broadcast(); // signal thread to stop
8940 mStartStopCond.wait(mLock);
Eric Laurent81784c32012-11-19 14:55:58 -08008941 }
Andy Hungce685402018-10-05 17:23:27 -07008942
Andy Hung8d31fd22023-06-26 19:20:57 -07008943 if (recordTrack->state() == IAfTrackBase::PAUSED) { // successful stop
Eric Laurent81784c32012-11-19 14:55:58 -08008944 ALOGV("Record stopped OK");
8945 return true;
8946 }
Andy Hungce685402018-10-05 17:23:27 -07008947
8948 // don't handle anything - we've been invalidated or restarted and in a different state
8949 ALOGW_IF("%s(%d): unsynchronized stop, state: %d",
Andy Hung8d31fd22023-06-26 19:20:57 -07008950 __func__, recordTrack->id(), recordTrack->state());
Eric Laurent81784c32012-11-19 14:55:58 -08008951 return false;
8952}
8953
Andy Hungee58e4a2023-07-07 13:47:37 -07008954bool RecordThread::isValidSyncEvent(const sp<SyncEvent>& /* event */) const
Eric Laurent81784c32012-11-19 14:55:58 -08008955{
8956 return false;
8957}
8958
Andy Hungee58e4a2023-07-07 13:47:37 -07008959status_t RecordThread::setSyncEvent(const sp<SyncEvent>& /* event */)
Eric Laurent81784c32012-11-19 14:55:58 -08008960{
8961#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
8962 if (!isValidSyncEvent(event)) {
8963 return BAD_VALUE;
8964 }
8965
Glenn Kastend848eb42016-03-08 13:42:11 -08008966 audio_session_t eventSession = event->triggerSession();
Eric Laurent81784c32012-11-19 14:55:58 -08008967 status_t ret = NAME_NOT_FOUND;
8968
8969 Mutex::Autolock _l(mLock);
8970
8971 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07008972 sp<IAfRecordTrack> track = mTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08008973 if (eventSession == track->sessionId()) {
8974 (void) track->setSyncEvent(event);
8975 ret = NO_ERROR;
8976 }
8977 }
8978 return ret;
8979#else
8980 return BAD_VALUE;
8981#endif
8982}
8983
Andy Hungee58e4a2023-07-07 13:47:37 -07008984status_t RecordThread::getActiveMicrophones(
Andy Hung87c693c2023-07-06 20:56:16 -07008985 std::vector<media::MicrophoneInfoFw>* activeMicrophones) const
jiabin653cc0a2018-01-17 17:54:10 -08008986{
8987 ALOGV("RecordThread::getActiveMicrophones");
8988 AutoMutex _l(mLock);
Jasmine Chaeaa10e42021-05-11 10:11:14 +08008989 if (!isStreamInitialized()) {
Paul McLean8a661a32021-04-12 10:21:42 -06008990 return NO_INIT;
8991 }
jiabin9ff780e2018-03-19 18:19:52 -07008992 status_t status = mInput->stream->getActiveMicrophones(activeMicrophones);
8993 return status;
jiabin653cc0a2018-01-17 17:54:10 -08008994}
8995
Andy Hungee58e4a2023-07-07 13:47:37 -07008996status_t RecordThread::setPreferredMicrophoneDirection(
Paul McLean12340082019-03-19 09:35:05 -06008997 audio_microphone_direction_t direction)
Paul McLean03a6e6a2018-12-04 10:54:13 -07008998{
Paul McLean12340082019-03-19 09:35:05 -06008999 ALOGV("setPreferredMicrophoneDirection(%d)", direction);
Paul McLean03a6e6a2018-12-04 10:54:13 -07009000 AutoMutex _l(mLock);
Jasmine Chaeaa10e42021-05-11 10:11:14 +08009001 if (!isStreamInitialized()) {
Paul McLean8a661a32021-04-12 10:21:42 -06009002 return NO_INIT;
9003 }
Paul McLean12340082019-03-19 09:35:05 -06009004 return mInput->stream->setPreferredMicrophoneDirection(direction);
Paul McLean03a6e6a2018-12-04 10:54:13 -07009005}
9006
Andy Hungee58e4a2023-07-07 13:47:37 -07009007status_t RecordThread::setPreferredMicrophoneFieldDimension(float zoom)
Paul McLean03a6e6a2018-12-04 10:54:13 -07009008{
Paul McLean12340082019-03-19 09:35:05 -06009009 ALOGV("setPreferredMicrophoneFieldDimension(%f)", zoom);
Paul McLean03a6e6a2018-12-04 10:54:13 -07009010 AutoMutex _l(mLock);
Jasmine Chaeaa10e42021-05-11 10:11:14 +08009011 if (!isStreamInitialized()) {
Paul McLean8a661a32021-04-12 10:21:42 -06009012 return NO_INIT;
9013 }
Paul McLean12340082019-03-19 09:35:05 -06009014 return mInput->stream->setPreferredMicrophoneFieldDimension(zoom);
Paul McLean03a6e6a2018-12-04 10:54:13 -07009015}
9016
Andy Hungee58e4a2023-07-07 13:47:37 -07009017status_t RecordThread::shareAudioHistory(
Eric Laurentec376dc2021-04-08 20:41:22 +02009018 const std::string& sharedAudioPackageName, audio_session_t sharedSessionId,
9019 int64_t sharedAudioStartMs) {
9020 AutoMutex _l(mLock);
9021 return shareAudioHistory_l(sharedAudioPackageName, sharedSessionId, sharedAudioStartMs);
9022}
9023
Andy Hungee58e4a2023-07-07 13:47:37 -07009024status_t RecordThread::shareAudioHistory_l(
Eric Laurentec376dc2021-04-08 20:41:22 +02009025 const std::string& sharedAudioPackageName, audio_session_t sharedSessionId,
9026 int64_t sharedAudioStartMs) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009027
Eric Laurentec376dc2021-04-08 20:41:22 +02009028 if ((hasAudioSession_l(sharedSessionId) & ThreadBase::TRACK_SESSION) == 0) {
9029 return BAD_VALUE;
9030 }
Eric Laurent2407ce32021-04-26 14:56:03 +02009031
9032 if (sharedAudioStartMs < 0
9033 || sharedAudioStartMs > INT64_MAX / mSampleRate) {
Eric Laurentec376dc2021-04-08 20:41:22 +02009034 return BAD_VALUE;
9035 }
9036
Eric Laurent2407ce32021-04-26 14:56:03 +02009037 // Current implementation of the input resampling buffer wraps around indexes at 32 bit.
9038 // As we cannot detect more than one wraparound, only accept values up current write position
9039 // after one wraparound
9040 // We assume recent wraparounds on mRsmpInRear only given it is unlikely that the requesting
9041 // app waits several hours after the start time was computed.
Eric Laurent92d0a322021-07-16 15:32:33 +02009042 int64_t sharedAudioStartFrames = sharedAudioStartMs * mSampleRate / 1000;
Eric Laurent2407ce32021-04-26 14:56:03 +02009043 const int32_t sharedOffset = audio_utils::safe_sub_overflow(mRsmpInRear,
9044 (int32_t)sharedAudioStartFrames);
Eric Laurent92d0a322021-07-16 15:32:33 +02009045 // Bring the start frame position within the input buffer to match the documented
9046 // "best effort" behavior of the API.
9047 if (sharedOffset < 0) {
9048 sharedAudioStartFrames = mRsmpInRear;
Andy Hung920f6572022-10-06 12:09:49 -07009049 } else if (sharedOffset > static_cast<signed>(mRsmpInFrames)) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009050 sharedAudioStartFrames =
9051 audio_utils::safe_sub_overflow(mRsmpInRear, (int32_t)mRsmpInFrames);
Eric Laurent2407ce32021-04-26 14:56:03 +02009052 }
9053
Eric Laurentec376dc2021-04-08 20:41:22 +02009054 mSharedAudioPackageName = sharedAudioPackageName;
9055 if (mSharedAudioPackageName.empty()) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009056 resetAudioHistory_l();
Eric Laurentec376dc2021-04-08 20:41:22 +02009057 } else {
9058 mSharedAudioSessionId = sharedSessionId;
Eric Laurent2407ce32021-04-26 14:56:03 +02009059 mSharedAudioStartFrames = (int32_t)sharedAudioStartFrames;
Eric Laurentec376dc2021-04-08 20:41:22 +02009060 }
9061 return NO_ERROR;
9062}
9063
Andy Hungee58e4a2023-07-07 13:47:37 -07009064void RecordThread::resetAudioHistory_l() {
Eric Laurent92d0a322021-07-16 15:32:33 +02009065 mSharedAudioSessionId = AUDIO_SESSION_NONE;
9066 mSharedAudioStartFrames = -1;
9067 mSharedAudioPackageName = "";
9068}
9069
Andy Hungee58e4a2023-07-07 13:47:37 -07009070ThreadBase::MetadataUpdate RecordThread::updateMetadata_l()
Kevin Rocard069c2712018-03-29 19:09:14 -07009071{
Jasmine Chaeaa10e42021-05-11 10:11:14 +08009072 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
Vlad Popa7e81cea2023-01-19 16:34:16 +01009073 return {}; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -07009074 }
9075 StreamInHalInterface::SinkMetadata metadata;
Eric Laurent78b07302022-10-07 16:20:34 +02009076 auto backInserter = std::back_inserter(metadata.tracks);
Andy Hung8d31fd22023-06-26 19:20:57 -07009077 for (const sp<IAfRecordTrack>& track : mActiveTracks) {
Eric Laurent78b07302022-10-07 16:20:34 +02009078 track->copyMetadataTo(backInserter);
Kevin Rocard069c2712018-03-29 19:09:14 -07009079 }
9080 mInput->stream->updateSinkMetadata(metadata);
Vlad Popa7e81cea2023-01-19 16:34:16 +01009081 MetadataUpdate change;
9082 change.recordMetadataUpdate = metadata.tracks;
9083 return change;
Kevin Rocard069c2712018-03-29 19:09:14 -07009084}
9085
Eric Laurent81784c32012-11-19 14:55:58 -08009086// destroyTrack_l() must be called with ThreadBase::mLock held
Andy Hungee58e4a2023-07-07 13:47:37 -07009087void RecordThread::destroyTrack_l(const sp<IAfRecordTrack>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08009088{
Eric Laurentbfb1b832013-01-07 09:53:42 -08009089 track->terminate();
Andy Hung8d31fd22023-06-26 19:20:57 -07009090 track->setState(IAfTrackBase::STOPPED);
Eric Laurentec376dc2021-04-08 20:41:22 +02009091
Eric Laurent81784c32012-11-19 14:55:58 -08009092 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08009093 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08009094 removeTrack_l(track);
9095 }
9096}
9097
Andy Hungee58e4a2023-07-07 13:47:37 -07009098void RecordThread::removeTrack_l(const sp<IAfRecordTrack>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08009099{
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009100 String8 result;
9101 track->appendDump(result, false /* active */);
9102 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.string());
9103
Eric Laurent81784c32012-11-19 14:55:58 -08009104 mTracks.remove(track);
9105 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07009106 if (track->isFastTrack()) {
9107 ALOG_ASSERT(!mFastTrackAvail);
9108 mFastTrackAvail = true;
9109 }
Eric Laurent81784c32012-11-19 14:55:58 -08009110}
9111
Andy Hungee58e4a2023-07-07 13:47:37 -07009112void RecordThread::dumpInternals_l(int fd, const Vector<String16>& /* args */)
Eric Laurent81784c32012-11-19 14:55:58 -08009113{
Mikhail Naganov913d06c2016-11-01 12:49:22 -07009114 AudioStreamIn *input = mInput;
9115 audio_input_flags_t flags = input != NULL ? input->flags : AUDIO_INPUT_FLAG_NONE;
9116 dprintf(fd, " AudioStreamIn: %p flags %#x (%s)\n",
Andy Hung9b181952019-02-25 14:53:36 -08009117 input, flags, toString(flags).c_str());
Andy Hung6427e442018-08-09 12:51:02 -07009118 dprintf(fd, " Frames read: %lld\n", (long long)mFramesRead);
Eric Tan39ec8d62018-07-24 09:49:29 -07009119 if (mActiveTracks.isEmpty()) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07009120 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08009121 }
Andy Hungbfa64962017-06-12 14:43:19 -07009122
9123 if (input != nullptr) {
9124 dprintf(fd, " Hal stream dump:\n");
9125 (void)input->stream->dump(fd);
9126 }
9127
Glenn Kasten6e6704c2014-07-03 10:20:00 -07009128 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07009129 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Glenn Kasten17c9c992015-03-02 15:53:01 -08009130
Glenn Kasten2f90c512015-12-02 11:40:09 -08009131 // Make a non-atomic copy of fast capture dump state so it won't change underneath us
9132 // while we are dumping it. It may be inconsistent, but it won't mutate!
9133 // This is a large object so we place it on the heap.
9134 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
Eric Tan2942a4e2018-09-12 17:41:27 -07009135 const std::unique_ptr<FastCaptureDumpState> copy =
9136 std::make_unique<FastCaptureDumpState>(mFastCaptureDumpState);
Glenn Kasten2f90c512015-12-02 11:40:09 -08009137 copy->dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08009138}
9139
Andy Hungee58e4a2023-07-07 13:47:37 -07009140void RecordThread::dumpTracks_l(int fd, const Vector<String16>& /* args */)
Eric Laurent81784c32012-11-19 14:55:58 -08009141{
Eric Laurent81784c32012-11-19 14:55:58 -08009142 String8 result;
Marco Nelissenb2208842014-02-07 14:00:50 -08009143 size_t numtracks = mTracks.size();
9144 size_t numactive = mActiveTracks.size();
9145 size_t numactiveseen = 0;
Glenn Kastenc42e9b42016-03-21 11:35:03 -07009146 dprintf(fd, " %zu Tracks", numtracks);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009147 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08009148 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07009149 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009150 result.append(prefix);
Andy Hung000adb52018-06-01 15:43:26 -07009151 mTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08009152 for (size_t i = 0; i < numtracks ; ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07009153 sp<IAfRecordTrack> track = mTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08009154 if (track != 0) {
9155 bool active = mActiveTracks.indexOf(track) >= 0;
9156 if (active) {
9157 numactiveseen++;
9158 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009159 result.append(prefix);
9160 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08009161 }
Eric Laurent81784c32012-11-19 14:55:58 -08009162 }
Marco Nelissenb2208842014-02-07 14:00:50 -08009163 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07009164 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08009165 }
9166
Marco Nelissenb2208842014-02-07 14:00:50 -08009167 if (numactiveseen != numactive) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009168 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08009169 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009170 result.append(prefix);
Andy Hung000adb52018-06-01 15:43:26 -07009171 mActiveTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08009172 for (size_t i = 0; i < numactive; ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07009173 sp<IAfRecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08009174 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009175 result.append(prefix);
9176 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08009177 }
Glenn Kasten2b806402013-11-20 16:37:38 -08009178 }
Eric Laurent81784c32012-11-19 14:55:58 -08009179
9180 }
9181 write(fd, result.string(), result.size());
9182}
9183
Andy Hungee58e4a2023-07-07 13:47:37 -07009184void RecordThread::setRecordSilenced(audio_port_handle_t portId, bool silenced)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08009185{
9186 Mutex::Autolock _l(mLock);
9187 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07009188 sp<IAfRecordTrack> track = mTracks[i];
Eric Laurent5ada82e2019-08-29 17:53:54 -07009189 if (track != 0 && track->portId() == portId) {
Svet Ganovf4ddfef2018-01-16 07:37:58 -08009190 track->setSilenced(silenced);
9191 }
9192 }
9193}
Andy Hung73c02e42015-03-29 01:13:58 -07009194
Andy Hung8d31fd22023-06-26 19:20:57 -07009195void ResamplerBufferProvider::reset()
Andy Hung73c02e42015-03-29 01:13:58 -07009196{
Andy Hung87c693c2023-07-06 20:56:16 -07009197 const auto threadBase = mRecordTrack->thread().promote();
Andy Hungee58e4a2023-07-07 13:47:37 -07009198 auto* const recordThread = static_cast<RecordThread *>(threadBase->asIAfRecordThread().get());
Andy Hung73c02e42015-03-29 01:13:58 -07009199 mRsmpInUnrel = 0;
Eric Laurentec376dc2021-04-08 20:41:22 +02009200 const int32_t rear = recordThread->mRsmpInRear;
9201 ssize_t deltaFrames = 0;
Eric Laurent2407ce32021-04-26 14:56:03 +02009202 if (mRecordTrack->startFrames() >= 0) {
9203 int32_t startFrames = mRecordTrack->startFrames();
9204 // Accept a recent wraparound of mRsmpInRear
9205 if (startFrames <= rear) {
9206 deltaFrames = rear - startFrames;
9207 } else {
9208 deltaFrames = (int32_t)((int64_t)rear + UINT32_MAX + 1 - startFrames);
Eric Laurentec376dc2021-04-08 20:41:22 +02009209 }
Eric Laurentec376dc2021-04-08 20:41:22 +02009210 // start frame cannot be further in the past than start of resampling buffer
9211 if ((size_t) deltaFrames > recordThread->mRsmpInFrames) {
9212 deltaFrames = recordThread->mRsmpInFrames;
9213 }
9214 }
9215 mRsmpInFront = audio_utils::safe_sub_overflow(rear, static_cast<int32_t>(deltaFrames));
Andy Hung73c02e42015-03-29 01:13:58 -07009216}
9217
Andy Hung8d31fd22023-06-26 19:20:57 -07009218void ResamplerBufferProvider::sync(
Andy Hung73c02e42015-03-29 01:13:58 -07009219 size_t *framesAvailable, bool *hasOverrun)
9220{
Andy Hung87c693c2023-07-06 20:56:16 -07009221 const auto threadBase = mRecordTrack->thread().promote();
Andy Hungee58e4a2023-07-07 13:47:37 -07009222 auto* const recordThread = static_cast<RecordThread *>(threadBase->asIAfRecordThread().get());
Andy Hung73c02e42015-03-29 01:13:58 -07009223 const int32_t rear = recordThread->mRsmpInRear;
9224 const int32_t front = mRsmpInFront;
Hongwei Wang95e37682019-04-12 11:13:36 -07009225 const ssize_t filled = audio_utils::safe_sub_overflow(rear, front);
Andy Hung73c02e42015-03-29 01:13:58 -07009226
9227 size_t framesIn;
9228 bool overrun = false;
9229 if (filled < 0) {
9230 // should not happen, but treat like a massive overrun and re-sync
9231 framesIn = 0;
9232 mRsmpInFront = rear;
9233 overrun = true;
9234 } else if ((size_t) filled <= recordThread->mRsmpInFrames) {
9235 framesIn = (size_t) filled;
9236 } else {
9237 // client is not keeping up with server, but give it latest data
9238 framesIn = recordThread->mRsmpInFrames;
Hongwei Wang95e37682019-04-12 11:13:36 -07009239 mRsmpInFront = /* front = */ audio_utils::safe_sub_overflow(
9240 rear, static_cast<int32_t>(framesIn));
Andy Hung73c02e42015-03-29 01:13:58 -07009241 overrun = true;
9242 }
9243 if (framesAvailable != NULL) {
9244 *framesAvailable = framesIn;
9245 }
9246 if (hasOverrun != NULL) {
9247 *hasOverrun = overrun;
9248 }
9249}
9250
Eric Laurent81784c32012-11-19 14:55:58 -08009251// AudioBufferProvider interface
Andy Hung8d31fd22023-06-26 19:20:57 -07009252status_t ResamplerBufferProvider::getNextBuffer(
Glenn Kastend79072e2016-01-06 08:41:20 -08009253 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08009254{
Andy Hung87c693c2023-07-06 20:56:16 -07009255 const auto threadBase = mRecordTrack->thread().promote();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009256 if (threadBase == 0) {
9257 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08009258 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009259 return NOT_ENOUGH_DATA;
9260 }
Andy Hungee58e4a2023-07-07 13:47:37 -07009261 auto* const recordThread = static_cast<RecordThread *>(threadBase->asIAfRecordThread().get());
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009262 int32_t rear = recordThread->mRsmpInRear;
Andy Hung73c02e42015-03-29 01:13:58 -07009263 int32_t front = mRsmpInFront;
Hongwei Wang95e37682019-04-12 11:13:36 -07009264 ssize_t filled = audio_utils::safe_sub_overflow(rear, front);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009265 // FIXME should not be P2 (don't want to increase latency)
9266 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08009267 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07009268 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009269
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009270 front &= recordThread->mRsmpInFramesP2 - 1;
9271 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07009272 if (part1 > (size_t) filled) {
9273 part1 = filled;
9274 }
9275 size_t ask = buffer->frameCount;
9276 ALOG_ASSERT(ask > 0);
9277 if (part1 > ask) {
9278 part1 = ask;
9279 }
9280 if (part1 == 0) {
Andy Hung73c02e42015-03-29 01:13:58 -07009281 // out of data is fine since the resampler will return a short-count.
Glenn Kasten85948432013-08-19 12:09:05 -07009282 buffer->raw = NULL;
9283 buffer->frameCount = 0;
Andy Hung73c02e42015-03-29 01:13:58 -07009284 mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07009285 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08009286 }
9287
Andy Hung57446612015-04-19 23:56:46 -07009288 buffer->raw = (uint8_t*)recordThread->mRsmpInBuffer + front * recordThread->mFrameSize;
Glenn Kasten85948432013-08-19 12:09:05 -07009289 buffer->frameCount = part1;
Andy Hung73c02e42015-03-29 01:13:58 -07009290 mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08009291 return NO_ERROR;
9292}
9293
9294// AudioBufferProvider interface
Andy Hung8d31fd22023-06-26 19:20:57 -07009295void ResamplerBufferProvider::releaseBuffer(
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009296 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08009297{
Hongwei Wang95e37682019-04-12 11:13:36 -07009298 int32_t stepCount = static_cast<int32_t>(buffer->frameCount);
Glenn Kasten85948432013-08-19 12:09:05 -07009299 if (stepCount == 0) {
9300 return;
9301 }
Eric Laurent1e28aaa2023-04-16 19:34:23 +02009302 ALOG_ASSERT(stepCount <= (int32_t)mRsmpInUnrel);
Andy Hung73c02e42015-03-29 01:13:58 -07009303 mRsmpInUnrel -= stepCount;
Hongwei Wang95e37682019-04-12 11:13:36 -07009304 mRsmpInFront = audio_utils::safe_add_overflow(mRsmpInFront, stepCount);
Glenn Kasten85948432013-08-19 12:09:05 -07009305 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08009306 buffer->frameCount = 0;
9307}
9308
Andy Hungee58e4a2023-07-07 13:47:37 -07009309void RecordThread::checkBtNrec()
Eric Laurentd8365c52017-07-16 15:27:05 -07009310{
9311 Mutex::Autolock _l(mLock);
9312 checkBtNrec_l();
9313}
9314
Andy Hungee58e4a2023-07-07 13:47:37 -07009315void RecordThread::checkBtNrec_l()
Eric Laurentd8365c52017-07-16 15:27:05 -07009316{
9317 // disable AEC and NS if the device is a BT SCO headset supporting those
9318 // pre processings
jiabinc52b1ff2019-10-31 17:20:42 -07009319 bool suspend = audio_is_bluetooth_sco_device(inDeviceType()) &&
Andy Hung583043b2023-07-17 17:05:00 -07009320 mAfThreadCallback->btNrecIsOff();
Eric Laurentd8365c52017-07-16 15:27:05 -07009321 if (mBtNrecSuspended.exchange(suspend) != suspend) {
9322 for (size_t i = 0; i < mEffectChains.size(); i++) {
9323 setEffectSuspended_l(FX_IID_AEC, suspend, mEffectChains[i]->sessionId());
9324 setEffectSuspended_l(FX_IID_NS, suspend, mEffectChains[i]->sessionId());
9325 }
9326 }
9327}
9328
Andy Hung97a893e2015-03-29 01:03:07 -07009329
Andy Hungee58e4a2023-07-07 13:47:37 -07009330bool RecordThread::checkForNewParameter_l(const String8& keyValuePair,
Eric Laurent10351942014-05-08 18:49:52 -07009331 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08009332{
9333 bool reconfig = false;
9334
Eric Laurent10351942014-05-08 18:49:52 -07009335 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08009336
Eric Laurent10351942014-05-08 18:49:52 -07009337 audio_format_t reqFormat = mFormat;
9338 uint32_t samplingRate = mSampleRate;
Glenn Kastene1635ec2015-06-08 15:46:49 -07009339 // 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 +08009340 [[maybe_unused]] audio_channel_mask_t channelMask =
9341 audio_channel_in_mask_from_count(mChannelCount);
Eric Laurent10351942014-05-08 18:49:52 -07009342
9343 AudioParameter param = AudioParameter(keyValuePair);
9344 int value;
Haynes Mathew George9ce67b52015-09-30 11:40:47 -07009345
9346 // scope for AutoPark extends to end of method
9347 AutoPark<FastCapture> park(mFastCapture);
9348
Eric Laurent10351942014-05-08 18:49:52 -07009349 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
9350 // channel count change can be requested. Do we mandate the first client defines the
9351 // HAL sampling rate and channel count or do we allow changes on the fly?
9352 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
9353 samplingRate = value;
9354 reconfig = true;
9355 }
9356 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung97a893e2015-03-29 01:03:07 -07009357 if (!audio_is_linear_pcm((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07009358 status = BAD_VALUE;
9359 } else {
9360 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08009361 reconfig = true;
9362 }
Eric Laurent10351942014-05-08 18:49:52 -07009363 }
9364 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
9365 audio_channel_mask_t mask = (audio_channel_mask_t) value;
Andy Hungd330ee42015-04-20 13:23:41 -07009366 if (!audio_is_input_channel(mask) ||
Andy Hung936845a2021-06-08 00:09:06 -07009367 audio_channel_count_from_in_mask(mask) > FCC_LIMIT) {
Eric Laurent10351942014-05-08 18:49:52 -07009368 status = BAD_VALUE;
9369 } else {
9370 channelMask = mask;
9371 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08009372 }
Eric Laurent10351942014-05-08 18:49:52 -07009373 }
9374 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
9375 // do not accept frame count changes if tracks are open as the track buffer
9376 // size depends on frame count and correct behavior would not be guaranteed
9377 // if frame count is changed after track creation
9378 if (mActiveTracks.size() > 0) {
9379 status = INVALID_OPERATION;
9380 } else {
9381 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08009382 }
Eric Laurent10351942014-05-08 18:49:52 -07009383 }
9384 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07009385 LOG_FATAL("Should not set routing device in RecordThread");
Eric Laurent10351942014-05-08 18:49:52 -07009386 }
9387 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
9388 mAudioSource != (audio_source_t)value) {
jiabinc52b1ff2019-10-31 17:20:42 -07009389 LOG_FATAL("Should not set audio source in RecordThread");
Eric Laurent10351942014-05-08 18:49:52 -07009390 }
Glenn Kastene198c362013-08-13 09:13:36 -07009391
Eric Laurent10351942014-05-08 18:49:52 -07009392 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009393 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07009394 if (status == INVALID_OPERATION) {
9395 inputStandBy();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009396 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07009397 }
9398 if (reconfig) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009399 if (status == BAD_VALUE) {
Mikhail Naganov560637e2021-03-31 22:40:13 +00009400 audio_config_base_t config = AUDIO_CONFIG_BASE_INITIALIZER;
9401 if (mInput->stream->getAudioProperties(&config) == OK &&
9402 audio_is_linear_pcm(config.format) && audio_is_linear_pcm(reqFormat) &&
9403 config.sample_rate <= (AUDIO_RESAMPLER_DOWN_RATIO_MAX * samplingRate) &&
Andy Hung936845a2021-06-08 00:09:06 -07009404 audio_channel_count_from_in_mask(config.channel_mask) <= FCC_LIMIT) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009405 status = NO_ERROR;
9406 }
Eric Laurent81784c32012-11-19 14:55:58 -08009407 }
Eric Laurent10351942014-05-08 18:49:52 -07009408 if (status == NO_ERROR) {
9409 readInputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07009410 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08009411 }
9412 }
Eric Laurent81784c32012-11-19 14:55:58 -08009413 }
Eric Laurent10351942014-05-08 18:49:52 -07009414
Eric Laurent81784c32012-11-19 14:55:58 -08009415 return reconfig;
9416}
9417
Andy Hungee58e4a2023-07-07 13:47:37 -07009418String8 RecordThread::getParameters(const String8& keys)
Eric Laurent81784c32012-11-19 14:55:58 -08009419{
Eric Laurent81784c32012-11-19 14:55:58 -08009420 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009421 if (initCheck() == NO_ERROR) {
9422 String8 out_s8;
9423 if (mInput->stream->getParameters(keys, &out_s8) == OK) {
9424 return out_s8;
9425 }
Eric Laurent81784c32012-11-19 14:55:58 -08009426 }
Andy Hung920f6572022-10-06 12:09:49 -07009427 return {};
Eric Laurent81784c32012-11-19 14:55:58 -08009428}
9429
Andy Hungee58e4a2023-07-07 13:47:37 -07009430void RecordThread::ioConfigChanged(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -07009431 audio_port_handle_t portId) {
Mikhail Naganov88536df2021-07-26 17:30:29 -07009432 sp<AudioIoDescriptor> desc;
Eric Laurent81784c32012-11-19 14:55:58 -08009433 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07009434 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07009435 case AUDIO_INPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07009436 case AUDIO_INPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07009437 desc = sp<AudioIoDescriptor>::make(mId, mPatch, true /*isInput*/,
9438 mSampleRate, mFormat, mChannelMask, mFrameCount, mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08009439 break;
Eric Laurent09f1ed22019-04-24 17:45:17 -07009440 case AUDIO_CLIENT_STARTED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07009441 desc = sp<AudioIoDescriptor>::make(mId, mPatch, portId);
Eric Laurent09f1ed22019-04-24 17:45:17 -07009442 break;
Eric Laurent73e26b62015-04-27 16:55:58 -07009443 case AUDIO_INPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08009444 default:
Mikhail Naganov88536df2021-07-26 17:30:29 -07009445 desc = sp<AudioIoDescriptor>::make(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08009446 break;
9447 }
Andy Hung583043b2023-07-17 17:05:00 -07009448 mAfThreadCallback->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08009449}
9450
Andy Hungee58e4a2023-07-07 13:47:37 -07009451void RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08009452{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009453 status_t result = mInput->stream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
9454 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
Andy Hung463be252014-07-10 16:56:07 -07009455 mFormat = mHALFormat;
Mikhail Naganovce9f2652018-07-16 11:09:24 -07009456 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
9457 if (audio_is_linear_pcm(mFormat)) {
Andy Hung936845a2021-06-08 00:09:06 -07009458 LOG_ALWAYS_FATAL_IF(mChannelCount > FCC_LIMIT, "HAL channel count %d > %d",
9459 mChannelCount, FCC_LIMIT);
Mikhail Naganovce9f2652018-07-16 11:09:24 -07009460 } else {
Andy Hung936845a2021-06-08 00:09:06 -07009461 // Can have more that FCC_LIMIT channels in encoded streams.
Mikhail Naganovce9f2652018-07-16 11:09:24 -07009462 ALOGI("HAL format %#x is not linear pcm", mFormat);
9463 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009464 result = mInput->stream->getFrameSize(&mFrameSize);
9465 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
Hayden Gomes1a89ab32020-06-12 11:05:47 -07009466 LOG_ALWAYS_FATAL_IF(mFrameSize <= 0, "Error frame size was %zu but must be greater than zero",
9467 mFrameSize);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009468 result = mInput->stream->getBufferSize(&mBufferSize);
9469 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
Glenn Kasten548efc92012-11-29 08:48:51 -08009470 mFrameCount = mBufferSize / mFrameSize;
Hayden Gomes1a89ab32020-06-12 11:05:47 -07009471 ALOGV("%p RecordThread params: mChannelCount=%u, mFormat=%#x, mFrameSize=%zu, "
9472 "mBufferSize=%zu, mFrameCount=%zu",
9473 this, mChannelCount, mFormat, mFrameSize, mBufferSize, mFrameCount);
Glenn Kasten49d00ad2014-07-21 11:22:03 -07009474
Eric Laurentec376dc2021-04-08 20:41:22 +02009475 // mRsmpInFrames must be 0 before calling resizeInputBuffer_l for the first time
9476 mRsmpInFrames = 0;
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009477 resizeInputBuffer_l(0 /*maxSharedAudioHistoryMs*/);
Eric Laurent81784c32012-11-19 14:55:58 -08009478
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08009479 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
9480 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Andy Hungea840382020-05-05 21:50:17 -07009481
9482 audio_input_flags_t flags = mInput->flags;
9483 mediametrics::LogItem item(mThreadMetrics.getMetricsId());
9484 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
9485 .set(AMEDIAMETRICS_PROP_ENCODING, formatToString(mFormat).c_str())
9486 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
9487 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
9488 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
9489 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
9490 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mFrameCount)
9491 .record();
Eric Laurent81784c32012-11-19 14:55:58 -08009492}
9493
Andy Hungee58e4a2023-07-07 13:47:37 -07009494uint32_t RecordThread::getInputFramesLost() const
Eric Laurent81784c32012-11-19 14:55:58 -08009495{
9496 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009497 uint32_t result;
9498 if (initCheck() == NO_ERROR && mInput->stream->getInputFramesLost(&result) == OK) {
9499 return result;
Eric Laurent81784c32012-11-19 14:55:58 -08009500 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009501 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08009502}
9503
Andy Hungee58e4a2023-07-07 13:47:37 -07009504KeyedVector<audio_session_t, bool> RecordThread::sessionIds() const
Eric Laurent81784c32012-11-19 14:55:58 -08009505{
Glenn Kastend848eb42016-03-08 13:42:11 -08009506 KeyedVector<audio_session_t, bool> ids;
Eric Laurent81784c32012-11-19 14:55:58 -08009507 Mutex::Autolock _l(mLock);
9508 for (size_t j = 0; j < mTracks.size(); ++j) {
Andy Hung8d31fd22023-06-26 19:20:57 -07009509 sp<IAfRecordTrack> track = mTracks[j];
Glenn Kastend848eb42016-03-08 13:42:11 -08009510 audio_session_t sessionId = track->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08009511 if (ids.indexOfKey(sessionId) < 0) {
9512 ids.add(sessionId, true);
9513 }
9514 }
9515 return ids;
9516}
9517
Andy Hungee58e4a2023-07-07 13:47:37 -07009518AudioStreamIn* RecordThread::clearInput()
Eric Laurent81784c32012-11-19 14:55:58 -08009519{
9520 Mutex::Autolock _l(mLock);
9521 AudioStreamIn *input = mInput;
9522 mInput = NULL;
9523 return input;
9524}
9525
9526// this method must always be called either with ThreadBase mLock held or inside the thread loop
Andy Hungee58e4a2023-07-07 13:47:37 -07009527sp<StreamHalInterface> RecordThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08009528{
9529 if (mInput == NULL) {
9530 return NULL;
9531 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009532 return mInput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08009533}
9534
Andy Hungee58e4a2023-07-07 13:47:37 -07009535status_t RecordThread::addEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08009536{
Eric Laurent81784c32012-11-19 14:55:58 -08009537 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurentaaa44472014-09-12 17:41:50 -07009538 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08009539 chain->setInBuffer(NULL);
9540 chain->setOutBuffer(NULL);
9541
9542 checkSuspendOnAddEffectChain_l(chain);
9543
Eric Laurent1b928682014-10-02 19:41:47 -07009544 // make sure enabled pre processing effects state is communicated to the HAL as we
9545 // just moved them to a new input stream.
9546 chain->syncHalEffectsState();
9547
Eric Laurent81784c32012-11-19 14:55:58 -08009548 mEffectChains.add(chain);
9549
9550 return NO_ERROR;
9551}
9552
Andy Hungee58e4a2023-07-07 13:47:37 -07009553size_t RecordThread::removeEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08009554{
9555 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
Eric Laurentb20cf7d2019-04-05 19:37:34 -07009556
9557 for (size_t i = 0; i < mEffectChains.size(); i++) {
9558 if (chain == mEffectChains[i]) {
9559 mEffectChains.removeAt(i);
9560 break;
9561 }
Eric Laurent81784c32012-11-19 14:55:58 -08009562 }
Eric Laurentb20cf7d2019-04-05 19:37:34 -07009563 return mEffectChains.size();
Eric Laurent81784c32012-11-19 14:55:58 -08009564}
9565
Andy Hungee58e4a2023-07-07 13:47:37 -07009566status_t RecordThread::createAudioPatch_l(const struct audio_patch* patch,
Eric Laurent1c333e22014-05-20 10:48:17 -07009567 audio_patch_handle_t *handle)
9568{
9569 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07009570
9571 // store new device and send to effects
jiabinc52b1ff2019-10-31 17:20:42 -07009572 mInDeviceTypeAddr.mType = patch->sources[0].ext.device.type;
jiabin0a488932020-08-07 17:32:40 -07009573 mInDeviceTypeAddr.setAddress(patch->sources[0].ext.device.address);
François Gaffie0c280aa2018-07-25 10:02:15 +02009574 audio_port_handle_t deviceId = patch->sources[0].id;
Eric Laurent054d9d32015-04-24 08:48:48 -07009575 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08009576 mEffectChains[i]->setInputDevice_l(inDeviceTypeAddr());
Eric Laurent054d9d32015-04-24 08:48:48 -07009577 }
9578
Eric Laurentd8365c52017-07-16 15:27:05 -07009579 checkBtNrec_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07009580
9581 // store new source and send to effects
9582 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
9583 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent1c333e22014-05-20 10:48:17 -07009584 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent054d9d32015-04-24 08:48:48 -07009585 mEffectChains[i]->setAudioSource_l(mAudioSource);
Eric Laurent1c333e22014-05-20 10:48:17 -07009586 }
Eric Laurent054d9d32015-04-24 08:48:48 -07009587 }
Eric Laurent1c333e22014-05-20 10:48:17 -07009588
Mikhail Naganov9ee05402016-10-13 15:58:17 -07009589 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07009590 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
9591 status = hwDevice->createAudioPatch(patch->num_sources,
9592 patch->sources,
9593 patch->num_sinks,
9594 patch->sinks,
9595 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07009596 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08009597 status = mInput->stream->legacyCreateAudioPatch(patch->sources[0],
9598 patch->sinks[0].ext.mix.usecase.source,
9599 patch->sources[0].ext.device.type);
Eric Laurent054d9d32015-04-24 08:48:48 -07009600 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07009601 }
Eric Laurent054d9d32015-04-24 08:48:48 -07009602
jiabinc52b1ff2019-10-31 17:20:42 -07009603 if ((mPatch.num_sources == 0) || (mPatch.sources[0].id != deviceId)) {
Eric Laurente8726fe2015-06-26 09:39:24 -07009604 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
jiabinc52b1ff2019-10-31 17:20:42 -07009605 mPatch = *patch;
Eric Laurente8726fe2015-06-26 09:39:24 -07009606 }
Eric Laurent296fb132015-05-01 11:38:42 -07009607
Andy Hungc2b11cb2020-04-22 09:04:01 -07009608 const std::string pathSourcesAsString = patchSourcesToString(patch);
Andy Hungcf10d742020-04-28 15:38:24 -07009609 mThreadMetrics.logEndInterval();
Andy Hungea840382020-05-05 21:50:17 -07009610 mThreadMetrics.logCreatePatch(pathSourcesAsString, /* outDevices */ {});
Andy Hungcf10d742020-04-28 15:38:24 -07009611 mThreadMetrics.logBeginInterval();
Andy Hungc2b11cb2020-04-22 09:04:01 -07009612 // also dispatch to active AudioRecords
9613 for (const auto &track : mActiveTracks) {
9614 track->logEndInterval();
9615 track->logBeginInterval(pathSourcesAsString);
9616 }
Eric Laurentdda206a2022-07-08 17:28:35 +02009617 // Force meteadata update after a route change
9618 mActiveTracks.setHasChanged();
9619
Eric Laurent1c333e22014-05-20 10:48:17 -07009620 return status;
9621}
9622
Andy Hungee58e4a2023-07-07 13:47:37 -07009623status_t RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
Eric Laurent1c333e22014-05-20 10:48:17 -07009624{
9625 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07009626
jiabinc52b1ff2019-10-31 17:20:42 -07009627 mPatch = audio_patch{};
9628 mInDeviceTypeAddr.reset();
Eric Laurent054d9d32015-04-24 08:48:48 -07009629
Mikhail Naganov9ee05402016-10-13 15:58:17 -07009630 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07009631 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
9632 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07009633 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08009634 status = mInput->stream->legacyReleaseAudioPatch();
Eric Laurent1c333e22014-05-20 10:48:17 -07009635 }
Eric Laurentdda206a2022-07-08 17:28:35 +02009636 // Force meteadata update after a route change
9637 mActiveTracks.setHasChanged();
9638
Eric Laurent1c333e22014-05-20 10:48:17 -07009639 return status;
9640}
9641
Andy Hungee58e4a2023-07-07 13:47:37 -07009642void RecordThread::updateOutDevices(const DeviceDescriptorBaseVector& outDevices)
jiabinc52b1ff2019-10-31 17:20:42 -07009643{
wendy lin56aa82b2020-12-02 15:19:55 +08009644 Mutex::Autolock _l(mLock);
jiabinc52b1ff2019-10-31 17:20:42 -07009645 mOutDevices = outDevices;
9646 mOutDeviceTypeAddrs = deviceTypeAddrsFromDescriptors(mOutDevices);
9647 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08009648 mEffectChains[i]->setDevices_l(outDeviceTypeAddrs());
jiabinc52b1ff2019-10-31 17:20:42 -07009649 }
9650}
9651
Andy Hungee58e4a2023-07-07 13:47:37 -07009652int32_t RecordThread::getOldestFront_l()
Eric Laurentec376dc2021-04-08 20:41:22 +02009653{
9654 if (mTracks.size() == 0) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009655 return mRsmpInRear;
Eric Laurentec376dc2021-04-08 20:41:22 +02009656 }
Eric Laurent2407ce32021-04-26 14:56:03 +02009657 int32_t oldestFront = mRsmpInRear;
9658 int32_t maxFilled = 0;
Eric Laurentec376dc2021-04-08 20:41:22 +02009659 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07009660 int32_t front = mTracks[i]->resamplerBufferProvider()->getFront();
Eric Laurent2407ce32021-04-26 14:56:03 +02009661 int32_t filled;
Eric Laurent92d0a322021-07-16 15:32:33 +02009662 (void)__builtin_sub_overflow(mRsmpInRear, front, &filled);
Eric Laurent2407ce32021-04-26 14:56:03 +02009663 if (filled > maxFilled) {
9664 oldestFront = front;
9665 maxFilled = filled;
9666 }
Eric Laurentec376dc2021-04-08 20:41:22 +02009667 }
Andy Hung920f6572022-10-06 12:09:49 -07009668 if (maxFilled > static_cast<signed>(mRsmpInFrames)) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009669 (void)__builtin_sub_overflow(mRsmpInRear, mRsmpInFrames, &oldestFront);
9670 }
Eric Laurent2407ce32021-04-26 14:56:03 +02009671 return oldestFront;
Eric Laurentec376dc2021-04-08 20:41:22 +02009672}
9673
Andy Hungee58e4a2023-07-07 13:47:37 -07009674void RecordThread::updateFronts_l(int32_t offset)
Eric Laurentec376dc2021-04-08 20:41:22 +02009675{
9676 if (offset == 0) {
9677 return;
9678 }
9679 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07009680 int32_t front = mTracks[i]->resamplerBufferProvider()->getFront();
Eric Laurentec376dc2021-04-08 20:41:22 +02009681 front = audio_utils::safe_sub_overflow(front, offset);
Andy Hung8d31fd22023-06-26 19:20:57 -07009682 mTracks[i]->resamplerBufferProvider()->setFront(front);
Eric Laurentec376dc2021-04-08 20:41:22 +02009683 }
9684}
9685
Andy Hungee58e4a2023-07-07 13:47:37 -07009686void RecordThread::resizeInputBuffer_l(int32_t maxSharedAudioHistoryMs)
Eric Laurentec376dc2021-04-08 20:41:22 +02009687{
9688 // This is the formula for calculating the temporary buffer size.
9689 // With 7 HAL buffers, we can guarantee ability to down-sample the input by ratio of 6:1 to
9690 // 1 full output buffer, regardless of the alignment of the available input.
9691 // The value is somewhat arbitrary, and could probably be even larger.
9692 // A larger value should allow more old data to be read after a track calls start(),
9693 // without increasing latency.
9694 //
9695 // Note this is independent of the maximum downsampling ratio permitted for capture.
9696 size_t minRsmpInFrames = mFrameCount * 7;
9697
9698 // maxSharedAudioHistoryMs != 0 indicates a request to possibly make some part of the audio
9699 // capture history available to another client using the same session ID:
9700 // dimension the resampler input buffer accordingly.
9701
9702 // Get oldest client read position: getOldestFront_l() must be called before altering
9703 // mRsmpInRear, or mRsmpInFrames
9704 int32_t previousFront = getOldestFront_l();
9705 size_t previousRsmpInFramesP2 = mRsmpInFramesP2;
9706 int32_t previousRear = mRsmpInRear;
9707 mRsmpInRear = 0;
9708
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009709 ALOG_ASSERT(maxSharedAudioHistoryMs >= 0
Andy Hungee58e4a2023-07-07 13:47:37 -07009710 && maxSharedAudioHistoryMs <= kMaxSharedAudioHistoryMs,
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009711 "resizeInputBuffer_l() called with invalid max shared history %d",
9712 maxSharedAudioHistoryMs);
Eric Laurentec376dc2021-04-08 20:41:22 +02009713 if (maxSharedAudioHistoryMs != 0) {
9714 // resizeInputBuffer_l should never be called with a non zero shared history if the
9715 // buffer was not already allocated
9716 ALOG_ASSERT(mRsmpInBuffer != nullptr && mRsmpInFrames != 0,
9717 "resizeInputBuffer_l() called with shared history and unallocated buffer");
9718 size_t rsmpInFrames = (size_t)maxSharedAudioHistoryMs * mSampleRate / 1000;
9719 // never reduce resampler input buffer size
Eric Laurent92d0a322021-07-16 15:32:33 +02009720 if (rsmpInFrames <= mRsmpInFrames) {
Eric Laurentec376dc2021-04-08 20:41:22 +02009721 return;
9722 }
9723 mRsmpInFrames = rsmpInFrames;
9724 }
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009725 mMaxSharedAudioHistoryMs = maxSharedAudioHistoryMs;
Eric Laurentec376dc2021-04-08 20:41:22 +02009726 // Note: mRsmpInFrames is 0 when called with maxSharedAudioHistoryMs equals to 0 so it is always
9727 // initialized
9728 if (mRsmpInFrames < minRsmpInFrames) {
9729 mRsmpInFrames = minRsmpInFrames;
9730 }
9731 mRsmpInFramesP2 = roundup(mRsmpInFrames);
9732
9733 // TODO optimize audio capture buffer sizes ...
9734 // Here we calculate the size of the sliding buffer used as a source
9735 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
9736 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
9737 // be better to have it derived from the pipe depth in the long term.
9738 // The current value is higher than necessary. However it should not add to latency.
9739
9740 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
9741 mRsmpInFramesOA = mRsmpInFramesP2 + mFrameCount - 1;
9742
9743 void *rsmpInBuffer;
9744 (void)posix_memalign(&rsmpInBuffer, 32, mRsmpInFramesOA * mFrameSize);
9745 // if posix_memalign fails, will segv here.
9746 memset(rsmpInBuffer, 0, mRsmpInFramesOA * mFrameSize);
9747
9748 // Copy audio history if any from old buffer before freeing it
9749 if (previousRear != 0) {
9750 ALOG_ASSERT(mRsmpInBuffer != nullptr,
9751 "resizeInputBuffer_l() called with null buffer but frames already read from HAL");
9752
9753 ssize_t unread = audio_utils::safe_sub_overflow(previousRear, previousFront);
9754 previousFront &= previousRsmpInFramesP2 - 1;
9755 size_t part1 = previousRsmpInFramesP2 - previousFront;
9756 if (part1 > (size_t) unread) {
9757 part1 = unread;
9758 }
9759 if (part1 != 0) {
9760 memcpy(rsmpInBuffer, (const uint8_t*)mRsmpInBuffer + previousFront * mFrameSize,
9761 part1 * mFrameSize);
9762 mRsmpInRear = part1;
9763 part1 = unread - part1;
9764 if (part1 != 0) {
9765 memcpy((uint8_t*)rsmpInBuffer + mRsmpInRear * mFrameSize,
9766 (const uint8_t*)mRsmpInBuffer, part1 * mFrameSize);
9767 mRsmpInRear += part1;
9768 }
9769 }
9770 // Update front for all clients according to new rear
9771 updateFronts_l(audio_utils::safe_sub_overflow(previousRear, mRsmpInRear));
9772 } else {
9773 mRsmpInRear = 0;
9774 }
9775 free(mRsmpInBuffer);
9776 mRsmpInBuffer = rsmpInBuffer;
9777}
9778
Andy Hungee58e4a2023-07-07 13:47:37 -07009779void RecordThread::addPatchTrack(const sp<IAfPatchRecord>& record)
Eric Laurent83b88082014-06-20 18:31:16 -07009780{
9781 Mutex::Autolock _l(mLock);
9782 mTracks.add(record);
Mikhail Naganov2534b382019-09-25 13:05:02 -07009783 if (record->getSource()) {
9784 mSource = record->getSource();
9785 }
Eric Laurent83b88082014-06-20 18:31:16 -07009786}
9787
Andy Hungee58e4a2023-07-07 13:47:37 -07009788void RecordThread::deletePatchTrack(const sp<IAfPatchRecord>& record)
Eric Laurent83b88082014-06-20 18:31:16 -07009789{
9790 Mutex::Autolock _l(mLock);
Mikhail Naganov2534b382019-09-25 13:05:02 -07009791 if (mSource == record->getSource()) {
9792 mSource = mInput;
9793 }
Eric Laurent83b88082014-06-20 18:31:16 -07009794 destroyTrack_l(record);
9795}
9796
Andy Hungee58e4a2023-07-07 13:47:37 -07009797void RecordThread::toAudioPortConfig(struct audio_port_config* config)
Eric Laurent83b88082014-06-20 18:31:16 -07009798{
Mikhail Naganovdc769682018-05-04 15:34:08 -07009799 ThreadBase::toAudioPortConfig(config);
Eric Laurent83b88082014-06-20 18:31:16 -07009800 config->role = AUDIO_PORT_ROLE_SINK;
9801 config->ext.mix.hw_module = mInput->audioHwDev->handle();
9802 config->ext.mix.usecase.source = mAudioSource;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07009803 if (mInput && mInput->flags != AUDIO_INPUT_FLAG_NONE) {
9804 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
9805 config->flags.input = mInput->flags;
9806 }
Eric Laurent83b88082014-06-20 18:31:16 -07009807}
Eric Laurent1c333e22014-05-20 10:48:17 -07009808
Eric Laurent6acd1d42017-01-04 14:23:29 -08009809// ----------------------------------------------------------------------------
9810// Mmap
9811// ----------------------------------------------------------------------------
9812
Andy Hung7aa7d102023-07-07 15:58:48 -07009813// Mmap stream control interface implementation. Each MmapThreadHandle controls one
9814// MmapPlaybackThread or MmapCaptureThread instance.
9815class MmapThreadHandle : public MmapStreamInterface {
9816public:
9817 explicit MmapThreadHandle(const sp<IAfMmapThread>& thread);
9818 ~MmapThreadHandle() override;
9819
9820 // MmapStreamInterface virtuals
9821 status_t createMmapBuffer(int32_t minSizeFrames,
9822 struct audio_mmap_buffer_info* info) final;
9823 status_t getMmapPosition(struct audio_mmap_position* position) final;
9824 status_t getExternalPosition(uint64_t* position, int64_t* timeNanos) final;
9825 status_t start(const AudioClient& client,
9826 const audio_attributes_t* attr, audio_port_handle_t* handle) final;
9827 status_t stop(audio_port_handle_t handle) final;
9828 status_t standby() final;
9829 status_t reportData(const void* buffer, size_t frameCount) final;
9830private:
9831 const sp<IAfMmapThread> mThread;
9832};
9833
9834/* static */
9835sp<MmapStreamInterface> IAfMmapThread::createMmapStreamInterfaceAdapter(
9836 const sp<IAfMmapThread>& mmapThread) {
9837 return sp<MmapThreadHandle>::make(mmapThread);
9838}
9839
9840MmapThreadHandle::MmapThreadHandle(const sp<IAfMmapThread>& thread)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009841 : mThread(thread)
9842{
Phil Burk9fabbf82017-08-03 12:02:00 -07009843 assert(thread != 0); // thread must start non-null and stay non-null
Eric Laurent6acd1d42017-01-04 14:23:29 -08009844}
9845
Andy Hung7aa7d102023-07-07 15:58:48 -07009846// MmapStreamInterface could be directly implemented by MmapThread excepting this
9847// special handling on adapter dtor.
9848MmapThreadHandle::~MmapThreadHandle()
Eric Laurent6acd1d42017-01-04 14:23:29 -08009849{
Phil Burk9fabbf82017-08-03 12:02:00 -07009850 mThread->disconnect();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009851}
9852
Andy Hung7aa7d102023-07-07 15:58:48 -07009853status_t MmapThreadHandle::createMmapBuffer(int32_t minSizeFrames,
Eric Laurent6acd1d42017-01-04 14:23:29 -08009854 struct audio_mmap_buffer_info *info)
9855{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009856 return mThread->createMmapBuffer(minSizeFrames, info);
9857}
9858
Andy Hung7aa7d102023-07-07 15:58:48 -07009859status_t MmapThreadHandle::getMmapPosition(struct audio_mmap_position* position)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009860{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009861 return mThread->getMmapPosition(position);
9862}
9863
Andy Hung7aa7d102023-07-07 15:58:48 -07009864status_t MmapThreadHandle::getExternalPosition(uint64_t* position,
jiabinb7d8c5a2020-08-26 17:24:52 -07009865 int64_t *timeNanos) {
9866 return mThread->getExternalPosition(position, timeNanos);
9867}
9868
Andy Hung7aa7d102023-07-07 15:58:48 -07009869status_t MmapThreadHandle::start(const AudioClient& client,
jiabind1f1cb62020-03-24 11:57:57 -07009870 const audio_attributes_t *attr, audio_port_handle_t *handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009871{
jiabind1f1cb62020-03-24 11:57:57 -07009872 return mThread->start(client, attr, handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009873}
9874
Andy Hung7aa7d102023-07-07 15:58:48 -07009875status_t MmapThreadHandle::stop(audio_port_handle_t handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009876{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009877 return mThread->stop(handle);
9878}
9879
Andy Hung7aa7d102023-07-07 15:58:48 -07009880status_t MmapThreadHandle::standby()
Eric Laurent18b57012017-02-13 16:23:52 -08009881{
Eric Laurent18b57012017-02-13 16:23:52 -08009882 return mThread->standby();
9883}
9884
Andy Hung7aa7d102023-07-07 15:58:48 -07009885status_t MmapThreadHandle::reportData(const void* buffer, size_t frameCount)
9886{
jiabinfc791ee2023-02-15 19:43:40 +00009887 return mThread->reportData(buffer, frameCount);
9888}
9889
Eric Laurent6acd1d42017-01-04 14:23:29 -08009890
Andy Hungee58e4a2023-07-07 13:47:37 -07009891MmapThread::MmapThread(
Andy Hung583043b2023-07-17 17:05:00 -07009892 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
Andy Hung920f6572022-10-06 12:09:49 -07009893 AudioHwDevice *hwDev, const sp<StreamHalInterface>& stream, bool systemReady, bool isOut)
Andy Hung583043b2023-07-17 17:05:00 -07009894 : ThreadBase(afThreadCallback, id, (isOut ? MMAP_PLAYBACK : MMAP_CAPTURE), systemReady, isOut),
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009895 mSessionId(AUDIO_SESSION_NONE),
François Gaffie0c280aa2018-07-25 10:02:15 +02009896 mPortId(AUDIO_PORT_HANDLE_NONE),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009897 mHalStream(stream), mHalDevice(hwDev->hwDevice()), mAudioHwDev(hwDev),
Eric Laurent67f97292018-04-20 18:05:41 -07009898 mActiveTracks(&this->mLocalLog),
9899 mHalVolFloat(-1.0f), // Initialize to illegal value so it always gets set properly later.
9900 mNoCallbackWarningCount(0)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009901{
Eric Laurent18b57012017-02-13 16:23:52 -08009902 mStandby = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009903 readHalParameters_l();
9904}
9905
Andy Hungee58e4a2023-07-07 13:47:37 -07009906void MmapThread::onFirstRef()
Eric Laurent6acd1d42017-01-04 14:23:29 -08009907{
9908 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
9909}
9910
Andy Hungee58e4a2023-07-07 13:47:37 -07009911void MmapThread::disconnect()
Eric Laurent6acd1d42017-01-04 14:23:29 -08009912{
Andy Hung8d31fd22023-06-26 19:20:57 -07009913 ActiveTracks<IAfMmapTrack> activeTracks;
Eric Laurent331679c2018-04-16 17:03:16 -07009914 {
9915 Mutex::Autolock _l(mLock);
Andy Hung8d31fd22023-06-26 19:20:57 -07009916 for (const sp<IAfMmapTrack>& t : mActiveTracks) {
Eric Laurent331679c2018-04-16 17:03:16 -07009917 activeTracks.add(t);
9918 }
9919 }
Andy Hung8d31fd22023-06-26 19:20:57 -07009920 for (const sp<IAfMmapTrack>& t : activeTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08009921 stop(t->portId());
9922 }
Phil Burk9fabbf82017-08-03 12:02:00 -07009923 // This will decrement references and may cause the destruction of this thread.
Eric Laurent6acd1d42017-01-04 14:23:29 -08009924 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07009925 AudioSystem::releaseOutput(mPortId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009926 } else {
Eric Laurentfee19762018-01-29 18:44:13 -08009927 AudioSystem::releaseInput(mPortId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009928 }
9929}
9930
9931
Andy Hungee58e4a2023-07-07 13:47:37 -07009932void MmapThread::configure(const audio_attributes_t* attr,
Eric Laurent6acd1d42017-01-04 14:23:29 -08009933 audio_stream_type_t streamType __unused,
9934 audio_session_t sessionId,
9935 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009936 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -08009937 audio_port_handle_t portId)
9938{
9939 mAttr = *attr;
9940 mSessionId = sessionId;
9941 mCallback = callback;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009942 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009943 mPortId = portId;
9944}
9945
Andy Hungee58e4a2023-07-07 13:47:37 -07009946status_t MmapThread::createMmapBuffer(int32_t minSizeFrames,
Eric Laurent6acd1d42017-01-04 14:23:29 -08009947 struct audio_mmap_buffer_info *info)
9948{
9949 if (mHalStream == 0) {
9950 return NO_INIT;
9951 }
Eric Laurent18b57012017-02-13 16:23:52 -08009952 mStandby = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009953 return mHalStream->createMmapBuffer(minSizeFrames, info);
9954}
9955
Andy Hungee58e4a2023-07-07 13:47:37 -07009956status_t MmapThread::getMmapPosition(struct audio_mmap_position* position) const
Eric Laurent6acd1d42017-01-04 14:23:29 -08009957{
9958 if (mHalStream == 0) {
9959 return NO_INIT;
9960 }
9961 return mHalStream->getMmapPosition(position);
9962}
9963
Andy Hungee58e4a2023-07-07 13:47:37 -07009964status_t MmapThread::exitStandby_l()
Eric Laurent331679c2018-04-16 17:03:16 -07009965{
Eric Laurentdda206a2022-07-08 17:28:35 +02009966 // The HAL must receive track metadata before starting the stream
9967 updateMetadata_l();
Eric Laurent331679c2018-04-16 17:03:16 -07009968 status_t ret = mHalStream->start();
9969 if (ret != NO_ERROR) {
9970 ALOGE("%s: error mHalStream->start() = %d for first track", __FUNCTION__, ret);
9971 return ret;
9972 }
Andy Hungcf10d742020-04-28 15:38:24 -07009973 if (mStandby) {
9974 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07009975 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -07009976 mStandby = false;
9977 }
Eric Laurent331679c2018-04-16 17:03:16 -07009978 return NO_ERROR;
9979}
9980
Andy Hungee58e4a2023-07-07 13:47:37 -07009981status_t MmapThread::start(const AudioClient& client,
jiabind1f1cb62020-03-24 11:57:57 -07009982 const audio_attributes_t *attr,
Eric Laurent6acd1d42017-01-04 14:23:29 -08009983 audio_port_handle_t *handle)
9984{
Eric Laurenta54f1282017-07-01 19:39:32 -07009985 ALOGV("%s clientUid %d mStandby %d mPortId %d *handle %d", __FUNCTION__,
Svet Ganov33761132021-05-13 22:51:08 +00009986 client.attributionSource.uid, mStandby, mPortId, *handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009987 if (mHalStream == 0) {
9988 return NO_INIT;
9989 }
9990
9991 status_t ret;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009992
Eric Laurentdda206a2022-07-08 17:28:35 +02009993 // For the first track, reuse portId and session allocated when the stream was opened.
Eric Laurenta54f1282017-07-01 19:39:32 -07009994 if (*handle == mPortId) {
Eric Laurentdda206a2022-07-08 17:28:35 +02009995 acquireWakeLock();
9996 return NO_ERROR;
Eric Laurenta54f1282017-07-01 19:39:32 -07009997 }
9998
9999 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
10000
10001 audio_io_handle_t io = mId;
Andy Hung6cd79802023-07-19 16:56:19 -070010002 const AttributionSourceState adjAttributionSource = afutils::checkAttributionSourcePackage(
Atneya Nairf59db5c2023-05-10 21:37:41 -070010003 client.attributionSource);
10004
Eric Laurenta54f1282017-07-01 19:39:32 -070010005 if (isOutput()) {
10006 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
10007 config.sample_rate = mSampleRate;
10008 config.channel_mask = mChannelMask;
10009 config.format = mFormat;
10010 audio_stream_type_t stream = streamType();
10011 audio_output_flags_t flags =
10012 (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010013 audio_port_handle_t deviceId = mDeviceId;
Kevin Rocard153f92d2018-12-18 18:33:28 -080010014 std::vector<audio_io_handle_t> secondaryOutputs;
Eric Laurentb0a7bc92022-04-05 15:06:08 +020010015 bool isSpatialized;
jiabinc658e452022-10-21 20:52:21 +000010016 bool isBitPerfect;
Eric Laurenta54f1282017-07-01 19:39:32 -070010017 ret = AudioSystem::getOutputForAttr(&mAttr, &io,
10018 mSessionId,
10019 &stream,
Atneya Nairf59db5c2023-05-10 21:37:41 -070010020 adjAttributionSource,
Eric Laurenta54f1282017-07-01 19:39:32 -070010021 &config,
10022 flags,
10023 &deviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -080010024 &portId,
Eric Laurentb0a7bc92022-04-05 15:06:08 +020010025 &secondaryOutputs,
jiabinc658e452022-10-21 20:52:21 +000010026 &isSpatialized,
10027 &isBitPerfect);
Kevin Rocard153f92d2018-12-18 18:33:28 -080010028 ALOGD_IF(!secondaryOutputs.empty(),
10029 "MmapThread::start does not support secondary outputs, ignoring them");
Eric Laurent6acd1d42017-01-04 14:23:29 -080010030 } else {
Eric Laurenta54f1282017-07-01 19:39:32 -070010031 audio_config_base_t config;
10032 config.sample_rate = mSampleRate;
10033 config.channel_mask = mChannelMask;
10034 config.format = mFormat;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010035 audio_port_handle_t deviceId = mDeviceId;
Eric Laurenta54f1282017-07-01 19:39:32 -070010036 ret = AudioSystem::getInputForAttr(&mAttr, &io,
Mikhail Naganov2996f672019-04-18 12:29:59 -070010037 RECORD_RIID_INVALID,
Eric Laurenta54f1282017-07-01 19:39:32 -070010038 mSessionId,
Atneya Nairf59db5c2023-05-10 21:37:41 -070010039 adjAttributionSource,
Eric Laurenta54f1282017-07-01 19:39:32 -070010040 &config,
10041 AUDIO_INPUT_FLAG_MMAP_NOIRQ,
10042 &deviceId,
10043 &portId);
10044 }
10045 // APM should not chose a different input or output stream for the same set of attributes
10046 // and audo configuration
10047 if (ret != NO_ERROR || io != mId) {
10048 ALOGE("%s: error getting output or input from APM (error %d, io %d expected io %d)",
10049 __FUNCTION__, ret, io, mId);
10050 return BAD_VALUE;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010051 }
10052
10053 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -070010054 ret = AudioSystem::startOutput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010055 } else {
jiabin09609032022-06-15 19:26:01 +000010056 {
10057 // Add the track record before starting input so that the silent status for the
10058 // client can be cached.
10059 Mutex::Autolock _l(mLock);
10060 setClientSilencedState_l(portId, false /*silenced*/);
10061 }
Eric Laurent4eb58f12018-12-07 16:41:02 -080010062 ret = AudioSystem::startInput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010063 }
10064
Eric Laurent331679c2018-04-16 17:03:16 -070010065 Mutex::Autolock _l(mLock);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010066 // abort if start is rejected by audio policy manager
10067 if (ret != NO_ERROR) {
Phil Burk7f6b40d2017-02-09 13:18:38 -080010068 ALOGE("%s: error start rejected by AudioPolicyManager = %d", __FUNCTION__, ret);
Eric Tan39ec8d62018-07-24 09:49:29 -070010069 if (!mActiveTracks.isEmpty()) {
Eric Laurent331679c2018-04-16 17:03:16 -070010070 mLock.unlock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010071 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -070010072 AudioSystem::releaseOutput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010073 } else {
Eric Laurentfee19762018-01-29 18:44:13 -080010074 AudioSystem::releaseInput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010075 }
Eric Laurent331679c2018-04-16 17:03:16 -070010076 mLock.lock();
Eric Laurent18b57012017-02-13 16:23:52 -080010077 } else {
10078 mHalStream->stop();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010079 }
jiabin09609032022-06-15 19:26:01 +000010080 eraseClientSilencedState_l(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010081 return PERMISSION_DENIED;
10082 }
10083
Kevin Rocard1f564ac2018-03-29 13:53:10 -070010084 // Given that MmapThread::mAttr is mutable, should a MmapTrack have attributes ?
Andy Hung8d31fd22023-06-26 19:20:57 -070010085 sp<IAfMmapTrack> track = IAfMmapTrack::create(
10086 this, attr == nullptr ? mAttr : *attr, mSampleRate, mFormat,
Svet Ganov33761132021-05-13 22:51:08 +000010087 mChannelMask, mSessionId, isOutput(),
10088 client.attributionSource,
Philip P. Moltmannbda45752020-07-17 16:41:18 -070010089 IPCThreadState::self()->getCallingPid(), portId);
jiabin09609032022-06-15 19:26:01 +000010090 if (!isOutput()) {
10091 track->setSilenced_l(isClientSilenced_l(portId));
10092 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010093
Eric Laurent4eb58f12018-12-07 16:41:02 -080010094 if (isOutput()) {
10095 // force volume update when a new track is added
10096 mHalVolFloat = -1.0f;
10097 } else if (!track->isSilenced_l()) {
Andy Hung8d31fd22023-06-26 19:20:57 -070010098 for (const sp<IAfMmapTrack>& t : mActiveTracks) {
Andy Hung920f6572022-10-06 12:09:49 -070010099 if (t->isSilenced_l()
10100 && t->uid() != static_cast<uid_t>(client.attributionSource.uid)) {
Eric Laurent4eb58f12018-12-07 16:41:02 -080010101 t->invalidate();
Andy Hung920f6572022-10-06 12:09:49 -070010102 }
Eric Laurent4eb58f12018-12-07 16:41:02 -080010103 }
10104 }
10105
Eric Laurent6acd1d42017-01-04 14:23:29 -080010106 mActiveTracks.add(track);
Andy Hung116bc262023-06-20 18:56:17 -070010107 sp<IAfEffectChain> chain = getEffectChain_l(mSessionId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010108 if (chain != 0) {
Eric Laurentd66d7a12021-07-13 13:35:32 +020010109 chain->setStrategy(getStrategyForStream(streamType()));
Eric Laurent6acd1d42017-01-04 14:23:29 -080010110 chain->incTrackCnt();
10111 chain->incActiveTrackCnt();
10112 }
10113
Andy Hungc2b11cb2020-04-22 09:04:01 -070010114 track->logBeginInterval(patchSinksToString(&mPatch)); // log to MediaMetrics
Eric Laurent6acd1d42017-01-04 14:23:29 -080010115 *handle = portId;
Eric Laurentdda206a2022-07-08 17:28:35 +020010116
10117 if (mActiveTracks.size() == 1) {
10118 ret = exitStandby_l();
10119 }
10120
Eric Laurent6acd1d42017-01-04 14:23:29 -080010121 broadcast_l();
10122
Eric Laurentdda206a2022-07-08 17:28:35 +020010123 ALOGV("%s DONE status %d handle %d stream %p", __FUNCTION__, ret, *handle, mHalStream.get());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010124
Eric Laurentdda206a2022-07-08 17:28:35 +020010125 return ret;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010126}
10127
Andy Hungee58e4a2023-07-07 13:47:37 -070010128status_t MmapThread::stop(audio_port_handle_t handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010129{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010130 ALOGV("%s handle %d", __FUNCTION__, handle);
10131
10132 if (mHalStream == 0) {
10133 return NO_INIT;
10134 }
10135
Eric Laurenta54f1282017-07-01 19:39:32 -070010136 if (handle == mPortId) {
Phil Burk98ab4082020-09-25 21:46:34 +000010137 releaseWakeLock();
Eric Laurenta54f1282017-07-01 19:39:32 -070010138 return NO_ERROR;
10139 }
10140
Eric Laurent331679c2018-04-16 17:03:16 -070010141 Mutex::Autolock _l(mLock);
10142
Andy Hung8d31fd22023-06-26 19:20:57 -070010143 sp<IAfMmapTrack> track;
10144 for (const sp<IAfMmapTrack>& t : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010145 if (handle == t->portId()) {
10146 track = t;
10147 break;
10148 }
10149 }
10150 if (track == 0) {
10151 return BAD_VALUE;
10152 }
10153
10154 mActiveTracks.remove(track);
jiabin09609032022-06-15 19:26:01 +000010155 eraseClientSilencedState_l(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010156
Eric Laurent331679c2018-04-16 17:03:16 -070010157 mLock.unlock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010158 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -070010159 AudioSystem::stopOutput(track->portId());
10160 AudioSystem::releaseOutput(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010161 } else {
Eric Laurentfee19762018-01-29 18:44:13 -080010162 AudioSystem::stopInput(track->portId());
10163 AudioSystem::releaseInput(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010164 }
Eric Laurent331679c2018-04-16 17:03:16 -070010165 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010166
Andy Hung116bc262023-06-20 18:56:17 -070010167 sp<IAfEffectChain> chain = getEffectChain_l(track->sessionId());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010168 if (chain != 0) {
10169 chain->decActiveTrackCnt();
10170 chain->decTrackCnt();
10171 }
10172
Eric Laurentdda206a2022-07-08 17:28:35 +020010173 if (mActiveTracks.isEmpty()) {
10174 mHalStream->stop();
10175 }
10176
Eric Laurent6acd1d42017-01-04 14:23:29 -080010177 broadcast_l();
10178
Eric Laurent6acd1d42017-01-04 14:23:29 -080010179 return NO_ERROR;
10180}
10181
Andy Hungee58e4a2023-07-07 13:47:37 -070010182status_t MmapThread::standby()
Eric Laurent18b57012017-02-13 16:23:52 -080010183{
10184 ALOGV("%s", __FUNCTION__);
10185
10186 if (mHalStream == 0) {
10187 return NO_INIT;
10188 }
Eric Tan39ec8d62018-07-24 09:49:29 -070010189 if (!mActiveTracks.isEmpty()) {
Eric Laurent18b57012017-02-13 16:23:52 -080010190 return INVALID_OPERATION;
10191 }
10192 mHalStream->standby();
Andy Hungcf10d742020-04-28 15:38:24 -070010193 if (!mStandby) {
10194 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -070010195 mThreadSnapshot.onEnd();
Andy Hungcf10d742020-04-28 15:38:24 -070010196 mStandby = true;
10197 }
Eric Laurent18b57012017-02-13 16:23:52 -080010198 releaseWakeLock();
10199 return NO_ERROR;
10200}
10201
Andy Hungee58e4a2023-07-07 13:47:37 -070010202status_t MmapThread::reportData(const void* /*buffer*/, size_t /*frameCount*/) {
jiabinfc791ee2023-02-15 19:43:40 +000010203 // This is a stub implementation. The MmapPlaybackThread overrides this function.
10204 return INVALID_OPERATION;
10205}
10206
Andy Hungee58e4a2023-07-07 13:47:37 -070010207void MmapThread::readHalParameters_l()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010208{
10209 status_t result = mHalStream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
10210 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
10211 mFormat = mHALFormat;
10212 LOG_ALWAYS_FATAL_IF(!audio_is_linear_pcm(mFormat), "HAL format %#x is not linear pcm", mFormat);
10213 result = mHalStream->getFrameSize(&mFrameSize);
10214 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
Hayden Gomes1a89ab32020-06-12 11:05:47 -070010215 LOG_ALWAYS_FATAL_IF(mFrameSize <= 0, "Error frame size was %zu but must be greater than zero",
10216 mFrameSize);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010217 result = mHalStream->getBufferSize(&mBufferSize);
10218 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
10219 mFrameCount = mBufferSize / mFrameSize;
Andy Hungc2b11cb2020-04-22 09:04:01 -070010220
Andy Hungcf10d742020-04-28 15:38:24 -070010221 // TODO: make a readHalParameters call?
10222 mediametrics::LogItem item(mThreadMetrics.getMetricsId());
Andy Hungc2b11cb2020-04-22 09:04:01 -070010223 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
10224 .set(AMEDIAMETRICS_PROP_ENCODING, formatToString(mFormat).c_str())
10225 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
10226 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
10227 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
10228 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mFrameCount)
10229 /*
10230 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
10231 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELMASK,
10232 (int32_t)mHapticChannelMask)
10233 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELCOUNT,
10234 (int32_t)mHapticChannelCount)
10235 */
10236 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_ENCODING,
10237 formatToString(mHALFormat).c_str())
10238 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_FRAMECOUNT,
10239 (int32_t)mFrameCount) // sic - added HAL
10240 .record();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010241}
10242
Andy Hungee58e4a2023-07-07 13:47:37 -070010243bool MmapThread::threadLoop()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010244{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010245 checkSilentMode_l();
10246
10247 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
10248
10249 while (!exitPending())
10250 {
Andy Hung116bc262023-06-20 18:56:17 -070010251 Vector<sp<IAfEffectChain>> effectChains;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010252
Andy Hung13850be2019-03-14 11:33:09 -070010253 { // under Thread lock
10254 Mutex::Autolock _l(mLock);
10255
Eric Laurent6acd1d42017-01-04 14:23:29 -080010256 if (mSignalPending) {
10257 // A signal was raised while we were unlocked
10258 mSignalPending = false;
10259 } else {
10260 if (mConfigEvents.isEmpty()) {
10261 // we're about to wait, flush the binder command buffer
10262 IPCThreadState::self()->flushCommands();
10263
10264 if (exitPending()) {
10265 break;
10266 }
10267
Eric Laurent6acd1d42017-01-04 14:23:29 -080010268 // wait until we have something to do...
10269 ALOGV("%s going to sleep", myName.string());
10270 mWaitWorkCV.wait(mLock);
10271 ALOGV("%s waking up", myName.string());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010272
10273 checkSilentMode_l();
10274
10275 continue;
10276 }
10277 }
10278
10279 processConfigEvents_l();
10280
10281 processVolume_l();
10282
10283 checkInvalidTracks_l();
10284
10285 mActiveTracks.updatePowerState(this);
10286
Kevin Rocard069c2712018-03-29 19:09:14 -070010287 updateMetadata_l();
10288
Eric Laurent6acd1d42017-01-04 14:23:29 -080010289 lockEffectChains_l(effectChains);
Andy Hung13850be2019-03-14 11:33:09 -070010290 } // release Thread lock
10291
Eric Laurent6acd1d42017-01-04 14:23:29 -080010292 for (size_t i = 0; i < effectChains.size(); i ++) {
Andy Hung13850be2019-03-14 11:33:09 -070010293 effectChains[i]->process_l(); // Thread is not locked, but effect chain is locked
Eric Laurent6acd1d42017-01-04 14:23:29 -080010294 }
Andy Hung13850be2019-03-14 11:33:09 -070010295
10296 // enable changes in effect chain, including moving to another thread.
Eric Laurent6acd1d42017-01-04 14:23:29 -080010297 unlockEffectChains(effectChains);
10298 // Effect chains will be actually deleted here if they were removed from
10299 // mEffectChains list during mixing or effects processing
10300 }
10301
10302 threadLoop_exit();
10303
10304 if (!mStandby) {
10305 threadLoop_standby();
10306 mStandby = true;
10307 }
10308
Eric Laurent6acd1d42017-01-04 14:23:29 -080010309 ALOGV("Thread %p type %d exiting", this, mType);
10310 return false;
10311}
10312
10313// checkForNewParameter_l() must be called with ThreadBase::mLock held
Andy Hungee58e4a2023-07-07 13:47:37 -070010314bool MmapThread::checkForNewParameter_l(const String8& keyValuePair,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010315 status_t& status)
10316{
10317 AudioParameter param = AudioParameter(keyValuePair);
10318 int value;
Eric Laurente6e9a482017-07-25 19:26:02 -070010319 bool sendToHal = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010320 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -070010321 LOG_FATAL("Should not happen set routing device in MmapThread");
Eric Laurent6acd1d42017-01-04 14:23:29 -080010322 }
Eric Laurente6e9a482017-07-25 19:26:02 -070010323 if (sendToHal) {
10324 status = mHalStream->setParameters(keyValuePair);
10325 } else {
10326 status = NO_ERROR;
10327 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010328
10329 return false;
10330}
10331
Andy Hungee58e4a2023-07-07 13:47:37 -070010332String8 MmapThread::getParameters(const String8& keys)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010333{
10334 Mutex::Autolock _l(mLock);
10335 String8 out_s8;
10336 if (initCheck() == NO_ERROR && mHalStream->getParameters(keys, &out_s8) == OK) {
10337 return out_s8;
10338 }
Andy Hung920f6572022-10-06 12:09:49 -070010339 return {};
Eric Laurent6acd1d42017-01-04 14:23:29 -080010340}
10341
Andy Hungee58e4a2023-07-07 13:47:37 -070010342void MmapThread::ioConfigChanged(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -070010343 audio_port_handle_t portId __unused) {
Mikhail Naganov88536df2021-07-26 17:30:29 -070010344 sp<AudioIoDescriptor> desc;
10345 bool isInput = false;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010346 switch (event) {
10347 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -070010348 case AUDIO_INPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -080010349 case AUDIO_INPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -070010350 isInput = true;
10351 FALLTHROUGH_INTENDED;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010352 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -070010353 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -080010354 case AUDIO_OUTPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -070010355 desc = sp<AudioIoDescriptor>::make(mId, mPatch, isInput,
10356 mSampleRate, mFormat, mChannelMask, mFrameCount, mFrameCount);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010357 break;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010358 case AUDIO_INPUT_CLOSED:
10359 case AUDIO_OUTPUT_CLOSED:
10360 default:
Mikhail Naganov88536df2021-07-26 17:30:29 -070010361 desc = sp<AudioIoDescriptor>::make(mId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010362 break;
10363 }
Andy Hung583043b2023-07-17 17:05:00 -070010364 mAfThreadCallback->ioConfigChanged(event, desc, pid);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010365}
10366
Andy Hungee58e4a2023-07-07 13:47:37 -070010367status_t MmapThread::createAudioPatch_l(const struct audio_patch* patch,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010368 audio_patch_handle_t *handle)
Andy Hung920f6572022-10-06 12:09:49 -070010369NO_THREAD_SAFETY_ANALYSIS // elease and re-acquire mLock
Eric Laurent6acd1d42017-01-04 14:23:29 -080010370{
10371 status_t status = NO_ERROR;
10372
10373 // store new device and send to effects
10374 audio_devices_t type = AUDIO_DEVICE_NONE;
10375 audio_port_handle_t deviceId;
jiabinc52b1ff2019-10-31 17:20:42 -070010376 AudioDeviceTypeAddrVector sinkDeviceTypeAddrs;
10377 AudioDeviceTypeAddr sourceDeviceTypeAddr;
10378 uint32_t numDevices = 0;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010379 if (isOutput()) {
10380 for (unsigned int i = 0; i < patch->num_sinks; i++) {
jiabinc52b1ff2019-10-31 17:20:42 -070010381 LOG_ALWAYS_FATAL_IF(popcount(patch->sinks[i].ext.device.type) > 1
10382 && !mAudioHwDev->supportsAudioPatches(),
10383 "Enumerated device type(%#x) must not be used "
10384 "as it does not support audio patches",
10385 patch->sinks[i].ext.device.type);
Mikhail Naganov55773032020-10-01 15:08:13 -070010386 type = static_cast<audio_devices_t>(type | patch->sinks[i].ext.device.type);
Andy Hung920f6572022-10-06 12:09:49 -070010387 sinkDeviceTypeAddrs.emplace_back(patch->sinks[i].ext.device.type,
10388 patch->sinks[i].ext.device.address);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010389 }
10390 deviceId = patch->sinks[0].id;
jiabinc52b1ff2019-10-31 17:20:42 -070010391 numDevices = mPatch.num_sinks;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010392 } else {
10393 type = patch->sources[0].ext.device.type;
10394 deviceId = patch->sources[0].id;
jiabinc52b1ff2019-10-31 17:20:42 -070010395 numDevices = mPatch.num_sources;
10396 sourceDeviceTypeAddr.mType = patch->sources[0].ext.device.type;
jiabin0a488932020-08-07 17:32:40 -070010397 sourceDeviceTypeAddr.setAddress(patch->sources[0].ext.device.address);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010398 }
10399
10400 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -080010401 if (isOutput()) {
10402 mEffectChains[i]->setDevices_l(sinkDeviceTypeAddrs);
10403 } else {
10404 mEffectChains[i]->setInputDevice_l(sourceDeviceTypeAddr);
10405 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010406 }
10407
jiabinc52b1ff2019-10-31 17:20:42 -070010408 if (!isOutput()) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010409 // store new source and send to effects
10410 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
10411 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
10412 for (size_t i = 0; i < mEffectChains.size(); i++) {
10413 mEffectChains[i]->setAudioSource_l(mAudioSource);
10414 }
10415 }
10416 }
10417
10418 if (mAudioHwDev->supportsAudioPatches()) {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010419 status = mHalDevice->createAudioPatch(patch->num_sources, patch->sources, patch->num_sinks,
10420 patch->sinks, handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010421 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010422 audio_port_config port;
10423 std::optional<audio_source_t> source;
10424 if (isOutput()) {
10425 port = patch->sinks[0];
Eric Laurent6acd1d42017-01-04 14:23:29 -080010426 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010427 port = patch->sources[0];
10428 source = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010429 }
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010430 status = mHalStream->legacyCreateAudioPatch(port, source, type);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010431 *handle = AUDIO_PATCH_HANDLE_NONE;
10432 }
10433
jiabinc52b1ff2019-10-31 17:20:42 -070010434 if (numDevices == 0 || mDeviceId != deviceId) {
10435 if (isOutput()) {
10436 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
10437 mOutDeviceTypeAddrs = sinkDeviceTypeAddrs;
jiabin0a957d32020-04-29 10:56:20 -070010438 checkSilentMode_l();
jiabinc52b1ff2019-10-31 17:20:42 -070010439 } else {
10440 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
10441 mInDeviceTypeAddr = sourceDeviceTypeAddr;
10442 }
Phil Burk7f6b40d2017-02-09 13:18:38 -080010443 sp<MmapStreamCallback> callback = mCallback.promote();
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010444 if (mDeviceId != deviceId && callback != 0) {
Eric Laurent734046e2018-04-16 14:50:52 -070010445 mLock.unlock();
Phil Burk7f6b40d2017-02-09 13:18:38 -080010446 callback->onRoutingChanged(deviceId);
Eric Laurent734046e2018-04-16 14:50:52 -070010447 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010448 }
jiabinc52b1ff2019-10-31 17:20:42 -070010449 mPatch = *patch;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010450 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010451 }
Eric Laurentdda206a2022-07-08 17:28:35 +020010452 // Force meteadata update after a route change
10453 mActiveTracks.setHasChanged();
10454
Eric Laurent6acd1d42017-01-04 14:23:29 -080010455 return status;
10456}
10457
Andy Hungee58e4a2023-07-07 13:47:37 -070010458status_t MmapThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010459{
10460 status_t status = NO_ERROR;
10461
jiabinc52b1ff2019-10-31 17:20:42 -070010462 mPatch = audio_patch{};
10463 mOutDeviceTypeAddrs.clear();
10464 mInDeviceTypeAddr.reset();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010465
10466 bool supportsAudioPatches = mHalDevice->supportsAudioPatches(&supportsAudioPatches) == OK ?
10467 supportsAudioPatches : false;
10468
10469 if (supportsAudioPatches) {
10470 status = mHalDevice->releaseAudioPatch(handle);
10471 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010472 status = mHalStream->legacyReleaseAudioPatch();
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 Hungee58e4a2023-07-07 13:47:37 -070010480void MmapThread::toAudioPortConfig(struct audio_port_config* config)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010481{
Mikhail Naganovdc769682018-05-04 15:34:08 -070010482 ThreadBase::toAudioPortConfig(config);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010483 if (isOutput()) {
10484 config->role = AUDIO_PORT_ROLE_SOURCE;
10485 config->ext.mix.hw_module = mAudioHwDev->handle();
10486 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
10487 } else {
10488 config->role = AUDIO_PORT_ROLE_SINK;
10489 config->ext.mix.hw_module = mAudioHwDev->handle();
10490 config->ext.mix.usecase.source = mAudioSource;
10491 }
10492}
10493
Andy Hungee58e4a2023-07-07 13:47:37 -070010494status_t MmapThread::addEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010495{
10496 audio_session_t session = chain->sessionId();
10497
10498 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
10499 // Attach all tracks with same session ID to this chain.
10500 // indicate all active tracks in the chain
Andy Hung8d31fd22023-06-26 19:20:57 -070010501 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010502 if (session == track->sessionId()) {
10503 chain->incTrackCnt();
10504 chain->incActiveTrackCnt();
10505 }
10506 }
10507
10508 chain->setThread(this);
10509 chain->setInBuffer(nullptr);
10510 chain->setOutBuffer(nullptr);
10511 chain->syncHalEffectsState();
10512
10513 mEffectChains.add(chain);
10514 checkSuspendOnAddEffectChain_l(chain);
10515 return NO_ERROR;
10516}
10517
Andy Hungee58e4a2023-07-07 13:47:37 -070010518size_t MmapThread::removeEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010519{
10520 audio_session_t session = chain->sessionId();
10521
10522 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
10523
10524 for (size_t i = 0; i < mEffectChains.size(); i++) {
10525 if (chain == mEffectChains[i]) {
10526 mEffectChains.removeAt(i);
10527 // detach all active tracks from the chain
10528 // detach all tracks with same session ID from this chain
Andy Hung8d31fd22023-06-26 19:20:57 -070010529 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010530 if (session == track->sessionId()) {
10531 chain->decActiveTrackCnt();
10532 chain->decTrackCnt();
10533 }
10534 }
10535 break;
10536 }
10537 }
10538 return mEffectChains.size();
10539}
10540
Andy Hungee58e4a2023-07-07 13:47:37 -070010541void MmapThread::threadLoop_standby()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010542{
10543 mHalStream->standby();
10544}
10545
Andy Hungee58e4a2023-07-07 13:47:37 -070010546void MmapThread::threadLoop_exit()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010547{
Phil Burk7dce7282017-09-27 13:51:41 -070010548 // Do not call callback->onTearDown() because it is redundant for thread exit
10549 // and because it can cause a recursive mutex lock on stop().
Eric Laurent6acd1d42017-01-04 14:23:29 -080010550}
10551
Andy Hungee58e4a2023-07-07 13:47:37 -070010552status_t MmapThread::setSyncEvent(const sp<SyncEvent>& /* event */)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010553{
10554 return BAD_VALUE;
10555}
10556
Andy Hungee58e4a2023-07-07 13:47:37 -070010557bool MmapThread::isValidSyncEvent(
10558 const sp<SyncEvent>& /* event */) const
Eric Laurent6acd1d42017-01-04 14:23:29 -080010559{
10560 return false;
10561}
10562
Andy Hungee58e4a2023-07-07 13:47:37 -070010563status_t MmapThread::checkEffectCompatibility_l(
Eric Laurent6acd1d42017-01-04 14:23:29 -080010564 const effect_descriptor_t *desc, audio_session_t sessionId)
10565{
10566 // No global effect sessions on mmap threads
Eric Laurent3f75a5b2019-11-12 15:55:51 -080010567 if (audio_is_global_session(sessionId)) {
10568 ALOGW("checkEffectCompatibility_l(): global effect %s on MMAP thread %s",
Eric Laurent6acd1d42017-01-04 14:23:29 -080010569 desc->name, mThreadName);
10570 return BAD_VALUE;
10571 }
10572
10573 if (!isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC)) {
10574 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on capture mmap thread",
10575 desc->name);
10576 return BAD_VALUE;
10577 }
10578 if (isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Glenn Kastend3bb6452016-12-05 18:14:37 -080010579 ALOGW("checkEffectCompatibility_l(): pre processing effect %s created on playback mmap "
10580 "thread", desc->name);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010581 return BAD_VALUE;
10582 }
10583
10584 // Only allow effects without processing load or latency
10585 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) != EFFECT_FLAG_NO_PROCESS) {
10586 return BAD_VALUE;
10587 }
10588
Andy Hung116bc262023-06-20 18:56:17 -070010589 if (IAfEffectModule::isHapticGenerator(&desc->type)) {
jiabineb3bda02020-06-30 14:07:03 -070010590 ALOGE("%s(): HapticGenerator is not supported for MmapThread", __func__);
10591 return BAD_VALUE;
10592 }
10593
Eric Laurent6acd1d42017-01-04 14:23:29 -080010594 return NO_ERROR;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010595}
10596
Andy Hungee58e4a2023-07-07 13:47:37 -070010597void MmapThread::checkInvalidTracks_l()
Andy Hung920f6572022-10-06 12:09:49 -070010598NO_THREAD_SAFETY_ANALYSIS // release and re-acquire mLock
Eric Laurent6acd1d42017-01-04 14:23:29 -080010599{
Eric Laurent039c24a2022-10-07 14:01:59 +020010600 sp<MmapStreamCallback> callback;
Andy Hung8d31fd22023-06-26 19:20:57 -070010601 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010602 if (track->isInvalid()) {
Eric Laurent039c24a2022-10-07 14:01:59 +020010603 callback = mCallback.promote();
10604 if (callback == nullptr && mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
10605 ALOGW("Could not notify MMAP stream tear down: no onRoutingChanged callback!");
10606 mNoCallbackWarningCount++;
10607 }
10608 break;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010609 }
10610 }
Eric Laurent039c24a2022-10-07 14:01:59 +020010611 if (callback != 0) {
10612 mLock.unlock();
10613 callback->onRoutingChanged(AUDIO_PORT_HANDLE_NONE);
10614 mLock.lock();
jiabindfa32482022-10-06 19:45:50 +000010615 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010616}
10617
Andy Hungee58e4a2023-07-07 13:47:37 -070010618void MmapThread::dumpInternals_l(int fd, const Vector<String16>& /* args */)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010619{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010620 dprintf(fd, " Attributes: content type %d usage %d source %d\n",
10621 mAttr.content_type, mAttr.usage, mAttr.source);
10622 dprintf(fd, " Session: %d port Id: %d\n", mSessionId, mPortId);
Eric Tan39ec8d62018-07-24 09:49:29 -070010623 if (mActiveTracks.isEmpty()) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010624 dprintf(fd, " No active clients\n");
10625 }
10626}
10627
Andy Hungee58e4a2023-07-07 13:47:37 -070010628void MmapThread::dumpTracks_l(int fd, const Vector<String16>& /* args */)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010629{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010630 String8 result;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010631 size_t numtracks = mActiveTracks.size();
Andy Hung2c6c3bb2017-06-16 14:01:45 -070010632 dprintf(fd, " %zu Tracks\n", numtracks);
10633 const char *prefix = " ";
Eric Laurent6acd1d42017-01-04 14:23:29 -080010634 if (numtracks) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -070010635 result.append(prefix);
Kevin Rocard5f2136e2018-05-11 22:03:00 -070010636 mActiveTracks[0]->appendDumpHeader(result);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010637 for (size_t i = 0; i < numtracks ; ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -070010638 sp<IAfMmapTrack> track = mActiveTracks[i];
Andy Hung2c6c3bb2017-06-16 14:01:45 -070010639 result.append(prefix);
10640 track->appendDump(result, true /* active */);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010641 }
10642 } else {
10643 dprintf(fd, "\n");
10644 }
10645 write(fd, result.string(), result.size());
10646}
10647
Andy Hungee58e4a2023-07-07 13:47:37 -070010648/* static */
10649sp<IAfMmapPlaybackThread> IAfMmapPlaybackThread::create(
Andy Hung583043b2023-07-17 17:05:00 -070010650 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
Andy Hungee58e4a2023-07-07 13:47:37 -070010651 AudioHwDevice* hwDev, AudioStreamOut* output, bool systemReady) {
Andy Hung583043b2023-07-17 17:05:00 -070010652 return sp<MmapPlaybackThread>::make(afThreadCallback, id, hwDev, output, systemReady);
Andy Hungee58e4a2023-07-07 13:47:37 -070010653}
10654
10655MmapPlaybackThread::MmapPlaybackThread(
Andy Hung583043b2023-07-17 17:05:00 -070010656 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
jiabinc52b1ff2019-10-31 17:20:42 -070010657 AudioHwDevice *hwDev, AudioStreamOut *output, bool systemReady)
Andy Hung583043b2023-07-17 17:05:00 -070010658 : MmapThread(afThreadCallback, id, hwDev, output->stream, systemReady, true /* isOut */),
Eric Laurent6acd1d42017-01-04 14:23:29 -080010659 mStreamType(AUDIO_STREAM_MUSIC),
Phil Burk56ecf3e2018-03-12 15:38:17 -070010660 mOutput(output)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010661{
10662 snprintf(mThreadName, kThreadNameLength, "AudioMmapOut_%X", id);
10663 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Andy Hung583043b2023-07-17 17:05:00 -070010664 mMasterVolume = afThreadCallback->masterVolume_l();
10665 mMasterMute = afThreadCallback->masterMute_l();
Eric Laurent1f9b5e62023-07-03 18:14:07 +020010666
10667 for (int i = AUDIO_STREAM_MIN; i < AUDIO_STREAM_FOR_POLICY_CNT; ++i) {
10668 const audio_stream_type_t stream{static_cast<audio_stream_type_t>(i)};
10669 mStreamTypes[stream].volume = 0.0f;
Andy Hung583043b2023-07-17 17:05:00 -070010670 mStreamTypes[stream].mute = mAfThreadCallback->streamMute_l(stream);
Eric Laurent1f9b5e62023-07-03 18:14:07 +020010671 }
10672 // Audio patch and call assistant volume are always max
10673 mStreamTypes[AUDIO_STREAM_PATCH].volume = 1.0f;
10674 mStreamTypes[AUDIO_STREAM_PATCH].mute = false;
10675 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].volume = 1.0f;
10676 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].mute = false;
10677
Eric Laurent6acd1d42017-01-04 14:23:29 -080010678 if (mAudioHwDev) {
10679 if (mAudioHwDev->canSetMasterVolume()) {
10680 mMasterVolume = 1.0;
10681 }
10682
10683 if (mAudioHwDev->canSetMasterMute()) {
10684 mMasterMute = false;
10685 }
10686 }
10687}
10688
Andy Hungee58e4a2023-07-07 13:47:37 -070010689void MmapPlaybackThread::configure(const audio_attributes_t* attr,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010690 audio_stream_type_t streamType,
10691 audio_session_t sessionId,
10692 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010693 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010694 audio_port_handle_t portId)
10695{
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010696 MmapThread::configure(attr, streamType, sessionId, callback, deviceId, portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010697 mStreamType = streamType;
10698}
10699
Andy Hungee58e4a2023-07-07 13:47:37 -070010700AudioStreamOut* MmapPlaybackThread::clearOutput()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010701{
10702 Mutex::Autolock _l(mLock);
10703 AudioStreamOut *output = mOutput;
10704 mOutput = NULL;
10705 return output;
10706}
10707
Andy Hungee58e4a2023-07-07 13:47:37 -070010708void MmapPlaybackThread::setMasterVolume(float value)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010709{
10710 Mutex::Autolock _l(mLock);
10711 // Don't apply master volume in SW if our HAL can do it for us.
10712 if (mAudioHwDev &&
10713 mAudioHwDev->canSetMasterVolume()) {
10714 mMasterVolume = 1.0;
10715 } else {
10716 mMasterVolume = value;
10717 }
10718}
10719
Andy Hungee58e4a2023-07-07 13:47:37 -070010720void MmapPlaybackThread::setMasterMute(bool muted)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010721{
10722 Mutex::Autolock _l(mLock);
10723 // Don't apply master mute in SW if our HAL can do it for us.
10724 if (mAudioHwDev && mAudioHwDev->canSetMasterMute()) {
10725 mMasterMute = false;
10726 } else {
10727 mMasterMute = muted;
10728 }
10729}
10730
Andy Hungee58e4a2023-07-07 13:47:37 -070010731void MmapPlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010732{
10733 Mutex::Autolock _l(mLock);
Eric Laurent1f9b5e62023-07-03 18:14:07 +020010734 mStreamTypes[stream].volume = value;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010735 if (stream == mStreamType) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010736 broadcast_l();
10737 }
10738}
10739
Andy Hungee58e4a2023-07-07 13:47:37 -070010740float MmapPlaybackThread::streamVolume(audio_stream_type_t stream) const
Eric Laurent6acd1d42017-01-04 14:23:29 -080010741{
10742 Mutex::Autolock _l(mLock);
Eric Laurent1f9b5e62023-07-03 18:14:07 +020010743 return mStreamTypes[stream].volume;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010744}
10745
Andy Hungee58e4a2023-07-07 13:47:37 -070010746void MmapPlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010747{
10748 Mutex::Autolock _l(mLock);
Eric Laurent1f9b5e62023-07-03 18:14:07 +020010749 mStreamTypes[stream].mute = muted;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010750 if (stream == mStreamType) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010751 broadcast_l();
10752 }
10753}
10754
Andy Hungee58e4a2023-07-07 13:47:37 -070010755void MmapPlaybackThread::invalidateTracks(audio_stream_type_t streamType)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010756{
10757 Mutex::Autolock _l(mLock);
10758 if (streamType == mStreamType) {
Andy Hung8d31fd22023-06-26 19:20:57 -070010759 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010760 track->invalidate();
10761 }
10762 broadcast_l();
10763 }
10764}
10765
Andy Hungee58e4a2023-07-07 13:47:37 -070010766void MmapPlaybackThread::invalidateTracks(std::set<audio_port_handle_t>& portIds)
jiabinc44b3462022-12-08 12:52:31 -080010767{
10768 Mutex::Autolock _l(mLock);
10769 bool trackMatch = false;
Andy Hung8d31fd22023-06-26 19:20:57 -070010770 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
jiabinc44b3462022-12-08 12:52:31 -080010771 if (portIds.find(track->portId()) != portIds.end()) {
10772 track->invalidate();
10773 trackMatch = true;
10774 portIds.erase(track->portId());
10775 }
10776 if (portIds.empty()) {
10777 break;
10778 }
10779 }
10780 if (trackMatch) {
10781 broadcast_l();
10782 }
10783}
10784
Andy Hungee58e4a2023-07-07 13:47:37 -070010785void MmapPlaybackThread::processVolume_l()
Andy Hung920f6572022-10-06 12:09:49 -070010786NO_THREAD_SAFETY_ANALYSIS // access of track->processMuteEvent_l
Eric Laurent6acd1d42017-01-04 14:23:29 -080010787{
10788 float volume;
10789
Eric Laurent1f9b5e62023-07-03 18:14:07 +020010790 if (mMasterMute || streamMuted_l()) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010791 volume = 0;
10792 } else {
Eric Laurent1f9b5e62023-07-03 18:14:07 +020010793 volume = mMasterVolume * streamVolume_l();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010794 }
10795
10796 if (volume != mHalVolFloat) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010797 // Convert volumes from float to 8.24
10798 uint32_t vol = (uint32_t)(volume * (1 << 24));
10799
10800 // Delegate volume control to effect in track effect chain if needed
10801 // only one effect chain can be present on DirectOutputThread, so if
10802 // there is one, the track is connected to it
10803 if (!mEffectChains.isEmpty()) {
10804 mEffectChains[0]->setVolume_l(&vol, &vol);
10805 volume = (float)vol / (1 << 24);
10806 }
Eric Laurentdff774a2017-04-21 15:29:38 -070010807 // Try to use HW volume control and fall back to SW control if not implemented
Phil Burk56ecf3e2018-03-12 15:38:17 -070010808 if (mOutput->stream->setVolume(volume, volume) == NO_ERROR) {
10809 mHalVolFloat = volume; // HW volume control worked, so update value.
10810 mNoCallbackWarningCount = 0;
10811 } else {
Eric Laurentdff774a2017-04-21 15:29:38 -070010812 sp<MmapStreamCallback> callback = mCallback.promote();
10813 if (callback != 0) {
Phil Burk56ecf3e2018-03-12 15:38:17 -070010814 mHalVolFloat = volume; // SW volume control worked, so update value.
10815 mNoCallbackWarningCount = 0;
Eric Laurent734046e2018-04-16 14:50:52 -070010816 mLock.unlock();
Robert Wu4389ae62022-02-17 18:39:41 +000010817 callback->onVolumeChanged(volume);
Eric Laurent734046e2018-04-16 14:50:52 -070010818 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010819 } else {
Phil Burk56ecf3e2018-03-12 15:38:17 -070010820 if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
10821 ALOGW("Could not set MMAP stream volume: no volume callback!");
10822 mNoCallbackWarningCount++;
10823 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010824 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010825 }
Andy Hung8d31fd22023-06-26 19:20:57 -070010826 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Jasmine Chaeaa10e42021-05-11 10:11:14 +080010827 track->setMetadataHasChanged();
Andy Hung583043b2023-07-17 17:05:00 -070010828 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
Vlad Popaec1788e2022-08-04 11:23:30 +020010829 /*muteState=*/{mMasterMute,
Eric Laurent1f9b5e62023-07-03 18:14:07 +020010830 streamVolume_l() == 0.f,
10831 streamMuted_l(),
Vlad Popaec1788e2022-08-04 11:23:30 +020010832 // TODO(b/241533526): adjust logic to include mute from AppOps
10833 false /*muteFromPlaybackRestricted*/,
10834 false /*muteFromClientVolume*/,
10835 false /*muteFromVolumeShaper*/});
Jasmine Chaeaa10e42021-05-11 10:11:14 +080010836 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010837 }
10838}
10839
Andy Hungee58e4a2023-07-07 13:47:37 -070010840ThreadBase::MetadataUpdate MmapPlaybackThread::updateMetadata_l()
Kevin Rocard069c2712018-03-29 19:09:14 -070010841{
Jasmine Chaeaa10e42021-05-11 10:11:14 +080010842 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
Vlad Popa7e81cea2023-01-19 16:34:16 +010010843 return {}; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -070010844 }
10845 StreamOutHalInterface::SourceMetadata metadata;
Andy Hung8d31fd22023-06-26 19:20:57 -070010846 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Kevin Rocard069c2712018-03-29 19:09:14 -070010847 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurent94579172020-11-20 18:41:04 +010010848 playback_track_metadata_v7_t trackMetadata;
10849 trackMetadata.base = {
Kevin Rocard069c2712018-03-29 19:09:14 -070010850 .usage = track->attributes().usage,
10851 .content_type = track->attributes().content_type,
10852 .gain = mHalVolFloat, // TODO: propagate from aaudio pre-mix volume
Eric Laurent94579172020-11-20 18:41:04 +010010853 };
10854 trackMetadata.channel_mask = track->channelMask(),
10855 strncpy(trackMetadata.tags, track->attributes().tags, AUDIO_ATTRIBUTES_TAGS_MAX_SIZE);
10856 metadata.tracks.push_back(trackMetadata);
Kevin Rocard069c2712018-03-29 19:09:14 -070010857 }
10858 mOutput->stream->updateSourceMetadata(metadata);
Vlad Popa7e81cea2023-01-19 16:34:16 +010010859
10860 MetadataUpdate change;
10861 change.playbackMetadataUpdate = metadata.tracks;
10862 return change;
10863};
Kevin Rocard069c2712018-03-29 19:09:14 -070010864
Andy Hungee58e4a2023-07-07 13:47:37 -070010865void MmapPlaybackThread::checkSilentMode_l()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010866{
10867 if (!mMasterMute) {
10868 char value[PROPERTY_VALUE_MAX];
10869 if (property_get("ro.audio.silent", value, "0") > 0) {
10870 char *endptr;
10871 unsigned long ul = strtoul(value, &endptr, 0);
10872 if (*endptr == '\0' && ul != 0) {
10873 ALOGD("Silence is golden");
10874 // The setprop command will not allow a property to be changed after
10875 // the first time it is set, so we don't have to worry about un-muting.
10876 setMasterMute_l(true);
10877 }
10878 }
10879 }
10880}
10881
Andy Hungee58e4a2023-07-07 13:47:37 -070010882void MmapPlaybackThread::toAudioPortConfig(struct audio_port_config* config)
Mikhail Naganov32abc2b2018-05-24 12:57:11 -070010883{
10884 MmapThread::toAudioPortConfig(config);
10885 if (mOutput && mOutput->flags != AUDIO_OUTPUT_FLAG_NONE) {
10886 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
10887 config->flags.output = mOutput->flags;
10888 }
10889}
10890
Andy Hungee58e4a2023-07-07 13:47:37 -070010891status_t MmapPlaybackThread::getExternalPosition(uint64_t* position,
Andy Hung440901d2023-06-29 21:19:25 -070010892 int64_t* timeNanos) const
jiabinb7d8c5a2020-08-26 17:24:52 -070010893{
10894 if (mOutput == nullptr) {
10895 return NO_INIT;
10896 }
10897 struct timespec timestamp;
10898 status_t status = mOutput->getPresentationPosition(position, &timestamp);
10899 if (status == NO_ERROR) {
10900 *timeNanos = timestamp.tv_sec * NANOS_PER_SECOND + timestamp.tv_nsec;
10901 }
10902 return status;
10903}
10904
Andy Hungee58e4a2023-07-07 13:47:37 -070010905status_t MmapPlaybackThread::reportData(const void* buffer, size_t frameCount) {
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010010906 // Send to MelProcessor for sound dose measurement.
10907 auto processor = mMelProcessor.load();
10908 if (processor) {
10909 processor->process(buffer, frameCount * mFrameSize);
10910 }
10911
jiabinfc791ee2023-02-15 19:43:40 +000010912 return NO_ERROR;
10913}
10914
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010010915// startMelComputation_l() must be called with AudioFlinger::mLock held
Andy Hungee58e4a2023-07-07 13:47:37 -070010916void MmapPlaybackThread::startMelComputation_l(
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010010917 const sp<audio_utils::MelProcessor>& processor)
10918{
10919 ALOGV("%s: starting mel processor for thread %d", __func__, id());
Vlad Popa1c2f7e12023-03-28 02:08:56 +020010920 mMelProcessor.store(processor);
10921 if (processor) {
10922 processor->resume();
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010010923 }
Vlad Popa1c2f7e12023-03-28 02:08:56 +020010924
10925 // no need to update output format for MMapPlaybackThread since it is
10926 // assigned constant for each thread
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010010927}
10928
10929// stopMelComputation_l() must be called with AudioFlinger::mLock held
Andy Hungee58e4a2023-07-07 13:47:37 -070010930void MmapPlaybackThread::stopMelComputation_l()
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010010931{
Vlad Popa1c2f7e12023-03-28 02:08:56 +020010932 ALOGV("%s: pausing mel processor for thread %d", __func__, id());
10933 auto melProcessor = mMelProcessor.load();
10934 if (melProcessor != nullptr) {
10935 melProcessor->pause();
10936 }
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010010937}
10938
Andy Hungee58e4a2023-07-07 13:47:37 -070010939void MmapPlaybackThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010940{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -070010941 MmapThread::dumpInternals_l(fd, args);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010942
Glenn Kastend3bb6452016-12-05 18:14:37 -080010943 dprintf(fd, " Stream type: %d Stream volume: %f HAL volume: %f Stream mute %d\n",
Eric Laurent1f9b5e62023-07-03 18:14:07 +020010944 mStreamType, streamVolume_l(), mHalVolFloat, streamMuted_l());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010945 dprintf(fd, " Master volume: %f Master mute %d\n", mMasterVolume, mMasterMute);
10946}
10947
Andy Hungee58e4a2023-07-07 13:47:37 -070010948/* static */
10949sp<IAfMmapCaptureThread> IAfMmapCaptureThread::create(
Andy Hung583043b2023-07-17 17:05:00 -070010950 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
Andy Hungee58e4a2023-07-07 13:47:37 -070010951 AudioHwDevice* hwDev, AudioStreamIn* input, bool systemReady) {
Andy Hung583043b2023-07-17 17:05:00 -070010952 return sp<MmapCaptureThread>::make(afThreadCallback, id, hwDev, input, systemReady);
Andy Hungee58e4a2023-07-07 13:47:37 -070010953}
10954
10955MmapCaptureThread::MmapCaptureThread(
Andy Hung583043b2023-07-17 17:05:00 -070010956 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
jiabinc52b1ff2019-10-31 17:20:42 -070010957 AudioHwDevice *hwDev, AudioStreamIn *input, bool systemReady)
Andy Hung583043b2023-07-17 17:05:00 -070010958 : MmapThread(afThreadCallback, id, hwDev, input->stream, systemReady, false /* isOut */),
Eric Laurent6acd1d42017-01-04 14:23:29 -080010959 mInput(input)
10960{
10961 snprintf(mThreadName, kThreadNameLength, "AudioMmapIn_%X", id);
10962 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
10963}
10964
Andy Hungee58e4a2023-07-07 13:47:37 -070010965status_t MmapCaptureThread::exitStandby_l()
Eric Laurent331679c2018-04-16 17:03:16 -070010966{
Phil Burkf054fc32018-12-06 09:45:59 -080010967 {
10968 // mInput might have been cleared by clearInput()
Phil Burkf054fc32018-12-06 09:45:59 -080010969 if (mInput != nullptr && mInput->stream != nullptr) {
10970 mInput->stream->setGain(1.0f);
10971 }
10972 }
Eric Laurentdda206a2022-07-08 17:28:35 +020010973 return MmapThread::exitStandby_l();
Eric Laurent331679c2018-04-16 17:03:16 -070010974}
10975
Andy Hungee58e4a2023-07-07 13:47:37 -070010976AudioStreamIn* MmapCaptureThread::clearInput()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010977{
10978 Mutex::Autolock _l(mLock);
10979 AudioStreamIn *input = mInput;
10980 mInput = NULL;
10981 return input;
10982}
Kevin Rocard069c2712018-03-29 19:09:14 -070010983
Andy Hungee58e4a2023-07-07 13:47:37 -070010984void MmapCaptureThread::processVolume_l()
Eric Laurent331679c2018-04-16 17:03:16 -070010985{
10986 bool changed = false;
10987 bool silenced = false;
10988
10989 sp<MmapStreamCallback> callback = mCallback.promote();
10990 if (callback == 0) {
10991 if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
10992 ALOGW("Could not set MMAP stream silenced: no onStreamSilenced callback!");
10993 mNoCallbackWarningCount++;
10994 }
10995 }
10996
10997 // After a change occurred in track silenced state, mute capture in audio DSP if at least one
10998 // track is silenced and unmute otherwise
10999 for (size_t i = 0; i < mActiveTracks.size() && !silenced; i++) {
11000 if (!mActiveTracks[i]->getAndSetSilencedNotified_l()) {
11001 changed = true;
11002 silenced = mActiveTracks[i]->isSilenced_l();
11003 }
11004 }
11005
11006 if (changed) {
11007 mInput->stream->setGain(silenced ? 0.0f: 1.0f);
11008 }
11009}
11010
Andy Hungee58e4a2023-07-07 13:47:37 -070011011ThreadBase::MetadataUpdate MmapCaptureThread::updateMetadata_l()
Kevin Rocard069c2712018-03-29 19:09:14 -070011012{
Jasmine Chaeaa10e42021-05-11 10:11:14 +080011013 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
Vlad Popa7e81cea2023-01-19 16:34:16 +010011014 return {}; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -070011015 }
11016 StreamInHalInterface::SinkMetadata metadata;
Andy Hung8d31fd22023-06-26 19:20:57 -070011017 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Kevin Rocard069c2712018-03-29 19:09:14 -070011018 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurent94579172020-11-20 18:41:04 +010011019 record_track_metadata_v7_t trackMetadata;
11020 trackMetadata.base = {
Kevin Rocard069c2712018-03-29 19:09:14 -070011021 .source = track->attributes().source,
11022 .gain = 1, // capture tracks do not have volumes
Eric Laurent94579172020-11-20 18:41:04 +010011023 };
11024 trackMetadata.channel_mask = track->channelMask(),
11025 strncpy(trackMetadata.tags, track->attributes().tags, AUDIO_ATTRIBUTES_TAGS_MAX_SIZE);
11026 metadata.tracks.push_back(trackMetadata);
Kevin Rocard069c2712018-03-29 19:09:14 -070011027 }
11028 mInput->stream->updateSinkMetadata(metadata);
Vlad Popa7e81cea2023-01-19 16:34:16 +010011029 MetadataUpdate change;
11030 change.recordMetadataUpdate = metadata.tracks;
11031 return change;
Kevin Rocard069c2712018-03-29 19:09:14 -070011032}
11033
Andy Hungee58e4a2023-07-07 13:47:37 -070011034void MmapCaptureThread::setRecordSilenced(audio_port_handle_t portId, bool silenced)
Eric Laurent331679c2018-04-16 17:03:16 -070011035{
11036 Mutex::Autolock _l(mLock);
11037 for (size_t i = 0; i < mActiveTracks.size() ; i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -070011038 if (mActiveTracks[i]->portId() == portId) {
Eric Laurent331679c2018-04-16 17:03:16 -070011039 mActiveTracks[i]->setSilenced_l(silenced);
11040 broadcast_l();
11041 }
11042 }
jiabin09609032022-06-15 19:26:01 +000011043 setClientSilencedIfExists_l(portId, silenced);
Eric Laurent331679c2018-04-16 17:03:16 -070011044}
11045
Andy Hungee58e4a2023-07-07 13:47:37 -070011046void MmapCaptureThread::toAudioPortConfig(struct audio_port_config* config)
Mikhail Naganov32abc2b2018-05-24 12:57:11 -070011047{
11048 MmapThread::toAudioPortConfig(config);
11049 if (mInput && mInput->flags != AUDIO_INPUT_FLAG_NONE) {
11050 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
11051 config->flags.input = mInput->flags;
11052 }
11053}
11054
Andy Hungee58e4a2023-07-07 13:47:37 -070011055status_t MmapCaptureThread::getExternalPosition(
Andy Hung440901d2023-06-29 21:19:25 -070011056 uint64_t* position, int64_t* timeNanos) const
jiabinb7d8c5a2020-08-26 17:24:52 -070011057{
11058 if (mInput == nullptr) {
11059 return NO_INIT;
11060 }
11061 return mInput->getCapturePosition((int64_t*)position, timeNanos);
11062}
11063
jiabinc658e452022-10-21 20:52:21 +000011064// ----------------------------------------------------------------------------
11065
Andy Hungee58e4a2023-07-07 13:47:37 -070011066/* static */
11067sp<IAfPlaybackThread> IAfPlaybackThread::createBitPerfectThread(
Andy Hung583043b2023-07-17 17:05:00 -070011068 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hungee58e4a2023-07-07 13:47:37 -070011069 AudioStreamOut* output, audio_io_handle_t id, bool systemReady) {
Andy Hung583043b2023-07-17 17:05:00 -070011070 return sp<BitPerfectThread>::make(afThreadCallback, output, id, systemReady);
Andy Hungee58e4a2023-07-07 13:47:37 -070011071}
11072
Andy Hung583043b2023-07-17 17:05:00 -070011073BitPerfectThread::BitPerfectThread(const sp<IAfThreadCallback> &afThreadCallback,
jiabinc658e452022-10-21 20:52:21 +000011074 AudioStreamOut *output, audio_io_handle_t id, bool systemReady)
Andy Hung583043b2023-07-17 17:05:00 -070011075 : MixerThread(afThreadCallback, output, id, systemReady, BIT_PERFECT) {}
jiabinc658e452022-10-21 20:52:21 +000011076
Andy Hungee58e4a2023-07-07 13:47:37 -070011077PlaybackThread::mixer_state BitPerfectThread::prepareTracks_l(
Andy Hung8d31fd22023-06-26 19:20:57 -070011078 Vector<sp<IAfTrack>>* tracksToRemove) {
jiabinc658e452022-10-21 20:52:21 +000011079 mixer_state result = MixerThread::prepareTracks_l(tracksToRemove);
11080 // If there is only one active track and it is bit-perfect, enable tee buffer.
jiabin76d94692022-12-15 21:51:21 +000011081 float volumeLeft = 1.0f;
11082 float volumeRight = 1.0f;
jiabinc658e452022-10-21 20:52:21 +000011083 if (mActiveTracks.size() == 1 && mActiveTracks[0]->isBitPerfect()) {
11084 const int trackId = mActiveTracks[0]->id();
11085 mAudioMixer->setParameter(
11086 trackId, AudioMixer::TRACK, AudioMixer::TEE_BUFFER, (void *)mSinkBuffer);
11087 mAudioMixer->setParameter(
11088 trackId, AudioMixer::TRACK, AudioMixer::TEE_BUFFER_FRAME_COUNT,
11089 (void *)(uintptr_t)mNormalFrameCount);
jiabin76d94692022-12-15 21:51:21 +000011090 mActiveTracks[0]->getFinalVolume(&volumeLeft, &volumeRight);
jiabinc658e452022-10-21 20:52:21 +000011091 mIsBitPerfect = true;
11092 } else {
11093 mIsBitPerfect = false;
11094 // No need to copy bit-perfect data directly to sink buffer given there are multiple tracks
11095 // active.
11096 for (const auto& track : mActiveTracks) {
11097 const int trackId = track->id();
11098 mAudioMixer->setParameter(
11099 trackId, AudioMixer::TRACK, AudioMixer::TEE_BUFFER, nullptr);
11100 }
11101 }
jiabin76d94692022-12-15 21:51:21 +000011102 if (mVolumeLeft != volumeLeft || mVolumeRight != volumeRight) {
11103 mVolumeLeft = volumeLeft;
11104 mVolumeRight = volumeRight;
11105 setVolumeForOutput_l(volumeLeft, volumeRight);
11106 }
jiabinc658e452022-10-21 20:52:21 +000011107 return result;
11108}
11109
Andy Hungee58e4a2023-07-07 13:47:37 -070011110void BitPerfectThread::threadLoop_mix() {
jiabinc658e452022-10-21 20:52:21 +000011111 MixerThread::threadLoop_mix();
11112 mHasDataCopiedToSinkBuffer = mIsBitPerfect;
11113}
11114
Glenn Kasten63238ef2015-03-02 15:50:29 -080011115} // namespace android