blob: 77e242163fd4d461a87157a6f9b556632a1c75ef [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"
20//#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>
jiabinf6eb4c32020-02-25 14:06:25 -080047#include <audio_utils/Metadata.h>
jiabin245cdd92018-12-07 17:55:15 -080048#include <audio_utils/channels.h>
Glenn Kasten6bf707f2017-02-23 16:53:58 -080049#include <audio_utils/mono_blend.h>
Eric Laurent81784c32012-11-19 14:55:58 -080050#include <audio_utils/primitives.h>
Andy Hung98ef9782014-03-04 14:46:50 -080051#include <audio_utils/format.h>
Glenn Kastenc56f3422014-03-21 17:53:17 -070052#include <audio_utils/minifloat.h>
Hongwei Wang95e37682019-04-12 11:13:36 -070053#include <audio_utils/safe_math.h>
Mikhail Naganov9fe94012016-10-14 14:57:40 -070054#include <system/audio_effects/effect_aec.h>
Eric Laurentb3f315a2021-07-13 15:09:05 +020055#include <system/audio_effects/effect_downmix.h>
56#include <system/audio_effects/effect_ns.h>
Eric Laurent1c5e2e32021-08-18 18:50:28 +020057#include <system/audio_effects/effect_spatializer.h>
Mikhail Naganovcbc8f612016-10-11 18:05:13 -070058#include <system/audio.h>
Eric Laurent81784c32012-11-19 14:55:58 -080059
60// NBAIO implementations
Glenn Kasten6dbb5e32014-05-13 10:38:42 -070061#include <media/nbaio/AudioStreamInSource.h>
Eric Laurent81784c32012-11-19 14:55:58 -080062#include <media/nbaio/AudioStreamOutSink.h>
63#include <media/nbaio/MonoPipe.h>
64#include <media/nbaio/MonoPipeReader.h>
65#include <media/nbaio/Pipe.h>
66#include <media/nbaio/PipeReader.h>
67#include <media/nbaio/SourceAudioBufferProvider.h>
Wei Jia3f273d12015-11-24 09:06:49 -080068#include <mediautils/BatteryNotifier.h>
Andy Hungafc51db2022-04-08 17:33:40 -070069#include <mediautils/Process.h>
Eric Laurent81784c32012-11-19 14:55:58 -080070
Mikhail Naganov2996f672019-04-18 12:29:59 -070071#include <audiomanager/AudioManager.h>
Eric Laurent81784c32012-11-19 14:55:58 -080072#include <powermanager/PowerManager.h>
73
Kevin Rocard7588ff42018-01-08 11:11:30 -080074#include <media/audiohal/EffectsFactoryHalInterface.h>
Kevin Rocard069c2712018-03-29 19:09:14 -070075#include <media/audiohal/StreamHalInterface.h>
Kevin Rocard7588ff42018-01-08 11:11:30 -080076
Eric Laurent81784c32012-11-19 14:55:58 -080077#include "AudioFlinger.h"
Eric Laurent81784c32012-11-19 14:55:58 -080078#include "FastMixer.h"
Glenn Kasten6dbb5e32014-05-13 10:38:42 -070079#include "FastCapture.h"
Andy Hungab7ef302018-05-15 19:35:29 -070080#include <mediautils/SchedulingPolicyService.h>
81#include <mediautils/ServiceUtilities.h>
Eric Laurent81784c32012-11-19 14:55:58 -080082
Eric Laurent81784c32012-11-19 14:55:58 -080083#ifdef ADD_BATTERY_DATA
84#include <media/IMediaPlayerService.h>
85#include <media/IMediaDeathNotifier.h>
86#endif
87
Eric Laurent81784c32012-11-19 14:55:58 -080088#ifdef DEBUG_CPU_USAGE
Eric Tan5b13ff82018-07-27 11:20:17 -070089#include <audio_utils/Statistics.h>
Eric Laurent81784c32012-11-19 14:55:58 -080090#include <cpustats/ThreadCpuUsage.h>
91#endif
92
Glenn Kastenc05b8d72016-03-24 09:48:17 -070093#include "AutoPark.h"
94
Nicolas Rouletfe1e1442017-01-30 12:02:03 -080095#include <pthread.h>
96#include "TypedLogger.h"
97
Eric Laurent81784c32012-11-19 14:55:58 -080098// ----------------------------------------------------------------------------
99
100// Note: the following macro is used for extremely verbose logging message. In
101// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
102// 0; but one side effect of this is to turn all LOGV's as well. Some messages
103// are so verbose that we want to suppress them even when we have ALOG_ASSERT
104// turned on. Do not uncomment the #def below unless you really know what you
105// are doing and want to see all of the extremely verbose messages.
106//#define VERY_VERY_VERBOSE_LOGGING
107#ifdef VERY_VERY_VERBOSE_LOGGING
108#define ALOGVV ALOGV
109#else
110#define ALOGVV(a...) do { } while(0)
111#endif
112
Andy Hung6770c6f2015-04-07 13:43:36 -0700113// TODO: Move these macro/inlines to a header file.
Glenn Kasten49d00ad2014-07-21 11:22:03 -0700114#define max(a, b) ((a) > (b) ? (a) : (b))
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700115
Andy Hung6770c6f2015-04-07 13:43:36 -0700116template <typename T>
117static inline T min(const T& a, const T& b)
118{
119 return a < b ? a : b;
120}
Glenn Kasten49d00ad2014-07-21 11:22:03 -0700121
Eric Laurent81784c32012-11-19 14:55:58 -0800122namespace android {
123
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -0700124using media::IEffectClient;
Svet Ganov33761132021-05-13 22:51:08 +0000125using content::AttributionSourceState;
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -0700126
Eric Laurent81784c32012-11-19 14:55:58 -0800127// retry counts for buffer fill timeout
128// 50 * ~20msecs = 1 second
129static const int8_t kMaxTrackRetries = 50;
130static const int8_t kMaxTrackStartupRetries = 50;
Andy Hung455982f2021-04-27 17:46:12 -0700131
Eric Laurent81784c32012-11-19 14:55:58 -0800132// allow less retry attempts on direct output thread.
133// direct outputs can be a scarce resource in audio hardware and should
134// be released as quickly as possible.
Andy Hung455982f2021-04-27 17:46:12 -0700135// Notes:
136// 1) The retry duration kMaxTrackRetriesDirectMs may be increased
137// in case the data write is bursty for the AudioTrack. The application
138// should endeavor to write at least once every kMaxTrackRetriesDirectMs
139// to prevent an underrun situation. If the data is bursty, then
140// the application can also throttle the data sent to be even.
141// 2) For compressed audio data, any data present in the AudioTrack buffer
142// will be sent and reset the retry count. This delivers data as
143// it arrives, with approximately kDirectMinSleepTimeUs = 10ms checking interval.
144// 3) For linear PCM or proportional PCM, we wait one period for a period's worth
145// of data to be available, then any remaining data is delivered.
146// This is required to ensure the last bit of data is delivered before underrun.
147//
148// Sleep time per cycle is kDirectMinSleepTimeUs for compressed tracks
149// or the size of the HAL period for proportional / linear PCM tracks.
150static const int32_t kMaxTrackRetriesDirectMs = 200;
Eric Laurent81784c32012-11-19 14:55:58 -0800151
152// don't warn about blocked writes or record buffer overflows more often than this
153static const nsecs_t kWarningThrottleNs = seconds(5);
154
155// RecordThread loop sleep time upon application overrun or audio HAL read error
156static const int kRecordThreadSleepUs = 5000;
157
Eric Laurent10351942014-05-08 18:49:52 -0700158// maximum time to wait in sendConfigEvent_l() for a status to be received
159static const nsecs_t kConfigEventTimeoutNs = seconds(2);
Eric Laurent81784c32012-11-19 14:55:58 -0800160
161// minimum sleep time for the mixer thread loop when tracks are active but in underrun
162static const uint32_t kMinThreadSleepTimeUs = 5000;
163// maximum divider applied to the active sleep time in the mixer thread loop
164static const uint32_t kMaxThreadSleepTimeShift = 2;
165
Andy Hung09a50072014-02-27 14:30:47 -0800166// minimum normal sink buffer size, expressed in milliseconds rather than frames
Glenn Kasteneb9487e2015-07-22 09:15:17 -0700167// FIXME This should be based on experimentally observed scheduling jitter
Andy Hung09a50072014-02-27 14:30:47 -0800168static const uint32_t kMinNormalSinkBufferSizeMs = 20;
169// maximum normal sink buffer size
170static const uint32_t kMaxNormalSinkBufferSizeMs = 24;
Eric Laurent81784c32012-11-19 14:55:58 -0800171
Glenn Kasteneb9487e2015-07-22 09:15:17 -0700172// minimum capture buffer size in milliseconds to _not_ need a fast capture thread
173// FIXME This should be based on experimentally observed scheduling jitter
174static const uint32_t kMinNormalCaptureBufferSizeMs = 12;
175
Eric Laurent972a1732013-09-04 09:42:59 -0700176// Offloaded output thread standby delay: allows track transition without going to standby
177static const nsecs_t kOffloadStandbyDelayNs = seconds(1);
178
Eric Laurent51716182016-02-29 18:00:56 -0800179// Direct output thread minimum sleep time in idle or active(underrun) state
180static const nsecs_t kDirectMinSleepTimeUs = 10000;
181
Brian Lindahl65e90012022-07-27 18:01:07 +0200182// Minimum amount of time between checking to see if the timestamp is advancing
183// for underrun detection. If we check too frequently, we may not detect a
184// timestamp update and will falsely detect underrun.
185static const nsecs_t kMinimumTimeBetweenTimestampChecksNs = 150 /* ms */ * 1000;
186
Glenn Kasten1b291842016-07-18 14:55:21 -0700187// The universal constant for ubiquitous 20ms value. The value of 20ms seems to provide a good
188// balance between power consumption and latency, and allows threads to be scheduled reliably
189// by the CFS scheduler.
190// FIXME Express other hardcoded references to 20ms with references to this constant and move
191// it appropriately.
192#define FMS_20 20
Eric Laurent51716182016-02-29 18:00:56 -0800193
Eric Laurent81784c32012-11-19 14:55:58 -0800194// Whether to use fast mixer
195static const enum {
196 FastMixer_Never, // never initialize or use: for debugging only
197 FastMixer_Always, // always initialize and use, even if not needed: for debugging only
198 // normal mixer multiplier is 1
199 FastMixer_Static, // initialize if needed, then use all the time if initialized,
200 // multiplier is calculated based on min & max normal mixer buffer size
201 FastMixer_Dynamic, // initialize if needed, then use dynamically depending on track load,
202 // multiplier is calculated based on min & max normal mixer buffer size
203 // FIXME for FastMixer_Dynamic:
204 // Supporting this option will require fixing HALs that can't handle large writes.
205 // For example, one HAL implementation returns an error from a large write,
206 // and another HAL implementation corrupts memory, possibly in the sample rate converter.
207 // We could either fix the HAL implementations, or provide a wrapper that breaks
208 // up large writes into smaller ones, and the wrapper would need to deal with scheduler.
209} kUseFastMixer = FastMixer_Static;
210
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700211// Whether to use fast capture
212static const enum {
213 FastCapture_Never, // never initialize or use: for debugging only
214 FastCapture_Always, // always initialize and use, even if not needed: for debugging only
215 FastCapture_Static, // initialize if needed, then use all the time if initialized
216} kUseFastCapture = FastCapture_Static;
217
Eric Laurent81784c32012-11-19 14:55:58 -0800218// Priorities for requestPriority
219static const int kPriorityAudioApp = 2;
220static const int kPriorityFastMixer = 3;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700221static const int kPriorityFastCapture = 3;
Eric Laurent81784c32012-11-19 14:55:58 -0800222
Glenn Kastenea38ee72016-04-18 11:08:01 -0700223// IAudioFlinger::createTrack() has an in/out parameter 'pFrameCount' for the total size of the
224// track buffer in shared memory. Zero on input means to use a default value. For fast tracks,
225// AudioFlinger derives the default from HAL buffer size and 'fast track multiplier'.
Glenn Kasten03490092014-05-27 12:30:54 -0700226
227// This is the default value, if not specified by property.
Glenn Kastenb5fed682013-12-03 09:06:43 -0800228static const int kFastTrackMultiplier = 2;
Eric Laurent81784c32012-11-19 14:55:58 -0800229
Glenn Kasten03490092014-05-27 12:30:54 -0700230// The minimum and maximum allowed values
231static const int kFastTrackMultiplierMin = 1;
232static const int kFastTrackMultiplierMax = 2;
233
234// The actual value to use, which can be specified per-device via property af.fast_track_multiplier.
235static int sFastTrackMultiplier = kFastTrackMultiplier;
236
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700237// See Thread::readOnlyHeap().
238// Initially this heap is used to allocate client buffers for "fast" AudioRecord.
239// Eventually it will be the single buffer that FastCapture writes into via HAL read(),
240// and that all "fast" AudioRecord clients read from. In either case, the size can be small.
Mikhail Naganov79a77822018-05-10 15:57:25 -0700241static const size_t kRecordThreadReadOnlyHeapSize = 0xD000;
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700242
Eric Laurent81784c32012-11-19 14:55:58 -0800243// ----------------------------------------------------------------------------
244
Andy Hungb68f5eb2019-12-03 16:49:17 -0800245// TODO: move all toString helpers to audio.h
246// under #ifdef __cplusplus #endif
247static std::string patchSinksToString(const struct audio_patch *patch)
248{
249 std::stringstream ss;
250 for (size_t i = 0; i < patch->num_sinks; ++i) {
Andy Hungc2b11cb2020-04-22 09:04:01 -0700251 if (i > 0) {
252 ss << "|";
253 }
Andy Hungb68f5eb2019-12-03 16:49:17 -0800254 ss << "(" << toString(patch->sinks[i].ext.device.type)
255 << ", " << patch->sinks[i].ext.device.address << ")";
256 }
257 return ss.str();
258}
259
260static std::string patchSourcesToString(const struct audio_patch *patch)
261{
262 std::stringstream ss;
263 for (size_t i = 0; i < patch->num_sources; ++i) {
Andy Hungc2b11cb2020-04-22 09:04:01 -0700264 if (i > 0) {
265 ss << "|";
266 }
Andy Hungb68f5eb2019-12-03 16:49:17 -0800267 ss << "(" << toString(patch->sources[i].ext.device.type)
268 << ", " << patch->sources[i].ext.device.address << ")";
269 }
270 return ss.str();
271}
272
Glenn Kasten03490092014-05-27 12:30:54 -0700273static pthread_once_t sFastTrackMultiplierOnce = PTHREAD_ONCE_INIT;
274
275static void sFastTrackMultiplierInit()
276{
277 char value[PROPERTY_VALUE_MAX];
278 if (property_get("af.fast_track_multiplier", value, NULL) > 0) {
279 char *endptr;
280 unsigned long ul = strtoul(value, &endptr, 0);
281 if (*endptr == '\0' && kFastTrackMultiplierMin <= ul && ul <= kFastTrackMultiplierMax) {
282 sFastTrackMultiplier = (int) ul;
283 }
284 }
285}
286
287// ----------------------------------------------------------------------------
288
Eric Laurent81784c32012-11-19 14:55:58 -0800289#ifdef ADD_BATTERY_DATA
290// To collect the amplifier usage
291static void addBatteryData(uint32_t params) {
292 sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService();
293 if (service == NULL) {
294 // it already logged
295 return;
296 }
297
298 service->addBatteryData(params);
299}
300#endif
301
Andy Hung3f0c9022016-01-15 17:49:46 -0800302// Track the CLOCK_BOOTTIME versus CLOCK_MONOTONIC timebase offset
303struct {
304 // call when you acquire a partial wakelock
305 void acquire(const sp<IBinder> &wakeLockToken) {
306 pthread_mutex_lock(&mLock);
307 if (wakeLockToken.get() == nullptr) {
308 adjustTimebaseOffset(&mBoottimeOffset, ExtendedTimestamp::TIMEBASE_BOOTTIME);
309 } else {
310 if (mCount == 0) {
311 adjustTimebaseOffset(&mBoottimeOffset, ExtendedTimestamp::TIMEBASE_BOOTTIME);
312 }
313 ++mCount;
314 }
315 pthread_mutex_unlock(&mLock);
316 }
317
318 // call when you release a partial wakelock.
319 void release(const sp<IBinder> &wakeLockToken) {
320 if (wakeLockToken.get() == nullptr) {
321 return;
322 }
323 pthread_mutex_lock(&mLock);
324 if (--mCount < 0) {
325 ALOGE("negative wakelock count");
326 mCount = 0;
327 }
328 pthread_mutex_unlock(&mLock);
329 }
330
331 // retrieves the boottime timebase offset from monotonic.
332 int64_t getBoottimeOffset() {
333 pthread_mutex_lock(&mLock);
334 int64_t boottimeOffset = mBoottimeOffset;
335 pthread_mutex_unlock(&mLock);
336 return boottimeOffset;
337 }
338
339 // Adjusts the timebase offset between TIMEBASE_MONOTONIC
340 // and the selected timebase.
341 // Currently only TIMEBASE_BOOTTIME is allowed.
342 //
343 // This only needs to be called upon acquiring the first partial wakelock
344 // after all other partial wakelocks are released.
345 //
346 // We do an empirical measurement of the offset rather than parsing
347 // /proc/timer_list since the latter is not a formal kernel ABI.
348 static void adjustTimebaseOffset(int64_t *offset, ExtendedTimestamp::Timebase timebase) {
349 int clockbase;
350 switch (timebase) {
351 case ExtendedTimestamp::TIMEBASE_BOOTTIME:
352 clockbase = SYSTEM_TIME_BOOTTIME;
353 break;
354 default:
355 LOG_ALWAYS_FATAL("invalid timebase %d", timebase);
356 break;
357 }
358 // try three times to get the clock offset, choose the one
359 // with the minimum gap in measurements.
360 const int tries = 3;
361 nsecs_t bestGap, measured;
362 for (int i = 0; i < tries; ++i) {
363 const nsecs_t tmono = systemTime(SYSTEM_TIME_MONOTONIC);
364 const nsecs_t tbase = systemTime(clockbase);
365 const nsecs_t tmono2 = systemTime(SYSTEM_TIME_MONOTONIC);
366 const nsecs_t gap = tmono2 - tmono;
367 if (i == 0 || gap < bestGap) {
368 bestGap = gap;
369 measured = tbase - ((tmono + tmono2) >> 1);
370 }
371 }
372
373 // to avoid micro-adjusting, we don't change the timebase
374 // unless it is significantly different.
375 //
376 // Assumption: It probably takes more than toleranceNs to
377 // suspend and resume the device.
378 static int64_t toleranceNs = 10000; // 10 us
379 if (llabs(*offset - measured) > toleranceNs) {
380 ALOGV("Adjusting timebase offset old: %lld new: %lld",
381 (long long)*offset, (long long)measured);
382 *offset = measured;
383 }
384 }
385
386 pthread_mutex_t mLock;
387 int32_t mCount;
388 int64_t mBoottimeOffset;
389} gBoottime = { PTHREAD_MUTEX_INITIALIZER, 0, 0 }; // static, so use POD initialization
Eric Laurent81784c32012-11-19 14:55:58 -0800390
391// ----------------------------------------------------------------------------
392// CPU Stats
393// ----------------------------------------------------------------------------
394
395class CpuStats {
396public:
397 CpuStats();
398 void sample(const String8 &title);
399#ifdef DEBUG_CPU_USAGE
400private:
401 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns
Andy Hung16698b82018-08-01 10:48:38 -0700402 audio_utils::Statistics<double> mWcStats; // statistics on thread CPU usage in wall clock ns
Eric Laurent81784c32012-11-19 14:55:58 -0800403
Andy Hung16698b82018-08-01 10:48:38 -0700404 audio_utils::Statistics<double> mHzStats; // statistics on thread CPU usage in cycles
Eric Laurent81784c32012-11-19 14:55:58 -0800405
406 int mCpuNum; // thread's current CPU number
407 int mCpukHz; // frequency of thread's current CPU in kHz
408#endif
409};
410
411CpuStats::CpuStats()
412#ifdef DEBUG_CPU_USAGE
413 : mCpuNum(-1), mCpukHz(-1)
414#endif
415{
416}
417
Glenn Kasten0f11b512014-01-31 16:18:54 -0800418void CpuStats::sample(const String8 &title
419#ifndef DEBUG_CPU_USAGE
420 __unused
421#endif
422 ) {
Eric Laurent81784c32012-11-19 14:55:58 -0800423#ifdef DEBUG_CPU_USAGE
424 // get current thread's delta CPU time in wall clock ns
425 double wcNs;
426 bool valid = mCpuUsage.sampleAndEnable(wcNs);
427
428 // record sample for wall clock statistics
429 if (valid) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700430 mWcStats.add(wcNs);
Eric Laurent81784c32012-11-19 14:55:58 -0800431 }
432
433 // get the current CPU number
434 int cpuNum = sched_getcpu();
435
436 // get the current CPU frequency in kHz
437 int cpukHz = mCpuUsage.getCpukHz(cpuNum);
438
439 // check if either CPU number or frequency changed
440 if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
441 mCpuNum = cpuNum;
442 mCpukHz = cpukHz;
443 // ignore sample for purposes of cycles
444 valid = false;
445 }
446
447 // if no change in CPU number or frequency, then record sample for cycle statistics
448 if (valid && mCpukHz > 0) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700449 const double cycles = wcNs * cpukHz * 0.000001;
450 mHzStats.add(cycles);
Eric Laurent81784c32012-11-19 14:55:58 -0800451 }
452
Eric Tan5b13ff82018-07-27 11:20:17 -0700453 const unsigned n = mWcStats.getN();
Eric Laurent81784c32012-11-19 14:55:58 -0800454 // mCpuUsage.elapsed() is expensive, so don't call it every loop
455 if ((n & 127) == 1) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700456 const long long elapsed = mCpuUsage.elapsed();
Eric Laurent81784c32012-11-19 14:55:58 -0800457 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700458 const double perLoop = elapsed / (double) n;
459 const double perLoop100 = perLoop * 0.01;
460 const double perLoop1k = perLoop * 0.001;
461 const double mean = mWcStats.getMean();
462 const double stddev = mWcStats.getStdDev();
463 const double minimum = mWcStats.getMin();
464 const double maximum = mWcStats.getMax();
465 const double meanCycles = mHzStats.getMean();
466 const double stddevCycles = mHzStats.getStdDev();
467 const double minCycles = mHzStats.getMin();
468 const double maxCycles = mHzStats.getMax();
Eric Laurent81784c32012-11-19 14:55:58 -0800469 mCpuUsage.resetElapsed();
470 mWcStats.reset();
471 mHzStats.reset();
472 ALOGD("CPU usage for %s over past %.1f secs\n"
473 " (%u mixer loops at %.1f mean ms per loop):\n"
474 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
475 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
476 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
477 title.string(),
478 elapsed * .000000001, n, perLoop * .000001,
479 mean * .001,
480 stddev * .001,
481 minimum * .001,
482 maximum * .001,
483 mean / perLoop100,
484 stddev / perLoop100,
485 minimum / perLoop100,
486 maximum / perLoop100,
487 meanCycles / perLoop1k,
488 stddevCycles / perLoop1k,
489 minCycles / perLoop1k,
490 maxCycles / perLoop1k);
491
492 }
493 }
494#endif
495};
496
497// ----------------------------------------------------------------------------
498// ThreadBase
499// ----------------------------------------------------------------------------
500
Glenn Kasten97b7b752014-09-28 13:04:24 -0700501// static
502const char *AudioFlinger::ThreadBase::threadTypeToString(AudioFlinger::ThreadBase::type_t type)
503{
504 switch (type) {
505 case MIXER:
506 return "MIXER";
507 case DIRECT:
508 return "DIRECT";
509 case DUPLICATING:
510 return "DUPLICATING";
511 case RECORD:
512 return "RECORD";
513 case OFFLOAD:
514 return "OFFLOAD";
Andy Hungea840382020-05-05 21:50:17 -0700515 case MMAP_PLAYBACK:
516 return "MMAP_PLAYBACK";
517 case MMAP_CAPTURE:
518 return "MMAP_CAPTURE";
Eric Laurent1c5e2e32021-08-18 18:50:28 +0200519 case SPATIALIZER:
520 return "SPATIALIZER";
Glenn Kasten97b7b752014-09-28 13:04:24 -0700521 default:
522 return "unknown";
523 }
524}
525
Eric Laurent81784c32012-11-19 14:55:58 -0800526AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
Andy Hungcf10d742020-04-28 15:38:24 -0700527 type_t type, bool systemReady, bool isOut)
Eric Laurent81784c32012-11-19 14:55:58 -0800528 : Thread(false /*canCallJava*/),
529 mType(type),
Glenn Kasten9b58f632013-07-16 11:37:48 -0700530 mAudioFlinger(audioFlinger),
Andy Hungcf10d742020-04-28 15:38:24 -0700531 mThreadMetrics(std::string(AMEDIAMETRICS_KEY_PREFIX_AUDIO_THREAD) + std::to_string(id),
532 isOut),
533 mIsOut(isOut),
Glenn Kasten70949c42013-08-06 07:40:12 -0700534 // mSampleRate, mFrameCount, mChannelMask, mChannelCount, mFrameSize, mFormat, mBufferSize
Glenn Kastendeca2ae2014-02-07 10:25:56 -0800535 // are set by PlaybackThread::readOutputParameters_l() or
536 // RecordThread::readInputParameters_l()
Eric Laurentfd477972013-10-25 18:10:40 -0700537 //FIXME: mStandby should be true here. Is this some kind of hack?
jiabinc52b1ff2019-10-31 17:20:42 -0700538 mStandby(false),
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700539 mAudioSource(AUDIO_SOURCE_DEFAULT), mId(id),
Eric Laurent81784c32012-11-19 14:55:58 -0800540 // mName will be set by concrete (non-virtual) subclass
Eric Laurent72e3f392015-05-20 14:43:50 -0700541 mDeathRecipient(new PMDeathRecipient(this)),
Eric Laurent6acd1d42017-01-04 14:23:29 -0800542 mSystemReady(systemReady),
543 mSignalPending(false)
Eric Laurent81784c32012-11-19 14:55:58 -0800544{
Andy Hungcf10d742020-04-28 15:38:24 -0700545 mThreadMetrics.logConstructor(getpid(), threadTypeToString(type), id);
Eric Laurent296fb132015-05-01 11:38:42 -0700546 memset(&mPatch, 0, sizeof(struct audio_patch));
Eric Laurent81784c32012-11-19 14:55:58 -0800547}
548
549AudioFlinger::ThreadBase::~ThreadBase()
550{
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700551 // mConfigEvents should be empty, but just in case it isn't, free the memory it owns
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700552 mConfigEvents.clear();
553
Eric Laurent81784c32012-11-19 14:55:58 -0800554 // do not lock the mutex in destructor
555 releaseWakeLock_l();
556 if (mPowerManager != 0) {
Marco Nelissen06b46062014-11-14 07:58:25 -0800557 sp<IBinder> binder = IInterface::asBinder(mPowerManager);
Eric Laurent81784c32012-11-19 14:55:58 -0800558 binder->unlinkToDeath(mDeathRecipient);
559 }
Andy Hungd0979812019-02-21 15:51:44 -0800560
561 sendStatistics(true /* force */);
Eric Laurent81784c32012-11-19 14:55:58 -0800562}
563
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700564status_t AudioFlinger::ThreadBase::readyToRun()
565{
566 status_t status = initCheck();
567 if (status == NO_ERROR) {
Glenn Kasten1bfe09a2017-02-21 13:05:56 -0800568 ALOGI("AudioFlinger's thread %p tid=%d ready to run", this, getTid());
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700569 } else {
570 ALOGE("No working audio driver found.");
571 }
572 return status;
573}
574
Eric Laurent81784c32012-11-19 14:55:58 -0800575void AudioFlinger::ThreadBase::exit()
576{
577 ALOGV("ThreadBase::exit");
578 // do any cleanup required for exit to succeed
579 preExit();
580 {
581 // This lock prevents the following race in thread (uniprocessor for illustration):
582 // if (!exitPending()) {
583 // // context switch from here to exit()
584 // // exit() calls requestExit(), what exitPending() observes
585 // // exit() calls signal(), which is dropped since no waiters
586 // // context switch back from exit() to here
587 // mWaitWorkCV.wait(...);
588 // // now thread is hung
589 // }
590 AutoMutex lock(mLock);
591 requestExit();
592 mWaitWorkCV.broadcast();
593 }
594 // When Thread::requestExitAndWait is made virtual and this method is renamed to
595 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
596 requestExitAndWait();
597}
598
599status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
600{
Eric Laurent81784c32012-11-19 14:55:58 -0800601 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
602 Mutex::Autolock _l(mLock);
603
Eric Laurent10351942014-05-08 18:49:52 -0700604 return sendSetParameterConfigEvent_l(keyValuePairs);
605}
606
607// sendConfigEvent_l() must be called with ThreadBase::mLock held
608// Can temporarily release the lock if waiting for a reply from processConfigEvents_l().
609status_t AudioFlinger::ThreadBase::sendConfigEvent_l(sp<ConfigEvent>& event)
610{
611 status_t status = NO_ERROR;
612
Eric Laurent72e3f392015-05-20 14:43:50 -0700613 if (event->mRequiresSystemReady && !mSystemReady) {
614 event->mWaitStatus = false;
615 mPendingConfigEvents.add(event);
616 return status;
617 }
Eric Laurent10351942014-05-08 18:49:52 -0700618 mConfigEvents.add(event);
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700619 ALOGV("sendConfigEvent_l() num events %zu event %d", mConfigEvents.size(), event->mType);
Eric Laurent81784c32012-11-19 14:55:58 -0800620 mWaitWorkCV.signal();
Eric Laurent10351942014-05-08 18:49:52 -0700621 mLock.unlock();
622 {
623 Mutex::Autolock _l(event->mLock);
624 while (event->mWaitStatus) {
625 if (event->mCond.waitRelative(event->mLock, kConfigEventTimeoutNs) != NO_ERROR) {
626 event->mStatus = TIMED_OUT;
627 event->mWaitStatus = false;
628 }
629 }
630 status = event->mStatus;
Eric Laurent81784c32012-11-19 14:55:58 -0800631 }
Eric Laurent10351942014-05-08 18:49:52 -0700632 mLock.lock();
Eric Laurent81784c32012-11-19 14:55:58 -0800633 return status;
634}
635
Mikhail Naganov88536df2021-07-26 17:30:29 -0700636void AudioFlinger::ThreadBase::sendIoConfigEvent(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -0700637 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -0800638{
639 Mutex::Autolock _l(mLock);
Eric Laurent09f1ed22019-04-24 17:45:17 -0700640 sendIoConfigEvent_l(event, pid, portId);
Eric Laurent81784c32012-11-19 14:55:58 -0800641}
642
643// sendIoConfigEvent_l() must be called with ThreadBase::mLock held
Mikhail Naganov88536df2021-07-26 17:30:29 -0700644void AudioFlinger::ThreadBase::sendIoConfigEvent_l(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -0700645 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -0800646{
Andy Hungd0979812019-02-21 15:51:44 -0800647 // The audio statistics history is exponentially weighted to forget events
648 // about five or more seconds in the past. In order to have
649 // crisper statistics for mediametrics, we reset the statistics on
650 // an IoConfigEvent, to reflect different properties for a new device.
651 mIoJitterMs.reset();
652 mLatencyMs.reset();
653 mProcessTimeMs.reset();
Robert Wu06db0a32021-08-10 19:05:34 +0000654 mMonopipePipeDepthStats.reset();
Dean Wheatley12473e92021-03-18 23:00:55 +1100655 mTimestampVerifier.discontinuity(mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS);
Andy Hungd0979812019-02-21 15:51:44 -0800656
Eric Laurent09f1ed22019-04-24 17:45:17 -0700657 sp<ConfigEvent> configEvent = (ConfigEvent *)new IoConfigEvent(event, pid, portId);
Eric Laurent10351942014-05-08 18:49:52 -0700658 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800659}
660
Mikhail Naganov83f04272017-02-07 10:45:09 -0800661void AudioFlinger::ThreadBase::sendPrioConfigEvent(pid_t pid, pid_t tid, int32_t prio, bool forApp)
Eric Laurent72e3f392015-05-20 14:43:50 -0700662{
663 Mutex::Autolock _l(mLock);
Mikhail Naganov83f04272017-02-07 10:45:09 -0800664 sendPrioConfigEvent_l(pid, tid, prio, forApp);
Eric Laurent72e3f392015-05-20 14:43:50 -0700665}
666
Eric Laurent81784c32012-11-19 14:55:58 -0800667// sendPrioConfigEvent_l() must be called with ThreadBase::mLock held
Mikhail Naganov83f04272017-02-07 10:45:09 -0800668void AudioFlinger::ThreadBase::sendPrioConfigEvent_l(
669 pid_t pid, pid_t tid, int32_t prio, bool forApp)
Eric Laurent81784c32012-11-19 14:55:58 -0800670{
Mikhail Naganov83f04272017-02-07 10:45:09 -0800671 sp<ConfigEvent> configEvent = (ConfigEvent *)new PrioConfigEvent(pid, tid, prio, forApp);
Eric Laurent10351942014-05-08 18:49:52 -0700672 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800673}
674
Eric Laurent10351942014-05-08 18:49:52 -0700675// sendSetParameterConfigEvent_l() must be called with ThreadBase::mLock held
676status_t AudioFlinger::ThreadBase::sendSetParameterConfigEvent_l(const String8& keyValuePair)
Eric Laurent81784c32012-11-19 14:55:58 -0800677{
Andy Hung2ddee192015-12-18 17:34:44 -0800678 sp<ConfigEvent> configEvent;
679 AudioParameter param(keyValuePair);
680 int value;
Mikhail Naganov00260b52016-10-13 12:54:24 -0700681 if (param.getInt(String8(AudioParameter::keyMonoOutput), value) == NO_ERROR) {
Andy Hung2ddee192015-12-18 17:34:44 -0800682 setMasterMono_l(value != 0);
683 if (param.size() == 1) {
684 return NO_ERROR; // should be a solo parameter - we don't pass down
685 }
Mikhail Naganov00260b52016-10-13 12:54:24 -0700686 param.remove(String8(AudioParameter::keyMonoOutput));
Andy Hung2ddee192015-12-18 17:34:44 -0800687 configEvent = new SetParameterConfigEvent(param.toString());
688 } else {
689 configEvent = new SetParameterConfigEvent(keyValuePair);
690 }
Eric Laurent10351942014-05-08 18:49:52 -0700691 return sendConfigEvent_l(configEvent);
Glenn Kastenf7773312013-08-13 16:00:42 -0700692}
693
Eric Laurent1c333e22014-05-20 10:48:17 -0700694status_t AudioFlinger::ThreadBase::sendCreateAudioPatchConfigEvent(
695 const struct audio_patch *patch,
696 audio_patch_handle_t *handle)
697{
698 Mutex::Autolock _l(mLock);
699 sp<ConfigEvent> configEvent = (ConfigEvent *)new CreateAudioPatchConfigEvent(*patch, *handle);
700 status_t status = sendConfigEvent_l(configEvent);
701 if (status == NO_ERROR) {
702 CreateAudioPatchConfigEventData *data =
703 (CreateAudioPatchConfigEventData *)configEvent->mData.get();
704 *handle = data->mHandle;
705 }
706 return status;
707}
708
709status_t AudioFlinger::ThreadBase::sendReleaseAudioPatchConfigEvent(
710 const audio_patch_handle_t handle)
711{
712 Mutex::Autolock _l(mLock);
713 sp<ConfigEvent> configEvent = (ConfigEvent *)new ReleaseAudioPatchConfigEvent(handle);
714 return sendConfigEvent_l(configEvent);
715}
716
jiabinc52b1ff2019-10-31 17:20:42 -0700717status_t AudioFlinger::ThreadBase::sendUpdateOutDeviceConfigEvent(
718 const DeviceDescriptorBaseVector& outDevices)
719{
720 if (type() != RECORD) {
721 // The update out device operation is only for record thread.
722 return INVALID_OPERATION;
723 }
724 Mutex::Autolock _l(mLock);
725 sp<ConfigEvent> configEvent = (ConfigEvent *)new UpdateOutDevicesConfigEvent(outDevices);
726 return sendConfigEvent_l(configEvent);
727}
728
Eric Laurentec376dc2021-04-08 20:41:22 +0200729void AudioFlinger::ThreadBase::sendResizeBufferConfigEvent_l(int32_t maxSharedAudioHistoryMs)
730{
731 ALOG_ASSERT(type() == RECORD, "sendResizeBufferConfigEvent_l() called on non record thread");
732 sp<ConfigEvent> configEvent =
733 (ConfigEvent *)new ResizeBufferConfigEvent(maxSharedAudioHistoryMs);
734 sendConfigEvent_l(configEvent);
735}
Eric Laurent1c333e22014-05-20 10:48:17 -0700736
Eric Laurentb3f315a2021-07-13 15:09:05 +0200737void AudioFlinger::ThreadBase::sendCheckOutputStageEffectsEvent()
738{
739 Mutex::Autolock _l(mLock);
740 sendCheckOutputStageEffectsEvent_l();
741}
742
743void AudioFlinger::ThreadBase::sendCheckOutputStageEffectsEvent_l()
744{
745 sp<ConfigEvent> configEvent =
746 (ConfigEvent *)new CheckOutputStageEffectsEvent();
747 sendConfigEvent_l(configEvent);
748}
749
Eric Laurent68a40a82022-05-03 18:15:04 +0200750void AudioFlinger::ThreadBase::sendHalLatencyModesChangedEvent_l()
751{
752 sp<ConfigEvent> configEvent = sp<HalLatencyModesChangedEvent>::make();
753 sendConfigEvent_l(configEvent);
754}
755
Glenn Kasten2cfbf882013-08-14 13:12:11 -0700756// post condition: mConfigEvents.isEmpty()
Eric Laurent021cf962014-05-13 10:18:14 -0700757void AudioFlinger::ThreadBase::processConfigEvents_l()
Glenn Kastenf7773312013-08-13 16:00:42 -0700758{
Eric Laurent10351942014-05-08 18:49:52 -0700759 bool configChanged = false;
760
Eric Laurent81784c32012-11-19 14:55:58 -0800761 while (!mConfigEvents.isEmpty()) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700762 ALOGV("processConfigEvents_l() remaining events %zu", mConfigEvents.size());
Eric Laurent10351942014-05-08 18:49:52 -0700763 sp<ConfigEvent> event = mConfigEvents[0];
Eric Laurent81784c32012-11-19 14:55:58 -0800764 mConfigEvents.removeAt(0);
Eric Laurent10351942014-05-08 18:49:52 -0700765 switch (event->mType) {
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700766 case CFG_EVENT_PRIO: {
Eric Laurent10351942014-05-08 18:49:52 -0700767 PrioConfigEventData *data = (PrioConfigEventData *)event->mData.get();
768 // FIXME Need to understand why this has to be done asynchronously
Mikhail Naganov83f04272017-02-07 10:45:09 -0800769 int err = requestPriority(data->mPid, data->mTid, data->mPrio, data->mForApp,
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700770 true /*asynchronous*/);
771 if (err != 0) {
772 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Eric Laurent10351942014-05-08 18:49:52 -0700773 data->mPrio, data->mPid, data->mTid, err);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700774 }
775 } break;
776 case CFG_EVENT_IO: {
Eric Laurent10351942014-05-08 18:49:52 -0700777 IoConfigEventData *data = (IoConfigEventData *)event->mData.get();
Eric Laurent09f1ed22019-04-24 17:45:17 -0700778 ioConfigChanged(data->mEvent, data->mPid, data->mPortId);
Eric Laurent10351942014-05-08 18:49:52 -0700779 } break;
780 case CFG_EVENT_SET_PARAMETER: {
781 SetParameterConfigEventData *data = (SetParameterConfigEventData *)event->mData.get();
782 if (checkForNewParameter_l(data->mKeyValuePairs, event->mStatus)) {
783 configChanged = true;
Andy Hung293558a2017-03-21 12:19:20 -0700784 mLocalLog.log("CFG_EVENT_SET_PARAMETER: (%s) configuration changed",
785 data->mKeyValuePairs.string());
Glenn Kastend5418eb2013-08-14 13:11:06 -0700786 }
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700787 } break;
Eric Laurent1c333e22014-05-20 10:48:17 -0700788 case CFG_EVENT_CREATE_AUDIO_PATCH: {
jiabinc52b1ff2019-10-31 17:20:42 -0700789 const DeviceTypeSet oldDevices = getDeviceTypes();
Eric Laurent1c333e22014-05-20 10:48:17 -0700790 CreateAudioPatchConfigEventData *data =
791 (CreateAudioPatchConfigEventData *)event->mData.get();
792 event->mStatus = createAudioPatch_l(&data->mPatch, &data->mHandle);
jiabinc52b1ff2019-10-31 17:20:42 -0700793 const DeviceTypeSet newDevices = getDeviceTypes();
794 mLocalLog.log("CFG_EVENT_CREATE_AUDIO_PATCH: old device %s (%s) new device %s (%s)",
795 dumpDeviceTypes(oldDevices).c_str(), toString(oldDevices).c_str(),
796 dumpDeviceTypes(newDevices).c_str(), toString(newDevices).c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -0700797 } break;
798 case CFG_EVENT_RELEASE_AUDIO_PATCH: {
jiabinc52b1ff2019-10-31 17:20:42 -0700799 const DeviceTypeSet oldDevices = getDeviceTypes();
Eric Laurent1c333e22014-05-20 10:48:17 -0700800 ReleaseAudioPatchConfigEventData *data =
801 (ReleaseAudioPatchConfigEventData *)event->mData.get();
802 event->mStatus = releaseAudioPatch_l(data->mHandle);
jiabinc52b1ff2019-10-31 17:20:42 -0700803 const DeviceTypeSet newDevices = getDeviceTypes();
804 mLocalLog.log("CFG_EVENT_RELEASE_AUDIO_PATCH: old device %s (%s) new device %s (%s)",
805 dumpDeviceTypes(oldDevices).c_str(), toString(oldDevices).c_str(),
806 dumpDeviceTypes(newDevices).c_str(), toString(newDevices).c_str());
807 } break;
808 case CFG_EVENT_UPDATE_OUT_DEVICE: {
809 UpdateOutDevicesConfigEventData *data =
810 (UpdateOutDevicesConfigEventData *)event->mData.get();
811 updateOutDevices(data->mOutDevices);
Eric Laurent1c333e22014-05-20 10:48:17 -0700812 } break;
Eric Laurentec376dc2021-04-08 20:41:22 +0200813 case CFG_EVENT_RESIZE_BUFFER: {
814 ResizeBufferConfigEventData *data =
815 (ResizeBufferConfigEventData *)event->mData.get();
816 resizeInputBuffer_l(data->mMaxSharedAudioHistoryMs);
817 } break;
Eric Laurentb3f315a2021-07-13 15:09:05 +0200818
819 case CFG_EVENT_CHECK_OUTPUT_STAGE_EFFECTS: {
820 setCheckOutputStageEffects();
821 } break;
822
Eric Laurent68a40a82022-05-03 18:15:04 +0200823 case CFG_EVENT_HAL_LATENCY_MODES_CHANGED: {
824 onHalLatencyModesChanged_l();
825 } break;
826
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700827 default:
Eric Laurent10351942014-05-08 18:49:52 -0700828 ALOG_ASSERT(false, "processConfigEvents_l() unknown event type %d", event->mType);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700829 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800830 }
Eric Laurent10351942014-05-08 18:49:52 -0700831 {
832 Mutex::Autolock _l(event->mLock);
833 if (event->mWaitStatus) {
834 event->mWaitStatus = false;
835 event->mCond.signal();
836 }
837 }
838 ALOGV_IF(mConfigEvents.isEmpty(), "processConfigEvents_l() DONE thread %p", this);
839 }
840
841 if (configChanged) {
842 cacheParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800843 }
Eric Laurent81784c32012-11-19 14:55:58 -0800844}
845
Marco Nelissenb2208842014-02-07 14:00:50 -0800846String8 channelMaskToString(audio_channel_mask_t mask, bool output) {
847 String8 s;
Glenn Kastene1635ec2015-06-08 15:46:49 -0700848 const audio_channel_representation_t representation =
849 audio_channel_mask_get_representation(mask);
Andy Hungf98ec8d2015-05-19 12:53:24 -0700850
851 switch (representation) {
jiabin245cdd92018-12-07 17:55:15 -0800852 // Travel all single bit channel mask to convert channel mask to string.
Andy Hungf98ec8d2015-05-19 12:53:24 -0700853 case AUDIO_CHANNEL_REPRESENTATION_POSITION: {
854 if (output) {
855 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT) s.append("front-left, ");
856 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT) s.append("front-right, ");
857 if (mask & AUDIO_CHANNEL_OUT_FRONT_CENTER) s.append("front-center, ");
Andy Hungfba71252021-05-07 11:58:32 -0700858 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY) s.append("low-frequency, ");
Andy Hungf98ec8d2015-05-19 12:53:24 -0700859 if (mask & AUDIO_CHANNEL_OUT_BACK_LEFT) s.append("back-left, ");
860 if (mask & AUDIO_CHANNEL_OUT_BACK_RIGHT) s.append("back-right, ");
861 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT_OF_CENTER) s.append("front-left-of-center, ");
862 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT_OF_CENTER) s.append("front-right-of-center, ");
863 if (mask & AUDIO_CHANNEL_OUT_BACK_CENTER) s.append("back-center, ");
864 if (mask & AUDIO_CHANNEL_OUT_SIDE_LEFT) s.append("side-left, ");
865 if (mask & AUDIO_CHANNEL_OUT_SIDE_RIGHT) s.append("side-right, ");
866 if (mask & AUDIO_CHANNEL_OUT_TOP_CENTER) s.append("top-center ,");
867 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_LEFT) s.append("top-front-left, ");
868 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_CENTER) s.append("top-front-center, ");
869 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_RIGHT) s.append("top-front-right, ");
870 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_LEFT) s.append("top-back-left, ");
Andy Hungae81b4c2021-05-07 08:54:28 -0700871 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_CENTER) s.append("top-back-center, ");
872 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_RIGHT) s.append("top-back-right, ");
873 if (mask & AUDIO_CHANNEL_OUT_TOP_SIDE_LEFT) s.append("top-side-left, ");
874 if (mask & AUDIO_CHANNEL_OUT_TOP_SIDE_RIGHT) s.append("top-side-right, ");
875 if (mask & AUDIO_CHANNEL_OUT_BOTTOM_FRONT_LEFT) s.append("bottom-front-left, ");
876 if (mask & AUDIO_CHANNEL_OUT_BOTTOM_FRONT_CENTER) s.append("bottom-front-center, ");
877 if (mask & AUDIO_CHANNEL_OUT_BOTTOM_FRONT_RIGHT) s.append("bottom-front-right, ");
Andy Hungfba71252021-05-07 11:58:32 -0700878 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY_2) s.append("low-frequency-2, ");
Andy Hungae81b4c2021-05-07 08:54:28 -0700879 if (mask & AUDIO_CHANNEL_OUT_HAPTIC_B) s.append("haptic-B, ");
880 if (mask & AUDIO_CHANNEL_OUT_HAPTIC_A) s.append("haptic-A, ");
Andy Hungf98ec8d2015-05-19 12:53:24 -0700881 if (mask & ~AUDIO_CHANNEL_OUT_ALL) s.append("unknown, ");
882 } else {
883 if (mask & AUDIO_CHANNEL_IN_LEFT) s.append("left, ");
884 if (mask & AUDIO_CHANNEL_IN_RIGHT) s.append("right, ");
885 if (mask & AUDIO_CHANNEL_IN_FRONT) s.append("front, ");
886 if (mask & AUDIO_CHANNEL_IN_BACK) s.append("back, ");
887 if (mask & AUDIO_CHANNEL_IN_LEFT_PROCESSED) s.append("left-processed, ");
888 if (mask & AUDIO_CHANNEL_IN_RIGHT_PROCESSED) s.append("right-processed, ");
889 if (mask & AUDIO_CHANNEL_IN_FRONT_PROCESSED) s.append("front-processed, ");
890 if (mask & AUDIO_CHANNEL_IN_BACK_PROCESSED) s.append("back-processed, ");
891 if (mask & AUDIO_CHANNEL_IN_PRESSURE) s.append("pressure, ");
892 if (mask & AUDIO_CHANNEL_IN_X_AXIS) s.append("X, ");
893 if (mask & AUDIO_CHANNEL_IN_Y_AXIS) s.append("Y, ");
894 if (mask & AUDIO_CHANNEL_IN_Z_AXIS) s.append("Z, ");
Mikhail Naganovc9948492018-05-10 17:25:28 -0700895 if (mask & AUDIO_CHANNEL_IN_BACK_LEFT) s.append("back-left, ");
896 if (mask & AUDIO_CHANNEL_IN_BACK_RIGHT) s.append("back-right, ");
897 if (mask & AUDIO_CHANNEL_IN_CENTER) s.append("center, ");
Andy Hungfba71252021-05-07 11:58:32 -0700898 if (mask & AUDIO_CHANNEL_IN_LOW_FREQUENCY) s.append("low-frequency, ");
Andy Hungae81b4c2021-05-07 08:54:28 -0700899 if (mask & AUDIO_CHANNEL_IN_TOP_LEFT) s.append("top-left, ");
900 if (mask & AUDIO_CHANNEL_IN_TOP_RIGHT) s.append("top-right, ");
Andy Hungf98ec8d2015-05-19 12:53:24 -0700901 if (mask & AUDIO_CHANNEL_IN_VOICE_UPLINK) s.append("voice-uplink, ");
902 if (mask & AUDIO_CHANNEL_IN_VOICE_DNLINK) s.append("voice-dnlink, ");
903 if (mask & ~AUDIO_CHANNEL_IN_ALL) s.append("unknown, ");
904 }
905 const int len = s.length();
906 if (len > 2) {
Glenn Kasten57c4e6f2016-03-18 14:54:07 -0700907 (void) s.lockBuffer(len); // needed?
Andy Hungf98ec8d2015-05-19 12:53:24 -0700908 s.unlockBuffer(len - 2); // remove trailing ", "
909 }
910 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -0800911 }
Andy Hungf98ec8d2015-05-19 12:53:24 -0700912 case AUDIO_CHANNEL_REPRESENTATION_INDEX:
913 s.appendFormat("index mask, bits:%#x", audio_channel_mask_get_bits(mask));
914 return s;
915 default:
916 s.appendFormat("unknown mask, representation:%d bits:%#x",
917 representation, audio_channel_mask_get_bits(mask));
918 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -0800919 }
Marco Nelissenb2208842014-02-07 14:00:50 -0800920}
921
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -0700922void AudioFlinger::ThreadBase::dump(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -0800923{
Glenn Kasten1bfe09a2017-02-21 13:05:56 -0800924 dprintf(fd, "\n%s thread %p, name %s, tid %d, type %d (%s):\n", isOutput() ? "Output" : "Input",
925 this, mThreadName, getTid(), type(), threadTypeToString(type()));
926
Eric Laurent81784c32012-11-19 14:55:58 -0800927 bool locked = AudioFlinger::dumpTryLock(mLock);
928 if (!locked) {
Glenn Kasten1bfe09a2017-02-21 13:05:56 -0800929 dprintf(fd, " Thread may be deadlocked\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800930 }
931
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -0700932 dumpBase_l(fd, args);
933 dumpInternals_l(fd, args);
934 dumpTracks_l(fd, args);
935 dumpEffectChains_l(fd, args);
936
937 if (locked) {
938 mLock.unlock();
939 }
940
941 dprintf(fd, " Local log:\n");
942 mLocalLog.dump(fd, " " /* prefix */, 40 /* lines */);
Andy Hungafc51db2022-04-08 17:33:40 -0700943
944 // --all does the statistics
945 bool dumpAll = false;
946 for (const auto &arg : args) {
947 if (arg == String16("--all")) {
948 dumpAll = true;
949 }
950 }
951 if (dumpAll || type() == SPATIALIZER) {
Andy Hung44d648b2022-04-08 17:33:40 -0700952 const std::string sched = mThreadSnapshot.toString();
Andy Hungafc51db2022-04-08 17:33:40 -0700953 if (!sched.empty()) {
954 (void)write(fd, sched.c_str(), sched.size());
955 }
956 }
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -0700957}
958
959void AudioFlinger::ThreadBase::dumpBase_l(int fd, const Vector<String16>& args __unused)
960{
Elliott Hughes87cebad2014-05-22 10:14:43 -0700961 dprintf(fd, " I/O handle: %d\n", mId);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700962 dprintf(fd, " Standby: %s\n", mStandby ? "yes" : "no");
Glenn Kasten97b7b752014-09-28 13:04:24 -0700963 dprintf(fd, " Sample rate: %u Hz\n", mSampleRate);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700964 dprintf(fd, " HAL frame count: %zu\n", mFrameCount);
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700965 dprintf(fd, " HAL format: 0x%x (%s)\n", mHALFormat, formatToString(mHALFormat).c_str());
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700966 dprintf(fd, " HAL buffer size: %zu bytes\n", mBufferSize);
Glenn Kasten97b7b752014-09-28 13:04:24 -0700967 dprintf(fd, " Channel count: %u\n", mChannelCount);
968 dprintf(fd, " Channel mask: 0x%08x (%s)\n", mChannelMask,
Marco Nelissenb2208842014-02-07 14:00:50 -0800969 channelMaskToString(mChannelMask, mType != RECORD).string());
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700970 dprintf(fd, " Processing format: 0x%x (%s)\n", mFormat, formatToString(mFormat).c_str());
Glenn Kastenf87c2f52015-08-21 08:03:57 -0700971 dprintf(fd, " Processing frame size: %zu bytes\n", mFrameSize);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700972 dprintf(fd, " Pending config events:");
Marco Nelissenb2208842014-02-07 14:00:50 -0800973 size_t numConfig = mConfigEvents.size();
974 if (numConfig) {
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -0700975 const size_t SIZE = 256;
976 char buffer[SIZE];
Marco Nelissenb2208842014-02-07 14:00:50 -0800977 for (size_t i = 0; i < numConfig; i++) {
978 mConfigEvents[i]->dump(buffer, SIZE);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700979 dprintf(fd, "\n %s", buffer);
Marco Nelissenb2208842014-02-07 14:00:50 -0800980 }
Elliott Hughes87cebad2014-05-22 10:14:43 -0700981 dprintf(fd, "\n");
Marco Nelissenb2208842014-02-07 14:00:50 -0800982 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -0700983 dprintf(fd, " none\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800984 }
Andy Hung293558a2017-03-21 12:19:20 -0700985 // Note: output device may be used by capture threads for effects such as AEC.
jiabinc52b1ff2019-10-31 17:20:42 -0700986 dprintf(fd, " Output devices: %s (%s)\n",
987 dumpDeviceTypes(outDeviceTypes()).c_str(), toString(outDeviceTypes()).c_str());
988 dprintf(fd, " Input device: %#x (%s)\n",
989 inDeviceType(), toString(inDeviceType()).c_str());
Andy Hung9b181952019-02-25 14:53:36 -0800990 dprintf(fd, " Audio source: %d (%s)\n", mAudioSource, toString(mAudioSource).c_str());
Eric Laurent81784c32012-11-19 14:55:58 -0800991
Andy Hung2e2c0bb2018-06-11 19:13:11 -0700992 // Dump timestamp statistics for the Thread types that support it.
993 if (mType == RECORD
994 || mType == MIXER
995 || mType == DUPLICATING
Andy Hungf3234512018-07-03 14:51:47 -0700996 || mType == DIRECT
Andy Hung4b7f54f2022-04-28 17:45:28 -0700997 || mType == OFFLOAD
998 || mType == SPATIALIZER) {
Andy Hung2e2c0bb2018-06-11 19:13:11 -0700999 dprintf(fd, " Timestamp stats: %s\n", mTimestampVerifier.toString().c_str());
Andy Hungc8fddf32018-08-08 18:32:37 -07001000 dprintf(fd, " Timestamp corrected: %s\n", isTimestampCorrectionEnabled() ? "yes" : "no");
Andy Hung2e2c0bb2018-06-11 19:13:11 -07001001 }
1002
Andy Hung446f4df2019-02-21 12:26:41 -08001003 if (mLastIoBeginNs > 0) { // MMAP may not set this
1004 dprintf(fd, " Last %s occurred (msecs): %lld\n",
1005 isOutput() ? "write" : "read",
1006 (long long) (systemTime() - mLastIoBeginNs) / NANOS_PER_MILLISECOND);
1007 }
1008
1009 if (mProcessTimeMs.getN() > 0) {
1010 dprintf(fd, " Process time ms stats: %s\n", mProcessTimeMs.toString().c_str());
1011 }
1012
1013 if (mIoJitterMs.getN() > 0) {
1014 dprintf(fd, " Hal %s jitter ms stats: %s\n",
1015 isOutput() ? "write" : "read",
1016 mIoJitterMs.toString().c_str());
1017 }
1018
Andy Hunge6c37112019-02-26 17:38:10 -08001019 if (mLatencyMs.getN() > 0) {
1020 dprintf(fd, " Threadloop %s latency stats: %s\n",
1021 isOutput() ? "write" : "read",
1022 mLatencyMs.toString().c_str());
1023 }
Robert Wu06db0a32021-08-10 19:05:34 +00001024
1025 if (mMonopipePipeDepthStats.getN() > 0) {
1026 dprintf(fd, " Monopipe %s pipe depth stats: %s\n",
1027 isOutput() ? "write" : "read",
1028 mMonopipePipeDepthStats.toString().c_str());
1029 }
Eric Laurent81784c32012-11-19 14:55:58 -08001030}
1031
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001032void AudioFlinger::ThreadBase::dumpEffectChains_l(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -08001033{
1034 const size_t SIZE = 256;
1035 char buffer[SIZE];
Eric Laurent81784c32012-11-19 14:55:58 -08001036
Marco Nelissenb2208842014-02-07 14:00:50 -08001037 size_t numEffectChains = mEffectChains.size();
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +00001038 snprintf(buffer, SIZE, " %zu Effect Chains\n", numEffectChains);
Eric Laurent81784c32012-11-19 14:55:58 -08001039 write(fd, buffer, strlen(buffer));
1040
Marco Nelissenb2208842014-02-07 14:00:50 -08001041 for (size_t i = 0; i < numEffectChains; ++i) {
Eric Laurent81784c32012-11-19 14:55:58 -08001042 sp<EffectChain> chain = mEffectChains[i];
1043 if (chain != 0) {
1044 chain->dump(fd, args);
1045 }
1046 }
1047}
1048
Andy Hungdae27702016-10-31 14:01:16 -07001049void AudioFlinger::ThreadBase::acquireWakeLock()
Eric Laurent81784c32012-11-19 14:55:58 -08001050{
1051 Mutex::Autolock _l(mLock);
Andy Hungdae27702016-10-31 14:01:16 -07001052 acquireWakeLock_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001053}
1054
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001055String16 AudioFlinger::ThreadBase::getWakeLockTag()
1056{
1057 switch (mType) {
Glenn Kastenbcb14862015-03-05 17:11:21 -08001058 case MIXER:
1059 return String16("AudioMix");
1060 case DIRECT:
1061 return String16("AudioDirectOut");
1062 case DUPLICATING:
1063 return String16("AudioDup");
1064 case RECORD:
1065 return String16("AudioIn");
1066 case OFFLOAD:
1067 return String16("AudioOffload");
Andy Hungea840382020-05-05 21:50:17 -07001068 case MMAP_PLAYBACK:
1069 return String16("MmapPlayback");
1070 case MMAP_CAPTURE:
1071 return String16("MmapCapture");
Eric Laurent1c5e2e32021-08-18 18:50:28 +02001072 case SPATIALIZER:
1073 return String16("AudioSpatial");
Glenn Kastenbcb14862015-03-05 17:11:21 -08001074 default:
1075 ALOG_ASSERT(false);
1076 return String16("AudioUnknown");
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001077 }
1078}
1079
Andy Hungdae27702016-10-31 14:01:16 -07001080void AudioFlinger::ThreadBase::acquireWakeLock_l()
Eric Laurent81784c32012-11-19 14:55:58 -08001081{
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001082 getPowerManager_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001083 if (mPowerManager != 0) {
1084 sp<IBinder> binder = new BBinder();
Andy Hungdae27702016-10-31 14:01:16 -07001085 // Uses AID_AUDIOSERVER for wakelock. updateWakeLockUids_l() updates with client uids.
Chris Ye6597d732020-02-28 22:38:25 -08001086 binder::Status status = mPowerManager->acquireWakeLockAsync(binder,
1087 POWERMANAGER_PARTIAL_WAKE_LOCK,
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001088 getWakeLockTag(),
Marco Nelissendcb346b2015-09-09 10:47:29 -07001089 String16("audioserver"),
Chris Ye6597d732020-02-28 22:38:25 -08001090 {} /* workSource */,
1091 {} /* historyTag */);
1092 if (status.isOk()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001093 mWakeLockToken = binder;
1094 }
Chris Ye6597d732020-02-28 22:38:25 -08001095 ALOGV("acquireWakeLock_l() %s status %d", mThreadName, status.exceptionCode());
Eric Laurent81784c32012-11-19 14:55:58 -08001096 }
Wei Jia3f273d12015-11-24 09:06:49 -08001097
Andy Hung3f0c9022016-01-15 17:49:46 -08001098 gBoottime.acquire(mWakeLockToken);
Andy Hung818e7a32016-02-16 18:08:07 -08001099 mTimestamp.mTimebaseOffset[ExtendedTimestamp::TIMEBASE_BOOTTIME] =
1100 gBoottime.getBoottimeOffset();
Eric Laurent81784c32012-11-19 14:55:58 -08001101}
1102
1103void AudioFlinger::ThreadBase::releaseWakeLock()
1104{
1105 Mutex::Autolock _l(mLock);
1106 releaseWakeLock_l();
1107}
1108
1109void AudioFlinger::ThreadBase::releaseWakeLock_l()
1110{
Andy Hung3f0c9022016-01-15 17:49:46 -08001111 gBoottime.release(mWakeLockToken);
Eric Laurent81784c32012-11-19 14:55:58 -08001112 if (mWakeLockToken != 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -08001113 ALOGV("releaseWakeLock_l() %s", mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08001114 if (mPowerManager != 0) {
Chris Ye6597d732020-02-28 22:38:25 -08001115 mPowerManager->releaseWakeLockAsync(mWakeLockToken, 0);
Eric Laurent81784c32012-11-19 14:55:58 -08001116 }
1117 mWakeLockToken.clear();
1118 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001119}
1120
1121void AudioFlinger::ThreadBase::getPowerManager_l() {
Eric Laurent72e3f392015-05-20 14:43:50 -07001122 if (mSystemReady && mPowerManager == 0) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001123 // use checkService() to avoid blocking if power service is not up yet
1124 sp<IBinder> binder =
1125 defaultServiceManager()->checkService(String16("power"));
1126 if (binder == 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -08001127 ALOGW("Thread %s cannot connect to the power manager service", mThreadName);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001128 } else {
Chris Ye6597d732020-02-28 22:38:25 -08001129 mPowerManager = interface_cast<os::IPowerManager>(binder);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001130 binder->linkToDeath(mDeathRecipient);
1131 }
1132 }
1133}
1134
Andy Hungd01b0f12016-11-07 16:10:30 -08001135void AudioFlinger::ThreadBase::updateWakeLockUids_l(const SortedVector<uid_t> &uids) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001136 getPowerManager_l();
Andy Hungdae27702016-10-31 14:01:16 -07001137
1138#if !LOG_NDEBUG
1139 std::stringstream s;
Andy Hungd01b0f12016-11-07 16:10:30 -08001140 for (uid_t uid : uids) {
Andy Hungdae27702016-10-31 14:01:16 -07001141 s << uid << " ";
1142 }
1143 ALOGD("updateWakeLockUids_l %s uids:%s", mThreadName, s.str().c_str());
1144#endif
1145
Andy Hung438e7572015-12-14 15:51:17 -08001146 if (mWakeLockToken == NULL) { // token may be NULL if AudioFlinger::systemReady() not called.
1147 if (mSystemReady) {
1148 ALOGE("no wake lock to update, but system ready!");
1149 } else {
1150 ALOGW("no wake lock to update, system not ready yet");
1151 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001152 return;
1153 }
1154 if (mPowerManager != 0) {
Andy Hung1f12a8a2016-11-07 16:10:30 -08001155 std::vector<int> uidsAsInt(uids.begin(), uids.end()); // powermanager expects uids as ints
Chris Ye6597d732020-02-28 22:38:25 -08001156 binder::Status status = mPowerManager->updateWakeLockUidsAsync(
1157 mWakeLockToken, uidsAsInt);
1158 ALOGV("updateWakeLockUids_l() %s status %d", mThreadName, status.exceptionCode());
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001159 }
1160}
1161
Eric Laurent81784c32012-11-19 14:55:58 -08001162void AudioFlinger::ThreadBase::clearPowerManager()
1163{
1164 Mutex::Autolock _l(mLock);
1165 releaseWakeLock_l();
1166 mPowerManager.clear();
1167}
1168
jiabinc52b1ff2019-10-31 17:20:42 -07001169void AudioFlinger::ThreadBase::updateOutDevices(
1170 const DeviceDescriptorBaseVector& outDevices __unused)
1171{
1172 ALOGE("%s should only be called in RecordThread", __func__);
1173}
1174
Eric Laurentec376dc2021-04-08 20:41:22 +02001175void AudioFlinger::ThreadBase::resizeInputBuffer_l(int32_t maxSharedAudioHistoryMs __unused)
1176{
1177 ALOGE("%s should only be called in RecordThread", __func__);
1178}
1179
Glenn Kasten0f11b512014-01-31 16:18:54 -08001180void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001181{
1182 sp<ThreadBase> thread = mThread.promote();
1183 if (thread != 0) {
1184 thread->clearPowerManager();
1185 }
1186 ALOGW("power manager service died !!!");
1187}
1188
Eric Laurent81784c32012-11-19 14:55:58 -08001189void AudioFlinger::ThreadBase::setEffectSuspended_l(
Glenn Kastend848eb42016-03-08 13:42:11 -08001190 const effect_uuid_t *type, bool suspend, audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001191{
1192 sp<EffectChain> chain = getEffectChain_l(sessionId);
1193 if (chain != 0) {
1194 if (type != NULL) {
1195 chain->setEffectSuspended_l(type, suspend);
1196 } else {
1197 chain->setEffectSuspendedAll_l(suspend);
1198 }
1199 }
1200
1201 updateSuspendedSessions_l(type, suspend, sessionId);
1202}
1203
1204void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1205{
1206 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
1207 if (index < 0) {
1208 return;
1209 }
1210
1211 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
1212 mSuspendedSessions.valueAt(index);
1213
1214 for (size_t i = 0; i < sessionEffects.size(); i++) {
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07001215 const sp<SuspendedSessionDesc>& desc = sessionEffects.valueAt(i);
Eric Laurent81784c32012-11-19 14:55:58 -08001216 for (int j = 0; j < desc->mRefCount; j++) {
1217 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1218 chain->setEffectSuspendedAll_l(true);
1219 } else {
1220 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
1221 desc->mType.timeLow);
1222 chain->setEffectSuspended_l(&desc->mType, true);
1223 }
1224 }
1225 }
1226}
1227
1228void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1229 bool suspend,
Glenn Kastend848eb42016-03-08 13:42:11 -08001230 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001231{
1232 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
1233
1234 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1235
1236 if (suspend) {
1237 if (index >= 0) {
1238 sessionEffects = mSuspendedSessions.valueAt(index);
1239 } else {
1240 mSuspendedSessions.add(sessionId, sessionEffects);
1241 }
1242 } else {
1243 if (index < 0) {
1244 return;
1245 }
1246 sessionEffects = mSuspendedSessions.valueAt(index);
1247 }
1248
1249
1250 int key = EffectChain::kKeyForSuspendAll;
1251 if (type != NULL) {
1252 key = type->timeLow;
1253 }
1254 index = sessionEffects.indexOfKey(key);
1255
1256 sp<SuspendedSessionDesc> desc;
1257 if (suspend) {
1258 if (index >= 0) {
1259 desc = sessionEffects.valueAt(index);
1260 } else {
1261 desc = new SuspendedSessionDesc();
1262 if (type != NULL) {
1263 desc->mType = *type;
1264 }
1265 sessionEffects.add(key, desc);
1266 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
1267 }
1268 desc->mRefCount++;
1269 } else {
1270 if (index < 0) {
1271 return;
1272 }
1273 desc = sessionEffects.valueAt(index);
1274 if (--desc->mRefCount == 0) {
1275 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
1276 sessionEffects.removeItemsAt(index);
1277 if (sessionEffects.isEmpty()) {
1278 ALOGV("updateSuspendedSessions_l() restore removing session %d",
1279 sessionId);
1280 mSuspendedSessions.removeItem(sessionId);
1281 }
1282 }
1283 }
1284 if (!sessionEffects.isEmpty()) {
1285 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1286 }
1287}
1288
Eric Laurent6b446ce2019-12-13 10:56:31 -08001289void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(bool enabled,
1290 audio_session_t sessionId,
1291 bool threadLocked) {
1292 if (!threadLocked) {
1293 mLock.lock();
1294 }
Eric Laurent81784c32012-11-19 14:55:58 -08001295
Eric Laurent81784c32012-11-19 14:55:58 -08001296 if (mType != RECORD) {
1297 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1298 // another session. This gives the priority to well behaved effect control panels
1299 // and applications not using global effects.
1300 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
1301 // global effects
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001302 if (!audio_is_global_session(sessionId)) {
Eric Laurent81784c32012-11-19 14:55:58 -08001303 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1304 }
1305 }
1306
Eric Laurent6b446ce2019-12-13 10:56:31 -08001307 if (!threadLocked) {
1308 mLock.unlock();
Eric Laurent81784c32012-11-19 14:55:58 -08001309 }
1310}
1311
Eric Laurent4c415062016-06-17 16:14:16 -07001312// checkEffectCompatibility_l() must be called with ThreadBase::mLock held
1313status_t AudioFlinger::RecordThread::checkEffectCompatibility_l(
1314 const effect_descriptor_t *desc, audio_session_t sessionId)
1315{
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001316 // No global output effect sessions on record threads
1317 if (sessionId == AUDIO_SESSION_OUTPUT_MIX
1318 || sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Eric Laurent4c415062016-06-17 16:14:16 -07001319 ALOGW("checkEffectCompatibility_l(): global effect %s on record thread %s",
1320 desc->name, mThreadName);
1321 return BAD_VALUE;
1322 }
1323 // only pre processing effects on record thread
1324 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC) {
1325 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on record thread %s",
1326 desc->name, mThreadName);
1327 return BAD_VALUE;
1328 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001329
1330 // always allow effects without processing load or latency
1331 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1332 return NO_ERROR;
1333 }
1334
Eric Laurent4c415062016-06-17 16:14:16 -07001335 audio_input_flags_t flags = mInput->flags;
1336 if (hasFastCapture() || (flags & AUDIO_INPUT_FLAG_FAST)) {
1337 if (flags & AUDIO_INPUT_FLAG_RAW) {
1338 ALOGW("checkEffectCompatibility_l(): effect %s on record thread %s in raw mode",
1339 desc->name, mThreadName);
1340 return BAD_VALUE;
1341 }
1342 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1343 ALOGW("checkEffectCompatibility_l(): non HW effect %s on record thread %s in fast mode",
1344 desc->name, mThreadName);
1345 return BAD_VALUE;
1346 }
1347 }
jiabineb3bda02020-06-30 14:07:03 -07001348
1349 if (EffectModule::isHapticGenerator(&desc->type)) {
1350 ALOGE("%s(): HapticGenerator is not supported in RecordThread", __func__);
1351 return BAD_VALUE;
1352 }
Eric Laurent4c415062016-06-17 16:14:16 -07001353 return NO_ERROR;
1354}
1355
1356// checkEffectCompatibility_l() must be called with ThreadBase::mLock held
1357status_t AudioFlinger::PlaybackThread::checkEffectCompatibility_l(
1358 const effect_descriptor_t *desc, audio_session_t sessionId)
1359{
1360 // no preprocessing on playback threads
1361 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001362 ALOGW("%s: pre processing effect %s created on playback"
1363 " thread %s", __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001364 return BAD_VALUE;
1365 }
1366
Eric Laurent3e4de772017-07-16 16:55:08 -07001367 // always allow effects without processing load or latency
1368 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1369 return NO_ERROR;
1370 }
1371
jiabineb3bda02020-06-30 14:07:03 -07001372 if (EffectModule::isHapticGenerator(&desc->type) && mHapticChannelCount == 0) {
1373 ALOGW("%s: thread doesn't support haptic playback while the effect is HapticGenerator",
1374 __func__);
1375 return BAD_VALUE;
1376 }
1377
Eric Laurentf690c462021-09-17 14:47:03 +02001378 if (memcmp(&desc->type, FX_IID_SPATIALIZER, sizeof(effect_uuid_t)) == 0
1379 && mType != SPATIALIZER) {
1380 ALOGW("%s: attempt to create a spatializer effect on a thread of type %d",
1381 __func__, mType);
1382 return BAD_VALUE;
1383 }
1384
Eric Laurent4c415062016-06-17 16:14:16 -07001385 switch (mType) {
1386 case MIXER: {
Andy Hung9aad48c2017-11-29 10:29:19 -08001387#ifndef MULTICHANNEL_EFFECT_CHAIN
Eric Laurent4c415062016-06-17 16:14:16 -07001388 // Reject any effect on mixer multichannel sinks.
1389 // TODO: fix both format and multichannel issues with effects.
1390 if (mChannelCount != FCC_2) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001391 ALOGW("%s: effect %s for multichannel(%d) on MIXER thread %s",
1392 __func__, desc->name, mChannelCount, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001393 return BAD_VALUE;
1394 }
Andy Hung9aad48c2017-11-29 10:29:19 -08001395#endif
Eric Laurent4c415062016-06-17 16:14:16 -07001396 audio_output_flags_t flags = mOutput->flags;
1397 if (hasFastMixer() || (flags & AUDIO_OUTPUT_FLAG_FAST)) {
1398 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1399 // global effects are applied only to non fast tracks if they are SW
1400 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1401 break;
1402 }
1403 } else if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1404 // only post processing on output stage session
1405 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001406 ALOGW("%s: non post processing effect %s not allowed on output stage session",
1407 __func__, desc->name);
Eric Laurent4c415062016-06-17 16:14:16 -07001408 return BAD_VALUE;
1409 }
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001410 } else if (sessionId == AUDIO_SESSION_DEVICE) {
1411 // only post processing on output stage session
1412 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001413 ALOGW("%s: non post processing effect %s not allowed on device session",
1414 __func__, desc->name);
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001415 return BAD_VALUE;
1416 }
Eric Laurent4c415062016-06-17 16:14:16 -07001417 } else {
1418 // no restriction on effects applied on non fast tracks
1419 if ((hasAudioSession_l(sessionId) & ThreadBase::FAST_SESSION) == 0) {
1420 break;
1421 }
1422 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001423
Eric Laurent4c415062016-06-17 16:14:16 -07001424 if (flags & AUDIO_OUTPUT_FLAG_RAW) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001425 ALOGW("%s: effect %s on playback thread in raw mode", __func__, desc->name);
Eric Laurent4c415062016-06-17 16:14:16 -07001426 return BAD_VALUE;
1427 }
1428 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001429 ALOGW("%s: non HW effect %s on playback thread in fast mode",
1430 __func__, desc->name);
Eric Laurent4c415062016-06-17 16:14:16 -07001431 return BAD_VALUE;
1432 }
1433 }
1434 } break;
1435 case OFFLOAD:
Jean-Michel Trivi773ee952016-07-11 16:53:18 -07001436 // nothing actionable on offload threads, if the effect:
1437 // - is offloadable: the effect can be created
1438 // - is NOT offloadable: the effect should still be created, but EffectHandle::enable()
1439 // will take care of invalidating the tracks of the thread
Eric Laurent4c415062016-06-17 16:14:16 -07001440 break;
1441 case DIRECT:
1442 // Reject any effect on Direct output threads for now, since the format of
1443 // mSinkBuffer is not guaranteed to be compatible with effect processing (PCM 16 stereo).
Eric Laurentb62d0362021-10-26 17:40:18 +02001444 ALOGW("%s: effect %s on DIRECT output thread %s",
1445 __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001446 return BAD_VALUE;
1447 case DUPLICATING:
Andy Hung9aad48c2017-11-29 10:29:19 -08001448#ifndef MULTICHANNEL_EFFECT_CHAIN
Eric Laurent4c415062016-06-17 16:14:16 -07001449 // Reject any effect on mixer multichannel sinks.
1450 // TODO: fix both format and multichannel issues with effects.
1451 if (mChannelCount != FCC_2) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001452 ALOGW("%s: effect %s for multichannel(%d) on DUPLICATING thread %s",
1453 __func__, desc->name, mChannelCount, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001454 return BAD_VALUE;
1455 }
Andy Hung9aad48c2017-11-29 10:29:19 -08001456#endif
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001457 if (audio_is_global_session(sessionId)) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001458 ALOGW("%s: global effect %s on DUPLICATING thread %s",
1459 __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001460 return BAD_VALUE;
1461 }
1462 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001463 ALOGW("%s: post processing effect %s on DUPLICATING thread %s",
1464 __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001465 return BAD_VALUE;
1466 }
1467 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) != 0) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001468 ALOGW("%s: HW tunneled effect %s on DUPLICATING thread %s",
1469 __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001470 return BAD_VALUE;
1471 }
1472 break;
Eric Laurent1c5e2e32021-08-18 18:50:28 +02001473 case SPATIALIZER:
Eric Laurentb62d0362021-10-26 17:40:18 +02001474 // Global effects (AUDIO_SESSION_OUTPUT_MIX) are not supported on spatializer mixer
1475 // as there is no common accumulation buffer for sptialized and non sptialized tracks.
1476 // Post processing effects (AUDIO_SESSION_OUTPUT_STAGE or AUDIO_SESSION_DEVICE)
1477 // are supported and added after the spatializer.
1478 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1479 ALOGW("%s: global effect %s not supported on spatializer thread %s",
1480 __func__, desc->name, mThreadName);
Eric Laurentb3f315a2021-07-13 15:09:05 +02001481 return BAD_VALUE;
Eric Laurentb62d0362021-10-26 17:40:18 +02001482 } else if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1483 // only post processing , downmixer or spatializer effects on output stage session
1484 if (memcmp(&desc->type, FX_IID_SPATIALIZER, sizeof(effect_uuid_t)) == 0
1485 || memcmp(&desc->type, EFFECT_UIID_DOWNMIX, sizeof(effect_uuid_t)) == 0) {
1486 break;
1487 }
1488 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
1489 ALOGW("%s: non post processing effect %s not allowed on output stage session",
1490 __func__, desc->name);
1491 return BAD_VALUE;
1492 }
1493 } else if (sessionId == AUDIO_SESSION_DEVICE) {
1494 // only post processing on output stage session
1495 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
1496 ALOGW("%s: non post processing effect %s not allowed on device session",
1497 __func__, desc->name);
1498 return BAD_VALUE;
1499 }
Eric Laurentb3f315a2021-07-13 15:09:05 +02001500 }
1501 break;
Eric Laurent4c415062016-06-17 16:14:16 -07001502 default:
1503 LOG_ALWAYS_FATAL("checkEffectCompatibility_l(): wrong thread type %d", mType);
1504 }
1505
1506 return NO_ERROR;
1507}
1508
Eric Laurent81784c32012-11-19 14:55:58 -08001509// ThreadBase::createEffect_l() must be called with AudioFlinger::mLock held
1510sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
1511 const sp<AudioFlinger::Client>& client,
1512 const sp<IEffectClient>& effectClient,
1513 int32_t priority,
Glenn Kastend848eb42016-03-08 13:42:11 -08001514 audio_session_t sessionId,
Eric Laurent81784c32012-11-19 14:55:58 -08001515 effect_descriptor_t *desc,
1516 int *enabled,
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001517 status_t *status,
Eric Laurent2fe0acd2020-03-13 14:30:46 -07001518 bool pinned,
Eric Laurentde8caf42021-08-11 17:19:25 +02001519 bool probe,
1520 bool notifyFramesProcessed)
Eric Laurent81784c32012-11-19 14:55:58 -08001521{
1522 sp<EffectModule> effect;
1523 sp<EffectHandle> handle;
1524 status_t lStatus;
1525 sp<EffectChain> chain;
1526 bool chainCreated = false;
1527 bool effectCreated = false;
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001528 audio_unique_id_t effectId = AUDIO_UNIQUE_ID_USE_UNSPECIFIED;
Eric Laurent81784c32012-11-19 14:55:58 -08001529
1530 lStatus = initCheck();
1531 if (lStatus != NO_ERROR) {
1532 ALOGW("createEffect_l() Audio driver not initialized.");
1533 goto Exit;
1534 }
1535
Eric Laurent81784c32012-11-19 14:55:58 -08001536 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
1537
1538 { // scope for mLock
1539 Mutex::Autolock _l(mLock);
1540
Eric Laurent4c415062016-06-17 16:14:16 -07001541 lStatus = checkEffectCompatibility_l(desc, sessionId);
Eric Laurent2fe0acd2020-03-13 14:30:46 -07001542 if (probe || lStatus != NO_ERROR) {
Eric Laurent4c415062016-06-17 16:14:16 -07001543 goto Exit;
1544 }
1545
Eric Laurent81784c32012-11-19 14:55:58 -08001546 // check for existing effect chain with the requested audio session
1547 chain = getEffectChain_l(sessionId);
1548 if (chain == 0) {
1549 // create a new chain for this session
1550 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
1551 chain = new EffectChain(this, sessionId);
1552 addEffectChain_l(chain);
1553 chain->setStrategy(getStrategyForSession_l(sessionId));
1554 chainCreated = true;
1555 } else {
1556 effect = chain->getEffectFromDesc_l(desc);
1557 }
1558
1559 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
1560
1561 if (effect == 0) {
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001562 effectId = mAudioFlinger->nextUniqueId(AUDIO_UNIQUE_ID_USE_EFFECT);
Eric Laurent81784c32012-11-19 14:55:58 -08001563 // create a new effect module if none present in the chain
Eric Laurent6b446ce2019-12-13 10:56:31 -08001564 lStatus = chain->createEffect_l(effect, desc, effectId, sessionId, pinned);
Eric Laurent81784c32012-11-19 14:55:58 -08001565 if (lStatus != NO_ERROR) {
1566 goto Exit;
1567 }
1568 effectCreated = true;
1569
jiabinc52b1ff2019-10-31 17:20:42 -07001570 // FIXME: use vector of device and address when effect interface is ready.
jiabin8f278ee2019-11-11 12:16:27 -08001571 effect->setDevices(outDeviceTypeAddrs());
1572 effect->setInputDevice(inDeviceTypeAddr());
Eric Laurent81784c32012-11-19 14:55:58 -08001573 effect->setMode(mAudioFlinger->getMode());
1574 effect->setAudioSource(mAudioSource);
1575 }
jiabin1319f5a2021-03-30 22:21:24 +00001576 if (effect->isHapticGenerator()) {
1577 // TODO(b/184194057): Use the vibrator information from the vibrator that will be used
1578 // for the HapticGenerator.
Lais Andradebc3f37a2021-07-02 00:13:19 +01001579 const std::optional<media::AudioVibratorInfo> defaultVibratorInfo =
1580 std::move(mAudioFlinger->getDefaultVibratorInfo_l());
1581 if (defaultVibratorInfo) {
jiabin1319f5a2021-03-30 22:21:24 +00001582 // Only set the vibrator info when it is a valid one.
Lais Andradebc3f37a2021-07-02 00:13:19 +01001583 effect->setVibratorInfo(*defaultVibratorInfo);
jiabin1319f5a2021-03-30 22:21:24 +00001584 }
1585 }
Eric Laurent81784c32012-11-19 14:55:58 -08001586 // create effect handle and connect it to effect module
Eric Laurentde8caf42021-08-11 17:19:25 +02001587 handle = new EffectHandle(effect, client, effectClient, priority, notifyFramesProcessed);
Glenn Kastene75da402013-11-20 13:54:52 -08001588 lStatus = handle->initCheck();
1589 if (lStatus == OK) {
1590 lStatus = effect->addHandle(handle.get());
Eric Laurentb3f315a2021-07-13 15:09:05 +02001591 sendCheckOutputStageEffectsEvent_l();
Glenn Kastene75da402013-11-20 13:54:52 -08001592 }
Eric Laurent81784c32012-11-19 14:55:58 -08001593 if (enabled != NULL) {
1594 *enabled = (int)effect->isEnabled();
1595 }
1596 }
1597
1598Exit:
Eric Laurent2fe0acd2020-03-13 14:30:46 -07001599 if (!probe && lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurent81784c32012-11-19 14:55:58 -08001600 Mutex::Autolock _l(mLock);
1601 if (effectCreated) {
1602 chain->removeEffect_l(effect);
1603 }
Eric Laurent81784c32012-11-19 14:55:58 -08001604 if (chainCreated) {
1605 removeEffectChain_l(chain);
1606 }
haobo101735295ff7b0d2017-03-17 17:44:03 +08001607 // handle must be cleared by caller to avoid deadlock.
Eric Laurent81784c32012-11-19 14:55:58 -08001608 }
1609
Glenn Kasten9156ef32013-08-06 15:39:08 -07001610 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001611 return handle;
1612}
1613
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001614void AudioFlinger::ThreadBase::disconnectEffectHandle(EffectHandle *handle,
1615 bool unpinIfLast)
1616{
1617 bool remove = false;
1618 sp<EffectModule> effect;
1619 {
1620 Mutex::Autolock _l(mLock);
Eric Laurent41709552019-12-16 19:34:05 -08001621 sp<EffectBase> effectBase = handle->effect().promote();
1622 if (effectBase == nullptr) {
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001623 return;
1624 }
Eric Laurentb82e6b72019-11-22 17:25:04 -08001625 effect = effectBase->asEffectModule();
1626 if (effect == nullptr) {
1627 return;
1628 }
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001629 // restore suspended effects if the disconnected handle was enabled and the last one.
1630 remove = (effect->removeHandle(handle) == 0) && (!effect->isPinned() || unpinIfLast);
1631 if (remove) {
1632 removeEffect_l(effect, true);
1633 }
Eric Laurentb3f315a2021-07-13 15:09:05 +02001634 sendCheckOutputStageEffectsEvent_l();
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001635 }
1636 if (remove) {
1637 mAudioFlinger->updateOrphanEffectChains(effect);
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001638 if (handle->enabled()) {
Eric Laurent6b446ce2019-12-13 10:56:31 -08001639 effect->checkSuspendOnEffectEnabled(false, false /*threadLocked*/);
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001640 }
1641 }
1642}
1643
Eric Laurent6b446ce2019-12-13 10:56:31 -08001644void AudioFlinger::ThreadBase::onEffectEnable(const sp<EffectModule>& effect) {
Andy Hungea840382020-05-05 21:50:17 -07001645 if (isOffloadOrMmap()) {
Eric Laurent6b446ce2019-12-13 10:56:31 -08001646 Mutex::Autolock _l(mLock);
1647 broadcast_l();
1648 }
1649 if (!effect->isOffloadable()) {
1650 if (mType == ThreadBase::OFFLOAD) {
1651 PlaybackThread *t = (PlaybackThread *)this;
1652 t->invalidateTracks(AUDIO_STREAM_MUSIC);
1653 }
1654 if (effect->sessionId() == AUDIO_SESSION_OUTPUT_MIX) {
1655 mAudioFlinger->onNonOffloadableGlobalEffectEnable();
1656 }
1657 }
1658}
1659
1660void AudioFlinger::ThreadBase::onEffectDisable() {
Andy Hungea840382020-05-05 21:50:17 -07001661 if (isOffloadOrMmap()) {
Eric Laurent6b446ce2019-12-13 10:56:31 -08001662 Mutex::Autolock _l(mLock);
1663 broadcast_l();
1664 }
1665}
1666
Glenn Kastend848eb42016-03-08 13:42:11 -08001667sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(audio_session_t sessionId,
1668 int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08001669{
1670 Mutex::Autolock _l(mLock);
1671 return getEffect_l(sessionId, effectId);
1672}
1673
Glenn Kastend848eb42016-03-08 13:42:11 -08001674sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(audio_session_t sessionId,
1675 int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08001676{
1677 sp<EffectChain> chain = getEffectChain_l(sessionId);
1678 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
1679}
1680
Eric Laurent6c796322019-04-09 14:13:17 -07001681std::vector<int> AudioFlinger::ThreadBase::getEffectIds_l(audio_session_t sessionId)
1682{
1683 sp<EffectChain> chain = getEffectChain_l(sessionId);
1684 return chain != nullptr ? chain->getEffectIds() : std::vector<int>{};
1685}
1686
Eric Laurent81784c32012-11-19 14:55:58 -08001687// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
1688// PlaybackThread::mLock held
1689status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
1690{
1691 // check for existing effect chain with the requested audio session
Glenn Kastend848eb42016-03-08 13:42:11 -08001692 audio_session_t sessionId = effect->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08001693 sp<EffectChain> chain = getEffectChain_l(sessionId);
1694 bool chainCreated = false;
1695
Eric Laurent5baf2af2013-09-12 17:37:00 -07001696 ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(),
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001697 "addEffect_l() on offloaded thread %p: effect %s does not support offload flags %#x",
Eric Laurent5baf2af2013-09-12 17:37:00 -07001698 this, effect->desc().name, effect->desc().flags);
1699
Eric Laurent81784c32012-11-19 14:55:58 -08001700 if (chain == 0) {
1701 // create a new chain for this session
1702 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
1703 chain = new EffectChain(this, sessionId);
1704 addEffectChain_l(chain);
1705 chain->setStrategy(getStrategyForSession_l(sessionId));
1706 chainCreated = true;
1707 }
1708 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
1709
1710 if (chain->getEffectFromId_l(effect->id()) != 0) {
1711 ALOGW("addEffect_l() %p effect %s already present in chain %p",
1712 this, effect->desc().name, chain.get());
1713 return BAD_VALUE;
1714 }
1715
Eric Laurent5baf2af2013-09-12 17:37:00 -07001716 effect->setOffloaded(mType == OFFLOAD, mId);
1717
Eric Laurent81784c32012-11-19 14:55:58 -08001718 status_t status = chain->addEffect_l(effect);
1719 if (status != NO_ERROR) {
1720 if (chainCreated) {
1721 removeEffectChain_l(chain);
1722 }
1723 return status;
1724 }
1725
jiabin8f278ee2019-11-11 12:16:27 -08001726 effect->setDevices(outDeviceTypeAddrs());
1727 effect->setInputDevice(inDeviceTypeAddr());
Eric Laurent81784c32012-11-19 14:55:58 -08001728 effect->setMode(mAudioFlinger->getMode());
1729 effect->setAudioSource(mAudioSource);
Eric Laurentd8365c52017-07-16 15:27:05 -07001730
Eric Laurent81784c32012-11-19 14:55:58 -08001731 return NO_ERROR;
1732}
1733
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001734void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect, bool release) {
Eric Laurent81784c32012-11-19 14:55:58 -08001735
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001736 ALOGV("%s %p effect %p", __FUNCTION__, this, effect.get());
Eric Laurent81784c32012-11-19 14:55:58 -08001737 effect_descriptor_t desc = effect->desc();
1738 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
1739 detachAuxEffect_l(effect->id());
1740 }
1741
Andy Hungfda44002021-06-03 17:23:16 -07001742 sp<EffectChain> chain = effect->getCallback()->chain().promote();
Eric Laurent81784c32012-11-19 14:55:58 -08001743 if (chain != 0) {
1744 // remove effect chain if removing last effect
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001745 if (chain->removeEffect_l(effect, release) == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08001746 removeEffectChain_l(chain);
1747 }
1748 } else {
1749 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
1750 }
1751}
1752
1753void AudioFlinger::ThreadBase::lockEffectChains_l(
1754 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1755{
1756 effectChains = mEffectChains;
1757 for (size_t i = 0; i < mEffectChains.size(); i++) {
1758 mEffectChains[i]->lock();
1759 }
1760}
1761
1762void AudioFlinger::ThreadBase::unlockEffectChains(
1763 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1764{
1765 for (size_t i = 0; i < effectChains.size(); i++) {
1766 effectChains[i]->unlock();
1767 }
1768}
1769
Glenn Kastend848eb42016-03-08 13:42:11 -08001770sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001771{
1772 Mutex::Autolock _l(mLock);
1773 return getEffectChain_l(sessionId);
1774}
1775
Glenn Kastend848eb42016-03-08 13:42:11 -08001776sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(audio_session_t sessionId)
1777 const
Eric Laurent81784c32012-11-19 14:55:58 -08001778{
1779 size_t size = mEffectChains.size();
1780 for (size_t i = 0; i < size; i++) {
1781 if (mEffectChains[i]->sessionId() == sessionId) {
1782 return mEffectChains[i];
1783 }
1784 }
1785 return 0;
1786}
1787
1788void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
1789{
1790 Mutex::Autolock _l(mLock);
1791 size_t size = mEffectChains.size();
1792 for (size_t i = 0; i < size; i++) {
1793 mEffectChains[i]->setMode_l(mode);
1794 }
1795}
1796
Mikhail Naganovdc769682018-05-04 15:34:08 -07001797void AudioFlinger::ThreadBase::toAudioPortConfig(struct audio_port_config *config)
Eric Laurent83b88082014-06-20 18:31:16 -07001798{
1799 config->type = AUDIO_PORT_TYPE_MIX;
1800 config->ext.mix.handle = mId;
1801 config->sample_rate = mSampleRate;
1802 config->format = mFormat;
1803 config->channel_mask = mChannelMask;
1804 config->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
1805 AUDIO_PORT_CONFIG_FORMAT;
1806}
1807
Eric Laurent72e3f392015-05-20 14:43:50 -07001808void AudioFlinger::ThreadBase::systemReady()
1809{
1810 Mutex::Autolock _l(mLock);
1811 if (mSystemReady) {
1812 return;
1813 }
1814 mSystemReady = true;
1815
1816 for (size_t i = 0; i < mPendingConfigEvents.size(); i++) {
1817 sendConfigEvent_l(mPendingConfigEvents.editItemAt(i));
1818 }
1819 mPendingConfigEvents.clear();
1820}
1821
Andy Hungdae27702016-10-31 14:01:16 -07001822template <typename T>
1823ssize_t AudioFlinger::ThreadBase::ActiveTracks<T>::add(const sp<T> &track) {
1824 ssize_t index = mActiveTracks.indexOf(track);
1825 if (index >= 0) {
1826 ALOGW("ActiveTracks<T>::add track %p already there", track.get());
1827 return index;
1828 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001829 logTrack("add", track);
Andy Hungdae27702016-10-31 14:01:16 -07001830 mActiveTracksGeneration++;
1831 mLatestActiveTrack = track;
1832 ++mBatteryCounter[track->uid()].second;
Kevin Rocard069c2712018-03-29 19:09:14 -07001833 mHasChanged = true;
Andy Hungdae27702016-10-31 14:01:16 -07001834 return mActiveTracks.add(track);
1835}
1836
1837template <typename T>
1838ssize_t AudioFlinger::ThreadBase::ActiveTracks<T>::remove(const sp<T> &track) {
1839 ssize_t index = mActiveTracks.remove(track);
1840 if (index < 0) {
1841 ALOGW("ActiveTracks<T>::remove nonexistent track %p", track.get());
1842 return index;
1843 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001844 logTrack("remove", track);
Andy Hungdae27702016-10-31 14:01:16 -07001845 mActiveTracksGeneration++;
1846 --mBatteryCounter[track->uid()].second;
1847 // mLatestActiveTrack is not cleared even if is the same as track.
Kevin Rocard069c2712018-03-29 19:09:14 -07001848 mHasChanged = true;
Andy Hung8946a282018-04-19 20:04:56 -07001849#ifdef TEE_SINK
1850 track->dumpTee(-1 /* fd */, "_REMOVE");
1851#endif
Andy Hungc2b11cb2020-04-22 09:04:01 -07001852 track->logEndInterval(); // log to MediaMetrics
Andy Hungdae27702016-10-31 14:01:16 -07001853 return index;
1854}
1855
1856template <typename T>
1857void AudioFlinger::ThreadBase::ActiveTracks<T>::clear() {
1858 for (const sp<T> &track : mActiveTracks) {
1859 BatteryNotifier::getInstance().noteStopAudio(track->uid());
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001860 logTrack("clear", track);
Andy Hungdae27702016-10-31 14:01:16 -07001861 }
1862 mLastActiveTracksGeneration = mActiveTracksGeneration;
Kevin Rocard069c2712018-03-29 19:09:14 -07001863 if (!mActiveTracks.empty()) { mHasChanged = true; }
Andy Hungdae27702016-10-31 14:01:16 -07001864 mActiveTracks.clear();
1865 mLatestActiveTrack.clear();
1866 mBatteryCounter.clear();
1867}
1868
1869template <typename T>
1870void AudioFlinger::ThreadBase::ActiveTracks<T>::updatePowerState(
1871 sp<ThreadBase> thread, bool force) {
1872 // Updates ActiveTracks client uids to the thread wakelock.
1873 if (mActiveTracksGeneration != mLastActiveTracksGeneration || force) {
1874 thread->updateWakeLockUids_l(getWakeLockUids());
1875 mLastActiveTracksGeneration = mActiveTracksGeneration;
1876 }
1877
1878 // Updates BatteryNotifier uids
1879 for (auto it = mBatteryCounter.begin(); it != mBatteryCounter.end();) {
1880 const uid_t uid = it->first;
1881 ssize_t &previous = it->second.first;
1882 ssize_t &current = it->second.second;
1883 if (current > 0) {
1884 if (previous == 0) {
1885 BatteryNotifier::getInstance().noteStartAudio(uid);
1886 }
1887 previous = current;
1888 ++it;
1889 } else if (current == 0) {
1890 if (previous > 0) {
1891 BatteryNotifier::getInstance().noteStopAudio(uid);
1892 }
1893 it = mBatteryCounter.erase(it); // std::map<> is stable on iterator erase.
1894 } else /* (current < 0) */ {
1895 LOG_ALWAYS_FATAL("negative battery count %zd", current);
1896 }
1897 }
1898}
Eric Laurent83b88082014-06-20 18:31:16 -07001899
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001900template <typename T>
Kevin Rocard069c2712018-03-29 19:09:14 -07001901bool AudioFlinger::ThreadBase::ActiveTracks<T>::readAndClearHasChanged() {
Jasmine Chaeaa10e42021-05-11 10:11:14 +08001902 bool hasChanged = mHasChanged;
Kevin Rocard069c2712018-03-29 19:09:14 -07001903 mHasChanged = false;
Jasmine Chaeaa10e42021-05-11 10:11:14 +08001904
1905 for (const sp<T> &track : mActiveTracks) {
1906 // Do not short-circuit as all hasChanged states must be reset
1907 // as all the metadata are going to be sent
1908 hasChanged |= track->readAndClearHasChanged();
1909 }
Kevin Rocard069c2712018-03-29 19:09:14 -07001910 return hasChanged;
1911}
1912
1913template <typename T>
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001914void AudioFlinger::ThreadBase::ActiveTracks<T>::logTrack(
1915 const char *funcName, const sp<T> &track) const {
1916 if (mLocalLog != nullptr) {
1917 String8 result;
1918 track->appendDump(result, false /* active */);
1919 mLocalLog->log("AT::%-10s(%p) %s", funcName, track.get(), result.string());
1920 }
1921}
1922
Eric Laurent6acd1d42017-01-04 14:23:29 -08001923void AudioFlinger::ThreadBase::broadcast_l()
1924{
1925 // Thread could be blocked waiting for async
1926 // so signal it to handle state changes immediately
1927 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
1928 // be lost so we also flag to prevent it blocking on mWaitWorkCV
1929 mSignalPending = true;
1930 mWaitWorkCV.broadcast();
1931}
1932
Andy Hungd0979812019-02-21 15:51:44 -08001933// Call only from threadLoop() or when it is idle.
1934// Do not call from high performance code as this may do binder rpc to the MediaMetrics service.
1935void AudioFlinger::ThreadBase::sendStatistics(bool force)
1936{
1937 // Do not log if we have no stats.
1938 // We choose the timestamp verifier because it is the most likely item to be present.
1939 const int64_t nstats = mTimestampVerifier.getN() - mLastRecordedTimestampVerifierN;
1940 if (nstats == 0) {
1941 return;
1942 }
1943
1944 // Don't log more frequently than once per 12 hours.
1945 // We use BOOTTIME to include suspend time.
1946 const int64_t timeNs = systemTime(SYSTEM_TIME_BOOTTIME);
1947 const int64_t sinceNs = timeNs - mLastRecordedTimeNs; // ok if mLastRecordedTimeNs = 0
1948 if (!force && sinceNs <= 12 * NANOS_PER_HOUR) {
1949 return;
1950 }
1951
1952 mLastRecordedTimestampVerifierN = mTimestampVerifier.getN();
1953 mLastRecordedTimeNs = timeNs;
1954
Ray Essickf27e9872019-12-07 06:28:46 -08001955 std::unique_ptr<mediametrics::Item> item(mediametrics::Item::create("audiothread"));
Andy Hungd0979812019-02-21 15:51:44 -08001956
1957#define MM_PREFIX "android.media.audiothread." // avoid cut-n-paste errors.
1958
1959 // thread configuration
1960 item->setInt32(MM_PREFIX "id", (int32_t)mId); // IO handle
1961 // item->setInt32(MM_PREFIX "portId", (int32_t)mPortId);
1962 item->setCString(MM_PREFIX "type", threadTypeToString(mType));
1963 item->setInt32(MM_PREFIX "sampleRate", (int32_t)mSampleRate);
1964 item->setInt64(MM_PREFIX "channelMask", (int64_t)mChannelMask);
1965 item->setCString(MM_PREFIX "encoding", toString(mFormat).c_str());
1966 item->setInt32(MM_PREFIX "frameCount", (int32_t)mFrameCount);
jiabinc52b1ff2019-10-31 17:20:42 -07001967 item->setCString(MM_PREFIX "outDevice", toString(outDeviceTypes()).c_str());
1968 item->setCString(MM_PREFIX "inDevice", toString(inDeviceType()).c_str());
Andy Hungd0979812019-02-21 15:51:44 -08001969
1970 // thread statistics
1971 if (mIoJitterMs.getN() > 0) {
1972 item->setDouble(MM_PREFIX "ioJitterMs.mean", mIoJitterMs.getMean());
1973 item->setDouble(MM_PREFIX "ioJitterMs.std", mIoJitterMs.getStdDev());
1974 }
1975 if (mProcessTimeMs.getN() > 0) {
1976 item->setDouble(MM_PREFIX "processTimeMs.mean", mProcessTimeMs.getMean());
1977 item->setDouble(MM_PREFIX "processTimeMs.std", mProcessTimeMs.getStdDev());
1978 }
1979 const auto tsjitter = mTimestampVerifier.getJitterMs();
1980 if (tsjitter.getN() > 0) {
1981 item->setDouble(MM_PREFIX "timestampJitterMs.mean", tsjitter.getMean());
1982 item->setDouble(MM_PREFIX "timestampJitterMs.std", tsjitter.getStdDev());
1983 }
1984 if (mLatencyMs.getN() > 0) {
1985 item->setDouble(MM_PREFIX "latencyMs.mean", mLatencyMs.getMean());
1986 item->setDouble(MM_PREFIX "latencyMs.std", mLatencyMs.getStdDev());
1987 }
Robert Wu06db0a32021-08-10 19:05:34 +00001988 if (mMonopipePipeDepthStats.getN() > 0) {
1989 item->setDouble(MM_PREFIX "monopipePipeDepthStats.mean",
1990 mMonopipePipeDepthStats.getMean());
1991 item->setDouble(MM_PREFIX "monopipePipeDepthStats.std",
1992 mMonopipePipeDepthStats.getStdDev());
1993 }
Andy Hungd0979812019-02-21 15:51:44 -08001994
1995 item->selfrecord();
1996}
1997
Eric Laurentd66d7a12021-07-13 13:35:32 +02001998product_strategy_t AudioFlinger::ThreadBase::getStrategyForStream(audio_stream_type_t stream) const
1999{
2000 if (!mAudioFlinger->isAudioPolicyReady()) {
2001 return PRODUCT_STRATEGY_NONE;
2002 }
2003 return AudioSystem::getStrategyForStream(stream);
2004}
2005
Eric Laurent81784c32012-11-19 14:55:58 -08002006// ----------------------------------------------------------------------------
2007// Playback
2008// ----------------------------------------------------------------------------
2009
2010AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
2011 AudioStreamOut* output,
2012 audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -07002013 type_t type,
Eric Laurentf1f22e72021-07-13 14:04:14 +02002014 bool systemReady,
2015 audio_config_base_t *mixerConfig)
Andy Hungcf10d742020-04-28 15:38:24 -07002016 : ThreadBase(audioFlinger, id, type, systemReady, true /* isOut */),
Andy Hung2098f272014-02-27 14:00:06 -08002017 mNormalFrameCount(0), mSinkBuffer(NULL),
Eric Laurent1c5e2e32021-08-18 18:50:28 +02002018 mMixerBufferEnabled(AudioFlinger::kEnableExtendedPrecision || type == SPATIALIZER),
Andy Hung69aed5f2014-02-25 17:24:40 -08002019 mMixerBuffer(NULL),
2020 mMixerBufferSize(0),
2021 mMixerBufferFormat(AUDIO_FORMAT_INVALID),
2022 mMixerBufferValid(false),
Eric Laurent1c5e2e32021-08-18 18:50:28 +02002023 mEffectBufferEnabled(AudioFlinger::kEnableExtendedPrecision || type == SPATIALIZER),
Andy Hung98ef9782014-03-04 14:46:50 -08002024 mEffectBuffer(NULL),
2025 mEffectBufferSize(0),
2026 mEffectBufferFormat(AUDIO_FORMAT_INVALID),
2027 mEffectBufferValid(false),
Glenn Kastenc1fac192013-08-06 07:41:36 -07002028 mSuspended(0), mBytesWritten(0),
Andy Hungc54b1ff2016-02-23 14:07:07 -08002029 mFramesWritten(0),
Andy Hung238fa3d2016-07-28 10:53:22 -07002030 mSuspendedFrames(0),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002031 mActiveTracks(&this->mLocalLog),
Eric Laurent81784c32012-11-19 14:55:58 -08002032 // mStreamTypes[] initialized in constructor body
Andy Hung1bc088a2018-02-09 15:57:31 -08002033 mTracks(type == MIXER),
Eric Laurent81784c32012-11-19 14:55:58 -08002034 mOutput(output),
Andy Hung446f4df2019-02-21 12:26:41 -08002035 mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
Eric Laurent81784c32012-11-19 14:55:58 -08002036 mMixerStatus(MIXER_IDLE),
2037 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002038 mStandbyDelayNs(AudioFlinger::mStandbyTimeInNsecs),
Eric Laurentbfb1b832013-01-07 09:53:42 -08002039 mBytesRemaining(0),
2040 mCurrentWriteLength(0),
2041 mUseAsyncWrite(false),
Eric Laurent3b4529e2013-09-05 18:09:19 -07002042 mWriteAckSequence(0),
2043 mDrainSequence(0),
Eric Laurent81784c32012-11-19 14:55:58 -08002044 mScreenState(AudioFlinger::mScreenState),
2045 // index 0 is reserved for normal mixer's submix
Glenn Kastendc2c50b2016-04-21 08:13:14 -07002046 mFastTrackAvailMask(((1 << FastMixerState::sMaxFastTracks) - 1) & ~1),
Eric Laurent7c29ec92017-09-20 17:54:22 -07002047 mHwSupportsPause(false), mHwPaused(false), mFlushPending(false),
Eric Laurent74c38dc2020-12-23 18:19:44 +01002048 mLeftVolFloat(-1.0), mRightVolFloat(-1.0),
Brian Lindahl65e90012022-07-27 18:01:07 +02002049 mDownStreamPatch{},
2050 mIsTimestampAdvancing(kMinimumTimeBetweenTimestampChecksNs)
Eric Laurent81784c32012-11-19 14:55:58 -08002051{
Glenn Kastend7dca052015-03-05 16:05:54 -08002052 snprintf(mThreadName, kThreadNameLength, "AudioOut_%X", id);
2053 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08002054
2055 // Assumes constructor is called by AudioFlinger with it's mLock held, but
2056 // it would be safer to explicitly pass initial masterVolume/masterMute as
2057 // parameter.
2058 //
2059 // If the HAL we are using has support for master volume or master mute,
2060 // then do not attenuate or mute during mixing (just leave the volume at 1.0
2061 // and the mute set to false).
2062 mMasterVolume = audioFlinger->masterVolume_l();
2063 mMasterMute = audioFlinger->masterMute_l();
George Burgess IV5e4d86f2020-02-18 12:55:36 -08002064 if (mOutput->audioHwDev) {
Eric Laurent81784c32012-11-19 14:55:58 -08002065 if (mOutput->audioHwDev->canSetMasterVolume()) {
2066 mMasterVolume = 1.0;
2067 }
2068
2069 if (mOutput->audioHwDev->canSetMasterMute()) {
2070 mMasterMute = false;
2071 }
Andy Hungc8fddf32018-08-08 18:32:37 -07002072 mIsMsdDevice = strcmp(
2073 mOutput->audioHwDev->moduleName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002074 }
2075
Eric Laurentf1f22e72021-07-13 14:04:14 +02002076 if (mixerConfig != nullptr && mixerConfig->channel_mask != AUDIO_CHANNEL_NONE) {
2077 mMixerChannelMask = mixerConfig->channel_mask;
2078 }
2079
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002080 readOutputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002081
Eric Laurent1c5e2e32021-08-18 18:50:28 +02002082 if (mType != SPATIALIZER
Eric Laurentb3f315a2021-07-13 15:09:05 +02002083 && mMixerChannelMask != mChannelMask) {
2084 LOG_ALWAYS_FATAL("HAL channel mask %#x does not match mixer channel mask %#x",
2085 mChannelMask, mMixerChannelMask);
2086 }
2087
Andy Hungc8fddf32018-08-08 18:32:37 -07002088 // TODO: We may also match on address as well as device type for
2089 // AUDIO_DEVICE_OUT_BUS, AUDIO_DEVICE_OUT_ALL_A2DP, AUDIO_DEVICE_OUT_REMOTE_SUBMIX
Dean Wheatleyf8726f02019-12-02 14:12:01 +11002090 if (type == MIXER || type == DIRECT || type == OFFLOAD) {
jiabinc52b1ff2019-10-31 17:20:42 -07002091 // TODO: This property should be ensure that only contains one single device type.
2092 mTimestampCorrectedDevice = (audio_devices_t)property_get_int64(
2093 "audio.timestamp.corrected_output_device",
Andy Hungc8fddf32018-08-08 18:32:37 -07002094 (int64_t)(mIsMsdDevice ? AUDIO_DEVICE_OUT_BUS // turn on by default for MSD
2095 : AUDIO_DEVICE_NONE));
2096 }
2097
Mikhail Naganovf33115d2020-09-25 23:03:05 +00002098 for (int i = AUDIO_STREAM_MIN; i < AUDIO_STREAM_FOR_POLICY_CNT; ++i) {
2099 const audio_stream_type_t stream{static_cast<audio_stream_type_t>(i)};
Eric Laurent98e38192018-02-15 18:31:53 -08002100 mStreamTypes[stream].volume = 0.0f;
Eric Laurent81784c32012-11-19 14:55:58 -08002101 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
2102 }
Eric Laurent35f8c7c2020-02-08 11:42:35 -08002103 // Audio patch and call assistant volume are always max
Eric Laurent98e38192018-02-15 18:31:53 -08002104 mStreamTypes[AUDIO_STREAM_PATCH].volume = 1.0f;
2105 mStreamTypes[AUDIO_STREAM_PATCH].mute = false;
Eric Laurent35f8c7c2020-02-08 11:42:35 -08002106 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].volume = 1.0f;
2107 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].mute = false;
Eric Laurent81784c32012-11-19 14:55:58 -08002108}
2109
2110AudioFlinger::PlaybackThread::~PlaybackThread()
2111{
Glenn Kasten9e58b552013-01-18 15:09:48 -08002112 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung010a1a12014-03-13 13:57:33 -07002113 free(mSinkBuffer);
Andy Hung69aed5f2014-02-25 17:24:40 -08002114 free(mMixerBuffer);
Andy Hung98ef9782014-03-04 14:46:50 -08002115 free(mEffectBuffer);
Eric Laurentb62d0362021-10-26 17:40:18 +02002116 free(mPostSpatializerBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08002117}
2118
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002119// Thread virtuals
2120
2121void AudioFlinger::PlaybackThread::onFirstRef()
Eric Laurent81784c32012-11-19 14:55:58 -08002122{
Jasmine Chaeaa10e42021-05-11 10:11:14 +08002123 if (!isStreamInitialized()) {
jiabinf6eb4c32020-02-25 14:06:25 -08002124 ALOGE("The stream is not open yet"); // This should not happen.
2125 } else {
2126 // setEventCallback will need a strong pointer as a parameter. Calling it
2127 // here instead of constructor of PlaybackThread so that the onFirstRef
2128 // callback would not be made on an incompletely constructed object.
2129 if (mOutput->stream->setEventCallback(this) != OK) {
jiabinf1a36052020-08-19 14:33:31 -07002130 ALOGD("Failed to add event callback");
jiabinf6eb4c32020-02-25 14:06:25 -08002131 }
2132 }
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002133 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
Andy Hung44d648b2022-04-08 17:33:40 -07002134 mThreadSnapshot.setTid(getTid());
Eric Laurent81784c32012-11-19 14:55:58 -08002135}
2136
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002137// ThreadBase virtuals
2138void AudioFlinger::PlaybackThread::preExit()
2139{
2140 ALOGV(" preExit()");
Ytai Ben-Tsvi7e0183f2022-02-04 10:49:54 -08002141 status_t result = mOutput->stream->exit();
2142 ALOGE_IF(result != OK, "Error when calling exit(): %d", result);
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002143}
2144
2145void AudioFlinger::PlaybackThread::dumpTracks_l(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08002146{
Eric Laurent81784c32012-11-19 14:55:58 -08002147 String8 result;
2148
Marco Nelissenb2208842014-02-07 14:00:50 -08002149 result.appendFormat(" Stream volumes in dB: ");
Eric Laurent81784c32012-11-19 14:55:58 -08002150 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
2151 const stream_type_t *st = &mStreamTypes[i];
2152 if (i > 0) {
2153 result.appendFormat(", ");
2154 }
2155 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
2156 if (st->mute) {
2157 result.append("M");
2158 }
2159 }
2160 result.append("\n");
2161 write(fd, result.string(), result.length());
2162 result.clear();
2163
Eric Laurent81784c32012-11-19 14:55:58 -08002164 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
2165 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
Elliott Hughes87cebad2014-05-22 10:14:43 -07002166 dprintf(fd, " Normal mixer raw underrun counters: partial=%u empty=%u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08002167 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Marco Nelissenb2208842014-02-07 14:00:50 -08002168
2169 size_t numtracks = mTracks.size();
2170 size_t numactive = mActiveTracks.size();
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002171 dprintf(fd, " %zu Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08002172 size_t numactiveseen = 0;
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002173 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08002174 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002175 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002176 result.append(prefix);
Andy Hungf6ab58d2018-05-25 12:50:39 -07002177 mTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08002178 for (size_t i = 0; i < numtracks; ++i) {
2179 sp<Track> track = mTracks[i];
2180 if (track != 0) {
2181 bool active = mActiveTracks.indexOf(track) >= 0;
2182 if (active) {
2183 numactiveseen++;
2184 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002185 result.append(prefix);
2186 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08002187 }
2188 }
2189 } else {
2190 result.append("\n");
2191 }
2192 if (numactiveseen != numactive) {
2193 // some tracks in the active list were not in the tracks list
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002194 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08002195 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002196 result.append(prefix);
Andy Hungf6ab58d2018-05-25 12:50:39 -07002197 mActiveTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08002198 for (size_t i = 0; i < numactive; ++i) {
Andy Hungdae27702016-10-31 14:01:16 -07002199 sp<Track> track = mActiveTracks[i];
2200 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002201 result.append(prefix);
2202 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08002203 }
2204 }
2205 }
2206
2207 write(fd, result.string(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08002208}
2209
Andy Hung61589a42021-06-16 09:37:53 -07002210void AudioFlinger::PlaybackThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -08002211{
Andy Hung04cb8f72020-03-20 13:44:33 -07002212 dprintf(fd, " Master volume: %f\n", mMasterVolume);
Mikhail Naganovdfb411f2018-09-11 13:39:56 -07002213 dprintf(fd, " Master mute: %s\n", mMasterMute ? "on" : "off");
Eric Laurentf1f22e72021-07-13 14:04:14 +02002214 dprintf(fd, " Mixer channel Mask: %#x (%s)\n",
2215 mMixerChannelMask, channelMaskToString(mMixerChannelMask, true /* output */).c_str());
jiabin245cdd92018-12-07 17:55:15 -08002216 if (mHapticChannelMask != AUDIO_CHANNEL_NONE) {
2217 dprintf(fd, " Haptic channel mask: %#x (%s)\n", mHapticChannelMask,
2218 channelMaskToString(mHapticChannelMask, true /* output */).c_str());
2219 }
Elliott Hughes87cebad2014-05-22 10:14:43 -07002220 dprintf(fd, " Normal frame count: %zu\n", mNormalFrameCount);
Elliott Hughes87cebad2014-05-22 10:14:43 -07002221 dprintf(fd, " Total writes: %d\n", mNumWrites);
2222 dprintf(fd, " Delayed writes: %d\n", mNumDelayedWrites);
2223 dprintf(fd, " Blocked in write: %s\n", mInWrite ? "yes" : "no");
2224 dprintf(fd, " Suspend count: %d\n", mSuspended);
2225 dprintf(fd, " Sink buffer : %p\n", mSinkBuffer);
2226 dprintf(fd, " Mixer buffer: %p\n", mMixerBuffer);
2227 dprintf(fd, " Effect buffer: %p\n", mEffectBuffer);
2228 dprintf(fd, " Fast track availMask=%#x\n", mFastTrackAvailMask);
Eric Laurent42537be2016-01-08 17:16:42 -08002229 dprintf(fd, " Standby delay ns=%lld\n", (long long)mStandbyDelayNs);
Glenn Kasten97b7b752014-09-28 13:04:24 -07002230 AudioStreamOut *output = mOutput;
2231 audio_output_flags_t flags = output != NULL ? output->flags : AUDIO_OUTPUT_FLAG_NONE;
Mikhail Naganov913d06c2016-11-01 12:49:22 -07002232 dprintf(fd, " AudioStreamOut: %p flags %#x (%s)\n",
Andy Hung9b181952019-02-25 14:53:36 -08002233 output, flags, toString(flags).c_str());
Andy Hungb54c8542016-09-21 12:55:15 -07002234 dprintf(fd, " Frames written: %lld\n", (long long)mFramesWritten);
2235 dprintf(fd, " Suspended frames: %lld\n", (long long)mSuspendedFrames);
2236 if (mPipeSink.get() != nullptr) {
2237 dprintf(fd, " PipeSink frames written: %lld\n", (long long)mPipeSink->framesWritten());
2238 }
2239 if (output != nullptr) {
2240 dprintf(fd, " Hal stream dump:\n");
Andy Hung61589a42021-06-16 09:37:53 -07002241 (void)output->stream->dump(fd, args);
Andy Hungb54c8542016-09-21 12:55:15 -07002242 }
Eric Laurent81784c32012-11-19 14:55:58 -08002243}
2244
Eric Laurent81784c32012-11-19 14:55:58 -08002245// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
2246sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
2247 const sp<AudioFlinger::Client>& client,
2248 audio_stream_type_t streamType,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07002249 const audio_attributes_t& attr,
Eric Laurent21da6472017-11-09 16:29:26 -08002250 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08002251 audio_format_t format,
2252 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08002253 size_t *pFrameCount,
Eric Laurent21da6472017-11-09 16:29:26 -08002254 size_t *pNotificationFrameCount,
2255 uint32_t notificationsPerBuffer,
2256 float speed,
Eric Laurent81784c32012-11-19 14:55:58 -08002257 const sp<IMemory>& sharedBuffer,
Glenn Kastend848eb42016-03-08 13:42:11 -08002258 audio_session_t sessionId,
Eric Laurent05067782016-06-01 18:27:28 -07002259 audio_output_flags_t *flags,
Eric Laurent09f1ed22019-04-24 17:45:17 -07002260 pid_t creatorPid,
Svet Ganov33761132021-05-13 22:51:08 +00002261 const AttributionSourceState& attributionSource,
Eric Laurent81784c32012-11-19 14:55:58 -08002262 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002263 status_t *status,
jiabinf6eb4c32020-02-25 14:06:25 -08002264 audio_port_handle_t portId,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02002265 const sp<media::IAudioTrackCallback>& callback,
2266 bool isSpatialized)
Eric Laurent81784c32012-11-19 14:55:58 -08002267{
Glenn Kasten74935e42013-12-19 08:56:45 -08002268 size_t frameCount = *pFrameCount;
Eric Laurent21da6472017-11-09 16:29:26 -08002269 size_t notificationFrameCount = *pNotificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08002270 sp<Track> track;
2271 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07002272 audio_output_flags_t outputFlags = mOutput->flags;
Eric Laurent21da6472017-11-09 16:29:26 -08002273 audio_output_flags_t requestedFlags = *flags;
Eric Laurent9b11c022018-06-06 19:19:22 -07002274 uint32_t sampleRate;
2275
2276 if (sharedBuffer != 0 && checkIMemory(sharedBuffer) != NO_ERROR) {
2277 lStatus = BAD_VALUE;
2278 goto Exit;
2279 }
Eric Laurent21da6472017-11-09 16:29:26 -08002280
2281 if (*pSampleRate == 0) {
2282 *pSampleRate = mSampleRate;
2283 }
Eric Laurent9b11c022018-06-06 19:19:22 -07002284 sampleRate = *pSampleRate;
Eric Laurent05067782016-06-01 18:27:28 -07002285
2286 // special case for FAST flag considered OK if fast mixer is present
2287 if (hasFastMixer()) {
2288 outputFlags = (audio_output_flags_t)(outputFlags | AUDIO_OUTPUT_FLAG_FAST);
2289 }
2290
2291 // Check if requested flags are compatible with output stream flags
2292 if ((*flags & outputFlags) != *flags) {
2293 ALOGW("createTrack_l(): mismatch between requested flags (%08x) and output flags (%08x)",
2294 *flags, outputFlags);
2295 *flags = (audio_output_flags_t)(*flags & outputFlags);
2296 }
Eric Laurent81784c32012-11-19 14:55:58 -08002297
Eric Laurent81784c32012-11-19 14:55:58 -08002298 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07002299 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
Eric Laurent81784c32012-11-19 14:55:58 -08002300 if (
Eric Laurent81784c32012-11-19 14:55:58 -08002301 // PCM data
2302 audio_is_linear_pcm(format) &&
Andy Hung1f439e12015-05-19 12:57:41 -07002303 // TODO: extract as a data library function that checks that a computationally
2304 // expensive downmixer is not required: isFastOutputChannelConversion()
jiabin245cdd92018-12-07 17:55:15 -08002305 (channelMask == (mChannelMask | mHapticChannelMask) ||
Andy Hung1f439e12015-05-19 12:57:41 -07002306 mChannelMask != AUDIO_CHANNEL_OUT_STEREO ||
2307 (channelMask == AUDIO_CHANNEL_OUT_MONO
2308 /* && mChannelMask == AUDIO_CHANNEL_OUT_STEREO */)) &&
Eric Laurent81784c32012-11-19 14:55:58 -08002309 // hardware sample rate
2310 (sampleRate == mSampleRate) &&
Eric Laurent81784c32012-11-19 14:55:58 -08002311 // normal mixer has an associated fast mixer
2312 hasFastMixer() &&
2313 // there are sufficient fast track slots available
2314 (mFastTrackAvailMask != 0)
2315 // FIXME test that MixerThread for this fast track has a capable output HAL
2316 // FIXME add a permission test also?
2317 ) {
Andy Hunge0a269a2016-03-23 15:13:42 -07002318 // static tracks can have any nonzero framecount, streaming tracks check against minimum.
2319 if (sharedBuffer == 0) {
Glenn Kasten03490092014-05-27 12:30:54 -07002320 // read the fast track multiplier property the first time it is needed
2321 int ok = pthread_once(&sFastTrackMultiplierOnce, sFastTrackMultiplierInit);
2322 if (ok != 0) {
2323 ALOGE("%s pthread_once failed: %d", __func__, ok);
2324 }
Andy Hunge0a269a2016-03-23 15:13:42 -07002325 frameCount = max(frameCount, mFrameCount * sFastTrackMultiplier); // incl framecount 0
Eric Laurent81784c32012-11-19 14:55:58 -08002326 }
Eric Laurent4c415062016-06-17 16:14:16 -07002327
2328 // check compatibility with audio effects.
2329 { // scope for mLock
2330 Mutex::Autolock _l(mLock);
Andy Hungd3bb0ad2016-10-11 17:16:43 -07002331 for (audio_session_t session : {
Eric Laurent3f75a5b2019-11-12 15:55:51 -08002332 AUDIO_SESSION_DEVICE,
Andy Hungd3bb0ad2016-10-11 17:16:43 -07002333 AUDIO_SESSION_OUTPUT_STAGE,
2334 AUDIO_SESSION_OUTPUT_MIX,
2335 sessionId,
2336 }) {
2337 sp<EffectChain> chain = getEffectChain_l(session);
2338 if (chain.get() != nullptr) {
2339 audio_output_flags_t old = *flags;
2340 chain->checkOutputFlagCompatibility(flags);
2341 if (old != *flags) {
2342 ALOGV("AUDIO_OUTPUT_FLAGS denied by effect, session=%d old=%#x new=%#x",
2343 (int)session, (int)old, (int)*flags);
2344 }
Eric Laurent4c415062016-06-17 16:14:16 -07002345 }
2346 }
2347 }
Eric Laurent122f7e72016-06-29 11:53:29 -07002348 ALOGV_IF((*flags & AUDIO_OUTPUT_FLAG_FAST) != 0,
Eric Laurent4c415062016-06-17 16:14:16 -07002349 "AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
2350 frameCount, mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08002351 } else {
Robert Wu4c7bb7d2021-08-12 18:50:13 +00002352 ALOGD("AUDIO_OUTPUT_FLAG_FAST denied: sharedBuffer=%p frameCount=%zu "
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002353 "mFrameCount=%zu format=%#x mFormat=%#x isLinear=%d channelMask=%#x "
Andy Hung6146c082014-03-18 11:56:15 -07002354 "sampleRate=%u mSampleRate=%u "
Eric Laurent81784c32012-11-19 14:55:58 -08002355 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
Glenn Kastend79072e2016-01-06 08:41:20 -08002356 sharedBuffer.get(), frameCount, mFrameCount, format, mFormat,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07002357 audio_is_linear_pcm(format), channelMask, sampleRate,
2358 mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
Eric Laurent4c415062016-06-17 16:14:16 -07002359 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_FAST);
Andy Hung0e48d252015-01-26 11:43:15 -08002360 }
2361 }
Eric Laurent21da6472017-11-09 16:29:26 -08002362
2363 if (!audio_has_proportional_frames(format)) {
2364 if (sharedBuffer != 0) {
2365 // Same comment as below about ignoring frameCount parameter for set()
2366 frameCount = sharedBuffer->size();
2367 } else if (frameCount == 0) {
2368 frameCount = mNormalFrameCount;
2369 }
2370 if (notificationFrameCount != frameCount) {
2371 notificationFrameCount = frameCount;
2372 }
2373 } else if (sharedBuffer != 0) {
2374 // FIXME: Ensure client side memory buffers need
2375 // not have additional alignment beyond sample
2376 // (e.g. 16 bit stereo accessed as 32 bit frame).
2377 size_t alignment = audio_bytes_per_sample(format);
2378 if (alignment & 1) {
2379 // for AUDIO_FORMAT_PCM_24_BIT_PACKED (not exposed through Java).
2380 alignment = 1;
2381 }
2382 uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
2383 size_t frameSize = channelCount * audio_bytes_per_sample(format);
2384 if (channelCount > 1) {
2385 // More than 2 channels does not require stronger alignment than stereo
2386 alignment <<= 1;
2387 }
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07002388 if (((uintptr_t)sharedBuffer->unsecurePointer() & (alignment - 1)) != 0) {
Eric Laurent21da6472017-11-09 16:29:26 -08002389 ALOGE("Invalid buffer alignment: address %p, channel count %u",
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07002390 sharedBuffer->unsecurePointer(), channelCount);
Eric Laurent21da6472017-11-09 16:29:26 -08002391 lStatus = BAD_VALUE;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002392 goto Exit;
2393 }
Eric Laurent21da6472017-11-09 16:29:26 -08002394
2395 // When initializing a shared buffer AudioTrack via constructors,
2396 // there's no frameCount parameter.
2397 // But when initializing a shared buffer AudioTrack via set(),
2398 // there _is_ a frameCount parameter. We silently ignore it.
2399 frameCount = sharedBuffer->size() / frameSize;
2400 } else {
2401 size_t minFrameCount = 0;
2402 // For fast tracks we try to respect the application's request for notifications per buffer.
2403 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
2404 if (notificationsPerBuffer > 0) {
2405 // Avoid possible arithmetic overflow during multiplication.
2406 if (notificationsPerBuffer > SIZE_MAX / mFrameCount) {
2407 ALOGE("Requested notificationPerBuffer=%u ignored for HAL frameCount=%zu",
2408 notificationsPerBuffer, mFrameCount);
2409 } else {
2410 minFrameCount = mFrameCount * notificationsPerBuffer;
2411 }
2412 }
2413 } else {
2414 // For normal PCM streaming tracks, update minimum frame count.
2415 // Buffer depth is forced to be at least 2 x the normal mixer frame count and
2416 // cover audio hardware latency.
2417 // This is probably too conservative, but legacy application code may depend on it.
2418 // If you change this calculation, also review the start threshold which is related.
2419 uint32_t latencyMs = latency_l();
2420 if (latencyMs == 0) {
2421 ALOGE("Error when retrieving output stream latency");
2422 lStatus = UNKNOWN_ERROR;
2423 goto Exit;
2424 }
2425
2426 minFrameCount = AudioSystem::calculateMinFrameCount(latencyMs, mNormalFrameCount,
2427 mSampleRate, sampleRate, speed /*, 0 mNotificationsPerBufferReq*/);
2428
Eric Laurent81784c32012-11-19 14:55:58 -08002429 }
Eric Laurent21da6472017-11-09 16:29:26 -08002430 if (frameCount < minFrameCount) {
Eric Laurent81784c32012-11-19 14:55:58 -08002431 frameCount = minFrameCount;
2432 }
Eric Laurent81784c32012-11-19 14:55:58 -08002433 }
Eric Laurent21da6472017-11-09 16:29:26 -08002434
2435 // Make sure that application is notified with sufficient margin before underrun.
2436 // The client can divide the AudioTrack buffer into sub-buffers,
2437 // and expresses its desire to server as the notification frame count.
2438 if (sharedBuffer == 0 && audio_is_linear_pcm(format)) {
2439 size_t maxNotificationFrames;
2440 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
2441 // notify every HAL buffer, regardless of the size of the track buffer
2442 maxNotificationFrames = mFrameCount;
2443 } else {
Andy Hungfa117802019-04-12 13:50:39 -07002444 // Triple buffer the notification period for a triple buffered mixer period;
2445 // otherwise, double buffering for the notification period is fine.
2446 //
2447 // TODO: This should be moved to AudioTrack to modify the notification period
2448 // on AudioTrack::setBufferSizeInFrames() changes.
2449 const int nBuffering =
2450 (uint64_t{frameCount} * mSampleRate)
2451 / (uint64_t{mNormalFrameCount} * sampleRate) == 3 ? 3 : 2;
2452
Eric Laurent21da6472017-11-09 16:29:26 -08002453 maxNotificationFrames = frameCount / nBuffering;
2454 // If client requested a fast track but this was denied, then use the smaller maximum.
2455 if (requestedFlags & AUDIO_OUTPUT_FLAG_FAST) {
2456 size_t maxNotificationFramesFastDenied = FMS_20 * sampleRate / 1000;
2457 if (maxNotificationFrames > maxNotificationFramesFastDenied) {
2458 maxNotificationFrames = maxNotificationFramesFastDenied;
2459 }
2460 }
2461 }
2462 if (notificationFrameCount == 0 || notificationFrameCount > maxNotificationFrames) {
2463 if (notificationFrameCount == 0) {
2464 ALOGD("Client defaulted notificationFrames to %zu for frameCount %zu",
2465 maxNotificationFrames, frameCount);
2466 } else {
2467 ALOGW("Client adjusted notificationFrames from %zu to %zu for frameCount %zu",
2468 notificationFrameCount, maxNotificationFrames, frameCount);
2469 }
2470 notificationFrameCount = maxNotificationFrames;
2471 }
2472 }
2473
Glenn Kasten74935e42013-12-19 08:56:45 -08002474 *pFrameCount = frameCount;
Eric Laurent21da6472017-11-09 16:29:26 -08002475 *pNotificationFrameCount = notificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08002476
Glenn Kastenc3df8382014-03-13 15:05:25 -07002477 switch (mType) {
2478
2479 case DIRECT:
Phil Burkfdb3c072016-02-09 10:47:02 -08002480 if (audio_is_linear_pcm(format)) { // TODO maybe use audio_has_proportional_frames()?
Eric Laurent81784c32012-11-19 14:55:58 -08002481 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002482 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
2483 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08002484 sampleRate, format, channelMask, mOutput, mFormat);
2485 lStatus = BAD_VALUE;
2486 goto Exit;
2487 }
2488 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002489 break;
2490
2491 case OFFLOAD:
Eric Laurentbfb1b832013-01-07 09:53:42 -08002492 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002493 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
2494 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002495 sampleRate, format, channelMask, mOutput, mFormat);
2496 lStatus = BAD_VALUE;
2497 goto Exit;
2498 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002499 break;
2500
2501 default:
Glenn Kasten993fa062014-05-02 11:14:34 -07002502 if (!audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002503 ALOGE("createTrack_l() Bad parameter: format %#x \""
2504 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002505 format, mOutput, mFormat);
2506 lStatus = BAD_VALUE;
2507 goto Exit;
2508 }
Andy Hungcd044842014-08-07 11:04:34 -07002509 if (sampleRate > mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Eric Laurent81784c32012-11-19 14:55:58 -08002510 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
2511 lStatus = BAD_VALUE;
2512 goto Exit;
2513 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002514 break;
2515
Eric Laurent81784c32012-11-19 14:55:58 -08002516 }
2517
2518 lStatus = initCheck();
2519 if (lStatus != NO_ERROR) {
Glenn Kasten15e57982013-09-24 11:52:37 -07002520 ALOGE("createTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08002521 goto Exit;
2522 }
2523
2524 { // scope for mLock
2525 Mutex::Autolock _l(mLock);
2526
2527 // all tracks in same audio session must share the same routing strategy otherwise
2528 // conflicts will happen when tracks are moved from one output to another by audio policy
2529 // manager
Eric Laurentd66d7a12021-07-13 13:35:32 +02002530 product_strategy_t strategy = getStrategyForStream(streamType);
Eric Laurent81784c32012-11-19 14:55:58 -08002531 for (size_t i = 0; i < mTracks.size(); ++i) {
2532 sp<Track> t = mTracks[i];
Eric Laurent83b88082014-06-20 18:31:16 -07002533 if (t != 0 && t->isExternalTrack()) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02002534 product_strategy_t actual = getStrategyForStream(t->streamType());
Eric Laurent81784c32012-11-19 14:55:58 -08002535 if (sessionId == t->sessionId() && strategy != actual) {
2536 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
2537 strategy, actual);
2538 lStatus = BAD_VALUE;
2539 goto Exit;
2540 }
2541 }
2542 }
2543
yucliuc9c49cd2020-07-13 16:25:21 -07002544 // Set DIRECT flag if current thread is DirectOutputThread. This can
2545 // happen when the playback is rerouted to direct output thread by
2546 // dynamic audio policy.
2547 // Do NOT report the flag changes back to client, since the client
2548 // doesn't explicitly request a direct flag.
2549 audio_output_flags_t trackFlags = *flags;
2550 if (mType == DIRECT) {
2551 trackFlags = static_cast<audio_output_flags_t>(trackFlags | AUDIO_OUTPUT_FLAG_DIRECT);
2552 }
2553
Kevin Rocard1f564ac2018-03-29 13:53:10 -07002554 track = new Track(this, client, streamType, attr, sampleRate, format,
Andy Hung8fe68032017-06-05 16:17:51 -07002555 channelMask, frameCount,
2556 nullptr /* buffer */, (size_t)0 /* bufferSize */, sharedBuffer,
Svet Ganov33761132021-05-13 22:51:08 +00002557 sessionId, creatorPid, attributionSource, trackFlags,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02002558 TrackBase::TYPE_DEFAULT, portId, SIZE_MAX /*frameCountToBeReady*/,
2559 speed, isSpatialized);
Glenn Kasten03003332013-08-06 15:40:54 -07002560
Glenn Kasten03003332013-08-06 15:40:54 -07002561 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
2562 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08002563 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08002564 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08002565 goto Exit;
2566 }
2567 mTracks.add(track);
jiabinf6eb4c32020-02-25 14:06:25 -08002568 {
2569 Mutex::Autolock _atCbL(mAudioTrackCbLock);
2570 if (callback.get() != nullptr) {
jiabin18a4b1c2020-09-17 11:40:42 -07002571 mAudioTrackCallbacks.emplace(track, callback);
jiabinf6eb4c32020-02-25 14:06:25 -08002572 }
2573 }
Eric Laurent81784c32012-11-19 14:55:58 -08002574
2575 sp<EffectChain> chain = getEffectChain_l(sessionId);
2576 if (chain != 0) {
2577 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
2578 track->setMainBuffer(chain->inBuffer());
Eric Laurentd66d7a12021-07-13 13:35:32 +02002579 chain->setStrategy(getStrategyForStream(track->streamType()));
Eric Laurent81784c32012-11-19 14:55:58 -08002580 chain->incTrackCnt();
2581 }
2582
Eric Laurent05067782016-06-01 18:27:28 -07002583 if ((*flags & AUDIO_OUTPUT_FLAG_FAST) && (tid != -1)) {
Eric Laurent81784c32012-11-19 14:55:58 -08002584 pid_t callingPid = IPCThreadState::self()->getCallingPid();
2585 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
2586 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07002587 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08002588 }
2589 }
2590
2591 lStatus = NO_ERROR;
2592
2593Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07002594 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08002595 return track;
2596}
2597
Andy Hung1bc088a2018-02-09 15:57:31 -08002598template<typename T>
Andy Hung1bc088a2018-02-09 15:57:31 -08002599ssize_t AudioFlinger::PlaybackThread::Tracks<T>::remove(const sp<T> &track)
2600{
Andy Hungc0691382018-09-12 18:01:57 -07002601 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08002602 const ssize_t index = mTracks.remove(track);
2603 if (index >= 0) {
Andy Hungc0691382018-09-12 18:01:57 -07002604 if (mSaveDeletedTrackIds) {
Andy Hung1bc088a2018-02-09 15:57:31 -08002605 // We can't directly access mAudioMixer since the caller may be outside of threadLoop.
Andy Hungc0691382018-09-12 18:01:57 -07002606 // Instead, we add to mDeletedTrackIds which is solely used for mAudioMixer update,
Andy Hung1bc088a2018-02-09 15:57:31 -08002607 // to be handled when MixerThread::prepareTracks_l() next changes mAudioMixer.
Andy Hungc0691382018-09-12 18:01:57 -07002608 mDeletedTrackIds.emplace(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08002609 }
Andy Hung1bc088a2018-02-09 15:57:31 -08002610 }
2611 return index;
2612}
2613
Eric Laurent81784c32012-11-19 14:55:58 -08002614uint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const
2615{
2616 return latency;
2617}
2618
2619uint32_t AudioFlinger::PlaybackThread::latency() const
2620{
2621 Mutex::Autolock _l(mLock);
2622 return latency_l();
2623}
2624uint32_t AudioFlinger::PlaybackThread::latency_l() const
2625{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002626 uint32_t latency;
2627 if (initCheck() == NO_ERROR && mOutput->stream->getLatency(&latency) == OK) {
2628 return correctLatency_l(latency);
Eric Laurent81784c32012-11-19 14:55:58 -08002629 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002630 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002631}
2632
2633void AudioFlinger::PlaybackThread::setMasterVolume(float value)
2634{
2635 Mutex::Autolock _l(mLock);
2636 // Don't apply master volume in SW if our HAL can do it for us.
2637 if (mOutput && mOutput->audioHwDev &&
2638 mOutput->audioHwDev->canSetMasterVolume()) {
2639 mMasterVolume = 1.0;
2640 } else {
2641 mMasterVolume = value;
2642 }
2643}
2644
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01002645void AudioFlinger::PlaybackThread::setMasterBalance(float balance)
2646{
2647 mMasterBalance.store(balance);
2648}
2649
Eric Laurent81784c32012-11-19 14:55:58 -08002650void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
2651{
Eric Laurent6acd1d42017-01-04 14:23:29 -08002652 if (isDuplicating()) {
2653 return;
2654 }
Eric Laurent81784c32012-11-19 14:55:58 -08002655 Mutex::Autolock _l(mLock);
2656 // Don't apply master mute in SW if our HAL can do it for us.
2657 if (mOutput && mOutput->audioHwDev &&
2658 mOutput->audioHwDev->canSetMasterMute()) {
2659 mMasterMute = false;
2660 } else {
2661 mMasterMute = muted;
2662 }
2663}
2664
2665void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
2666{
2667 Mutex::Autolock _l(mLock);
2668 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002669 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002670}
2671
2672void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
2673{
2674 Mutex::Autolock _l(mLock);
2675 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002676 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002677}
2678
2679float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
2680{
2681 Mutex::Autolock _l(mLock);
2682 return mStreamTypes[stream].volume;
2683}
2684
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09002685void AudioFlinger::PlaybackThread::setVolumeForOutput_l(float left, float right) const
2686{
2687 mOutput->stream->setVolume(left, right);
2688}
2689
Eric Laurent81784c32012-11-19 14:55:58 -08002690// addTrack_l() must be called with ThreadBase::mLock held
2691status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
2692{
2693 status_t status = ALREADY_EXISTS;
2694
Eric Laurent81784c32012-11-19 14:55:58 -08002695 if (mActiveTracks.indexOf(track) < 0) {
2696 // the track is newly added, make sure it fills up all its
2697 // buffers before playing. This is to ensure the client will
2698 // effectively get the latency it requested.
Eric Laurent83b88082014-06-20 18:31:16 -07002699 if (track->isExternalTrack()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002700 TrackBase::track_state state = track->mState;
2701 mLock.unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002702 status = AudioSystem::startOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002703 mLock.lock();
2704 // abort track was stopped/paused while we released the lock
2705 if (state != track->mState) {
2706 if (status == NO_ERROR) {
2707 mLock.unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002708 AudioSystem::stopOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002709 mLock.lock();
2710 }
2711 return INVALID_OPERATION;
2712 }
2713 // abort if start is rejected by audio policy manager
2714 if (status != NO_ERROR) {
2715 return PERMISSION_DENIED;
2716 }
2717#ifdef ADD_BATTERY_DATA
2718 // to track the speaker usage
2719 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
2720#endif
Eric Laurent09f1ed22019-04-24 17:45:17 -07002721 sendIoConfigEvent_l(AUDIO_CLIENT_STARTED, track->creatorPid(), track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002722 }
2723
Eric Laurent51716182016-02-29 18:00:56 -08002724 // set retry count for buffer fill
2725 if (track->isOffloaded()) {
Eric Laurente93cc032016-05-05 10:15:10 -07002726 if (track->isStopping_1()) {
2727 track->mRetryCount = kMaxTrackStopRetriesOffload;
2728 } else {
2729 track->mRetryCount = kMaxTrackStartupRetriesOffload;
2730 }
2731 track->mFillingUpStatus = mStandby ? Track::FS_FILLING : Track::FS_FILLED;
Eric Laurent51716182016-02-29 18:00:56 -08002732 } else {
2733 track->mRetryCount = kMaxTrackStartupRetries;
Eric Laurente93cc032016-05-05 10:15:10 -07002734 track->mFillingUpStatus =
2735 track->sharedBuffer() != 0 ? Track::FS_FILLED : Track::FS_FILLING;
Eric Laurent51716182016-02-29 18:00:56 -08002736 }
2737
jiabineb3bda02020-06-30 14:07:03 -07002738 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2739 if (mHapticChannelMask != AUDIO_CHANNEL_NONE
2740 && ((track->channelMask() & AUDIO_CHANNEL_HAPTIC_ALL) != AUDIO_CHANNEL_NONE
2741 || (chain != nullptr && chain->containsHapticGeneratingEffect_l()))) {
jiabin57303cc2018-12-18 15:45:57 -08002742 // Unlock due to VibratorService will lock for this call and will
2743 // call Tracks.mute/unmute which also require thread's lock.
2744 mLock.unlock();
2745 const int intensity = AudioFlinger::onExternalVibrationStart(
2746 track->getExternalVibration());
Lais Andradebc3f37a2021-07-02 00:13:19 +01002747 std::optional<media::AudioVibratorInfo> vibratorInfo;
2748 {
2749 // TODO(b/184194780): Use the vibrator information from the vibrator that will be
2750 // used to play this track.
2751 Mutex::Autolock _l(mAudioFlinger->mLock);
2752 vibratorInfo = std::move(mAudioFlinger->getDefaultVibratorInfo_l());
2753 }
jiabin57303cc2018-12-18 15:45:57 -08002754 mLock.lock();
jiabine70bc7f2020-06-30 22:07:55 -07002755 track->setHapticIntensity(static_cast<os::HapticScale>(intensity));
Lais Andradebc3f37a2021-07-02 00:13:19 +01002756 if (vibratorInfo) {
2757 track->setHapticMaxAmplitude(vibratorInfo->maxAmplitude);
2758 }
2759
jiabin57303cc2018-12-18 15:45:57 -08002760 // Haptic playback should be enabled by vibrator service.
2761 if (track->getHapticPlaybackEnabled()) {
2762 // Disable haptic playback of all active track to ensure only
2763 // one track playing haptic if current track should play haptic.
2764 for (const auto &t : mActiveTracks) {
2765 t->setHapticPlaybackEnabled(false);
2766 }
jiabin245cdd92018-12-07 17:55:15 -08002767 }
jiabine70bc7f2020-06-30 22:07:55 -07002768
2769 // Set haptic intensity for effect
2770 if (chain != nullptr) {
2771 chain->setHapticIntensity_l(track->id(), intensity);
2772 }
jiabin245cdd92018-12-07 17:55:15 -08002773 }
2774
Eric Laurent81784c32012-11-19 14:55:58 -08002775 track->mResetDone = false;
Andy Hung59de4262021-06-14 10:53:54 -07002776 track->resetPresentationComplete();
Eric Laurent81784c32012-11-19 14:55:58 -08002777 mActiveTracks.add(track);
Eric Laurentd0107bc2013-06-11 14:38:48 -07002778 if (chain != 0) {
2779 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
2780 track->sessionId());
2781 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08002782 }
2783
Andy Hungc2b11cb2020-04-22 09:04:01 -07002784 track->logBeginInterval(patchSinksToString(&mPatch)); // log to MediaMetrics
Eric Laurent81784c32012-11-19 14:55:58 -08002785 status = NO_ERROR;
2786 }
2787
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08002788 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002789 return status;
2790}
2791
Eric Laurentbfb1b832013-01-07 09:53:42 -08002792bool AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002793{
Eric Laurentbfb1b832013-01-07 09:53:42 -08002794 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08002795 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002796 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
2797 track->mState = TrackBase::STOPPED;
2798 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08002799 removeTrack_l(track);
Eric Laurentab5cdba2014-06-09 17:22:27 -07002800 } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002801 track->mState = TrackBase::STOPPING_1;
Eric Laurent81784c32012-11-19 14:55:58 -08002802 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002803
2804 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08002805}
2806
2807void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
2808{
2809 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Andy Hung2148bf02016-11-28 19:01:02 -08002810
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002811 String8 result;
2812 track->appendDump(result, false /* active */);
2813 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.string());
Andy Hung2148bf02016-11-28 19:01:02 -08002814
Eric Laurent81784c32012-11-19 14:55:58 -08002815 mTracks.remove(track);
jiabin18a4b1c2020-09-17 11:40:42 -07002816 {
2817 Mutex::Autolock _atCbL(mAudioTrackCbLock);
2818 mAudioTrackCallbacks.erase(track);
2819 }
Eric Laurent81784c32012-11-19 14:55:58 -08002820 if (track->isFastTrack()) {
2821 int index = track->mFastIndex;
Glenn Kastendc2c50b2016-04-21 08:13:14 -07002822 ALOG_ASSERT(0 < index && index < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08002823 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
2824 mFastTrackAvailMask |= 1 << index;
2825 // redundant as track is about to be destroyed, for dumpsys only
2826 track->mFastIndex = -1;
2827 }
2828 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2829 if (chain != 0) {
2830 chain->decTrackCnt();
2831 }
2832}
2833
2834String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
2835{
Eric Laurent81784c32012-11-19 14:55:58 -08002836 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002837 String8 out_s8;
2838 if (initCheck() == NO_ERROR && mOutput->stream->getParameters(keys, &out_s8) == OK) {
2839 return out_s8;
Eric Laurent81784c32012-11-19 14:55:58 -08002840 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002841 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08002842}
2843
Mikhail Naganovac917ac2018-11-28 14:03:52 -08002844status_t AudioFlinger::DirectOutputThread::selectPresentation(int presentationId, int programId) {
2845 Mutex::Autolock _l(mLock);
Jasmine Chaeaa10e42021-05-11 10:11:14 +08002846 if (!isStreamInitialized()) {
Mikhail Naganovac917ac2018-11-28 14:03:52 -08002847 return NO_INIT;
2848 }
2849 return mOutput->stream->selectPresentation(presentationId, programId);
2850}
2851
Mikhail Naganov88536df2021-07-26 17:30:29 -07002852void AudioFlinger::PlaybackThread::ioConfigChanged(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -07002853 audio_port_handle_t portId) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002854 ALOGV("PlaybackThread::ioConfigChanged, thread %p, event %d", this, event);
Mikhail Naganov88536df2021-07-26 17:30:29 -07002855 sp<AudioIoDescriptor> desc;
2856 const struct audio_patch patch = isMsdDevice() ? mDownStreamPatch : mPatch;
Eric Laurent81784c32012-11-19 14:55:58 -08002857 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002858 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07002859 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07002860 case AUDIO_OUTPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07002861 desc = sp<AudioIoDescriptor>::make(mId, patch, false /*isInput*/,
2862 mSampleRate, mFormat, mChannelMask,
2863 // FIXME AudioFlinger::frameCount(audio_io_handle_t) instead of mNormalFrameCount?
2864 mNormalFrameCount, mFrameCount, latency_l());
Eric Laurent81784c32012-11-19 14:55:58 -08002865 break;
Eric Laurent09f1ed22019-04-24 17:45:17 -07002866 case AUDIO_CLIENT_STARTED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07002867 desc = sp<AudioIoDescriptor>::make(mId, patch, portId);
Eric Laurent09f1ed22019-04-24 17:45:17 -07002868 break;
Eric Laurent73e26b62015-04-27 16:55:58 -07002869 case AUDIO_OUTPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08002870 default:
Mikhail Naganov88536df2021-07-26 17:30:29 -07002871 desc = sp<AudioIoDescriptor>::make(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08002872 break;
2873 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002874 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08002875}
2876
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002877void AudioFlinger::PlaybackThread::onWriteReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002878{
Eric Laurent3b4529e2013-09-05 18:09:19 -07002879 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002880}
2881
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002882void AudioFlinger::PlaybackThread::onDrainReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002883{
Eric Laurent3b4529e2013-09-05 18:09:19 -07002884 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002885}
2886
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002887void AudioFlinger::PlaybackThread::onError()
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002888{
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002889 mCallbackThread->setAsyncError();
2890}
2891
jiabinf6eb4c32020-02-25 14:06:25 -08002892void AudioFlinger::PlaybackThread::onCodecFormatChanged(
2893 const std::basic_string<uint8_t>& metadataBs)
2894{
2895 std::thread([this, metadataBs]() {
2896 audio_utils::metadata::Data metadata =
2897 audio_utils::metadata::dataFromByteString(metadataBs);
2898 if (metadata.empty()) {
2899 ALOGW("Can not transform the buffer to audio metadata, %s, %d",
2900 reinterpret_cast<char*>(const_cast<uint8_t*>(metadataBs.data())),
2901 (int)metadataBs.size());
2902 return;
2903 }
2904
2905 audio_utils::metadata::ByteString metaDataStr =
2906 audio_utils::metadata::byteStringFromData(metadata);
2907 std::vector metadataVec(metaDataStr.begin(), metaDataStr.end());
2908 Mutex::Autolock _l(mAudioTrackCbLock);
jiabin18a4b1c2020-09-17 11:40:42 -07002909 for (const auto& callbackPair : mAudioTrackCallbacks) {
2910 callbackPair.second->onCodecFormatChanged(metadataVec);
jiabinf6eb4c32020-02-25 14:06:25 -08002911 }
2912 }).detach();
2913}
2914
Eric Laurent3b4529e2013-09-05 18:09:19 -07002915void AudioFlinger::PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002916{
2917 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002918 // reject out of sequence requests
2919 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
2920 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002921 mWaitWorkCV.signal();
2922 }
2923}
2924
Eric Laurent3b4529e2013-09-05 18:09:19 -07002925void AudioFlinger::PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002926{
2927 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002928 // reject out of sequence requests
2929 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
Andy Hungf3234512018-07-03 14:51:47 -07002930 // Register discontinuity when HW drain is completed because that can cause
2931 // the timestamp frame position to reset to 0 for direct and offload threads.
2932 // (Out of sequence requests are ignored, since the discontinuity would be handled
2933 // elsewhere, e.g. in flush).
Dean Wheatley12473e92021-03-18 23:00:55 +11002934 mTimestampVerifier.discontinuity(mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002935 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002936 mWaitWorkCV.signal();
2937 }
2938}
2939
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002940void AudioFlinger::PlaybackThread::readOutputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08002941{
Glenn Kastenadad3d72014-02-21 14:51:43 -08002942 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Mikhail Naganov560637e2021-03-31 22:40:13 +00002943 const audio_config_base_t audioConfig = mOutput->getAudioProperties();
2944 mSampleRate = audioConfig.sample_rate;
2945 mChannelMask = audioConfig.channel_mask;
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002946 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002947 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002948 }
Eric Laurentb3f315a2021-07-13 15:09:05 +02002949 if (hasMixer() && !isValidPcmSinkChannelMask(mChannelMask)) {
Andy Hung9a592762014-07-21 21:56:01 -07002950 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output",
2951 mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002952 }
Eric Laurentf1f22e72021-07-13 14:04:14 +02002953
2954 if (mMixerChannelMask == AUDIO_CHANNEL_NONE) {
2955 mMixerChannelMask = mChannelMask;
2956 }
2957
Andy Hunge5412692014-05-16 11:25:07 -07002958 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01002959 mBalance.setChannelMask(mChannelMask);
Phil Burkca5e6142015-07-14 09:42:29 -07002960
Eric Laurentf1f22e72021-07-13 14:04:14 +02002961 uint32_t mixerChannelCount = audio_channel_count_from_out_mask(mMixerChannelMask);
2962
Phil Burkca5e6142015-07-14 09:42:29 -07002963 // Get actual HAL format.
Mikhail Naganov560637e2021-03-31 22:40:13 +00002964 status_t result = mOutput->stream->getAudioProperties(nullptr, nullptr, &mHALFormat);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002965 LOG_ALWAYS_FATAL_IF(result != OK, "Error when retrieving output stream format: %d", result);
Phil Burkca5e6142015-07-14 09:42:29 -07002966 // Get format from the shim, which will be different than the HAL format
2967 // if playing compressed audio over HDMI passthrough.
Mikhail Naganov560637e2021-03-31 22:40:13 +00002968 mFormat = audioConfig.format;
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002969 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002970 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002971 }
Eric Laurentb3f315a2021-07-13 15:09:05 +02002972 if (hasMixer() && !isValidPcmSinkFormat(mFormat)) {
Andy Hung6146c082014-03-18 11:56:15 -07002973 LOG_FATAL("HAL format %#x not supported for mixed output",
2974 mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002975 }
Phil Burk062e67a2015-02-11 13:40:50 -08002976 mFrameSize = mOutput->getFrameSize();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002977 result = mOutput->stream->getBufferSize(&mBufferSize);
2978 LOG_ALWAYS_FATAL_IF(result != OK,
2979 "Error when retrieving output stream buffer size: %d", result);
Glenn Kasten70949c42013-08-06 07:40:12 -07002980 mFrameCount = mBufferSize / mFrameSize;
Eric Laurentb3f315a2021-07-13 15:09:05 +02002981 if (hasMixer() && (mFrameCount & 15)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002982 ALOGW("HAL output buffer size is %zu frames but AudioMixer requires multiples of 16 frames",
Eric Laurent81784c32012-11-19 14:55:58 -08002983 mFrameCount);
2984 }
2985
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002986 if (mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING) {
2987 if (mOutput->stream->setCallback(this) == OK) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002988 mUseAsyncWrite = true;
Eric Laurent4de95592013-09-26 15:28:21 -07002989 mCallbackThread = new AudioFlinger::AsyncCallbackThread(this);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002990 }
2991 }
2992
Eric Laurentd1f69b02014-12-15 14:33:13 -08002993 mHwSupportsPause = false;
2994 if (mOutput->flags & AUDIO_OUTPUT_FLAG_DIRECT) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002995 bool supportsPause = false, supportsResume = false;
2996 if (mOutput->stream->supportsPauseAndResume(&supportsPause, &supportsResume) == OK) {
2997 if (supportsPause && supportsResume) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08002998 mHwSupportsPause = true;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002999 } else if (supportsPause) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08003000 ALOGW("direct output implements pause but not resume");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003001 } else if (supportsResume) {
3002 ALOGW("direct output implements resume but not pause");
Eric Laurentd1f69b02014-12-15 14:33:13 -08003003 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08003004 }
3005 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07003006 if (!mHwSupportsPause && mOutput->flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) {
3007 LOG_ALWAYS_FATAL("HW_AV_SYNC requested but HAL does not implement pause and resume");
3008 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08003009
Andy Hungfbfc3952015-01-15 13:33:51 -08003010 if (mType == DUPLICATING && mMixerBufferEnabled && mEffectBufferEnabled) {
3011 // For best precision, we use float instead of the associated output
3012 // device format (typically PCM 16 bit).
3013
3014 mFormat = AUDIO_FORMAT_PCM_FLOAT;
3015 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
3016 mBufferSize = mFrameSize * mFrameCount;
3017
3018 // TODO: We currently use the associated output device channel mask and sample rate.
3019 // (1) Perhaps use the ORed channel mask of all downstream MixerThreads
3020 // (if a valid mask) to avoid premature downmix.
3021 // (2) Perhaps use the maximum sample rate of all downstream MixerThreads
3022 // instead of the output device sample rate to avoid loss of high frequency information.
3023 // This may need to be updated as MixerThread/OutputTracks are added and not here.
3024 }
3025
Andy Hung09a50072014-02-27 14:30:47 -08003026 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08003027 double multiplier = 1.0;
Andy Hungd3639922022-04-28 18:00:49 -07003028 // Note: mType == SPATIALIZER does not support FastMixer.
Eric Laurent81784c32012-11-19 14:55:58 -08003029 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
3030 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08003031 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
3032 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Haynes Mathew George227a14b2016-05-09 12:45:48 -07003033
Eric Laurent81784c32012-11-19 14:55:58 -08003034 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
3035 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
3036 maxNormalFrameCount = maxNormalFrameCount & ~15;
3037 if (maxNormalFrameCount < minNormalFrameCount) {
3038 maxNormalFrameCount = minNormalFrameCount;
3039 }
3040 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
3041 if (multiplier <= 1.0) {
3042 multiplier = 1.0;
3043 } else if (multiplier <= 2.0) {
3044 if (2 * mFrameCount <= maxNormalFrameCount) {
3045 multiplier = 2.0;
3046 } else {
3047 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
3048 }
3049 } else {
Haynes Mathew George227a14b2016-05-09 12:45:48 -07003050 multiplier = floor(multiplier);
Eric Laurent81784c32012-11-19 14:55:58 -08003051 }
3052 }
3053 mNormalFrameCount = multiplier * mFrameCount;
3054 // round up to nearest 16 frames to satisfy AudioMixer
Eric Laurentb3f315a2021-07-13 15:09:05 +02003055 if (hasMixer()) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07003056 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
3057 }
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003058 ALOGI("HAL output buffer size %zu frames, normal sink buffer size %zu frames", mFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08003059 mNormalFrameCount);
3060
Andy Hung08fb1742015-05-31 23:22:10 -07003061 // Check if we want to throttle the processing to no more than 2x normal rate
3062 mThreadThrottle = property_get_bool("af.thread.throttle", true /* default_value */);
Andy Hung40eb1a12015-06-18 13:42:02 -07003063 mThreadThrottleTimeMs = 0;
3064 mThreadThrottleEndMs = 0;
Andy Hung08fb1742015-05-31 23:22:10 -07003065 mHalfBufferMs = mNormalFrameCount * 1000 / (2 * mSampleRate);
3066
Andy Hung010a1a12014-03-13 13:57:33 -07003067 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
3068 // Originally this was int16_t[] array, need to remove legacy implications.
3069 free(mSinkBuffer);
3070 mSinkBuffer = NULL;
Eric Laurent39095982021-08-24 18:29:27 +02003071
Andy Hung5b10a202014-03-13 13:59:29 -07003072 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
3073 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
3074 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07003075 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08003076
Andy Hung69aed5f2014-02-25 17:24:40 -08003077 // We resize the mMixerBuffer according to the requirements of the sink buffer which
3078 // drives the output.
3079 free(mMixerBuffer);
3080 mMixerBuffer = NULL;
3081 if (mMixerBufferEnabled) {
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01003082 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // no longer valid: AUDIO_FORMAT_PCM_16_BIT.
Eric Laurentf1f22e72021-07-13 14:04:14 +02003083 mMixerBufferSize = mNormalFrameCount * mixerChannelCount
Andy Hung69aed5f2014-02-25 17:24:40 -08003084 * audio_bytes_per_sample(mMixerBufferFormat);
3085 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
3086 }
Andy Hung98ef9782014-03-04 14:46:50 -08003087 free(mEffectBuffer);
3088 mEffectBuffer = NULL;
3089 if (mEffectBufferEnabled) {
rago94a1ee82017-07-21 15:11:02 -07003090 mEffectBufferFormat = EFFECT_BUFFER_FORMAT;
Eric Laurentf1f22e72021-07-13 14:04:14 +02003091 mEffectBufferSize = mNormalFrameCount * mixerChannelCount
Andy Hung98ef9782014-03-04 14:46:50 -08003092 * audio_bytes_per_sample(mEffectBufferFormat);
3093 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
3094 }
Andy Hung69aed5f2014-02-25 17:24:40 -08003095
Eric Laurentb62d0362021-10-26 17:40:18 +02003096 if (mType == SPATIALIZER) {
3097 free(mPostSpatializerBuffer);
3098 mPostSpatializerBuffer = nullptr;
3099 mPostSpatializerBufferSize = mNormalFrameCount * mChannelCount
3100 * audio_bytes_per_sample(mEffectBufferFormat);
3101 (void)posix_memalign(&mPostSpatializerBuffer, 32, mPostSpatializerBufferSize);
3102 }
3103
Mikhail Naganov55773032020-10-01 15:08:13 -07003104 mHapticChannelMask = static_cast<audio_channel_mask_t>(mChannelMask & AUDIO_CHANNEL_HAPTIC_ALL);
3105 mChannelMask = static_cast<audio_channel_mask_t>(mChannelMask & ~mHapticChannelMask);
jiabin245cdd92018-12-07 17:55:15 -08003106 mHapticChannelCount = audio_channel_count_from_out_mask(mHapticChannelMask);
3107 mChannelCount -= mHapticChannelCount;
Eric Laurentf1f22e72021-07-13 14:04:14 +02003108 mMixerChannelMask = static_cast<audio_channel_mask_t>(mMixerChannelMask & ~mHapticChannelMask);
jiabin245cdd92018-12-07 17:55:15 -08003109
Eric Laurent81784c32012-11-19 14:55:58 -08003110 // force reconfiguration of effect chains and engines to take new buffer size and audio
3111 // parameters into account
Glenn Kastendeca2ae2014-02-07 10:25:56 -08003112 // Note that mLock is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08003113 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
3114 // matter.
3115 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
3116 Vector< sp<EffectChain> > effectChains = mEffectChains;
3117 for (size_t i = 0; i < effectChains.size(); i ++) {
Eric Laurent6c796322019-04-09 14:13:17 -07003118 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(),
3119 this/* srcThread */, this/* dstThread */);
Eric Laurent81784c32012-11-19 14:55:58 -08003120 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08003121
George Burgess IV5e4d86f2020-02-18 12:55:36 -08003122 audio_output_flags_t flags = mOutput->flags;
Andy Hungcf10d742020-04-28 15:38:24 -07003123 mediametrics::LogItem item(mThreadMetrics.getMetricsId()); // TODO: method in ThreadMetrics?
Andy Hungb68f5eb2019-12-03 16:49:17 -08003124 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
3125 .set(AMEDIAMETRICS_PROP_ENCODING, formatToString(mFormat).c_str())
3126 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
3127 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
3128 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
3129 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mNormalFrameCount)
3130 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
3131 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELMASK,
3132 (int32_t)mHapticChannelMask)
3133 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELCOUNT,
3134 (int32_t)mHapticChannelCount)
3135 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_ENCODING,
3136 formatToString(mHALFormat).c_str())
3137 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_FRAMECOUNT,
3138 (int32_t)mFrameCount) // sic - added HAL
3139 ;
3140 uint32_t latencyMs;
3141 if (mOutput->stream->getLatency(&latencyMs) == NO_ERROR) {
3142 item.set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_LATENCYMS, (double)latencyMs);
3143 }
3144 item.record();
Eric Laurent81784c32012-11-19 14:55:58 -08003145}
3146
Kevin Rocard069c2712018-03-29 19:09:14 -07003147void AudioFlinger::PlaybackThread::updateMetadata_l()
3148{
Jasmine Chaeaa10e42021-05-11 10:11:14 +08003149 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
Kevin Rocard12381092018-04-11 09:19:59 -07003150 return; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -07003151 }
3152 StreamOutHalInterface::SourceMetadata metadata;
Kevin Rocard12381092018-04-11 09:19:59 -07003153 auto backInserter = std::back_inserter(metadata.tracks);
Kevin Rocard069c2712018-03-29 19:09:14 -07003154 for (const sp<Track> &track : mActiveTracks) {
3155 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurent49e39282022-06-24 18:42:45 +02003156 track->copyMetadataTo(backInserter);
Kevin Rocard069c2712018-03-29 19:09:14 -07003157 }
Kevin Rocard12381092018-04-11 09:19:59 -07003158 sendMetadataToBackend_l(metadata);
Kevin Rocard80ee2722018-04-11 15:53:48 +00003159}
Kevin Rocardc86a7f72018-04-03 09:00:09 -07003160
Kevin Rocard12381092018-04-11 09:19:59 -07003161void AudioFlinger::PlaybackThread::sendMetadataToBackend_l(
3162 const StreamOutHalInterface::SourceMetadata& metadata)
3163{
3164 mOutput->stream->updateSourceMetadata(metadata);
3165};
3166
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003167status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
Eric Laurent81784c32012-11-19 14:55:58 -08003168{
3169 if (halFrames == NULL || dspFrames == NULL) {
3170 return BAD_VALUE;
3171 }
3172 Mutex::Autolock _l(mLock);
3173 if (initCheck() != NO_ERROR) {
3174 return INVALID_OPERATION;
3175 }
Andy Hung818e7a32016-02-16 18:08:07 -08003176 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08003177 *halFrames = framesWritten;
3178
3179 if (isSuspended()) {
3180 // return an estimation of rendered frames when the output is suspended
3181 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08003182 *dspFrames = (uint32_t)
3183 (framesWritten >= (int64_t)latencyFrames ? framesWritten - latencyFrames : 0);
Eric Laurent81784c32012-11-19 14:55:58 -08003184 return NO_ERROR;
3185 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003186 status_t status;
3187 uint32_t frames;
Phil Burk062e67a2015-02-11 13:40:50 -08003188 status = mOutput->getRenderPosition(&frames);
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003189 *dspFrames = (size_t)frames;
3190 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08003191 }
3192}
3193
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08003194product_strategy_t AudioFlinger::PlaybackThread::getStrategyForSession_l(audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08003195{
3196 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
3197 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
3198 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02003199 return getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurent81784c32012-11-19 14:55:58 -08003200 }
3201 for (size_t i = 0; i < mTracks.size(); i++) {
3202 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08003203 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02003204 return getStrategyForStream(track->streamType());
Eric Laurent81784c32012-11-19 14:55:58 -08003205 }
3206 }
Eric Laurentd66d7a12021-07-13 13:35:32 +02003207 return getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurent81784c32012-11-19 14:55:58 -08003208}
3209
3210
Phil Burk062e67a2015-02-11 13:40:50 -08003211AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurent81784c32012-11-19 14:55:58 -08003212{
3213 Mutex::Autolock _l(mLock);
3214 return mOutput;
3215}
3216
Phil Burk062e67a2015-02-11 13:40:50 -08003217AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
Eric Laurent81784c32012-11-19 14:55:58 -08003218{
3219 Mutex::Autolock _l(mLock);
3220 AudioStreamOut *output = mOutput;
3221 mOutput = NULL;
3222 // FIXME FastMixer might also have a raw ptr to mOutputSink;
3223 // must push a NULL and wait for ack
3224 mOutputSink.clear();
3225 mPipeSink.clear();
3226 mNormalSink.clear();
3227 return output;
3228}
3229
3230// this method must always be called either with ThreadBase mLock held or inside the thread loop
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003231sp<StreamHalInterface> AudioFlinger::PlaybackThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08003232{
3233 if (mOutput == NULL) {
3234 return NULL;
3235 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003236 return mOutput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08003237}
3238
3239uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
3240{
3241 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
3242}
3243
3244status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
3245{
3246 if (!isValidSyncEvent(event)) {
3247 return BAD_VALUE;
3248 }
3249
3250 Mutex::Autolock _l(mLock);
3251
3252 for (size_t i = 0; i < mTracks.size(); ++i) {
3253 sp<Track> track = mTracks[i];
3254 if (event->triggerSession() == track->sessionId()) {
3255 (void) track->setSyncEvent(event);
3256 return NO_ERROR;
3257 }
3258 }
3259
3260 return NAME_NOT_FOUND;
3261}
3262
3263bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
3264{
3265 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
3266}
3267
3268void AudioFlinger::PlaybackThread::threadLoop_removeTracks(
3269 const Vector< sp<Track> >& tracksToRemove)
3270{
Andy Hungfe726a62018-09-27 15:17:25 -07003271 // Miscellaneous track cleanup when removed from the active list,
3272 // called without Thread lock but synchronized with threadLoop processing.
Eric Laurentbfb1b832013-01-07 09:53:42 -08003273#ifdef ADD_BATTERY_DATA
Andy Hungfe726a62018-09-27 15:17:25 -07003274 for (const auto& track : tracksToRemove) {
3275 if (track->isExternalTrack()) {
3276 // to track the speaker usage
3277 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Eric Laurent81784c32012-11-19 14:55:58 -08003278 }
3279 }
Andy Hungfe726a62018-09-27 15:17:25 -07003280#else
3281 (void)tracksToRemove; // suppress unused warning
3282#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003283}
3284
3285void AudioFlinger::PlaybackThread::checkSilentMode_l()
3286{
3287 if (!mMasterMute) {
3288 char value[PROPERTY_VALUE_MAX];
jiabin0a957d32020-04-29 10:56:20 -07003289 if (mOutDeviceTypeAddrs.empty()) {
3290 ALOGD("ro.audio.silent is ignored since no output device is set");
3291 return;
3292 }
jiabinc52b1ff2019-10-31 17:20:42 -07003293 if (isSingleDeviceType(outDeviceTypes(), AUDIO_DEVICE_OUT_REMOTE_SUBMIX)) {
Jean-Michel Trivi32f37c22016-03-31 16:00:32 -07003294 ALOGD("ro.audio.silent will be ignored for threads on AUDIO_DEVICE_OUT_REMOTE_SUBMIX");
3295 return;
3296 }
Eric Laurent81784c32012-11-19 14:55:58 -08003297 if (property_get("ro.audio.silent", value, "0") > 0) {
3298 char *endptr;
3299 unsigned long ul = strtoul(value, &endptr, 0);
3300 if (*endptr == '\0' && ul != 0) {
3301 ALOGD("Silence is golden");
3302 // The setprop command will not allow a property to be changed after
3303 // the first time it is set, so we don't have to worry about un-muting.
3304 setMasterMute_l(true);
3305 }
3306 }
3307 }
3308}
3309
3310// shared by MIXER and DIRECT, overridden by DUPLICATING
Eric Laurentbfb1b832013-01-07 09:53:42 -08003311ssize_t AudioFlinger::PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08003312{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07003313 LOG_HIST_TS();
Eric Laurent81784c32012-11-19 14:55:58 -08003314 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003315 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07003316 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08003317
3318 // If an NBAIO sink is present, use it to write the normal mixer's submix
3319 if (mNormalSink != 0) {
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003320
Andy Hung010a1a12014-03-13 13:57:33 -07003321 const size_t count = mBytesRemaining / mFrameSize;
3322
Simon Wilson2d590962012-11-29 15:18:50 -08003323 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08003324 // update the setpoint when AudioFlinger::mScreenState changes
3325 uint32_t screenState = AudioFlinger::mScreenState;
3326 if (screenState != mScreenState) {
3327 mScreenState = screenState;
3328 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
3329 if (pipe != NULL) {
3330 pipe->setAvgFrames((mScreenState & 1) ?
3331 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
3332 }
3333 }
Andy Hung010a1a12014-03-13 13:57:33 -07003334 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08003335 ATRACE_END();
Eric Laurent81784c32012-11-19 14:55:58 -08003336 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07003337 bytesWritten = framesWritten * mFrameSize;
Andy Hung8946a282018-04-19 20:04:56 -07003338#ifdef TEE_SINK
3339 mTee.write((char *)mSinkBuffer + offset, framesWritten);
3340#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003341 } else {
3342 bytesWritten = framesWritten;
3343 }
3344 // otherwise use the HAL / AudioStreamOut directly
3345 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003346 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07003347
Eric Laurentbfb1b832013-01-07 09:53:42 -08003348 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003349 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
3350 mWriteAckSequence += 2;
3351 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003352 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003353 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003354 }
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07003355 ATRACE_BEGIN("write");
Glenn Kasten767094d2013-08-23 13:51:43 -07003356 // FIXME We should have an implementation of timestamps for direct output threads.
3357 // They are used e.g for multichannel PCM playback over HDMI.
Phil Burk062e67a2015-02-11 13:40:50 -08003358 bytesWritten = mOutput->write((char *)mSinkBuffer + offset, mBytesRemaining);
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07003359 ATRACE_END();
Eric Laurent51716182016-02-29 18:00:56 -08003360
Eric Laurentbfb1b832013-01-07 09:53:42 -08003361 if (mUseAsyncWrite &&
3362 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
3363 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07003364 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003365 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003366 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003367 }
Eric Laurent81784c32012-11-19 14:55:58 -08003368 }
3369
Eric Laurent81784c32012-11-19 14:55:58 -08003370 mNumWrites++;
3371 mInWrite = false;
Andy Hungcf10d742020-04-28 15:38:24 -07003372 if (mStandby) {
3373 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07003374 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -07003375 mStandby = false;
3376 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003377 return bytesWritten;
3378}
3379
3380void AudioFlinger::PlaybackThread::threadLoop_drain()
3381{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003382 bool supportsDrain = false;
3383 if (mOutput->stream->supportsDrain(&supportsDrain) == OK && supportsDrain) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003384 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
3385 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003386 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
3387 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003388 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003389 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003390 }
Mikhail Naganovcbc8f612016-10-11 18:05:13 -07003391 status_t result = mOutput->stream->drain(mMixerStatus == MIXER_DRAIN_TRACK);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003392 ALOGE_IF(result != OK, "Error when draining stream: %d", result);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003393 }
3394}
3395
3396void AudioFlinger::PlaybackThread::threadLoop_exit()
3397{
Eric Laurent275e8e92014-11-30 15:14:47 -08003398 {
3399 Mutex::Autolock _l(mLock);
3400 for (size_t i = 0; i < mTracks.size(); i++) {
3401 sp<Track> track = mTracks[i];
3402 track->invalidate();
3403 }
Andy Hungdae27702016-10-31 14:01:16 -07003404 // Clear ActiveTracks to update BatteryNotifier in case active tracks remain.
3405 // After we exit there are no more track changes sent to BatteryNotifier
3406 // because that requires an active threadLoop.
3407 // TODO: should we decActiveTrackCnt() of the cleared track effect chain?
3408 mActiveTracks.clear();
Eric Laurent275e8e92014-11-30 15:14:47 -08003409 }
Eric Laurent81784c32012-11-19 14:55:58 -08003410}
3411
3412/*
3413The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08003414 - mSinkBufferSize from frame count * frame size
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003415 - mActiveSleepTimeUs from activeSleepTimeUs()
3416 - mIdleSleepTimeUs from idleSleepTimeUs()
Eric Laurent42537be2016-01-08 17:16:42 -08003417 - mStandbyDelayNs from mActiveSleepTimeUs (DIRECT only) or forced to at least
3418 kDefaultStandbyTimeInNsecs when connected to an A2DP device.
Eric Laurent81784c32012-11-19 14:55:58 -08003419 - maxPeriod from frame count and sample rate (MIXER only)
3420
3421The parameters that affect these derived values are:
3422 - frame count
3423 - frame size
3424 - sample rate
3425 - device type: A2DP or not
3426 - device latency
3427 - format: PCM or not
3428 - active sleep time
3429 - idle sleep time
3430*/
3431
3432void AudioFlinger::PlaybackThread::cacheParameters_l()
3433{
Andy Hung25c2dac2014-02-27 14:56:00 -08003434 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003435 mActiveSleepTimeUs = activeSleepTimeUs();
3436 mIdleSleepTimeUs = idleSleepTimeUs();
Eric Laurent42537be2016-01-08 17:16:42 -08003437
3438 // make sure standby delay is not too short when connected to an A2DP sink to avoid
3439 // truncating audio when going to standby.
3440 mStandbyDelayNs = AudioFlinger::mStandbyTimeInNsecs;
jiabinc52b1ff2019-10-31 17:20:42 -07003441 if (!Intersection(outDeviceTypes(), getAudioDeviceOutAllA2dpSet()).empty()) {
Eric Laurent42537be2016-01-08 17:16:42 -08003442 if (mStandbyDelayNs < kDefaultStandbyTimeInNsecs) {
3443 mStandbyDelayNs = kDefaultStandbyTimeInNsecs;
3444 }
3445 }
Eric Laurent81784c32012-11-19 14:55:58 -08003446}
3447
Eric Laurent13084622016-05-17 10:51:49 -07003448bool AudioFlinger::PlaybackThread::invalidateTracks_l(audio_stream_type_t streamType)
Eric Laurent81784c32012-11-19 14:55:58 -08003449{
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003450 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %zu",
Eric Laurent81784c32012-11-19 14:55:58 -08003451 this, streamType, mTracks.size());
Eric Laurent13084622016-05-17 10:51:49 -07003452 bool trackMatch = false;
Eric Laurent81784c32012-11-19 14:55:58 -08003453 size_t size = mTracks.size();
3454 for (size_t i = 0; i < size; i++) {
3455 sp<Track> t = mTracks[i];
Eric Laurentd60560a2015-04-10 11:31:20 -07003456 if (t->streamType() == streamType && t->isExternalTrack()) {
Glenn Kasten5736c352012-12-04 12:12:34 -08003457 t->invalidate();
Eric Laurent13084622016-05-17 10:51:49 -07003458 trackMatch = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003459 }
3460 }
Eric Laurent13084622016-05-17 10:51:49 -07003461 return trackMatch;
Eric Laurent81784c32012-11-19 14:55:58 -08003462}
3463
Haynes Mathew George05317d22016-05-03 16:34:26 -07003464void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
3465{
3466 Mutex::Autolock _l(mLock);
3467 invalidateTracks_l(streamType);
3468}
3469
jiabinf042b9b2021-05-07 23:46:28 +00003470// getTrackById_l must be called with holding thread lock
3471AudioFlinger::PlaybackThread::Track* AudioFlinger::PlaybackThread::getTrackById_l(
3472 audio_port_handle_t trackPortId) {
3473 for (size_t i = 0; i < mTracks.size(); i++) {
3474 if (mTracks[i]->portId() == trackPortId) {
3475 return mTracks[i].get();
3476 }
3477 }
3478 return nullptr;
3479}
3480
Eric Laurent81784c32012-11-19 14:55:58 -08003481status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
3482{
Glenn Kastend848eb42016-03-08 13:42:11 -08003483 audio_session_t session = chain->sessionId();
Mikhail Naganov022b9952017-01-04 16:36:51 -08003484 sp<EffectBufferHalInterface> halInBuffer, halOutBuffer;
Eric Laurentb62d0362021-10-26 17:40:18 +02003485 effect_buffer_t *buffer = nullptr; // only used for non global sessions
3486
Andy Hungd3639922022-04-28 18:00:49 -07003487 if (mType == SPATIALIZER) {
Eric Laurentb62d0362021-10-26 17:40:18 +02003488 if (!audio_is_global_session(session)) {
3489 // player sessions on a spatializer output will use a dedicated input buffer and
3490 // will either output multi channel to mEffectBuffer if the track is spatilaized
3491 // or stereo to mPostSpatializerBuffer if not spatialized.
3492 uint32_t channelMask;
3493 bool isSessionSpatialized =
3494 (hasAudioSession_l(session) & ThreadBase::SPATIALIZED_SESSION) != 0;
3495 if (isSessionSpatialized) {
3496 channelMask = mMixerChannelMask;
3497 } else {
3498 channelMask = mChannelMask;
3499 }
Eric Laurentf1f22e72021-07-13 14:04:14 +02003500 size_t numSamples = mNormalFrameCount
Eric Laurentb62d0362021-10-26 17:40:18 +02003501 * (audio_channel_count_from_out_mask(channelMask) + mHapticChannelCount);
Kevin Rocard7588ff42018-01-08 11:11:30 -08003502 status_t result = mAudioFlinger->mEffectsFactoryHal->allocateBuffer(
rago94a1ee82017-07-21 15:11:02 -07003503 numSamples * sizeof(effect_buffer_t),
Mikhail Naganov022b9952017-01-04 16:36:51 -08003504 &halInBuffer);
3505 if (result != OK) return result;
Eric Laurentb62d0362021-10-26 17:40:18 +02003506
3507 result = mAudioFlinger->mEffectsFactoryHal->mirrorBuffer(
3508 isSessionSpatialized ? mEffectBuffer : mPostSpatializerBuffer,
3509 isSessionSpatialized ? mEffectBufferSize : mPostSpatializerBufferSize,
3510 &halOutBuffer);
3511 if (result != OK) return result;
3512
rago94a1ee82017-07-21 15:11:02 -07003513#ifdef FLOAT_EFFECT_CHAIN
3514 buffer = halInBuffer->audioBuffer()->f32;
3515#else
Mikhail Naganov022b9952017-01-04 16:36:51 -08003516 buffer = halInBuffer->audioBuffer()->s16;
rago94a1ee82017-07-21 15:11:02 -07003517#endif
Mikhail Naganov022b9952017-01-04 16:36:51 -08003518 ALOGV("addEffectChain_l() creating new input buffer %p session %d",
3519 buffer, session);
Eric Laurentb62d0362021-10-26 17:40:18 +02003520 } else {
3521 // A global session on a SPATIALIZER thread is either OUTPUT_STAGE or DEVICE
3522 // - OUTPUT_STAGE session uses the mEffectBuffer as input buffer and
3523 // mPostSpatializerBuffer as output buffer
3524 // - DEVICE session uses the mPostSpatializerBuffer as input and output buffer.
3525 status_t result = mAudioFlinger->mEffectsFactoryHal->mirrorBuffer(
3526 mEffectBuffer, mEffectBufferSize, &halInBuffer);
3527 if (result != OK) return result;
3528 result = mAudioFlinger->mEffectsFactoryHal->mirrorBuffer(
3529 mPostSpatializerBuffer, mPostSpatializerBufferSize, &halOutBuffer);
3530 if (result != OK) return result;
Eric Laurent81784c32012-11-19 14:55:58 -08003531
Eric Laurentb62d0362021-10-26 17:40:18 +02003532 if (session == AUDIO_SESSION_DEVICE) {
3533 halInBuffer = halOutBuffer;
3534 }
3535 }
3536 } else {
3537 status_t result = mAudioFlinger->mEffectsFactoryHal->mirrorBuffer(
3538 mEffectBufferEnabled ? mEffectBuffer : mSinkBuffer,
3539 mEffectBufferEnabled ? mEffectBufferSize : mSinkBufferSize,
3540 &halInBuffer);
3541 if (result != OK) return result;
3542 halOutBuffer = halInBuffer;
3543 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
3544 if (!audio_is_global_session(session)) {
3545 buffer = reinterpret_cast<effect_buffer_t*>(halInBuffer->externalData());
3546 // Only one effect chain can be present in direct output thread and it uses
3547 // the sink buffer as input
3548 if (mType != DIRECT) {
3549 size_t numSamples = mNormalFrameCount
3550 * (audio_channel_count_from_out_mask(mMixerChannelMask)
3551 + mHapticChannelCount);
3552 status_t result = mAudioFlinger->mEffectsFactoryHal->allocateBuffer(
3553 numSamples * sizeof(effect_buffer_t),
3554 &halInBuffer);
3555 if (result != OK) return result;
3556#ifdef FLOAT_EFFECT_CHAIN
3557 buffer = halInBuffer->audioBuffer()->f32;
3558#else
3559 buffer = halInBuffer->audioBuffer()->s16;
3560#endif
3561 ALOGV("addEffectChain_l() creating new input buffer %p session %d",
3562 buffer, session);
3563 }
3564 }
3565 }
3566
3567 if (!audio_is_global_session(session)) {
Eric Laurent81784c32012-11-19 14:55:58 -08003568 // Attach all tracks with same session ID to this chain.
3569 for (size_t i = 0; i < mTracks.size(); ++i) {
3570 sp<Track> track = mTracks[i];
3571 if (session == track->sessionId()) {
Eric Laurentb62d0362021-10-26 17:40:18 +02003572 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p",
3573 track.get(), buffer);
Eric Laurent81784c32012-11-19 14:55:58 -08003574 track->setMainBuffer(buffer);
3575 chain->incTrackCnt();
3576 }
3577 }
3578
3579 // indicate all active tracks in the chain
Andy Hungdae27702016-10-31 14:01:16 -07003580 for (const sp<Track> &track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08003581 if (session == track->sessionId()) {
Eric Laurentb62d0362021-10-26 17:40:18 +02003582 ALOGV("addEffectChain_l() activating track %p on session %d",
3583 track.get(), session);
Eric Laurent81784c32012-11-19 14:55:58 -08003584 chain->incActiveTrackCnt();
3585 }
3586 }
3587 }
Eric Laurentb62d0362021-10-26 17:40:18 +02003588
Eric Laurentaaa44472014-09-12 17:41:50 -07003589 chain->setThread(this);
Mikhail Naganov022b9952017-01-04 16:36:51 -08003590 chain->setInBuffer(halInBuffer);
3591 chain->setOutBuffer(halOutBuffer);
Eric Laurent3f75a5b2019-11-12 15:55:51 -08003592 // Effect chain for session AUDIO_SESSION_DEVICE is inserted at end of effect
3593 // chains list in order to be processed last as it contains output device effects.
3594 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted just before to apply post
3595 // processing effects specific to an output stream before effects applied to all streams
3596 // routed to a given device.
Eric Laurent81784c32012-11-19 14:55:58 -08003597 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
3598 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Glenn Kastend848eb42016-03-08 13:42:11 -08003599 // after track specific effects and before output stage.
Eric Laurent81784c32012-11-19 14:55:58 -08003600 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
Glenn Kastend848eb42016-03-08 13:42:11 -08003601 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX.
Eric Laurent81784c32012-11-19 14:55:58 -08003602 // Effect chain for other sessions are inserted at beginning of effect
3603 // chains list to be processed before output mix effects. Relative order between other
Glenn Kastend848eb42016-03-08 13:42:11 -08003604 // sessions is not important.
3605 static_assert(AUDIO_SESSION_OUTPUT_MIX == 0 &&
Eric Laurent3f75a5b2019-11-12 15:55:51 -08003606 AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX &&
3607 AUDIO_SESSION_DEVICE < AUDIO_SESSION_OUTPUT_STAGE,
Glenn Kastend848eb42016-03-08 13:42:11 -08003608 "audio_session_t constants misdefined");
Eric Laurent81784c32012-11-19 14:55:58 -08003609 size_t size = mEffectChains.size();
3610 size_t i = 0;
3611 for (i = 0; i < size; i++) {
3612 if (mEffectChains[i]->sessionId() < session) {
3613 break;
3614 }
3615 }
3616 mEffectChains.insertAt(chain, i);
3617 checkSuspendOnAddEffectChain_l(chain);
3618
3619 return NO_ERROR;
3620}
3621
3622size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
3623{
Glenn Kastend848eb42016-03-08 13:42:11 -08003624 audio_session_t session = chain->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08003625
3626 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
3627
3628 for (size_t i = 0; i < mEffectChains.size(); i++) {
3629 if (chain == mEffectChains[i]) {
3630 mEffectChains.removeAt(i);
3631 // detach all active tracks from the chain
Andy Hungdae27702016-10-31 14:01:16 -07003632 for (const sp<Track> &track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08003633 if (session == track->sessionId()) {
3634 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
3635 chain.get(), session);
3636 chain->decActiveTrackCnt();
3637 }
3638 }
3639
3640 // detach all tracks with same session ID from this chain
3641 for (size_t i = 0; i < mTracks.size(); ++i) {
3642 sp<Track> track = mTracks[i];
3643 if (session == track->sessionId()) {
rago94a1ee82017-07-21 15:11:02 -07003644 track->setMainBuffer(reinterpret_cast<effect_buffer_t*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08003645 chain->decTrackCnt();
3646 }
3647 }
3648 break;
3649 }
3650 }
3651 return mEffectChains.size();
3652}
3653
3654status_t AudioFlinger::PlaybackThread::attachAuxEffect(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003655 const sp<AudioFlinger::PlaybackThread::Track>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003656{
3657 Mutex::Autolock _l(mLock);
3658 return attachAuxEffect_l(track, EffectId);
3659}
3660
3661status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003662 const sp<AudioFlinger::PlaybackThread::Track>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003663{
3664 status_t status = NO_ERROR;
3665
3666 if (EffectId == 0) {
3667 track->setAuxBuffer(0, NULL);
3668 } else {
3669 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
3670 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
3671 if (effect != 0) {
3672 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
3673 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
3674 } else {
3675 status = INVALID_OPERATION;
3676 }
3677 } else {
3678 status = BAD_VALUE;
3679 }
3680 }
3681 return status;
3682}
3683
3684void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
3685{
3686 for (size_t i = 0; i < mTracks.size(); ++i) {
3687 sp<Track> track = mTracks[i];
3688 if (track->auxEffectId() == effectId) {
3689 attachAuxEffect_l(track, 0);
3690 }
3691 }
3692}
3693
3694bool AudioFlinger::PlaybackThread::threadLoop()
3695{
Glenn Kasten388d5712017-04-07 14:38:41 -07003696 tlNBLogWriter = mNBLogWriter.get();
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003697
Eric Laurent81784c32012-11-19 14:55:58 -08003698 Vector< sp<Track> > tracksToRemove;
3699
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003700 mStandbyTimeNs = systemTime();
Andy Hung446f4df2019-02-21 12:26:41 -08003701 int64_t lastLoopCountWritten = -2; // never matches "previous" loop, when loopCount = 0.
Eric Laurent81784c32012-11-19 14:55:58 -08003702
3703 // MIXER
3704 nsecs_t lastWarning = 0;
3705
3706 // DUPLICATING
3707 // FIXME could this be made local to while loop?
3708 writeFrames = 0;
3709
3710 cacheParameters_l();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003711 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003712
Andy Hungd3639922022-04-28 18:00:49 -07003713 if (mType == MIXER || mType == SPATIALIZER) {
Eric Laurent81784c32012-11-19 14:55:58 -08003714 sleepTimeShift = 0;
3715 }
3716
3717 CpuStats cpuStats;
3718 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
3719
3720 acquireWakeLock();
3721
Glenn Kasteneef598c2017-04-03 14:41:13 -07003722 // mNBLogWriter logging APIs can only be called by a single thread, typically the
3723 // thread associated with this PlaybackThread.
3724 // If you want to share the mNBLogWriter with other threads (for example, binder threads)
3725 // then all such threads must agree to hold a common mutex before logging.
Glenn Kasten9e58b552013-01-18 15:09:48 -08003726 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
3727 // and then that string will be logged at the next convenient opportunity.
Glenn Kasteneef598c2017-04-03 14:41:13 -07003728 // See reference to logString below.
Glenn Kasten9e58b552013-01-18 15:09:48 -08003729 const char *logString = NULL;
3730
rago1bb90822017-05-02 18:31:48 -07003731 // Estimated time for next buffer to be written to hal. This is used only on
3732 // suspended mode (for now) to help schedule the wait time until next iteration.
3733 nsecs_t timeLoopNextNs = 0;
3734
Eric Laurent664539d2013-09-23 18:24:31 -07003735 checkSilentMode_l();
Glenn Kasteneef598c2017-04-03 14:41:13 -07003736
Andy Hung2dbffc22018-08-08 18:50:41 -07003737 audio_patch_handle_t lastDownstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Andy Hungf3234512018-07-03 14:51:47 -07003738
Eric Laurentb3f315a2021-07-13 15:09:05 +02003739 sendCheckOutputStageEffectsEvent();
3740
Andy Hung446f4df2019-02-21 12:26:41 -08003741 // loopCount is used for statistics and diagnostics.
3742 for (int64_t loopCount = 0; !exitPending(); ++loopCount)
Eric Laurent81784c32012-11-19 14:55:58 -08003743 {
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08003744 // Log merge requests are performed during AudioFlinger binder transactions, but
3745 // that does not cover audio playback. It's requested here for that reason.
3746 mAudioFlinger->requestLogMerge();
3747
Eric Laurent81784c32012-11-19 14:55:58 -08003748 cpuStats.sample(myName);
3749
3750 Vector< sp<EffectChain> > effectChains;
Andy Hung6e6a2e62019-04-30 16:38:41 -07003751 audio_session_t activeHapticSessionId = AUDIO_SESSION_NONE;
Eric Laurentb62d0362021-10-26 17:40:18 +02003752 bool isHapticSessionSpatialized = false;
Andy Hungc1646382019-04-30 16:12:10 -07003753 std::vector<sp<Track>> activeTracks;
Eric Laurent81784c32012-11-19 14:55:58 -08003754
Andy Hung2dbffc22018-08-08 18:50:41 -07003755 // If the device is AUDIO_DEVICE_OUT_BUS, check for downstream latency.
3756 //
jiabinc52b1ff2019-10-31 17:20:42 -07003757 // Note: we access outDeviceTypes() outside of mLock.
3758 if (isMsdDevice() && outDeviceTypes().count(AUDIO_DEVICE_OUT_BUS) != 0) {
Andy Hung2dbffc22018-08-08 18:50:41 -07003759 // Here, we try for the AF lock, but do not block on it as the latency
3760 // is more informational.
3761 if (mAudioFlinger->mLock.tryLock() == NO_ERROR) {
3762 std::vector<PatchPanel::SoftwarePatch> swPatches;
3763 double latencyMs;
3764 status_t status = INVALID_OPERATION;
3765 audio_patch_handle_t downstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
3766 if (mAudioFlinger->mPatchPanel.getDownstreamSoftwarePatches(id(), &swPatches) == OK
3767 && swPatches.size() > 0) {
3768 status = swPatches[0].getLatencyMs_l(&latencyMs);
3769 downstreamPatchHandle = swPatches[0].getPatchHandle();
3770 }
3771 if (downstreamPatchHandle != lastDownstreamPatchHandle) {
Dean Wheatley30d28422018-11-06 10:27:40 +11003772 mDownstreamLatencyStatMs.reset();
Andy Hung2dbffc22018-08-08 18:50:41 -07003773 lastDownstreamPatchHandle = downstreamPatchHandle;
3774 }
3775 if (status == OK) {
3776 // verify downstream latency (we assume a max reasonable
Mikhail Naganov6aa0a312018-11-09 11:00:01 -08003777 // latency of 5 seconds).
3778 const double minLatency = 0., maxLatency = 5000.;
3779 if (latencyMs >= minLatency && latencyMs <= maxLatency) {
Dean Wheatley56a583e2020-05-08 15:12:17 +10003780 ALOGVV("new downstream latency %lf ms", latencyMs);
Andy Hung2dbffc22018-08-08 18:50:41 -07003781 } else {
3782 ALOGD("out of range downstream latency %lf ms", latencyMs);
Mikhail Naganov6aa0a312018-11-09 11:00:01 -08003783 if (latencyMs < minLatency) latencyMs = minLatency;
3784 else if (latencyMs > maxLatency) latencyMs = maxLatency;
Andy Hung2dbffc22018-08-08 18:50:41 -07003785 }
Dean Wheatley30d28422018-11-06 10:27:40 +11003786 mDownstreamLatencyStatMs.add(latencyMs);
Andy Hung2dbffc22018-08-08 18:50:41 -07003787 }
3788 mAudioFlinger->mLock.unlock();
3789 }
3790 } else {
3791 if (lastDownstreamPatchHandle != AUDIO_PATCH_HANDLE_NONE) {
3792 // our device is no longer AUDIO_DEVICE_OUT_BUS, reset patch handle and stats.
Dean Wheatley30d28422018-11-06 10:27:40 +11003793 mDownstreamLatencyStatMs.reset();
Andy Hung2dbffc22018-08-08 18:50:41 -07003794 lastDownstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
3795 }
3796 }
3797
Eric Laurentb3f315a2021-07-13 15:09:05 +02003798 if (mCheckOutputStageEffects.exchange(false)) {
3799 checkOutputStageEffects();
3800 }
3801
Eric Laurent81784c32012-11-19 14:55:58 -08003802 { // scope for mLock
3803
3804 Mutex::Autolock _l(mLock);
3805
Eric Laurent021cf962014-05-13 10:18:14 -07003806 processConfigEvents_l();
Eric Laurentb3f315a2021-07-13 15:09:05 +02003807 if (mCheckOutputStageEffects.load()) {
3808 continue;
3809 }
Eric Laurent10351942014-05-08 18:49:52 -07003810
Glenn Kasteneef598c2017-04-03 14:41:13 -07003811 // See comment at declaration of logString for why this is done under mLock
Glenn Kasten9e58b552013-01-18 15:09:48 -08003812 if (logString != NULL) {
3813 mNBLogWriter->logTimestamp();
3814 mNBLogWriter->log(logString);
3815 logString = NULL;
3816 }
3817
Dean Wheatley12473e92021-03-18 23:00:55 +11003818 collectTimestamps_l();
Andy Hungc8fddf32018-08-08 18:32:37 -07003819
Eric Laurent81784c32012-11-19 14:55:58 -08003820 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003821 if (mSignalPending) {
3822 // A signal was raised while we were unlocked
3823 mSignalPending = false;
3824 } else if (waitingAsyncCallback_l()) {
3825 if (exitPending()) {
3826 break;
3827 }
Marco Nelissen078538c2015-05-12 09:17:57 -07003828 bool released = false;
Eric Laurent64667972016-03-30 18:19:46 -07003829 if (!keepWakeLock()) {
Marco Nelissen078538c2015-05-12 09:17:57 -07003830 releaseWakeLock_l();
3831 released = true;
3832 }
Andy Hung10cbff12017-02-21 17:30:14 -08003833
3834 const int64_t waitNs = computeWaitTimeNs_l();
3835 ALOGV("wait async completion (wait time: %lld)", (long long)waitNs);
3836 status_t status = mWaitWorkCV.waitRelative(mLock, waitNs);
3837 if (status == TIMED_OUT) {
3838 mSignalPending = true; // if timeout recheck everything
3839 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003840 ALOGV("async completion/wake");
Marco Nelissen078538c2015-05-12 09:17:57 -07003841 if (released) {
3842 acquireWakeLock_l();
3843 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003844 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3845 mSleepTimeUs = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07003846
3847 continue;
3848 }
Eric Tan39ec8d62018-07-24 09:49:29 -07003849 if ((mActiveTracks.isEmpty() && systemTime() > mStandbyTimeNs) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08003850 isSuspended()) {
3851 // put audio hardware into standby after short delay
3852 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003853
3854 threadLoop_standby();
3855
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07003856 // This is where we go into standby
3857 if (!mStandby) {
3858 LOG_AUDIO_STATE();
Andy Hungcf10d742020-04-28 15:38:24 -07003859 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07003860 mThreadSnapshot.onEnd();
Andy Hungcf10d742020-04-28 15:38:24 -07003861 mStandby = true;
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07003862 }
Andy Hungd0979812019-02-21 15:51:44 -08003863 sendStatistics(false /* force */);
Eric Laurent81784c32012-11-19 14:55:58 -08003864 }
3865
Eric Tan39ec8d62018-07-24 09:49:29 -07003866 if (mActiveTracks.isEmpty() && mConfigEvents.isEmpty()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003867 // we're about to wait, flush the binder command buffer
3868 IPCThreadState::self()->flushCommands();
3869
3870 clearOutputTracks();
3871
3872 if (exitPending()) {
3873 break;
3874 }
3875
3876 releaseWakeLock_l();
3877 // wait until we have something to do...
3878 ALOGV("%s going to sleep", myName.string());
3879 mWaitWorkCV.wait(mLock);
3880 ALOGV("%s waking up", myName.string());
3881 acquireWakeLock_l();
3882
3883 mMixerStatus = MIXER_IDLE;
3884 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
3885 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003886 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003887 checkSilentMode_l();
3888
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003889 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3890 mSleepTimeUs = mIdleSleepTimeUs;
Andy Hungd3639922022-04-28 18:00:49 -07003891 if (mType == MIXER || mType == SPATIALIZER) {
Eric Laurent81784c32012-11-19 14:55:58 -08003892 sleepTimeShift = 0;
3893 }
3894
3895 continue;
3896 }
3897 }
Eric Laurent81784c32012-11-19 14:55:58 -08003898 // mMixerStatusIgnoringFastTracks is also updated internally
3899 mMixerStatus = prepareTracks_l(&tracksToRemove);
3900
Andy Hungdae27702016-10-31 14:01:16 -07003901 mActiveTracks.updatePowerState(this);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003902
Kevin Rocard069c2712018-03-29 19:09:14 -07003903 updateMetadata_l();
3904
Eric Laurent81784c32012-11-19 14:55:58 -08003905 // prevent any changes in effect chain list and in each effect chain
3906 // during mixing and effect process as the audio buffers could be deleted
3907 // or modified if an effect is created or deleted
3908 lockEffectChains_l(effectChains);
Andy Hung6e6a2e62019-04-30 16:38:41 -07003909
3910 // Determine which session to pick up haptic data.
3911 // This must be done under the same lock as prepareTracks_l().
jiabineb3bda02020-06-30 14:07:03 -07003912 // The haptic data from the effect is at a higher priority than the one from track.
Andy Hung6e6a2e62019-04-30 16:38:41 -07003913 // TODO: Write haptic data directly to sink buffer when mixing.
Eric Laurentb62d0362021-10-26 17:40:18 +02003914 if (mHapticChannelCount > 0) {
Andy Hung6e6a2e62019-04-30 16:38:41 -07003915 for (const auto& track : mActiveTracks) {
jiabineb3bda02020-06-30 14:07:03 -07003916 sp<EffectChain> effectChain = getEffectChain_l(track->sessionId());
Eric Laurentb62d0362021-10-26 17:40:18 +02003917 if (effectChain != nullptr
3918 && effectChain->containsHapticGeneratingEffect_l()) {
jiabineb3bda02020-06-30 14:07:03 -07003919 activeHapticSessionId = track->sessionId();
Eric Laurentb62d0362021-10-26 17:40:18 +02003920 isHapticSessionSpatialized =
Eric Laurentb0a7bc92022-04-05 15:06:08 +02003921 mType == SPATIALIZER && track->isSpatialized();
jiabineb3bda02020-06-30 14:07:03 -07003922 break;
3923 }
Eric Laurentb62d0362021-10-26 17:40:18 +02003924 if (activeHapticSessionId == AUDIO_SESSION_NONE
3925 && track->getHapticPlaybackEnabled()) {
Andy Hung6e6a2e62019-04-30 16:38:41 -07003926 activeHapticSessionId = track->sessionId();
Eric Laurentb62d0362021-10-26 17:40:18 +02003927 isHapticSessionSpatialized =
Eric Laurentb0a7bc92022-04-05 15:06:08 +02003928 mType == SPATIALIZER && track->isSpatialized();
Andy Hung6e6a2e62019-04-30 16:38:41 -07003929 }
3930 }
3931 }
3932
Andy Hungc1646382019-04-30 16:12:10 -07003933 // Acquire a local copy of active tracks with lock (release w/o lock).
3934 //
3935 // Control methods on the track acquire the ThreadBase lock (e.g. start()
3936 // stop(), pause(), etc.), but the threadLoop is entitled to call audio
3937 // data / buffer methods on tracks from activeTracks without the ThreadBase lock.
3938 activeTracks.insert(activeTracks.end(), mActiveTracks.begin(), mActiveTracks.end());
Eric Laurent68a40a82022-05-03 18:15:04 +02003939
3940 setHalLatencyMode_l();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003941 } // mLock scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08003942
Eric Laurentbfb1b832013-01-07 09:53:42 -08003943 if (mBytesRemaining == 0) {
3944 mCurrentWriteLength = 0;
3945 if (mMixerStatus == MIXER_TRACKS_READY) {
3946 // threadLoop_mix() sets mCurrentWriteLength
3947 threadLoop_mix();
3948 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
3949 && (mMixerStatus != MIXER_DRAIN_ALL)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003950 // threadLoop_sleepTime sets mSleepTimeUs to 0 if data
Eric Laurentbfb1b832013-01-07 09:53:42 -08003951 // must be written to HAL
3952 threadLoop_sleepTime();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003953 if (mSleepTimeUs == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08003954 mCurrentWriteLength = mSinkBufferSize;
Andy Hungc1646382019-04-30 16:12:10 -07003955
3956 // Tally underrun frames as we are inserting 0s here.
3957 for (const auto& track : activeTracks) {
Andy Hunge2e830f2019-12-03 12:54:46 -08003958 if (track->mFillingUpStatus == Track::FS_ACTIVE
3959 && !track->isStopped()
3960 && !track->isPaused()
3961 && !track->isTerminated()) {
3962 ALOGV("%s: track(%d) %s underrun due to thread sleep of %zu frames",
3963 __func__, track->id(), track->getTrackStateAsString(),
3964 mNormalFrameCount);
Andy Hungc1646382019-04-30 16:12:10 -07003965 track->mAudioTrackServerProxy->tallyUnderrunFrames(mNormalFrameCount);
3966 }
3967 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003968 }
3969 }
Andy Hung98ef9782014-03-04 14:46:50 -08003970 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003971 // mMixerBuffer with data if mMixerBufferValid is true and mSleepTimeUs == 0.
Andy Hung98ef9782014-03-04 14:46:50 -08003972 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
3973 // or mSinkBuffer (if there are no effects).
3974 //
3975 // This is done pre-effects computation; if effects change to
3976 // support higher precision, this needs to move.
3977 //
3978 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003979 // TODO use mSleepTimeUs == 0 as an additional condition.
Eric Laurent39095982021-08-24 18:29:27 +02003980 uint32_t mixerChannelCount = mEffectBufferValid ?
3981 audio_channel_count_from_out_mask(mMixerChannelMask) : mChannelCount;
Andy Hung98ef9782014-03-04 14:46:50 -08003982 if (mMixerBufferValid) {
3983 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
3984 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
3985
David Li88ee0902022-06-22 10:01:21 +08003986 // Apply mono blending and balancing if the effect buffer is not valid. Otherwise,
3987 // do these processes after effects are applied.
3988 if (!mEffectBufferValid) {
3989 // mono blend occurs for mixer threads only (not direct or offloaded)
3990 // and is handled here if we're going directly to the sink.
3991 if (requireMonoBlend()) {
3992 mono_blend(mMixerBuffer, mMixerBufferFormat, mChannelCount,
3993 mNormalFrameCount, true /*limit*/);
3994 }
Andy Hung2ddee192015-12-18 17:34:44 -08003995
David Li88ee0902022-06-22 10:01:21 +08003996 if (!hasFastMixer()) {
3997 // Balance must take effect after mono conversion.
3998 // We do it here if there is no FastMixer.
3999 // mBalance detects zero balance within the class for speed
4000 // (not needed here).
4001 mBalance.setBalance(mMasterBalance.load());
4002 mBalance.process((float *)mMixerBuffer, mNormalFrameCount);
4003 }
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01004004 }
4005
Andy Hung98ef9782014-03-04 14:46:50 -08004006 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
Eric Laurent39095982021-08-24 18:29:27 +02004007 mNormalFrameCount * (mixerChannelCount + mHapticChannelCount));
jiabin245cdd92018-12-07 17:55:15 -08004008
4009 // If we're going directly to the sink and there are haptic channels,
4010 // we should adjust channels as the sample data is partially interleaved
4011 // in this case.
4012 if (!mEffectBufferValid && mHapticChannelCount > 0) {
4013 adjust_channels_non_destructive(buffer, mChannelCount, buffer,
4014 mChannelCount + mHapticChannelCount,
4015 audio_bytes_per_sample(format),
4016 audio_bytes_per_frame(mChannelCount, format) * mNormalFrameCount);
4017 }
Andy Hung98ef9782014-03-04 14:46:50 -08004018 }
4019
Eric Laurentbfb1b832013-01-07 09:53:42 -08004020 mBytesRemaining = mCurrentWriteLength;
4021 if (isSuspended()) {
Andy Hung238fa3d2016-07-28 10:53:22 -07004022 // Simulate write to HAL when suspended (e.g. BT SCO phone call).
4023 mSleepTimeUs = suspendSleepTimeUs(); // assumes full buffer.
4024 const size_t framesRemaining = mBytesRemaining / mFrameSize;
4025 mBytesWritten += mBytesRemaining;
4026 mFramesWritten += framesRemaining;
4027 mSuspendedFrames += framesRemaining; // to adjust kernel HAL position
Eric Laurentbfb1b832013-01-07 09:53:42 -08004028 mBytesRemaining = 0;
4029 }
Eric Laurent81784c32012-11-19 14:55:58 -08004030
Eric Laurentbfb1b832013-01-07 09:53:42 -08004031 // only process effects if we're going to write
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004032 if (mSleepTimeUs == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004033 for (size_t i = 0; i < effectChains.size(); i ++) {
4034 effectChains[i]->process_l();
jiabin47affe52019-04-04 18:02:07 -07004035 // TODO: Write haptic data directly to sink buffer when mixing.
Andy Hung6e6a2e62019-04-30 16:38:41 -07004036 if (activeHapticSessionId != AUDIO_SESSION_NONE
4037 && activeHapticSessionId == effectChains[i]->sessionId()) {
jiabin47affe52019-04-04 18:02:07 -07004038 // Haptic data is active in this case, copy it directly from
4039 // in buffer to out buffer.
Eric Laurentb62d0362021-10-26 17:40:18 +02004040 uint32_t hapticSessionChannelCount = mEffectBufferValid ?
4041 audio_channel_count_from_out_mask(mMixerChannelMask) :
4042 mChannelCount;
4043 if (mType == SPATIALIZER && !isHapticSessionSpatialized) {
4044 hapticSessionChannelCount = mChannelCount;
4045 }
4046
jiabin47affe52019-04-04 18:02:07 -07004047 const size_t audioBufferSize = mNormalFrameCount
Eric Laurentb62d0362021-10-26 17:40:18 +02004048 * audio_bytes_per_frame(hapticSessionChannelCount,
4049 EFFECT_BUFFER_FORMAT);
jiabin47affe52019-04-04 18:02:07 -07004050 memcpy_by_audio_format(
4051 (uint8_t*)effectChains[i]->outBuffer() + audioBufferSize,
4052 EFFECT_BUFFER_FORMAT,
4053 (const uint8_t*)effectChains[i]->inBuffer() + audioBufferSize,
4054 EFFECT_BUFFER_FORMAT, mNormalFrameCount * mHapticChannelCount);
4055 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004056 }
Eric Laurent81784c32012-11-19 14:55:58 -08004057 }
4058 }
Eric Laurent59fe0102013-09-27 18:48:26 -07004059 // Process effect chains for offloaded thread even if no audio
4060 // was read from audio track: process only updates effect state
4061 // and thus does have to be synchronized with audio writes but may have
4062 // to be called while waiting for async write callback
4063 if (mType == OFFLOAD) {
4064 for (size_t i = 0; i < effectChains.size(); i ++) {
4065 effectChains[i]->process_l();
4066 }
4067 }
Eric Laurent81784c32012-11-19 14:55:58 -08004068
Andy Hung98ef9782014-03-04 14:46:50 -08004069 // Only if the Effects buffer is enabled and there is data in the
4070 // Effects buffer (buffer valid), we need to
4071 // copy into the sink buffer.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004072 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08004073 if (mEffectBufferValid) {
4074 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
Eric Laurentb62d0362021-10-26 17:40:18 +02004075 void *effectBuffer = (mType == SPATIALIZER) ? mPostSpatializerBuffer : mEffectBuffer;
Andy Hung2ddee192015-12-18 17:34:44 -08004076 if (requireMonoBlend()) {
Eric Laurentb62d0362021-10-26 17:40:18 +02004077 mono_blend(effectBuffer, mEffectBufferFormat, mChannelCount, mNormalFrameCount,
Glenn Kasten03c48d52016-01-27 17:25:17 -08004078 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08004079 }
4080
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01004081 if (!hasFastMixer()) {
4082 // Balance must take effect after mono conversion.
4083 // We do it here if there is no FastMixer.
4084 // mBalance detects zero balance within the class for speed (not needed here).
4085 mBalance.setBalance(mMasterBalance.load());
Eric Laurentb62d0362021-10-26 17:40:18 +02004086 mBalance.process((float *)effectBuffer, mNormalFrameCount);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01004087 }
4088
Eric Laurentb62d0362021-10-26 17:40:18 +02004089 // for SPATIALIZER thread, Move haptics channels from mEffectBuffer to
4090 // mPostSpatializerBuffer if the haptics track is spatialized.
4091 // Otherwise, the haptics channels are already in mPostSpatializerBuffer.
4092 // For other thread types, the haptics channels are already in mEffectBuffer.
4093 if (mType == SPATIALIZER && isHapticSessionSpatialized) {
4094 const size_t srcBufferSize = mNormalFrameCount *
4095 audio_bytes_per_frame(audio_channel_count_from_out_mask(mMixerChannelMask),
4096 mEffectBufferFormat);
4097 const size_t dstBufferSize = mNormalFrameCount
4098 * audio_bytes_per_frame(mChannelCount, mEffectBufferFormat);
4099
4100 memcpy_by_audio_format((uint8_t*)mPostSpatializerBuffer + dstBufferSize,
4101 mEffectBufferFormat,
4102 (uint8_t*)mEffectBuffer + srcBufferSize,
4103 mEffectBufferFormat,
4104 mNormalFrameCount * mHapticChannelCount);
Eric Laurent39095982021-08-24 18:29:27 +02004105 }
Eric Laurentb62d0362021-10-26 17:40:18 +02004106
4107 memcpy_by_audio_format(mSinkBuffer, mFormat, effectBuffer, mEffectBufferFormat,
4108 mNormalFrameCount * (mChannelCount + mHapticChannelCount));
4109
jiabin245cdd92018-12-07 17:55:15 -08004110 // The sample data is partially interleaved when haptic channels exist,
4111 // we need to adjust channels here.
4112 if (mHapticChannelCount > 0) {
4113 adjust_channels_non_destructive(mSinkBuffer, mChannelCount, mSinkBuffer,
4114 mChannelCount + mHapticChannelCount,
4115 audio_bytes_per_sample(mFormat),
4116 audio_bytes_per_frame(mChannelCount, mFormat) * mNormalFrameCount);
4117 }
Andy Hung98ef9782014-03-04 14:46:50 -08004118 }
4119
Eric Laurent81784c32012-11-19 14:55:58 -08004120 // enable changes in effect chain
4121 unlockEffectChains(effectChains);
4122
Eric Laurentbfb1b832013-01-07 09:53:42 -08004123 if (!waitingAsyncCallback()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004124 // mSleepTimeUs == 0 means we must write to audio hardware
4125 if (mSleepTimeUs == 0) {
Andy Hung08fb1742015-05-31 23:22:10 -07004126 ssize_t ret = 0;
Andy Hung446f4df2019-02-21 12:26:41 -08004127 // writePeriodNs is updated >= 0 when ret > 0.
4128 int64_t writePeriodNs = -1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004129 if (mBytesRemaining) {
Andy Hung69488c42016-05-16 18:43:33 -07004130 // FIXME rewrite to reduce number of system calls
Andy Hung446f4df2019-02-21 12:26:41 -08004131 const int64_t lastIoBeginNs = systemTime();
Andy Hung08fb1742015-05-31 23:22:10 -07004132 ret = threadLoop_write();
Andy Hung446f4df2019-02-21 12:26:41 -08004133 const int64_t lastIoEndNs = systemTime();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004134 if (ret < 0) {
4135 mBytesRemaining = 0;
Andy Hung446f4df2019-02-21 12:26:41 -08004136 } else if (ret > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004137 mBytesWritten += ret;
4138 mBytesRemaining -= ret;
Andy Hung446f4df2019-02-21 12:26:41 -08004139 const int64_t frames = ret / mFrameSize;
4140 mFramesWritten += frames;
4141
4142 writePeriodNs = lastIoEndNs - mLastIoEndNs;
4143 // process information relating to write time.
4144 if (audio_has_proportional_frames(mFormat)) {
4145 // we are in a continuous mixing cycle
4146 if (mMixerStatus == MIXER_TRACKS_READY &&
4147 loopCount == lastLoopCountWritten + 1) {
4148
4149 const double jitterMs =
4150 TimestampVerifier<int64_t, int64_t>::computeJitterMs(
4151 {frames, writePeriodNs},
4152 {0, 0} /* lastTimestamp */, mSampleRate);
4153 const double processMs =
4154 (lastIoBeginNs - mLastIoEndNs) * 1e-6;
4155
4156 Mutex::Autolock _l(mLock);
4157 mIoJitterMs.add(jitterMs);
4158 mProcessTimeMs.add(processMs);
Robert Wu06db0a32021-08-10 19:05:34 +00004159
4160 if (mPipeSink.get() != nullptr) {
4161 // Using the Monopipe availableToWrite, we estimate the current
4162 // buffer size.
4163 MonoPipe* monoPipe = static_cast<MonoPipe*>(mPipeSink.get());
4164 const ssize_t
4165 availableToWrite = mPipeSink->availableToWrite();
4166 const size_t pipeFrames = monoPipe->maxFrames();
4167 const size_t
4168 remainingFrames = pipeFrames - max(availableToWrite, 0);
4169 mMonopipePipeDepthStats.add(remainingFrames);
4170 }
Andy Hung446f4df2019-02-21 12:26:41 -08004171 }
4172
4173 // write blocked detection
4174 const int64_t deltaWriteNs = lastIoEndNs - lastIoBeginNs;
Andy Hungd3639922022-04-28 18:00:49 -07004175 if ((mType == MIXER || mType == SPATIALIZER)
4176 && deltaWriteNs > maxPeriod) {
Andy Hung446f4df2019-02-21 12:26:41 -08004177 mNumDelayedWrites++;
4178 if ((lastIoEndNs - lastWarning) > kWarningThrottleNs) {
4179 ATRACE_NAME("underrun");
4180 ALOGW("write blocked for %lld msecs, "
4181 "%d delayed writes, thread %d",
4182 (long long)deltaWriteNs / NANOS_PER_MILLISECOND,
4183 mNumDelayedWrites, mId);
4184 lastWarning = lastIoEndNs;
4185 }
4186 }
4187 }
4188 // update timing info.
4189 mLastIoBeginNs = lastIoBeginNs;
4190 mLastIoEndNs = lastIoEndNs;
4191 lastLoopCountWritten = loopCount;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004192 }
4193 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
4194 (mMixerStatus == MIXER_DRAIN_ALL)) {
4195 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08004196 }
Andy Hungd3639922022-04-28 18:00:49 -07004197 if ((mType == MIXER || mType == SPATIALIZER) && !mStandby) {
Andy Hung08fb1742015-05-31 23:22:10 -07004198
4199 if (mThreadThrottle
4200 && mMixerStatus == MIXER_TRACKS_READY // we are mixing (active tracks)
Andy Hung446f4df2019-02-21 12:26:41 -08004201 && writePeriodNs > 0) { // we have write period info
Andy Hung08fb1742015-05-31 23:22:10 -07004202 // Limit MixerThread data processing to no more than twice the
4203 // expected processing rate.
4204 //
4205 // This helps prevent underruns with NuPlayer and other applications
4206 // which may set up buffers that are close to the minimum size, or use
4207 // deep buffers, and rely on a double-buffering sleep strategy to fill.
4208 //
4209 // The throttle smooths out sudden large data drains from the device,
4210 // e.g. when it comes out of standby, which often causes problems with
4211 // (1) mixer threads without a fast mixer (which has its own warm-up)
4212 // (2) minimum buffer sized tracks (even if the track is full,
4213 // the app won't fill fast enough to handle the sudden draw).
Haynes Mathew Georgef92b2172016-05-09 11:34:15 -07004214 //
4215 // Total time spent in last processing cycle equals time spent in
4216 // 1. threadLoop_write, as well as time spent in
4217 // 2. threadLoop_mix (significant for heavy mixing, especially
4218 // on low tier processors)
Andy Hung08fb1742015-05-31 23:22:10 -07004219
Andy Hung446f4df2019-02-21 12:26:41 -08004220 // it's OK if deltaMs is an overestimate.
4221
4222 const int32_t deltaMs = writePeriodNs / NANOS_PER_MILLISECOND;
Ivan Lozanoe02bc542017-10-26 09:51:54 -07004223
Ivan Lozanoea04d392017-11-07 14:37:07 -08004224 const int32_t throttleMs = (int32_t)mHalfBufferMs - deltaMs;
Andy Hung08fb1742015-05-31 23:22:10 -07004225 if ((signed)mHalfBufferMs >= throttleMs && throttleMs > 0) {
Andy Hungcf10d742020-04-28 15:38:24 -07004226 mThreadMetrics.logThrottleMs((double)throttleMs);
Andy Hungb68f5eb2019-12-03 16:49:17 -08004227
Andy Hung08fb1742015-05-31 23:22:10 -07004228 usleep(throttleMs * 1000);
Andy Hung40eb1a12015-06-18 13:42:02 -07004229 // notify of throttle start on verbose log
4230 ALOGV_IF(mThreadThrottleEndMs == mThreadThrottleTimeMs,
4231 "mixer(%p) throttle begin:"
4232 " ret(%zd) deltaMs(%d) requires sleep %d ms",
Andy Hung08fb1742015-05-31 23:22:10 -07004233 this, ret, deltaMs, throttleMs);
Andy Hung40eb1a12015-06-18 13:42:02 -07004234 mThreadThrottleTimeMs += throttleMs;
Andy Hung0a31ddd2016-07-06 19:10:29 -07004235 // Throttle must be attributed to the previous mixer loop's write time
4236 // to allow back-to-back throttling.
Andy Hung446f4df2019-02-21 12:26:41 -08004237 // This also ensures proper timing statistics.
4238 mLastIoEndNs = systemTime(); // we fetch the write end time again.
Andy Hung40eb1a12015-06-18 13:42:02 -07004239 } else {
4240 uint32_t diff = mThreadThrottleTimeMs - mThreadThrottleEndMs;
4241 if (diff > 0) {
4242 // notify of throttle end on debug log
Andy Hung3ea004d2016-05-05 16:48:37 -07004243 // but prevent spamming for bluetooth
jiabinc52b1ff2019-10-31 17:20:42 -07004244 ALOGD_IF(!isSingleDeviceType(
4245 outDeviceTypes(), audio_is_a2dp_out_device) &&
4246 !isSingleDeviceType(
4247 outDeviceTypes(), audio_is_hearing_aid_out_device),
Andy Hung3ea004d2016-05-05 16:48:37 -07004248 "mixer(%p) throttle end: throttle time(%u)", this, diff);
Andy Hung40eb1a12015-06-18 13:42:02 -07004249 mThreadThrottleEndMs = mThreadThrottleTimeMs;
4250 }
Andy Hung08fb1742015-05-31 23:22:10 -07004251 }
4252 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004253 }
Eric Laurent81784c32012-11-19 14:55:58 -08004254
Eric Laurentbfb1b832013-01-07 09:53:42 -08004255 } else {
Glenn Kastene7754022014-10-31 12:11:26 -07004256 ATRACE_BEGIN("sleep");
Eric Laurente93cc032016-05-05 10:15:10 -07004257 Mutex::Autolock _l(mLock);
rago1bb90822017-05-02 18:31:48 -07004258 // suspended requires accurate metering of sleep time.
4259 if (isSuspended()) {
4260 // advance by expected sleepTime
4261 timeLoopNextNs += microseconds((nsecs_t)mSleepTimeUs);
4262 const nsecs_t nowNs = systemTime();
4263
4264 // compute expected next time vs current time.
4265 // (negative deltas are treated as delays).
4266 nsecs_t deltaNs = timeLoopNextNs - nowNs;
4267 if (deltaNs < -kMaxNextBufferDelayNs) {
4268 // Delays longer than the max allowed trigger a reset.
4269 ALOGV("DelayNs: %lld, resetting timeLoopNextNs", (long long) deltaNs);
4270 deltaNs = microseconds((nsecs_t)mSleepTimeUs);
4271 timeLoopNextNs = nowNs + deltaNs;
4272 } else if (deltaNs < 0) {
4273 // Delays within the max delay allowed: zero the delta/sleepTime
4274 // to help the system catch up in the next iteration(s)
4275 ALOGV("DelayNs: %lld, catching-up", (long long) deltaNs);
4276 deltaNs = 0;
4277 }
4278 // update sleep time (which is >= 0)
4279 mSleepTimeUs = deltaNs / 1000;
4280 }
Eric Laurente93cc032016-05-05 10:15:10 -07004281 if (!mSignalPending && mConfigEvents.isEmpty() && !exitPending()) {
4282 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)mSleepTimeUs));
Eric Laurent51716182016-02-29 18:00:56 -08004283 }
Glenn Kastene7754022014-10-31 12:11:26 -07004284 ATRACE_END();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004285 }
Eric Laurent81784c32012-11-19 14:55:58 -08004286 }
4287
4288 // Finally let go of removed track(s), without the lock held
4289 // since we can't guarantee the destructors won't acquire that
4290 // same lock. This will also mutate and push a new fast mixer state.
4291 threadLoop_removeTracks(tracksToRemove);
4292 tracksToRemove.clear();
4293
4294 // FIXME I don't understand the need for this here;
4295 // it was in the original code but maybe the
4296 // assignment in saveOutputTracks() makes this unnecessary?
4297 clearOutputTracks();
4298
4299 // Effect chains will be actually deleted here if they were removed from
4300 // mEffectChains list during mixing or effects processing
4301 effectChains.clear();
4302
4303 // FIXME Note that the above .clear() is no longer necessary since effectChains
4304 // is now local to this block, but will keep it for now (at least until merge done).
4305 }
4306
Eric Laurentbfb1b832013-01-07 09:53:42 -08004307 threadLoop_exit();
4308
Eric Laurentcf817a22014-08-04 20:36:31 -07004309 if (!mStandby) {
4310 threadLoop_standby();
4311 mStandby = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004312 }
4313
4314 releaseWakeLock();
4315
4316 ALOGV("Thread %p type %d exiting", this, mType);
4317 return false;
4318}
4319
Dean Wheatley12473e92021-03-18 23:00:55 +11004320void AudioFlinger::PlaybackThread::collectTimestamps_l()
4321{
Dean Wheatley12473e92021-03-18 23:00:55 +11004322 if (mStandby) {
4323 mTimestampVerifier.discontinuity(discontinuityForStandbyOrFlush());
4324 return;
4325 } else if (mHwPaused) {
4326 mTimestampVerifier.discontinuity(mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS);
4327 return;
4328 }
4329
4330 // Gather the framesReleased counters for all active tracks,
4331 // and associate with the sink frames written out. We need
4332 // this to convert the sink timestamp to the track timestamp.
4333 bool kernelLocationUpdate = false;
4334 ExtendedTimestamp timestamp; // use private copy to fetch
4335
4336 // Always query HAL timestamp and update timestamp verifier. In standby or pause,
4337 // HAL may be draining some small duration buffered data for fade out.
4338 if (threadloop_getHalTimestamp_l(&timestamp) == OK) {
4339 mTimestampVerifier.add(timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL],
4340 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4341 mSampleRate);
4342
4343 if (isTimestampCorrectionEnabled()) {
4344 ALOGVV("TS_BEFORE: %d %lld %lld", id(),
4345 (long long)timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4346 (long long)timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]);
4347 auto correctedTimestamp = mTimestampVerifier.getLastCorrectedTimestamp();
4348 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4349 = correctedTimestamp.mFrames;
4350 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]
4351 = correctedTimestamp.mTimeNs;
4352 ALOGVV("TS_AFTER: %d %lld %lld", id(),
4353 (long long)timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4354 (long long)timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]);
4355
4356 // Note: Downstream latency only added if timestamp correction enabled.
4357 if (mDownstreamLatencyStatMs.getN() > 0) { // we have latency info.
4358 const int64_t newPosition =
4359 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4360 - int64_t(mDownstreamLatencyStatMs.getMean() * mSampleRate * 1e-3);
4361 // prevent retrograde
4362 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = max(
4363 newPosition,
4364 (mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4365 - mSuspendedFrames));
4366 }
4367 }
4368
4369 // We always fetch the timestamp here because often the downstream
4370 // sink will block while writing.
4371
4372 // We keep track of the last valid kernel position in case we are in underrun
4373 // and the normal mixer period is the same as the fast mixer period, or there
4374 // is some error from the HAL.
4375 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
4376 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
4377 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
4378 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
4379 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4380
4381 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
4382 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER];
4383 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
4384 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER];
4385 }
4386
4387 if (timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
4388 kernelLocationUpdate = true;
4389 } else {
4390 ALOGVV("getTimestamp error - no valid kernel position");
4391 }
4392
4393 // copy over kernel info
4394 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] =
4395 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4396 + mSuspendedFrames; // add frames discarded when suspended
4397 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] =
4398 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4399 } else {
4400 mTimestampVerifier.error();
4401 }
4402
4403 // mFramesWritten for non-offloaded tracks are contiguous
4404 // even after standby() is called. This is useful for the track frame
4405 // to sink frame mapping.
4406 bool serverLocationUpdate = false;
4407 if (mFramesWritten != mLastFramesWritten) {
4408 serverLocationUpdate = true;
4409 mLastFramesWritten = mFramesWritten;
4410 }
4411 // Only update timestamps if there is a meaningful change.
4412 // Either the kernel timestamp must be valid or we have written something.
4413 if (kernelLocationUpdate || serverLocationUpdate) {
4414 if (serverLocationUpdate) {
4415 // use the time before we called the HAL write - it is a bit more accurate
4416 // to when the server last read data than the current time here.
4417 //
4418 // If we haven't written anything, mLastIoBeginNs will be -1
4419 // and we use systemTime().
4420 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] = mFramesWritten;
4421 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = mLastIoBeginNs == -1
4422 ? systemTime() : mLastIoBeginNs;
4423 }
4424
4425 for (const sp<Track> &t : mActiveTracks) {
4426 if (!t->isFastTrack()) {
4427 t->updateTrackFrameInfo(
4428 t->mAudioTrackServerProxy->framesReleased(),
4429 mFramesWritten,
4430 mSampleRate,
4431 mTimestamp);
4432 }
4433 }
4434 }
4435
4436 if (audio_has_proportional_frames(mFormat)) {
4437 const double latencyMs = mTimestamp.getOutputServerLatencyMs(mSampleRate);
4438 if (latencyMs != 0.) { // note 0. means timestamp is empty.
4439 mLatencyMs.add(latencyMs);
4440 }
4441 }
4442#if 0
4443 // logFormat example
4444 if (z % 100 == 0) {
4445 timespec ts;
4446 clock_gettime(CLOCK_MONOTONIC, &ts);
4447 LOGT("This is an integer %d, this is a float %f, this is my "
4448 "pid %p %% %s %t", 42, 3.14, "and this is a timestamp", ts);
4449 LOGT("A deceptive null-terminated string %\0");
4450 }
4451 ++z;
4452#endif
4453}
4454
Eric Laurentbfb1b832013-01-07 09:53:42 -08004455// removeTracks_l() must be called with ThreadBase::mLock held
4456void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
4457{
Andy Hungfe726a62018-09-27 15:17:25 -07004458 for (const auto& track : tracksToRemove) {
4459 mActiveTracks.remove(track);
4460 ALOGV("%s(%d): removing track on session %d", __func__, track->id(), track->sessionId());
4461 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
4462 if (chain != 0) {
4463 ALOGV("%s(%d): stopping track on chain %p for session Id: %d",
4464 __func__, track->id(), chain.get(), track->sessionId());
4465 chain->decActiveTrackCnt();
4466 }
4467 // If an external client track, inform APM we're no longer active, and remove if needed.
4468 // We do this under lock so that the state is consistent if the Track is destroyed.
4469 if (track->isExternalTrack()) {
4470 AudioSystem::stopOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08004471 if (track->isTerminated()) {
Andy Hungfe726a62018-09-27 15:17:25 -07004472 AudioSystem::releaseOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08004473 }
4474 }
Andy Hungfe726a62018-09-27 15:17:25 -07004475 if (track->isTerminated()) {
4476 // remove from our tracks vector
4477 removeTrack_l(track);
4478 }
jiabineb3bda02020-06-30 14:07:03 -07004479 if (mHapticChannelCount > 0 &&
4480 ((track->channelMask() & AUDIO_CHANNEL_HAPTIC_ALL) != AUDIO_CHANNEL_NONE
4481 || (chain != nullptr && chain->containsHapticGeneratingEffect_l()))) {
jiabin57303cc2018-12-18 15:45:57 -08004482 mLock.unlock();
4483 // Unlock due to VibratorService will lock for this call and will
4484 // call Tracks.mute/unmute which also require thread's lock.
4485 AudioFlinger::onExternalVibrationStop(track->getExternalVibration());
4486 mLock.lock();
jiabine70bc7f2020-06-30 22:07:55 -07004487
4488 // When the track is stop, set the haptic intensity as MUTE
4489 // for the HapticGenerator effect.
4490 if (chain != nullptr) {
4491 chain->setHapticIntensity_l(track->id(), static_cast<int>(os::HapticScale::MUTE));
4492 }
jiabin245cdd92018-12-07 17:55:15 -08004493 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004494 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004495}
Eric Laurent81784c32012-11-19 14:55:58 -08004496
Eric Laurentaccc1472013-09-20 09:36:34 -07004497status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
4498{
4499 if (mNormalSink != 0) {
Andy Hung818e7a32016-02-16 18:08:07 -08004500 ExtendedTimestamp ets;
4501 status_t status = mNormalSink->getTimestamp(ets);
4502 if (status == NO_ERROR) {
4503 status = ets.getBestTimestamp(&timestamp);
4504 }
4505 return status;
Eric Laurentaccc1472013-09-20 09:36:34 -07004506 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004507 if ((mType == OFFLOAD || mType == DIRECT) && mOutput != NULL) {
Dean Wheatley12473e92021-03-18 23:00:55 +11004508 collectTimestamps_l();
4509 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] <= 0) {
4510 return INVALID_OPERATION;
Eric Laurentaccc1472013-09-20 09:36:34 -07004511 }
Dean Wheatley12473e92021-03-18 23:00:55 +11004512 timestamp.mPosition = mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
4513 const int64_t timeNs = mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4514 timestamp.mTime.tv_sec = timeNs / NANOS_PER_SECOND;
4515 timestamp.mTime.tv_nsec = timeNs - (timestamp.mTime.tv_sec * NANOS_PER_SECOND);
4516 return NO_ERROR;
Eric Laurentaccc1472013-09-20 09:36:34 -07004517 }
4518 return INVALID_OPERATION;
4519}
Eric Laurent1c333e22014-05-20 10:48:17 -07004520
Eric Laurenteab90452019-06-24 15:17:46 -07004521// For dedicated VoIP outputs, let the HAL apply the stream volume. Track volume is
4522// still applied by the mixer.
4523// All tracks attached to a mixer with flag VOIP_RX are tied to the same
4524// stream type STREAM_VOICE_CALL so this will only change the HAL volume once even
4525// if more than one track are active
4526status_t AudioFlinger::PlaybackThread::handleVoipVolume_l(float *volume)
4527{
4528 status_t result = NO_ERROR;
4529 if ((mOutput->flags & AUDIO_OUTPUT_FLAG_VOIP_RX) != 0) {
4530 if (*volume != mLeftVolFloat) {
4531 result = mOutput->stream->setVolume(*volume, *volume);
4532 ALOGE_IF(result != OK,
4533 "Error when setting output stream volume: %d", result);
4534 if (result == NO_ERROR) {
4535 mLeftVolFloat = *volume;
4536 }
4537 }
4538 // if stream volume was successfully sent to the HAL, mLeftVolFloat == v here and we
4539 // remove stream volume contribution from software volume.
4540 if (mLeftVolFloat == *volume) {
4541 *volume = 1.0f;
4542 }
4543 }
4544 return result;
4545}
4546
Eric Laurent054d9d32015-04-24 08:48:48 -07004547status_t AudioFlinger::MixerThread::createAudioPatch_l(const struct audio_patch *patch,
4548 audio_patch_handle_t *handle)
4549{
Andy Hungf60abce2016-08-26 11:37:54 -07004550 status_t status;
4551 if (property_get_bool("af.patch_park", false /* default_value */)) {
4552 // Park FastMixer to avoid potential DOS issues with writing to the HAL
4553 // or if HAL does not properly lock against access.
4554 AutoPark<FastMixer> park(mFastMixer);
4555 status = PlaybackThread::createAudioPatch_l(patch, handle);
4556 } else {
4557 status = PlaybackThread::createAudioPatch_l(patch, handle);
4558 }
Eric Laurent054d9d32015-04-24 08:48:48 -07004559 return status;
4560}
4561
Eric Laurent1c333e22014-05-20 10:48:17 -07004562status_t AudioFlinger::PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
4563 audio_patch_handle_t *handle)
4564{
4565 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07004566
4567 // store new device and send to effects
4568 audio_devices_t type = AUDIO_DEVICE_NONE;
jiabinc52b1ff2019-10-31 17:20:42 -07004569 AudioDeviceTypeAddrVector deviceTypeAddrs;
Eric Laurent054d9d32015-04-24 08:48:48 -07004570 for (unsigned int i = 0; i < patch->num_sinks; i++) {
jiabinc52b1ff2019-10-31 17:20:42 -07004571 LOG_ALWAYS_FATAL_IF(popcount(patch->sinks[i].ext.device.type) > 1
4572 && !mOutput->audioHwDev->supportsAudioPatches(),
4573 "Enumerated device type(%#x) must not be used "
4574 "as it does not support audio patches",
4575 patch->sinks[i].ext.device.type);
Mikhail Naganov55773032020-10-01 15:08:13 -07004576 type = static_cast<audio_devices_t>(type | patch->sinks[i].ext.device.type);
jiabinc52b1ff2019-10-31 17:20:42 -07004577 deviceTypeAddrs.push_back(AudioDeviceTypeAddr(patch->sinks[i].ext.device.type,
4578 patch->sinks[i].ext.device.address));
Eric Laurent054d9d32015-04-24 08:48:48 -07004579 }
4580
François Gaffie0c280aa2018-07-25 10:02:15 +02004581 audio_port_handle_t sinkPortId = patch->sinks[0].id;
Eric Laurent054d9d32015-04-24 08:48:48 -07004582#ifdef ADD_BATTERY_DATA
4583 // when changing the audio output device, call addBatteryData to notify
4584 // the change
jiabinc52b1ff2019-10-31 17:20:42 -07004585 if (outDeviceTypes() != deviceTypes) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004586 uint32_t params = 0;
4587 // check whether speaker is on
jiabinc52b1ff2019-10-31 17:20:42 -07004588 if (deviceTypes.count(AUDIO_DEVICE_OUT_SPEAKER) > 0) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004589 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent1c333e22014-05-20 10:48:17 -07004590 }
4591
Eric Laurent054d9d32015-04-24 08:48:48 -07004592 // check if any other device (except speaker) is on
jiabinc52b1ff2019-10-31 17:20:42 -07004593 if (!isSingleDeviceType(deviceTypes, AUDIO_DEVICE_OUT_SPEAKER)) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004594 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
4595 }
4596
4597 if (params != 0) {
4598 addBatteryData(params);
4599 }
4600 }
4601#endif
4602
4603 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08004604 mEffectChains[i]->setDevices_l(deviceTypeAddrs);
Eric Laurent054d9d32015-04-24 08:48:48 -07004605 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07004606
jiabinc52b1ff2019-10-31 17:20:42 -07004607 // mPatch.num_sinks is not set when the thread is created so that
4608 // the first patch creation triggers an ioConfigChanged callback
4609 bool configChanged = (mPatch.num_sinks == 0) ||
4610 (mPatch.sinks[0].id != sinkPortId);
Eric Laurent296fb132015-05-01 11:38:42 -07004611 mPatch = *patch;
jiabinc52b1ff2019-10-31 17:20:42 -07004612 mOutDeviceTypeAddrs = deviceTypeAddrs;
jiabin0a957d32020-04-29 10:56:20 -07004613 checkSilentMode_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07004614
Mikhail Naganov9ee05402016-10-13 15:58:17 -07004615 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07004616 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
4617 status = hwDevice->createAudioPatch(patch->num_sources,
4618 patch->sources,
4619 patch->num_sinks,
4620 patch->sinks,
4621 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07004622 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08004623 status = mOutput->stream->legacyCreateAudioPatch(patch->sinks[0], std::nullopt, type);
Eric Laurent054d9d32015-04-24 08:48:48 -07004624 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07004625 }
Andy Hungc2b11cb2020-04-22 09:04:01 -07004626 const std::string patchSinksAsString = patchSinksToString(patch);
Andy Hungcf10d742020-04-28 15:38:24 -07004627
4628 mThreadMetrics.logEndInterval();
Andy Hungea840382020-05-05 21:50:17 -07004629 mThreadMetrics.logCreatePatch(/* inDevices */ {}, patchSinksAsString);
Andy Hungcf10d742020-04-28 15:38:24 -07004630 mThreadMetrics.logBeginInterval();
Andy Hungc2b11cb2020-04-22 09:04:01 -07004631 // also dispatch to active AudioTracks for MediaMetrics
4632 for (const auto &track : mActiveTracks) {
4633 track->logEndInterval();
4634 track->logBeginInterval(patchSinksAsString);
4635 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08004636
Eric Laurente8726fe2015-06-26 09:39:24 -07004637 if (configChanged) {
4638 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
4639 }
Eric Laurentdda206a2022-07-08 17:28:35 +02004640 // Force meteadata update after a route change
4641 mActiveTracks.setHasChanged();
4642
Eric Laurent1c333e22014-05-20 10:48:17 -07004643 return status;
4644}
4645
Eric Laurent054d9d32015-04-24 08:48:48 -07004646status_t AudioFlinger::MixerThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
4647{
Andy Hungf60abce2016-08-26 11:37:54 -07004648 status_t status;
4649 if (property_get_bool("af.patch_park", false /* default_value */)) {
4650 // Park FastMixer to avoid potential DOS issues with writing to the HAL
4651 // or if HAL does not properly lock against access.
4652 AutoPark<FastMixer> park(mFastMixer);
4653 status = PlaybackThread::releaseAudioPatch_l(handle);
4654 } else {
4655 status = PlaybackThread::releaseAudioPatch_l(handle);
4656 }
Eric Laurent054d9d32015-04-24 08:48:48 -07004657 return status;
4658}
4659
Eric Laurent1c333e22014-05-20 10:48:17 -07004660status_t AudioFlinger::PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
4661{
4662 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07004663
jiabinc52b1ff2019-10-31 17:20:42 -07004664 mPatch = audio_patch{};
4665 mOutDeviceTypeAddrs.clear();
Eric Laurent054d9d32015-04-24 08:48:48 -07004666
Mikhail Naganov9ee05402016-10-13 15:58:17 -07004667 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07004668 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
4669 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07004670 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08004671 status = mOutput->stream->legacyReleaseAudioPatch();
Eric Laurent1c333e22014-05-20 10:48:17 -07004672 }
Eric Laurentdda206a2022-07-08 17:28:35 +02004673 // Force meteadata update after a route change
4674 mActiveTracks.setHasChanged();
4675
Eric Laurent1c333e22014-05-20 10:48:17 -07004676 return status;
4677}
4678
Eric Laurent83b88082014-06-20 18:31:16 -07004679void AudioFlinger::PlaybackThread::addPatchTrack(const sp<PatchTrack>& track)
4680{
4681 Mutex::Autolock _l(mLock);
4682 mTracks.add(track);
4683}
4684
4685void AudioFlinger::PlaybackThread::deletePatchTrack(const sp<PatchTrack>& track)
4686{
4687 Mutex::Autolock _l(mLock);
4688 destroyTrack_l(track);
4689}
4690
Mikhail Naganovdc769682018-05-04 15:34:08 -07004691void AudioFlinger::PlaybackThread::toAudioPortConfig(struct audio_port_config *config)
Eric Laurent83b88082014-06-20 18:31:16 -07004692{
Mikhail Naganovdc769682018-05-04 15:34:08 -07004693 ThreadBase::toAudioPortConfig(config);
Eric Laurent83b88082014-06-20 18:31:16 -07004694 config->role = AUDIO_PORT_ROLE_SOURCE;
4695 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
4696 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07004697 if (mOutput && mOutput->flags != AUDIO_OUTPUT_FLAG_NONE) {
4698 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
4699 config->flags.output = mOutput->flags;
4700 }
Eric Laurent83b88082014-06-20 18:31:16 -07004701}
4702
Eric Laurent81784c32012-11-19 14:55:58 -08004703// ----------------------------------------------------------------------------
4704
4705AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Eric Laurentf1f22e72021-07-13 14:04:14 +02004706 audio_io_handle_t id, bool systemReady, type_t type, audio_config_base_t *mixerConfig)
4707 : PlaybackThread(audioFlinger, output, id, type, systemReady, mixerConfig),
Eric Laurent81784c32012-11-19 14:55:58 -08004708 // mAudioMixer below
4709 // mFastMixer below
Andy Hung2ddee192015-12-18 17:34:44 -08004710 mFastMixerFutex(0),
4711 mMasterMono(false)
Eric Laurent81784c32012-11-19 14:55:58 -08004712 // mOutputSink below
4713 // mPipeSink below
4714 // mNormalSink below
4715{
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01004716 setMasterBalance(audioFlinger->getMasterBalance_l());
jiabinc52b1ff2019-10-31 17:20:42 -07004717 ALOGV("MixerThread() id=%d type=%d", id, type);
Glenn Kasten49f36ba2017-12-06 13:02:02 -08004718 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%#x, mFrameSize=%zu, "
Glenn Kastenc42e9b42016-03-21 11:35:03 -07004719 "mFrameCount=%zu, mNormalFrameCount=%zu",
Eric Laurent81784c32012-11-19 14:55:58 -08004720 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
4721 mNormalFrameCount);
4722 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
4723
Andy Hungfbfc3952015-01-15 13:33:51 -08004724 if (type == DUPLICATING) {
4725 // The Duplicating thread uses the AudioMixer and delivers data to OutputTracks
4726 // (downstream MixerThreads) in DuplicatingThread::threadLoop_write().
4727 // Do not create or use mFastMixer, mOutputSink, mPipeSink, or mNormalSink.
4728 return;
4729 }
Eric Laurent81784c32012-11-19 14:55:58 -08004730 // create an NBAIO sink for the HAL output stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07004731 mOutputSink = new AudioStreamOutSink(output->stream);
Eric Laurent81784c32012-11-19 14:55:58 -08004732 size_t numCounterOffers = 0;
jiabin245cdd92018-12-07 17:55:15 -08004733 const NBAIO_Format offers[1] = {Format_from_SR_C(
4734 mSampleRate, mChannelCount + mHapticChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07004735#if !LOG_NDEBUG
4736 ssize_t index =
4737#else
4738 (void)
4739#endif
4740 mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08004741 ALOG_ASSERT(index == 0);
4742
4743 // initialize fast mixer depending on configuration
4744 bool initFastMixer;
Eric Laurentb62d0362021-10-26 17:40:18 +02004745 if (mType == SPATIALIZER) {
Eric Laurent81784c32012-11-19 14:55:58 -08004746 initFastMixer = false;
Eric Laurentb62d0362021-10-26 17:40:18 +02004747 } else {
4748 switch (kUseFastMixer) {
4749 case FastMixer_Never:
4750 initFastMixer = false;
4751 break;
4752 case FastMixer_Always:
4753 initFastMixer = true;
4754 break;
4755 case FastMixer_Static:
4756 case FastMixer_Dynamic:
4757 initFastMixer = mFrameCount < mNormalFrameCount;
4758 break;
4759 }
4760 ALOGW_IF(initFastMixer == false && mFrameCount < mNormalFrameCount,
4761 "FastMixer is preferred for this sink as frameCount %zu is less than threshold %zu",
4762 mFrameCount, mNormalFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08004763 }
4764 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07004765 audio_format_t fastMixerFormat;
4766 if (mMixerBufferEnabled && mEffectBufferEnabled) {
4767 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
4768 } else {
4769 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
4770 }
4771 if (mFormat != fastMixerFormat) {
4772 // change our Sink format to accept our intermediate precision
4773 mFormat = fastMixerFormat;
4774 free(mSinkBuffer);
jiabin245cdd92018-12-07 17:55:15 -08004775 mFrameSize = audio_bytes_per_frame(mChannelCount + mHapticChannelCount, mFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07004776 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
4777 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
4778 }
Eric Laurent81784c32012-11-19 14:55:58 -08004779
4780 // create a MonoPipe to connect our submix to FastMixer
4781 NBAIO_Format format = mOutputSink->format();
Andy Hung8946a282018-04-19 20:04:56 -07004782
Andy Hung1258c1a2014-05-23 21:22:17 -07004783 // adjust format to match that of the Fast Mixer
Glenn Kasten49f36ba2017-12-06 13:02:02 -08004784 ALOGV("format changed from %#x to %#x", format.mFormat, fastMixerFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07004785 format.mFormat = fastMixerFormat;
4786 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
4787
Eric Laurent81784c32012-11-19 14:55:58 -08004788 // This pipe depth compensates for scheduling latency of the normal mixer thread.
4789 // When it wakes up after a maximum latency, it runs a few cycles quickly before
4790 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
4791 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
4792 const NBAIO_Format offers[1] = {format};
4793 size_t numCounterOffers = 0;
Andy Hung8946a282018-04-19 20:04:56 -07004794#if !LOG_NDEBUG
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07004795 ssize_t index =
4796#else
4797 (void)
4798#endif
4799 monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08004800 ALOG_ASSERT(index == 0);
4801 monoPipe->setAvgFrames((mScreenState & 1) ?
4802 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
4803 mPipeSink = monoPipe;
4804
Eric Laurent81784c32012-11-19 14:55:58 -08004805 // create fast mixer and configure it initially with just one fast track for our submix
Andy Hung8946a282018-04-19 20:04:56 -07004806 mFastMixer = new FastMixer(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08004807 FastMixerStateQueue *sq = mFastMixer->sq();
4808#ifdef STATE_QUEUE_DUMP
4809 sq->setObserverDump(&mStateQueueObserverDump);
4810 sq->setMutatorDump(&mStateQueueMutatorDump);
4811#endif
4812 FastMixerState *state = sq->begin();
4813 FastTrack *fastTrack = &state->mFastTracks[0];
4814 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
4815 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
4816 fastTrack->mVolumeProvider = NULL;
Mikhail Naganov55773032020-10-01 15:08:13 -07004817 fastTrack->mChannelMask = static_cast<audio_channel_mask_t>(
4818 mChannelMask | mHapticChannelMask); // mPipeSink channel mask for
4819 // audio to FastMixer
Andy Hunge8a1ced2014-05-09 15:02:21 -07004820 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
jiabin245cdd92018-12-07 17:55:15 -08004821 fastTrack->mHapticPlaybackEnabled = mHapticChannelMask != AUDIO_CHANNEL_NONE;
jiabine70bc7f2020-06-30 22:07:55 -07004822 fastTrack->mHapticIntensity = os::HapticScale::NONE;
Lais Andradebc3f37a2021-07-02 00:13:19 +01004823 fastTrack->mHapticMaxAmplitude = NAN;
Eric Laurent81784c32012-11-19 14:55:58 -08004824 fastTrack->mGeneration++;
4825 state->mFastTracksGen++;
4826 state->mTrackMask = 1;
4827 // fast mixer will use the HAL output sink
4828 state->mOutputSink = mOutputSink.get();
4829 state->mOutputSinkGen++;
4830 state->mFrameCount = mFrameCount;
jiabin245cdd92018-12-07 17:55:15 -08004831 // specify sink channel mask when haptic channel mask present as it can not
4832 // be calculated directly from channel count
4833 state->mSinkChannelMask = mHapticChannelMask == AUDIO_CHANNEL_NONE
Mikhail Naganov55773032020-10-01 15:08:13 -07004834 ? AUDIO_CHANNEL_NONE
4835 : static_cast<audio_channel_mask_t>(mChannelMask | mHapticChannelMask);
Eric Laurent81784c32012-11-19 14:55:58 -08004836 state->mCommand = FastMixerState::COLD_IDLE;
4837 // already done in constructor initialization list
4838 //mFastMixerFutex = 0;
4839 state->mColdFutexAddr = &mFastMixerFutex;
4840 state->mColdGen++;
4841 state->mDumpState = &mFastMixerDumpState;
Glenn Kasten9e58b552013-01-18 15:09:48 -08004842 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
4843 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08004844 sq->end();
4845 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
4846
Eric Tan0513b5d2018-09-17 10:32:48 -07004847 NBLog::thread_info_t info;
4848 info.id = mId;
4849 info.type = NBLog::FASTMIXER;
4850 mFastMixerNBLogWriter->log<NBLog::EVENT_THREAD_INFO>(info);
4851
Eric Laurent81784c32012-11-19 14:55:58 -08004852 // start the fast mixer
4853 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
4854 pid_t tid = mFastMixer->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07004855 sendPrioConfigEvent(getpid(), tid, kPriorityFastMixer, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08004856 stream()->setHalThreadPriority(kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08004857
4858#ifdef AUDIO_WATCHDOG
4859 // create and start the watchdog
4860 mAudioWatchdog = new AudioWatchdog();
4861 mAudioWatchdog->setDump(&mAudioWatchdogDump);
4862 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
4863 tid = mAudioWatchdog->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07004864 sendPrioConfigEvent(getpid(), tid, kPriorityFastMixer, false /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08004865#endif
Andy Hung8946a282018-04-19 20:04:56 -07004866 } else {
4867#ifdef TEE_SINK
4868 // Only use the MixerThread tee if there is no FastMixer.
4869 mTee.set(mOutputSink->format(), NBAIO_Tee::TEE_FLAG_OUTPUT_THREAD);
4870 mTee.setId(std::string("_") + std::to_string(mId) + "_M");
4871#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004872 }
4873
4874 switch (kUseFastMixer) {
4875 case FastMixer_Never:
4876 case FastMixer_Dynamic:
4877 mNormalSink = mOutputSink;
4878 break;
4879 case FastMixer_Always:
4880 mNormalSink = mPipeSink;
4881 break;
4882 case FastMixer_Static:
4883 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
4884 break;
4885 }
4886}
4887
4888AudioFlinger::MixerThread::~MixerThread()
4889{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004890 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004891 FastMixerStateQueue *sq = mFastMixer->sq();
4892 FastMixerState *state = sq->begin();
4893 if (state->mCommand == FastMixerState::COLD_IDLE) {
4894 int32_t old = android_atomic_inc(&mFastMixerFutex);
4895 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07004896 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08004897 }
4898 }
4899 state->mCommand = FastMixerState::EXIT;
4900 sq->end();
4901 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
4902 mFastMixer->join();
4903 // Though the fast mixer thread has exited, it's state queue is still valid.
4904 // We'll use that extract the final state which contains one remaining fast track
4905 // corresponding to our sub-mix.
4906 state = sq->begin();
4907 ALOG_ASSERT(state->mTrackMask == 1);
4908 FastTrack *fastTrack = &state->mFastTracks[0];
4909 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
4910 delete fastTrack->mBufferProvider;
4911 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004912 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08004913#ifdef AUDIO_WATCHDOG
4914 if (mAudioWatchdog != 0) {
4915 mAudioWatchdog->requestExit();
4916 mAudioWatchdog->requestExitAndWait();
4917 mAudioWatchdog.clear();
4918 }
4919#endif
4920 }
Glenn Kasten9e58b552013-01-18 15:09:48 -08004921 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08004922 delete mAudioMixer;
4923}
4924
4925
4926uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
4927{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004928 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004929 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
4930 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
4931 }
4932 return latency;
4933}
4934
Eric Laurentbfb1b832013-01-07 09:53:42 -08004935ssize_t AudioFlinger::MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08004936{
4937 // FIXME we should only do one push per cycle; confirm this is true
4938 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004939 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004940 FastMixerStateQueue *sq = mFastMixer->sq();
4941 FastMixerState *state = sq->begin();
4942 if (state->mCommand != FastMixerState::MIX_WRITE &&
4943 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
4944 if (state->mCommand == FastMixerState::COLD_IDLE) {
Eric Laurenta2ab4502015-09-09 12:25:51 -07004945
4946 // FIXME workaround for first HAL write being CPU bound on some devices
4947 ATRACE_BEGIN("write");
4948 mOutput->write((char *)mSinkBuffer, 0);
4949 ATRACE_END();
4950
Eric Laurent81784c32012-11-19 14:55:58 -08004951 int32_t old = android_atomic_inc(&mFastMixerFutex);
4952 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07004953 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08004954 }
4955#ifdef AUDIO_WATCHDOG
4956 if (mAudioWatchdog != 0) {
4957 mAudioWatchdog->resume();
4958 }
4959#endif
4960 }
4961 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kastend797a9d2015-03-02 14:19:25 -08004962#ifdef FAST_THREAD_STATISTICS
Glenn Kasten4182c4e2013-07-15 14:45:07 -07004963 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08004964 FastThreadDumpState::kSamplingNforLowRamDevice : FastThreadDumpState::kSamplingN);
Glenn Kastend797a9d2015-03-02 14:19:25 -08004965#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004966 sq->end();
4967 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
4968 if (kUseFastMixer == FastMixer_Dynamic) {
4969 mNormalSink = mPipeSink;
4970 }
4971 } else {
4972 sq->end(false /*didModify*/);
4973 }
4974 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004975 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08004976}
4977
4978void AudioFlinger::MixerThread::threadLoop_standby()
4979{
4980 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004981 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004982 FastMixerStateQueue *sq = mFastMixer->sq();
4983 FastMixerState *state = sq->begin();
4984 if (!(state->mCommand & FastMixerState::IDLE)) {
Andy Hung2148bf02016-11-28 19:01:02 -08004985 // Report any frames trapped in the Monopipe
4986 MonoPipe *monoPipe = (MonoPipe *)mPipeSink.get();
4987 const long long pipeFrames = monoPipe->maxFrames() - monoPipe->availableToWrite();
4988 mLocalLog.log("threadLoop_standby: framesWritten:%lld suspendedFrames:%lld "
4989 "monoPipeWritten:%lld monoPipeLeft:%lld",
4990 (long long)mFramesWritten, (long long)mSuspendedFrames,
4991 (long long)mPipeSink->framesWritten(), pipeFrames);
4992 mLocalLog.log("threadLoop_standby: %s", mTimestamp.toString().c_str());
4993
Eric Laurent81784c32012-11-19 14:55:58 -08004994 state->mCommand = FastMixerState::COLD_IDLE;
4995 state->mColdFutexAddr = &mFastMixerFutex;
4996 state->mColdGen++;
4997 mFastMixerFutex = 0;
4998 sq->end();
4999 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
5000 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
5001 if (kUseFastMixer == FastMixer_Dynamic) {
5002 mNormalSink = mOutputSink;
5003 }
5004#ifdef AUDIO_WATCHDOG
5005 if (mAudioWatchdog != 0) {
5006 mAudioWatchdog->pause();
5007 }
5008#endif
5009 } else {
5010 sq->end(false /*didModify*/);
5011 }
5012 }
5013 PlaybackThread::threadLoop_standby();
5014}
5015
Eric Laurentbfb1b832013-01-07 09:53:42 -08005016bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
5017{
5018 return false;
5019}
5020
5021bool AudioFlinger::PlaybackThread::shouldStandby_l()
5022{
5023 return !mStandby;
5024}
5025
5026bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
5027{
5028 Mutex::Autolock _l(mLock);
5029 return waitingAsyncCallback_l();
5030}
5031
Eric Laurent81784c32012-11-19 14:55:58 -08005032// shared by MIXER and DIRECT, overridden by DUPLICATING
5033void AudioFlinger::PlaybackThread::threadLoop_standby()
5034{
5035 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
Phil Burk062e67a2015-02-11 13:40:50 -08005036 mOutput->standby();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005037 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005038 // discard any pending drain or write ack by incrementing sequence
5039 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
5040 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005041 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005042 mCallbackThread->setWriteBlocked(mWriteAckSequence);
5043 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005044 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08005045 mHwPaused = false;
Eric Laurent68a40a82022-05-03 18:15:04 +02005046 setHalLatencyMode_l();
Eric Laurent81784c32012-11-19 14:55:58 -08005047}
5048
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08005049void AudioFlinger::PlaybackThread::onAddNewTrack_l()
5050{
5051 ALOGV("signal playback thread");
5052 broadcast_l();
5053}
5054
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005055void AudioFlinger::PlaybackThread::onAsyncError()
5056{
5057 for (int i = AUDIO_STREAM_SYSTEM; i < (int)AUDIO_STREAM_CNT; i++) {
5058 invalidateTracks((audio_stream_type_t)i);
5059 }
5060}
5061
Eric Laurent81784c32012-11-19 14:55:58 -08005062void AudioFlinger::MixerThread::threadLoop_mix()
5063{
Eric Laurent81784c32012-11-19 14:55:58 -08005064 // mix buffers...
Glenn Kastend79072e2016-01-06 08:41:20 -08005065 mAudioMixer->process();
Andy Hung25c2dac2014-02-27 14:56:00 -08005066 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005067 // increase sleep time progressively when application underrun condition clears.
5068 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
5069 // that a steady state of alternating ready/not ready conditions keeps the sleep time
5070 // such that we would underrun the audio HAL.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005071 if ((mSleepTimeUs == 0) && (sleepTimeShift > 0)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005072 sleepTimeShift--;
5073 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005074 mSleepTimeUs = 0;
5075 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08005076 //TODO: delay standby when effects have a tail
Glenn Kasten4c053ea2014-09-28 14:41:07 -07005077
Eric Laurent81784c32012-11-19 14:55:58 -08005078}
5079
5080void AudioFlinger::MixerThread::threadLoop_sleepTime()
5081{
5082 // If no tracks are ready, sleep once for the duration of an output
5083 // buffer size, then write 0s to the output
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005084 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005085 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Andy Hung06d13222018-05-03 20:13:31 -07005086 if (mPipeSink.get() != nullptr && mPipeSink == mNormalSink) {
5087 // Using the Monopipe availableToWrite, we estimate the
5088 // sleep time to retry for more data (before we underrun).
5089 MonoPipe *monoPipe = static_cast<MonoPipe *>(mPipeSink.get());
5090 const ssize_t availableToWrite = mPipeSink->availableToWrite();
5091 const size_t pipeFrames = monoPipe->maxFrames();
5092 const size_t framesLeft = pipeFrames - max(availableToWrite, 0);
5093 // HAL_framecount <= framesDelay ~ framesLeft / 2 <= Normal_Mixer_framecount
5094 const size_t framesDelay = std::min(
5095 mNormalFrameCount, max(framesLeft / 2, mFrameCount));
5096 ALOGV("pipeFrames:%zu framesLeft:%zu framesDelay:%zu",
5097 pipeFrames, framesLeft, framesDelay);
5098 mSleepTimeUs = framesDelay * MICROS_PER_SECOND / mSampleRate;
5099 } else {
5100 mSleepTimeUs = mActiveSleepTimeUs >> sleepTimeShift;
5101 if (mSleepTimeUs < kMinThreadSleepTimeUs) {
5102 mSleepTimeUs = kMinThreadSleepTimeUs;
5103 }
5104 // reduce sleep time in case of consecutive application underruns to avoid
5105 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
5106 // duration we would end up writing less data than needed by the audio HAL if
5107 // the condition persists.
5108 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
5109 sleepTimeShift++;
5110 }
Eric Laurent81784c32012-11-19 14:55:58 -08005111 }
5112 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005113 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005114 }
5115 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08005116 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
5117 // before effects processing or output.
5118 if (mMixerBufferValid) {
5119 memset(mMixerBuffer, 0, mMixerBufferSize);
Eric Laurent39095982021-08-24 18:29:27 +02005120 if (mType == SPATIALIZER) {
5121 memset(mSinkBuffer, 0, mSinkBufferSize);
5122 }
Andy Hung98ef9782014-03-04 14:46:50 -08005123 } else {
5124 memset(mSinkBuffer, 0, mSinkBufferSize);
5125 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005126 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005127 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
5128 "anticipated start");
5129 }
5130 // TODO add standby time extension fct of effect tail
5131}
5132
5133// prepareTracks_l() must be called with ThreadBase::mLock held
5134AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
5135 Vector< sp<Track> > *tracksToRemove)
5136{
Andy Hungc0691382018-09-12 18:01:57 -07005137 // clean up deleted track ids in AudioMixer before allocating new tracks
5138 (void)mTracks.processDeletedTrackIds([this](int trackId) {
5139 // for each trackId, destroy it in the AudioMixer
5140 if (mAudioMixer->exists(trackId)) {
5141 mAudioMixer->destroy(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08005142 }
5143 });
Andy Hungc0691382018-09-12 18:01:57 -07005144 mTracks.clearDeletedTrackIds();
Eric Laurent81784c32012-11-19 14:55:58 -08005145
5146 mixer_state mixerStatus = MIXER_IDLE;
5147 // find out which tracks need to be processed
5148 size_t count = mActiveTracks.size();
5149 size_t mixedTracks = 0;
5150 size_t tracksWithEffect = 0;
5151 // counts only _active_ fast tracks
5152 size_t fastTracks = 0;
5153 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
5154
5155 float masterVolume = mMasterVolume;
5156 bool masterMute = mMasterMute;
5157
5158 if (masterMute) {
5159 masterVolume = 0;
5160 }
5161 // Delegate master volume control to effect in output mix effect chain if needed
5162 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
5163 if (chain != 0) {
5164 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
5165 chain->setVolume_l(&v, &v);
5166 masterVolume = (float)((v + (1 << 23)) >> 24);
5167 chain.clear();
5168 }
5169
5170 // prepare a new state to push
5171 FastMixerStateQueue *sq = NULL;
5172 FastMixerState *state = NULL;
5173 bool didModify = false;
5174 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Andy Hungf2285312017-02-14 18:31:59 -08005175 bool coldIdle = false;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005176 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005177 sq = mFastMixer->sq();
5178 state = sq->begin();
Andy Hungf2285312017-02-14 18:31:59 -08005179 coldIdle = state->mCommand == FastMixerState::COLD_IDLE;
Eric Laurent81784c32012-11-19 14:55:58 -08005180 }
5181
Andy Hung69aed5f2014-02-25 17:24:40 -08005182 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08005183 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08005184
Andy Hungbd3b2b02018-05-21 10:53:11 -07005185 // DeferredOperations handles statistics after setting mixerStatus.
5186 class DeferredOperations {
5187 public:
Andy Hungea840382020-05-05 21:50:17 -07005188 DeferredOperations(mixer_state *mixerStatus, ThreadMetrics *threadMetrics)
5189 : mMixerStatus(mixerStatus)
5190 , mThreadMetrics(threadMetrics) {}
Andy Hungbd3b2b02018-05-21 10:53:11 -07005191
5192 // when leaving scope, tally frames properly.
5193 ~DeferredOperations() {
5194 // Tally underrun frames only if we are actually mixing (MIXER_TRACKS_READY)
5195 // because that is when the underrun occurs.
5196 // We do not distinguish between FastTracks and NormalTracks here.
Andy Hungea840382020-05-05 21:50:17 -07005197 size_t maxUnderrunFrames = 0;
Andy Hungb68f5eb2019-12-03 16:49:17 -08005198 if (*mMixerStatus == MIXER_TRACKS_READY && mUnderrunFrames.size() > 0) {
Andy Hungbd3b2b02018-05-21 10:53:11 -07005199 for (const auto &underrun : mUnderrunFrames) {
Andy Hungc2b11cb2020-04-22 09:04:01 -07005200 underrun.first->tallyUnderrunFrames(underrun.second);
Andy Hungea840382020-05-05 21:50:17 -07005201 maxUnderrunFrames = max(underrun.second, maxUnderrunFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07005202 }
5203 }
Andy Hungea840382020-05-05 21:50:17 -07005204 // send the max underrun frames for this mixer period
5205 mThreadMetrics->logUnderrunFrames(maxUnderrunFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07005206 }
5207
5208 // tallyUnderrunFrames() is called to update the track counters
5209 // with the number of underrun frames for a particular mixer period.
5210 // We defer tallying until we know the final mixer status.
5211 void tallyUnderrunFrames(sp<Track> track, size_t underrunFrames) {
5212 mUnderrunFrames.emplace_back(track, underrunFrames);
5213 }
5214
5215 private:
5216 const mixer_state * const mMixerStatus;
Andy Hungea840382020-05-05 21:50:17 -07005217 ThreadMetrics * const mThreadMetrics;
Andy Hungbd3b2b02018-05-21 10:53:11 -07005218 std::vector<std::pair<sp<Track>, size_t>> mUnderrunFrames;
Andy Hungea840382020-05-05 21:50:17 -07005219 } deferredOperations(&mixerStatus, &mThreadMetrics);
Andy Hungb68f5eb2019-12-03 16:49:17 -08005220 // implicit nested scope for variable capture
Andy Hungbd3b2b02018-05-21 10:53:11 -07005221
jiabin245cdd92018-12-07 17:55:15 -08005222 bool noFastHapticTrack = true;
Eric Laurent81784c32012-11-19 14:55:58 -08005223 for (size_t i=0 ; i<count ; i++) {
Andy Hungdae27702016-10-31 14:01:16 -07005224 const sp<Track> t = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08005225
5226 // this const just means the local variable doesn't change
5227 Track* const track = t.get();
5228
5229 // process fast tracks
5230 if (track->isFastTrack()) {
Andy Hungae22b482019-05-09 15:38:55 -07005231 LOG_ALWAYS_FATAL_IF(mFastMixer.get() == nullptr,
5232 "%s(%d): FastTrack(%d) present without FastMixer",
5233 __func__, id(), track->id());
5234
jiabin245cdd92018-12-07 17:55:15 -08005235 if (track->getHapticPlaybackEnabled()) {
5236 noFastHapticTrack = false;
5237 }
Eric Laurent81784c32012-11-19 14:55:58 -08005238
5239 // It's theoretically possible (though unlikely) for a fast track to be created
5240 // and then removed within the same normal mix cycle. This is not a problem, as
5241 // the track never becomes active so it's fast mixer slot is never touched.
5242 // The converse, of removing an (active) track and then creating a new track
5243 // at the identical fast mixer slot within the same normal mix cycle,
5244 // is impossible because the slot isn't marked available until the end of each cycle.
5245 int j = track->mFastIndex;
Glenn Kastendc2c50b2016-04-21 08:13:14 -07005246 ALOG_ASSERT(0 < j && j < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08005247 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
5248 FastTrack *fastTrack = &state->mFastTracks[j];
5249
5250 // Determine whether the track is currently in underrun condition,
5251 // and whether it had a recent underrun.
5252 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
5253 FastTrackUnderruns underruns = ftDump->mUnderruns;
5254 uint32_t recentFull = (underruns.mBitFields.mFull -
5255 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
5256 uint32_t recentPartial = (underruns.mBitFields.mPartial -
5257 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
5258 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
5259 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
5260 uint32_t recentUnderruns = recentPartial + recentEmpty;
5261 track->mObservedUnderruns = underruns;
5262 // don't count underruns that occur while stopping or pausing
5263 // or stopped which can occur when flush() is called while active
Andy Hungbd3b2b02018-05-21 10:53:11 -07005264 size_t underrunFrames = 0;
Glenn Kasten82aaf942013-07-17 16:05:07 -07005265 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
5266 recentUnderruns > 0) {
5267 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
Andy Hungbd3b2b02018-05-21 10:53:11 -07005268 underrunFrames = recentUnderruns * mFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08005269 }
Andy Hungbd3b2b02018-05-21 10:53:11 -07005270 // Immediately account for FastTrack underruns.
5271 track->mAudioTrackServerProxy->tallyUnderrunFrames(underrunFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08005272
5273 // This is similar to the state machine for normal tracks,
5274 // with a few modifications for fast tracks.
5275 bool isActive = true;
5276 switch (track->mState) {
5277 case TrackBase::STOPPING_1:
5278 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08005279 if (recentUnderruns > 0 || track->isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -08005280 track->mState = TrackBase::STOPPING_2;
5281 }
5282 break;
5283 case TrackBase::PAUSING:
5284 // ramp down is not yet implemented
5285 track->setPaused();
5286 break;
5287 case TrackBase::RESUMING:
5288 // ramp up is not yet implemented
5289 track->mState = TrackBase::ACTIVE;
5290 break;
5291 case TrackBase::ACTIVE:
5292 if (recentFull > 0 || recentPartial > 0) {
5293 // track has provided at least some frames recently: reset retry count
5294 track->mRetryCount = kMaxTrackRetries;
5295 }
5296 if (recentUnderruns == 0) {
5297 // no recent underruns: stay active
5298 break;
5299 }
5300 // there has recently been an underrun of some kind
5301 if (track->sharedBuffer() == 0) {
5302 // were any of the recent underruns "empty" (no frames available)?
5303 if (recentEmpty == 0) {
5304 // no, then ignore the partial underruns as they are allowed indefinitely
5305 break;
5306 }
5307 // there has recently been an "empty" underrun: decrement the retry counter
5308 if (--(track->mRetryCount) > 0) {
5309 break;
5310 }
5311 // indicate to client process that the track was disabled because of underrun;
5312 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08005313 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08005314 // remove from active list, but state remains ACTIVE [confusing but true]
5315 isActive = false;
5316 break;
5317 }
Chih-Hung Hsieh2b487032018-09-13 14:16:02 -07005318 FALLTHROUGH_INTENDED;
Eric Laurent81784c32012-11-19 14:55:58 -08005319 case TrackBase::STOPPING_2:
5320 case TrackBase::PAUSED:
Eric Laurent81784c32012-11-19 14:55:58 -08005321 case TrackBase::STOPPED:
5322 case TrackBase::FLUSHED: // flush() while active
5323 // Check for presentation complete if track is inactive
5324 // We have consumed all the buffers of this track.
5325 // This would be incomplete if we auto-paused on underrun
5326 {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005327 uint32_t latency = 0;
5328 status_t result = mOutput->stream->getLatency(&latency);
5329 ALOGE_IF(result != OK,
5330 "Error when retrieving output stream latency: %d", result);
5331 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08005332 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005333 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
5334 // track stays in active list until presentation is complete
5335 break;
5336 }
5337 }
5338 if (track->isStopping_2()) {
5339 track->mState = TrackBase::STOPPED;
5340 }
5341 if (track->isStopped()) {
5342 // Can't reset directly, as fast mixer is still polling this track
5343 // track->reset();
5344 // So instead mark this track as needing to be reset after push with ack
5345 resetMask |= 1 << i;
5346 }
5347 isActive = false;
5348 break;
5349 case TrackBase::IDLE:
5350 default:
Andy Hung959b5b82021-09-24 10:46:20 -07005351 LOG_ALWAYS_FATAL("unexpected track state %d", (int)track->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08005352 }
5353
5354 if (isActive) {
5355 // was it previously inactive?
5356 if (!(state->mTrackMask & (1 << j))) {
5357 ExtendedAudioBufferProvider *eabp = track;
5358 VolumeProvider *vp = track;
5359 fastTrack->mBufferProvider = eabp;
5360 fastTrack->mVolumeProvider = vp;
Eric Laurent81784c32012-11-19 14:55:58 -08005361 fastTrack->mChannelMask = track->mChannelMask;
Andy Hunge8a1ced2014-05-09 15:02:21 -07005362 fastTrack->mFormat = track->mFormat;
jiabin245cdd92018-12-07 17:55:15 -08005363 fastTrack->mHapticPlaybackEnabled = track->getHapticPlaybackEnabled();
jiabin77270b82018-12-18 15:41:29 -08005364 fastTrack->mHapticIntensity = track->getHapticIntensity();
Lais Andradebc3f37a2021-07-02 00:13:19 +01005365 fastTrack->mHapticMaxAmplitude = track->getHapticMaxAmplitude();
Eric Laurent81784c32012-11-19 14:55:58 -08005366 fastTrack->mGeneration++;
5367 state->mTrackMask |= 1 << j;
5368 didModify = true;
5369 // no acknowledgement required for newly active tracks
5370 }
Kevin Rocard12381092018-04-11 09:19:59 -07005371 sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
Eric Laurenteab90452019-06-24 15:17:46 -07005372 float volume;
5373 if (track->isPlaybackRestricted() || mStreamTypes[track->streamType()].mute) {
5374 volume = 0.f;
5375 } else {
5376 volume = masterVolume * mStreamTypes[track->streamType()].volume;
5377 }
5378
Vlad Popae8d99472022-06-30 16:02:48 +02005379 track->processMuteEvent_l(mAudioFlinger->getOrCreateAudioManager(),
5380 /*muteState=*/{masterVolume == 0.f,
5381 mStreamTypes[track->streamType()].volume == 0.f,
5382 mStreamTypes[track->streamType()].mute,
5383 track->isPlaybackRestricted()});
5384
Eric Laurenteab90452019-06-24 15:17:46 -07005385 handleVoipVolume_l(&volume);
5386
Eric Laurent81784c32012-11-19 14:55:58 -08005387 // cache the combined master volume and stream type volume for fast mixer; this
5388 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005389 const float vh = track->getVolumeHandler()->getVolume(
Eric Laurenteab90452019-06-24 15:17:46 -07005390 proxy->framesReleased()).first;
5391 volume *= vh;
Kevin Rocardb0eeaf122018-04-11 08:30:16 -07005392 track->mCachedVolume = volume;
Kevin Rocard12381092018-04-11 09:19:59 -07005393 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
5394 float vlf = volume * float_from_gain(gain_minifloat_unpack_left(vlr));
5395 float vrf = volume * float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurenteab90452019-06-24 15:17:46 -07005396
Kevin Rocard12381092018-04-11 09:19:59 -07005397 track->setFinalVolume((vlf + vrf) / 2.f);
Eric Laurent81784c32012-11-19 14:55:58 -08005398 ++fastTracks;
5399 } else {
5400 // was it previously active?
5401 if (state->mTrackMask & (1 << j)) {
5402 fastTrack->mBufferProvider = NULL;
5403 fastTrack->mGeneration++;
5404 state->mTrackMask &= ~(1 << j);
5405 didModify = true;
5406 // If any fast tracks were removed, we must wait for acknowledgement
5407 // because we're about to decrement the last sp<> on those tracks.
5408 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
5409 } else {
Glenn Kastenbf848af2017-12-22 11:55:01 -08005410 // ALOGW rather than LOG_ALWAYS_FATAL because it seems there are cases where an
5411 // AudioTrack may start (which may not be with a start() but with a write()
5412 // after underrun) and immediately paused or released. In that case the
5413 // FastTrack state hasn't had time to update.
5414 // TODO Remove the ALOGW when this theory is confirmed.
5415 ALOGW("fast track %d should have been active; "
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08005416 "mState=%d, mTrackMask=%#x, recentUnderruns=%u, isShared=%d",
Andy Hung959b5b82021-09-24 10:46:20 -07005417 j, (int)track->mState, state->mTrackMask, recentUnderruns,
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08005418 track->sharedBuffer() != 0);
Glenn Kastenbf848af2017-12-22 11:55:01 -08005419 // Since the FastMixer state already has the track inactive, do nothing here.
Eric Laurent81784c32012-11-19 14:55:58 -08005420 }
5421 tracksToRemove->add(track);
5422 // Avoids a misleading display in dumpsys
5423 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
5424 }
jiabin245cdd92018-12-07 17:55:15 -08005425 if (fastTrack->mHapticPlaybackEnabled != track->getHapticPlaybackEnabled()) {
5426 fastTrack->mHapticPlaybackEnabled = track->getHapticPlaybackEnabled();
5427 didModify = true;
5428 }
Eric Laurent81784c32012-11-19 14:55:58 -08005429 continue;
5430 }
5431
5432 { // local variable scope to avoid goto warning
5433
5434 audio_track_cblk_t* cblk = track->cblk();
5435
5436 // The first time a track is added we wait
5437 // for all its buffers to be filled before processing it
Andy Hungc0691382018-09-12 18:01:57 -07005438 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08005439
5440 // if an active track doesn't exist in the AudioMixer, create it.
Andy Hungc0691382018-09-12 18:01:57 -07005441 // use the trackId as the AudioMixer name.
5442 if (!mAudioMixer->exists(trackId)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08005443 status_t status = mAudioMixer->create(
Andy Hungc0691382018-09-12 18:01:57 -07005444 trackId,
Andy Hung1bc088a2018-02-09 15:57:31 -08005445 track->mChannelMask,
5446 track->mFormat,
5447 track->mSessionId);
5448 if (status != OK) {
Andy Hungc0691382018-09-12 18:01:57 -07005449 ALOGW("%s(): AudioMixer cannot create track(%d)"
5450 " mask %#x, format %#x, sessionId %d",
5451 __func__, trackId,
5452 track->mChannelMask, track->mFormat, track->mSessionId);
Andy Hung1bc088a2018-02-09 15:57:31 -08005453 tracksToRemove->add(track);
5454 track->invalidate(); // consider it dead.
5455 continue;
5456 }
5457 }
5458
Eric Laurent81784c32012-11-19 14:55:58 -08005459 // make sure that we have enough frames to mix one full buffer.
5460 // enforce this condition only once to enable draining the buffer in case the client
5461 // app does not call stop() and relies on underrun to stop:
5462 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
5463 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005464 size_t desiredFrames;
Andy Hung8edb8dc2015-03-26 19:13:55 -07005465 const uint32_t sampleRate = track->mAudioTrackServerProxy->getSampleRate();
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07005466 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07005467
5468 desiredFrames = sourceFramesNeededWithTimestretch(
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07005469 sampleRate, mNormalFrameCount, mSampleRate, playbackRate.mSpeed);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005470 // TODO: ONLY USED FOR LEGACY RESAMPLERS, remove when they are removed.
5471 // add frames already consumed but not yet released by the resampler
5472 // because mAudioTrackServerProxy->framesReady() will include these frames
Andy Hungc0691382018-09-12 18:01:57 -07005473 desiredFrames += mAudioMixer->getUnreleasedFrames(trackId);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005474
Eric Laurent81784c32012-11-19 14:55:58 -08005475 uint32_t minFrames = 1;
5476 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
5477 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005478 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08005479 }
Eric Laurent13e4c962013-12-20 17:36:01 -08005480
5481 size_t framesReady = track->framesReady();
Glenn Kastene7754022014-10-31 12:11:26 -07005482 if (ATRACE_ENABLED()) {
5483 // I wish we had formatted trace names
Andy Hung1bc088a2018-02-09 15:57:31 -08005484 std::string traceName("nRdy");
Andy Hungc0691382018-09-12 18:01:57 -07005485 traceName += std::to_string(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08005486 ATRACE_INT(traceName.c_str(), framesReady);
Glenn Kastene7754022014-10-31 12:11:26 -07005487 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005488 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08005489 !track->isPaused() && !track->isTerminated())
5490 {
Andy Hungc0691382018-09-12 18:01:57 -07005491 ALOGVV("track(%d) s=%08x [OK] on thread %p", trackId, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08005492
5493 mixedTracks++;
5494
Andy Hung69aed5f2014-02-25 17:24:40 -08005495 // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
5496 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08005497 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08005498 if (track->mainBuffer() != mSinkBuffer &&
5499 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08005500 if (mEffectBufferEnabled) {
5501 mEffectBufferValid = true; // Later can set directly.
5502 }
Eric Laurent81784c32012-11-19 14:55:58 -08005503 chain = getEffectChain_l(track->sessionId());
5504 // Delegate volume control to effect in track effect chain if needed
5505 if (chain != 0) {
5506 tracksWithEffect++;
5507 } else {
Andy Hungc0691382018-09-12 18:01:57 -07005508 ALOGW("prepareTracks_l(): track(%d) attached to effect but no chain found on "
Eric Laurent81784c32012-11-19 14:55:58 -08005509 "session %d",
Andy Hungc0691382018-09-12 18:01:57 -07005510 trackId, track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08005511 }
5512 }
5513
5514
5515 int param = AudioMixer::VOLUME;
5516 if (track->mFillingUpStatus == Track::FS_FILLED) {
5517 // no ramp for the first volume setting
5518 track->mFillingUpStatus = Track::FS_ACTIVE;
5519 if (track->mState == TrackBase::RESUMING) {
5520 track->mState = TrackBase::ACTIVE;
Revathi Uddaraju453bcb52017-08-14 14:19:40 +08005521 // If a new track is paused immediately after start, do not ramp on resume.
5522 if (cblk->mServer != 0) {
5523 param = AudioMixer::RAMP_VOLUME;
5524 }
Eric Laurent81784c32012-11-19 14:55:58 -08005525 }
Andy Hungc0691382018-09-12 18:01:57 -07005526 mAudioMixer->setParameter(trackId, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Eric Laurent7c29ec92017-09-20 17:54:22 -07005527 mLeftVolFloat = -1.0;
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005528 // FIXME should not make a decision based on mServer
5529 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005530 // If the track is stopped before the first frame was mixed,
5531 // do not apply ramp
5532 param = AudioMixer::RAMP_VOLUME;
5533 }
5534
5535 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07005536 uint32_t vl, vr; // in U8.24 integer format
5537 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Eric Laurent7c29ec92017-09-20 17:54:22 -07005538 // read original volumes with volume control
Eric Laurenteab90452019-06-24 15:17:46 -07005539 float v = masterVolume * mStreamTypes[track->streamType()].volume;
Andy Hung333ab962019-05-28 20:23:35 -07005540 // Always fetch volumeshaper volume to ensure state is updated.
5541 const sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
5542 const float vh = track->getVolumeHandler()->getVolume(
5543 track->mAudioTrackServerProxy->framesReleased()).first;
Eric Laurent7c29ec92017-09-20 17:54:22 -07005544
Eric Laurenteab90452019-06-24 15:17:46 -07005545 if (mStreamTypes[track->streamType()].mute || track->isPlaybackRestricted()) {
5546 v = 0;
5547 }
5548
Vlad Popae8d99472022-06-30 16:02:48 +02005549 track->processMuteEvent_l(mAudioFlinger->getOrCreateAudioManager(),
5550 /*muteState=*/{masterVolume == 0.f,
5551 mStreamTypes[track->streamType()].volume == 0.f,
5552 mStreamTypes[track->streamType()].mute,
5553 track->isPlaybackRestricted()});
5554
Eric Laurenteab90452019-06-24 15:17:46 -07005555 handleVoipVolume_l(&v);
5556
5557 if (track->isPausing()) {
Andy Hung6be49402014-05-30 10:42:03 -07005558 vl = vr = 0;
5559 vlf = vrf = vaf = 0.;
Eric Laurenteab90452019-06-24 15:17:46 -07005560 track->setPaused();
Eric Laurent81784c32012-11-19 14:55:58 -08005561 } else {
Glenn Kastenc56f3422014-03-21 17:53:17 -07005562 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07005563 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
5564 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08005565 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07005566 if (vlf > GAIN_FLOAT_UNITY) {
5567 ALOGV("Track left volume out of range: %.3g", vlf);
5568 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08005569 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07005570 if (vrf > GAIN_FLOAT_UNITY) {
5571 ALOGV("Track right volume out of range: %.3g", vrf);
5572 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08005573 }
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005574 // now apply the master volume and stream type volume and shaper volume
5575 vlf *= v * vh;
5576 vrf *= v * vh;
Eric Laurent81784c32012-11-19 14:55:58 -08005577 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07005578 // then derive vl and vr as U8.24 versions for the effect chain
5579 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
5580 vl = (uint32_t) (scaleto8_24 * vlf);
5581 vr = (uint32_t) (scaleto8_24 * vrf);
5582 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08005583 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08005584 // send level comes from shared memory and so may be corrupt
5585 if (sendLevel > MAX_GAIN_INT) {
5586 ALOGV("Track send level out of range: %04X", sendLevel);
5587 sendLevel = MAX_GAIN_INT;
5588 }
Andy Hung6be49402014-05-30 10:42:03 -07005589 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
5590 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08005591 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005592
Kevin Rocard12381092018-04-11 09:19:59 -07005593 track->setFinalVolume((vrf + vlf) / 2.f);
5594
Eric Laurent81784c32012-11-19 14:55:58 -08005595 // Delegate volume control to effect in track effect chain if needed
5596 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
5597 // Do not ramp volume if volume is controlled by effect
5598 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08005599 // Update remaining floating point volume levels
5600 vlf = (float)vl / (1 << 24);
5601 vrf = (float)vr / (1 << 24);
Eric Laurent81784c32012-11-19 14:55:58 -08005602 track->mHasVolumeController = true;
5603 } else {
5604 // force no volume ramp when volume controller was just disabled or removed
5605 // from effect chain to avoid volume spike
5606 if (track->mHasVolumeController) {
5607 param = AudioMixer::VOLUME;
5608 }
5609 track->mHasVolumeController = false;
5610 }
5611
Eric Laurent81784c32012-11-19 14:55:58 -08005612 // XXX: these things DON'T need to be done each time
Andy Hungc0691382018-09-12 18:01:57 -07005613 mAudioMixer->setBufferProvider(trackId, track);
5614 mAudioMixer->enable(trackId);
Eric Laurent81784c32012-11-19 14:55:58 -08005615
Andy Hungc0691382018-09-12 18:01:57 -07005616 mAudioMixer->setParameter(trackId, param, AudioMixer::VOLUME0, &vlf);
5617 mAudioMixer->setParameter(trackId, param, AudioMixer::VOLUME1, &vrf);
5618 mAudioMixer->setParameter(trackId, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08005619 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005620 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005621 AudioMixer::TRACK,
5622 AudioMixer::FORMAT, (void *)track->format());
5623 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005624 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005625 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00005626 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Eric Laurent39095982021-08-24 18:29:27 +02005627
Eric Laurentb0a7bc92022-04-05 15:06:08 +02005628 if (mType == SPATIALIZER && !track->isSpatialized()) {
Eric Laurent39095982021-08-24 18:29:27 +02005629 mAudioMixer->setParameter(
5630 trackId,
5631 AudioMixer::TRACK,
5632 AudioMixer::MIXER_CHANNEL_MASK,
5633 (void *)(uintptr_t)(mChannelMask | mHapticChannelMask));
5634 } else {
5635 mAudioMixer->setParameter(
5636 trackId,
5637 AudioMixer::TRACK,
5638 AudioMixer::MIXER_CHANNEL_MASK,
5639 (void *)(uintptr_t)(mMixerChannelMask | mHapticChannelMask));
5640 }
5641
Glenn Kastene3aa6592012-12-04 12:22:46 -08005642 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07005643 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Andy Hung333ab962019-05-28 20:23:35 -07005644 uint32_t reqSampleRate = proxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08005645 if (reqSampleRate == 0) {
5646 reqSampleRate = mSampleRate;
5647 } else if (reqSampleRate > maxSampleRate) {
5648 reqSampleRate = maxSampleRate;
5649 }
Eric Laurent81784c32012-11-19 14:55:58 -08005650 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005651 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005652 AudioMixer::RESAMPLE,
5653 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00005654 (void *)(uintptr_t)reqSampleRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005655
Andy Hung333ab962019-05-28 20:23:35 -07005656 AudioPlaybackRate playbackRate = proxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07005657 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005658 trackId,
Andy Hung8edb8dc2015-03-26 19:13:55 -07005659 AudioMixer::TIMESTRETCH,
5660 AudioMixer::PLAYBACK_RATE,
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07005661 &playbackRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005662
Andy Hung69aed5f2014-02-25 17:24:40 -08005663 /*
5664 * Select the appropriate output buffer for the track.
5665 *
Andy Hung98ef9782014-03-04 14:46:50 -08005666 * Tracks with effects go into their own effects chain buffer
5667 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08005668 *
5669 * Other tracks can use mMixerBuffer for higher precision
5670 * channel accumulation. If this buffer is enabled
5671 * (mMixerBufferEnabled true), then selected tracks will accumulate
5672 * into it.
5673 *
5674 */
5675 if (mMixerBufferEnabled
5676 && (track->mainBuffer() == mSinkBuffer
5677 || track->mainBuffer() == mMixerBuffer)) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02005678 if (mType == SPATIALIZER && !track->isSpatialized()) {
Eric Laurent39095982021-08-24 18:29:27 +02005679 mAudioMixer->setParameter(
5680 trackId,
5681 AudioMixer::TRACK,
Eric Laurentb62d0362021-10-26 17:40:18 +02005682 AudioMixer::MIXER_FORMAT, (void *)mEffectBufferFormat);
Eric Laurent39095982021-08-24 18:29:27 +02005683 mAudioMixer->setParameter(
5684 trackId,
5685 AudioMixer::TRACK,
Eric Laurentb62d0362021-10-26 17:40:18 +02005686 AudioMixer::MAIN_BUFFER, (void *)mPostSpatializerBuffer);
Eric Laurent39095982021-08-24 18:29:27 +02005687 } else {
5688 mAudioMixer->setParameter(
5689 trackId,
5690 AudioMixer::TRACK,
5691 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
5692 mAudioMixer->setParameter(
5693 trackId,
5694 AudioMixer::TRACK,
5695 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
5696 // TODO: override track->mainBuffer()?
5697 mMixerBufferValid = true;
5698 }
Andy Hung69aed5f2014-02-25 17:24:40 -08005699 } else {
5700 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005701 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08005702 AudioMixer::TRACK,
rago94a1ee82017-07-21 15:11:02 -07005703 AudioMixer::MIXER_FORMAT, (void *)EFFECT_BUFFER_FORMAT);
Andy Hung69aed5f2014-02-25 17:24:40 -08005704 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005705 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08005706 AudioMixer::TRACK,
5707 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
5708 }
Eric Laurent81784c32012-11-19 14:55:58 -08005709 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005710 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005711 AudioMixer::TRACK,
5712 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
jiabin245cdd92018-12-07 17:55:15 -08005713 mAudioMixer->setParameter(
5714 trackId,
5715 AudioMixer::TRACK,
5716 AudioMixer::HAPTIC_ENABLED, (void *)(uintptr_t)track->getHapticPlaybackEnabled());
jiabin77270b82018-12-18 15:41:29 -08005717 mAudioMixer->setParameter(
5718 trackId,
5719 AudioMixer::TRACK,
5720 AudioMixer::HAPTIC_INTENSITY, (void *)(uintptr_t)track->getHapticIntensity());
Lais Andradebc3f37a2021-07-02 00:13:19 +01005721 mAudioMixer->setParameter(
5722 trackId,
5723 AudioMixer::TRACK,
5724 AudioMixer::HAPTIC_MAX_AMPLITUDE, (void *)(&(track->mHapticMaxAmplitude)));
Eric Laurent81784c32012-11-19 14:55:58 -08005725
5726 // reset retry count
5727 track->mRetryCount = kMaxTrackRetries;
5728
5729 // If one track is ready, set the mixer ready if:
5730 // - the mixer was not ready during previous round OR
5731 // - no other track is not ready
5732 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
5733 mixerStatus != MIXER_TRACKS_ENABLED) {
5734 mixerStatus = MIXER_TRACKS_READY;
5735 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08005736
5737 // Enable the next few lines to instrument a test for underrun log handling.
5738 // TODO: Remove when we have a better way of testing the underrun log.
5739#if 0
5740 static int i;
5741 if ((++i & 0xf) == 0) {
5742 deferredOperations.tallyUnderrunFrames(track, 10 /* underrunFrames */);
5743 }
5744#endif
Eric Laurent81784c32012-11-19 14:55:58 -08005745 } else {
Andy Hungbd3b2b02018-05-21 10:53:11 -07005746 size_t underrunFrames = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005747 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Andy Hungb68f5eb2019-12-03 16:49:17 -08005748 ALOGV("track(%d) underrun, track state %s framesReady(%zu) < framesDesired(%zd)",
5749 trackId, track->getTrackStateAsString(), framesReady, desiredFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07005750 underrunFrames = desiredFrames;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005751 }
Andy Hungbd3b2b02018-05-21 10:53:11 -07005752 deferredOperations.tallyUnderrunFrames(track, underrunFrames);
Phil Burk2812d9e2016-01-04 10:34:30 -08005753
Eric Laurent81784c32012-11-19 14:55:58 -08005754 // clear effect chain input buffer if an active track underruns to avoid sending
5755 // previous audio buffer again to effects
5756 chain = getEffectChain_l(track->sessionId());
5757 if (chain != 0) {
5758 chain->clearInputBuffer();
5759 }
5760
Andy Hungc0691382018-09-12 18:01:57 -07005761 ALOGVV("track(%d) s=%08x [NOT READY] on thread %p", trackId, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08005762 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
5763 track->isStopped() || track->isPaused()) {
5764 // We have consumed all the buffers of this track.
5765 // Remove it from the list of active tracks.
5766 // TODO: use actual buffer filling status instead of latency when available from
5767 // audio HAL
5768 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08005769 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005770 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
5771 if (track->isStopped()) {
5772 track->reset();
5773 }
5774 tracksToRemove->add(track);
5775 }
5776 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08005777 // No buffers for this track. Give it a few chances to
5778 // fill a buffer, then remove it from active list.
5779 if (--(track->mRetryCount) <= 0) {
Andy Hungc0691382018-09-12 18:01:57 -07005780 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p",
5781 trackId, this);
Eric Laurent81784c32012-11-19 14:55:58 -08005782 tracksToRemove->add(track);
5783 // indicate to client process that the track was disabled because of underrun;
5784 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08005785 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08005786 // If one track is not ready, mark the mixer also not ready if:
5787 // - the mixer was ready during previous round OR
5788 // - no other track is ready
5789 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
5790 mixerStatus != MIXER_TRACKS_READY) {
5791 mixerStatus = MIXER_TRACKS_ENABLED;
5792 }
5793 }
Andy Hungc0691382018-09-12 18:01:57 -07005794 mAudioMixer->disable(trackId);
Eric Laurent81784c32012-11-19 14:55:58 -08005795 }
5796
5797 } // local variable scope to avoid goto warning
Eric Laurent81784c32012-11-19 14:55:58 -08005798
5799 }
5800
jiabin245cdd92018-12-07 17:55:15 -08005801 if (mHapticChannelMask != AUDIO_CHANNEL_NONE && sq != NULL) {
5802 // When there is no fast track playing haptic and FastMixer exists,
5803 // enabling the first FastTrack, which provides mixed data from normal
5804 // tracks, to play haptic data.
5805 FastTrack *fastTrack = &state->mFastTracks[0];
5806 if (fastTrack->mHapticPlaybackEnabled != noFastHapticTrack) {
5807 fastTrack->mHapticPlaybackEnabled = noFastHapticTrack;
5808 didModify = true;
5809 }
5810 }
5811
Eric Laurent81784c32012-11-19 14:55:58 -08005812 // Push the new FastMixer state if necessary
5813 bool pauseAudioWatchdog = false;
5814 if (didModify) {
5815 state->mFastTracksGen++;
5816 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
5817 if (kUseFastMixer == FastMixer_Dynamic &&
5818 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
5819 state->mCommand = FastMixerState::COLD_IDLE;
5820 state->mColdFutexAddr = &mFastMixerFutex;
5821 state->mColdGen++;
5822 mFastMixerFutex = 0;
5823 if (kUseFastMixer == FastMixer_Dynamic) {
5824 mNormalSink = mOutputSink;
5825 }
5826 // If we go into cold idle, need to wait for acknowledgement
5827 // so that fast mixer stops doing I/O.
5828 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
5829 pauseAudioWatchdog = true;
5830 }
Eric Laurent81784c32012-11-19 14:55:58 -08005831 }
5832 if (sq != NULL) {
5833 sq->end(didModify);
Andy Hungf2285312017-02-14 18:31:59 -08005834 // No need to block if the FastMixer is in COLD_IDLE as the FastThread
5835 // is not active. (We BLOCK_UNTIL_ACKED when entering COLD_IDLE
5836 // when bringing the output sink into standby.)
5837 //
5838 // We will get the latest FastMixer state when we come out of COLD_IDLE.
5839 //
5840 // This occurs with BT suspend when we idle the FastMixer with
5841 // active tracks, which may be added or removed.
5842 sq->push(coldIdle ? FastMixerStateQueue::BLOCK_NEVER : block);
Eric Laurent81784c32012-11-19 14:55:58 -08005843 }
5844#ifdef AUDIO_WATCHDOG
5845 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
5846 mAudioWatchdog->pause();
5847 }
5848#endif
5849
5850 // Now perform the deferred reset on fast tracks that have stopped
5851 while (resetMask != 0) {
5852 size_t i = __builtin_ctz(resetMask);
5853 ALOG_ASSERT(i < count);
5854 resetMask &= ~(1 << i);
Andy Hungdae27702016-10-31 14:01:16 -07005855 sp<Track> track = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08005856 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
5857 track->reset();
5858 }
5859
Andy Hung80d03d22018-04-10 10:32:11 -07005860 // Track destruction may occur outside of threadLoop once it is removed from active tracks.
5861 // Ensure the AudioMixer doesn't have a raw "buffer provider" pointer to the track if
5862 // it ceases to be active, to allow safe removal from the AudioMixer at the start
5863 // of prepareTracks_l(); this releases any outstanding buffer back to the track.
5864 // See also the implementation of destroyTrack_l().
5865 for (const auto &track : *tracksToRemove) {
Andy Hungc0691382018-09-12 18:01:57 -07005866 const int trackId = track->id();
5867 if (mAudioMixer->exists(trackId)) { // Normal tracks here, fast tracks in FastMixer.
5868 mAudioMixer->setBufferProvider(trackId, nullptr /* bufferProvider */);
Andy Hung80d03d22018-04-10 10:32:11 -07005869 }
5870 }
5871
Eric Laurent81784c32012-11-19 14:55:58 -08005872 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08005873 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08005874
Eric Laurentb3f315a2021-07-13 15:09:05 +02005875 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0 ||
5876 getEffectChain_l(AUDIO_SESSION_OUTPUT_STAGE) != 0) {
Eric Laurent97d547d2014-09-02 14:45:53 -07005877 mEffectBufferValid = true;
Marco Nelissenac302142014-10-20 13:15:38 -07005878 }
5879
5880 if (mEffectBufferValid) {
Marco Nelissen57088b52014-10-17 16:39:39 -07005881 // as long as there are effects we should clear the effects buffer, to avoid
5882 // passing a non-clean buffer to the effect chain
5883 memset(mEffectBuffer, 0, mEffectBufferSize);
Eric Laurentb62d0362021-10-26 17:40:18 +02005884 if (mType == SPATIALIZER) {
5885 memset(mPostSpatializerBuffer, 0, mPostSpatializerBufferSize);
5886 }
Eric Laurent97d547d2014-09-02 14:45:53 -07005887 }
Andy Hung69aed5f2014-02-25 17:24:40 -08005888 // sink or mix buffer must be cleared if all tracks are connected to an
5889 // effect chain as in this case the mixer will not write to the sink or mix buffer
5890 // and track effects will accumulate into it
Eric Laurent39095982021-08-24 18:29:27 +02005891 // always clear sink buffer for spatializer output as the output of the spatializer
5892 // effect will be accumulated into it
5893 if ((mBytesRemaining == 0) && (((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
5894 (mixedTracks == 0 && fastTracks > 0)) || (mType == SPATIALIZER))) {
Eric Laurent81784c32012-11-19 14:55:58 -08005895 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08005896 if (mMixerBufferValid) {
5897 memset(mMixerBuffer, 0, mMixerBufferSize);
5898 // TODO: In testing, mSinkBuffer below need not be cleared because
5899 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
5900 // after mixing.
5901 //
5902 // To enforce this guarantee:
5903 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
5904 // (mixedTracks == 0 && fastTracks > 0))
5905 // must imply MIXER_TRACKS_READY.
5906 // Later, we may clear buffers regardless, and skip much of this logic.
5907 }
Andy Hung98ef9782014-03-04 14:46:50 -08005908 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07005909 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08005910 }
5911
5912 // if any fast tracks, then status is ready
5913 mMixerStatusIgnoringFastTracks = mixerStatus;
5914 if (fastTracks > 0) {
5915 mixerStatus = MIXER_TRACKS_READY;
5916 }
5917 return mixerStatus;
5918}
5919
Eric Laurentad7dd962016-09-22 12:38:37 -07005920// trackCountForUid_l() must be called with ThreadBase::mLock held
Andy Hung1bc088a2018-02-09 15:57:31 -08005921uint32_t AudioFlinger::PlaybackThread::trackCountForUid_l(uid_t uid) const
Eric Laurentad7dd962016-09-22 12:38:37 -07005922{
5923 uint32_t trackCount = 0;
5924 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hung1f12a8a2016-11-07 16:10:30 -08005925 if (mTracks[i]->uid() == uid) {
Eric Laurentad7dd962016-09-22 12:38:37 -07005926 trackCount++;
5927 }
5928 }
5929 return trackCount;
5930}
5931
Brian Lindahl65e90012022-07-27 18:01:07 +02005932bool AudioFlinger::PlaybackThread::IsTimestampAdvancing::check(AudioStreamOut * output)
ziyangch8f194f12021-12-01 13:48:04 -08005933{
Brian Lindahl65e90012022-07-27 18:01:07 +02005934 // Check the timestamp to see if it's advancing once every 150ms. If we check too frequently, we
5935 // could falsely detect that the frame position has stalled due to underrun because we haven't
5936 // given the Audio HAL enough time to update.
5937 const nsecs_t nowNs = systemTime();
5938 if (nowNs - mPreviousNs < mMinimumTimeBetweenChecksNs) {
5939 return mLatchedValue;
5940 }
5941 mPreviousNs = nowNs;
5942 mLatchedValue = false;
5943 // Determine if the presentation position is still advancing.
ziyangch8f194f12021-12-01 13:48:04 -08005944 uint64_t position = 0;
5945 struct timespec unused;
Brian Lindahl65e90012022-07-27 18:01:07 +02005946 const status_t ret = output->getPresentationPosition(&position, &unused);
ziyangch8f194f12021-12-01 13:48:04 -08005947 if (ret == NO_ERROR) {
Brian Lindahl65e90012022-07-27 18:01:07 +02005948 if (position != mPreviousPosition) {
5949 mPreviousPosition = position;
5950 mLatchedValue = true;
ziyangch8f194f12021-12-01 13:48:04 -08005951 }
5952 }
Brian Lindahl65e90012022-07-27 18:01:07 +02005953 return mLatchedValue;
5954}
5955
5956void AudioFlinger::PlaybackThread::IsTimestampAdvancing::clear()
5957{
5958 mLatchedValue = true;
5959 mPreviousPosition = 0;
5960 mPreviousNs = 0;
ziyangch8f194f12021-12-01 13:48:04 -08005961}
5962
Andy Hung1bc088a2018-02-09 15:57:31 -08005963// isTrackAllowed_l() must be called with ThreadBase::mLock held
5964bool AudioFlinger::MixerThread::isTrackAllowed_l(
5965 audio_channel_mask_t channelMask, audio_format_t format,
5966 audio_session_t sessionId, uid_t uid) const
Eric Laurent81784c32012-11-19 14:55:58 -08005967{
Andy Hung1bc088a2018-02-09 15:57:31 -08005968 if (!PlaybackThread::isTrackAllowed_l(channelMask, format, sessionId, uid)) {
5969 return false;
Eric Laurentad7dd962016-09-22 12:38:37 -07005970 }
Andy Hung1bc088a2018-02-09 15:57:31 -08005971 // Check validity as we don't call AudioMixer::create() here.
Mikhail Naganov7ad7a252019-07-30 14:42:32 -07005972 if (!mAudioMixer->isValidFormat(format)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08005973 ALOGW("%s: invalid format: %#x", __func__, format);
5974 return false;
5975 }
Mikhail Naganov7ad7a252019-07-30 14:42:32 -07005976 if (!mAudioMixer->isValidChannelMask(channelMask)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08005977 ALOGW("%s: invalid channelMask: %#x", __func__, channelMask);
5978 return false;
5979 }
5980 return true;
Eric Laurent81784c32012-11-19 14:55:58 -08005981}
5982
Eric Laurent10351942014-05-08 18:49:52 -07005983// checkForNewParameter_l() must be called with ThreadBase::mLock held
5984bool AudioFlinger::MixerThread::checkForNewParameter_l(const String8& keyValuePair,
5985 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08005986{
Eric Laurent81784c32012-11-19 14:55:58 -08005987 bool reconfig = false;
Eric Laurent10351942014-05-08 18:49:52 -07005988 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08005989
Glenn Kastenc05b8d72016-03-24 09:48:17 -07005990 AutoPark<FastMixer> park(mFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08005991
Eric Laurent10351942014-05-08 18:49:52 -07005992 AudioParameter param = AudioParameter(keyValuePair);
5993 int value;
5994 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
5995 reconfig = true;
5996 }
5997 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07005998 if (!isValidPcmSinkFormat((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07005999 status = BAD_VALUE;
6000 } else {
6001 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08006002 reconfig = true;
6003 }
Eric Laurent10351942014-05-08 18:49:52 -07006004 }
6005 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07006006 if (!isValidPcmSinkChannelMask((audio_channel_mask_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07006007 status = BAD_VALUE;
6008 } else {
6009 // no need to save value, since it's constant
6010 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006011 }
Eric Laurent10351942014-05-08 18:49:52 -07006012 }
6013 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6014 // do not accept frame count changes if tracks are open as the track buffer
6015 // size depends on frame count and correct behavior would not be guaranteed
6016 // if frame count is changed after track creation
6017 if (!mTracks.isEmpty()) {
6018 status = INVALID_OPERATION;
6019 } else {
6020 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006021 }
Eric Laurent10351942014-05-08 18:49:52 -07006022 }
6023 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07006024 LOG_FATAL("Should not set routing device in MixerThread");
Eric Laurent10351942014-05-08 18:49:52 -07006025 }
Eric Laurent81784c32012-11-19 14:55:58 -08006026
Eric Laurent10351942014-05-08 18:49:52 -07006027 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006028 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07006029 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08006030 mOutput->standby();
Andy Hungcf10d742020-04-28 15:38:24 -07006031 if (!mStandby) {
6032 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07006033 mThreadSnapshot.onEnd();
Andy Hungcf10d742020-04-28 15:38:24 -07006034 mStandby = true;
6035 }
Eric Laurent10351942014-05-08 18:49:52 -07006036 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006037 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent81784c32012-11-19 14:55:58 -08006038 }
Eric Laurent10351942014-05-08 18:49:52 -07006039 if (status == NO_ERROR && reconfig) {
6040 readOutputParameters_l();
6041 delete mAudioMixer;
6042 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
Andy Hung1bc088a2018-02-09 15:57:31 -08006043 for (const auto &track : mTracks) {
Andy Hungc0691382018-09-12 18:01:57 -07006044 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08006045 status_t status = mAudioMixer->create(
Andy Hungc0691382018-09-12 18:01:57 -07006046 trackId,
Andy Hung1bc088a2018-02-09 15:57:31 -08006047 track->mChannelMask,
6048 track->mFormat,
6049 track->mSessionId);
6050 ALOGW_IF(status != NO_ERROR,
Andy Hungc0691382018-09-12 18:01:57 -07006051 "%s(): AudioMixer cannot create track(%d)"
6052 " mask %#x, format %#x, sessionId %d",
Andy Hung1bc088a2018-02-09 15:57:31 -08006053 __func__,
Andy Hungc0691382018-09-12 18:01:57 -07006054 trackId, track->mChannelMask, track->mFormat, track->mSessionId);
Eric Laurent10351942014-05-08 18:49:52 -07006055 }
Eric Laurent73e26b62015-04-27 16:55:58 -07006056 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07006057 }
Eric Laurent81784c32012-11-19 14:55:58 -08006058 }
6059
Dean Wheatley68918102021-03-19 22:09:19 +11006060 return reconfig;
Eric Laurent81784c32012-11-19 14:55:58 -08006061}
6062
6063
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07006064void AudioFlinger::MixerThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -08006065{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07006066 PlaybackThread::dumpInternals_l(fd, args);
Andy Hung40eb1a12015-06-18 13:42:02 -07006067 dprintf(fd, " Thread throttle time (msecs): %u\n", mThreadThrottleTimeMs);
Andy Hung8ed196a2018-01-05 13:21:11 -08006068 dprintf(fd, " AudioMixer tracks: %s\n", mAudioMixer->trackNames().c_str());
Andy Hung2ddee192015-12-18 17:34:44 -08006069 dprintf(fd, " Master mono: %s\n", mMasterMono ? "on" : "off");
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006070 dprintf(fd, " Master balance: %f (%s)\n", mMasterBalance.load(),
6071 (hasFastMixer() ? std::to_string(mFastMixer->getMasterBalance())
6072 : mBalance.toString()).c_str());
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006073 if (hasFastMixer()) {
6074 dprintf(fd, " FastMixer thread %p tid=%d", mFastMixer.get(), mFastMixer->getTid());
6075
6076 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
6077 // while we are dumping it. It may be inconsistent, but it won't mutate!
6078 // This is a large object so we place it on the heap.
6079 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
Eric Tan2942a4e2018-09-12 17:41:27 -07006080 const std::unique_ptr<FastMixerDumpState> copy =
6081 std::make_unique<FastMixerDumpState>(mFastMixerDumpState);
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006082 copy->dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08006083
6084#ifdef STATE_QUEUE_DUMP
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006085 // Similar for state queue
6086 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
6087 observerCopy.dump(fd);
6088 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
6089 mutatorCopy.dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08006090#endif
6091
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006092#ifdef AUDIO_WATCHDOG
6093 if (mAudioWatchdog != 0) {
6094 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
6095 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
6096 wdCopy.dump(fd);
6097 }
6098#endif
6099
6100 } else {
6101 dprintf(fd, " No FastMixer\n");
6102 }
Eric Laurent81784c32012-11-19 14:55:58 -08006103}
6104
6105uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
6106{
6107 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
6108}
6109
6110uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
6111{
6112 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
6113}
6114
6115void AudioFlinger::MixerThread::cacheParameters_l()
6116{
6117 PlaybackThread::cacheParameters_l();
6118
6119 // FIXME: Relaxed timing because of a certain device that can't meet latency
6120 // Should be reduced to 2x after the vendor fixes the driver issue
6121 // increase threshold again due to low power audio mode. The way this warning
6122 // threshold is calculated and its usefulness should be reconsidered anyway.
6123 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
6124}
6125
6126// ----------------------------------------------------------------------------
6127
6128AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
jiabinc52b1ff2019-10-31 17:20:42 -07006129 AudioStreamOut* output, audio_io_handle_t id, ThreadBase::type_t type, bool systemReady)
6130 : PlaybackThread(audioFlinger, output, id, type, systemReady)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006131{
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006132 setMasterBalance(audioFlinger->getMasterBalance_l());
Eric Laurentbfb1b832013-01-07 09:53:42 -08006133}
6134
Eric Laurent81784c32012-11-19 14:55:58 -08006135AudioFlinger::DirectOutputThread::~DirectOutputThread()
6136{
6137}
6138
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07006139void AudioFlinger::DirectOutputThread::dumpInternals_l(int fd, const Vector<String16>& args)
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006140{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07006141 PlaybackThread::dumpInternals_l(fd, args);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006142 dprintf(fd, " Master balance: %f Left: %f Right: %f\n",
6143 mMasterBalance.load(), mMasterBalanceLeft, mMasterBalanceRight);
6144}
6145
6146void AudioFlinger::DirectOutputThread::setMasterBalance(float balance)
6147{
6148 Mutex::Autolock _l(mLock);
6149 if (mMasterBalance != balance) {
6150 mMasterBalance.store(balance);
6151 mBalance.computeStereoBalance(balance, &mMasterBalanceLeft, &mMasterBalanceRight);
6152 broadcast_l();
6153 }
6154}
6155
Eric Laurent5850c4c2016-11-10 13:04:31 -08006156void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006157{
Eric Laurentbfb1b832013-01-07 09:53:42 -08006158 float left, right;
6159
Andy Hung333ab962019-05-28 20:23:35 -07006160 // Ensure volumeshaper state always advances even when muted.
6161 const sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
6162 const auto [shaperVolume, shaperActive] = track->getVolumeHandler()->getVolume(
6163 proxy->framesReleased());
6164 mVolumeShaperActive = shaperActive;
6165
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08006166 if (mMasterMute || mStreamTypes[track->streamType()].mute || track->isPlaybackRestricted()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08006167 left = right = 0;
6168 } else {
6169 float typeVolume = mStreamTypes[track->streamType()].volume;
Andy Hung333ab962019-05-28 20:23:35 -07006170 const float v = mMasterVolume * typeVolume * shaperVolume;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08006171
Glenn Kastenc56f3422014-03-21 17:53:17 -07006172 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
6173 left = float_from_gain(gain_minifloat_unpack_left(vlr));
6174 if (left > GAIN_FLOAT_UNITY) {
6175 left = GAIN_FLOAT_UNITY;
6176 }
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006177 left *= v * mMasterBalanceLeft; // DirectOutputThread balance applied as track volume
Glenn Kastenc56f3422014-03-21 17:53:17 -07006178 right = float_from_gain(gain_minifloat_unpack_right(vlr));
6179 if (right > GAIN_FLOAT_UNITY) {
6180 right = GAIN_FLOAT_UNITY;
6181 }
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006182 right *= v * mMasterBalanceRight;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006183 }
6184
Vlad Popae8d99472022-06-30 16:02:48 +02006185 track->processMuteEvent_l(mAudioFlinger->getOrCreateAudioManager(),
6186 /*muteState=*/{mMasterMute,
6187 mStreamTypes[track->streamType()].volume == 0.f,
6188 mStreamTypes[track->streamType()].mute,
6189 track->isPlaybackRestricted()});
6190
Eric Laurentbfb1b832013-01-07 09:53:42 -08006191 if (lastTrack) {
Kevin Rocard12381092018-04-11 09:19:59 -07006192 track->setFinalVolume((left + right) / 2.f);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006193 if (left != mLeftVolFloat || right != mRightVolFloat) {
6194 mLeftVolFloat = left;
6195 mRightVolFloat = right;
6196
Eric Laurentbfb1b832013-01-07 09:53:42 -08006197 // Delegate volume control to effect in track effect chain if needed
6198 // only one effect chain can be present on DirectOutputThread, so if
6199 // there is one, the track is connected to it
6200 if (!mEffectChains.isEmpty()) {
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09006201 // if effect chain exists, volume is handled by it.
6202 // Convert volumes from float to 8.24
6203 uint32_t vl = (uint32_t)(left * (1 << 24));
6204 uint32_t vr = (uint32_t)(right * (1 << 24));
6205 // Direct/Offload effect chains set output volume in setVolume_l().
6206 (void)mEffectChains[0]->setVolume_l(&vl, &vr);
6207 } else {
6208 // otherwise we directly set the volume.
6209 setVolumeForOutput_l(left, right);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006210 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006211 }
6212 }
6213}
6214
Phil Burk43b4dcc2015-06-09 16:53:44 -07006215void AudioFlinger::DirectOutputThread::onAddNewTrack_l()
6216{
6217 sp<Track> previousTrack = mPreviousTrack.promote();
Andy Hungdae27702016-10-31 14:01:16 -07006218 sp<Track> latestTrack = mActiveTracks.getLatest();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006219
Eric Laurent0f0631e2015-07-06 18:01:25 -07006220 if (previousTrack != 0 && latestTrack != 0) {
6221 if (mType == DIRECT) {
6222 if (previousTrack.get() != latestTrack.get()) {
6223 mFlushPending = true;
6224 }
6225 } else /* mType == OFFLOAD */ {
6226 if (previousTrack->sessionId() != latestTrack->sessionId()) {
6227 mFlushPending = true;
6228 }
6229 }
Revathi Uddaraju20413a92016-10-13 17:16:14 +08006230 } else if (previousTrack == 0) {
6231 // there could be an old track added back during track transition for direct
6232 // output, so always issues flush to flush data of the previous track if it
6233 // was already destroyed with HAL paused, then flush can resume the playback
6234 mFlushPending = true;
Phil Burk43b4dcc2015-06-09 16:53:44 -07006235 }
6236 PlaybackThread::onAddNewTrack_l();
6237}
Eric Laurentbfb1b832013-01-07 09:53:42 -08006238
Eric Laurent81784c32012-11-19 14:55:58 -08006239AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
6240 Vector< sp<Track> > *tracksToRemove
6241)
6242{
Eric Laurentd595b7c2013-04-03 17:27:56 -07006243 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08006244 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006245 bool doHwPause = false;
6246 bool doHwResume = false;
Eric Laurent81784c32012-11-19 14:55:58 -08006247
6248 // find out which tracks need to be processed
Andy Hungdae27702016-10-31 14:01:16 -07006249 for (const sp<Track> &t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08006250 if (t->isInvalid()) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07006251 ALOGW("An invalidated track shouldn't be in active list");
Eric Laurent5850c4c2016-11-10 13:04:31 -08006252 tracksToRemove->add(t);
Phil Burk43b4dcc2015-06-09 16:53:44 -07006253 continue;
6254 }
6255
Eric Laurent5850c4c2016-11-10 13:04:31 -08006256 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006257#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurent81784c32012-11-19 14:55:58 -08006258 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006259#endif
Eric Laurentfd477972013-10-25 18:10:40 -07006260 // Only consider last track started for volume and mixer state control.
6261 // In theory an older track could underrun and restart after the new one starts
6262 // but as we only care about the transition phase between two tracks on a
6263 // direct output, it is not a problem to ignore the underrun case.
Andy Hungdae27702016-10-31 14:01:16 -07006264 sp<Track> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08006265 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08006266
Kuowei Li23666472021-01-20 10:23:25 +08006267 if (track->isPausePending()) {
6268 track->pauseAck();
6269 // It is possible a track might have been flushed or stopped.
6270 // Other operations such as flush pending might occur on the next prepare.
6271 if (track->isPausing()) {
6272 track->setPaused();
6273 }
6274 // Always perform pause, as an immediate flush will change
6275 // the pause state to be no longer isPausing().
Phil Burk6fc2a7c2015-04-30 16:08:10 -07006276 if (mHwSupportsPause && last && !mHwPaused) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006277 doHwPause = true;
6278 mHwPaused = true;
6279 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08006280 } else if (track->isFlushPending()) {
6281 track->flushAck();
6282 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07006283 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006284 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07006285 } else if (track->isResumePending()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006286 track->resumeAck();
Eric Laurent3df841a2016-07-15 15:15:40 -07006287 if (last) {
6288 mLeftVolFloat = mRightVolFloat = -1.0;
6289 if (mHwPaused) {
6290 doHwResume = true;
6291 mHwPaused = false;
6292 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08006293 }
6294 }
6295
Eric Laurent81784c32012-11-19 14:55:58 -08006296 // The first time a track is added we wait
Phil Burk99adee32014-12-10 16:46:30 -08006297 // for all its buffers to be filled before processing it.
6298 // Allow draining the buffer in case the client
6299 // app does not call stop() and relies on underrun to stop:
6300 // hence the test on (track->mRetryCount > 1).
Andy Hung455982f2021-04-27 17:46:12 -07006301 // If track->mRetryCount <= 1 then track is about to be disabled, paused, removed,
6302 // so we accept any nonzero amount of data delivered by the AudioTrack (which will
6303 // reset the retry counter).
Phil Burkca5e6142015-07-14 09:42:29 -07006304 // Do not use a high threshold for compressed audio.
Andy Hung455982f2021-04-27 17:46:12 -07006305
6306 // target retry count that we will use is based on the time we wait for retries.
6307 const int32_t targetRetryCount = kMaxTrackRetriesDirectMs * 1000 / mActiveSleepTimeUs;
6308 // the retry threshold is when we accept any size for PCM data. This is slightly
6309 // smaller than the retry count so we can push small bits of data without a glitch.
6310 const int32_t retryThreshold = targetRetryCount > 2 ? targetRetryCount - 1 : 1;
Eric Laurent81784c32012-11-19 14:55:58 -08006311 uint32_t minFrames;
Phil Burk99adee32014-12-10 16:46:30 -08006312 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
Andy Hung455982f2021-04-27 17:46:12 -07006313 && (track->mRetryCount > retryThreshold) && audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006314 minFrames = mNormalFrameCount;
6315 } else {
6316 minFrames = 1;
6317 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006318
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07006319 const size_t framesReady = track->framesReady();
6320 const int trackId = track->id();
6321 if (ATRACE_ENABLED()) {
6322 std::string traceName("nRdy");
6323 traceName += std::to_string(trackId);
6324 ATRACE_INT(traceName.c_str(), framesReady);
6325 }
6326 if ((framesReady >= minFrames) && track->isReady() && !track->isPaused() &&
Eric Laurentab5cdba2014-06-09 17:22:27 -07006327 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08006328 {
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07006329 ALOGVV("track(%d) s=%08x [OK]", trackId, cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08006330
6331 if (track->mFillingUpStatus == Track::FS_FILLED) {
6332 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07006333 if (last) {
6334 // make sure processVolume_l() will apply new volume even if 0
6335 mLeftVolFloat = mRightVolFloat = -1.0;
6336 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08006337 if (!mHwSupportsPause) {
6338 track->resumeAck();
Eric Laurent81784c32012-11-19 14:55:58 -08006339 }
6340 }
6341
6342 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08006343 processVolume_l(track, last);
6344 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07006345 sp<Track> previousTrack = mPreviousTrack.promote();
6346 if (previousTrack != 0) {
6347 if (track != previousTrack.get()) {
6348 // Flush any data still being written from last track
6349 mBytesRemaining = 0;
Eric Laurent0f0631e2015-07-06 18:01:25 -07006350 // Invalidate previous track to force a seek when resuming.
6351 previousTrack->invalidate();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006352 }
6353 }
6354 mPreviousTrack = track;
6355
Eric Laurentd595b7c2013-04-03 17:27:56 -07006356 // reset retry count
Andy Hung455982f2021-04-27 17:46:12 -07006357 track->mRetryCount = targetRetryCount;
Eric Laurent5850c4c2016-11-10 13:04:31 -08006358 mActiveTrack = t;
Eric Laurentd595b7c2013-04-03 17:27:56 -07006359 mixerStatus = MIXER_TRACKS_READY;
Eric Laurent5cff4032015-05-26 13:49:58 -07006360 if (mHwPaused) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08006361 doHwResume = true;
6362 mHwPaused = false;
6363 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07006364 }
Eric Laurent81784c32012-11-19 14:55:58 -08006365 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07006366 // clear effect chain input buffer if the last active track started underruns
6367 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07006368 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08006369 mEffectChains[0]->clearInputBuffer();
6370 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07006371 if (track->isStopping_1()) {
6372 track->mState = TrackBase::STOPPING_2;
Eric Laurentb369caf2015-03-30 20:51:47 -07006373 if (last && mHwPaused) {
6374 doHwResume = true;
6375 mHwPaused = false;
6376 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07006377 }
6378 if ((track->sharedBuffer() != 0) || track->isStopped() ||
6379 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08006380 // We have consumed all the buffers of this track.
6381 // Remove it from the list of active tracks.
Atneya Nair0cae0432022-05-10 18:12:12 -04006382 bool presComplete = false;
Eric Laurentfd477972013-10-25 18:10:40 -07006383 if (mStandby || !last ||
Atneya Nair0cae0432022-05-10 18:12:12 -04006384 (presComplete = track->presentationComplete(latency_l())) ||
Jindong32dc26e2019-11-11 18:10:01 +08006385 track->isPaused() || mHwPaused) {
Atneya Nair0cae0432022-05-10 18:12:12 -04006386 if (presComplete) {
6387 mOutput->presentationComplete();
6388 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07006389 if (track->isStopping_2()) {
6390 track->mState = TrackBase::STOPPED;
6391 }
Eric Laurent81784c32012-11-19 14:55:58 -08006392 if (track->isStopped()) {
6393 track->reset();
6394 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07006395 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08006396 }
6397 } else {
6398 // No buffers for this track. Give it a few chances to
6399 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07006400 // Only consider last track started for mixer state control
Brian Lindahl65e90012022-07-27 18:01:07 +02006401 bool isTimestampAdvancing = mIsTimestampAdvancing.check(mOutput);
Eric Laurent81784c32012-11-19 14:55:58 -08006402 if (--(track->mRetryCount) <= 0) {
Brian Lindahl65e90012022-07-27 18:01:07 +02006403 if (isTimestampAdvancing) { // HAL is still playing audio, give us more time.
ziyangch8f194f12021-12-01 13:48:04 -08006404 track->mRetryCount = kMaxTrackRetriesOffload;
6405 } else {
6406 ALOGV("BUFFER TIMEOUT: remove track(%d) from active list", trackId);
6407 tracksToRemove->add(track);
6408 // indicate to client process that the track was disabled because of
6409 // underrun; it will then automatically call start() when data is available
6410 track->disable();
6411 // only do hw pause when track is going to be removed due to BUFFER TIMEOUT.
6412 // unlike mixerthread, HAL can be paused for direct output
6413 ALOGW("pause because of UNDERRUN, framesReady = %zu,"
6414 "minFrames = %u, mFormat = %#x",
6415 framesReady, minFrames, mFormat);
6416 if (last && mHwSupportsPause && !mHwPaused && !mStandby) {
6417 doHwPause = true;
6418 mHwPaused = true;
6419 }
Eric Laurent0f7b5f22014-12-19 10:43:21 -08006420 }
Haynes Mathew George5c6daae2017-01-24 20:06:05 -08006421 } else if (last) {
6422 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurent81784c32012-11-19 14:55:58 -08006423 }
6424 }
6425 }
6426 }
6427
Eric Laurentd1f69b02014-12-15 14:33:13 -08006428 // if an active track did not command a flush, check for pending flush on stopped tracks
Phil Burk43b4dcc2015-06-09 16:53:44 -07006429 if (!mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006430 for (size_t i = 0; i < mTracks.size(); i++) {
6431 if (mTracks[i]->isFlushPending()) {
6432 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006433 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006434 }
6435 }
6436 }
6437
6438 // make sure the pause/flush/resume sequence is executed in the right order.
6439 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
6440 // before flush and then resume HW. This can happen in case of pause/flush/resume
6441 // if resume is received before pause is executed.
6442 if (mHwSupportsPause && !mStandby &&
Phil Burk43b4dcc2015-06-09 16:53:44 -07006443 (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006444 status_t result = mOutput->stream->pause();
6445 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08006446 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07006447 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006448 flushHw_l();
6449 }
6450 if (mHwSupportsPause && !mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006451 status_t result = mOutput->stream->resume();
6452 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08006453 }
Eric Laurent81784c32012-11-19 14:55:58 -08006454 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08006455 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08006456
6457 return mixerStatus;
6458}
6459
6460void AudioFlinger::DirectOutputThread::threadLoop_mix()
6461{
Eric Laurent81784c32012-11-19 14:55:58 -08006462 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08006463 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08006464 // output audio to hardware
6465 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07006466 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08006467 buffer.frameCount = frameCount;
Phil Burk062e67a2015-02-11 13:40:50 -08006468 status_t status = mActiveTrack->getNextBuffer(&buffer);
6469 if (status != NO_ERROR || buffer.raw == NULL) {
Eric Laurent51716182016-02-29 18:00:56 -08006470 // no need to pad with 0 for compressed audio
6471 if (audio_has_proportional_frames(mFormat)) {
6472 memset(curBuf, 0, frameCount * mFrameSize);
6473 }
Eric Laurent81784c32012-11-19 14:55:58 -08006474 break;
6475 }
6476 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
6477 frameCount -= buffer.frameCount;
6478 curBuf += buffer.frameCount * mFrameSize;
6479 mActiveTrack->releaseBuffer(&buffer);
6480 }
Andy Hung2098f272014-02-27 14:00:06 -08006481 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006482 mSleepTimeUs = 0;
6483 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08006484 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08006485}
6486
6487void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
6488{
Eric Laurentd1f69b02014-12-15 14:33:13 -08006489 // do not write to HAL when paused
Eric Laurent0f7b5f22014-12-19 10:43:21 -08006490 if (mHwPaused || (usesHwAvSync() && mStandby)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006491 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006492 return;
6493 }
Andy Hung85ba3332021-04-27 17:40:26 -07006494 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
6495 mSleepTimeUs = mActiveSleepTimeUs;
6496 } else {
6497 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006498 }
Andy Hung85ba3332021-04-27 17:40:26 -07006499 // Note: In S or later, we do not write zeroes for
6500 // linear or proportional PCM direct tracks in underrun.
Eric Laurent81784c32012-11-19 14:55:58 -08006501}
6502
Eric Laurentd1f69b02014-12-15 14:33:13 -08006503void AudioFlinger::DirectOutputThread::threadLoop_exit()
6504{
6505 {
6506 Mutex::Autolock _l(mLock);
Eric Laurentd1f69b02014-12-15 14:33:13 -08006507 for (size_t i = 0; i < mTracks.size(); i++) {
6508 if (mTracks[i]->isFlushPending()) {
6509 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006510 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006511 }
6512 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07006513 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006514 flushHw_l();
6515 }
6516 }
6517 PlaybackThread::threadLoop_exit();
6518}
6519
6520// must be called with thread mutex locked
6521bool AudioFlinger::DirectOutputThread::shouldStandby_l()
6522{
6523 bool trackPaused = false;
Eric Laurentb369caf2015-03-30 20:51:47 -07006524 bool trackStopped = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006525
6526 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
6527 // after a timeout and we will enter standby then.
6528 if (mTracks.size() > 0) {
6529 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
Eric Laurentb369caf2015-03-30 20:51:47 -07006530 trackStopped = mTracks[mTracks.size() - 1]->isStopped() ||
6531 mTracks[mTracks.size() - 1]->mState == TrackBase::IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006532 }
6533
Eric Laurent5cff4032015-05-26 13:49:58 -07006534 return !mStandby && !(trackPaused || (mHwPaused && !trackStopped));
Eric Laurentd1f69b02014-12-15 14:33:13 -08006535}
6536
Eric Laurent10351942014-05-08 18:49:52 -07006537// checkForNewParameter_l() must be called with ThreadBase::mLock held
6538bool AudioFlinger::DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
6539 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08006540{
6541 bool reconfig = false;
Eric Laurent10351942014-05-08 18:49:52 -07006542 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006543
Eric Laurent10351942014-05-08 18:49:52 -07006544 AudioParameter param = AudioParameter(keyValuePair);
6545 int value;
6546 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07006547 LOG_FATAL("Should not set routing device in DirectOutputThread");
Eric Laurent81784c32012-11-19 14:55:58 -08006548 }
Eric Laurent10351942014-05-08 18:49:52 -07006549 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6550 // do not accept frame count changes if tracks are open as the track buffer
6551 // size depends on frame count and correct behavior would not be garantied
6552 // if frame count is changed after track creation
6553 if (!mTracks.isEmpty()) {
6554 status = INVALID_OPERATION;
6555 } else {
6556 reconfig = true;
6557 }
6558 }
6559 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006560 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07006561 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08006562 mOutput->standby();
Andy Hungcf10d742020-04-28 15:38:24 -07006563 if (!mStandby) {
6564 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07006565 mThreadSnapshot.onEnd();
Andy Hungcf10d742020-04-28 15:38:24 -07006566 mStandby = true;
6567 }
Eric Laurent10351942014-05-08 18:49:52 -07006568 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006569 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07006570 }
6571 if (status == NO_ERROR && reconfig) {
6572 readOutputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07006573 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07006574 }
6575 }
6576
Dean Wheatley68918102021-03-19 22:09:19 +11006577 return reconfig;
Eric Laurent81784c32012-11-19 14:55:58 -08006578}
6579
6580uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
6581{
6582 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08006583 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006584 time = PlaybackThread::activeSleepTimeUs();
6585 } else {
Eric Laurent51716182016-02-29 18:00:56 -08006586 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006587 }
6588 return time;
6589}
6590
6591uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
6592{
6593 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08006594 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006595 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
6596 } else {
Eric Laurent51716182016-02-29 18:00:56 -08006597 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006598 }
6599 return time;
6600}
6601
6602uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
6603{
6604 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08006605 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006606 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
6607 } else {
Eric Laurent51716182016-02-29 18:00:56 -08006608 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006609 }
6610 return time;
6611}
6612
6613void AudioFlinger::DirectOutputThread::cacheParameters_l()
6614{
6615 PlaybackThread::cacheParameters_l();
6616
6617 // use shorter standby delay as on normal output to release
6618 // hardware resources as soon as possible
Eric Laurentb369caf2015-03-30 20:51:47 -07006619 // no delay on outputs with HW A/V sync
6620 if (usesHwAvSync()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006621 mStandbyDelayNs = 0;
Phil Burkfdb3c072016-02-09 10:47:02 -08006622 } else if ((mType == OFFLOAD) && !audio_has_proportional_frames(mFormat)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006623 mStandbyDelayNs = kOffloadStandbyDelayNs;
Eric Laurent5cff4032015-05-26 13:49:58 -07006624 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006625 mStandbyDelayNs = microseconds(mActiveSleepTimeUs*2);
Eric Laurent972a1732013-09-04 09:42:59 -07006626 }
Eric Laurent81784c32012-11-19 14:55:58 -08006627}
6628
Eric Laurente659ef42014-09-29 13:06:46 -07006629void AudioFlinger::DirectOutputThread::flushHw_l()
6630{
ziyangch8f194f12021-12-01 13:48:04 -08006631 PlaybackThread::flushHw_l();
Phil Burk062e67a2015-02-11 13:40:50 -08006632 mOutput->flush();
Eric Laurentd1f69b02014-12-15 14:33:13 -08006633 mHwPaused = false;
Phil Burk43b4dcc2015-06-09 16:53:44 -07006634 mFlushPending = false;
Dean Wheatley12473e92021-03-18 23:00:55 +11006635 mTimestampVerifier.discontinuity(discontinuityForStandbyOrFlush());
Sampath Shetty999f0e82020-01-15 10:19:06 +11006636 mTimestamp.clear();
Eric Laurente659ef42014-09-29 13:06:46 -07006637}
6638
Andy Hung10cbff12017-02-21 17:30:14 -08006639int64_t AudioFlinger::DirectOutputThread::computeWaitTimeNs_l() const {
6640 // If a VolumeShaper is active, we must wake up periodically to update volume.
6641 const int64_t NS_PER_MS = 1000000;
6642 return mVolumeShaperActive ?
6643 kMinNormalSinkBufferSizeMs * NS_PER_MS : PlaybackThread::computeWaitTimeNs_l();
6644}
6645
Eric Laurent81784c32012-11-19 14:55:58 -08006646// ----------------------------------------------------------------------------
6647
Eric Laurentbfb1b832013-01-07 09:53:42 -08006648AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
Eric Laurent4de95592013-09-26 15:28:21 -07006649 const wp<AudioFlinger::PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006650 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07006651 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07006652 mWriteAckSequence(0),
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006653 mDrainSequence(0),
6654 mAsyncError(false)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006655{
6656}
6657
6658AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
6659{
6660}
6661
6662void AudioFlinger::AsyncCallbackThread::onFirstRef()
6663{
6664 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
6665}
6666
6667bool AudioFlinger::AsyncCallbackThread::threadLoop()
6668{
6669 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07006670 uint32_t writeAckSequence;
6671 uint32_t drainSequence;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006672 bool asyncError;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006673
6674 {
6675 Mutex::Autolock _l(mLock);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08006676 while (!((mWriteAckSequence & 1) ||
6677 (mDrainSequence & 1) ||
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006678 mAsyncError ||
Haynes Mathew George24a325d2013-12-03 21:26:02 -08006679 exitPending())) {
6680 mWaitWorkCV.wait(mLock);
6681 }
6682
Eric Laurentbfb1b832013-01-07 09:53:42 -08006683 if (exitPending()) {
6684 break;
6685 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07006686 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
6687 mWriteAckSequence, mDrainSequence);
6688 writeAckSequence = mWriteAckSequence;
6689 mWriteAckSequence &= ~1;
6690 drainSequence = mDrainSequence;
6691 mDrainSequence &= ~1;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006692 asyncError = mAsyncError;
6693 mAsyncError = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006694 }
6695 {
Eric Laurent4de95592013-09-26 15:28:21 -07006696 sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
6697 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07006698 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07006699 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006700 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07006701 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07006702 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006703 }
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006704 if (asyncError) {
6705 playbackThread->onAsyncError();
6706 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006707 }
6708 }
6709 }
6710 return false;
6711}
6712
6713void AudioFlinger::AsyncCallbackThread::exit()
6714{
6715 ALOGV("AsyncCallbackThread::exit");
6716 Mutex::Autolock _l(mLock);
6717 requestExit();
6718 mWaitWorkCV.broadcast();
6719}
6720
Eric Laurent3b4529e2013-09-05 18:09:19 -07006721void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006722{
6723 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07006724 // bit 0 is cleared
6725 mWriteAckSequence = sequence << 1;
6726}
6727
6728void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
6729{
6730 Mutex::Autolock _l(mLock);
6731 // ignore unexpected callbacks
6732 if (mWriteAckSequence & 2) {
6733 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006734 mWaitWorkCV.signal();
6735 }
6736}
6737
Eric Laurent3b4529e2013-09-05 18:09:19 -07006738void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006739{
6740 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07006741 // bit 0 is cleared
6742 mDrainSequence = sequence << 1;
6743}
6744
6745void AudioFlinger::AsyncCallbackThread::resetDraining()
6746{
6747 Mutex::Autolock _l(mLock);
6748 // ignore unexpected callbacks
6749 if (mDrainSequence & 2) {
6750 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006751 mWaitWorkCV.signal();
6752 }
6753}
6754
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006755void AudioFlinger::AsyncCallbackThread::setAsyncError()
6756{
6757 Mutex::Autolock _l(mLock);
6758 mAsyncError = true;
6759 mWaitWorkCV.signal();
6760}
6761
Eric Laurentbfb1b832013-01-07 09:53:42 -08006762
6763// ----------------------------------------------------------------------------
6764AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
jiabinc52b1ff2019-10-31 17:20:42 -07006765 AudioStreamOut* output, audio_io_handle_t id, bool systemReady)
6766 : DirectOutputThread(audioFlinger, output, id, OFFLOAD, systemReady),
ziyangch8f194f12021-12-01 13:48:04 -08006767 mPausedWriteLength(0), mPausedBytesRemaining(0), mKeepWakeLock(true)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006768{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07006769 //FIXME: mStandby should be set to true by ThreadBase constructo
Eric Laurentfd477972013-10-25 18:10:40 -07006770 mStandby = true;
Eric Laurent64667972016-03-30 18:19:46 -07006771 mKeepWakeLock = property_get_bool("ro.audio.offload_wakelock", true /* default_value */);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006772}
6773
Eric Laurentbfb1b832013-01-07 09:53:42 -08006774void AudioFlinger::OffloadThread::threadLoop_exit()
6775{
6776 if (mFlushPending || mHwPaused) {
6777 // If a flush is pending or track was paused, just discard buffered data
6778 flushHw_l();
6779 } else {
6780 mMixerStatus = MIXER_DRAIN_ALL;
6781 threadLoop_drain();
6782 }
Uday Gupta56604aa2014-05-13 11:19:17 -07006783 if (mUseAsyncWrite) {
6784 ALOG_ASSERT(mCallbackThread != 0);
6785 mCallbackThread->exit();
6786 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006787 PlaybackThread::threadLoop_exit();
6788}
6789
6790AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
6791 Vector< sp<Track> > *tracksToRemove
6792)
6793{
Eric Laurentbfb1b832013-01-07 09:53:42 -08006794 size_t count = mActiveTracks.size();
6795
6796 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07006797 bool doHwPause = false;
6798 bool doHwResume = false;
6799
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006800 ALOGV("OffloadThread::prepareTracks_l active tracks %zu", count);
Eric Laurentede6c3b2013-09-19 14:37:46 -07006801
Eric Laurentbfb1b832013-01-07 09:53:42 -08006802 // find out which tracks need to be processed
Andy Hungdae27702016-10-31 14:01:16 -07006803 for (const sp<Track> &t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08006804 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006805#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurentbfb1b832013-01-07 09:53:42 -08006806 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006807#endif
Eric Laurentfd477972013-10-25 18:10:40 -07006808 // Only consider last track started for volume and mixer state control.
6809 // In theory an older track could underrun and restart after the new one starts
6810 // but as we only care about the transition phase between two tracks on a
6811 // direct output, it is not a problem to ignore the underrun case.
Andy Hungdae27702016-10-31 14:01:16 -07006812 sp<Track> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08006813 bool last = l.get() == track;
Eric Laurentfd477972013-10-25 18:10:40 -07006814
Haynes Mathew George7844f672014-01-15 12:32:55 -08006815 if (track->isInvalid()) {
6816 ALOGW("An invalidated track shouldn't be in active list");
6817 tracksToRemove->add(track);
6818 continue;
6819 }
6820
6821 if (track->mState == TrackBase::IDLE) {
6822 ALOGW("An idle track shouldn't be in active list");
6823 continue;
6824 }
6825
Kuowei Li23666472021-01-20 10:23:25 +08006826 if (track->isPausePending()) {
6827 track->pauseAck();
6828 // It is possible a track might have been flushed or stopped.
6829 // Other operations such as flush pending might occur on the next prepare.
6830 if (track->isPausing()) {
6831 track->setPaused();
6832 }
6833 // Always perform pause if last, as an immediate flush will change
6834 // the pause state to be no longer isPausing().
Eric Laurentbfb1b832013-01-07 09:53:42 -08006835 if (last) {
Eric Laurent5cff4032015-05-26 13:49:58 -07006836 if (mHwSupportsPause && !mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07006837 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006838 mHwPaused = true;
6839 }
6840 // If we were part way through writing the mixbuffer to
6841 // the HAL we must save this until we resume
6842 // BUG - this will be wrong if a different track is made active,
6843 // in that case we want to discard the pending data in the
6844 // mixbuffer and tell the client to present it again when the
6845 // track is resumed
6846 mPausedWriteLength = mCurrentWriteLength;
6847 mPausedBytesRemaining = mBytesRemaining;
6848 mBytesRemaining = 0; // stop writing
6849 }
6850 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08006851 } else if (track->isFlushPending()) {
Eric Laurente93cc032016-05-05 10:15:10 -07006852 if (track->isStopping_1()) {
6853 track->mRetryCount = kMaxTrackStopRetriesOffload;
6854 } else {
6855 track->mRetryCount = kMaxTrackRetriesOffload;
6856 }
Haynes Mathew George7844f672014-01-15 12:32:55 -08006857 track->flushAck();
6858 if (last) {
6859 mFlushPending = true;
6860 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08006861 } else if (track->isResumePending()){
6862 track->resumeAck();
6863 if (last) {
6864 if (mPausedBytesRemaining) {
6865 // Need to continue write that was interrupted
6866 mCurrentWriteLength = mPausedWriteLength;
6867 mBytesRemaining = mPausedBytesRemaining;
6868 mPausedBytesRemaining = 0;
6869 }
6870 if (mHwPaused) {
6871 doHwResume = true;
6872 mHwPaused = false;
6873 // threadLoop_mix() will handle the case that we need to
6874 // resume an interrupted write
6875 }
6876 // enable write to audio HAL
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006877 mSleepTimeUs = 0;
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08006878
Eric Laurent3df841a2016-07-15 15:15:40 -07006879 mLeftVolFloat = mRightVolFloat = -1.0;
6880
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08006881 // Do not handle new data in this iteration even if track->framesReady()
6882 mixerStatus = MIXER_TRACKS_ENABLED;
6883 }
6884 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07006885 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Andy Hungc0691382018-09-12 18:01:57 -07006886 ALOGVV("OffloadThread: track(%d) s=%08x [OK]", track->id(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006887 if (track->mFillingUpStatus == Track::FS_FILLED) {
6888 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07006889 if (last) {
6890 // make sure processVolume_l() will apply new volume even if 0
6891 mLeftVolFloat = mRightVolFloat = -1.0;
6892 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006893 }
6894
6895 if (last) {
Eric Laurentd7e59222013-11-15 12:02:28 -08006896 sp<Track> previousTrack = mPreviousTrack.promote();
6897 if (previousTrack != 0) {
6898 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08006899 // Flush any data still being written from last track
6900 mBytesRemaining = 0;
6901 if (mPausedBytesRemaining) {
6902 // Last track was paused so we also need to flush saved
6903 // mixbuffer state and invalidate track so that it will
6904 // re-submit that unwritten data when it is next resumed
6905 mPausedBytesRemaining = 0;
6906 // Invalidate is a bit drastic - would be more efficient
6907 // to have a flag to tell client that some of the
6908 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08006909 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08006910 }
6911 // flush data already sent to the DSP if changing audio session as audio
6912 // comes from a different source. Also invalidate previous track to force a
6913 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08006914 if (previousTrack->sessionId() != track->sessionId()) {
6915 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08006916 }
6917 }
6918 }
6919 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006920 // reset retry count
Eric Laurente93cc032016-05-05 10:15:10 -07006921 if (track->isStopping_1()) {
6922 track->mRetryCount = kMaxTrackStopRetriesOffload;
6923 } else {
6924 track->mRetryCount = kMaxTrackRetriesOffload;
6925 }
Eric Laurent5850c4c2016-11-10 13:04:31 -08006926 mActiveTrack = t;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006927 mixerStatus = MIXER_TRACKS_READY;
6928 }
6929 } else {
Andy Hungc0691382018-09-12 18:01:57 -07006930 ALOGVV("OffloadThread: track(%d) s=%08x [NOT READY]", track->id(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006931 if (track->isStopping_1()) {
Eric Laurente93cc032016-05-05 10:15:10 -07006932 if (--(track->mRetryCount) <= 0) {
6933 // Hardware buffer can hold a large amount of audio so we must
6934 // wait for all current track's data to drain before we say
6935 // that the track is stopped.
6936 if (mBytesRemaining == 0) {
6937 // Only start draining when all data in mixbuffer
6938 // has been written
6939 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
6940 track->mState = TrackBase::STOPPING_2; // so presentation completes after
6941 // drain do not drain if no data was ever sent to HAL (mStandby == true)
6942 if (last && !mStandby) {
6943 // do not modify drain sequence if we are already draining. This happens
6944 // when resuming from pause after drain.
6945 if ((mDrainSequence & 1) == 0) {
6946 mSleepTimeUs = 0;
6947 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
6948 mixerStatus = MIXER_DRAIN_TRACK;
6949 mDrainSequence += 2;
6950 }
6951 if (mHwPaused) {
6952 // It is possible to move from PAUSED to STOPPING_1 without
6953 // a resume so we must ensure hardware is running
6954 doHwResume = true;
6955 mHwPaused = false;
6956 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006957 }
6958 }
Eric Laurente93cc032016-05-05 10:15:10 -07006959 } else if (last) {
6960 ALOGV("stopping1 underrun retries left %d", track->mRetryCount);
6961 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006962 }
6963 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07006964 // Drain has completed or we are in standby, signal presentation complete
6965 if (!(mDrainSequence & 1) || !last || mStandby) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08006966 track->mState = TrackBase::STOPPED;
Atneya Nair0cae0432022-05-10 18:12:12 -04006967 mOutput->presentationComplete();
6968 track->presentationComplete(latency_l()); // always returns true
Eric Laurentbfb1b832013-01-07 09:53:42 -08006969 track->reset();
6970 tracksToRemove->add(track);
Dean Wheatley12473e92021-03-18 23:00:55 +11006971 // OFFLOADED stop resets frame counts.
Andy Hungf3234512018-07-03 14:51:47 -07006972 if (!mUseAsyncWrite) {
6973 // If we don't get explicit drain notification we must
6974 // register discontinuity regardless of whether this is
6975 // the previous (!last) or the upcoming (last) track
6976 // to avoid skipping the discontinuity.
Dean Wheatley12473e92021-03-18 23:00:55 +11006977 mTimestampVerifier.discontinuity(
6978 mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Andy Hungf3234512018-07-03 14:51:47 -07006979 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006980 }
6981 } else {
6982 // No buffers for this track. Give it a few chances to
6983 // fill a buffer, then remove it from active list.
Brian Lindahl65e90012022-07-27 18:01:07 +02006984 bool isTimestampAdvancing = mIsTimestampAdvancing.check(mOutput);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006985 if (--(track->mRetryCount) <= 0) {
Brian Lindahl65e90012022-07-27 18:01:07 +02006986 if (isTimestampAdvancing) { // HAL is still playing audio, give us more time.
Andy Hungf8044752016-07-27 14:58:11 -07006987 track->mRetryCount = kMaxTrackRetriesOffload;
6988 } else {
Andy Hungc0691382018-09-12 18:01:57 -07006989 ALOGV("OffloadThread: BUFFER TIMEOUT: remove track(%d) from active list",
6990 track->id());
Andy Hungf8044752016-07-27 14:58:11 -07006991 tracksToRemove->add(track);
Glenn Kastend3bb6452016-12-05 18:14:37 -08006992 // tell client process that the track was disabled because of underrun;
Andy Hungf8044752016-07-27 14:58:11 -07006993 // it will then automatically call start() when data is available
6994 track->disable();
6995 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006996 } else if (last){
6997 mixerStatus = MIXER_TRACKS_ENABLED;
6998 }
6999 }
7000 }
7001 // compute volume for this track
Wenfeng Sun79458332019-05-29 20:12:43 +08007002 if (track->isReady()) { // check ready to prevent premature start.
7003 processVolume_l(track, last);
7004 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007005 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007006
Eric Laurentea0fade2013-10-04 16:23:48 -07007007 // make sure the pause/flush/resume sequence is executed in the right order.
7008 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
7009 // before flush and then resume HW. This can happen in case of pause/flush/resume
7010 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07007011 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007012 status_t result = mOutput->stream->pause();
7013 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07007014 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007015 if (mFlushPending) {
7016 flushHw_l();
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007017 }
Eric Laurentfd477972013-10-25 18:10:40 -07007018 if (!mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007019 status_t result = mOutput->stream->resume();
7020 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07007021 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007022
Eric Laurentbfb1b832013-01-07 09:53:42 -08007023 // remove all the tracks that need to be...
7024 removeTracks_l(*tracksToRemove);
7025
7026 return mixerStatus;
7027}
7028
Eric Laurentbfb1b832013-01-07 09:53:42 -08007029// must be called with thread mutex locked
7030bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
7031{
Eric Laurent3b4529e2013-09-05 18:09:19 -07007032 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
7033 mWriteAckSequence, mDrainSequence);
7034 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08007035 return true;
7036 }
7037 return false;
7038}
7039
Eric Laurentbfb1b832013-01-07 09:53:42 -08007040bool AudioFlinger::OffloadThread::waitingAsyncCallback()
7041{
7042 Mutex::Autolock _l(mLock);
7043 return waitingAsyncCallback_l();
7044}
7045
7046void AudioFlinger::OffloadThread::flushHw_l()
7047{
Eric Laurente659ef42014-09-29 13:06:46 -07007048 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08007049 // Flush anything still waiting in the mixbuffer
7050 mCurrentWriteLength = 0;
7051 mBytesRemaining = 0;
7052 mPausedWriteLength = 0;
7053 mPausedBytesRemaining = 0;
Eric Laurent3eaf66b2016-04-01 14:44:17 -07007054 // reset bytes written count to reflect that DSP buffers are empty after flush.
7055 mBytesWritten = 0;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08007056
Eric Laurentbfb1b832013-01-07 09:53:42 -08007057 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07007058 // discard any pending drain or write ack by incrementing sequence
7059 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
7060 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007061 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07007062 mCallbackThread->setWriteBlocked(mWriteAckSequence);
7063 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007064 }
7065}
7066
Haynes Mathew George05317d22016-05-03 16:34:26 -07007067void AudioFlinger::OffloadThread::invalidateTracks(audio_stream_type_t streamType)
7068{
7069 Mutex::Autolock _l(mLock);
Eric Laurent13084622016-05-17 10:51:49 -07007070 if (PlaybackThread::invalidateTracks_l(streamType)) {
7071 mFlushPending = true;
7072 }
Haynes Mathew George05317d22016-05-03 16:34:26 -07007073}
7074
Eric Laurentbfb1b832013-01-07 09:53:42 -08007075// ----------------------------------------------------------------------------
7076
Eric Laurent81784c32012-11-19 14:55:58 -08007077AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurent72e3f392015-05-20 14:43:50 -07007078 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id, bool systemReady)
jiabinc52b1ff2019-10-31 17:20:42 -07007079 : MixerThread(audioFlinger, mainThread->getOutput(), id,
Eric Laurent72e3f392015-05-20 14:43:50 -07007080 systemReady, DUPLICATING),
Eric Laurent81784c32012-11-19 14:55:58 -08007081 mWaitTimeMs(UINT_MAX)
7082{
7083 addOutputTrack(mainThread);
7084}
7085
7086AudioFlinger::DuplicatingThread::~DuplicatingThread()
7087{
7088 for (size_t i = 0; i < mOutputTracks.size(); i++) {
7089 mOutputTracks[i]->destroy();
7090 }
7091}
7092
7093void AudioFlinger::DuplicatingThread::threadLoop_mix()
7094{
7095 // mix buffers...
7096 if (outputsReady(outputTracks)) {
Glenn Kastend79072e2016-01-06 08:41:20 -08007097 mAudioMixer->process();
Eric Laurent81784c32012-11-19 14:55:58 -08007098 } else {
Eric Laurent02b57082014-11-07 17:28:28 -08007099 if (mMixerBufferValid) {
7100 memset(mMixerBuffer, 0, mMixerBufferSize);
7101 } else {
7102 memset(mSinkBuffer, 0, mSinkBufferSize);
7103 }
Eric Laurent81784c32012-11-19 14:55:58 -08007104 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007105 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007106 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08007107 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007108 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08007109}
7110
7111void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
7112{
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007113 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08007114 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007115 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007116 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007117 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007118 }
7119 } else if (mBytesWritten != 0) {
7120 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
7121 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08007122 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08007123 } else {
7124 // flush remaining overflow buffers in output tracks
7125 writeFrames = 0;
7126 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007127 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007128 }
7129}
7130
Eric Laurentbfb1b832013-01-07 09:53:42 -08007131ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08007132{
7133 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hung1c86ebe2018-05-29 20:29:08 -07007134 const ssize_t actualWritten = outputTracks[i]->write(mSinkBuffer, writeFrames);
7135
7136 // Consider the first OutputTrack for timestamp and frame counting.
7137
7138 // The threadLoop() generally assumes writing a full sink buffer size at a time.
7139 // Here, we correct for writeFrames of 0 (a stop) or underruns because
7140 // we always claim success.
7141 if (i == 0) {
7142 const ssize_t correction = mSinkBufferSize / mFrameSize - actualWritten;
7143 ALOGD_IF(correction != 0 && writeFrames != 0,
7144 "%s: writeFrames:%u actualWritten:%zd correction:%zd mFramesWritten:%lld",
7145 __func__, writeFrames, actualWritten, correction, (long long)mFramesWritten);
7146 mFramesWritten -= correction;
7147 }
7148
7149 // TODO: Report correction for the other output tracks and show in the dump.
Eric Laurent81784c32012-11-19 14:55:58 -08007150 }
Andy Hungcf10d742020-04-28 15:38:24 -07007151 if (mStandby) {
7152 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07007153 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -07007154 mStandby = false;
7155 }
Andy Hung25c2dac2014-02-27 14:56:00 -08007156 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08007157}
7158
7159void AudioFlinger::DuplicatingThread::threadLoop_standby()
7160{
7161 // DuplicatingThread implements standby by stopping all tracks
7162 for (size_t i = 0; i < outputTracks.size(); i++) {
7163 outputTracks[i]->stop();
7164 }
7165}
7166
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07007167void AudioFlinger::DuplicatingThread::dumpInternals_l(int fd, const Vector<String16>& args __unused)
Andy Hung1bc088a2018-02-09 15:57:31 -08007168{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07007169 MixerThread::dumpInternals_l(fd, args);
Andy Hung1bc088a2018-02-09 15:57:31 -08007170
7171 std::stringstream ss;
7172 const size_t numTracks = mOutputTracks.size();
7173 ss << " " << numTracks << " OutputTracks";
7174 if (numTracks > 0) {
7175 ss << ":";
7176 for (const auto &track : mOutputTracks) {
7177 const sp<ThreadBase> thread = track->thread().promote();
Andy Hungc0691382018-09-12 18:01:57 -07007178 ss << " (" << track->id() << " : ";
Andy Hung1bc088a2018-02-09 15:57:31 -08007179 if (thread.get() != nullptr) {
7180 ss << thread.get() << ", " << thread->id();
7181 } else {
7182 ss << "null";
7183 }
7184 ss << ")";
7185 }
7186 }
7187 ss << "\n";
7188 std::string result = ss.str();
7189 write(fd, result.c_str(), result.size());
7190}
7191
Eric Laurent81784c32012-11-19 14:55:58 -08007192void AudioFlinger::DuplicatingThread::saveOutputTracks()
7193{
7194 outputTracks = mOutputTracks;
7195}
7196
7197void AudioFlinger::DuplicatingThread::clearOutputTracks()
7198{
7199 outputTracks.clear();
7200}
7201
7202void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
7203{
7204 Mutex::Autolock _l(mLock);
Andy Hungc25b84a2015-01-14 19:04:10 -08007205 // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
7206 // Adjust for thread->sampleRate() to determine minimum buffer frame count.
7207 // Then triple buffer because Threads do not run synchronously and may not be clock locked.
7208 const size_t frameCount =
7209 3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
7210 // TODO: Consider asynchronous sample rate conversion to handle clock disparity
7211 // from different OutputTracks and their associated MixerThreads (e.g. one may
7212 // nearly empty and the other may be dropping data).
7213
Svet Ganov33761132021-05-13 22:51:08 +00007214 // TODO b/182392769: use attribution source util, move to server edge
7215 AttributionSourceState attributionSource = AttributionSourceState();
7216 attributionSource.uid = VALUE_OR_FATAL(legacy2aidl_uid_t_int32_t(
Philip P. Moltmannbda45752020-07-17 16:41:18 -07007217 IPCThreadState::self()->getCallingUid()));
Svet Ganov33761132021-05-13 22:51:08 +00007218 attributionSource.pid = VALUE_OR_FATAL(legacy2aidl_pid_t_int32_t(
Philip P. Moltmannbda45752020-07-17 16:41:18 -07007219 IPCThreadState::self()->getCallingPid()));
Svet Ganov33761132021-05-13 22:51:08 +00007220 attributionSource.token = sp<BBinder>::make();
Andy Hungc25b84a2015-01-14 19:04:10 -08007221 sp<OutputTrack> outputTrack = new OutputTrack(thread,
Eric Laurent81784c32012-11-19 14:55:58 -08007222 this,
7223 mSampleRate,
Andy Hungc25b84a2015-01-14 19:04:10 -08007224 mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08007225 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08007226 frameCount,
Svet Ganov33761132021-05-13 22:51:08 +00007227 attributionSource);
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07007228 status_t status = outputTrack != 0 ? outputTrack->initCheck() : (status_t) NO_MEMORY;
7229 if (status != NO_ERROR) {
7230 ALOGE("addOutputTrack() initCheck failed %d", status);
7231 return;
Eric Laurent81784c32012-11-19 14:55:58 -08007232 }
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07007233 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
7234 mOutputTracks.add(outputTrack);
7235 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
7236 updateWaitTime_l();
Eric Laurent81784c32012-11-19 14:55:58 -08007237}
7238
7239void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
7240{
7241 Mutex::Autolock _l(mLock);
7242 for (size_t i = 0; i < mOutputTracks.size(); i++) {
7243 if (mOutputTracks[i]->thread() == thread) {
7244 mOutputTracks[i]->destroy();
7245 mOutputTracks.removeAt(i);
7246 updateWaitTime_l();
Eric Laurentf6870ae2015-05-08 10:50:03 -07007247 if (thread->getOutput() == mOutput) {
7248 mOutput = NULL;
7249 }
Eric Laurent81784c32012-11-19 14:55:58 -08007250 return;
7251 }
7252 }
Eric Laurentf6870ae2015-05-08 10:50:03 -07007253 ALOGV("removeOutputTrack(): unknown thread: %p", thread);
Eric Laurent81784c32012-11-19 14:55:58 -08007254}
7255
7256// caller must hold mLock
7257void AudioFlinger::DuplicatingThread::updateWaitTime_l()
7258{
7259 mWaitTimeMs = UINT_MAX;
7260 for (size_t i = 0; i < mOutputTracks.size(); i++) {
7261 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
7262 if (strong != 0) {
7263 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
7264 if (waitTimeMs < mWaitTimeMs) {
7265 mWaitTimeMs = waitTimeMs;
7266 }
7267 }
7268 }
7269}
7270
7271
7272bool AudioFlinger::DuplicatingThread::outputsReady(
7273 const SortedVector< sp<OutputTrack> > &outputTracks)
7274{
7275 for (size_t i = 0; i < outputTracks.size(); i++) {
7276 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
7277 if (thread == 0) {
7278 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
7279 outputTracks[i].get());
7280 return false;
7281 }
7282 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
7283 // see note at standby() declaration
7284 if (playbackThread->standby() && !playbackThread->isSuspended()) {
7285 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
7286 thread.get());
7287 return false;
7288 }
7289 }
7290 return true;
7291}
7292
Kevin Rocard12381092018-04-11 09:19:59 -07007293void AudioFlinger::DuplicatingThread::sendMetadataToBackend_l(
7294 const StreamOutHalInterface::SourceMetadata& metadata)
Kevin Rocard069c2712018-03-29 19:09:14 -07007295{
Kevin Rocard12381092018-04-11 09:19:59 -07007296 for (auto& outputTrack : outputTracks) { // not mOutputTracks
7297 outputTrack->setMetadatas(metadata.tracks);
7298 }
Kevin Rocard069c2712018-03-29 19:09:14 -07007299}
7300
Eric Laurent81784c32012-11-19 14:55:58 -08007301uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
7302{
7303 return (mWaitTimeMs * 1000) / 2;
7304}
7305
7306void AudioFlinger::DuplicatingThread::cacheParameters_l()
7307{
7308 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
7309 updateWaitTime_l();
7310
7311 MixerThread::cacheParameters_l();
7312}
7313
Eric Laurentb3f315a2021-07-13 15:09:05 +02007314// ----------------------------------------------------------------------------
7315
Eric Laurentfa0f6742021-08-17 18:39:44 +02007316AudioFlinger::SpatializerThread::SpatializerThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurentb3f315a2021-07-13 15:09:05 +02007317 AudioStreamOut* output,
7318 audio_io_handle_t id,
7319 bool systemReady,
7320 audio_config_base_t *mixerConfig)
Eric Laurent1c5e2e32021-08-18 18:50:28 +02007321 : MixerThread(audioFlinger, output, id, systemReady, SPATIALIZER, mixerConfig)
Eric Laurentb3f315a2021-07-13 15:09:05 +02007322{
7323}
7324
Eric Laurent68a40a82022-05-03 18:15:04 +02007325void AudioFlinger::SpatializerThread::onFirstRef() {
7326 PlaybackThread::onFirstRef();
7327
7328 Mutex::Autolock _l(mLock);
7329 status_t status = mOutput->stream->setLatencyModeCallback(this);
7330 if (status != INVALID_OPERATION) {
7331 updateHalSupportedLatencyModes_l();
7332 }
7333}
7334
7335status_t AudioFlinger::SpatializerThread::createAudioPatch_l(const struct audio_patch *patch,
7336 audio_patch_handle_t *handle)
7337{
7338 status_t status = MixerThread::createAudioPatch_l(patch, handle);
7339 updateHalSupportedLatencyModes_l();
7340 return status;
7341}
7342
7343void AudioFlinger::SpatializerThread::updateHalSupportedLatencyModes_l() {
7344 std::vector<audio_latency_mode_t> latencyModes;
7345 if (mOutput->stream->getRecommendedLatencyModes(&latencyModes) != NO_ERROR) {
7346 latencyModes.clear();
7347 }
7348 if (latencyModes != mSupportedLatencyModes) {
7349 mSupportedLatencyModes.swap(latencyModes);
7350 sendHalLatencyModesChangedEvent_l();
7351 }
7352}
7353
7354void AudioFlinger::SpatializerThread::onHalLatencyModesChanged_l() {
7355 mAudioFlinger->onSupportedLatencyModesChanged(mId, mSupportedLatencyModes);
7356}
7357
7358void AudioFlinger::SpatializerThread::setHalLatencyMode_l() {
7359 // if mSupportedLatencyModes is empty, the HAL stream does not support
7360 // latency mode control and we can exit.
7361 if (mSupportedLatencyModes.empty()) {
7362 return;
7363 }
7364 audio_latency_mode_t latencyMode = AUDIO_LATENCY_MODE_FREE;
7365 if (mSupportedLatencyModes.size() == 1) {
7366 // If the HAL only support one latency mode currently, confirm the choice
7367 latencyMode = mSupportedLatencyModes[0];
7368 } else if (mSupportedLatencyModes.size() > 1) {
7369 // Request low latency if:
7370 // - The low latency mode is requested by the spatializer controller
7371 // (mRequestedLatencyMode = AUDIO_LATENCY_MODE_LOW)
7372 // AND
7373 // - At least one active track is spatialized
7374 bool hasSpatializedActiveTrack = false;
7375 for (const auto& track : mActiveTracks) {
7376 if (track->isSpatialized()) {
7377 hasSpatializedActiveTrack = true;
7378 break;
7379 }
7380 }
7381 if (hasSpatializedActiveTrack && mRequestedLatencyMode == AUDIO_LATENCY_MODE_LOW) {
7382 latencyMode = AUDIO_LATENCY_MODE_LOW;
7383 }
7384 }
7385
7386 if (latencyMode != mSetLatencyMode) {
7387 status_t status = mOutput->stream->setLatencyMode(latencyMode);
7388 if (status == NO_ERROR) {
7389 mSetLatencyMode = latencyMode;
7390 }
7391 }
7392}
7393
7394status_t AudioFlinger::SpatializerThread::setRequestedLatencyMode(audio_latency_mode_t mode) {
7395 if (mode != AUDIO_LATENCY_MODE_LOW && mode != AUDIO_LATENCY_MODE_FREE) {
7396 return BAD_VALUE;
7397 }
7398 Mutex::Autolock _l(mLock);
7399 mRequestedLatencyMode = mode;
7400 return NO_ERROR;
7401}
7402
7403status_t AudioFlinger::SpatializerThread::getSupportedLatencyModes(
7404 std::vector<audio_latency_mode_t>* modes) {
7405 if (modes == nullptr) {
7406 return BAD_VALUE;
7407 }
7408 Mutex::Autolock _l(mLock);
7409 *modes = mSupportedLatencyModes;
7410 return NO_ERROR;
7411}
7412
Eric Laurentfa0f6742021-08-17 18:39:44 +02007413void AudioFlinger::SpatializerThread::checkOutputStageEffects()
Eric Laurentb3f315a2021-07-13 15:09:05 +02007414{
7415 bool hasVirtualizer = false;
7416 bool hasDownMixer = false;
7417 sp<EffectHandle> finalDownMixer;
7418 {
7419 Mutex::Autolock _l(mLock);
7420 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_STAGE);
7421 if (chain != 0) {
Eric Laurent1c5e2e32021-08-18 18:50:28 +02007422 hasVirtualizer = chain->getEffectFromType_l(FX_IID_SPATIALIZER) != nullptr;
Eric Laurentb3f315a2021-07-13 15:09:05 +02007423 hasDownMixer = chain->getEffectFromType_l(EFFECT_UIID_DOWNMIX) != nullptr;
7424 }
7425
7426 finalDownMixer = mFinalDownMixer;
7427 mFinalDownMixer.clear();
7428 }
7429
7430 if (hasVirtualizer) {
7431 if (finalDownMixer != nullptr) {
7432 int32_t ret;
7433 finalDownMixer->disable(&ret);
7434 }
7435 finalDownMixer.clear();
7436 } else if (!hasDownMixer) {
7437 std::vector<effect_descriptor_t> descriptors;
7438 status_t status = mAudioFlinger->mEffectsFactoryHal->getDescriptors(
7439 EFFECT_UIID_DOWNMIX, &descriptors);
7440 if (status != NO_ERROR) {
7441 return;
7442 }
7443 ALOG_ASSERT(!descriptors.empty(),
7444 "%s getDescriptors() returned no error but empty list", __func__);
7445
7446 finalDownMixer = createEffect_l(nullptr /*client*/, nullptr /*effectClient*/,
7447 0 /*priority*/, AUDIO_SESSION_OUTPUT_STAGE, &descriptors[0], nullptr /*enabled*/,
Eric Laurentde8caf42021-08-11 17:19:25 +02007448 &status, false /*pinned*/, false /*probe*/, false /*notifyFramesProcessed*/);
Eric Laurentb3f315a2021-07-13 15:09:05 +02007449
7450 if (finalDownMixer == nullptr || (status != NO_ERROR && status != ALREADY_EXISTS)) {
7451 ALOGW("%s error creating downmixer %d", __func__, status);
7452 finalDownMixer.clear();
7453 } else {
7454 int32_t ret;
7455 finalDownMixer->enable(&ret);
7456 }
7457 }
7458
7459 {
7460 Mutex::Autolock _l(mLock);
7461 mFinalDownMixer = finalDownMixer;
7462 }
7463}
7464
Eric Laurent68a40a82022-05-03 18:15:04 +02007465void AudioFlinger::SpatializerThread::onRecommendedLatencyModeChanged(
7466 std::vector<audio_latency_mode_t> modes) {
7467 Mutex::Autolock _l(mLock);
7468 if (modes != mSupportedLatencyModes) {
7469 mSupportedLatencyModes.swap(modes);
7470 sendHalLatencyModesChangedEvent_l();
7471 }
7472}
Eric Laurent6acd1d42017-01-04 14:23:29 -08007473
Eric Laurent81784c32012-11-19 14:55:58 -08007474// ----------------------------------------------------------------------------
7475// Record
7476// ----------------------------------------------------------------------------
7477
7478AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
7479 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08007480 audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -07007481 bool systemReady
Glenn Kasten46909e72013-02-26 09:20:22 -08007482 ) :
Andy Hungcf10d742020-04-28 15:38:24 -07007483 ThreadBase(audioFlinger, id, RECORD, systemReady, false /* isOut */),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007484 mInput(input),
Mikhail Naganov2534b382019-09-25 13:05:02 -07007485 mSource(mInput),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007486 mActiveTracks(&this->mLocalLog),
7487 mRsmpInBuffer(NULL),
Glenn Kasten1b291842016-07-18 14:55:21 -07007488 // mRsmpInFrames, mRsmpInFramesP2, and mRsmpInFramesOA are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007489 mRsmpInRear(0)
Glenn Kastenb880f5e2014-05-07 08:43:45 -07007490 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
7491 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007492 // mFastCapture below
7493 , mFastCaptureFutex(0)
7494 // mInputSource
7495 // mPipeSink
7496 // mPipeSource
7497 , mPipeFramesP2(0)
7498 // mPipeMemory
7499 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07007500 , mFastTrackAvail(false)
Eric Laurentd8365c52017-07-16 15:27:05 -07007501 , mBtNrecSuspended(false)
Eric Laurent81784c32012-11-19 14:55:58 -08007502{
Glenn Kastend7dca052015-03-05 16:05:54 -08007503 snprintf(mThreadName, kThreadNameLength, "AudioIn_%X", id);
7504 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08007505
George Burgess IVa8f90c12020-05-14 11:27:19 -07007506 if (mInput->audioHwDev != nullptr) {
Andy Hungc8fddf32018-08-08 18:32:37 -07007507 mIsMsdDevice = strcmp(
7508 mInput->audioHwDev->moduleName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0;
7509 }
7510
Glenn Kastendeca2ae2014-02-07 10:25:56 -08007511 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007512
Andy Hungc8fddf32018-08-08 18:32:37 -07007513 // TODO: We may also match on address as well as device type for
7514 // AUDIO_DEVICE_IN_BUS, AUDIO_DEVICE_IN_BLUETOOTH_A2DP, AUDIO_DEVICE_IN_REMOTE_SUBMIX
jiabinc52b1ff2019-10-31 17:20:42 -07007515 // TODO: This property should be ensure that only contains one single device type.
7516 mTimestampCorrectedDevice = (audio_devices_t)property_get_int64(
7517 "audio.timestamp.corrected_input_device",
Andy Hungc8fddf32018-08-08 18:32:37 -07007518 (int64_t)(mIsMsdDevice ? AUDIO_DEVICE_IN_BUS // turn on by default for MSD
7519 : AUDIO_DEVICE_NONE));
7520
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007521 // create an NBAIO source for the HAL input stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07007522 mInputSource = new AudioStreamInSource(input->stream);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007523 size_t numCounterOffers = 0;
7524 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07007525#if !LOG_NDEBUG
7526 ssize_t index =
7527#else
7528 (void)
7529#endif
7530 mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007531 ALOG_ASSERT(index == 0);
7532
7533 // initialize fast capture depending on configuration
7534 bool initFastCapture;
7535 switch (kUseFastCapture) {
7536 case FastCapture_Never:
7537 initFastCapture = false;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007538 ALOGV("%p kUseFastCapture = Never, initFastCapture = false", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007539 break;
7540 case FastCapture_Always:
7541 initFastCapture = true;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007542 ALOGV("%p kUseFastCapture = Always, initFastCapture = true", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007543 break;
7544 case FastCapture_Static:
Glenn Kasteneb9487e2015-07-22 09:15:17 -07007545 initFastCapture = (mFrameCount * 1000) / mSampleRate < kMinNormalCaptureBufferSizeMs;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007546 ALOGV("%p kUseFastCapture = Static, (%lld * 1000) / %u vs %u, initFastCapture = %d",
7547 this, (long long)mFrameCount, mSampleRate, kMinNormalCaptureBufferSizeMs,
7548 initFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007549 break;
7550 // case FastCapture_Dynamic:
7551 }
7552
7553 if (initFastCapture) {
Glenn Kastend198b852015-03-16 14:55:53 -07007554 // create a Pipe for FastCapture to write to, and for us and fast tracks to read from
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007555 NBAIO_Format format = mInputSource->format();
Glenn Kasten1b291842016-07-18 14:55:21 -07007556 // quadruple-buffering of 20 ms each; this ensures we can sleep for 20ms in RecordThread
7557 size_t pipeFramesP2 = roundup(4 * FMS_20 * mSampleRate / 1000);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007558 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007559 void *pipeBuffer = nullptr;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007560 const sp<MemoryDealer> roHeap(readOnlyHeap());
7561 sp<IMemory> pipeMemory;
7562 if ((roHeap == 0) ||
7563 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07007564 (pipeBuffer = pipeMemory->unsecurePointer()) == nullptr) {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007565 ALOGE("not enough memory for pipe buffer size=%zu; "
7566 "roHeap=%p, pipeMemory=%p, pipeBuffer=%p; roHeapSize: %lld",
7567 pipeSize, roHeap.get(), pipeMemory.get(), pipeBuffer,
7568 (long long)kRecordThreadReadOnlyHeapSize);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007569 goto failed;
7570 }
7571 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
7572 memset(pipeBuffer, 0, pipeSize);
7573 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
7574 const NBAIO_Format offers[1] = {format};
7575 size_t numCounterOffers = 0;
7576 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
7577 ALOG_ASSERT(index == 0);
7578 mPipeSink = pipe;
7579 PipeReader *pipeReader = new PipeReader(*pipe);
7580 numCounterOffers = 0;
7581 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
7582 ALOG_ASSERT(index == 0);
7583 mPipeSource = pipeReader;
7584 mPipeFramesP2 = pipeFramesP2;
7585 mPipeMemory = pipeMemory;
7586
7587 // create fast capture
7588 mFastCapture = new FastCapture();
7589 FastCaptureStateQueue *sq = mFastCapture->sq();
7590#ifdef STATE_QUEUE_DUMP
7591 // FIXME
7592#endif
7593 FastCaptureState *state = sq->begin();
7594 state->mCblk = NULL;
7595 state->mInputSource = mInputSource.get();
7596 state->mInputSourceGen++;
7597 state->mPipeSink = pipe;
7598 state->mPipeSinkGen++;
7599 state->mFrameCount = mFrameCount;
7600 state->mCommand = FastCaptureState::COLD_IDLE;
7601 // already done in constructor initialization list
7602 //mFastCaptureFutex = 0;
7603 state->mColdFutexAddr = &mFastCaptureFutex;
7604 state->mColdGen++;
7605 state->mDumpState = &mFastCaptureDumpState;
7606#ifdef TEE_SINK
7607 // FIXME
7608#endif
7609 mFastCaptureNBLogWriter = audioFlinger->newWriter_l(kFastCaptureLogSize, "FastCapture");
7610 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
7611 sq->end();
7612 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
7613
7614 // start the fast capture
7615 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
7616 pid_t tid = mFastCapture->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07007617 sendPrioConfigEvent(getpid(), tid, kPriorityFastCapture, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08007618 stream()->setHalThreadPriority(kPriorityFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007619#ifdef AUDIO_WATCHDOG
7620 // FIXME
7621#endif
7622
Glenn Kasten6e6704c2014-07-03 10:20:00 -07007623 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007624 }
Andy Hung8946a282018-04-19 20:04:56 -07007625#ifdef TEE_SINK
7626 mTee.set(mInputSource->format(), NBAIO_Tee::TEE_FLAG_INPUT_THREAD);
7627 mTee.setId(std::string("_") + std::to_string(mId) + "_C");
7628#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007629failed: ;
7630
7631 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08007632}
7633
Eric Laurent81784c32012-11-19 14:55:58 -08007634AudioFlinger::RecordThread::~RecordThread()
7635{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007636 if (mFastCapture != 0) {
7637 FastCaptureStateQueue *sq = mFastCapture->sq();
7638 FastCaptureState *state = sq->begin();
7639 if (state->mCommand == FastCaptureState::COLD_IDLE) {
7640 int32_t old = android_atomic_inc(&mFastCaptureFutex);
7641 if (old == -1) {
7642 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
7643 }
7644 }
7645 state->mCommand = FastCaptureState::EXIT;
7646 sq->end();
7647 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
7648 mFastCapture->join();
7649 mFastCapture.clear();
7650 }
7651 mAudioFlinger->unregisterWriter(mFastCaptureNBLogWriter);
Glenn Kasten481fb672013-09-30 14:39:28 -07007652 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung57446612015-04-19 23:56:46 -07007653 free(mRsmpInBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08007654}
7655
7656void AudioFlinger::RecordThread::onFirstRef()
7657{
Glenn Kastend7dca052015-03-05 16:05:54 -08007658 run(mThreadName, PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08007659}
7660
Eric Laurent555530a2017-02-07 18:17:24 -08007661void AudioFlinger::RecordThread::preExit()
7662{
7663 ALOGV(" preExit()");
7664 Mutex::Autolock _l(mLock);
7665 for (size_t i = 0; i < mTracks.size(); i++) {
7666 sp<RecordTrack> track = mTracks[i];
7667 track->invalidate();
7668 }
7669 mActiveTracks.clear();
7670 mStartStopCond.broadcast();
7671}
7672
Eric Laurent81784c32012-11-19 14:55:58 -08007673bool AudioFlinger::RecordThread::threadLoop()
7674{
Eric Laurent81784c32012-11-19 14:55:58 -08007675 nsecs_t lastWarning = 0;
7676
7677 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08007678
Glenn Kastenf10ffec2013-11-20 16:40:08 -08007679reacquire_wakelock:
7680 sp<RecordTrack> activeTrack;
7681 {
7682 Mutex::Autolock _l(mLock);
Andy Hungdae27702016-10-31 14:01:16 -07007683 acquireWakeLock_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08007684 }
7685
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007686 // used to request a deferred sleep, to be executed later while mutex is unlocked
7687 uint32_t sleepUs = 0;
7688
Andy Hung446f4df2019-02-21 12:26:41 -08007689 int64_t lastLoopCountRead = -2; // never matches "previous" loop, when loopCount = 0.
7690
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007691 // loop while there is work to do
Andy Hung446f4df2019-02-21 12:26:41 -08007692 for (int64_t loopCount = 0;; ++loopCount) { // loopCount used for statistics tracking
Glenn Kastenc527a7c2013-08-13 15:43:49 -07007693 Vector< sp<EffectChain> > effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07007694
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007695 // activeTracks accumulates a copy of a subset of mActiveTracks
7696 Vector< sp<RecordTrack> > activeTracks;
7697
Glenn Kasten735f45f2014-08-18 15:51:59 -07007698 // reference to the (first and only) active fast track
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007699 sp<RecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07007700
Glenn Kasten735f45f2014-08-18 15:51:59 -07007701 // reference to a fast track which is about to be removed
7702 sp<RecordTrack> fastTrackToRemove;
7703
Eric Laurent33403f02020-05-29 18:35:06 -07007704 bool silenceFastCapture = false;
7705
Eric Laurent81784c32012-11-19 14:55:58 -08007706 { // scope for mLock
7707 Mutex::Autolock _l(mLock);
Eric Laurent000a4192014-01-29 15:17:32 -08007708
Eric Laurent021cf962014-05-13 10:18:14 -07007709 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08007710
Eric Laurent000a4192014-01-29 15:17:32 -08007711 // check exitPending here because checkForNewParameters_l() and
7712 // checkForNewParameters_l() can temporarily release mLock
7713 if (exitPending()) {
7714 break;
7715 }
7716
Eric Laurent5c25d562016-07-13 17:17:45 -07007717 // sleep with mutex unlocked
7718 if (sleepUs > 0) {
Glenn Kastenf9715e42016-07-13 14:02:03 -07007719 ATRACE_BEGIN("sleepC");
Eric Laurent5c25d562016-07-13 17:17:45 -07007720 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)sleepUs));
7721 ATRACE_END();
7722 sleepUs = 0;
7723 continue;
7724 }
7725
Glenn Kasten2b806402013-11-20 16:37:38 -08007726 // if no active track(s), then standby and release wakelock
7727 size_t size = mActiveTracks.size();
7728 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07007729 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07007730 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08007731 releaseWakeLock_l();
7732 ALOGV("RecordThread: loop stopping");
7733 // go to sleep
7734 mWaitWorkCV.wait(mLock);
7735 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08007736 goto reacquire_wakelock;
7737 }
7738
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007739 bool doBroadcast = false;
Eric Laurent5c25d562016-07-13 17:17:45 -07007740 bool allStopped = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007741 for (size_t i = 0; i < size; ) {
Glenn Kasten9e982352013-08-14 14:39:50 -07007742
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007743 activeTrack = mActiveTracks[i];
7744 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07007745 if (activeTrack->isFastTrack()) {
7746 ALOG_ASSERT(fastTrackToRemove == 0);
7747 fastTrackToRemove = activeTrack;
7748 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007749 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08007750 mActiveTracks.remove(activeTrack);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007751 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07007752 continue;
7753 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007754
7755 TrackBase::track_state activeTrackState = activeTrack->mState;
7756 switch (activeTrackState) {
7757
7758 case TrackBase::PAUSING:
7759 mActiveTracks.remove(activeTrack);
Andy Hungce685402018-10-05 17:23:27 -07007760 activeTrack->mState = TrackBase::PAUSED;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007761 doBroadcast = true;
7762 size--;
7763 continue;
7764
7765 case TrackBase::STARTING_1:
7766 sleepUs = 10000;
7767 i++;
Eric Laurent5c25d562016-07-13 17:17:45 -07007768 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007769 continue;
7770
7771 case TrackBase::STARTING_2:
7772 doBroadcast = true;
Andy Hungcf10d742020-04-28 15:38:24 -07007773 if (mStandby) {
7774 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07007775 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -07007776 mStandby = false;
7777 }
Glenn Kasten9e982352013-08-14 14:39:50 -07007778 activeTrack->mState = TrackBase::ACTIVE;
Eric Laurent5c25d562016-07-13 17:17:45 -07007779 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007780 break;
7781
7782 case TrackBase::ACTIVE:
Eric Laurent5c25d562016-07-13 17:17:45 -07007783 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007784 break;
7785
Andy Hungce685402018-10-05 17:23:27 -07007786 case TrackBase::IDLE: // cannot be on ActiveTracks if idle
7787 case TrackBase::PAUSED: // cannot be on ActiveTracks if paused
7788 case TrackBase::STOPPED: // cannot be on ActiveTracks if destroyed/terminated
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007789 default:
Andy Hungce685402018-10-05 17:23:27 -07007790 LOG_ALWAYS_FATAL("%s: Unexpected active track state:%d, id:%d, tracks:%zu",
7791 __func__, activeTrackState, activeTrack->id(), size);
Glenn Kasten9e982352013-08-14 14:39:50 -07007792 }
Glenn Kasten9e982352013-08-14 14:39:50 -07007793
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007794 if (activeTrack->isFastTrack()) {
7795 ALOG_ASSERT(!mFastTrackAvail);
7796 ALOG_ASSERT(fastTrack == 0);
Eric Laurent33403f02020-05-29 18:35:06 -07007797 // if the active fast track is silenced either:
7798 // 1) silence the whole capture from fast capture buffer if this is
7799 // the only active track
7800 // 2) invalidate this track: this will cause the client to reconnect and possibly
7801 // be invalidated again until unsilenced
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02007802 bool invalidate = false;
Eric Laurent33403f02020-05-29 18:35:06 -07007803 if (activeTrack->isSilenced()) {
7804 if (size > 1) {
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02007805 invalidate = true;
Eric Laurent33403f02020-05-29 18:35:06 -07007806 } else {
7807 silenceFastCapture = true;
7808 }
7809 }
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02007810 // Invalidate fast tracks if access to audio history is required as this is not
7811 // possible with fast tracks. Once the fast track has been invalidated, no new
7812 // fast track will be created until mMaxSharedAudioHistoryMs is cleared.
7813 if (mMaxSharedAudioHistoryMs != 0) {
7814 invalidate = true;
7815 }
7816 if (invalidate) {
7817 activeTrack->invalidate();
7818 ALOG_ASSERT(fastTrackToRemove == 0);
7819 fastTrackToRemove = activeTrack;
7820 removeTrack_l(activeTrack);
7821 mActiveTracks.remove(activeTrack);
7822 size--;
7823 continue;
7824 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007825 fastTrack = activeTrack;
7826 }
Eric Laurent33403f02020-05-29 18:35:06 -07007827
7828 activeTracks.add(activeTrack);
7829 i++;
7830
Glenn Kasten9e982352013-08-14 14:39:50 -07007831 }
Eric Laurent5c25d562016-07-13 17:17:45 -07007832
Andy Hungdae27702016-10-31 14:01:16 -07007833 mActiveTracks.updatePowerState(this);
7834
Kevin Rocard069c2712018-03-29 19:09:14 -07007835 updateMetadata_l();
7836
Eric Laurent5c25d562016-07-13 17:17:45 -07007837 if (allStopped) {
7838 standbyIfNotAlreadyInStandby();
7839 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007840 if (doBroadcast) {
7841 mStartStopCond.broadcast();
7842 }
7843
7844 // sleep if there are no active tracks to process
Eric Tan39ec8d62018-07-24 09:49:29 -07007845 if (activeTracks.isEmpty()) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007846 if (sleepUs == 0) {
7847 sleepUs = kRecordThreadSleepUs;
7848 }
7849 continue;
7850 }
7851 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07007852
Eric Laurent81784c32012-11-19 14:55:58 -08007853 lockEffectChains_l(effectChains);
7854 }
7855
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007856 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07007857
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007858 size_t size = effectChains.size();
7859 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07007860 // thread mutex is not locked, but effect chain is locked
7861 effectChains[i]->process_l();
7862 }
7863
Glenn Kasten735f45f2014-08-18 15:51:59 -07007864 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007865 if (mFastCapture != 0) {
7866 FastCaptureStateQueue *sq = mFastCapture->sq();
7867 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07007868 bool didModify = false;
7869 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007870 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
7871 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
7872 if (state->mCommand == FastCaptureState::COLD_IDLE) {
7873 int32_t old = android_atomic_inc(&mFastCaptureFutex);
7874 if (old == -1) {
7875 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
7876 }
7877 }
7878 state->mCommand = FastCaptureState::READ_WRITE;
7879#if 0 // FIXME
7880 mFastCaptureDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08007881 FastThreadDumpState::kSamplingNforLowRamDevice :
7882 FastThreadDumpState::kSamplingN);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007883#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07007884 didModify = true;
7885 }
7886 audio_track_cblk_t *cblkOld = state->mCblk;
7887 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
7888 if (cblkNew != cblkOld) {
7889 state->mCblk = cblkNew;
7890 // block until acked if removing a fast track
7891 if (cblkOld != NULL) {
7892 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
7893 }
7894 didModify = true;
7895 }
jiabin01c8f562018-07-19 17:47:28 -07007896 AudioBufferProvider* abp = (fastTrack != 0 && fastTrack->isPatchTrack()) ?
7897 reinterpret_cast<AudioBufferProvider*>(fastTrack.get()) : nullptr;
7898 if (state->mFastPatchRecordBufferProvider != abp) {
7899 state->mFastPatchRecordBufferProvider = abp;
7900 state->mFastPatchRecordFormat = fastTrack == 0 ?
7901 AUDIO_FORMAT_INVALID : fastTrack->format();
7902 didModify = true;
7903 }
Eric Laurent33403f02020-05-29 18:35:06 -07007904 if (state->mSilenceCapture != silenceFastCapture) {
7905 state->mSilenceCapture = silenceFastCapture;
7906 didModify = true;
7907 }
Glenn Kasten735f45f2014-08-18 15:51:59 -07007908 sq->end(didModify);
7909 if (didModify) {
7910 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007911#if 0
7912 if (kUseFastCapture == FastCapture_Dynamic) {
7913 mNormalSource = mPipeSource;
7914 }
7915#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007916 }
7917 }
7918
Glenn Kasten735f45f2014-08-18 15:51:59 -07007919 // now run the fast track destructor with thread mutex unlocked
7920 fastTrackToRemove.clear();
7921
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007922 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
7923 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
7924 // slow, then this RecordThread will overrun by not calling HAL read often enough.
7925 // If destination is non-contiguous, first read past the nominal end of buffer, then
7926 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07007927
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007928 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007929 ssize_t framesRead;
Andy Hung446f4df2019-02-21 12:26:41 -08007930 const int64_t lastIoBeginNs = systemTime(); // start IO timing
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007931
7932 // If an NBAIO source is present, use it to read the normal capture's data
7933 if (mPipeSource != 0) {
Andy Hung156317a2018-08-02 11:49:29 -07007934 size_t framesToRead = min(mRsmpInFramesOA - rear, mRsmpInFramesP2 / 2);
Andy Hungd5b638f2018-04-30 13:56:10 -07007935
7936 // The audio fifo read() returns OVERRUN on overflow, and advances the read pointer
7937 // to the full buffer point (clearing the overflow condition). Upon OVERRUN error,
7938 // we immediately retry the read() to get data and prevent another overflow.
7939 for (int retries = 0; retries <= 2; ++retries) {
7940 ALOGW_IF(retries > 0, "overrun on read from pipe, retry #%d", retries);
7941 framesRead = mPipeSource->read((uint8_t*)mRsmpInBuffer + rear * mFrameSize,
7942 framesToRead);
7943 if (framesRead != OVERRUN) break;
7944 }
7945
Andy Hung7a3dc6b2018-05-01 16:39:51 -07007946 const ssize_t availableToRead = mPipeSource->availableToRead();
7947 if (availableToRead >= 0) {
Robert Wu06db0a32021-08-10 19:05:34 +00007948 mMonopipePipeDepthStats.add(availableToRead);
Glenn Kastena2f59b32020-08-03 16:37:24 -07007949 // PipeSource is the primary clock. It is up to the AudioRecord client to keep up.
Andy Hung7a3dc6b2018-05-01 16:39:51 -07007950 LOG_ALWAYS_FATAL_IF((size_t)availableToRead > mPipeFramesP2,
7951 "more frames to read than fifo size, %zd > %zu",
7952 availableToRead, mPipeFramesP2);
7953 const size_t pipeFramesFree = mPipeFramesP2 - availableToRead;
7954 const size_t sleepFrames = min(pipeFramesFree, mRsmpInFramesP2) / 2;
7955 ALOGVV("mPipeFramesP2:%zu mRsmpInFramesP2:%zu sleepFrames:%zu availableToRead:%zd",
7956 mPipeFramesP2, mRsmpInFramesP2, sleepFrames, availableToRead);
Glenn Kasten1b291842016-07-18 14:55:21 -07007957 sleepUs = (sleepFrames * 1000000LL) / mSampleRate;
7958 }
7959 if (framesRead < 0) {
7960 status_t status = (status_t) framesRead;
7961 switch (status) {
7962 case OVERRUN:
7963 ALOGW("overrun on read from pipe");
7964 framesRead = 0;
7965 break;
7966 case NEGOTIATE:
7967 ALOGE("re-negotiation is needed");
7968 framesRead = -1; // Will cause an attempt to recover.
7969 break;
7970 default:
7971 ALOGE("unknown error %d on read from pipe", status);
7972 break;
7973 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007974 }
7975 // otherwise use the HAL / AudioStreamIn directly
7976 } else {
Glenn Kastenec6a7032016-03-14 07:40:23 -07007977 ATRACE_BEGIN("read");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007978 size_t bytesRead;
Mikhail Naganov2534b382019-09-25 13:05:02 -07007979 status_t result = mSource->read(
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007980 (uint8_t*)mRsmpInBuffer + rear * mFrameSize, mBufferSize, &bytesRead);
Glenn Kastenec6a7032016-03-14 07:40:23 -07007981 ATRACE_END();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007982 if (result < 0) {
7983 framesRead = result;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007984 } else {
7985 framesRead = bytesRead / mFrameSize;
7986 }
7987 }
7988
Andy Hung446f4df2019-02-21 12:26:41 -08007989 const int64_t lastIoEndNs = systemTime(); // end IO timing
7990
Andy Hung3f0c9022016-01-15 17:49:46 -08007991 // Update server timestamp with server stats
7992 // systemTime() is optional if the hardware supports timestamps.
Andy Hung743f6402020-06-03 13:17:04 -07007993 if (framesRead >= 0) {
7994 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += framesRead;
7995 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = lastIoEndNs;
7996 }
Andy Hung3f0c9022016-01-15 17:49:46 -08007997
7998 // Update server timestamp with kernel stats
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007999 if (mPipeSource.get() == nullptr /* don't obtain for FastCapture, could block */) {
Andy Hung3f0c9022016-01-15 17:49:46 -08008000 int64_t position, time;
Andy Hung2e2c0bb2018-06-11 19:13:11 -07008001 if (mStandby) {
Dean Wheatley12473e92021-03-18 23:00:55 +11008002 mTimestampVerifier.discontinuity(audio_is_linear_pcm(mFormat) ?
8003 mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS :
8004 mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Mikhail Naganov2534b382019-09-25 13:05:02 -07008005 } else if (mSource->getCapturePosition(&position, &time) == NO_ERROR
Andy Hungc8fddf32018-08-08 18:32:37 -07008006 && time > mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]) {
8007
8008 mTimestampVerifier.add(position, time, mSampleRate);
8009
8010 // Correct timestamps
8011 if (isTimestampCorrectionEnabled()) {
Dean Wheatley56a583e2020-05-08 15:12:17 +10008012 ALOGVV("TS_BEFORE: %d %lld %lld",
Andy Hungc8fddf32018-08-08 18:32:37 -07008013 id(), (long long)time, (long long)position);
8014 auto correctedTimestamp = mTimestampVerifier.getLastCorrectedTimestamp();
8015 position = correctedTimestamp.mFrames;
8016 time = correctedTimestamp.mTimeNs;
Dean Wheatley56a583e2020-05-08 15:12:17 +10008017 ALOGVV("TS_AFTER: %d %lld %lld",
Andy Hungc8fddf32018-08-08 18:32:37 -07008018 id(), (long long)time, (long long)position);
8019 }
8020
Andy Hung3f0c9022016-01-15 17:49:46 -08008021 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = position;
8022 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] = time;
8023 // Note: In general record buffers should tend to be empty in
8024 // a properly running pipeline.
8025 //
8026 // Also, it is not advantageous to call get_presentation_position during the read
8027 // as the read obtains a lock, preventing the timestamp call from executing.
Andy Hung2e2c0bb2018-06-11 19:13:11 -07008028 } else {
8029 mTimestampVerifier.error();
Andy Hung3f0c9022016-01-15 17:49:46 -08008030 }
8031 }
Andy Hunge6c37112019-02-26 17:38:10 -08008032
8033 // From the timestamp, input read latency is negative output write latency.
8034 const audio_input_flags_t flags = mInput != NULL ? mInput->flags : AUDIO_INPUT_FLAG_NONE;
8035 const double latencyMs = RecordTrack::checkServerLatencySupported(mFormat, flags)
8036 ? - mTimestamp.getOutputServerLatencyMs(mSampleRate) : 0.;
8037 if (latencyMs != 0.) { // note 0. means timestamp is empty.
8038 mLatencyMs.add(latencyMs);
8039 }
8040
Andy Hung3f0c9022016-01-15 17:49:46 -08008041 // Use this to track timestamp information
8042 // ALOGD("%s", mTimestamp.toString().c_str());
8043
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008044 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07008045 ALOGE("read failed: framesRead=%zd", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008046 // Force input into standby so that it tries to recover at next read attempt
8047 inputStandBy();
8048 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008049 }
8050 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008051 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008052 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008053 ALOG_ASSERT(framesRead > 0);
Andy Hung6427e442018-08-09 12:51:02 -07008054 mFramesRead += framesRead;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008055
Andy Hung8946a282018-04-19 20:04:56 -07008056#ifdef TEE_SINK
8057 (void)mTee.write((uint8_t*)mRsmpInBuffer + rear * mFrameSize, framesRead);
8058#endif
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008059 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008060 {
8061 size_t part1 = mRsmpInFramesP2 - rear;
8062 if ((size_t) framesRead > part1) {
Andy Hung57446612015-04-19 23:56:46 -07008063 memcpy(mRsmpInBuffer, (uint8_t*)mRsmpInBuffer + mRsmpInFramesP2 * mFrameSize,
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008064 (framesRead - part1) * mFrameSize);
8065 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008066 }
Dean Wheatleyfd56e812020-11-06 22:32:21 +11008067 mRsmpInRear = audio_utils::safe_add_overflow(mRsmpInRear, (int32_t)framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008068
8069 size = activeTracks.size();
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008070
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008071 // loop over each active track
8072 for (size_t i = 0; i < size; i++) {
8073 activeTrack = activeTracks[i];
8074
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008075 // skip fast tracks, as those are handled directly by FastCapture
8076 if (activeTrack->isFastTrack()) {
8077 continue;
8078 }
8079
Andy Hung73c02e42015-03-29 01:13:58 -07008080 // TODO: This code probably should be moved to RecordTrack.
Andy Hung97a893e2015-03-29 01:03:07 -07008081 // TODO: Update the activeTrack buffer converter in case of reconfigure.
8082
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008083 enum {
8084 OVERRUN_UNKNOWN,
8085 OVERRUN_TRUE,
8086 OVERRUN_FALSE
8087 } overrun = OVERRUN_UNKNOWN;
8088
8089 // loop over getNextBuffer to handle circular sink
8090 for (;;) {
8091
8092 activeTrack->mSink.frameCount = ~0;
8093 status_t status = activeTrack->getNextBuffer(&activeTrack->mSink);
8094 size_t framesOut = activeTrack->mSink.frameCount;
8095 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
8096
Andy Hung73c02e42015-03-29 01:13:58 -07008097 // check available frames and handle overrun conditions
8098 // if the record track isn't draining fast enough.
8099 bool hasOverrun;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008100 size_t framesIn;
Andy Hung73c02e42015-03-29 01:13:58 -07008101 activeTrack->mResamplerBufferProvider->sync(&framesIn, &hasOverrun);
8102 if (hasOverrun) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008103 overrun = OVERRUN_TRUE;
8104 }
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08008105 if (framesOut == 0 || framesIn == 0) {
8106 break;
8107 }
8108
Andy Hung6770c6f2015-04-07 13:43:36 -07008109 // Don't allow framesOut to be larger than what is possible with resampling
8110 // from framesIn.
8111 // This isn't strictly necessary but helps limit buffer resizing in
8112 // RecordBufferConverter. TODO: remove when no longer needed.
8113 framesOut = min(framesOut,
8114 destinationFramesPossible(
8115 framesIn, mSampleRate, activeTrack->mSampleRate));
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008116
8117 if (activeTrack->isDirect()) {
Daniel Van Veen9e2376e2018-09-27 14:37:58 +10008118 // No RecordBufferConverter used for direct streams. Pass
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008119 // straight from RecordThread buffer to RecordTrack buffer.
8120 AudioBufferProvider::Buffer buffer;
8121 buffer.frameCount = framesOut;
8122 status_t status = activeTrack->mResamplerBufferProvider->getNextBuffer(&buffer);
8123 if (status == OK && buffer.frameCount != 0) {
8124 ALOGV_IF(buffer.frameCount != framesOut,
8125 "%s() read less than expected (%zu vs %zu)",
8126 __func__, buffer.frameCount, framesOut);
8127 framesOut = buffer.frameCount;
Daniel Van Veen9e2376e2018-09-27 14:37:58 +10008128 memcpy(activeTrack->mSink.raw, buffer.raw, buffer.frameCount * mFrameSize);
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008129 activeTrack->mResamplerBufferProvider->releaseBuffer(&buffer);
8130 } else {
8131 framesOut = 0;
8132 ALOGE("%s() cannot fill request, status: %d, frameCount: %zu",
8133 __func__, status, buffer.frameCount);
8134 }
8135 } else {
8136 // process frames from the RecordThread buffer provider to the RecordTrack
8137 // buffer
8138 framesOut = activeTrack->mRecordBufferConverter->convert(
8139 activeTrack->mSink.raw,
8140 activeTrack->mResamplerBufferProvider,
8141 framesOut);
8142 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008143
8144 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
8145 overrun = OVERRUN_FALSE;
8146 }
8147
8148 if (activeTrack->mFramesToDrop == 0) {
8149 if (framesOut > 0) {
8150 activeTrack->mSink.frameCount = framesOut;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008151 // Sanitize before releasing if the track has no access to the source data
8152 // An idle UID receives silence from non virtual devices until active
8153 if (activeTrack->isSilenced()) {
Jean-Michel Trividdf87ef2019-08-20 15:42:04 -07008154 memset(activeTrack->mSink.raw, 0, framesOut * activeTrack->frameSize());
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008155 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008156 activeTrack->releaseBuffer(&activeTrack->mSink);
8157 }
8158 } else {
8159 // FIXME could do a partial drop of framesOut
8160 if (activeTrack->mFramesToDrop > 0) {
Mikhail Naganov6d91ba52019-03-26 14:35:28 -07008161 activeTrack->mFramesToDrop -= (ssize_t)framesOut;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008162 if (activeTrack->mFramesToDrop <= 0) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08008163 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008164 }
8165 } else {
8166 activeTrack->mFramesToDrop += framesOut;
8167 if (activeTrack->mFramesToDrop >= 0 || activeTrack->mSyncStartEvent == 0 ||
8168 activeTrack->mSyncStartEvent->isCancelled()) {
8169 ALOGW("Synced record %s, session %d, trigger session %d",
8170 (activeTrack->mFramesToDrop >= 0) ? "timed out" : "cancelled",
8171 activeTrack->sessionId(),
8172 (activeTrack->mSyncStartEvent != 0) ?
Glenn Kastend848eb42016-03-08 13:42:11 -08008173 activeTrack->mSyncStartEvent->triggerSession() :
8174 AUDIO_SESSION_NONE);
Glenn Kasten25f4aa82014-02-07 10:50:43 -08008175 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008176 }
8177 }
8178 }
8179
8180 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008181 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008182 }
8183 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008184
8185 switch (overrun) {
8186 case OVERRUN_TRUE:
8187 // client isn't retrieving buffers fast enough
8188 if (!activeTrack->setOverflow()) {
8189 nsecs_t now = systemTime();
8190 // FIXME should lastWarning per track?
8191 if ((now - lastWarning) > kWarningThrottleNs) {
8192 ALOGW("RecordThread: buffer overflow");
8193 lastWarning = now;
8194 }
8195 }
8196 break;
8197 case OVERRUN_FALSE:
8198 activeTrack->clearOverflow();
8199 break;
8200 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008201 break;
8202 }
8203
Andy Hung3f0c9022016-01-15 17:49:46 -08008204 // update frame information and push timestamp out
8205 activeTrack->updateTrackFrameInfo(
Andy Hung6ae58432016-02-16 18:32:24 -08008206 activeTrack->mServerProxy->framesReleased(),
Andy Hung3f0c9022016-01-15 17:49:46 -08008207 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER],
8208 mSampleRate, mTimestamp);
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008209 }
8210
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008211unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08008212 // enable changes in effect chain
8213 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07008214 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurentcccbc762019-04-05 14:20:05 -07008215 if (audio_has_proportional_frames(mFormat)
8216 && loopCount == lastLoopCountRead + 1) {
8217 const int64_t readPeriodNs = lastIoEndNs - mLastIoEndNs;
8218 const double jitterMs =
8219 TimestampVerifier<int64_t, int64_t>::computeJitterMs(
8220 {framesRead, readPeriodNs},
8221 {0, 0} /* lastTimestamp */, mSampleRate);
8222 const double processMs = (lastIoBeginNs - mLastIoEndNs) * 1e-6;
8223
8224 Mutex::Autolock _l(mLock);
8225 mIoJitterMs.add(jitterMs);
8226 mProcessTimeMs.add(processMs);
8227 }
8228 // update timing info.
8229 mLastIoBeginNs = lastIoBeginNs;
8230 mLastIoEndNs = lastIoEndNs;
8231 lastLoopCountRead = loopCount;
Eric Laurent81784c32012-11-19 14:55:58 -08008232 }
8233
Glenn Kasten93e471f2013-08-19 08:40:07 -07008234 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08008235
8236 {
8237 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07008238 for (size_t i = 0; i < mTracks.size(); i++) {
8239 sp<RecordTrack> track = mTracks[i];
8240 track->invalidate();
8241 }
Glenn Kasten2b806402013-11-20 16:37:38 -08008242 mActiveTracks.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08008243 mStartStopCond.broadcast();
8244 }
8245
8246 releaseWakeLock();
8247
8248 ALOGV("RecordThread %p exiting", this);
8249 return false;
8250}
8251
Glenn Kasten93e471f2013-08-19 08:40:07 -07008252void AudioFlinger::RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08008253{
8254 if (!mStandby) {
8255 inputStandBy();
Andy Hungcf10d742020-04-28 15:38:24 -07008256 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07008257 mThreadSnapshot.onEnd();
Eric Laurent81784c32012-11-19 14:55:58 -08008258 mStandby = true;
8259 }
8260}
8261
8262void AudioFlinger::RecordThread::inputStandBy()
8263{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008264 // Idle the fast capture if it's currently running
8265 if (mFastCapture != 0) {
8266 FastCaptureStateQueue *sq = mFastCapture->sq();
8267 FastCaptureState *state = sq->begin();
8268 if (!(state->mCommand & FastCaptureState::IDLE)) {
8269 state->mCommand = FastCaptureState::COLD_IDLE;
8270 state->mColdFutexAddr = &mFastCaptureFutex;
8271 state->mColdGen++;
8272 mFastCaptureFutex = 0;
8273 sq->end();
8274 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
8275 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
8276#if 0
8277 if (kUseFastCapture == FastCapture_Dynamic) {
8278 // FIXME
8279 }
8280#endif
8281#ifdef AUDIO_WATCHDOG
8282 // FIXME
8283#endif
8284 } else {
8285 sq->end(false /*didModify*/);
8286 }
8287 }
Mikhail Naganov2534b382019-09-25 13:05:02 -07008288 status_t result = mSource->standby();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008289 ALOGE_IF(result != OK, "Error when putting input stream into standby: %d", result);
Andy Hungad6d52d2016-07-18 13:42:03 -07008290
8291 // If going into standby, flush the pipe source.
8292 if (mPipeSource.get() != nullptr) {
8293 const ssize_t flushed = mPipeSource->flush();
8294 if (flushed > 0) {
8295 ALOGV("Input standby flushed PipeSource %zd frames", flushed);
8296 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += flushed;
8297 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
8298 }
8299 }
Eric Laurent81784c32012-11-19 14:55:58 -08008300}
8301
Glenn Kasten05997e22014-03-13 15:08:33 -07008302// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastene198c362013-08-13 09:13:36 -07008303sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
Eric Laurent81784c32012-11-19 14:55:58 -08008304 const sp<AudioFlinger::Client>& client,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07008305 const audio_attributes_t& attr,
Eric Laurentf14db3c2017-12-08 14:20:36 -08008306 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08008307 audio_format_t format,
8308 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08008309 size_t *pFrameCount,
Glenn Kastend848eb42016-03-08 13:42:11 -08008310 audio_session_t sessionId,
Eric Laurentf14db3c2017-12-08 14:20:36 -08008311 size_t *pNotificationFrameCount,
Eric Laurent09f1ed22019-04-24 17:45:17 -07008312 pid_t creatorPid,
Svet Ganov33761132021-05-13 22:51:08 +00008313 const AttributionSourceState& attributionSource,
Eric Laurent05067782016-06-01 18:27:28 -07008314 audio_input_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08008315 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08008316 status_t *status,
Eric Laurentec376dc2021-04-08 20:41:22 +02008317 audio_port_handle_t portId,
8318 int32_t maxSharedAudioHistoryMs)
Eric Laurent81784c32012-11-19 14:55:58 -08008319{
Glenn Kasten74935e42013-12-19 08:56:45 -08008320 size_t frameCount = *pFrameCount;
Eric Laurentf14db3c2017-12-08 14:20:36 -08008321 size_t notificationFrameCount = *pNotificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08008322 sp<RecordTrack> track;
8323 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07008324 audio_input_flags_t inputFlags = mInput->flags;
Eric Laurentf14db3c2017-12-08 14:20:36 -08008325 audio_input_flags_t requestedFlags = *flags;
8326 uint32_t sampleRate;
Svet Ganov33761132021-05-13 22:51:08 +00008327 AttributionSourceState checkedAttributionSource = AudioFlinger::checkAttributionSourcePackage(
8328 attributionSource);
Eric Laurentf14db3c2017-12-08 14:20:36 -08008329
8330 lStatus = initCheck();
8331 if (lStatus != NO_ERROR) {
8332 ALOGE("createRecordTrack_l() audio driver not initialized");
8333 goto Exit;
8334 }
8335
Mikhail Naganovce9f2652018-07-16 11:09:24 -07008336 if (!audio_is_linear_pcm(mFormat) && (*flags & AUDIO_INPUT_FLAG_DIRECT) == 0) {
8337 ALOGE("createRecordTrack_l() on an encoded stream requires AUDIO_INPUT_FLAG_DIRECT");
8338 lStatus = BAD_VALUE;
8339 goto Exit;
8340 }
8341
Eric Laurentec376dc2021-04-08 20:41:22 +02008342 if (maxSharedAudioHistoryMs != 0) {
Svet Ganov33761132021-05-13 22:51:08 +00008343 if (!captureHotwordAllowed(checkedAttributionSource)) {
Eric Laurentec376dc2021-04-08 20:41:22 +02008344 lStatus = PERMISSION_DENIED;
8345 goto Exit;
8346 }
Eric Laurentec376dc2021-04-08 20:41:22 +02008347 if (maxSharedAudioHistoryMs < 0
8348 || maxSharedAudioHistoryMs > AudioFlinger::kMaxSharedAudioHistoryMs) {
8349 lStatus = BAD_VALUE;
8350 goto Exit;
8351 }
8352 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08008353 if (*pSampleRate == 0) {
8354 *pSampleRate = mSampleRate;
8355 }
8356 sampleRate = *pSampleRate;
Eric Laurent05067782016-06-01 18:27:28 -07008357
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008358 // special case for FAST flag considered OK if fast capture is present and access to
8359 // audio history is not required
8360 if (hasFastCapture() && mMaxSharedAudioHistoryMs == 0) {
Eric Laurent05067782016-06-01 18:27:28 -07008361 inputFlags = (audio_input_flags_t)(inputFlags | AUDIO_INPUT_FLAG_FAST);
8362 }
8363
Eric Laurentf14db3c2017-12-08 14:20:36 -08008364 // Check if requested flags are compatible with input stream flags
Eric Laurent05067782016-06-01 18:27:28 -07008365 if ((*flags & inputFlags) != *flags) {
8366 ALOGW("createRecordTrack_l(): mismatch between requested flags (%08x) and"
8367 " input flags (%08x)",
8368 *flags, inputFlags);
8369 *flags = (audio_input_flags_t)(*flags & inputFlags);
8370 }
Eric Laurent81784c32012-11-19 14:55:58 -08008371
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008372 // client expresses a preference for FAST and no access to audio history,
8373 // but we get the final say
8374 if (*flags & AUDIO_INPUT_FLAG_FAST && maxSharedAudioHistoryMs == 0) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07008375 if (
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07008376 // we formerly checked for a callback handler (non-0 tid),
8377 // but that is no longer required for TRANSFER_OBTAIN mode
jiabinb00edc32021-08-16 16:27:54 +00008378 // No need to match hardware format, format conversion will be done in client side.
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07008379 //
Phil Burk7ed66a12019-04-18 13:20:30 -07008380 // Frame count is not specified (0), or is less than or equal the pipe depth.
8381 // It is OK to provide a higher capacity than requested.
8382 // We will force it to mPipeFramesP2 below.
8383 (frameCount <= mPipeFramesP2) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07008384 // PCM data
8385 audio_is_linear_pcm(format) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08008386 // hardware channel mask
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008387 (channelMask == mChannelMask) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08008388 // hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07008389 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07008390 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008391 hasFastCapture() &&
8392 // there are sufficient fast track slots available
8393 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07008394 ) {
Eric Laurent4c415062016-06-17 16:14:16 -07008395 // check compatibility with audio effects.
8396 Mutex::Autolock _l(mLock);
8397 // Do not accept FAST flag if the session has software effects
8398 sp<EffectChain> chain = getEffectChain_l(sessionId);
8399 if (chain != 0) {
Andy Hungd3bb0ad2016-10-11 17:16:43 -07008400 audio_input_flags_t old = *flags;
8401 chain->checkInputFlagCompatibility(flags);
8402 if (old != *flags) {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008403 ALOGV("%p AUDIO_INPUT_FLAGS denied by effect old=%#x new=%#x",
8404 this, (int)old, (int)*flags);
Eric Laurent4c415062016-06-17 16:14:16 -07008405 }
8406 }
Eric Laurent122f7e72016-06-29 11:53:29 -07008407 ALOGV_IF((*flags & AUDIO_INPUT_FLAG_FAST) != 0,
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008408 "%p AUDIO_INPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
8409 this, frameCount, mFrameCount);
Glenn Kasten90e58b12013-07-31 16:16:02 -07008410 } else {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008411 ALOGV("%p AUDIO_INPUT_FLAG_FAST denied: frameCount=%zu mFrameCount=%zu mPipeFramesP2=%zu "
8412 "format=%#x isLinear=%d mFormat=%#x channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008413 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008414 this, frameCount, mFrameCount, mPipeFramesP2,
8415 format, audio_is_linear_pcm(format), mFormat, channelMask, sampleRate, mSampleRate,
Glenn Kasten74105912014-07-03 12:28:53 -07008416 hasFastCapture(), tid, mFastTrackAvail);
Eric Laurent05067782016-06-01 18:27:28 -07008417 *flags = (audio_input_flags_t)(*flags & ~AUDIO_INPUT_FLAG_FAST);
Glenn Kasten74105912014-07-03 12:28:53 -07008418 }
8419 }
8420
Eric Laurentf14db3c2017-12-08 14:20:36 -08008421 // If FAST or RAW flags were corrected, ask caller to request new input from audio policy
8422 if ((*flags & AUDIO_INPUT_FLAG_FAST) !=
8423 (requestedFlags & AUDIO_INPUT_FLAG_FAST)) {
8424 *flags = (audio_input_flags_t) (*flags & ~(AUDIO_INPUT_FLAG_FAST | AUDIO_INPUT_FLAG_RAW));
8425 lStatus = BAD_TYPE;
8426 goto Exit;
8427 }
8428
Glenn Kasten74105912014-07-03 12:28:53 -07008429 // compute track buffer size in frames, and suggest the notification frame count
Eric Laurent05067782016-06-01 18:27:28 -07008430 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten74105912014-07-03 12:28:53 -07008431 // fast track: frame count is exactly the pipe depth
8432 frameCount = mPipeFramesP2;
8433 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
Eric Laurentf14db3c2017-12-08 14:20:36 -08008434 notificationFrameCount = mFrameCount;
Glenn Kasten74105912014-07-03 12:28:53 -07008435 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07008436 // not fast track: max notification period is resampled equivalent of one HAL buffer time
8437 // or 20 ms if there is a fast capture
8438 // TODO This could be a roundupRatio inline, and const
8439 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
8440 * sampleRate + mSampleRate - 1) / mSampleRate;
8441 // minimum number of notification periods is at least kMinNotifications,
8442 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
8443 static const size_t kMinNotifications = 3;
8444 static const uint32_t kMinMs = 30;
8445 // TODO This could be a roundupRatio inline
8446 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
8447 // TODO This could be a roundupRatio inline
8448 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
8449 maxNotificationFrames;
8450 const size_t minFrameCount = maxNotificationFrames *
8451 max(kMinNotifications, minNotificationsByMs);
8452 frameCount = max(frameCount, minFrameCount);
Eric Laurentf14db3c2017-12-08 14:20:36 -08008453 if (notificationFrameCount == 0 || notificationFrameCount > maxNotificationFrames) {
8454 notificationFrameCount = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07008455 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07008456 }
Glenn Kasten74935e42013-12-19 08:56:45 -08008457 *pFrameCount = frameCount;
Eric Laurentf14db3c2017-12-08 14:20:36 -08008458 *pNotificationFrameCount = notificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08008459
8460 { // scope for mLock
8461 Mutex::Autolock _l(mLock);
Eric Laurent2407ce32021-04-26 14:56:03 +02008462 int32_t startFrames = -1;
Eric Laurentec376dc2021-04-08 20:41:22 +02008463 if (!mSharedAudioPackageName.empty()
Svet Ganov33761132021-05-13 22:51:08 +00008464 && mSharedAudioPackageName == checkedAttributionSource.packageName
Eric Laurentec376dc2021-04-08 20:41:22 +02008465 && mSharedAudioSessionId == sessionId
Svet Ganov33761132021-05-13 22:51:08 +00008466 && captureHotwordAllowed(checkedAttributionSource)) {
Eric Laurent2407ce32021-04-26 14:56:03 +02008467 startFrames = mSharedAudioStartFrames;
Eric Laurentec376dc2021-04-08 20:41:22 +02008468 }
Eric Laurent81784c32012-11-19 14:55:58 -08008469
Kevin Rocard1f564ac2018-03-29 13:53:10 -07008470 track = new RecordTrack(this, client, attr, sampleRate,
Andy Hung8fe68032017-06-05 16:17:51 -07008471 format, channelMask, frameCount,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07008472 nullptr /* buffer */, (size_t)0 /* bufferSize */, sessionId, creatorPid,
Svet Ganov33761132021-05-13 22:51:08 +00008473 checkedAttributionSource, *flags, TrackBase::TYPE_DEFAULT, portId,
8474 startFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08008475
Glenn Kasten03003332013-08-06 15:40:54 -07008476 lStatus = track->initCheck();
8477 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07008478 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08008479 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08008480 goto Exit;
8481 }
8482 mTracks.add(track);
8483
Eric Laurent05067782016-06-01 18:27:28 -07008484 if ((*flags & AUDIO_INPUT_FLAG_FAST) && (tid != -1)) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07008485 pid_t callingPid = IPCThreadState::self()->getCallingPid();
8486 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
8487 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07008488 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Glenn Kasten90e58b12013-07-31 16:16:02 -07008489 }
Eric Laurentec376dc2021-04-08 20:41:22 +02008490
8491 if (maxSharedAudioHistoryMs != 0) {
8492 sendResizeBufferConfigEvent_l(maxSharedAudioHistoryMs);
8493 }
Eric Laurent81784c32012-11-19 14:55:58 -08008494 }
Glenn Kasten05997e22014-03-13 15:08:33 -07008495
Eric Laurent81784c32012-11-19 14:55:58 -08008496 lStatus = NO_ERROR;
8497
8498Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07008499 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08008500 return track;
8501}
8502
8503status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
8504 AudioSystem::sync_event_t event,
Glenn Kastend848eb42016-03-08 13:42:11 -08008505 audio_session_t triggerSession)
Eric Laurent81784c32012-11-19 14:55:58 -08008506{
8507 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
8508 sp<ThreadBase> strongMe = this;
8509 status_t status = NO_ERROR;
8510
8511 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08008512 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08008513 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008514 recordTrack->mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
Eric Laurent81784c32012-11-19 14:55:58 -08008515 triggerSession,
8516 recordTrack->sessionId(),
8517 syncStartEventCallback,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008518 recordTrack);
Eric Laurent81784c32012-11-19 14:55:58 -08008519 // Sync event can be cancelled by the trigger session if the track is not in a
8520 // compatible state in which case we start record immediately
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008521 if (recordTrack->mSyncStartEvent->isCancelled()) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08008522 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08008523 } else {
8524 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
Ivan Lozano1b35dd62017-12-06 16:55:10 -08008525 recordTrack->mFramesToDrop = -(ssize_t)
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08008526 ((AudioSystem::kSyncRecordStartTimeOutMs * recordTrack->mSampleRate) / 1000);
Eric Laurent81784c32012-11-19 14:55:58 -08008527 }
8528 }
8529
8530 {
Glenn Kasten47c20702013-08-13 15:37:35 -07008531 // This section is a rendezvous between binder thread executing start() and RecordThread
Eric Laurent81784c32012-11-19 14:55:58 -08008532 AutoMutex lock(mLock);
Andy Hungce685402018-10-05 17:23:27 -07008533 if (recordTrack->isInvalid()) {
8534 recordTrack->clearSyncStartEvent();
Eric Laurentd52a28c2020-08-21 17:10:39 -07008535 ALOGW("%s track %d: invalidated before startInput", __func__, recordTrack->portId());
8536 return DEAD_OBJECT;
Andy Hungce685402018-10-05 17:23:27 -07008537 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008538 if (mActiveTracks.indexOf(recordTrack) >= 0) {
8539 if (recordTrack->mState == TrackBase::PAUSING) {
Andy Hungce685402018-10-05 17:23:27 -07008540 // We haven't stopped yet (moved to PAUSED and not in mActiveTracks)
8541 // so no need to startInput().
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008542 ALOGV("active record track PAUSING -> ACTIVE");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008543 recordTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008544 } else {
Andy Hung959b5b82021-09-24 10:46:20 -07008545 ALOGV("active record track state %d", (int)recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08008546 }
8547 return status;
8548 }
8549
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08008550 // TODO consider other ways of handling this, such as changing the state to :STARTING and
8551 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
8552 // or using a separate command thread
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008553 recordTrack->mState = TrackBase::STARTING_1;
Glenn Kasten2b806402013-11-20 16:37:38 -08008554 mActiveTracks.add(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07008555 status_t status = NO_ERROR;
8556 if (recordTrack->isExternalTrack()) {
8557 mLock.unlock();
Eric Laurent4eb58f12018-12-07 16:41:02 -08008558 status = AudioSystem::startInput(recordTrack->portId());
Eric Laurent83b88082014-06-20 18:31:16 -07008559 mLock.lock();
Andy Hungce685402018-10-05 17:23:27 -07008560 if (recordTrack->isInvalid()) {
8561 recordTrack->clearSyncStartEvent();
8562 if (status == NO_ERROR && recordTrack->mState == TrackBase::STARTING_1) {
8563 recordTrack->mState = TrackBase::STARTING_2;
8564 // STARTING_2 forces destroy to call stopInput.
8565 }
Eric Laurentd52a28c2020-08-21 17:10:39 -07008566 ALOGW("%s track %d: invalidated after startInput", __func__, recordTrack->portId());
8567 return DEAD_OBJECT;
Andy Hungce685402018-10-05 17:23:27 -07008568 }
8569 if (recordTrack->mState != TrackBase::STARTING_1) {
8570 ALOGW("%s(%d): unsynchronized mState:%d change",
Andy Hung959b5b82021-09-24 10:46:20 -07008571 __func__, recordTrack->id(), (int)recordTrack->mState);
Andy Hungce685402018-10-05 17:23:27 -07008572 // Someone else has changed state, let them take over,
8573 // leave mState in the new state.
8574 recordTrack->clearSyncStartEvent();
8575 return INVALID_OPERATION;
8576 }
8577 // we're ok, but perhaps startInput has failed
Eric Laurent83b88082014-06-20 18:31:16 -07008578 if (status != NO_ERROR) {
Andy Hungce685402018-10-05 17:23:27 -07008579 ALOGW("%s(%d): startInput failed, status %d",
8580 __func__, recordTrack->id(), status);
8581 // We are in ActiveTracks if STARTING_1 and valid, so remove from ActiveTracks,
8582 // leave in STARTING_1, so destroy() will not call stopInput.
Eric Laurent83b88082014-06-20 18:31:16 -07008583 mActiveTracks.remove(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07008584 recordTrack->clearSyncStartEvent();
Eric Laurent83b88082014-06-20 18:31:16 -07008585 return status;
8586 }
Eric Laurent09f1ed22019-04-24 17:45:17 -07008587 sendIoConfigEvent_l(
8588 AUDIO_CLIENT_STARTED, recordTrack->creatorPid(), recordTrack->portId());
Eric Laurent81784c32012-11-19 14:55:58 -08008589 }
Andy Hungc2b11cb2020-04-22 09:04:01 -07008590
8591 recordTrack->logBeginInterval(patchSourcesToString(&mPatch)); // log to MediaMetrics
8592
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008593 // Catch up with current buffer indices if thread is already running.
8594 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
8595 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
8596 // see previously buffered data before it called start(), but with greater risk of overrun.
8597
Andy Hung73c02e42015-03-29 01:13:58 -07008598 recordTrack->mResamplerBufferProvider->reset();
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008599 if (!recordTrack->isDirect()) {
8600 // clear any converter state as new data will be discontinuous
8601 recordTrack->mRecordBufferConverter->reset();
8602 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008603 recordTrack->mState = TrackBase::STARTING_2;
Eric Laurent81784c32012-11-19 14:55:58 -08008604 // signal thread to start
Eric Laurent81784c32012-11-19 14:55:58 -08008605 mWaitWorkCV.broadcast();
Eric Laurent81784c32012-11-19 14:55:58 -08008606 return status;
8607 }
Eric Laurent81784c32012-11-19 14:55:58 -08008608}
8609
Eric Laurent81784c32012-11-19 14:55:58 -08008610void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
8611{
8612 sp<SyncEvent> strongEvent = event.promote();
8613
8614 if (strongEvent != 0) {
Eric Laurent8ea16e42014-02-20 16:26:11 -08008615 sp<RefBase> ptr = strongEvent->cookie().promote();
8616 if (ptr != 0) {
8617 RecordTrack *recordTrack = (RecordTrack *)ptr.get();
8618 recordTrack->handleSyncStartEvent(strongEvent);
8619 }
Eric Laurent81784c32012-11-19 14:55:58 -08008620 }
8621}
8622
Glenn Kastena8356f62013-07-25 14:37:52 -07008623bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08008624 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07008625 AutoMutex _l(mLock);
Andy Hungce685402018-10-05 17:23:27 -07008626 // if we're invalid, we can't be on the ActiveTracks.
Jean-Michel Trivi38f86712017-04-11 14:10:17 -07008627 if (mActiveTracks.indexOf(recordTrack) < 0 || recordTrack->mState == TrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08008628 return false;
8629 }
Glenn Kasten47c20702013-08-13 15:37:35 -07008630 // note that threadLoop may still be processing the track at this point [without lock]
Eric Laurent81784c32012-11-19 14:55:58 -08008631 recordTrack->mState = TrackBase::PAUSING;
Andy Hungce685402018-10-05 17:23:27 -07008632
Andy Hungabfab202019-03-07 19:45:54 -08008633 // NOTE: Waiting here is important to keep stop synchronous.
8634 // This is needed for proper patchRecord peer release.
Andy Hungce685402018-10-05 17:23:27 -07008635 while (recordTrack->mState == TrackBase::PAUSING && !recordTrack->isInvalid()) {
8636 mWaitWorkCV.broadcast(); // signal thread to stop
8637 mStartStopCond.wait(mLock);
Eric Laurent81784c32012-11-19 14:55:58 -08008638 }
Andy Hungce685402018-10-05 17:23:27 -07008639
8640 if (recordTrack->mState == TrackBase::PAUSED) { // successful stop
Eric Laurent81784c32012-11-19 14:55:58 -08008641 ALOGV("Record stopped OK");
8642 return true;
8643 }
Andy Hungce685402018-10-05 17:23:27 -07008644
8645 // don't handle anything - we've been invalidated or restarted and in a different state
8646 ALOGW_IF("%s(%d): unsynchronized stop, state: %d",
8647 __func__, recordTrack->id(), recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08008648 return false;
8649}
8650
Glenn Kasten0f11b512014-01-31 16:18:54 -08008651bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
Eric Laurent81784c32012-11-19 14:55:58 -08008652{
8653 return false;
8654}
8655
Glenn Kasten0f11b512014-01-31 16:18:54 -08008656status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08008657{
8658#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
8659 if (!isValidSyncEvent(event)) {
8660 return BAD_VALUE;
8661 }
8662
Glenn Kastend848eb42016-03-08 13:42:11 -08008663 audio_session_t eventSession = event->triggerSession();
Eric Laurent81784c32012-11-19 14:55:58 -08008664 status_t ret = NAME_NOT_FOUND;
8665
8666 Mutex::Autolock _l(mLock);
8667
8668 for (size_t i = 0; i < mTracks.size(); i++) {
8669 sp<RecordTrack> track = mTracks[i];
8670 if (eventSession == track->sessionId()) {
8671 (void) track->setSyncEvent(event);
8672 ret = NO_ERROR;
8673 }
8674 }
8675 return ret;
8676#else
8677 return BAD_VALUE;
8678#endif
8679}
8680
jiabin653cc0a2018-01-17 17:54:10 -08008681status_t AudioFlinger::RecordThread::getActiveMicrophones(
8682 std::vector<media::MicrophoneInfo>* activeMicrophones)
8683{
8684 ALOGV("RecordThread::getActiveMicrophones");
8685 AutoMutex _l(mLock);
Jasmine Chaeaa10e42021-05-11 10:11:14 +08008686 if (!isStreamInitialized()) {
Paul McLean8a661a32021-04-12 10:21:42 -06008687 return NO_INIT;
8688 }
jiabin9ff780e2018-03-19 18:19:52 -07008689 status_t status = mInput->stream->getActiveMicrophones(activeMicrophones);
8690 return status;
jiabin653cc0a2018-01-17 17:54:10 -08008691}
8692
Paul McLean12340082019-03-19 09:35:05 -06008693status_t AudioFlinger::RecordThread::setPreferredMicrophoneDirection(
8694 audio_microphone_direction_t direction)
Paul McLean03a6e6a2018-12-04 10:54:13 -07008695{
Paul McLean12340082019-03-19 09:35:05 -06008696 ALOGV("setPreferredMicrophoneDirection(%d)", direction);
Paul McLean03a6e6a2018-12-04 10:54:13 -07008697 AutoMutex _l(mLock);
Jasmine Chaeaa10e42021-05-11 10:11:14 +08008698 if (!isStreamInitialized()) {
Paul McLean8a661a32021-04-12 10:21:42 -06008699 return NO_INIT;
8700 }
Paul McLean12340082019-03-19 09:35:05 -06008701 return mInput->stream->setPreferredMicrophoneDirection(direction);
Paul McLean03a6e6a2018-12-04 10:54:13 -07008702}
8703
Paul McLean12340082019-03-19 09:35:05 -06008704status_t AudioFlinger::RecordThread::setPreferredMicrophoneFieldDimension(float zoom)
Paul McLean03a6e6a2018-12-04 10:54:13 -07008705{
Paul McLean12340082019-03-19 09:35:05 -06008706 ALOGV("setPreferredMicrophoneFieldDimension(%f)", zoom);
Paul McLean03a6e6a2018-12-04 10:54:13 -07008707 AutoMutex _l(mLock);
Jasmine Chaeaa10e42021-05-11 10:11:14 +08008708 if (!isStreamInitialized()) {
Paul McLean8a661a32021-04-12 10:21:42 -06008709 return NO_INIT;
8710 }
Paul McLean12340082019-03-19 09:35:05 -06008711 return mInput->stream->setPreferredMicrophoneFieldDimension(zoom);
Paul McLean03a6e6a2018-12-04 10:54:13 -07008712}
8713
Eric Laurentec376dc2021-04-08 20:41:22 +02008714status_t AudioFlinger::RecordThread::shareAudioHistory(
8715 const std::string& sharedAudioPackageName, audio_session_t sharedSessionId,
8716 int64_t sharedAudioStartMs) {
8717 AutoMutex _l(mLock);
8718 return shareAudioHistory_l(sharedAudioPackageName, sharedSessionId, sharedAudioStartMs);
8719}
8720
8721status_t AudioFlinger::RecordThread::shareAudioHistory_l(
8722 const std::string& sharedAudioPackageName, audio_session_t sharedSessionId,
8723 int64_t sharedAudioStartMs) {
Eric Laurent92d0a322021-07-16 15:32:33 +02008724
Eric Laurentec376dc2021-04-08 20:41:22 +02008725 if ((hasAudioSession_l(sharedSessionId) & ThreadBase::TRACK_SESSION) == 0) {
8726 return BAD_VALUE;
8727 }
Eric Laurent2407ce32021-04-26 14:56:03 +02008728
8729 if (sharedAudioStartMs < 0
8730 || sharedAudioStartMs > INT64_MAX / mSampleRate) {
Eric Laurentec376dc2021-04-08 20:41:22 +02008731 return BAD_VALUE;
8732 }
8733
Eric Laurent2407ce32021-04-26 14:56:03 +02008734 // Current implementation of the input resampling buffer wraps around indexes at 32 bit.
8735 // As we cannot detect more than one wraparound, only accept values up current write position
8736 // after one wraparound
8737 // We assume recent wraparounds on mRsmpInRear only given it is unlikely that the requesting
8738 // app waits several hours after the start time was computed.
Eric Laurent92d0a322021-07-16 15:32:33 +02008739 int64_t sharedAudioStartFrames = sharedAudioStartMs * mSampleRate / 1000;
Eric Laurent2407ce32021-04-26 14:56:03 +02008740 const int32_t sharedOffset = audio_utils::safe_sub_overflow(mRsmpInRear,
8741 (int32_t)sharedAudioStartFrames);
Eric Laurent92d0a322021-07-16 15:32:33 +02008742 // Bring the start frame position within the input buffer to match the documented
8743 // "best effort" behavior of the API.
8744 if (sharedOffset < 0) {
8745 sharedAudioStartFrames = mRsmpInRear;
8746 } else if (sharedOffset > mRsmpInFrames) {
8747 sharedAudioStartFrames =
8748 audio_utils::safe_sub_overflow(mRsmpInRear, (int32_t)mRsmpInFrames);
Eric Laurent2407ce32021-04-26 14:56:03 +02008749 }
8750
Eric Laurentec376dc2021-04-08 20:41:22 +02008751 mSharedAudioPackageName = sharedAudioPackageName;
8752 if (mSharedAudioPackageName.empty()) {
Eric Laurent92d0a322021-07-16 15:32:33 +02008753 resetAudioHistory_l();
Eric Laurentec376dc2021-04-08 20:41:22 +02008754 } else {
8755 mSharedAudioSessionId = sharedSessionId;
Eric Laurent2407ce32021-04-26 14:56:03 +02008756 mSharedAudioStartFrames = (int32_t)sharedAudioStartFrames;
Eric Laurentec376dc2021-04-08 20:41:22 +02008757 }
8758 return NO_ERROR;
8759}
8760
Eric Laurent92d0a322021-07-16 15:32:33 +02008761void AudioFlinger::RecordThread::resetAudioHistory_l() {
8762 mSharedAudioSessionId = AUDIO_SESSION_NONE;
8763 mSharedAudioStartFrames = -1;
8764 mSharedAudioPackageName = "";
8765}
8766
Kevin Rocard069c2712018-03-29 19:09:14 -07008767void AudioFlinger::RecordThread::updateMetadata_l()
8768{
Jasmine Chaeaa10e42021-05-11 10:11:14 +08008769 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
8770 return; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -07008771 }
8772 StreamInHalInterface::SinkMetadata metadata;
8773 for (const sp<RecordTrack> &track : mActiveTracks) {
Eric Laurentb9cc0ab2021-01-29 11:46:52 +01008774 // Do not forward PatchRecord metadata to audio HAL
8775 if (track->isPatchTrack()) {
8776 continue;
8777 }
Kevin Rocard069c2712018-03-29 19:09:14 -07008778 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurent94579172020-11-20 18:41:04 +01008779 record_track_metadata_v7_t trackMetadata;
8780 trackMetadata.base = {
Kevin Rocard069c2712018-03-29 19:09:14 -07008781 .source = track->attributes().source,
8782 .gain = 1, // capture tracks do not have volumes
Eric Laurent94579172020-11-20 18:41:04 +01008783 };
8784 trackMetadata.channel_mask = track->channelMask(),
8785 strncpy(trackMetadata.tags, track->attributes().tags, AUDIO_ATTRIBUTES_TAGS_MAX_SIZE);
8786
8787 metadata.tracks.push_back(trackMetadata);
Kevin Rocard069c2712018-03-29 19:09:14 -07008788 }
8789 mInput->stream->updateSinkMetadata(metadata);
8790}
8791
Eric Laurent81784c32012-11-19 14:55:58 -08008792// destroyTrack_l() must be called with ThreadBase::mLock held
8793void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
8794{
Eric Laurentbfb1b832013-01-07 09:53:42 -08008795 track->terminate();
8796 track->mState = TrackBase::STOPPED;
Eric Laurentec376dc2021-04-08 20:41:22 +02008797
Eric Laurent81784c32012-11-19 14:55:58 -08008798 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08008799 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08008800 removeTrack_l(track);
8801 }
8802}
8803
8804void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
8805{
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008806 String8 result;
8807 track->appendDump(result, false /* active */);
8808 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.string());
8809
Eric Laurent81784c32012-11-19 14:55:58 -08008810 mTracks.remove(track);
8811 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008812 if (track->isFastTrack()) {
8813 ALOG_ASSERT(!mFastTrackAvail);
8814 mFastTrackAvail = true;
8815 }
Eric Laurent81784c32012-11-19 14:55:58 -08008816}
8817
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07008818void AudioFlinger::RecordThread::dumpInternals_l(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08008819{
Mikhail Naganov913d06c2016-11-01 12:49:22 -07008820 AudioStreamIn *input = mInput;
8821 audio_input_flags_t flags = input != NULL ? input->flags : AUDIO_INPUT_FLAG_NONE;
8822 dprintf(fd, " AudioStreamIn: %p flags %#x (%s)\n",
Andy Hung9b181952019-02-25 14:53:36 -08008823 input, flags, toString(flags).c_str());
Andy Hung6427e442018-08-09 12:51:02 -07008824 dprintf(fd, " Frames read: %lld\n", (long long)mFramesRead);
Eric Tan39ec8d62018-07-24 09:49:29 -07008825 if (mActiveTracks.isEmpty()) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07008826 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08008827 }
Andy Hungbfa64962017-06-12 14:43:19 -07008828
8829 if (input != nullptr) {
8830 dprintf(fd, " Hal stream dump:\n");
8831 (void)input->stream->dump(fd);
8832 }
8833
Glenn Kasten6e6704c2014-07-03 10:20:00 -07008834 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008835 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Glenn Kasten17c9c992015-03-02 15:53:01 -08008836
Glenn Kasten2f90c512015-12-02 11:40:09 -08008837 // Make a non-atomic copy of fast capture dump state so it won't change underneath us
8838 // while we are dumping it. It may be inconsistent, but it won't mutate!
8839 // This is a large object so we place it on the heap.
8840 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
Eric Tan2942a4e2018-09-12 17:41:27 -07008841 const std::unique_ptr<FastCaptureDumpState> copy =
8842 std::make_unique<FastCaptureDumpState>(mFastCaptureDumpState);
Glenn Kasten2f90c512015-12-02 11:40:09 -08008843 copy->dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08008844}
8845
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07008846void AudioFlinger::RecordThread::dumpTracks_l(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08008847{
Eric Laurent81784c32012-11-19 14:55:58 -08008848 String8 result;
Marco Nelissenb2208842014-02-07 14:00:50 -08008849 size_t numtracks = mTracks.size();
8850 size_t numactive = mActiveTracks.size();
8851 size_t numactiveseen = 0;
Glenn Kastenc42e9b42016-03-21 11:35:03 -07008852 dprintf(fd, " %zu Tracks", numtracks);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008853 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08008854 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07008855 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008856 result.append(prefix);
Andy Hung000adb52018-06-01 15:43:26 -07008857 mTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08008858 for (size_t i = 0; i < numtracks ; ++i) {
8859 sp<RecordTrack> track = mTracks[i];
8860 if (track != 0) {
8861 bool active = mActiveTracks.indexOf(track) >= 0;
8862 if (active) {
8863 numactiveseen++;
8864 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008865 result.append(prefix);
8866 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08008867 }
Eric Laurent81784c32012-11-19 14:55:58 -08008868 }
Marco Nelissenb2208842014-02-07 14:00:50 -08008869 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07008870 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08008871 }
8872
Marco Nelissenb2208842014-02-07 14:00:50 -08008873 if (numactiveseen != numactive) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008874 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08008875 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008876 result.append(prefix);
Andy Hung000adb52018-06-01 15:43:26 -07008877 mActiveTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08008878 for (size_t i = 0; i < numactive; ++i) {
Glenn Kasten2b806402013-11-20 16:37:38 -08008879 sp<RecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08008880 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008881 result.append(prefix);
8882 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08008883 }
Glenn Kasten2b806402013-11-20 16:37:38 -08008884 }
Eric Laurent81784c32012-11-19 14:55:58 -08008885
8886 }
8887 write(fd, result.string(), result.size());
8888}
8889
Eric Laurent5ada82e2019-08-29 17:53:54 -07008890void AudioFlinger::RecordThread::setRecordSilenced(audio_port_handle_t portId, bool silenced)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008891{
8892 Mutex::Autolock _l(mLock);
8893 for (size_t i = 0; i < mTracks.size() ; i++) {
8894 sp<RecordTrack> track = mTracks[i];
Eric Laurent5ada82e2019-08-29 17:53:54 -07008895 if (track != 0 && track->portId() == portId) {
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008896 track->setSilenced(silenced);
8897 }
8898 }
8899}
Andy Hung73c02e42015-03-29 01:13:58 -07008900
8901void AudioFlinger::RecordThread::ResamplerBufferProvider::reset()
8902{
8903 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
8904 RecordThread *recordThread = (RecordThread *) threadBase.get();
Andy Hung73c02e42015-03-29 01:13:58 -07008905 mRsmpInUnrel = 0;
Eric Laurentec376dc2021-04-08 20:41:22 +02008906 const int32_t rear = recordThread->mRsmpInRear;
8907 ssize_t deltaFrames = 0;
Eric Laurent2407ce32021-04-26 14:56:03 +02008908 if (mRecordTrack->startFrames() >= 0) {
8909 int32_t startFrames = mRecordTrack->startFrames();
8910 // Accept a recent wraparound of mRsmpInRear
8911 if (startFrames <= rear) {
8912 deltaFrames = rear - startFrames;
8913 } else {
8914 deltaFrames = (int32_t)((int64_t)rear + UINT32_MAX + 1 - startFrames);
Eric Laurentec376dc2021-04-08 20:41:22 +02008915 }
Eric Laurentec376dc2021-04-08 20:41:22 +02008916 // start frame cannot be further in the past than start of resampling buffer
8917 if ((size_t) deltaFrames > recordThread->mRsmpInFrames) {
8918 deltaFrames = recordThread->mRsmpInFrames;
8919 }
8920 }
8921 mRsmpInFront = audio_utils::safe_sub_overflow(rear, static_cast<int32_t>(deltaFrames));
Andy Hung73c02e42015-03-29 01:13:58 -07008922}
8923
8924void AudioFlinger::RecordThread::ResamplerBufferProvider::sync(
8925 size_t *framesAvailable, bool *hasOverrun)
8926{
8927 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
8928 RecordThread *recordThread = (RecordThread *) threadBase.get();
8929 const int32_t rear = recordThread->mRsmpInRear;
8930 const int32_t front = mRsmpInFront;
Hongwei Wang95e37682019-04-12 11:13:36 -07008931 const ssize_t filled = audio_utils::safe_sub_overflow(rear, front);
Andy Hung73c02e42015-03-29 01:13:58 -07008932
8933 size_t framesIn;
8934 bool overrun = false;
8935 if (filled < 0) {
8936 // should not happen, but treat like a massive overrun and re-sync
8937 framesIn = 0;
8938 mRsmpInFront = rear;
8939 overrun = true;
8940 } else if ((size_t) filled <= recordThread->mRsmpInFrames) {
8941 framesIn = (size_t) filled;
8942 } else {
8943 // client is not keeping up with server, but give it latest data
8944 framesIn = recordThread->mRsmpInFrames;
Hongwei Wang95e37682019-04-12 11:13:36 -07008945 mRsmpInFront = /* front = */ audio_utils::safe_sub_overflow(
8946 rear, static_cast<int32_t>(framesIn));
Andy Hung73c02e42015-03-29 01:13:58 -07008947 overrun = true;
8948 }
8949 if (framesAvailable != NULL) {
8950 *framesAvailable = framesIn;
8951 }
8952 if (hasOverrun != NULL) {
8953 *hasOverrun = overrun;
8954 }
8955}
8956
Eric Laurent81784c32012-11-19 14:55:58 -08008957// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008958status_t AudioFlinger::RecordThread::ResamplerBufferProvider::getNextBuffer(
Glenn Kastend79072e2016-01-06 08:41:20 -08008959 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08008960{
Andy Hung73c02e42015-03-29 01:13:58 -07008961 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008962 if (threadBase == 0) {
8963 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08008964 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008965 return NOT_ENOUGH_DATA;
8966 }
8967 RecordThread *recordThread = (RecordThread *) threadBase.get();
8968 int32_t rear = recordThread->mRsmpInRear;
Andy Hung73c02e42015-03-29 01:13:58 -07008969 int32_t front = mRsmpInFront;
Hongwei Wang95e37682019-04-12 11:13:36 -07008970 ssize_t filled = audio_utils::safe_sub_overflow(rear, front);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008971 // FIXME should not be P2 (don't want to increase latency)
8972 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08008973 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07008974 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008975
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008976 front &= recordThread->mRsmpInFramesP2 - 1;
8977 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07008978 if (part1 > (size_t) filled) {
8979 part1 = filled;
8980 }
8981 size_t ask = buffer->frameCount;
8982 ALOG_ASSERT(ask > 0);
8983 if (part1 > ask) {
8984 part1 = ask;
8985 }
8986 if (part1 == 0) {
Andy Hung73c02e42015-03-29 01:13:58 -07008987 // out of data is fine since the resampler will return a short-count.
Glenn Kasten85948432013-08-19 12:09:05 -07008988 buffer->raw = NULL;
8989 buffer->frameCount = 0;
Andy Hung73c02e42015-03-29 01:13:58 -07008990 mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07008991 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08008992 }
8993
Andy Hung57446612015-04-19 23:56:46 -07008994 buffer->raw = (uint8_t*)recordThread->mRsmpInBuffer + front * recordThread->mFrameSize;
Glenn Kasten85948432013-08-19 12:09:05 -07008995 buffer->frameCount = part1;
Andy Hung73c02e42015-03-29 01:13:58 -07008996 mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08008997 return NO_ERROR;
8998}
8999
9000// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009001void AudioFlinger::RecordThread::ResamplerBufferProvider::releaseBuffer(
9002 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08009003{
Hongwei Wang95e37682019-04-12 11:13:36 -07009004 int32_t stepCount = static_cast<int32_t>(buffer->frameCount);
Glenn Kasten85948432013-08-19 12:09:05 -07009005 if (stepCount == 0) {
9006 return;
9007 }
Andy Hung73c02e42015-03-29 01:13:58 -07009008 ALOG_ASSERT(stepCount <= mRsmpInUnrel);
9009 mRsmpInUnrel -= stepCount;
Hongwei Wang95e37682019-04-12 11:13:36 -07009010 mRsmpInFront = audio_utils::safe_add_overflow(mRsmpInFront, stepCount);
Glenn Kasten85948432013-08-19 12:09:05 -07009011 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08009012 buffer->frameCount = 0;
9013}
9014
Eric Laurentd8365c52017-07-16 15:27:05 -07009015void AudioFlinger::RecordThread::checkBtNrec()
9016{
9017 Mutex::Autolock _l(mLock);
9018 checkBtNrec_l();
9019}
9020
9021void AudioFlinger::RecordThread::checkBtNrec_l()
9022{
9023 // disable AEC and NS if the device is a BT SCO headset supporting those
9024 // pre processings
jiabinc52b1ff2019-10-31 17:20:42 -07009025 bool suspend = audio_is_bluetooth_sco_device(inDeviceType()) &&
Eric Laurentd8365c52017-07-16 15:27:05 -07009026 mAudioFlinger->btNrecIsOff();
9027 if (mBtNrecSuspended.exchange(suspend) != suspend) {
9028 for (size_t i = 0; i < mEffectChains.size(); i++) {
9029 setEffectSuspended_l(FX_IID_AEC, suspend, mEffectChains[i]->sessionId());
9030 setEffectSuspended_l(FX_IID_NS, suspend, mEffectChains[i]->sessionId());
9031 }
9032 }
9033}
9034
Andy Hung97a893e2015-03-29 01:03:07 -07009035
Eric Laurent10351942014-05-08 18:49:52 -07009036bool AudioFlinger::RecordThread::checkForNewParameter_l(const String8& keyValuePair,
9037 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08009038{
9039 bool reconfig = false;
9040
Eric Laurent10351942014-05-08 18:49:52 -07009041 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08009042
Eric Laurent10351942014-05-08 18:49:52 -07009043 audio_format_t reqFormat = mFormat;
9044 uint32_t samplingRate = mSampleRate;
Glenn Kastene1635ec2015-06-08 15:46:49 -07009045 // TODO this may change if we want to support capture from HDMI PCM multi channel (e.g on TVs).
Eric Laurent10351942014-05-08 18:49:52 -07009046 audio_channel_mask_t channelMask = audio_channel_in_mask_from_count(mChannelCount);
9047
9048 AudioParameter param = AudioParameter(keyValuePair);
9049 int value;
Haynes Mathew George9ce67b52015-09-30 11:40:47 -07009050
9051 // scope for AutoPark extends to end of method
9052 AutoPark<FastCapture> park(mFastCapture);
9053
Eric Laurent10351942014-05-08 18:49:52 -07009054 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
9055 // channel count change can be requested. Do we mandate the first client defines the
9056 // HAL sampling rate and channel count or do we allow changes on the fly?
9057 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
9058 samplingRate = value;
9059 reconfig = true;
9060 }
9061 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung97a893e2015-03-29 01:03:07 -07009062 if (!audio_is_linear_pcm((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07009063 status = BAD_VALUE;
9064 } else {
9065 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08009066 reconfig = true;
9067 }
Eric Laurent10351942014-05-08 18:49:52 -07009068 }
9069 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
9070 audio_channel_mask_t mask = (audio_channel_mask_t) value;
Andy Hungd330ee42015-04-20 13:23:41 -07009071 if (!audio_is_input_channel(mask) ||
Andy Hung936845a2021-06-08 00:09:06 -07009072 audio_channel_count_from_in_mask(mask) > FCC_LIMIT) {
Eric Laurent10351942014-05-08 18:49:52 -07009073 status = BAD_VALUE;
9074 } else {
9075 channelMask = mask;
9076 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08009077 }
Eric Laurent10351942014-05-08 18:49:52 -07009078 }
9079 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
9080 // do not accept frame count changes if tracks are open as the track buffer
9081 // size depends on frame count and correct behavior would not be guaranteed
9082 // if frame count is changed after track creation
9083 if (mActiveTracks.size() > 0) {
9084 status = INVALID_OPERATION;
9085 } else {
9086 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08009087 }
Eric Laurent10351942014-05-08 18:49:52 -07009088 }
9089 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07009090 LOG_FATAL("Should not set routing device in RecordThread");
Eric Laurent10351942014-05-08 18:49:52 -07009091 }
9092 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
9093 mAudioSource != (audio_source_t)value) {
jiabinc52b1ff2019-10-31 17:20:42 -07009094 LOG_FATAL("Should not set audio source in RecordThread");
Eric Laurent10351942014-05-08 18:49:52 -07009095 }
Glenn Kastene198c362013-08-13 09:13:36 -07009096
Eric Laurent10351942014-05-08 18:49:52 -07009097 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009098 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07009099 if (status == INVALID_OPERATION) {
9100 inputStandBy();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009101 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07009102 }
9103 if (reconfig) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009104 if (status == BAD_VALUE) {
Mikhail Naganov560637e2021-03-31 22:40:13 +00009105 audio_config_base_t config = AUDIO_CONFIG_BASE_INITIALIZER;
9106 if (mInput->stream->getAudioProperties(&config) == OK &&
9107 audio_is_linear_pcm(config.format) && audio_is_linear_pcm(reqFormat) &&
9108 config.sample_rate <= (AUDIO_RESAMPLER_DOWN_RATIO_MAX * samplingRate) &&
Andy Hung936845a2021-06-08 00:09:06 -07009109 audio_channel_count_from_in_mask(config.channel_mask) <= FCC_LIMIT) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009110 status = NO_ERROR;
9111 }
Eric Laurent81784c32012-11-19 14:55:58 -08009112 }
Eric Laurent10351942014-05-08 18:49:52 -07009113 if (status == NO_ERROR) {
9114 readInputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07009115 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08009116 }
9117 }
Eric Laurent81784c32012-11-19 14:55:58 -08009118 }
Eric Laurent10351942014-05-08 18:49:52 -07009119
Eric Laurent81784c32012-11-19 14:55:58 -08009120 return reconfig;
9121}
9122
9123String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
9124{
Eric Laurent81784c32012-11-19 14:55:58 -08009125 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009126 if (initCheck() == NO_ERROR) {
9127 String8 out_s8;
9128 if (mInput->stream->getParameters(keys, &out_s8) == OK) {
9129 return out_s8;
9130 }
Eric Laurent81784c32012-11-19 14:55:58 -08009131 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009132 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08009133}
9134
Mikhail Naganov88536df2021-07-26 17:30:29 -07009135void AudioFlinger::RecordThread::ioConfigChanged(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -07009136 audio_port_handle_t portId) {
Mikhail Naganov88536df2021-07-26 17:30:29 -07009137 sp<AudioIoDescriptor> desc;
Eric Laurent81784c32012-11-19 14:55:58 -08009138 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07009139 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07009140 case AUDIO_INPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07009141 case AUDIO_INPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07009142 desc = sp<AudioIoDescriptor>::make(mId, mPatch, true /*isInput*/,
9143 mSampleRate, mFormat, mChannelMask, mFrameCount, mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08009144 break;
Eric Laurent09f1ed22019-04-24 17:45:17 -07009145 case AUDIO_CLIENT_STARTED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07009146 desc = sp<AudioIoDescriptor>::make(mId, mPatch, portId);
Eric Laurent09f1ed22019-04-24 17:45:17 -07009147 break;
Eric Laurent73e26b62015-04-27 16:55:58 -07009148 case AUDIO_INPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08009149 default:
Mikhail Naganov88536df2021-07-26 17:30:29 -07009150 desc = sp<AudioIoDescriptor>::make(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08009151 break;
9152 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07009153 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08009154}
9155
Glenn Kastendeca2ae2014-02-07 10:25:56 -08009156void AudioFlinger::RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08009157{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009158 status_t result = mInput->stream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
9159 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
Andy Hung463be252014-07-10 16:56:07 -07009160 mFormat = mHALFormat;
Mikhail Naganovce9f2652018-07-16 11:09:24 -07009161 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
9162 if (audio_is_linear_pcm(mFormat)) {
Andy Hung936845a2021-06-08 00:09:06 -07009163 LOG_ALWAYS_FATAL_IF(mChannelCount > FCC_LIMIT, "HAL channel count %d > %d",
9164 mChannelCount, FCC_LIMIT);
Mikhail Naganovce9f2652018-07-16 11:09:24 -07009165 } else {
Andy Hung936845a2021-06-08 00:09:06 -07009166 // Can have more that FCC_LIMIT channels in encoded streams.
Mikhail Naganovce9f2652018-07-16 11:09:24 -07009167 ALOGI("HAL format %#x is not linear pcm", mFormat);
9168 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009169 result = mInput->stream->getFrameSize(&mFrameSize);
9170 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
Hayden Gomes1a89ab32020-06-12 11:05:47 -07009171 LOG_ALWAYS_FATAL_IF(mFrameSize <= 0, "Error frame size was %zu but must be greater than zero",
9172 mFrameSize);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009173 result = mInput->stream->getBufferSize(&mBufferSize);
9174 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
Glenn Kasten548efc92012-11-29 08:48:51 -08009175 mFrameCount = mBufferSize / mFrameSize;
Hayden Gomes1a89ab32020-06-12 11:05:47 -07009176 ALOGV("%p RecordThread params: mChannelCount=%u, mFormat=%#x, mFrameSize=%zu, "
9177 "mBufferSize=%zu, mFrameCount=%zu",
9178 this, mChannelCount, mFormat, mFrameSize, mBufferSize, mFrameCount);
Glenn Kasten49d00ad2014-07-21 11:22:03 -07009179
Eric Laurentec376dc2021-04-08 20:41:22 +02009180 // mRsmpInFrames must be 0 before calling resizeInputBuffer_l for the first time
9181 mRsmpInFrames = 0;
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009182 resizeInputBuffer_l(0 /*maxSharedAudioHistoryMs*/);
Eric Laurent81784c32012-11-19 14:55:58 -08009183
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08009184 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
9185 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Andy Hungea840382020-05-05 21:50:17 -07009186
9187 audio_input_flags_t flags = mInput->flags;
9188 mediametrics::LogItem item(mThreadMetrics.getMetricsId());
9189 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
9190 .set(AMEDIAMETRICS_PROP_ENCODING, formatToString(mFormat).c_str())
9191 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
9192 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
9193 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
9194 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
9195 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mFrameCount)
9196 .record();
Eric Laurent81784c32012-11-19 14:55:58 -08009197}
9198
Glenn Kasten5f972c02014-01-13 09:59:31 -08009199uint32_t AudioFlinger::RecordThread::getInputFramesLost()
Eric Laurent81784c32012-11-19 14:55:58 -08009200{
9201 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009202 uint32_t result;
9203 if (initCheck() == NO_ERROR && mInput->stream->getInputFramesLost(&result) == OK) {
9204 return result;
Eric Laurent81784c32012-11-19 14:55:58 -08009205 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009206 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08009207}
9208
Glenn Kastend848eb42016-03-08 13:42:11 -08009209KeyedVector<audio_session_t, bool> AudioFlinger::RecordThread::sessionIds() const
Eric Laurent81784c32012-11-19 14:55:58 -08009210{
Glenn Kastend848eb42016-03-08 13:42:11 -08009211 KeyedVector<audio_session_t, bool> ids;
Eric Laurent81784c32012-11-19 14:55:58 -08009212 Mutex::Autolock _l(mLock);
9213 for (size_t j = 0; j < mTracks.size(); ++j) {
9214 sp<RecordThread::RecordTrack> track = mTracks[j];
Glenn Kastend848eb42016-03-08 13:42:11 -08009215 audio_session_t sessionId = track->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08009216 if (ids.indexOfKey(sessionId) < 0) {
9217 ids.add(sessionId, true);
9218 }
9219 }
9220 return ids;
9221}
9222
9223AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
9224{
9225 Mutex::Autolock _l(mLock);
9226 AudioStreamIn *input = mInput;
9227 mInput = NULL;
9228 return input;
9229}
9230
9231// this method must always be called either with ThreadBase mLock held or inside the thread loop
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009232sp<StreamHalInterface> AudioFlinger::RecordThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08009233{
9234 if (mInput == NULL) {
9235 return NULL;
9236 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009237 return mInput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08009238}
9239
9240status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
9241{
Eric Laurent81784c32012-11-19 14:55:58 -08009242 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurentaaa44472014-09-12 17:41:50 -07009243 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08009244 chain->setInBuffer(NULL);
9245 chain->setOutBuffer(NULL);
9246
9247 checkSuspendOnAddEffectChain_l(chain);
9248
Eric Laurent1b928682014-10-02 19:41:47 -07009249 // make sure enabled pre processing effects state is communicated to the HAL as we
9250 // just moved them to a new input stream.
9251 chain->syncHalEffectsState();
9252
Eric Laurent81784c32012-11-19 14:55:58 -08009253 mEffectChains.add(chain);
9254
9255 return NO_ERROR;
9256}
9257
9258size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
9259{
9260 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
Eric Laurentb20cf7d2019-04-05 19:37:34 -07009261
9262 for (size_t i = 0; i < mEffectChains.size(); i++) {
9263 if (chain == mEffectChains[i]) {
9264 mEffectChains.removeAt(i);
9265 break;
9266 }
Eric Laurent81784c32012-11-19 14:55:58 -08009267 }
Eric Laurentb20cf7d2019-04-05 19:37:34 -07009268 return mEffectChains.size();
Eric Laurent81784c32012-11-19 14:55:58 -08009269}
9270
Eric Laurent1c333e22014-05-20 10:48:17 -07009271status_t AudioFlinger::RecordThread::createAudioPatch_l(const struct audio_patch *patch,
9272 audio_patch_handle_t *handle)
9273{
9274 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07009275
9276 // store new device and send to effects
jiabinc52b1ff2019-10-31 17:20:42 -07009277 mInDeviceTypeAddr.mType = patch->sources[0].ext.device.type;
jiabin0a488932020-08-07 17:32:40 -07009278 mInDeviceTypeAddr.setAddress(patch->sources[0].ext.device.address);
François Gaffie0c280aa2018-07-25 10:02:15 +02009279 audio_port_handle_t deviceId = patch->sources[0].id;
Eric Laurent054d9d32015-04-24 08:48:48 -07009280 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08009281 mEffectChains[i]->setInputDevice_l(inDeviceTypeAddr());
Eric Laurent054d9d32015-04-24 08:48:48 -07009282 }
9283
Eric Laurentd8365c52017-07-16 15:27:05 -07009284 checkBtNrec_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07009285
9286 // store new source and send to effects
9287 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
9288 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent1c333e22014-05-20 10:48:17 -07009289 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent054d9d32015-04-24 08:48:48 -07009290 mEffectChains[i]->setAudioSource_l(mAudioSource);
Eric Laurent1c333e22014-05-20 10:48:17 -07009291 }
Eric Laurent054d9d32015-04-24 08:48:48 -07009292 }
Eric Laurent1c333e22014-05-20 10:48:17 -07009293
Mikhail Naganov9ee05402016-10-13 15:58:17 -07009294 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07009295 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
9296 status = hwDevice->createAudioPatch(patch->num_sources,
9297 patch->sources,
9298 patch->num_sinks,
9299 patch->sinks,
9300 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07009301 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08009302 status = mInput->stream->legacyCreateAudioPatch(patch->sources[0],
9303 patch->sinks[0].ext.mix.usecase.source,
9304 patch->sources[0].ext.device.type);
Eric Laurent054d9d32015-04-24 08:48:48 -07009305 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07009306 }
Eric Laurent054d9d32015-04-24 08:48:48 -07009307
jiabinc52b1ff2019-10-31 17:20:42 -07009308 if ((mPatch.num_sources == 0) || (mPatch.sources[0].id != deviceId)) {
Eric Laurente8726fe2015-06-26 09:39:24 -07009309 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
jiabinc52b1ff2019-10-31 17:20:42 -07009310 mPatch = *patch;
Eric Laurente8726fe2015-06-26 09:39:24 -07009311 }
Eric Laurent296fb132015-05-01 11:38:42 -07009312
Andy Hungc2b11cb2020-04-22 09:04:01 -07009313 const std::string pathSourcesAsString = patchSourcesToString(patch);
Andy Hungcf10d742020-04-28 15:38:24 -07009314 mThreadMetrics.logEndInterval();
Andy Hungea840382020-05-05 21:50:17 -07009315 mThreadMetrics.logCreatePatch(pathSourcesAsString, /* outDevices */ {});
Andy Hungcf10d742020-04-28 15:38:24 -07009316 mThreadMetrics.logBeginInterval();
Andy Hungc2b11cb2020-04-22 09:04:01 -07009317 // also dispatch to active AudioRecords
9318 for (const auto &track : mActiveTracks) {
9319 track->logEndInterval();
9320 track->logBeginInterval(pathSourcesAsString);
9321 }
Eric Laurentdda206a2022-07-08 17:28:35 +02009322 // Force meteadata update after a route change
9323 mActiveTracks.setHasChanged();
9324
Eric Laurent1c333e22014-05-20 10:48:17 -07009325 return status;
9326}
9327
9328status_t AudioFlinger::RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
9329{
9330 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07009331
jiabinc52b1ff2019-10-31 17:20:42 -07009332 mPatch = audio_patch{};
9333 mInDeviceTypeAddr.reset();
Eric Laurent054d9d32015-04-24 08:48:48 -07009334
Mikhail Naganov9ee05402016-10-13 15:58:17 -07009335 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07009336 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
9337 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07009338 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08009339 status = mInput->stream->legacyReleaseAudioPatch();
Eric Laurent1c333e22014-05-20 10:48:17 -07009340 }
Eric Laurentdda206a2022-07-08 17:28:35 +02009341 // Force meteadata update after a route change
9342 mActiveTracks.setHasChanged();
9343
Eric Laurent1c333e22014-05-20 10:48:17 -07009344 return status;
9345}
9346
jiabinc52b1ff2019-10-31 17:20:42 -07009347void AudioFlinger::RecordThread::updateOutDevices(const DeviceDescriptorBaseVector& outDevices)
9348{
wendy lin56aa82b2020-12-02 15:19:55 +08009349 Mutex::Autolock _l(mLock);
jiabinc52b1ff2019-10-31 17:20:42 -07009350 mOutDevices = outDevices;
9351 mOutDeviceTypeAddrs = deviceTypeAddrsFromDescriptors(mOutDevices);
9352 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08009353 mEffectChains[i]->setDevices_l(outDeviceTypeAddrs());
jiabinc52b1ff2019-10-31 17:20:42 -07009354 }
9355}
9356
Eric Laurentec376dc2021-04-08 20:41:22 +02009357int32_t AudioFlinger::RecordThread::getOldestFront_l()
9358{
9359 if (mTracks.size() == 0) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009360 return mRsmpInRear;
Eric Laurentec376dc2021-04-08 20:41:22 +02009361 }
Eric Laurent2407ce32021-04-26 14:56:03 +02009362 int32_t oldestFront = mRsmpInRear;
9363 int32_t maxFilled = 0;
Eric Laurentec376dc2021-04-08 20:41:22 +02009364 for (size_t i = 0; i < mTracks.size(); i++) {
Eric Laurent2407ce32021-04-26 14:56:03 +02009365 int32_t front = mTracks[i]->mResamplerBufferProvider->getFront();
9366 int32_t filled;
Eric Laurent92d0a322021-07-16 15:32:33 +02009367 (void)__builtin_sub_overflow(mRsmpInRear, front, &filled);
Eric Laurent2407ce32021-04-26 14:56:03 +02009368 if (filled > maxFilled) {
9369 oldestFront = front;
9370 maxFilled = filled;
9371 }
Eric Laurentec376dc2021-04-08 20:41:22 +02009372 }
Eric Laurent92d0a322021-07-16 15:32:33 +02009373 if (maxFilled > mRsmpInFrames) {
9374 (void)__builtin_sub_overflow(mRsmpInRear, mRsmpInFrames, &oldestFront);
9375 }
Eric Laurent2407ce32021-04-26 14:56:03 +02009376 return oldestFront;
Eric Laurentec376dc2021-04-08 20:41:22 +02009377}
9378
9379void AudioFlinger::RecordThread::updateFronts_l(int32_t offset)
9380{
9381 if (offset == 0) {
9382 return;
9383 }
9384 for (size_t i = 0; i < mTracks.size(); i++) {
9385 int32_t front = mTracks[i]->mResamplerBufferProvider->getFront();
9386 front = audio_utils::safe_sub_overflow(front, offset);
9387 mTracks[i]->mResamplerBufferProvider->setFront(front);
9388 }
9389}
9390
9391void AudioFlinger::RecordThread::resizeInputBuffer_l(int32_t maxSharedAudioHistoryMs)
9392{
9393 // This is the formula for calculating the temporary buffer size.
9394 // With 7 HAL buffers, we can guarantee ability to down-sample the input by ratio of 6:1 to
9395 // 1 full output buffer, regardless of the alignment of the available input.
9396 // The value is somewhat arbitrary, and could probably be even larger.
9397 // A larger value should allow more old data to be read after a track calls start(),
9398 // without increasing latency.
9399 //
9400 // Note this is independent of the maximum downsampling ratio permitted for capture.
9401 size_t minRsmpInFrames = mFrameCount * 7;
9402
9403 // maxSharedAudioHistoryMs != 0 indicates a request to possibly make some part of the audio
9404 // capture history available to another client using the same session ID:
9405 // dimension the resampler input buffer accordingly.
9406
9407 // Get oldest client read position: getOldestFront_l() must be called before altering
9408 // mRsmpInRear, or mRsmpInFrames
9409 int32_t previousFront = getOldestFront_l();
9410 size_t previousRsmpInFramesP2 = mRsmpInFramesP2;
9411 int32_t previousRear = mRsmpInRear;
9412 mRsmpInRear = 0;
9413
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009414 ALOG_ASSERT(maxSharedAudioHistoryMs >= 0
9415 && maxSharedAudioHistoryMs <= AudioFlinger::kMaxSharedAudioHistoryMs,
9416 "resizeInputBuffer_l() called with invalid max shared history %d",
9417 maxSharedAudioHistoryMs);
Eric Laurentec376dc2021-04-08 20:41:22 +02009418 if (maxSharedAudioHistoryMs != 0) {
9419 // resizeInputBuffer_l should never be called with a non zero shared history if the
9420 // buffer was not already allocated
9421 ALOG_ASSERT(mRsmpInBuffer != nullptr && mRsmpInFrames != 0,
9422 "resizeInputBuffer_l() called with shared history and unallocated buffer");
9423 size_t rsmpInFrames = (size_t)maxSharedAudioHistoryMs * mSampleRate / 1000;
9424 // never reduce resampler input buffer size
Eric Laurent92d0a322021-07-16 15:32:33 +02009425 if (rsmpInFrames <= mRsmpInFrames) {
Eric Laurentec376dc2021-04-08 20:41:22 +02009426 return;
9427 }
9428 mRsmpInFrames = rsmpInFrames;
9429 }
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009430 mMaxSharedAudioHistoryMs = maxSharedAudioHistoryMs;
Eric Laurentec376dc2021-04-08 20:41:22 +02009431 // Note: mRsmpInFrames is 0 when called with maxSharedAudioHistoryMs equals to 0 so it is always
9432 // initialized
9433 if (mRsmpInFrames < minRsmpInFrames) {
9434 mRsmpInFrames = minRsmpInFrames;
9435 }
9436 mRsmpInFramesP2 = roundup(mRsmpInFrames);
9437
9438 // TODO optimize audio capture buffer sizes ...
9439 // Here we calculate the size of the sliding buffer used as a source
9440 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
9441 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
9442 // be better to have it derived from the pipe depth in the long term.
9443 // The current value is higher than necessary. However it should not add to latency.
9444
9445 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
9446 mRsmpInFramesOA = mRsmpInFramesP2 + mFrameCount - 1;
9447
9448 void *rsmpInBuffer;
9449 (void)posix_memalign(&rsmpInBuffer, 32, mRsmpInFramesOA * mFrameSize);
9450 // if posix_memalign fails, will segv here.
9451 memset(rsmpInBuffer, 0, mRsmpInFramesOA * mFrameSize);
9452
9453 // Copy audio history if any from old buffer before freeing it
9454 if (previousRear != 0) {
9455 ALOG_ASSERT(mRsmpInBuffer != nullptr,
9456 "resizeInputBuffer_l() called with null buffer but frames already read from HAL");
9457
9458 ssize_t unread = audio_utils::safe_sub_overflow(previousRear, previousFront);
9459 previousFront &= previousRsmpInFramesP2 - 1;
9460 size_t part1 = previousRsmpInFramesP2 - previousFront;
9461 if (part1 > (size_t) unread) {
9462 part1 = unread;
9463 }
9464 if (part1 != 0) {
9465 memcpy(rsmpInBuffer, (const uint8_t*)mRsmpInBuffer + previousFront * mFrameSize,
9466 part1 * mFrameSize);
9467 mRsmpInRear = part1;
9468 part1 = unread - part1;
9469 if (part1 != 0) {
9470 memcpy((uint8_t*)rsmpInBuffer + mRsmpInRear * mFrameSize,
9471 (const uint8_t*)mRsmpInBuffer, part1 * mFrameSize);
9472 mRsmpInRear += part1;
9473 }
9474 }
9475 // Update front for all clients according to new rear
9476 updateFronts_l(audio_utils::safe_sub_overflow(previousRear, mRsmpInRear));
9477 } else {
9478 mRsmpInRear = 0;
9479 }
9480 free(mRsmpInBuffer);
9481 mRsmpInBuffer = rsmpInBuffer;
9482}
9483
Mikhail Naganov444ecc32018-05-01 17:40:05 -07009484void AudioFlinger::RecordThread::addPatchTrack(const sp<PatchRecord>& record)
Eric Laurent83b88082014-06-20 18:31:16 -07009485{
9486 Mutex::Autolock _l(mLock);
9487 mTracks.add(record);
Mikhail Naganov2534b382019-09-25 13:05:02 -07009488 if (record->getSource()) {
9489 mSource = record->getSource();
9490 }
Eric Laurent83b88082014-06-20 18:31:16 -07009491}
9492
Mikhail Naganov444ecc32018-05-01 17:40:05 -07009493void AudioFlinger::RecordThread::deletePatchTrack(const sp<PatchRecord>& record)
Eric Laurent83b88082014-06-20 18:31:16 -07009494{
9495 Mutex::Autolock _l(mLock);
Mikhail Naganov2534b382019-09-25 13:05:02 -07009496 if (mSource == record->getSource()) {
9497 mSource = mInput;
9498 }
Eric Laurent83b88082014-06-20 18:31:16 -07009499 destroyTrack_l(record);
9500}
9501
Mikhail Naganovdc769682018-05-04 15:34:08 -07009502void AudioFlinger::RecordThread::toAudioPortConfig(struct audio_port_config *config)
Eric Laurent83b88082014-06-20 18:31:16 -07009503{
Mikhail Naganovdc769682018-05-04 15:34:08 -07009504 ThreadBase::toAudioPortConfig(config);
Eric Laurent83b88082014-06-20 18:31:16 -07009505 config->role = AUDIO_PORT_ROLE_SINK;
9506 config->ext.mix.hw_module = mInput->audioHwDev->handle();
9507 config->ext.mix.usecase.source = mAudioSource;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07009508 if (mInput && mInput->flags != AUDIO_INPUT_FLAG_NONE) {
9509 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
9510 config->flags.input = mInput->flags;
9511 }
Eric Laurent83b88082014-06-20 18:31:16 -07009512}
Eric Laurent1c333e22014-05-20 10:48:17 -07009513
Eric Laurent6acd1d42017-01-04 14:23:29 -08009514// ----------------------------------------------------------------------------
9515// Mmap
9516// ----------------------------------------------------------------------------
9517
9518AudioFlinger::MmapThreadHandle::MmapThreadHandle(const sp<MmapThread>& thread)
9519 : mThread(thread)
9520{
Phil Burk9fabbf82017-08-03 12:02:00 -07009521 assert(thread != 0); // thread must start non-null and stay non-null
Eric Laurent6acd1d42017-01-04 14:23:29 -08009522}
9523
9524AudioFlinger::MmapThreadHandle::~MmapThreadHandle()
9525{
Phil Burk9fabbf82017-08-03 12:02:00 -07009526 mThread->disconnect();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009527}
9528
9529status_t AudioFlinger::MmapThreadHandle::createMmapBuffer(int32_t minSizeFrames,
9530 struct audio_mmap_buffer_info *info)
9531{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009532 return mThread->createMmapBuffer(minSizeFrames, info);
9533}
9534
9535status_t AudioFlinger::MmapThreadHandle::getMmapPosition(struct audio_mmap_position *position)
9536{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009537 return mThread->getMmapPosition(position);
9538}
9539
jiabinb7d8c5a2020-08-26 17:24:52 -07009540status_t AudioFlinger::MmapThreadHandle::getExternalPosition(uint64_t *position,
9541 int64_t *timeNanos) {
9542 return mThread->getExternalPosition(position, timeNanos);
9543}
9544
Eric Laurenta54f1282017-07-01 19:39:32 -07009545status_t AudioFlinger::MmapThreadHandle::start(const AudioClient& client,
jiabind1f1cb62020-03-24 11:57:57 -07009546 const audio_attributes_t *attr, audio_port_handle_t *handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009547
9548{
jiabind1f1cb62020-03-24 11:57:57 -07009549 return mThread->start(client, attr, handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009550}
9551
9552status_t AudioFlinger::MmapThreadHandle::stop(audio_port_handle_t handle)
9553{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009554 return mThread->stop(handle);
9555}
9556
Eric Laurent18b57012017-02-13 16:23:52 -08009557status_t AudioFlinger::MmapThreadHandle::standby()
9558{
Eric Laurent18b57012017-02-13 16:23:52 -08009559 return mThread->standby();
9560}
9561
Eric Laurent6acd1d42017-01-04 14:23:29 -08009562
9563AudioFlinger::MmapThread::MmapThread(
9564 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
Andy Hungcf10d742020-04-28 15:38:24 -07009565 AudioHwDevice *hwDev, sp<StreamHalInterface> stream, bool systemReady, bool isOut)
Andy Hungea840382020-05-05 21:50:17 -07009566 : ThreadBase(audioFlinger, id, (isOut ? MMAP_PLAYBACK : MMAP_CAPTURE), systemReady, isOut),
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009567 mSessionId(AUDIO_SESSION_NONE),
François Gaffie0c280aa2018-07-25 10:02:15 +02009568 mPortId(AUDIO_PORT_HANDLE_NONE),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009569 mHalStream(stream), mHalDevice(hwDev->hwDevice()), mAudioHwDev(hwDev),
Eric Laurent67f97292018-04-20 18:05:41 -07009570 mActiveTracks(&this->mLocalLog),
9571 mHalVolFloat(-1.0f), // Initialize to illegal value so it always gets set properly later.
9572 mNoCallbackWarningCount(0)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009573{
Eric Laurent18b57012017-02-13 16:23:52 -08009574 mStandby = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009575 readHalParameters_l();
9576}
9577
9578AudioFlinger::MmapThread::~MmapThread()
9579{
9580}
9581
9582void AudioFlinger::MmapThread::onFirstRef()
9583{
9584 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
9585}
9586
9587void AudioFlinger::MmapThread::disconnect()
9588{
Eric Laurent331679c2018-04-16 17:03:16 -07009589 ActiveTracks<MmapTrack> activeTracks;
9590 {
9591 Mutex::Autolock _l(mLock);
9592 for (const sp<MmapTrack> &t : mActiveTracks) {
9593 activeTracks.add(t);
9594 }
9595 }
9596 for (const sp<MmapTrack> &t : activeTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08009597 stop(t->portId());
9598 }
Phil Burk9fabbf82017-08-03 12:02:00 -07009599 // This will decrement references and may cause the destruction of this thread.
Eric Laurent6acd1d42017-01-04 14:23:29 -08009600 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07009601 AudioSystem::releaseOutput(mPortId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009602 } else {
Eric Laurentfee19762018-01-29 18:44:13 -08009603 AudioSystem::releaseInput(mPortId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009604 }
9605}
9606
9607
9608void AudioFlinger::MmapThread::configure(const audio_attributes_t *attr,
9609 audio_stream_type_t streamType __unused,
9610 audio_session_t sessionId,
9611 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009612 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -08009613 audio_port_handle_t portId)
9614{
9615 mAttr = *attr;
9616 mSessionId = sessionId;
9617 mCallback = callback;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009618 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009619 mPortId = portId;
9620}
9621
9622status_t AudioFlinger::MmapThread::createMmapBuffer(int32_t minSizeFrames,
9623 struct audio_mmap_buffer_info *info)
9624{
9625 if (mHalStream == 0) {
9626 return NO_INIT;
9627 }
Eric Laurent18b57012017-02-13 16:23:52 -08009628 mStandby = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009629 return mHalStream->createMmapBuffer(minSizeFrames, info);
9630}
9631
9632status_t AudioFlinger::MmapThread::getMmapPosition(struct audio_mmap_position *position)
9633{
9634 if (mHalStream == 0) {
9635 return NO_INIT;
9636 }
9637 return mHalStream->getMmapPosition(position);
9638}
9639
Eric Laurentdda206a2022-07-08 17:28:35 +02009640status_t AudioFlinger::MmapThread::exitStandby_l()
Eric Laurent331679c2018-04-16 17:03:16 -07009641{
Eric Laurentdda206a2022-07-08 17:28:35 +02009642 // The HAL must receive track metadata before starting the stream
9643 updateMetadata_l();
Eric Laurent331679c2018-04-16 17:03:16 -07009644 status_t ret = mHalStream->start();
9645 if (ret != NO_ERROR) {
9646 ALOGE("%s: error mHalStream->start() = %d for first track", __FUNCTION__, ret);
9647 return ret;
9648 }
Andy Hungcf10d742020-04-28 15:38:24 -07009649 if (mStandby) {
9650 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07009651 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -07009652 mStandby = false;
9653 }
Eric Laurent331679c2018-04-16 17:03:16 -07009654 return NO_ERROR;
9655}
9656
Eric Laurenta54f1282017-07-01 19:39:32 -07009657status_t AudioFlinger::MmapThread::start(const AudioClient& client,
jiabind1f1cb62020-03-24 11:57:57 -07009658 const audio_attributes_t *attr,
Eric Laurent6acd1d42017-01-04 14:23:29 -08009659 audio_port_handle_t *handle)
9660{
Eric Laurenta54f1282017-07-01 19:39:32 -07009661 ALOGV("%s clientUid %d mStandby %d mPortId %d *handle %d", __FUNCTION__,
Svet Ganov33761132021-05-13 22:51:08 +00009662 client.attributionSource.uid, mStandby, mPortId, *handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009663 if (mHalStream == 0) {
9664 return NO_INIT;
9665 }
9666
9667 status_t ret;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009668
Eric Laurentdda206a2022-07-08 17:28:35 +02009669 // For the first track, reuse portId and session allocated when the stream was opened.
Eric Laurenta54f1282017-07-01 19:39:32 -07009670 if (*handle == mPortId) {
Eric Laurentdda206a2022-07-08 17:28:35 +02009671 acquireWakeLock();
9672 return NO_ERROR;
Eric Laurenta54f1282017-07-01 19:39:32 -07009673 }
9674
9675 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
9676
9677 audio_io_handle_t io = mId;
9678 if (isOutput()) {
9679 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
9680 config.sample_rate = mSampleRate;
9681 config.channel_mask = mChannelMask;
9682 config.format = mFormat;
9683 audio_stream_type_t stream = streamType();
9684 audio_output_flags_t flags =
9685 (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009686 audio_port_handle_t deviceId = mDeviceId;
Kevin Rocard153f92d2018-12-18 18:33:28 -08009687 std::vector<audio_io_handle_t> secondaryOutputs;
Eric Laurentb0a7bc92022-04-05 15:06:08 +02009688 bool isSpatialized;
Eric Laurenta54f1282017-07-01 19:39:32 -07009689 ret = AudioSystem::getOutputForAttr(&mAttr, &io,
9690 mSessionId,
9691 &stream,
Svet Ganov33761132021-05-13 22:51:08 +00009692 client.attributionSource,
Eric Laurenta54f1282017-07-01 19:39:32 -07009693 &config,
9694 flags,
9695 &deviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -08009696 &portId,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02009697 &secondaryOutputs,
9698 &isSpatialized);
Kevin Rocard153f92d2018-12-18 18:33:28 -08009699 ALOGD_IF(!secondaryOutputs.empty(),
9700 "MmapThread::start does not support secondary outputs, ignoring them");
Eric Laurent6acd1d42017-01-04 14:23:29 -08009701 } else {
Eric Laurenta54f1282017-07-01 19:39:32 -07009702 audio_config_base_t config;
9703 config.sample_rate = mSampleRate;
9704 config.channel_mask = mChannelMask;
9705 config.format = mFormat;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009706 audio_port_handle_t deviceId = mDeviceId;
Eric Laurenta54f1282017-07-01 19:39:32 -07009707 ret = AudioSystem::getInputForAttr(&mAttr, &io,
Mikhail Naganov2996f672019-04-18 12:29:59 -07009708 RECORD_RIID_INVALID,
Eric Laurenta54f1282017-07-01 19:39:32 -07009709 mSessionId,
Svet Ganov33761132021-05-13 22:51:08 +00009710 client.attributionSource,
Eric Laurenta54f1282017-07-01 19:39:32 -07009711 &config,
9712 AUDIO_INPUT_FLAG_MMAP_NOIRQ,
9713 &deviceId,
9714 &portId);
9715 }
9716 // APM should not chose a different input or output stream for the same set of attributes
9717 // and audo configuration
9718 if (ret != NO_ERROR || io != mId) {
9719 ALOGE("%s: error getting output or input from APM (error %d, io %d expected io %d)",
9720 __FUNCTION__, ret, io, mId);
9721 return BAD_VALUE;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009722 }
9723
9724 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07009725 ret = AudioSystem::startOutput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009726 } else {
jiabin09609032022-06-15 19:26:01 +00009727 {
9728 // Add the track record before starting input so that the silent status for the
9729 // client can be cached.
9730 Mutex::Autolock _l(mLock);
9731 setClientSilencedState_l(portId, false /*silenced*/);
9732 }
Eric Laurent4eb58f12018-12-07 16:41:02 -08009733 ret = AudioSystem::startInput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009734 }
9735
Eric Laurent331679c2018-04-16 17:03:16 -07009736 Mutex::Autolock _l(mLock);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009737 // abort if start is rejected by audio policy manager
9738 if (ret != NO_ERROR) {
Phil Burk7f6b40d2017-02-09 13:18:38 -08009739 ALOGE("%s: error start rejected by AudioPolicyManager = %d", __FUNCTION__, ret);
Eric Tan39ec8d62018-07-24 09:49:29 -07009740 if (!mActiveTracks.isEmpty()) {
Eric Laurent331679c2018-04-16 17:03:16 -07009741 mLock.unlock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009742 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07009743 AudioSystem::releaseOutput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009744 } else {
Eric Laurentfee19762018-01-29 18:44:13 -08009745 AudioSystem::releaseInput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009746 }
Eric Laurent331679c2018-04-16 17:03:16 -07009747 mLock.lock();
Eric Laurent18b57012017-02-13 16:23:52 -08009748 } else {
9749 mHalStream->stop();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009750 }
jiabin09609032022-06-15 19:26:01 +00009751 eraseClientSilencedState_l(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009752 return PERMISSION_DENIED;
9753 }
9754
Kevin Rocard1f564ac2018-03-29 13:53:10 -07009755 // Given that MmapThread::mAttr is mutable, should a MmapTrack have attributes ?
jiabind1f1cb62020-03-24 11:57:57 -07009756 sp<MmapTrack> track = new MmapTrack(this, attr == nullptr ? mAttr : *attr, mSampleRate, mFormat,
Svet Ganov33761132021-05-13 22:51:08 +00009757 mChannelMask, mSessionId, isOutput(),
9758 client.attributionSource,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07009759 IPCThreadState::self()->getCallingPid(), portId);
jiabin09609032022-06-15 19:26:01 +00009760 if (!isOutput()) {
9761 track->setSilenced_l(isClientSilenced_l(portId));
9762 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08009763
Eric Laurent4eb58f12018-12-07 16:41:02 -08009764 if (isOutput()) {
9765 // force volume update when a new track is added
9766 mHalVolFloat = -1.0f;
9767 } else if (!track->isSilenced_l()) {
9768 for (const sp<MmapTrack> &t : mActiveTracks) {
Svet Ganov33761132021-05-13 22:51:08 +00009769 if (t->isSilenced_l() && t->uid() != client.attributionSource.uid)
Eric Laurent4eb58f12018-12-07 16:41:02 -08009770 t->invalidate();
9771 }
9772 }
9773
Eric Laurent6acd1d42017-01-04 14:23:29 -08009774 mActiveTracks.add(track);
Eric Laurenta54f1282017-07-01 19:39:32 -07009775 sp<EffectChain> chain = getEffectChain_l(mSessionId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009776 if (chain != 0) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02009777 chain->setStrategy(getStrategyForStream(streamType()));
Eric Laurent6acd1d42017-01-04 14:23:29 -08009778 chain->incTrackCnt();
9779 chain->incActiveTrackCnt();
9780 }
9781
Andy Hungc2b11cb2020-04-22 09:04:01 -07009782 track->logBeginInterval(patchSinksToString(&mPatch)); // log to MediaMetrics
Eric Laurent6acd1d42017-01-04 14:23:29 -08009783 *handle = portId;
Eric Laurentdda206a2022-07-08 17:28:35 +02009784
9785 if (mActiveTracks.size() == 1) {
9786 ret = exitStandby_l();
9787 }
9788
Eric Laurent6acd1d42017-01-04 14:23:29 -08009789 broadcast_l();
9790
Eric Laurentdda206a2022-07-08 17:28:35 +02009791 ALOGV("%s DONE status %d handle %d stream %p", __FUNCTION__, ret, *handle, mHalStream.get());
Eric Laurent6acd1d42017-01-04 14:23:29 -08009792
Eric Laurentdda206a2022-07-08 17:28:35 +02009793 return ret;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009794}
9795
9796status_t AudioFlinger::MmapThread::stop(audio_port_handle_t handle)
9797{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009798 ALOGV("%s handle %d", __FUNCTION__, handle);
9799
9800 if (mHalStream == 0) {
9801 return NO_INIT;
9802 }
9803
Eric Laurenta54f1282017-07-01 19:39:32 -07009804 if (handle == mPortId) {
Phil Burk98ab4082020-09-25 21:46:34 +00009805 releaseWakeLock();
Eric Laurenta54f1282017-07-01 19:39:32 -07009806 return NO_ERROR;
9807 }
9808
Eric Laurent331679c2018-04-16 17:03:16 -07009809 Mutex::Autolock _l(mLock);
9810
Eric Laurent6acd1d42017-01-04 14:23:29 -08009811 sp<MmapTrack> track;
9812 for (const sp<MmapTrack> &t : mActiveTracks) {
9813 if (handle == t->portId()) {
9814 track = t;
9815 break;
9816 }
9817 }
9818 if (track == 0) {
9819 return BAD_VALUE;
9820 }
9821
9822 mActiveTracks.remove(track);
jiabin09609032022-06-15 19:26:01 +00009823 eraseClientSilencedState_l(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -08009824
Eric Laurent331679c2018-04-16 17:03:16 -07009825 mLock.unlock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009826 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07009827 AudioSystem::stopOutput(track->portId());
9828 AudioSystem::releaseOutput(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -08009829 } else {
Eric Laurentfee19762018-01-29 18:44:13 -08009830 AudioSystem::stopInput(track->portId());
9831 AudioSystem::releaseInput(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -08009832 }
Eric Laurent331679c2018-04-16 17:03:16 -07009833 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009834
9835 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
9836 if (chain != 0) {
9837 chain->decActiveTrackCnt();
9838 chain->decTrackCnt();
9839 }
9840
Eric Laurentdda206a2022-07-08 17:28:35 +02009841 if (mActiveTracks.isEmpty()) {
9842 mHalStream->stop();
9843 }
9844
Eric Laurent6acd1d42017-01-04 14:23:29 -08009845 broadcast_l();
9846
Eric Laurent6acd1d42017-01-04 14:23:29 -08009847 return NO_ERROR;
9848}
9849
Eric Laurent18b57012017-02-13 16:23:52 -08009850status_t AudioFlinger::MmapThread::standby()
9851{
9852 ALOGV("%s", __FUNCTION__);
9853
9854 if (mHalStream == 0) {
9855 return NO_INIT;
9856 }
Eric Tan39ec8d62018-07-24 09:49:29 -07009857 if (!mActiveTracks.isEmpty()) {
Eric Laurent18b57012017-02-13 16:23:52 -08009858 return INVALID_OPERATION;
9859 }
9860 mHalStream->standby();
Andy Hungcf10d742020-04-28 15:38:24 -07009861 if (!mStandby) {
9862 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07009863 mThreadSnapshot.onEnd();
Andy Hungcf10d742020-04-28 15:38:24 -07009864 mStandby = true;
9865 }
Eric Laurent18b57012017-02-13 16:23:52 -08009866 releaseWakeLock();
9867 return NO_ERROR;
9868}
9869
Eric Laurent6acd1d42017-01-04 14:23:29 -08009870
9871void AudioFlinger::MmapThread::readHalParameters_l()
9872{
9873 status_t result = mHalStream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
9874 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
9875 mFormat = mHALFormat;
9876 LOG_ALWAYS_FATAL_IF(!audio_is_linear_pcm(mFormat), "HAL format %#x is not linear pcm", mFormat);
9877 result = mHalStream->getFrameSize(&mFrameSize);
9878 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
Hayden Gomes1a89ab32020-06-12 11:05:47 -07009879 LOG_ALWAYS_FATAL_IF(mFrameSize <= 0, "Error frame size was %zu but must be greater than zero",
9880 mFrameSize);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009881 result = mHalStream->getBufferSize(&mBufferSize);
9882 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
9883 mFrameCount = mBufferSize / mFrameSize;
Andy Hungc2b11cb2020-04-22 09:04:01 -07009884
Andy Hungcf10d742020-04-28 15:38:24 -07009885 // TODO: make a readHalParameters call?
9886 mediametrics::LogItem item(mThreadMetrics.getMetricsId());
Andy Hungc2b11cb2020-04-22 09:04:01 -07009887 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
9888 .set(AMEDIAMETRICS_PROP_ENCODING, formatToString(mFormat).c_str())
9889 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
9890 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
9891 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
9892 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mFrameCount)
9893 /*
9894 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
9895 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELMASK,
9896 (int32_t)mHapticChannelMask)
9897 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELCOUNT,
9898 (int32_t)mHapticChannelCount)
9899 */
9900 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_ENCODING,
9901 formatToString(mHALFormat).c_str())
9902 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_FRAMECOUNT,
9903 (int32_t)mFrameCount) // sic - added HAL
9904 .record();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009905}
9906
9907bool AudioFlinger::MmapThread::threadLoop()
9908{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009909 checkSilentMode_l();
9910
9911 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
9912
9913 while (!exitPending())
9914 {
Eric Laurent6acd1d42017-01-04 14:23:29 -08009915 Vector< sp<EffectChain> > effectChains;
9916
Andy Hung13850be2019-03-14 11:33:09 -07009917 { // under Thread lock
9918 Mutex::Autolock _l(mLock);
9919
Eric Laurent6acd1d42017-01-04 14:23:29 -08009920 if (mSignalPending) {
9921 // A signal was raised while we were unlocked
9922 mSignalPending = false;
9923 } else {
9924 if (mConfigEvents.isEmpty()) {
9925 // we're about to wait, flush the binder command buffer
9926 IPCThreadState::self()->flushCommands();
9927
9928 if (exitPending()) {
9929 break;
9930 }
9931
Eric Laurent6acd1d42017-01-04 14:23:29 -08009932 // wait until we have something to do...
9933 ALOGV("%s going to sleep", myName.string());
9934 mWaitWorkCV.wait(mLock);
9935 ALOGV("%s waking up", myName.string());
Eric Laurent6acd1d42017-01-04 14:23:29 -08009936
9937 checkSilentMode_l();
9938
9939 continue;
9940 }
9941 }
9942
9943 processConfigEvents_l();
9944
9945 processVolume_l();
9946
9947 checkInvalidTracks_l();
9948
9949 mActiveTracks.updatePowerState(this);
9950
Kevin Rocard069c2712018-03-29 19:09:14 -07009951 updateMetadata_l();
9952
Eric Laurent6acd1d42017-01-04 14:23:29 -08009953 lockEffectChains_l(effectChains);
Andy Hung13850be2019-03-14 11:33:09 -07009954 } // release Thread lock
9955
Eric Laurent6acd1d42017-01-04 14:23:29 -08009956 for (size_t i = 0; i < effectChains.size(); i ++) {
Andy Hung13850be2019-03-14 11:33:09 -07009957 effectChains[i]->process_l(); // Thread is not locked, but effect chain is locked
Eric Laurent6acd1d42017-01-04 14:23:29 -08009958 }
Andy Hung13850be2019-03-14 11:33:09 -07009959
9960 // enable changes in effect chain, including moving to another thread.
Eric Laurent6acd1d42017-01-04 14:23:29 -08009961 unlockEffectChains(effectChains);
9962 // Effect chains will be actually deleted here if they were removed from
9963 // mEffectChains list during mixing or effects processing
9964 }
9965
9966 threadLoop_exit();
9967
9968 if (!mStandby) {
9969 threadLoop_standby();
9970 mStandby = true;
9971 }
9972
Eric Laurent6acd1d42017-01-04 14:23:29 -08009973 ALOGV("Thread %p type %d exiting", this, mType);
9974 return false;
9975}
9976
9977// checkForNewParameter_l() must be called with ThreadBase::mLock held
9978bool AudioFlinger::MmapThread::checkForNewParameter_l(const String8& keyValuePair,
9979 status_t& status)
9980{
9981 AudioParameter param = AudioParameter(keyValuePair);
9982 int value;
Eric Laurente6e9a482017-07-25 19:26:02 -07009983 bool sendToHal = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009984 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07009985 LOG_FATAL("Should not happen set routing device in MmapThread");
Eric Laurent6acd1d42017-01-04 14:23:29 -08009986 }
Eric Laurente6e9a482017-07-25 19:26:02 -07009987 if (sendToHal) {
9988 status = mHalStream->setParameters(keyValuePair);
9989 } else {
9990 status = NO_ERROR;
9991 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08009992
9993 return false;
9994}
9995
9996String8 AudioFlinger::MmapThread::getParameters(const String8& keys)
9997{
9998 Mutex::Autolock _l(mLock);
9999 String8 out_s8;
10000 if (initCheck() == NO_ERROR && mHalStream->getParameters(keys, &out_s8) == OK) {
10001 return out_s8;
10002 }
10003 return String8();
10004}
10005
Mikhail Naganov88536df2021-07-26 17:30:29 -070010006void AudioFlinger::MmapThread::ioConfigChanged(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -070010007 audio_port_handle_t portId __unused) {
Mikhail Naganov88536df2021-07-26 17:30:29 -070010008 sp<AudioIoDescriptor> desc;
10009 bool isInput = false;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010010 switch (event) {
10011 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -070010012 case AUDIO_INPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -080010013 case AUDIO_INPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -070010014 isInput = true;
10015 FALLTHROUGH_INTENDED;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010016 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -070010017 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -080010018 case AUDIO_OUTPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -070010019 desc = sp<AudioIoDescriptor>::make(mId, mPatch, isInput,
10020 mSampleRate, mFormat, mChannelMask, mFrameCount, mFrameCount);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010021 break;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010022 case AUDIO_INPUT_CLOSED:
10023 case AUDIO_OUTPUT_CLOSED:
10024 default:
Mikhail Naganov88536df2021-07-26 17:30:29 -070010025 desc = sp<AudioIoDescriptor>::make(mId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010026 break;
10027 }
10028 mAudioFlinger->ioConfigChanged(event, desc, pid);
10029}
10030
10031status_t AudioFlinger::MmapThread::createAudioPatch_l(const struct audio_patch *patch,
10032 audio_patch_handle_t *handle)
10033{
10034 status_t status = NO_ERROR;
10035
10036 // store new device and send to effects
10037 audio_devices_t type = AUDIO_DEVICE_NONE;
10038 audio_port_handle_t deviceId;
jiabinc52b1ff2019-10-31 17:20:42 -070010039 AudioDeviceTypeAddrVector sinkDeviceTypeAddrs;
10040 AudioDeviceTypeAddr sourceDeviceTypeAddr;
10041 uint32_t numDevices = 0;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010042 if (isOutput()) {
10043 for (unsigned int i = 0; i < patch->num_sinks; i++) {
jiabinc52b1ff2019-10-31 17:20:42 -070010044 LOG_ALWAYS_FATAL_IF(popcount(patch->sinks[i].ext.device.type) > 1
10045 && !mAudioHwDev->supportsAudioPatches(),
10046 "Enumerated device type(%#x) must not be used "
10047 "as it does not support audio patches",
10048 patch->sinks[i].ext.device.type);
Mikhail Naganov55773032020-10-01 15:08:13 -070010049 type = static_cast<audio_devices_t>(type | patch->sinks[i].ext.device.type);
jiabinc52b1ff2019-10-31 17:20:42 -070010050 sinkDeviceTypeAddrs.push_back(AudioDeviceTypeAddr(patch->sinks[i].ext.device.type,
10051 patch->sinks[i].ext.device.address));
Eric Laurent6acd1d42017-01-04 14:23:29 -080010052 }
10053 deviceId = patch->sinks[0].id;
jiabinc52b1ff2019-10-31 17:20:42 -070010054 numDevices = mPatch.num_sinks;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010055 } else {
10056 type = patch->sources[0].ext.device.type;
10057 deviceId = patch->sources[0].id;
jiabinc52b1ff2019-10-31 17:20:42 -070010058 numDevices = mPatch.num_sources;
10059 sourceDeviceTypeAddr.mType = patch->sources[0].ext.device.type;
jiabin0a488932020-08-07 17:32:40 -070010060 sourceDeviceTypeAddr.setAddress(patch->sources[0].ext.device.address);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010061 }
10062
10063 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -080010064 if (isOutput()) {
10065 mEffectChains[i]->setDevices_l(sinkDeviceTypeAddrs);
10066 } else {
10067 mEffectChains[i]->setInputDevice_l(sourceDeviceTypeAddr);
10068 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010069 }
10070
jiabinc52b1ff2019-10-31 17:20:42 -070010071 if (!isOutput()) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010072 // store new source and send to effects
10073 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
10074 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
10075 for (size_t i = 0; i < mEffectChains.size(); i++) {
10076 mEffectChains[i]->setAudioSource_l(mAudioSource);
10077 }
10078 }
10079 }
10080
10081 if (mAudioHwDev->supportsAudioPatches()) {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010082 status = mHalDevice->createAudioPatch(patch->num_sources, patch->sources, patch->num_sinks,
10083 patch->sinks, handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010084 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010085 audio_port_config port;
10086 std::optional<audio_source_t> source;
10087 if (isOutput()) {
10088 port = patch->sinks[0];
Eric Laurent6acd1d42017-01-04 14:23:29 -080010089 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010090 port = patch->sources[0];
10091 source = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010092 }
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010093 status = mHalStream->legacyCreateAudioPatch(port, source, type);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010094 *handle = AUDIO_PATCH_HANDLE_NONE;
10095 }
10096
jiabinc52b1ff2019-10-31 17:20:42 -070010097 if (numDevices == 0 || mDeviceId != deviceId) {
10098 if (isOutput()) {
10099 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
10100 mOutDeviceTypeAddrs = sinkDeviceTypeAddrs;
jiabin0a957d32020-04-29 10:56:20 -070010101 checkSilentMode_l();
jiabinc52b1ff2019-10-31 17:20:42 -070010102 } else {
10103 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
10104 mInDeviceTypeAddr = sourceDeviceTypeAddr;
10105 }
Phil Burk7f6b40d2017-02-09 13:18:38 -080010106 sp<MmapStreamCallback> callback = mCallback.promote();
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010107 if (mDeviceId != deviceId && callback != 0) {
Eric Laurent734046e2018-04-16 14:50:52 -070010108 mLock.unlock();
Phil Burk7f6b40d2017-02-09 13:18:38 -080010109 callback->onRoutingChanged(deviceId);
Eric Laurent734046e2018-04-16 14:50:52 -070010110 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010111 }
jiabinc52b1ff2019-10-31 17:20:42 -070010112 mPatch = *patch;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010113 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010114 }
Eric Laurentdda206a2022-07-08 17:28:35 +020010115 // Force meteadata update after a route change
10116 mActiveTracks.setHasChanged();
10117
Eric Laurent6acd1d42017-01-04 14:23:29 -080010118 return status;
10119}
10120
10121status_t AudioFlinger::MmapThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
10122{
10123 status_t status = NO_ERROR;
10124
jiabinc52b1ff2019-10-31 17:20:42 -070010125 mPatch = audio_patch{};
10126 mOutDeviceTypeAddrs.clear();
10127 mInDeviceTypeAddr.reset();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010128
10129 bool supportsAudioPatches = mHalDevice->supportsAudioPatches(&supportsAudioPatches) == OK ?
10130 supportsAudioPatches : false;
10131
10132 if (supportsAudioPatches) {
10133 status = mHalDevice->releaseAudioPatch(handle);
10134 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010135 status = mHalStream->legacyReleaseAudioPatch();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010136 }
Eric Laurentdda206a2022-07-08 17:28:35 +020010137 // Force meteadata update after a route change
10138 mActiveTracks.setHasChanged();
10139
Eric Laurent6acd1d42017-01-04 14:23:29 -080010140 return status;
10141}
10142
Mikhail Naganovdc769682018-05-04 15:34:08 -070010143void AudioFlinger::MmapThread::toAudioPortConfig(struct audio_port_config *config)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010144{
Mikhail Naganovdc769682018-05-04 15:34:08 -070010145 ThreadBase::toAudioPortConfig(config);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010146 if (isOutput()) {
10147 config->role = AUDIO_PORT_ROLE_SOURCE;
10148 config->ext.mix.hw_module = mAudioHwDev->handle();
10149 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
10150 } else {
10151 config->role = AUDIO_PORT_ROLE_SINK;
10152 config->ext.mix.hw_module = mAudioHwDev->handle();
10153 config->ext.mix.usecase.source = mAudioSource;
10154 }
10155}
10156
10157status_t AudioFlinger::MmapThread::addEffectChain_l(const sp<EffectChain>& chain)
10158{
10159 audio_session_t session = chain->sessionId();
10160
10161 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
10162 // Attach all tracks with same session ID to this chain.
10163 // indicate all active tracks in the chain
10164 for (const sp<MmapTrack> &track : mActiveTracks) {
10165 if (session == track->sessionId()) {
10166 chain->incTrackCnt();
10167 chain->incActiveTrackCnt();
10168 }
10169 }
10170
10171 chain->setThread(this);
10172 chain->setInBuffer(nullptr);
10173 chain->setOutBuffer(nullptr);
10174 chain->syncHalEffectsState();
10175
10176 mEffectChains.add(chain);
10177 checkSuspendOnAddEffectChain_l(chain);
10178 return NO_ERROR;
10179}
10180
10181size_t AudioFlinger::MmapThread::removeEffectChain_l(const sp<EffectChain>& chain)
10182{
10183 audio_session_t session = chain->sessionId();
10184
10185 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
10186
10187 for (size_t i = 0; i < mEffectChains.size(); i++) {
10188 if (chain == mEffectChains[i]) {
10189 mEffectChains.removeAt(i);
10190 // detach all active tracks from the chain
10191 // detach all tracks with same session ID from this chain
10192 for (const sp<MmapTrack> &track : mActiveTracks) {
10193 if (session == track->sessionId()) {
10194 chain->decActiveTrackCnt();
10195 chain->decTrackCnt();
10196 }
10197 }
10198 break;
10199 }
10200 }
10201 return mEffectChains.size();
10202}
10203
Eric Laurent6acd1d42017-01-04 14:23:29 -080010204void AudioFlinger::MmapThread::threadLoop_standby()
10205{
10206 mHalStream->standby();
10207}
10208
10209void AudioFlinger::MmapThread::threadLoop_exit()
10210{
Phil Burk7dce7282017-09-27 13:51:41 -070010211 // Do not call callback->onTearDown() because it is redundant for thread exit
10212 // and because it can cause a recursive mutex lock on stop().
Eric Laurent6acd1d42017-01-04 14:23:29 -080010213}
10214
10215status_t AudioFlinger::MmapThread::setSyncEvent(const sp<SyncEvent>& event __unused)
10216{
10217 return BAD_VALUE;
10218}
10219
10220bool AudioFlinger::MmapThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
10221{
10222 return false;
10223}
10224
10225status_t AudioFlinger::MmapThread::checkEffectCompatibility_l(
10226 const effect_descriptor_t *desc, audio_session_t sessionId)
10227{
10228 // No global effect sessions on mmap threads
Eric Laurent3f75a5b2019-11-12 15:55:51 -080010229 if (audio_is_global_session(sessionId)) {
10230 ALOGW("checkEffectCompatibility_l(): global effect %s on MMAP thread %s",
Eric Laurent6acd1d42017-01-04 14:23:29 -080010231 desc->name, mThreadName);
10232 return BAD_VALUE;
10233 }
10234
10235 if (!isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC)) {
10236 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on capture mmap thread",
10237 desc->name);
10238 return BAD_VALUE;
10239 }
10240 if (isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Glenn Kastend3bb6452016-12-05 18:14:37 -080010241 ALOGW("checkEffectCompatibility_l(): pre processing effect %s created on playback mmap "
10242 "thread", desc->name);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010243 return BAD_VALUE;
10244 }
10245
10246 // Only allow effects without processing load or latency
10247 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) != EFFECT_FLAG_NO_PROCESS) {
10248 return BAD_VALUE;
10249 }
10250
jiabineb3bda02020-06-30 14:07:03 -070010251 if (EffectModule::isHapticGenerator(&desc->type)) {
10252 ALOGE("%s(): HapticGenerator is not supported for MmapThread", __func__);
10253 return BAD_VALUE;
10254 }
10255
Eric Laurent6acd1d42017-01-04 14:23:29 -080010256 return NO_ERROR;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010257}
10258
10259void AudioFlinger::MmapThread::checkInvalidTracks_l()
10260{
10261 for (const sp<MmapTrack> &track : mActiveTracks) {
10262 if (track->isInvalid()) {
Phil Burk7f6b40d2017-02-09 13:18:38 -080010263 sp<MmapStreamCallback> callback = mCallback.promote();
10264 if (callback != 0) {
Eric Laurent734046e2018-04-16 14:50:52 -070010265 mLock.unlock();
Eric Laurent331679c2018-04-16 17:03:16 -070010266 callback->onTearDown(track->portId());
Eric Laurent734046e2018-04-16 14:50:52 -070010267 mLock.lock();
Eric Laurent331679c2018-04-16 17:03:16 -070010268 } else if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
10269 ALOGW("Could not notify MMAP stream tear down: no onTearDown callback!");
10270 mNoCallbackWarningCount++;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010271 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010272 }
10273 }
10274}
10275
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -070010276void AudioFlinger::MmapThread::dumpInternals_l(int fd, const Vector<String16>& args __unused)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010277{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010278 dprintf(fd, " Attributes: content type %d usage %d source %d\n",
10279 mAttr.content_type, mAttr.usage, mAttr.source);
10280 dprintf(fd, " Session: %d port Id: %d\n", mSessionId, mPortId);
Eric Tan39ec8d62018-07-24 09:49:29 -070010281 if (mActiveTracks.isEmpty()) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010282 dprintf(fd, " No active clients\n");
10283 }
10284}
10285
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -070010286void AudioFlinger::MmapThread::dumpTracks_l(int fd, const Vector<String16>& args __unused)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010287{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010288 String8 result;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010289 size_t numtracks = mActiveTracks.size();
Andy Hung2c6c3bb2017-06-16 14:01:45 -070010290 dprintf(fd, " %zu Tracks\n", numtracks);
10291 const char *prefix = " ";
Eric Laurent6acd1d42017-01-04 14:23:29 -080010292 if (numtracks) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -070010293 result.append(prefix);
Kevin Rocard5f2136e2018-05-11 22:03:00 -070010294 mActiveTracks[0]->appendDumpHeader(result);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010295 for (size_t i = 0; i < numtracks ; ++i) {
10296 sp<MmapTrack> track = mActiveTracks[i];
Andy Hung2c6c3bb2017-06-16 14:01:45 -070010297 result.append(prefix);
10298 track->appendDump(result, true /* active */);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010299 }
10300 } else {
10301 dprintf(fd, "\n");
10302 }
10303 write(fd, result.string(), result.size());
10304}
10305
10306AudioFlinger::MmapPlaybackThread::MmapPlaybackThread(
10307 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
jiabinc52b1ff2019-10-31 17:20:42 -070010308 AudioHwDevice *hwDev, AudioStreamOut *output, bool systemReady)
Andy Hungcf10d742020-04-28 15:38:24 -070010309 : MmapThread(audioFlinger, id, hwDev, output->stream, systemReady, true /* isOut */),
Eric Laurent6acd1d42017-01-04 14:23:29 -080010310 mStreamType(AUDIO_STREAM_MUSIC),
Phil Burk56ecf3e2018-03-12 15:38:17 -070010311 mStreamVolume(1.0),
10312 mStreamMute(false),
Phil Burk56ecf3e2018-03-12 15:38:17 -070010313 mOutput(output)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010314{
10315 snprintf(mThreadName, kThreadNameLength, "AudioMmapOut_%X", id);
10316 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
10317 mMasterVolume = audioFlinger->masterVolume_l();
10318 mMasterMute = audioFlinger->masterMute_l();
10319 if (mAudioHwDev) {
10320 if (mAudioHwDev->canSetMasterVolume()) {
10321 mMasterVolume = 1.0;
10322 }
10323
10324 if (mAudioHwDev->canSetMasterMute()) {
10325 mMasterMute = false;
10326 }
10327 }
10328}
10329
10330void AudioFlinger::MmapPlaybackThread::configure(const audio_attributes_t *attr,
10331 audio_stream_type_t streamType,
10332 audio_session_t sessionId,
10333 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010334 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010335 audio_port_handle_t portId)
10336{
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010337 MmapThread::configure(attr, streamType, sessionId, callback, deviceId, portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010338 mStreamType = streamType;
10339}
10340
10341AudioStreamOut* AudioFlinger::MmapPlaybackThread::clearOutput()
10342{
10343 Mutex::Autolock _l(mLock);
10344 AudioStreamOut *output = mOutput;
10345 mOutput = NULL;
10346 return output;
10347}
10348
10349void AudioFlinger::MmapPlaybackThread::setMasterVolume(float value)
10350{
10351 Mutex::Autolock _l(mLock);
10352 // Don't apply master volume in SW if our HAL can do it for us.
10353 if (mAudioHwDev &&
10354 mAudioHwDev->canSetMasterVolume()) {
10355 mMasterVolume = 1.0;
10356 } else {
10357 mMasterVolume = value;
10358 }
10359}
10360
10361void AudioFlinger::MmapPlaybackThread::setMasterMute(bool muted)
10362{
10363 Mutex::Autolock _l(mLock);
10364 // Don't apply master mute in SW if our HAL can do it for us.
10365 if (mAudioHwDev && mAudioHwDev->canSetMasterMute()) {
10366 mMasterMute = false;
10367 } else {
10368 mMasterMute = muted;
10369 }
10370}
10371
10372void AudioFlinger::MmapPlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
10373{
10374 Mutex::Autolock _l(mLock);
10375 if (stream == mStreamType) {
10376 mStreamVolume = value;
10377 broadcast_l();
10378 }
10379}
10380
10381float AudioFlinger::MmapPlaybackThread::streamVolume(audio_stream_type_t stream) const
10382{
10383 Mutex::Autolock _l(mLock);
10384 if (stream == mStreamType) {
10385 return mStreamVolume;
10386 }
10387 return 0.0f;
10388}
10389
10390void AudioFlinger::MmapPlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
10391{
10392 Mutex::Autolock _l(mLock);
10393 if (stream == mStreamType) {
10394 mStreamMute= muted;
10395 broadcast_l();
10396 }
10397}
10398
10399void AudioFlinger::MmapPlaybackThread::invalidateTracks(audio_stream_type_t streamType)
10400{
10401 Mutex::Autolock _l(mLock);
10402 if (streamType == mStreamType) {
10403 for (const sp<MmapTrack> &track : mActiveTracks) {
10404 track->invalidate();
10405 }
10406 broadcast_l();
10407 }
10408}
10409
10410void AudioFlinger::MmapPlaybackThread::processVolume_l()
10411{
10412 float volume;
10413
10414 if (mMasterMute || mStreamMute) {
10415 volume = 0;
10416 } else {
10417 volume = mMasterVolume * mStreamVolume;
10418 }
10419
10420 if (volume != mHalVolFloat) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010421
10422 // Convert volumes from float to 8.24
10423 uint32_t vol = (uint32_t)(volume * (1 << 24));
10424
10425 // Delegate volume control to effect in track effect chain if needed
10426 // only one effect chain can be present on DirectOutputThread, so if
10427 // there is one, the track is connected to it
10428 if (!mEffectChains.isEmpty()) {
10429 mEffectChains[0]->setVolume_l(&vol, &vol);
10430 volume = (float)vol / (1 << 24);
10431 }
Eric Laurentdff774a2017-04-21 15:29:38 -070010432 // Try to use HW volume control and fall back to SW control if not implemented
Phil Burk56ecf3e2018-03-12 15:38:17 -070010433 if (mOutput->stream->setVolume(volume, volume) == NO_ERROR) {
10434 mHalVolFloat = volume; // HW volume control worked, so update value.
10435 mNoCallbackWarningCount = 0;
10436 } else {
Eric Laurentdff774a2017-04-21 15:29:38 -070010437 sp<MmapStreamCallback> callback = mCallback.promote();
10438 if (callback != 0) {
Phil Burk56ecf3e2018-03-12 15:38:17 -070010439 mHalVolFloat = volume; // SW volume control worked, so update value.
10440 mNoCallbackWarningCount = 0;
Eric Laurent734046e2018-04-16 14:50:52 -070010441 mLock.unlock();
Robert Wu4389ae62022-02-17 18:39:41 +000010442 callback->onVolumeChanged(volume);
Eric Laurent734046e2018-04-16 14:50:52 -070010443 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010444 } else {
Phil Burk56ecf3e2018-03-12 15:38:17 -070010445 if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
10446 ALOGW("Could not set MMAP stream volume: no volume callback!");
10447 mNoCallbackWarningCount++;
10448 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010449 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010450 }
Jasmine Chaeaa10e42021-05-11 10:11:14 +080010451 for (const sp<MmapTrack> &track : mActiveTracks) {
10452 track->setMetadataHasChanged();
10453 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010454 }
10455}
10456
Kevin Rocard069c2712018-03-29 19:09:14 -070010457void AudioFlinger::MmapPlaybackThread::updateMetadata_l()
10458{
Jasmine Chaeaa10e42021-05-11 10:11:14 +080010459 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
10460 return; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -070010461 }
10462 StreamOutHalInterface::SourceMetadata metadata;
10463 for (const sp<MmapTrack> &track : mActiveTracks) {
10464 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurent94579172020-11-20 18:41:04 +010010465 playback_track_metadata_v7_t trackMetadata;
10466 trackMetadata.base = {
Kevin Rocard069c2712018-03-29 19:09:14 -070010467 .usage = track->attributes().usage,
10468 .content_type = track->attributes().content_type,
10469 .gain = mHalVolFloat, // TODO: propagate from aaudio pre-mix volume
Eric Laurent94579172020-11-20 18:41:04 +010010470 };
10471 trackMetadata.channel_mask = track->channelMask(),
10472 strncpy(trackMetadata.tags, track->attributes().tags, AUDIO_ATTRIBUTES_TAGS_MAX_SIZE);
10473 metadata.tracks.push_back(trackMetadata);
Kevin Rocard069c2712018-03-29 19:09:14 -070010474 }
10475 mOutput->stream->updateSourceMetadata(metadata);
10476}
10477
Eric Laurent6acd1d42017-01-04 14:23:29 -080010478void AudioFlinger::MmapPlaybackThread::checkSilentMode_l()
10479{
10480 if (!mMasterMute) {
10481 char value[PROPERTY_VALUE_MAX];
10482 if (property_get("ro.audio.silent", value, "0") > 0) {
10483 char *endptr;
10484 unsigned long ul = strtoul(value, &endptr, 0);
10485 if (*endptr == '\0' && ul != 0) {
10486 ALOGD("Silence is golden");
10487 // The setprop command will not allow a property to be changed after
10488 // the first time it is set, so we don't have to worry about un-muting.
10489 setMasterMute_l(true);
10490 }
10491 }
10492 }
10493}
10494
Mikhail Naganov32abc2b2018-05-24 12:57:11 -070010495void AudioFlinger::MmapPlaybackThread::toAudioPortConfig(struct audio_port_config *config)
10496{
10497 MmapThread::toAudioPortConfig(config);
10498 if (mOutput && mOutput->flags != AUDIO_OUTPUT_FLAG_NONE) {
10499 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
10500 config->flags.output = mOutput->flags;
10501 }
10502}
10503
jiabinb7d8c5a2020-08-26 17:24:52 -070010504status_t AudioFlinger::MmapPlaybackThread::getExternalPosition(uint64_t *position,
10505 int64_t *timeNanos)
10506{
10507 if (mOutput == nullptr) {
10508 return NO_INIT;
10509 }
10510 struct timespec timestamp;
10511 status_t status = mOutput->getPresentationPosition(position, &timestamp);
10512 if (status == NO_ERROR) {
10513 *timeNanos = timestamp.tv_sec * NANOS_PER_SECOND + timestamp.tv_nsec;
10514 }
10515 return status;
10516}
10517
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -070010518void AudioFlinger::MmapPlaybackThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010519{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -070010520 MmapThread::dumpInternals_l(fd, args);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010521
Glenn Kastend3bb6452016-12-05 18:14:37 -080010522 dprintf(fd, " Stream type: %d Stream volume: %f HAL volume: %f Stream mute %d\n",
10523 mStreamType, mStreamVolume, mHalVolFloat, mStreamMute);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010524 dprintf(fd, " Master volume: %f Master mute %d\n", mMasterVolume, mMasterMute);
10525}
10526
10527AudioFlinger::MmapCaptureThread::MmapCaptureThread(
10528 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
jiabinc52b1ff2019-10-31 17:20:42 -070010529 AudioHwDevice *hwDev, AudioStreamIn *input, bool systemReady)
Andy Hungcf10d742020-04-28 15:38:24 -070010530 : MmapThread(audioFlinger, id, hwDev, input->stream, systemReady, false /* isOut */),
Eric Laurent6acd1d42017-01-04 14:23:29 -080010531 mInput(input)
10532{
10533 snprintf(mThreadName, kThreadNameLength, "AudioMmapIn_%X", id);
10534 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
10535}
10536
Eric Laurentdda206a2022-07-08 17:28:35 +020010537status_t AudioFlinger::MmapCaptureThread::exitStandby_l()
Eric Laurent331679c2018-04-16 17:03:16 -070010538{
Phil Burkf054fc32018-12-06 09:45:59 -080010539 {
10540 // mInput might have been cleared by clearInput()
Phil Burkf054fc32018-12-06 09:45:59 -080010541 if (mInput != nullptr && mInput->stream != nullptr) {
10542 mInput->stream->setGain(1.0f);
10543 }
10544 }
Eric Laurentdda206a2022-07-08 17:28:35 +020010545 return MmapThread::exitStandby_l();
Eric Laurent331679c2018-04-16 17:03:16 -070010546}
10547
Eric Laurent6acd1d42017-01-04 14:23:29 -080010548AudioFlinger::AudioStreamIn* AudioFlinger::MmapCaptureThread::clearInput()
10549{
10550 Mutex::Autolock _l(mLock);
10551 AudioStreamIn *input = mInput;
10552 mInput = NULL;
10553 return input;
10554}
Kevin Rocard069c2712018-03-29 19:09:14 -070010555
Eric Laurent331679c2018-04-16 17:03:16 -070010556
10557void AudioFlinger::MmapCaptureThread::processVolume_l()
10558{
10559 bool changed = false;
10560 bool silenced = false;
10561
10562 sp<MmapStreamCallback> callback = mCallback.promote();
10563 if (callback == 0) {
10564 if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
10565 ALOGW("Could not set MMAP stream silenced: no onStreamSilenced callback!");
10566 mNoCallbackWarningCount++;
10567 }
10568 }
10569
10570 // After a change occurred in track silenced state, mute capture in audio DSP if at least one
10571 // track is silenced and unmute otherwise
10572 for (size_t i = 0; i < mActiveTracks.size() && !silenced; i++) {
10573 if (!mActiveTracks[i]->getAndSetSilencedNotified_l()) {
10574 changed = true;
10575 silenced = mActiveTracks[i]->isSilenced_l();
10576 }
10577 }
10578
10579 if (changed) {
10580 mInput->stream->setGain(silenced ? 0.0f: 1.0f);
10581 }
10582}
10583
Kevin Rocard069c2712018-03-29 19:09:14 -070010584void AudioFlinger::MmapCaptureThread::updateMetadata_l()
10585{
Jasmine Chaeaa10e42021-05-11 10:11:14 +080010586 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
10587 return; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -070010588 }
10589 StreamInHalInterface::SinkMetadata metadata;
10590 for (const sp<MmapTrack> &track : mActiveTracks) {
10591 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurent94579172020-11-20 18:41:04 +010010592 record_track_metadata_v7_t trackMetadata;
10593 trackMetadata.base = {
Kevin Rocard069c2712018-03-29 19:09:14 -070010594 .source = track->attributes().source,
10595 .gain = 1, // capture tracks do not have volumes
Eric Laurent94579172020-11-20 18:41:04 +010010596 };
10597 trackMetadata.channel_mask = track->channelMask(),
10598 strncpy(trackMetadata.tags, track->attributes().tags, AUDIO_ATTRIBUTES_TAGS_MAX_SIZE);
10599 metadata.tracks.push_back(trackMetadata);
Kevin Rocard069c2712018-03-29 19:09:14 -070010600 }
10601 mInput->stream->updateSinkMetadata(metadata);
10602}
10603
Eric Laurent5ada82e2019-08-29 17:53:54 -070010604void AudioFlinger::MmapCaptureThread::setRecordSilenced(audio_port_handle_t portId, bool silenced)
Eric Laurent331679c2018-04-16 17:03:16 -070010605{
10606 Mutex::Autolock _l(mLock);
10607 for (size_t i = 0; i < mActiveTracks.size() ; i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -070010608 if (mActiveTracks[i]->portId() == portId) {
Eric Laurent331679c2018-04-16 17:03:16 -070010609 mActiveTracks[i]->setSilenced_l(silenced);
10610 broadcast_l();
10611 }
10612 }
jiabin09609032022-06-15 19:26:01 +000010613 setClientSilencedIfExists_l(portId, silenced);
Eric Laurent331679c2018-04-16 17:03:16 -070010614}
10615
Mikhail Naganov32abc2b2018-05-24 12:57:11 -070010616void AudioFlinger::MmapCaptureThread::toAudioPortConfig(struct audio_port_config *config)
10617{
10618 MmapThread::toAudioPortConfig(config);
10619 if (mInput && mInput->flags != AUDIO_INPUT_FLAG_NONE) {
10620 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
10621 config->flags.input = mInput->flags;
10622 }
10623}
10624
jiabinb7d8c5a2020-08-26 17:24:52 -070010625status_t AudioFlinger::MmapCaptureThread::getExternalPosition(
10626 uint64_t *position, int64_t *timeNanos)
10627{
10628 if (mInput == nullptr) {
10629 return NO_INIT;
10630 }
10631 return mInput->getCapturePosition((int64_t*)position, timeNanos);
10632}
10633
Glenn Kasten63238ef2015-03-02 15:50:29 -080010634} // namespace android