blob: 87eb1f52cd14037e6a46c942e3faaffa37ed4bce [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 }
Atneya Nairba9a1072022-09-19 17:51:37 -07004106 const size_t framesToCopy = mNormalFrameCount * (mChannelCount + mHapticChannelCount);
4107 if (mFormat == AUDIO_FORMAT_PCM_FLOAT &&
4108 mEffectBufferFormat == AUDIO_FORMAT_PCM_FLOAT) {
4109 // Clamp PCM float values more than this distance from 0 to insulate
4110 // a HAL which doesn't handle NaN correctly.
4111 static constexpr float HAL_FLOAT_SAMPLE_LIMIT = 2.0f;
4112 memcpy_to_float_from_float_with_clamping(static_cast<float*>(mSinkBuffer),
4113 static_cast<const float*>(effectBuffer),
4114 framesToCopy, HAL_FLOAT_SAMPLE_LIMIT /* absMax */);
4115 } else {
4116 memcpy_by_audio_format(mSinkBuffer, mFormat,
4117 effectBuffer, mEffectBufferFormat, framesToCopy);
4118 }
jiabin245cdd92018-12-07 17:55:15 -08004119 // The sample data is partially interleaved when haptic channels exist,
4120 // we need to adjust channels here.
4121 if (mHapticChannelCount > 0) {
4122 adjust_channels_non_destructive(mSinkBuffer, mChannelCount, mSinkBuffer,
4123 mChannelCount + mHapticChannelCount,
4124 audio_bytes_per_sample(mFormat),
4125 audio_bytes_per_frame(mChannelCount, mFormat) * mNormalFrameCount);
4126 }
Andy Hung98ef9782014-03-04 14:46:50 -08004127 }
4128
Eric Laurent81784c32012-11-19 14:55:58 -08004129 // enable changes in effect chain
4130 unlockEffectChains(effectChains);
4131
Eric Laurentbfb1b832013-01-07 09:53:42 -08004132 if (!waitingAsyncCallback()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004133 // mSleepTimeUs == 0 means we must write to audio hardware
4134 if (mSleepTimeUs == 0) {
Andy Hung08fb1742015-05-31 23:22:10 -07004135 ssize_t ret = 0;
Andy Hung446f4df2019-02-21 12:26:41 -08004136 // writePeriodNs is updated >= 0 when ret > 0.
4137 int64_t writePeriodNs = -1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004138 if (mBytesRemaining) {
Andy Hung69488c42016-05-16 18:43:33 -07004139 // FIXME rewrite to reduce number of system calls
Andy Hung446f4df2019-02-21 12:26:41 -08004140 const int64_t lastIoBeginNs = systemTime();
Andy Hung08fb1742015-05-31 23:22:10 -07004141 ret = threadLoop_write();
Andy Hung446f4df2019-02-21 12:26:41 -08004142 const int64_t lastIoEndNs = systemTime();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004143 if (ret < 0) {
4144 mBytesRemaining = 0;
Andy Hung446f4df2019-02-21 12:26:41 -08004145 } else if (ret > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004146 mBytesWritten += ret;
4147 mBytesRemaining -= ret;
Andy Hung446f4df2019-02-21 12:26:41 -08004148 const int64_t frames = ret / mFrameSize;
4149 mFramesWritten += frames;
4150
4151 writePeriodNs = lastIoEndNs - mLastIoEndNs;
4152 // process information relating to write time.
4153 if (audio_has_proportional_frames(mFormat)) {
4154 // we are in a continuous mixing cycle
4155 if (mMixerStatus == MIXER_TRACKS_READY &&
4156 loopCount == lastLoopCountWritten + 1) {
4157
4158 const double jitterMs =
4159 TimestampVerifier<int64_t, int64_t>::computeJitterMs(
4160 {frames, writePeriodNs},
4161 {0, 0} /* lastTimestamp */, mSampleRate);
4162 const double processMs =
4163 (lastIoBeginNs - mLastIoEndNs) * 1e-6;
4164
4165 Mutex::Autolock _l(mLock);
4166 mIoJitterMs.add(jitterMs);
4167 mProcessTimeMs.add(processMs);
Robert Wu06db0a32021-08-10 19:05:34 +00004168
4169 if (mPipeSink.get() != nullptr) {
4170 // Using the Monopipe availableToWrite, we estimate the current
4171 // buffer size.
4172 MonoPipe* monoPipe = static_cast<MonoPipe*>(mPipeSink.get());
4173 const ssize_t
4174 availableToWrite = mPipeSink->availableToWrite();
4175 const size_t pipeFrames = monoPipe->maxFrames();
4176 const size_t
4177 remainingFrames = pipeFrames - max(availableToWrite, 0);
4178 mMonopipePipeDepthStats.add(remainingFrames);
4179 }
Andy Hung446f4df2019-02-21 12:26:41 -08004180 }
4181
4182 // write blocked detection
4183 const int64_t deltaWriteNs = lastIoEndNs - lastIoBeginNs;
Andy Hungd3639922022-04-28 18:00:49 -07004184 if ((mType == MIXER || mType == SPATIALIZER)
4185 && deltaWriteNs > maxPeriod) {
Andy Hung446f4df2019-02-21 12:26:41 -08004186 mNumDelayedWrites++;
4187 if ((lastIoEndNs - lastWarning) > kWarningThrottleNs) {
4188 ATRACE_NAME("underrun");
4189 ALOGW("write blocked for %lld msecs, "
4190 "%d delayed writes, thread %d",
4191 (long long)deltaWriteNs / NANOS_PER_MILLISECOND,
4192 mNumDelayedWrites, mId);
4193 lastWarning = lastIoEndNs;
4194 }
4195 }
4196 }
4197 // update timing info.
4198 mLastIoBeginNs = lastIoBeginNs;
4199 mLastIoEndNs = lastIoEndNs;
4200 lastLoopCountWritten = loopCount;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004201 }
4202 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
4203 (mMixerStatus == MIXER_DRAIN_ALL)) {
4204 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08004205 }
Andy Hungd3639922022-04-28 18:00:49 -07004206 if ((mType == MIXER || mType == SPATIALIZER) && !mStandby) {
Andy Hung08fb1742015-05-31 23:22:10 -07004207
4208 if (mThreadThrottle
4209 && mMixerStatus == MIXER_TRACKS_READY // we are mixing (active tracks)
Andy Hung446f4df2019-02-21 12:26:41 -08004210 && writePeriodNs > 0) { // we have write period info
Andy Hung08fb1742015-05-31 23:22:10 -07004211 // Limit MixerThread data processing to no more than twice the
4212 // expected processing rate.
4213 //
4214 // This helps prevent underruns with NuPlayer and other applications
4215 // which may set up buffers that are close to the minimum size, or use
4216 // deep buffers, and rely on a double-buffering sleep strategy to fill.
4217 //
4218 // The throttle smooths out sudden large data drains from the device,
4219 // e.g. when it comes out of standby, which often causes problems with
4220 // (1) mixer threads without a fast mixer (which has its own warm-up)
4221 // (2) minimum buffer sized tracks (even if the track is full,
4222 // the app won't fill fast enough to handle the sudden draw).
Haynes Mathew Georgef92b2172016-05-09 11:34:15 -07004223 //
4224 // Total time spent in last processing cycle equals time spent in
4225 // 1. threadLoop_write, as well as time spent in
4226 // 2. threadLoop_mix (significant for heavy mixing, especially
4227 // on low tier processors)
Andy Hung08fb1742015-05-31 23:22:10 -07004228
Andy Hung446f4df2019-02-21 12:26:41 -08004229 // it's OK if deltaMs is an overestimate.
4230
4231 const int32_t deltaMs = writePeriodNs / NANOS_PER_MILLISECOND;
Ivan Lozanoe02bc542017-10-26 09:51:54 -07004232
Ivan Lozanoea04d392017-11-07 14:37:07 -08004233 const int32_t throttleMs = (int32_t)mHalfBufferMs - deltaMs;
Andy Hung08fb1742015-05-31 23:22:10 -07004234 if ((signed)mHalfBufferMs >= throttleMs && throttleMs > 0) {
Andy Hungcf10d742020-04-28 15:38:24 -07004235 mThreadMetrics.logThrottleMs((double)throttleMs);
Andy Hungb68f5eb2019-12-03 16:49:17 -08004236
Andy Hung08fb1742015-05-31 23:22:10 -07004237 usleep(throttleMs * 1000);
Andy Hung40eb1a12015-06-18 13:42:02 -07004238 // notify of throttle start on verbose log
4239 ALOGV_IF(mThreadThrottleEndMs == mThreadThrottleTimeMs,
4240 "mixer(%p) throttle begin:"
4241 " ret(%zd) deltaMs(%d) requires sleep %d ms",
Andy Hung08fb1742015-05-31 23:22:10 -07004242 this, ret, deltaMs, throttleMs);
Andy Hung40eb1a12015-06-18 13:42:02 -07004243 mThreadThrottleTimeMs += throttleMs;
Andy Hung0a31ddd2016-07-06 19:10:29 -07004244 // Throttle must be attributed to the previous mixer loop's write time
4245 // to allow back-to-back throttling.
Andy Hung446f4df2019-02-21 12:26:41 -08004246 // This also ensures proper timing statistics.
4247 mLastIoEndNs = systemTime(); // we fetch the write end time again.
Andy Hung40eb1a12015-06-18 13:42:02 -07004248 } else {
4249 uint32_t diff = mThreadThrottleTimeMs - mThreadThrottleEndMs;
4250 if (diff > 0) {
4251 // notify of throttle end on debug log
Andy Hung3ea004d2016-05-05 16:48:37 -07004252 // but prevent spamming for bluetooth
jiabinc52b1ff2019-10-31 17:20:42 -07004253 ALOGD_IF(!isSingleDeviceType(
4254 outDeviceTypes(), audio_is_a2dp_out_device) &&
4255 !isSingleDeviceType(
4256 outDeviceTypes(), audio_is_hearing_aid_out_device),
Andy Hung3ea004d2016-05-05 16:48:37 -07004257 "mixer(%p) throttle end: throttle time(%u)", this, diff);
Andy Hung40eb1a12015-06-18 13:42:02 -07004258 mThreadThrottleEndMs = mThreadThrottleTimeMs;
4259 }
Andy Hung08fb1742015-05-31 23:22:10 -07004260 }
4261 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004262 }
Eric Laurent81784c32012-11-19 14:55:58 -08004263
Eric Laurentbfb1b832013-01-07 09:53:42 -08004264 } else {
Glenn Kastene7754022014-10-31 12:11:26 -07004265 ATRACE_BEGIN("sleep");
Eric Laurente93cc032016-05-05 10:15:10 -07004266 Mutex::Autolock _l(mLock);
rago1bb90822017-05-02 18:31:48 -07004267 // suspended requires accurate metering of sleep time.
4268 if (isSuspended()) {
4269 // advance by expected sleepTime
4270 timeLoopNextNs += microseconds((nsecs_t)mSleepTimeUs);
4271 const nsecs_t nowNs = systemTime();
4272
4273 // compute expected next time vs current time.
4274 // (negative deltas are treated as delays).
4275 nsecs_t deltaNs = timeLoopNextNs - nowNs;
4276 if (deltaNs < -kMaxNextBufferDelayNs) {
4277 // Delays longer than the max allowed trigger a reset.
4278 ALOGV("DelayNs: %lld, resetting timeLoopNextNs", (long long) deltaNs);
4279 deltaNs = microseconds((nsecs_t)mSleepTimeUs);
4280 timeLoopNextNs = nowNs + deltaNs;
4281 } else if (deltaNs < 0) {
4282 // Delays within the max delay allowed: zero the delta/sleepTime
4283 // to help the system catch up in the next iteration(s)
4284 ALOGV("DelayNs: %lld, catching-up", (long long) deltaNs);
4285 deltaNs = 0;
4286 }
4287 // update sleep time (which is >= 0)
4288 mSleepTimeUs = deltaNs / 1000;
4289 }
Eric Laurente93cc032016-05-05 10:15:10 -07004290 if (!mSignalPending && mConfigEvents.isEmpty() && !exitPending()) {
4291 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)mSleepTimeUs));
Eric Laurent51716182016-02-29 18:00:56 -08004292 }
Glenn Kastene7754022014-10-31 12:11:26 -07004293 ATRACE_END();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004294 }
Eric Laurent81784c32012-11-19 14:55:58 -08004295 }
4296
4297 // Finally let go of removed track(s), without the lock held
4298 // since we can't guarantee the destructors won't acquire that
4299 // same lock. This will also mutate and push a new fast mixer state.
4300 threadLoop_removeTracks(tracksToRemove);
4301 tracksToRemove.clear();
4302
4303 // FIXME I don't understand the need for this here;
4304 // it was in the original code but maybe the
4305 // assignment in saveOutputTracks() makes this unnecessary?
4306 clearOutputTracks();
4307
4308 // Effect chains will be actually deleted here if they were removed from
4309 // mEffectChains list during mixing or effects processing
4310 effectChains.clear();
4311
4312 // FIXME Note that the above .clear() is no longer necessary since effectChains
4313 // is now local to this block, but will keep it for now (at least until merge done).
4314 }
4315
Eric Laurentbfb1b832013-01-07 09:53:42 -08004316 threadLoop_exit();
4317
Eric Laurentcf817a22014-08-04 20:36:31 -07004318 if (!mStandby) {
4319 threadLoop_standby();
4320 mStandby = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004321 }
4322
4323 releaseWakeLock();
4324
4325 ALOGV("Thread %p type %d exiting", this, mType);
4326 return false;
4327}
4328
Dean Wheatley12473e92021-03-18 23:00:55 +11004329void AudioFlinger::PlaybackThread::collectTimestamps_l()
4330{
Dean Wheatley12473e92021-03-18 23:00:55 +11004331 if (mStandby) {
4332 mTimestampVerifier.discontinuity(discontinuityForStandbyOrFlush());
4333 return;
4334 } else if (mHwPaused) {
4335 mTimestampVerifier.discontinuity(mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS);
4336 return;
4337 }
4338
4339 // Gather the framesReleased counters for all active tracks,
4340 // and associate with the sink frames written out. We need
4341 // this to convert the sink timestamp to the track timestamp.
4342 bool kernelLocationUpdate = false;
4343 ExtendedTimestamp timestamp; // use private copy to fetch
4344
4345 // Always query HAL timestamp and update timestamp verifier. In standby or pause,
4346 // HAL may be draining some small duration buffered data for fade out.
4347 if (threadloop_getHalTimestamp_l(&timestamp) == OK) {
4348 mTimestampVerifier.add(timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL],
4349 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4350 mSampleRate);
4351
4352 if (isTimestampCorrectionEnabled()) {
4353 ALOGVV("TS_BEFORE: %d %lld %lld", id(),
4354 (long long)timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4355 (long long)timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]);
4356 auto correctedTimestamp = mTimestampVerifier.getLastCorrectedTimestamp();
4357 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4358 = correctedTimestamp.mFrames;
4359 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]
4360 = correctedTimestamp.mTimeNs;
4361 ALOGVV("TS_AFTER: %d %lld %lld", id(),
4362 (long long)timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4363 (long long)timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]);
4364
4365 // Note: Downstream latency only added if timestamp correction enabled.
4366 if (mDownstreamLatencyStatMs.getN() > 0) { // we have latency info.
4367 const int64_t newPosition =
4368 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4369 - int64_t(mDownstreamLatencyStatMs.getMean() * mSampleRate * 1e-3);
4370 // prevent retrograde
4371 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = max(
4372 newPosition,
4373 (mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4374 - mSuspendedFrames));
4375 }
4376 }
4377
4378 // We always fetch the timestamp here because often the downstream
4379 // sink will block while writing.
4380
4381 // We keep track of the last valid kernel position in case we are in underrun
4382 // and the normal mixer period is the same as the fast mixer period, or there
4383 // is some error from the HAL.
4384 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
4385 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
4386 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
4387 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
4388 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4389
4390 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
4391 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER];
4392 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
4393 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER];
4394 }
4395
4396 if (timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
4397 kernelLocationUpdate = true;
4398 } else {
4399 ALOGVV("getTimestamp error - no valid kernel position");
4400 }
4401
4402 // copy over kernel info
4403 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] =
4404 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4405 + mSuspendedFrames; // add frames discarded when suspended
4406 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] =
4407 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4408 } else {
4409 mTimestampVerifier.error();
4410 }
4411
4412 // mFramesWritten for non-offloaded tracks are contiguous
4413 // even after standby() is called. This is useful for the track frame
4414 // to sink frame mapping.
4415 bool serverLocationUpdate = false;
4416 if (mFramesWritten != mLastFramesWritten) {
4417 serverLocationUpdate = true;
4418 mLastFramesWritten = mFramesWritten;
4419 }
4420 // Only update timestamps if there is a meaningful change.
4421 // Either the kernel timestamp must be valid or we have written something.
4422 if (kernelLocationUpdate || serverLocationUpdate) {
4423 if (serverLocationUpdate) {
4424 // use the time before we called the HAL write - it is a bit more accurate
4425 // to when the server last read data than the current time here.
4426 //
4427 // If we haven't written anything, mLastIoBeginNs will be -1
4428 // and we use systemTime().
4429 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] = mFramesWritten;
4430 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = mLastIoBeginNs == -1
4431 ? systemTime() : mLastIoBeginNs;
4432 }
4433
4434 for (const sp<Track> &t : mActiveTracks) {
4435 if (!t->isFastTrack()) {
4436 t->updateTrackFrameInfo(
4437 t->mAudioTrackServerProxy->framesReleased(),
4438 mFramesWritten,
4439 mSampleRate,
4440 mTimestamp);
4441 }
4442 }
4443 }
4444
4445 if (audio_has_proportional_frames(mFormat)) {
4446 const double latencyMs = mTimestamp.getOutputServerLatencyMs(mSampleRate);
4447 if (latencyMs != 0.) { // note 0. means timestamp is empty.
4448 mLatencyMs.add(latencyMs);
4449 }
4450 }
4451#if 0
4452 // logFormat example
4453 if (z % 100 == 0) {
4454 timespec ts;
4455 clock_gettime(CLOCK_MONOTONIC, &ts);
4456 LOGT("This is an integer %d, this is a float %f, this is my "
4457 "pid %p %% %s %t", 42, 3.14, "and this is a timestamp", ts);
4458 LOGT("A deceptive null-terminated string %\0");
4459 }
4460 ++z;
4461#endif
4462}
4463
Eric Laurentbfb1b832013-01-07 09:53:42 -08004464// removeTracks_l() must be called with ThreadBase::mLock held
4465void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
4466{
Andy Hungfe726a62018-09-27 15:17:25 -07004467 for (const auto& track : tracksToRemove) {
4468 mActiveTracks.remove(track);
4469 ALOGV("%s(%d): removing track on session %d", __func__, track->id(), track->sessionId());
4470 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
4471 if (chain != 0) {
4472 ALOGV("%s(%d): stopping track on chain %p for session Id: %d",
4473 __func__, track->id(), chain.get(), track->sessionId());
4474 chain->decActiveTrackCnt();
4475 }
4476 // If an external client track, inform APM we're no longer active, and remove if needed.
4477 // We do this under lock so that the state is consistent if the Track is destroyed.
4478 if (track->isExternalTrack()) {
4479 AudioSystem::stopOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08004480 if (track->isTerminated()) {
Andy Hungfe726a62018-09-27 15:17:25 -07004481 AudioSystem::releaseOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08004482 }
4483 }
Andy Hungfe726a62018-09-27 15:17:25 -07004484 if (track->isTerminated()) {
4485 // remove from our tracks vector
4486 removeTrack_l(track);
4487 }
jiabineb3bda02020-06-30 14:07:03 -07004488 if (mHapticChannelCount > 0 &&
4489 ((track->channelMask() & AUDIO_CHANNEL_HAPTIC_ALL) != AUDIO_CHANNEL_NONE
4490 || (chain != nullptr && chain->containsHapticGeneratingEffect_l()))) {
jiabin57303cc2018-12-18 15:45:57 -08004491 mLock.unlock();
4492 // Unlock due to VibratorService will lock for this call and will
4493 // call Tracks.mute/unmute which also require thread's lock.
4494 AudioFlinger::onExternalVibrationStop(track->getExternalVibration());
4495 mLock.lock();
jiabine70bc7f2020-06-30 22:07:55 -07004496
4497 // When the track is stop, set the haptic intensity as MUTE
4498 // for the HapticGenerator effect.
4499 if (chain != nullptr) {
4500 chain->setHapticIntensity_l(track->id(), static_cast<int>(os::HapticScale::MUTE));
4501 }
jiabin245cdd92018-12-07 17:55:15 -08004502 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004503 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004504}
Eric Laurent81784c32012-11-19 14:55:58 -08004505
Eric Laurentaccc1472013-09-20 09:36:34 -07004506status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
4507{
4508 if (mNormalSink != 0) {
Andy Hung818e7a32016-02-16 18:08:07 -08004509 ExtendedTimestamp ets;
4510 status_t status = mNormalSink->getTimestamp(ets);
4511 if (status == NO_ERROR) {
4512 status = ets.getBestTimestamp(&timestamp);
4513 }
4514 return status;
Eric Laurentaccc1472013-09-20 09:36:34 -07004515 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004516 if ((mType == OFFLOAD || mType == DIRECT) && mOutput != NULL) {
Dean Wheatley12473e92021-03-18 23:00:55 +11004517 collectTimestamps_l();
4518 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] <= 0) {
4519 return INVALID_OPERATION;
Eric Laurentaccc1472013-09-20 09:36:34 -07004520 }
Dean Wheatley12473e92021-03-18 23:00:55 +11004521 timestamp.mPosition = mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
4522 const int64_t timeNs = mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4523 timestamp.mTime.tv_sec = timeNs / NANOS_PER_SECOND;
4524 timestamp.mTime.tv_nsec = timeNs - (timestamp.mTime.tv_sec * NANOS_PER_SECOND);
4525 return NO_ERROR;
Eric Laurentaccc1472013-09-20 09:36:34 -07004526 }
4527 return INVALID_OPERATION;
4528}
Eric Laurent1c333e22014-05-20 10:48:17 -07004529
Eric Laurenteab90452019-06-24 15:17:46 -07004530// For dedicated VoIP outputs, let the HAL apply the stream volume. Track volume is
4531// still applied by the mixer.
4532// All tracks attached to a mixer with flag VOIP_RX are tied to the same
4533// stream type STREAM_VOICE_CALL so this will only change the HAL volume once even
4534// if more than one track are active
4535status_t AudioFlinger::PlaybackThread::handleVoipVolume_l(float *volume)
4536{
4537 status_t result = NO_ERROR;
4538 if ((mOutput->flags & AUDIO_OUTPUT_FLAG_VOIP_RX) != 0) {
4539 if (*volume != mLeftVolFloat) {
4540 result = mOutput->stream->setVolume(*volume, *volume);
4541 ALOGE_IF(result != OK,
4542 "Error when setting output stream volume: %d", result);
4543 if (result == NO_ERROR) {
4544 mLeftVolFloat = *volume;
4545 }
4546 }
4547 // if stream volume was successfully sent to the HAL, mLeftVolFloat == v here and we
4548 // remove stream volume contribution from software volume.
4549 if (mLeftVolFloat == *volume) {
4550 *volume = 1.0f;
4551 }
4552 }
4553 return result;
4554}
4555
Eric Laurent054d9d32015-04-24 08:48:48 -07004556status_t AudioFlinger::MixerThread::createAudioPatch_l(const struct audio_patch *patch,
4557 audio_patch_handle_t *handle)
4558{
Andy Hungf60abce2016-08-26 11:37:54 -07004559 status_t status;
4560 if (property_get_bool("af.patch_park", false /* default_value */)) {
4561 // Park FastMixer to avoid potential DOS issues with writing to the HAL
4562 // or if HAL does not properly lock against access.
4563 AutoPark<FastMixer> park(mFastMixer);
4564 status = PlaybackThread::createAudioPatch_l(patch, handle);
4565 } else {
4566 status = PlaybackThread::createAudioPatch_l(patch, handle);
4567 }
Eric Laurent054d9d32015-04-24 08:48:48 -07004568 return status;
4569}
4570
Eric Laurent1c333e22014-05-20 10:48:17 -07004571status_t AudioFlinger::PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
4572 audio_patch_handle_t *handle)
4573{
4574 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07004575
4576 // store new device and send to effects
4577 audio_devices_t type = AUDIO_DEVICE_NONE;
jiabinc52b1ff2019-10-31 17:20:42 -07004578 AudioDeviceTypeAddrVector deviceTypeAddrs;
Eric Laurent054d9d32015-04-24 08:48:48 -07004579 for (unsigned int i = 0; i < patch->num_sinks; i++) {
jiabinc52b1ff2019-10-31 17:20:42 -07004580 LOG_ALWAYS_FATAL_IF(popcount(patch->sinks[i].ext.device.type) > 1
4581 && !mOutput->audioHwDev->supportsAudioPatches(),
4582 "Enumerated device type(%#x) must not be used "
4583 "as it does not support audio patches",
4584 patch->sinks[i].ext.device.type);
Mikhail Naganov55773032020-10-01 15:08:13 -07004585 type = static_cast<audio_devices_t>(type | patch->sinks[i].ext.device.type);
jiabinc52b1ff2019-10-31 17:20:42 -07004586 deviceTypeAddrs.push_back(AudioDeviceTypeAddr(patch->sinks[i].ext.device.type,
4587 patch->sinks[i].ext.device.address));
Eric Laurent054d9d32015-04-24 08:48:48 -07004588 }
4589
François Gaffie0c280aa2018-07-25 10:02:15 +02004590 audio_port_handle_t sinkPortId = patch->sinks[0].id;
Eric Laurent054d9d32015-04-24 08:48:48 -07004591#ifdef ADD_BATTERY_DATA
4592 // when changing the audio output device, call addBatteryData to notify
4593 // the change
jiabinc52b1ff2019-10-31 17:20:42 -07004594 if (outDeviceTypes() != deviceTypes) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004595 uint32_t params = 0;
4596 // check whether speaker is on
jiabinc52b1ff2019-10-31 17:20:42 -07004597 if (deviceTypes.count(AUDIO_DEVICE_OUT_SPEAKER) > 0) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004598 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent1c333e22014-05-20 10:48:17 -07004599 }
4600
Eric Laurent054d9d32015-04-24 08:48:48 -07004601 // check if any other device (except speaker) is on
jiabinc52b1ff2019-10-31 17:20:42 -07004602 if (!isSingleDeviceType(deviceTypes, AUDIO_DEVICE_OUT_SPEAKER)) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004603 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
4604 }
4605
4606 if (params != 0) {
4607 addBatteryData(params);
4608 }
4609 }
4610#endif
4611
4612 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08004613 mEffectChains[i]->setDevices_l(deviceTypeAddrs);
Eric Laurent054d9d32015-04-24 08:48:48 -07004614 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07004615
jiabinc52b1ff2019-10-31 17:20:42 -07004616 // mPatch.num_sinks is not set when the thread is created so that
4617 // the first patch creation triggers an ioConfigChanged callback
4618 bool configChanged = (mPatch.num_sinks == 0) ||
4619 (mPatch.sinks[0].id != sinkPortId);
Eric Laurent296fb132015-05-01 11:38:42 -07004620 mPatch = *patch;
jiabinc52b1ff2019-10-31 17:20:42 -07004621 mOutDeviceTypeAddrs = deviceTypeAddrs;
jiabin0a957d32020-04-29 10:56:20 -07004622 checkSilentMode_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07004623
Mikhail Naganov9ee05402016-10-13 15:58:17 -07004624 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07004625 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
4626 status = hwDevice->createAudioPatch(patch->num_sources,
4627 patch->sources,
4628 patch->num_sinks,
4629 patch->sinks,
4630 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07004631 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08004632 status = mOutput->stream->legacyCreateAudioPatch(patch->sinks[0], std::nullopt, type);
Eric Laurent054d9d32015-04-24 08:48:48 -07004633 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07004634 }
Andy Hungc2b11cb2020-04-22 09:04:01 -07004635 const std::string patchSinksAsString = patchSinksToString(patch);
Andy Hungcf10d742020-04-28 15:38:24 -07004636
4637 mThreadMetrics.logEndInterval();
Andy Hungea840382020-05-05 21:50:17 -07004638 mThreadMetrics.logCreatePatch(/* inDevices */ {}, patchSinksAsString);
Andy Hungcf10d742020-04-28 15:38:24 -07004639 mThreadMetrics.logBeginInterval();
Andy Hungc2b11cb2020-04-22 09:04:01 -07004640 // also dispatch to active AudioTracks for MediaMetrics
4641 for (const auto &track : mActiveTracks) {
4642 track->logEndInterval();
4643 track->logBeginInterval(patchSinksAsString);
4644 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08004645
Eric Laurente8726fe2015-06-26 09:39:24 -07004646 if (configChanged) {
4647 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
4648 }
Eric Laurentdda206a2022-07-08 17:28:35 +02004649 // Force meteadata update after a route change
4650 mActiveTracks.setHasChanged();
4651
Eric Laurent1c333e22014-05-20 10:48:17 -07004652 return status;
4653}
4654
Eric Laurent054d9d32015-04-24 08:48:48 -07004655status_t AudioFlinger::MixerThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
4656{
Andy Hungf60abce2016-08-26 11:37:54 -07004657 status_t status;
4658 if (property_get_bool("af.patch_park", false /* default_value */)) {
4659 // Park FastMixer to avoid potential DOS issues with writing to the HAL
4660 // or if HAL does not properly lock against access.
4661 AutoPark<FastMixer> park(mFastMixer);
4662 status = PlaybackThread::releaseAudioPatch_l(handle);
4663 } else {
4664 status = PlaybackThread::releaseAudioPatch_l(handle);
4665 }
Eric Laurent054d9d32015-04-24 08:48:48 -07004666 return status;
4667}
4668
Eric Laurent1c333e22014-05-20 10:48:17 -07004669status_t AudioFlinger::PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
4670{
4671 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07004672
jiabinc52b1ff2019-10-31 17:20:42 -07004673 mPatch = audio_patch{};
4674 mOutDeviceTypeAddrs.clear();
Eric Laurent054d9d32015-04-24 08:48:48 -07004675
Mikhail Naganov9ee05402016-10-13 15:58:17 -07004676 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07004677 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
4678 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07004679 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08004680 status = mOutput->stream->legacyReleaseAudioPatch();
Eric Laurent1c333e22014-05-20 10:48:17 -07004681 }
Eric Laurentdda206a2022-07-08 17:28:35 +02004682 // Force meteadata update after a route change
4683 mActiveTracks.setHasChanged();
4684
Eric Laurent1c333e22014-05-20 10:48:17 -07004685 return status;
4686}
4687
Eric Laurent83b88082014-06-20 18:31:16 -07004688void AudioFlinger::PlaybackThread::addPatchTrack(const sp<PatchTrack>& track)
4689{
4690 Mutex::Autolock _l(mLock);
4691 mTracks.add(track);
4692}
4693
4694void AudioFlinger::PlaybackThread::deletePatchTrack(const sp<PatchTrack>& track)
4695{
4696 Mutex::Autolock _l(mLock);
4697 destroyTrack_l(track);
4698}
4699
Mikhail Naganovdc769682018-05-04 15:34:08 -07004700void AudioFlinger::PlaybackThread::toAudioPortConfig(struct audio_port_config *config)
Eric Laurent83b88082014-06-20 18:31:16 -07004701{
Mikhail Naganovdc769682018-05-04 15:34:08 -07004702 ThreadBase::toAudioPortConfig(config);
Eric Laurent83b88082014-06-20 18:31:16 -07004703 config->role = AUDIO_PORT_ROLE_SOURCE;
4704 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
4705 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07004706 if (mOutput && mOutput->flags != AUDIO_OUTPUT_FLAG_NONE) {
4707 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
4708 config->flags.output = mOutput->flags;
4709 }
Eric Laurent83b88082014-06-20 18:31:16 -07004710}
4711
Eric Laurent81784c32012-11-19 14:55:58 -08004712// ----------------------------------------------------------------------------
4713
4714AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Eric Laurentf1f22e72021-07-13 14:04:14 +02004715 audio_io_handle_t id, bool systemReady, type_t type, audio_config_base_t *mixerConfig)
4716 : PlaybackThread(audioFlinger, output, id, type, systemReady, mixerConfig),
Eric Laurent81784c32012-11-19 14:55:58 -08004717 // mAudioMixer below
4718 // mFastMixer below
Andy Hung2ddee192015-12-18 17:34:44 -08004719 mFastMixerFutex(0),
4720 mMasterMono(false)
Eric Laurent81784c32012-11-19 14:55:58 -08004721 // mOutputSink below
4722 // mPipeSink below
4723 // mNormalSink below
4724{
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01004725 setMasterBalance(audioFlinger->getMasterBalance_l());
jiabinc52b1ff2019-10-31 17:20:42 -07004726 ALOGV("MixerThread() id=%d type=%d", id, type);
Glenn Kasten49f36ba2017-12-06 13:02:02 -08004727 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%#x, mFrameSize=%zu, "
Glenn Kastenc42e9b42016-03-21 11:35:03 -07004728 "mFrameCount=%zu, mNormalFrameCount=%zu",
Eric Laurent81784c32012-11-19 14:55:58 -08004729 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
4730 mNormalFrameCount);
4731 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
4732
Andy Hungfbfc3952015-01-15 13:33:51 -08004733 if (type == DUPLICATING) {
4734 // The Duplicating thread uses the AudioMixer and delivers data to OutputTracks
4735 // (downstream MixerThreads) in DuplicatingThread::threadLoop_write().
4736 // Do not create or use mFastMixer, mOutputSink, mPipeSink, or mNormalSink.
4737 return;
4738 }
Eric Laurent81784c32012-11-19 14:55:58 -08004739 // create an NBAIO sink for the HAL output stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07004740 mOutputSink = new AudioStreamOutSink(output->stream);
Eric Laurent81784c32012-11-19 14:55:58 -08004741 size_t numCounterOffers = 0;
jiabin245cdd92018-12-07 17:55:15 -08004742 const NBAIO_Format offers[1] = {Format_from_SR_C(
4743 mSampleRate, mChannelCount + mHapticChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07004744#if !LOG_NDEBUG
4745 ssize_t index =
4746#else
4747 (void)
4748#endif
4749 mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08004750 ALOG_ASSERT(index == 0);
4751
4752 // initialize fast mixer depending on configuration
4753 bool initFastMixer;
Eric Laurentb62d0362021-10-26 17:40:18 +02004754 if (mType == SPATIALIZER) {
Eric Laurent81784c32012-11-19 14:55:58 -08004755 initFastMixer = false;
Eric Laurentb62d0362021-10-26 17:40:18 +02004756 } else {
4757 switch (kUseFastMixer) {
4758 case FastMixer_Never:
4759 initFastMixer = false;
4760 break;
4761 case FastMixer_Always:
4762 initFastMixer = true;
4763 break;
4764 case FastMixer_Static:
4765 case FastMixer_Dynamic:
4766 initFastMixer = mFrameCount < mNormalFrameCount;
4767 break;
4768 }
4769 ALOGW_IF(initFastMixer == false && mFrameCount < mNormalFrameCount,
4770 "FastMixer is preferred for this sink as frameCount %zu is less than threshold %zu",
4771 mFrameCount, mNormalFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08004772 }
4773 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07004774 audio_format_t fastMixerFormat;
4775 if (mMixerBufferEnabled && mEffectBufferEnabled) {
4776 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
4777 } else {
4778 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
4779 }
4780 if (mFormat != fastMixerFormat) {
4781 // change our Sink format to accept our intermediate precision
4782 mFormat = fastMixerFormat;
4783 free(mSinkBuffer);
jiabin245cdd92018-12-07 17:55:15 -08004784 mFrameSize = audio_bytes_per_frame(mChannelCount + mHapticChannelCount, mFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07004785 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
4786 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
4787 }
Eric Laurent81784c32012-11-19 14:55:58 -08004788
4789 // create a MonoPipe to connect our submix to FastMixer
4790 NBAIO_Format format = mOutputSink->format();
Andy Hung8946a282018-04-19 20:04:56 -07004791
Andy Hung1258c1a2014-05-23 21:22:17 -07004792 // adjust format to match that of the Fast Mixer
Glenn Kasten49f36ba2017-12-06 13:02:02 -08004793 ALOGV("format changed from %#x to %#x", format.mFormat, fastMixerFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07004794 format.mFormat = fastMixerFormat;
4795 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
4796
Eric Laurent81784c32012-11-19 14:55:58 -08004797 // This pipe depth compensates for scheduling latency of the normal mixer thread.
4798 // When it wakes up after a maximum latency, it runs a few cycles quickly before
4799 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
4800 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
4801 const NBAIO_Format offers[1] = {format};
4802 size_t numCounterOffers = 0;
Andy Hung8946a282018-04-19 20:04:56 -07004803#if !LOG_NDEBUG
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07004804 ssize_t index =
4805#else
4806 (void)
4807#endif
4808 monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08004809 ALOG_ASSERT(index == 0);
4810 monoPipe->setAvgFrames((mScreenState & 1) ?
4811 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
4812 mPipeSink = monoPipe;
4813
Eric Laurent81784c32012-11-19 14:55:58 -08004814 // create fast mixer and configure it initially with just one fast track for our submix
Andy Hung8946a282018-04-19 20:04:56 -07004815 mFastMixer = new FastMixer(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08004816 FastMixerStateQueue *sq = mFastMixer->sq();
4817#ifdef STATE_QUEUE_DUMP
4818 sq->setObserverDump(&mStateQueueObserverDump);
4819 sq->setMutatorDump(&mStateQueueMutatorDump);
4820#endif
4821 FastMixerState *state = sq->begin();
4822 FastTrack *fastTrack = &state->mFastTracks[0];
4823 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
4824 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
4825 fastTrack->mVolumeProvider = NULL;
Mikhail Naganov55773032020-10-01 15:08:13 -07004826 fastTrack->mChannelMask = static_cast<audio_channel_mask_t>(
4827 mChannelMask | mHapticChannelMask); // mPipeSink channel mask for
4828 // audio to FastMixer
Andy Hunge8a1ced2014-05-09 15:02:21 -07004829 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
jiabin245cdd92018-12-07 17:55:15 -08004830 fastTrack->mHapticPlaybackEnabled = mHapticChannelMask != AUDIO_CHANNEL_NONE;
jiabine70bc7f2020-06-30 22:07:55 -07004831 fastTrack->mHapticIntensity = os::HapticScale::NONE;
Lais Andradebc3f37a2021-07-02 00:13:19 +01004832 fastTrack->mHapticMaxAmplitude = NAN;
Eric Laurent81784c32012-11-19 14:55:58 -08004833 fastTrack->mGeneration++;
4834 state->mFastTracksGen++;
4835 state->mTrackMask = 1;
4836 // fast mixer will use the HAL output sink
4837 state->mOutputSink = mOutputSink.get();
4838 state->mOutputSinkGen++;
4839 state->mFrameCount = mFrameCount;
jiabin245cdd92018-12-07 17:55:15 -08004840 // specify sink channel mask when haptic channel mask present as it can not
4841 // be calculated directly from channel count
4842 state->mSinkChannelMask = mHapticChannelMask == AUDIO_CHANNEL_NONE
Mikhail Naganov55773032020-10-01 15:08:13 -07004843 ? AUDIO_CHANNEL_NONE
4844 : static_cast<audio_channel_mask_t>(mChannelMask | mHapticChannelMask);
Eric Laurent81784c32012-11-19 14:55:58 -08004845 state->mCommand = FastMixerState::COLD_IDLE;
4846 // already done in constructor initialization list
4847 //mFastMixerFutex = 0;
4848 state->mColdFutexAddr = &mFastMixerFutex;
4849 state->mColdGen++;
4850 state->mDumpState = &mFastMixerDumpState;
Glenn Kasten9e58b552013-01-18 15:09:48 -08004851 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
4852 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08004853 sq->end();
4854 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
4855
Eric Tan0513b5d2018-09-17 10:32:48 -07004856 NBLog::thread_info_t info;
4857 info.id = mId;
4858 info.type = NBLog::FASTMIXER;
4859 mFastMixerNBLogWriter->log<NBLog::EVENT_THREAD_INFO>(info);
4860
Eric Laurent81784c32012-11-19 14:55:58 -08004861 // start the fast mixer
4862 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
4863 pid_t tid = mFastMixer->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07004864 sendPrioConfigEvent(getpid(), tid, kPriorityFastMixer, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08004865 stream()->setHalThreadPriority(kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08004866
4867#ifdef AUDIO_WATCHDOG
4868 // create and start the watchdog
4869 mAudioWatchdog = new AudioWatchdog();
4870 mAudioWatchdog->setDump(&mAudioWatchdogDump);
4871 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
4872 tid = mAudioWatchdog->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07004873 sendPrioConfigEvent(getpid(), tid, kPriorityFastMixer, false /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08004874#endif
Andy Hung8946a282018-04-19 20:04:56 -07004875 } else {
4876#ifdef TEE_SINK
4877 // Only use the MixerThread tee if there is no FastMixer.
4878 mTee.set(mOutputSink->format(), NBAIO_Tee::TEE_FLAG_OUTPUT_THREAD);
4879 mTee.setId(std::string("_") + std::to_string(mId) + "_M");
4880#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004881 }
4882
4883 switch (kUseFastMixer) {
4884 case FastMixer_Never:
4885 case FastMixer_Dynamic:
4886 mNormalSink = mOutputSink;
4887 break;
4888 case FastMixer_Always:
4889 mNormalSink = mPipeSink;
4890 break;
4891 case FastMixer_Static:
4892 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
4893 break;
4894 }
4895}
4896
4897AudioFlinger::MixerThread::~MixerThread()
4898{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004899 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004900 FastMixerStateQueue *sq = mFastMixer->sq();
4901 FastMixerState *state = sq->begin();
4902 if (state->mCommand == FastMixerState::COLD_IDLE) {
4903 int32_t old = android_atomic_inc(&mFastMixerFutex);
4904 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07004905 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08004906 }
4907 }
4908 state->mCommand = FastMixerState::EXIT;
4909 sq->end();
4910 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
4911 mFastMixer->join();
4912 // Though the fast mixer thread has exited, it's state queue is still valid.
4913 // We'll use that extract the final state which contains one remaining fast track
4914 // corresponding to our sub-mix.
4915 state = sq->begin();
4916 ALOG_ASSERT(state->mTrackMask == 1);
4917 FastTrack *fastTrack = &state->mFastTracks[0];
4918 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
4919 delete fastTrack->mBufferProvider;
4920 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004921 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08004922#ifdef AUDIO_WATCHDOG
4923 if (mAudioWatchdog != 0) {
4924 mAudioWatchdog->requestExit();
4925 mAudioWatchdog->requestExitAndWait();
4926 mAudioWatchdog.clear();
4927 }
4928#endif
4929 }
Glenn Kasten9e58b552013-01-18 15:09:48 -08004930 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08004931 delete mAudioMixer;
4932}
4933
4934
4935uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
4936{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004937 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004938 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
4939 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
4940 }
4941 return latency;
4942}
4943
Eric Laurentbfb1b832013-01-07 09:53:42 -08004944ssize_t AudioFlinger::MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08004945{
4946 // FIXME we should only do one push per cycle; confirm this is true
4947 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004948 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004949 FastMixerStateQueue *sq = mFastMixer->sq();
4950 FastMixerState *state = sq->begin();
4951 if (state->mCommand != FastMixerState::MIX_WRITE &&
4952 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
4953 if (state->mCommand == FastMixerState::COLD_IDLE) {
Eric Laurenta2ab4502015-09-09 12:25:51 -07004954
4955 // FIXME workaround for first HAL write being CPU bound on some devices
4956 ATRACE_BEGIN("write");
4957 mOutput->write((char *)mSinkBuffer, 0);
4958 ATRACE_END();
4959
Eric Laurent81784c32012-11-19 14:55:58 -08004960 int32_t old = android_atomic_inc(&mFastMixerFutex);
4961 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07004962 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08004963 }
4964#ifdef AUDIO_WATCHDOG
4965 if (mAudioWatchdog != 0) {
4966 mAudioWatchdog->resume();
4967 }
4968#endif
4969 }
4970 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kastend797a9d2015-03-02 14:19:25 -08004971#ifdef FAST_THREAD_STATISTICS
Glenn Kasten4182c4e2013-07-15 14:45:07 -07004972 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08004973 FastThreadDumpState::kSamplingNforLowRamDevice : FastThreadDumpState::kSamplingN);
Glenn Kastend797a9d2015-03-02 14:19:25 -08004974#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004975 sq->end();
4976 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
4977 if (kUseFastMixer == FastMixer_Dynamic) {
4978 mNormalSink = mPipeSink;
4979 }
4980 } else {
4981 sq->end(false /*didModify*/);
4982 }
4983 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004984 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08004985}
4986
4987void AudioFlinger::MixerThread::threadLoop_standby()
4988{
4989 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004990 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004991 FastMixerStateQueue *sq = mFastMixer->sq();
4992 FastMixerState *state = sq->begin();
4993 if (!(state->mCommand & FastMixerState::IDLE)) {
Andy Hung2148bf02016-11-28 19:01:02 -08004994 // Report any frames trapped in the Monopipe
4995 MonoPipe *monoPipe = (MonoPipe *)mPipeSink.get();
4996 const long long pipeFrames = monoPipe->maxFrames() - monoPipe->availableToWrite();
4997 mLocalLog.log("threadLoop_standby: framesWritten:%lld suspendedFrames:%lld "
4998 "monoPipeWritten:%lld monoPipeLeft:%lld",
4999 (long long)mFramesWritten, (long long)mSuspendedFrames,
5000 (long long)mPipeSink->framesWritten(), pipeFrames);
5001 mLocalLog.log("threadLoop_standby: %s", mTimestamp.toString().c_str());
5002
Eric Laurent81784c32012-11-19 14:55:58 -08005003 state->mCommand = FastMixerState::COLD_IDLE;
5004 state->mColdFutexAddr = &mFastMixerFutex;
5005 state->mColdGen++;
5006 mFastMixerFutex = 0;
5007 sq->end();
5008 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
5009 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
5010 if (kUseFastMixer == FastMixer_Dynamic) {
5011 mNormalSink = mOutputSink;
5012 }
5013#ifdef AUDIO_WATCHDOG
5014 if (mAudioWatchdog != 0) {
5015 mAudioWatchdog->pause();
5016 }
5017#endif
5018 } else {
5019 sq->end(false /*didModify*/);
5020 }
5021 }
5022 PlaybackThread::threadLoop_standby();
5023}
5024
Eric Laurentbfb1b832013-01-07 09:53:42 -08005025bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
5026{
5027 return false;
5028}
5029
5030bool AudioFlinger::PlaybackThread::shouldStandby_l()
5031{
5032 return !mStandby;
5033}
5034
5035bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
5036{
5037 Mutex::Autolock _l(mLock);
5038 return waitingAsyncCallback_l();
5039}
5040
Eric Laurent81784c32012-11-19 14:55:58 -08005041// shared by MIXER and DIRECT, overridden by DUPLICATING
5042void AudioFlinger::PlaybackThread::threadLoop_standby()
5043{
5044 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
Phil Burk062e67a2015-02-11 13:40:50 -08005045 mOutput->standby();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005046 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005047 // discard any pending drain or write ack by incrementing sequence
5048 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
5049 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005050 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005051 mCallbackThread->setWriteBlocked(mWriteAckSequence);
5052 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005053 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08005054 mHwPaused = false;
Eric Laurent68a40a82022-05-03 18:15:04 +02005055 setHalLatencyMode_l();
Eric Laurent81784c32012-11-19 14:55:58 -08005056}
5057
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08005058void AudioFlinger::PlaybackThread::onAddNewTrack_l()
5059{
5060 ALOGV("signal playback thread");
5061 broadcast_l();
5062}
5063
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005064void AudioFlinger::PlaybackThread::onAsyncError()
5065{
5066 for (int i = AUDIO_STREAM_SYSTEM; i < (int)AUDIO_STREAM_CNT; i++) {
5067 invalidateTracks((audio_stream_type_t)i);
5068 }
5069}
5070
Eric Laurent81784c32012-11-19 14:55:58 -08005071void AudioFlinger::MixerThread::threadLoop_mix()
5072{
Eric Laurent81784c32012-11-19 14:55:58 -08005073 // mix buffers...
Glenn Kastend79072e2016-01-06 08:41:20 -08005074 mAudioMixer->process();
Andy Hung25c2dac2014-02-27 14:56:00 -08005075 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005076 // increase sleep time progressively when application underrun condition clears.
5077 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
5078 // that a steady state of alternating ready/not ready conditions keeps the sleep time
5079 // such that we would underrun the audio HAL.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005080 if ((mSleepTimeUs == 0) && (sleepTimeShift > 0)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005081 sleepTimeShift--;
5082 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005083 mSleepTimeUs = 0;
5084 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08005085 //TODO: delay standby when effects have a tail
Glenn Kasten4c053ea2014-09-28 14:41:07 -07005086
Eric Laurent81784c32012-11-19 14:55:58 -08005087}
5088
5089void AudioFlinger::MixerThread::threadLoop_sleepTime()
5090{
5091 // If no tracks are ready, sleep once for the duration of an output
5092 // buffer size, then write 0s to the output
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005093 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005094 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Andy Hung06d13222018-05-03 20:13:31 -07005095 if (mPipeSink.get() != nullptr && mPipeSink == mNormalSink) {
5096 // Using the Monopipe availableToWrite, we estimate the
5097 // sleep time to retry for more data (before we underrun).
5098 MonoPipe *monoPipe = static_cast<MonoPipe *>(mPipeSink.get());
5099 const ssize_t availableToWrite = mPipeSink->availableToWrite();
5100 const size_t pipeFrames = monoPipe->maxFrames();
5101 const size_t framesLeft = pipeFrames - max(availableToWrite, 0);
5102 // HAL_framecount <= framesDelay ~ framesLeft / 2 <= Normal_Mixer_framecount
5103 const size_t framesDelay = std::min(
5104 mNormalFrameCount, max(framesLeft / 2, mFrameCount));
5105 ALOGV("pipeFrames:%zu framesLeft:%zu framesDelay:%zu",
5106 pipeFrames, framesLeft, framesDelay);
5107 mSleepTimeUs = framesDelay * MICROS_PER_SECOND / mSampleRate;
5108 } else {
5109 mSleepTimeUs = mActiveSleepTimeUs >> sleepTimeShift;
5110 if (mSleepTimeUs < kMinThreadSleepTimeUs) {
5111 mSleepTimeUs = kMinThreadSleepTimeUs;
5112 }
5113 // reduce sleep time in case of consecutive application underruns to avoid
5114 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
5115 // duration we would end up writing less data than needed by the audio HAL if
5116 // the condition persists.
5117 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
5118 sleepTimeShift++;
5119 }
Eric Laurent81784c32012-11-19 14:55:58 -08005120 }
5121 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005122 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005123 }
5124 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08005125 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
5126 // before effects processing or output.
5127 if (mMixerBufferValid) {
5128 memset(mMixerBuffer, 0, mMixerBufferSize);
Eric Laurent39095982021-08-24 18:29:27 +02005129 if (mType == SPATIALIZER) {
5130 memset(mSinkBuffer, 0, mSinkBufferSize);
5131 }
Andy Hung98ef9782014-03-04 14:46:50 -08005132 } else {
5133 memset(mSinkBuffer, 0, mSinkBufferSize);
5134 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005135 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005136 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
5137 "anticipated start");
5138 }
5139 // TODO add standby time extension fct of effect tail
5140}
5141
5142// prepareTracks_l() must be called with ThreadBase::mLock held
5143AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
5144 Vector< sp<Track> > *tracksToRemove)
5145{
Andy Hungc0691382018-09-12 18:01:57 -07005146 // clean up deleted track ids in AudioMixer before allocating new tracks
5147 (void)mTracks.processDeletedTrackIds([this](int trackId) {
5148 // for each trackId, destroy it in the AudioMixer
5149 if (mAudioMixer->exists(trackId)) {
5150 mAudioMixer->destroy(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08005151 }
5152 });
Andy Hungc0691382018-09-12 18:01:57 -07005153 mTracks.clearDeletedTrackIds();
Eric Laurent81784c32012-11-19 14:55:58 -08005154
5155 mixer_state mixerStatus = MIXER_IDLE;
5156 // find out which tracks need to be processed
5157 size_t count = mActiveTracks.size();
5158 size_t mixedTracks = 0;
5159 size_t tracksWithEffect = 0;
5160 // counts only _active_ fast tracks
5161 size_t fastTracks = 0;
5162 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
5163
5164 float masterVolume = mMasterVolume;
5165 bool masterMute = mMasterMute;
5166
5167 if (masterMute) {
5168 masterVolume = 0;
5169 }
5170 // Delegate master volume control to effect in output mix effect chain if needed
5171 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
5172 if (chain != 0) {
5173 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
5174 chain->setVolume_l(&v, &v);
5175 masterVolume = (float)((v + (1 << 23)) >> 24);
5176 chain.clear();
5177 }
5178
5179 // prepare a new state to push
5180 FastMixerStateQueue *sq = NULL;
5181 FastMixerState *state = NULL;
5182 bool didModify = false;
5183 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Andy Hungf2285312017-02-14 18:31:59 -08005184 bool coldIdle = false;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005185 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005186 sq = mFastMixer->sq();
5187 state = sq->begin();
Andy Hungf2285312017-02-14 18:31:59 -08005188 coldIdle = state->mCommand == FastMixerState::COLD_IDLE;
Eric Laurent81784c32012-11-19 14:55:58 -08005189 }
5190
Andy Hung69aed5f2014-02-25 17:24:40 -08005191 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08005192 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08005193
Andy Hungbd3b2b02018-05-21 10:53:11 -07005194 // DeferredOperations handles statistics after setting mixerStatus.
5195 class DeferredOperations {
5196 public:
Andy Hungea840382020-05-05 21:50:17 -07005197 DeferredOperations(mixer_state *mixerStatus, ThreadMetrics *threadMetrics)
5198 : mMixerStatus(mixerStatus)
5199 , mThreadMetrics(threadMetrics) {}
Andy Hungbd3b2b02018-05-21 10:53:11 -07005200
5201 // when leaving scope, tally frames properly.
5202 ~DeferredOperations() {
5203 // Tally underrun frames only if we are actually mixing (MIXER_TRACKS_READY)
5204 // because that is when the underrun occurs.
5205 // We do not distinguish between FastTracks and NormalTracks here.
Andy Hungea840382020-05-05 21:50:17 -07005206 size_t maxUnderrunFrames = 0;
Andy Hungb68f5eb2019-12-03 16:49:17 -08005207 if (*mMixerStatus == MIXER_TRACKS_READY && mUnderrunFrames.size() > 0) {
Andy Hungbd3b2b02018-05-21 10:53:11 -07005208 for (const auto &underrun : mUnderrunFrames) {
Andy Hungc2b11cb2020-04-22 09:04:01 -07005209 underrun.first->tallyUnderrunFrames(underrun.second);
Andy Hungea840382020-05-05 21:50:17 -07005210 maxUnderrunFrames = max(underrun.second, maxUnderrunFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07005211 }
5212 }
Andy Hungea840382020-05-05 21:50:17 -07005213 // send the max underrun frames for this mixer period
5214 mThreadMetrics->logUnderrunFrames(maxUnderrunFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07005215 }
5216
5217 // tallyUnderrunFrames() is called to update the track counters
5218 // with the number of underrun frames for a particular mixer period.
5219 // We defer tallying until we know the final mixer status.
5220 void tallyUnderrunFrames(sp<Track> track, size_t underrunFrames) {
5221 mUnderrunFrames.emplace_back(track, underrunFrames);
5222 }
5223
5224 private:
5225 const mixer_state * const mMixerStatus;
Andy Hungea840382020-05-05 21:50:17 -07005226 ThreadMetrics * const mThreadMetrics;
Andy Hungbd3b2b02018-05-21 10:53:11 -07005227 std::vector<std::pair<sp<Track>, size_t>> mUnderrunFrames;
Andy Hungea840382020-05-05 21:50:17 -07005228 } deferredOperations(&mixerStatus, &mThreadMetrics);
Andy Hungb68f5eb2019-12-03 16:49:17 -08005229 // implicit nested scope for variable capture
Andy Hungbd3b2b02018-05-21 10:53:11 -07005230
jiabin245cdd92018-12-07 17:55:15 -08005231 bool noFastHapticTrack = true;
Eric Laurent81784c32012-11-19 14:55:58 -08005232 for (size_t i=0 ; i<count ; i++) {
Andy Hungdae27702016-10-31 14:01:16 -07005233 const sp<Track> t = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08005234
5235 // this const just means the local variable doesn't change
5236 Track* const track = t.get();
5237
5238 // process fast tracks
5239 if (track->isFastTrack()) {
Andy Hungae22b482019-05-09 15:38:55 -07005240 LOG_ALWAYS_FATAL_IF(mFastMixer.get() == nullptr,
5241 "%s(%d): FastTrack(%d) present without FastMixer",
5242 __func__, id(), track->id());
5243
jiabin245cdd92018-12-07 17:55:15 -08005244 if (track->getHapticPlaybackEnabled()) {
5245 noFastHapticTrack = false;
5246 }
Eric Laurent81784c32012-11-19 14:55:58 -08005247
5248 // It's theoretically possible (though unlikely) for a fast track to be created
5249 // and then removed within the same normal mix cycle. This is not a problem, as
5250 // the track never becomes active so it's fast mixer slot is never touched.
5251 // The converse, of removing an (active) track and then creating a new track
5252 // at the identical fast mixer slot within the same normal mix cycle,
5253 // is impossible because the slot isn't marked available until the end of each cycle.
5254 int j = track->mFastIndex;
Glenn Kastendc2c50b2016-04-21 08:13:14 -07005255 ALOG_ASSERT(0 < j && j < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08005256 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
5257 FastTrack *fastTrack = &state->mFastTracks[j];
5258
5259 // Determine whether the track is currently in underrun condition,
5260 // and whether it had a recent underrun.
5261 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
5262 FastTrackUnderruns underruns = ftDump->mUnderruns;
5263 uint32_t recentFull = (underruns.mBitFields.mFull -
5264 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
5265 uint32_t recentPartial = (underruns.mBitFields.mPartial -
5266 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
5267 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
5268 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
5269 uint32_t recentUnderruns = recentPartial + recentEmpty;
5270 track->mObservedUnderruns = underruns;
5271 // don't count underruns that occur while stopping or pausing
5272 // or stopped which can occur when flush() is called while active
Andy Hungbd3b2b02018-05-21 10:53:11 -07005273 size_t underrunFrames = 0;
Glenn Kasten82aaf942013-07-17 16:05:07 -07005274 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
5275 recentUnderruns > 0) {
5276 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
Andy Hungbd3b2b02018-05-21 10:53:11 -07005277 underrunFrames = recentUnderruns * mFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08005278 }
Andy Hungbd3b2b02018-05-21 10:53:11 -07005279 // Immediately account for FastTrack underruns.
5280 track->mAudioTrackServerProxy->tallyUnderrunFrames(underrunFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08005281
5282 // This is similar to the state machine for normal tracks,
5283 // with a few modifications for fast tracks.
5284 bool isActive = true;
5285 switch (track->mState) {
5286 case TrackBase::STOPPING_1:
5287 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08005288 if (recentUnderruns > 0 || track->isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -08005289 track->mState = TrackBase::STOPPING_2;
5290 }
5291 break;
5292 case TrackBase::PAUSING:
5293 // ramp down is not yet implemented
5294 track->setPaused();
5295 break;
5296 case TrackBase::RESUMING:
5297 // ramp up is not yet implemented
5298 track->mState = TrackBase::ACTIVE;
5299 break;
5300 case TrackBase::ACTIVE:
5301 if (recentFull > 0 || recentPartial > 0) {
5302 // track has provided at least some frames recently: reset retry count
5303 track->mRetryCount = kMaxTrackRetries;
5304 }
5305 if (recentUnderruns == 0) {
5306 // no recent underruns: stay active
5307 break;
5308 }
5309 // there has recently been an underrun of some kind
5310 if (track->sharedBuffer() == 0) {
5311 // were any of the recent underruns "empty" (no frames available)?
5312 if (recentEmpty == 0) {
5313 // no, then ignore the partial underruns as they are allowed indefinitely
5314 break;
5315 }
5316 // there has recently been an "empty" underrun: decrement the retry counter
5317 if (--(track->mRetryCount) > 0) {
5318 break;
5319 }
5320 // indicate to client process that the track was disabled because of underrun;
5321 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08005322 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08005323 // remove from active list, but state remains ACTIVE [confusing but true]
5324 isActive = false;
5325 break;
5326 }
Chih-Hung Hsieh2b487032018-09-13 14:16:02 -07005327 FALLTHROUGH_INTENDED;
Eric Laurent81784c32012-11-19 14:55:58 -08005328 case TrackBase::STOPPING_2:
5329 case TrackBase::PAUSED:
Eric Laurent81784c32012-11-19 14:55:58 -08005330 case TrackBase::STOPPED:
5331 case TrackBase::FLUSHED: // flush() while active
5332 // Check for presentation complete if track is inactive
5333 // We have consumed all the buffers of this track.
5334 // This would be incomplete if we auto-paused on underrun
5335 {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005336 uint32_t latency = 0;
5337 status_t result = mOutput->stream->getLatency(&latency);
5338 ALOGE_IF(result != OK,
5339 "Error when retrieving output stream latency: %d", result);
5340 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08005341 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005342 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
5343 // track stays in active list until presentation is complete
5344 break;
5345 }
5346 }
5347 if (track->isStopping_2()) {
5348 track->mState = TrackBase::STOPPED;
5349 }
5350 if (track->isStopped()) {
5351 // Can't reset directly, as fast mixer is still polling this track
5352 // track->reset();
5353 // So instead mark this track as needing to be reset after push with ack
5354 resetMask |= 1 << i;
5355 }
5356 isActive = false;
5357 break;
5358 case TrackBase::IDLE:
5359 default:
Andy Hung959b5b82021-09-24 10:46:20 -07005360 LOG_ALWAYS_FATAL("unexpected track state %d", (int)track->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08005361 }
5362
5363 if (isActive) {
5364 // was it previously inactive?
5365 if (!(state->mTrackMask & (1 << j))) {
5366 ExtendedAudioBufferProvider *eabp = track;
5367 VolumeProvider *vp = track;
5368 fastTrack->mBufferProvider = eabp;
5369 fastTrack->mVolumeProvider = vp;
Eric Laurent81784c32012-11-19 14:55:58 -08005370 fastTrack->mChannelMask = track->mChannelMask;
Andy Hunge8a1ced2014-05-09 15:02:21 -07005371 fastTrack->mFormat = track->mFormat;
jiabin245cdd92018-12-07 17:55:15 -08005372 fastTrack->mHapticPlaybackEnabled = track->getHapticPlaybackEnabled();
jiabin77270b82018-12-18 15:41:29 -08005373 fastTrack->mHapticIntensity = track->getHapticIntensity();
Lais Andradebc3f37a2021-07-02 00:13:19 +01005374 fastTrack->mHapticMaxAmplitude = track->getHapticMaxAmplitude();
Eric Laurent81784c32012-11-19 14:55:58 -08005375 fastTrack->mGeneration++;
5376 state->mTrackMask |= 1 << j;
5377 didModify = true;
5378 // no acknowledgement required for newly active tracks
5379 }
Kevin Rocard12381092018-04-11 09:19:59 -07005380 sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
Eric Laurenteab90452019-06-24 15:17:46 -07005381 float volume;
5382 if (track->isPlaybackRestricted() || mStreamTypes[track->streamType()].mute) {
5383 volume = 0.f;
5384 } else {
5385 volume = masterVolume * mStreamTypes[track->streamType()].volume;
5386 }
5387
5388 handleVoipVolume_l(&volume);
5389
Eric Laurent81784c32012-11-19 14:55:58 -08005390 // cache the combined master volume and stream type volume for fast mixer; this
5391 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005392 const float vh = track->getVolumeHandler()->getVolume(
Eric Laurenteab90452019-06-24 15:17:46 -07005393 proxy->framesReleased()).first;
5394 volume *= vh;
Kevin Rocardb0eeaf122018-04-11 08:30:16 -07005395 track->mCachedVolume = volume;
Kevin Rocard12381092018-04-11 09:19:59 -07005396 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Vlad Popae2f5aef2022-07-25 16:00:20 +02005397 float vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
5398 float vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
5399
5400 track->processMuteEvent_l(mAudioFlinger->getOrCreateAudioManager(),
5401 /*muteState=*/{masterVolume == 0.f,
5402 mStreamTypes[track->streamType()].volume == 0.f,
5403 mStreamTypes[track->streamType()].mute,
5404 track->isPlaybackRestricted(),
Vlad Popa436c9172022-08-02 15:25:08 +02005405 vlf == 0.f && vrf == 0.f,
5406 vh == 0.f});
Vlad Popae2f5aef2022-07-25 16:00:20 +02005407
5408 vlf *= volume;
5409 vrf *= volume;
Eric Laurenteab90452019-06-24 15:17:46 -07005410
Kevin Rocard12381092018-04-11 09:19:59 -07005411 track->setFinalVolume((vlf + vrf) / 2.f);
Eric Laurent81784c32012-11-19 14:55:58 -08005412 ++fastTracks;
5413 } else {
5414 // was it previously active?
5415 if (state->mTrackMask & (1 << j)) {
5416 fastTrack->mBufferProvider = NULL;
5417 fastTrack->mGeneration++;
5418 state->mTrackMask &= ~(1 << j);
5419 didModify = true;
5420 // If any fast tracks were removed, we must wait for acknowledgement
5421 // because we're about to decrement the last sp<> on those tracks.
5422 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
5423 } else {
Glenn Kastenbf848af2017-12-22 11:55:01 -08005424 // ALOGW rather than LOG_ALWAYS_FATAL because it seems there are cases where an
5425 // AudioTrack may start (which may not be with a start() but with a write()
5426 // after underrun) and immediately paused or released. In that case the
5427 // FastTrack state hasn't had time to update.
5428 // TODO Remove the ALOGW when this theory is confirmed.
5429 ALOGW("fast track %d should have been active; "
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08005430 "mState=%d, mTrackMask=%#x, recentUnderruns=%u, isShared=%d",
Andy Hung959b5b82021-09-24 10:46:20 -07005431 j, (int)track->mState, state->mTrackMask, recentUnderruns,
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08005432 track->sharedBuffer() != 0);
Glenn Kastenbf848af2017-12-22 11:55:01 -08005433 // Since the FastMixer state already has the track inactive, do nothing here.
Eric Laurent81784c32012-11-19 14:55:58 -08005434 }
5435 tracksToRemove->add(track);
5436 // Avoids a misleading display in dumpsys
5437 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
5438 }
jiabin245cdd92018-12-07 17:55:15 -08005439 if (fastTrack->mHapticPlaybackEnabled != track->getHapticPlaybackEnabled()) {
5440 fastTrack->mHapticPlaybackEnabled = track->getHapticPlaybackEnabled();
5441 didModify = true;
5442 }
Eric Laurent81784c32012-11-19 14:55:58 -08005443 continue;
5444 }
5445
5446 { // local variable scope to avoid goto warning
5447
5448 audio_track_cblk_t* cblk = track->cblk();
5449
5450 // The first time a track is added we wait
5451 // for all its buffers to be filled before processing it
Andy Hungc0691382018-09-12 18:01:57 -07005452 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08005453
5454 // if an active track doesn't exist in the AudioMixer, create it.
Andy Hungc0691382018-09-12 18:01:57 -07005455 // use the trackId as the AudioMixer name.
5456 if (!mAudioMixer->exists(trackId)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08005457 status_t status = mAudioMixer->create(
Andy Hungc0691382018-09-12 18:01:57 -07005458 trackId,
Andy Hung1bc088a2018-02-09 15:57:31 -08005459 track->mChannelMask,
5460 track->mFormat,
5461 track->mSessionId);
5462 if (status != OK) {
Andy Hungc0691382018-09-12 18:01:57 -07005463 ALOGW("%s(): AudioMixer cannot create track(%d)"
5464 " mask %#x, format %#x, sessionId %d",
5465 __func__, trackId,
5466 track->mChannelMask, track->mFormat, track->mSessionId);
Andy Hung1bc088a2018-02-09 15:57:31 -08005467 tracksToRemove->add(track);
5468 track->invalidate(); // consider it dead.
5469 continue;
5470 }
5471 }
5472
Eric Laurent81784c32012-11-19 14:55:58 -08005473 // make sure that we have enough frames to mix one full buffer.
5474 // enforce this condition only once to enable draining the buffer in case the client
5475 // app does not call stop() and relies on underrun to stop:
5476 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
5477 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005478 size_t desiredFrames;
Andy Hung8edb8dc2015-03-26 19:13:55 -07005479 const uint32_t sampleRate = track->mAudioTrackServerProxy->getSampleRate();
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07005480 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07005481
5482 desiredFrames = sourceFramesNeededWithTimestretch(
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07005483 sampleRate, mNormalFrameCount, mSampleRate, playbackRate.mSpeed);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005484 // TODO: ONLY USED FOR LEGACY RESAMPLERS, remove when they are removed.
5485 // add frames already consumed but not yet released by the resampler
5486 // because mAudioTrackServerProxy->framesReady() will include these frames
Andy Hungc0691382018-09-12 18:01:57 -07005487 desiredFrames += mAudioMixer->getUnreleasedFrames(trackId);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005488
Eric Laurent81784c32012-11-19 14:55:58 -08005489 uint32_t minFrames = 1;
5490 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
5491 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005492 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08005493 }
Eric Laurent13e4c962013-12-20 17:36:01 -08005494
5495 size_t framesReady = track->framesReady();
Glenn Kastene7754022014-10-31 12:11:26 -07005496 if (ATRACE_ENABLED()) {
5497 // I wish we had formatted trace names
Andy Hung1bc088a2018-02-09 15:57:31 -08005498 std::string traceName("nRdy");
Andy Hungc0691382018-09-12 18:01:57 -07005499 traceName += std::to_string(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08005500 ATRACE_INT(traceName.c_str(), framesReady);
Glenn Kastene7754022014-10-31 12:11:26 -07005501 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005502 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08005503 !track->isPaused() && !track->isTerminated())
5504 {
Andy Hungc0691382018-09-12 18:01:57 -07005505 ALOGVV("track(%d) s=%08x [OK] on thread %p", trackId, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08005506
5507 mixedTracks++;
5508
Andy Hung69aed5f2014-02-25 17:24:40 -08005509 // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
5510 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08005511 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08005512 if (track->mainBuffer() != mSinkBuffer &&
5513 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08005514 if (mEffectBufferEnabled) {
5515 mEffectBufferValid = true; // Later can set directly.
5516 }
Eric Laurent81784c32012-11-19 14:55:58 -08005517 chain = getEffectChain_l(track->sessionId());
5518 // Delegate volume control to effect in track effect chain if needed
5519 if (chain != 0) {
5520 tracksWithEffect++;
5521 } else {
Andy Hungc0691382018-09-12 18:01:57 -07005522 ALOGW("prepareTracks_l(): track(%d) attached to effect but no chain found on "
Eric Laurent81784c32012-11-19 14:55:58 -08005523 "session %d",
Andy Hungc0691382018-09-12 18:01:57 -07005524 trackId, track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08005525 }
5526 }
5527
5528
5529 int param = AudioMixer::VOLUME;
5530 if (track->mFillingUpStatus == Track::FS_FILLED) {
5531 // no ramp for the first volume setting
5532 track->mFillingUpStatus = Track::FS_ACTIVE;
5533 if (track->mState == TrackBase::RESUMING) {
5534 track->mState = TrackBase::ACTIVE;
Revathi Uddaraju453bcb52017-08-14 14:19:40 +08005535 // If a new track is paused immediately after start, do not ramp on resume.
5536 if (cblk->mServer != 0) {
5537 param = AudioMixer::RAMP_VOLUME;
5538 }
Eric Laurent81784c32012-11-19 14:55:58 -08005539 }
Andy Hungc0691382018-09-12 18:01:57 -07005540 mAudioMixer->setParameter(trackId, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Eric Laurent7c29ec92017-09-20 17:54:22 -07005541 mLeftVolFloat = -1.0;
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005542 // FIXME should not make a decision based on mServer
5543 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005544 // If the track is stopped before the first frame was mixed,
5545 // do not apply ramp
5546 param = AudioMixer::RAMP_VOLUME;
5547 }
5548
5549 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07005550 uint32_t vl, vr; // in U8.24 integer format
5551 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Eric Laurent7c29ec92017-09-20 17:54:22 -07005552 // read original volumes with volume control
Eric Laurenteab90452019-06-24 15:17:46 -07005553 float v = masterVolume * mStreamTypes[track->streamType()].volume;
Andy Hung333ab962019-05-28 20:23:35 -07005554 // Always fetch volumeshaper volume to ensure state is updated.
5555 const sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
5556 const float vh = track->getVolumeHandler()->getVolume(
5557 track->mAudioTrackServerProxy->framesReleased()).first;
Eric Laurent7c29ec92017-09-20 17:54:22 -07005558
Eric Laurenteab90452019-06-24 15:17:46 -07005559 if (mStreamTypes[track->streamType()].mute || track->isPlaybackRestricted()) {
5560 v = 0;
5561 }
5562
5563 handleVoipVolume_l(&v);
5564
5565 if (track->isPausing()) {
Andy Hung6be49402014-05-30 10:42:03 -07005566 vl = vr = 0;
5567 vlf = vrf = vaf = 0.;
Eric Laurenteab90452019-06-24 15:17:46 -07005568 track->setPaused();
Eric Laurent81784c32012-11-19 14:55:58 -08005569 } else {
Glenn Kastenc56f3422014-03-21 17:53:17 -07005570 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07005571 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
5572 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08005573 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07005574 if (vlf > GAIN_FLOAT_UNITY) {
5575 ALOGV("Track left volume out of range: %.3g", vlf);
5576 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08005577 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07005578 if (vrf > GAIN_FLOAT_UNITY) {
5579 ALOGV("Track right volume out of range: %.3g", vrf);
5580 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08005581 }
Vlad Popae2f5aef2022-07-25 16:00:20 +02005582
5583 track->processMuteEvent_l(mAudioFlinger->getOrCreateAudioManager(),
5584 /*muteState=*/{masterVolume == 0.f,
5585 mStreamTypes[track->streamType()].volume == 0.f,
5586 mStreamTypes[track->streamType()].mute,
5587 track->isPlaybackRestricted(),
Vlad Popa436c9172022-08-02 15:25:08 +02005588 vlf == 0.f && vrf == 0.f,
5589 vh == 0.f});
Vlad Popae2f5aef2022-07-25 16:00:20 +02005590
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005591 // now apply the master volume and stream type volume and shaper volume
5592 vlf *= v * vh;
5593 vrf *= v * vh;
Eric Laurent81784c32012-11-19 14:55:58 -08005594 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07005595 // then derive vl and vr as U8.24 versions for the effect chain
5596 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
5597 vl = (uint32_t) (scaleto8_24 * vlf);
5598 vr = (uint32_t) (scaleto8_24 * vrf);
5599 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08005600 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08005601 // send level comes from shared memory and so may be corrupt
5602 if (sendLevel > MAX_GAIN_INT) {
5603 ALOGV("Track send level out of range: %04X", sendLevel);
5604 sendLevel = MAX_GAIN_INT;
5605 }
Andy Hung6be49402014-05-30 10:42:03 -07005606 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
5607 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08005608 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005609
Kevin Rocard12381092018-04-11 09:19:59 -07005610 track->setFinalVolume((vrf + vlf) / 2.f);
5611
Eric Laurent81784c32012-11-19 14:55:58 -08005612 // Delegate volume control to effect in track effect chain if needed
5613 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
5614 // Do not ramp volume if volume is controlled by effect
5615 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08005616 // Update remaining floating point volume levels
5617 vlf = (float)vl / (1 << 24);
5618 vrf = (float)vr / (1 << 24);
Eric Laurent81784c32012-11-19 14:55:58 -08005619 track->mHasVolumeController = true;
5620 } else {
5621 // force no volume ramp when volume controller was just disabled or removed
5622 // from effect chain to avoid volume spike
5623 if (track->mHasVolumeController) {
5624 param = AudioMixer::VOLUME;
5625 }
5626 track->mHasVolumeController = false;
5627 }
5628
Eric Laurent81784c32012-11-19 14:55:58 -08005629 // XXX: these things DON'T need to be done each time
Andy Hungc0691382018-09-12 18:01:57 -07005630 mAudioMixer->setBufferProvider(trackId, track);
5631 mAudioMixer->enable(trackId);
Eric Laurent81784c32012-11-19 14:55:58 -08005632
Andy Hungc0691382018-09-12 18:01:57 -07005633 mAudioMixer->setParameter(trackId, param, AudioMixer::VOLUME0, &vlf);
5634 mAudioMixer->setParameter(trackId, param, AudioMixer::VOLUME1, &vrf);
5635 mAudioMixer->setParameter(trackId, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08005636 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005637 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005638 AudioMixer::TRACK,
5639 AudioMixer::FORMAT, (void *)track->format());
5640 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005641 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005642 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00005643 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Eric Laurent39095982021-08-24 18:29:27 +02005644
Eric Laurentb0a7bc92022-04-05 15:06:08 +02005645 if (mType == SPATIALIZER && !track->isSpatialized()) {
Eric Laurent39095982021-08-24 18:29:27 +02005646 mAudioMixer->setParameter(
5647 trackId,
5648 AudioMixer::TRACK,
5649 AudioMixer::MIXER_CHANNEL_MASK,
5650 (void *)(uintptr_t)(mChannelMask | mHapticChannelMask));
5651 } else {
5652 mAudioMixer->setParameter(
5653 trackId,
5654 AudioMixer::TRACK,
5655 AudioMixer::MIXER_CHANNEL_MASK,
5656 (void *)(uintptr_t)(mMixerChannelMask | mHapticChannelMask));
5657 }
5658
Glenn Kastene3aa6592012-12-04 12:22:46 -08005659 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07005660 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Andy Hung333ab962019-05-28 20:23:35 -07005661 uint32_t reqSampleRate = proxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08005662 if (reqSampleRate == 0) {
5663 reqSampleRate = mSampleRate;
5664 } else if (reqSampleRate > maxSampleRate) {
5665 reqSampleRate = maxSampleRate;
5666 }
Eric Laurent81784c32012-11-19 14:55:58 -08005667 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005668 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005669 AudioMixer::RESAMPLE,
5670 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00005671 (void *)(uintptr_t)reqSampleRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005672
Andy Hung333ab962019-05-28 20:23:35 -07005673 AudioPlaybackRate playbackRate = proxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07005674 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005675 trackId,
Andy Hung8edb8dc2015-03-26 19:13:55 -07005676 AudioMixer::TIMESTRETCH,
5677 AudioMixer::PLAYBACK_RATE,
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07005678 &playbackRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005679
Andy Hung69aed5f2014-02-25 17:24:40 -08005680 /*
5681 * Select the appropriate output buffer for the track.
5682 *
Andy Hung98ef9782014-03-04 14:46:50 -08005683 * Tracks with effects go into their own effects chain buffer
5684 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08005685 *
5686 * Other tracks can use mMixerBuffer for higher precision
5687 * channel accumulation. If this buffer is enabled
5688 * (mMixerBufferEnabled true), then selected tracks will accumulate
5689 * into it.
5690 *
5691 */
5692 if (mMixerBufferEnabled
5693 && (track->mainBuffer() == mSinkBuffer
5694 || track->mainBuffer() == mMixerBuffer)) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02005695 if (mType == SPATIALIZER && !track->isSpatialized()) {
Eric Laurent39095982021-08-24 18:29:27 +02005696 mAudioMixer->setParameter(
5697 trackId,
5698 AudioMixer::TRACK,
Eric Laurentb62d0362021-10-26 17:40:18 +02005699 AudioMixer::MIXER_FORMAT, (void *)mEffectBufferFormat);
Eric Laurent39095982021-08-24 18:29:27 +02005700 mAudioMixer->setParameter(
5701 trackId,
5702 AudioMixer::TRACK,
Eric Laurentb62d0362021-10-26 17:40:18 +02005703 AudioMixer::MAIN_BUFFER, (void *)mPostSpatializerBuffer);
Eric Laurent39095982021-08-24 18:29:27 +02005704 } else {
5705 mAudioMixer->setParameter(
5706 trackId,
5707 AudioMixer::TRACK,
5708 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
5709 mAudioMixer->setParameter(
5710 trackId,
5711 AudioMixer::TRACK,
5712 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
5713 // TODO: override track->mainBuffer()?
5714 mMixerBufferValid = true;
5715 }
Andy Hung69aed5f2014-02-25 17:24:40 -08005716 } else {
5717 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005718 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08005719 AudioMixer::TRACK,
rago94a1ee82017-07-21 15:11:02 -07005720 AudioMixer::MIXER_FORMAT, (void *)EFFECT_BUFFER_FORMAT);
Andy Hung69aed5f2014-02-25 17:24:40 -08005721 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005722 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08005723 AudioMixer::TRACK,
5724 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
5725 }
Eric Laurent81784c32012-11-19 14:55:58 -08005726 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005727 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005728 AudioMixer::TRACK,
5729 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
jiabin245cdd92018-12-07 17:55:15 -08005730 mAudioMixer->setParameter(
5731 trackId,
5732 AudioMixer::TRACK,
5733 AudioMixer::HAPTIC_ENABLED, (void *)(uintptr_t)track->getHapticPlaybackEnabled());
jiabin77270b82018-12-18 15:41:29 -08005734 mAudioMixer->setParameter(
5735 trackId,
5736 AudioMixer::TRACK,
5737 AudioMixer::HAPTIC_INTENSITY, (void *)(uintptr_t)track->getHapticIntensity());
Lais Andradebc3f37a2021-07-02 00:13:19 +01005738 mAudioMixer->setParameter(
5739 trackId,
5740 AudioMixer::TRACK,
5741 AudioMixer::HAPTIC_MAX_AMPLITUDE, (void *)(&(track->mHapticMaxAmplitude)));
Eric Laurent81784c32012-11-19 14:55:58 -08005742
5743 // reset retry count
5744 track->mRetryCount = kMaxTrackRetries;
5745
5746 // If one track is ready, set the mixer ready if:
5747 // - the mixer was not ready during previous round OR
5748 // - no other track is not ready
5749 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
5750 mixerStatus != MIXER_TRACKS_ENABLED) {
5751 mixerStatus = MIXER_TRACKS_READY;
5752 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08005753
5754 // Enable the next few lines to instrument a test for underrun log handling.
5755 // TODO: Remove when we have a better way of testing the underrun log.
5756#if 0
5757 static int i;
5758 if ((++i & 0xf) == 0) {
5759 deferredOperations.tallyUnderrunFrames(track, 10 /* underrunFrames */);
5760 }
5761#endif
Eric Laurent81784c32012-11-19 14:55:58 -08005762 } else {
Andy Hungbd3b2b02018-05-21 10:53:11 -07005763 size_t underrunFrames = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005764 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Andy Hungb68f5eb2019-12-03 16:49:17 -08005765 ALOGV("track(%d) underrun, track state %s framesReady(%zu) < framesDesired(%zd)",
5766 trackId, track->getTrackStateAsString(), framesReady, desiredFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07005767 underrunFrames = desiredFrames;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005768 }
Andy Hungbd3b2b02018-05-21 10:53:11 -07005769 deferredOperations.tallyUnderrunFrames(track, underrunFrames);
Phil Burk2812d9e2016-01-04 10:34:30 -08005770
Eric Laurent81784c32012-11-19 14:55:58 -08005771 // clear effect chain input buffer if an active track underruns to avoid sending
5772 // previous audio buffer again to effects
5773 chain = getEffectChain_l(track->sessionId());
5774 if (chain != 0) {
5775 chain->clearInputBuffer();
5776 }
5777
Andy Hungc0691382018-09-12 18:01:57 -07005778 ALOGVV("track(%d) s=%08x [NOT READY] on thread %p", trackId, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08005779 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
5780 track->isStopped() || track->isPaused()) {
5781 // We have consumed all the buffers of this track.
5782 // Remove it from the list of active tracks.
5783 // TODO: use actual buffer filling status instead of latency when available from
5784 // audio HAL
5785 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08005786 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005787 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
5788 if (track->isStopped()) {
5789 track->reset();
5790 }
5791 tracksToRemove->add(track);
5792 }
5793 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08005794 // No buffers for this track. Give it a few chances to
5795 // fill a buffer, then remove it from active list.
5796 if (--(track->mRetryCount) <= 0) {
Andy Hungc0691382018-09-12 18:01:57 -07005797 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p",
5798 trackId, this);
Eric Laurent81784c32012-11-19 14:55:58 -08005799 tracksToRemove->add(track);
5800 // indicate to client process that the track was disabled because of underrun;
5801 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08005802 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08005803 // If one track is not ready, mark the mixer also not ready if:
5804 // - the mixer was ready during previous round OR
5805 // - no other track is ready
5806 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
5807 mixerStatus != MIXER_TRACKS_READY) {
5808 mixerStatus = MIXER_TRACKS_ENABLED;
5809 }
5810 }
Andy Hungc0691382018-09-12 18:01:57 -07005811 mAudioMixer->disable(trackId);
Eric Laurent81784c32012-11-19 14:55:58 -08005812 }
5813
5814 } // local variable scope to avoid goto warning
Eric Laurent81784c32012-11-19 14:55:58 -08005815
5816 }
5817
jiabin245cdd92018-12-07 17:55:15 -08005818 if (mHapticChannelMask != AUDIO_CHANNEL_NONE && sq != NULL) {
5819 // When there is no fast track playing haptic and FastMixer exists,
5820 // enabling the first FastTrack, which provides mixed data from normal
5821 // tracks, to play haptic data.
5822 FastTrack *fastTrack = &state->mFastTracks[0];
5823 if (fastTrack->mHapticPlaybackEnabled != noFastHapticTrack) {
5824 fastTrack->mHapticPlaybackEnabled = noFastHapticTrack;
5825 didModify = true;
5826 }
5827 }
5828
Eric Laurent81784c32012-11-19 14:55:58 -08005829 // Push the new FastMixer state if necessary
5830 bool pauseAudioWatchdog = false;
5831 if (didModify) {
5832 state->mFastTracksGen++;
5833 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
5834 if (kUseFastMixer == FastMixer_Dynamic &&
5835 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
5836 state->mCommand = FastMixerState::COLD_IDLE;
5837 state->mColdFutexAddr = &mFastMixerFutex;
5838 state->mColdGen++;
5839 mFastMixerFutex = 0;
5840 if (kUseFastMixer == FastMixer_Dynamic) {
5841 mNormalSink = mOutputSink;
5842 }
5843 // If we go into cold idle, need to wait for acknowledgement
5844 // so that fast mixer stops doing I/O.
5845 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
5846 pauseAudioWatchdog = true;
5847 }
Eric Laurent81784c32012-11-19 14:55:58 -08005848 }
5849 if (sq != NULL) {
5850 sq->end(didModify);
Andy Hungf2285312017-02-14 18:31:59 -08005851 // No need to block if the FastMixer is in COLD_IDLE as the FastThread
5852 // is not active. (We BLOCK_UNTIL_ACKED when entering COLD_IDLE
5853 // when bringing the output sink into standby.)
5854 //
5855 // We will get the latest FastMixer state when we come out of COLD_IDLE.
5856 //
5857 // This occurs with BT suspend when we idle the FastMixer with
5858 // active tracks, which may be added or removed.
5859 sq->push(coldIdle ? FastMixerStateQueue::BLOCK_NEVER : block);
Eric Laurent81784c32012-11-19 14:55:58 -08005860 }
5861#ifdef AUDIO_WATCHDOG
5862 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
5863 mAudioWatchdog->pause();
5864 }
5865#endif
5866
5867 // Now perform the deferred reset on fast tracks that have stopped
5868 while (resetMask != 0) {
5869 size_t i = __builtin_ctz(resetMask);
5870 ALOG_ASSERT(i < count);
5871 resetMask &= ~(1 << i);
Andy Hungdae27702016-10-31 14:01:16 -07005872 sp<Track> track = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08005873 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
5874 track->reset();
5875 }
5876
Andy Hung80d03d22018-04-10 10:32:11 -07005877 // Track destruction may occur outside of threadLoop once it is removed from active tracks.
5878 // Ensure the AudioMixer doesn't have a raw "buffer provider" pointer to the track if
5879 // it ceases to be active, to allow safe removal from the AudioMixer at the start
5880 // of prepareTracks_l(); this releases any outstanding buffer back to the track.
5881 // See also the implementation of destroyTrack_l().
5882 for (const auto &track : *tracksToRemove) {
Andy Hungc0691382018-09-12 18:01:57 -07005883 const int trackId = track->id();
5884 if (mAudioMixer->exists(trackId)) { // Normal tracks here, fast tracks in FastMixer.
5885 mAudioMixer->setBufferProvider(trackId, nullptr /* bufferProvider */);
Andy Hung80d03d22018-04-10 10:32:11 -07005886 }
5887 }
5888
Eric Laurent81784c32012-11-19 14:55:58 -08005889 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08005890 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08005891
Eric Laurentb3f315a2021-07-13 15:09:05 +02005892 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0 ||
5893 getEffectChain_l(AUDIO_SESSION_OUTPUT_STAGE) != 0) {
Eric Laurent97d547d2014-09-02 14:45:53 -07005894 mEffectBufferValid = true;
Marco Nelissenac302142014-10-20 13:15:38 -07005895 }
5896
5897 if (mEffectBufferValid) {
Marco Nelissen57088b52014-10-17 16:39:39 -07005898 // as long as there are effects we should clear the effects buffer, to avoid
5899 // passing a non-clean buffer to the effect chain
5900 memset(mEffectBuffer, 0, mEffectBufferSize);
Eric Laurentb62d0362021-10-26 17:40:18 +02005901 if (mType == SPATIALIZER) {
5902 memset(mPostSpatializerBuffer, 0, mPostSpatializerBufferSize);
5903 }
Eric Laurent97d547d2014-09-02 14:45:53 -07005904 }
Andy Hung69aed5f2014-02-25 17:24:40 -08005905 // sink or mix buffer must be cleared if all tracks are connected to an
5906 // effect chain as in this case the mixer will not write to the sink or mix buffer
5907 // and track effects will accumulate into it
Eric Laurent39095982021-08-24 18:29:27 +02005908 // always clear sink buffer for spatializer output as the output of the spatializer
5909 // effect will be accumulated into it
5910 if ((mBytesRemaining == 0) && (((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
5911 (mixedTracks == 0 && fastTracks > 0)) || (mType == SPATIALIZER))) {
Eric Laurent81784c32012-11-19 14:55:58 -08005912 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08005913 if (mMixerBufferValid) {
5914 memset(mMixerBuffer, 0, mMixerBufferSize);
5915 // TODO: In testing, mSinkBuffer below need not be cleared because
5916 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
5917 // after mixing.
5918 //
5919 // To enforce this guarantee:
5920 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
5921 // (mixedTracks == 0 && fastTracks > 0))
5922 // must imply MIXER_TRACKS_READY.
5923 // Later, we may clear buffers regardless, and skip much of this logic.
5924 }
Andy Hung98ef9782014-03-04 14:46:50 -08005925 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07005926 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08005927 }
5928
5929 // if any fast tracks, then status is ready
5930 mMixerStatusIgnoringFastTracks = mixerStatus;
5931 if (fastTracks > 0) {
5932 mixerStatus = MIXER_TRACKS_READY;
5933 }
5934 return mixerStatus;
5935}
5936
Eric Laurentad7dd962016-09-22 12:38:37 -07005937// trackCountForUid_l() must be called with ThreadBase::mLock held
Andy Hung1bc088a2018-02-09 15:57:31 -08005938uint32_t AudioFlinger::PlaybackThread::trackCountForUid_l(uid_t uid) const
Eric Laurentad7dd962016-09-22 12:38:37 -07005939{
5940 uint32_t trackCount = 0;
5941 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hung1f12a8a2016-11-07 16:10:30 -08005942 if (mTracks[i]->uid() == uid) {
Eric Laurentad7dd962016-09-22 12:38:37 -07005943 trackCount++;
5944 }
5945 }
5946 return trackCount;
5947}
5948
Brian Lindahl65e90012022-07-27 18:01:07 +02005949bool AudioFlinger::PlaybackThread::IsTimestampAdvancing::check(AudioStreamOut * output)
ziyangch8f194f12021-12-01 13:48:04 -08005950{
Brian Lindahl65e90012022-07-27 18:01:07 +02005951 // Check the timestamp to see if it's advancing once every 150ms. If we check too frequently, we
5952 // could falsely detect that the frame position has stalled due to underrun because we haven't
5953 // given the Audio HAL enough time to update.
5954 const nsecs_t nowNs = systemTime();
5955 if (nowNs - mPreviousNs < mMinimumTimeBetweenChecksNs) {
5956 return mLatchedValue;
5957 }
5958 mPreviousNs = nowNs;
5959 mLatchedValue = false;
5960 // Determine if the presentation position is still advancing.
ziyangch8f194f12021-12-01 13:48:04 -08005961 uint64_t position = 0;
5962 struct timespec unused;
Brian Lindahl65e90012022-07-27 18:01:07 +02005963 const status_t ret = output->getPresentationPosition(&position, &unused);
ziyangch8f194f12021-12-01 13:48:04 -08005964 if (ret == NO_ERROR) {
Brian Lindahl65e90012022-07-27 18:01:07 +02005965 if (position != mPreviousPosition) {
5966 mPreviousPosition = position;
5967 mLatchedValue = true;
ziyangch8f194f12021-12-01 13:48:04 -08005968 }
5969 }
Brian Lindahl65e90012022-07-27 18:01:07 +02005970 return mLatchedValue;
5971}
5972
5973void AudioFlinger::PlaybackThread::IsTimestampAdvancing::clear()
5974{
5975 mLatchedValue = true;
5976 mPreviousPosition = 0;
5977 mPreviousNs = 0;
ziyangch8f194f12021-12-01 13:48:04 -08005978}
5979
Andy Hung1bc088a2018-02-09 15:57:31 -08005980// isTrackAllowed_l() must be called with ThreadBase::mLock held
5981bool AudioFlinger::MixerThread::isTrackAllowed_l(
5982 audio_channel_mask_t channelMask, audio_format_t format,
5983 audio_session_t sessionId, uid_t uid) const
Eric Laurent81784c32012-11-19 14:55:58 -08005984{
Andy Hung1bc088a2018-02-09 15:57:31 -08005985 if (!PlaybackThread::isTrackAllowed_l(channelMask, format, sessionId, uid)) {
5986 return false;
Eric Laurentad7dd962016-09-22 12:38:37 -07005987 }
Andy Hung1bc088a2018-02-09 15:57:31 -08005988 // Check validity as we don't call AudioMixer::create() here.
Mikhail Naganov7ad7a252019-07-30 14:42:32 -07005989 if (!mAudioMixer->isValidFormat(format)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08005990 ALOGW("%s: invalid format: %#x", __func__, format);
5991 return false;
5992 }
Mikhail Naganov7ad7a252019-07-30 14:42:32 -07005993 if (!mAudioMixer->isValidChannelMask(channelMask)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08005994 ALOGW("%s: invalid channelMask: %#x", __func__, channelMask);
5995 return false;
5996 }
5997 return true;
Eric Laurent81784c32012-11-19 14:55:58 -08005998}
5999
Eric Laurent10351942014-05-08 18:49:52 -07006000// checkForNewParameter_l() must be called with ThreadBase::mLock held
6001bool AudioFlinger::MixerThread::checkForNewParameter_l(const String8& keyValuePair,
6002 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08006003{
Eric Laurent81784c32012-11-19 14:55:58 -08006004 bool reconfig = false;
Eric Laurent10351942014-05-08 18:49:52 -07006005 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006006
Glenn Kastenc05b8d72016-03-24 09:48:17 -07006007 AutoPark<FastMixer> park(mFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08006008
Eric Laurent10351942014-05-08 18:49:52 -07006009 AudioParameter param = AudioParameter(keyValuePair);
6010 int value;
6011 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
6012 reconfig = true;
6013 }
6014 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07006015 if (!isValidPcmSinkFormat((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07006016 status = BAD_VALUE;
6017 } else {
6018 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08006019 reconfig = true;
6020 }
Eric Laurent10351942014-05-08 18:49:52 -07006021 }
6022 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07006023 if (!isValidPcmSinkChannelMask((audio_channel_mask_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07006024 status = BAD_VALUE;
6025 } else {
6026 // no need to save value, since it's constant
6027 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006028 }
Eric Laurent10351942014-05-08 18:49:52 -07006029 }
6030 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6031 // do not accept frame count changes if tracks are open as the track buffer
6032 // size depends on frame count and correct behavior would not be guaranteed
6033 // if frame count is changed after track creation
6034 if (!mTracks.isEmpty()) {
6035 status = INVALID_OPERATION;
6036 } else {
6037 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006038 }
Eric Laurent10351942014-05-08 18:49:52 -07006039 }
6040 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07006041 LOG_FATAL("Should not set routing device in MixerThread");
Eric Laurent10351942014-05-08 18:49:52 -07006042 }
Eric Laurent81784c32012-11-19 14:55:58 -08006043
Eric Laurent10351942014-05-08 18:49:52 -07006044 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006045 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07006046 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08006047 mOutput->standby();
Andy Hungcf10d742020-04-28 15:38:24 -07006048 if (!mStandby) {
6049 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07006050 mThreadSnapshot.onEnd();
Andy Hungcf10d742020-04-28 15:38:24 -07006051 mStandby = true;
6052 }
Eric Laurent10351942014-05-08 18:49:52 -07006053 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006054 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent81784c32012-11-19 14:55:58 -08006055 }
Eric Laurent10351942014-05-08 18:49:52 -07006056 if (status == NO_ERROR && reconfig) {
6057 readOutputParameters_l();
6058 delete mAudioMixer;
6059 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
Andy Hung1bc088a2018-02-09 15:57:31 -08006060 for (const auto &track : mTracks) {
Andy Hungc0691382018-09-12 18:01:57 -07006061 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08006062 status_t status = mAudioMixer->create(
Andy Hungc0691382018-09-12 18:01:57 -07006063 trackId,
Andy Hung1bc088a2018-02-09 15:57:31 -08006064 track->mChannelMask,
6065 track->mFormat,
6066 track->mSessionId);
6067 ALOGW_IF(status != NO_ERROR,
Andy Hungc0691382018-09-12 18:01:57 -07006068 "%s(): AudioMixer cannot create track(%d)"
6069 " mask %#x, format %#x, sessionId %d",
Andy Hung1bc088a2018-02-09 15:57:31 -08006070 __func__,
Andy Hungc0691382018-09-12 18:01:57 -07006071 trackId, track->mChannelMask, track->mFormat, track->mSessionId);
Eric Laurent10351942014-05-08 18:49:52 -07006072 }
Eric Laurent73e26b62015-04-27 16:55:58 -07006073 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07006074 }
Eric Laurent81784c32012-11-19 14:55:58 -08006075 }
6076
Dean Wheatley68918102021-03-19 22:09:19 +11006077 return reconfig;
Eric Laurent81784c32012-11-19 14:55:58 -08006078}
6079
6080
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07006081void AudioFlinger::MixerThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -08006082{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07006083 PlaybackThread::dumpInternals_l(fd, args);
Andy Hung40eb1a12015-06-18 13:42:02 -07006084 dprintf(fd, " Thread throttle time (msecs): %u\n", mThreadThrottleTimeMs);
Andy Hung8ed196a2018-01-05 13:21:11 -08006085 dprintf(fd, " AudioMixer tracks: %s\n", mAudioMixer->trackNames().c_str());
Andy Hung2ddee192015-12-18 17:34:44 -08006086 dprintf(fd, " Master mono: %s\n", mMasterMono ? "on" : "off");
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006087 dprintf(fd, " Master balance: %f (%s)\n", mMasterBalance.load(),
6088 (hasFastMixer() ? std::to_string(mFastMixer->getMasterBalance())
6089 : mBalance.toString()).c_str());
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006090 if (hasFastMixer()) {
6091 dprintf(fd, " FastMixer thread %p tid=%d", mFastMixer.get(), mFastMixer->getTid());
6092
6093 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
6094 // while we are dumping it. It may be inconsistent, but it won't mutate!
6095 // This is a large object so we place it on the heap.
6096 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
Eric Tan2942a4e2018-09-12 17:41:27 -07006097 const std::unique_ptr<FastMixerDumpState> copy =
6098 std::make_unique<FastMixerDumpState>(mFastMixerDumpState);
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006099 copy->dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08006100
6101#ifdef STATE_QUEUE_DUMP
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006102 // Similar for state queue
6103 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
6104 observerCopy.dump(fd);
6105 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
6106 mutatorCopy.dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08006107#endif
6108
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006109#ifdef AUDIO_WATCHDOG
6110 if (mAudioWatchdog != 0) {
6111 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
6112 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
6113 wdCopy.dump(fd);
6114 }
6115#endif
6116
6117 } else {
6118 dprintf(fd, " No FastMixer\n");
6119 }
Eric Laurent81784c32012-11-19 14:55:58 -08006120}
6121
6122uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
6123{
6124 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
6125}
6126
6127uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
6128{
6129 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
6130}
6131
6132void AudioFlinger::MixerThread::cacheParameters_l()
6133{
6134 PlaybackThread::cacheParameters_l();
6135
6136 // FIXME: Relaxed timing because of a certain device that can't meet latency
6137 // Should be reduced to 2x after the vendor fixes the driver issue
6138 // increase threshold again due to low power audio mode. The way this warning
6139 // threshold is calculated and its usefulness should be reconsidered anyway.
6140 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
6141}
6142
6143// ----------------------------------------------------------------------------
6144
6145AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
Gareth Fennb18c1a32022-10-05 13:42:36 -07006146 AudioStreamOut* output, audio_io_handle_t id, ThreadBase::type_t type, bool systemReady,
6147 const audio_offload_info_t& offloadInfo)
jiabinc52b1ff2019-10-31 17:20:42 -07006148 : PlaybackThread(audioFlinger, output, id, type, systemReady)
Gareth Fennb18c1a32022-10-05 13:42:36 -07006149 , mOffloadInfo(offloadInfo)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006150{
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006151 setMasterBalance(audioFlinger->getMasterBalance_l());
Eric Laurentbfb1b832013-01-07 09:53:42 -08006152}
6153
Eric Laurent81784c32012-11-19 14:55:58 -08006154AudioFlinger::DirectOutputThread::~DirectOutputThread()
6155{
6156}
6157
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07006158void AudioFlinger::DirectOutputThread::dumpInternals_l(int fd, const Vector<String16>& args)
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006159{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07006160 PlaybackThread::dumpInternals_l(fd, args);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006161 dprintf(fd, " Master balance: %f Left: %f Right: %f\n",
6162 mMasterBalance.load(), mMasterBalanceLeft, mMasterBalanceRight);
6163}
6164
6165void AudioFlinger::DirectOutputThread::setMasterBalance(float balance)
6166{
6167 Mutex::Autolock _l(mLock);
6168 if (mMasterBalance != balance) {
6169 mMasterBalance.store(balance);
6170 mBalance.computeStereoBalance(balance, &mMasterBalanceLeft, &mMasterBalanceRight);
6171 broadcast_l();
6172 }
6173}
6174
Eric Laurent5850c4c2016-11-10 13:04:31 -08006175void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006176{
Eric Laurentbfb1b832013-01-07 09:53:42 -08006177 float left, right;
6178
Vlad Popae2f5aef2022-07-25 16:00:20 +02006179
Andy Hung333ab962019-05-28 20:23:35 -07006180 // Ensure volumeshaper state always advances even when muted.
6181 const sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
6182 const auto [shaperVolume, shaperActive] = track->getVolumeHandler()->getVolume(
6183 proxy->framesReleased());
6184 mVolumeShaperActive = shaperActive;
6185
Vlad Popae2f5aef2022-07-25 16:00:20 +02006186 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
6187 left = float_from_gain(gain_minifloat_unpack_left(vlr));
6188 right = float_from_gain(gain_minifloat_unpack_right(vlr));
6189
6190 const bool clientVolumeMute = (left == 0.f && right == 0.f);
6191
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08006192 if (mMasterMute || mStreamTypes[track->streamType()].mute || track->isPlaybackRestricted()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08006193 left = right = 0;
6194 } else {
6195 float typeVolume = mStreamTypes[track->streamType()].volume;
Andy Hung333ab962019-05-28 20:23:35 -07006196 const float v = mMasterVolume * typeVolume * shaperVolume;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08006197
Glenn Kastenc56f3422014-03-21 17:53:17 -07006198 if (left > GAIN_FLOAT_UNITY) {
6199 left = GAIN_FLOAT_UNITY;
6200 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07006201 if (right > GAIN_FLOAT_UNITY) {
6202 right = GAIN_FLOAT_UNITY;
6203 }
Vlad Popae2f5aef2022-07-25 16:00:20 +02006204
6205 left *= v * mMasterBalanceLeft; // DirectOutputThread balance applied as track volume
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006206 right *= v * mMasterBalanceRight;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006207 }
6208
Vlad Popae8d99472022-06-30 16:02:48 +02006209 track->processMuteEvent_l(mAudioFlinger->getOrCreateAudioManager(),
6210 /*muteState=*/{mMasterMute,
6211 mStreamTypes[track->streamType()].volume == 0.f,
6212 mStreamTypes[track->streamType()].mute,
Vlad Popae2f5aef2022-07-25 16:00:20 +02006213 track->isPlaybackRestricted(),
Vlad Popa436c9172022-08-02 15:25:08 +02006214 clientVolumeMute,
6215 shaperVolume == 0.f});
Vlad Popae8d99472022-06-30 16:02:48 +02006216
Eric Laurentbfb1b832013-01-07 09:53:42 -08006217 if (lastTrack) {
Kevin Rocard12381092018-04-11 09:19:59 -07006218 track->setFinalVolume((left + right) / 2.f);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006219 if (left != mLeftVolFloat || right != mRightVolFloat) {
6220 mLeftVolFloat = left;
6221 mRightVolFloat = right;
6222
Eric Laurentbfb1b832013-01-07 09:53:42 -08006223 // Delegate volume control to effect in track effect chain if needed
6224 // only one effect chain can be present on DirectOutputThread, so if
6225 // there is one, the track is connected to it
6226 if (!mEffectChains.isEmpty()) {
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09006227 // if effect chain exists, volume is handled by it.
6228 // Convert volumes from float to 8.24
6229 uint32_t vl = (uint32_t)(left * (1 << 24));
6230 uint32_t vr = (uint32_t)(right * (1 << 24));
6231 // Direct/Offload effect chains set output volume in setVolume_l().
6232 (void)mEffectChains[0]->setVolume_l(&vl, &vr);
6233 } else {
6234 // otherwise we directly set the volume.
6235 setVolumeForOutput_l(left, right);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006236 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006237 }
6238 }
6239}
6240
Phil Burk43b4dcc2015-06-09 16:53:44 -07006241void AudioFlinger::DirectOutputThread::onAddNewTrack_l()
6242{
6243 sp<Track> previousTrack = mPreviousTrack.promote();
Andy Hungdae27702016-10-31 14:01:16 -07006244 sp<Track> latestTrack = mActiveTracks.getLatest();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006245
Eric Laurent0f0631e2015-07-06 18:01:25 -07006246 if (previousTrack != 0 && latestTrack != 0) {
6247 if (mType == DIRECT) {
6248 if (previousTrack.get() != latestTrack.get()) {
6249 mFlushPending = true;
6250 }
6251 } else /* mType == OFFLOAD */ {
6252 if (previousTrack->sessionId() != latestTrack->sessionId()) {
6253 mFlushPending = true;
6254 }
6255 }
Revathi Uddaraju20413a92016-10-13 17:16:14 +08006256 } else if (previousTrack == 0) {
6257 // there could be an old track added back during track transition for direct
6258 // output, so always issues flush to flush data of the previous track if it
6259 // was already destroyed with HAL paused, then flush can resume the playback
6260 mFlushPending = true;
Phil Burk43b4dcc2015-06-09 16:53:44 -07006261 }
6262 PlaybackThread::onAddNewTrack_l();
6263}
Eric Laurentbfb1b832013-01-07 09:53:42 -08006264
Eric Laurent81784c32012-11-19 14:55:58 -08006265AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
6266 Vector< sp<Track> > *tracksToRemove
6267)
6268{
Eric Laurentd595b7c2013-04-03 17:27:56 -07006269 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08006270 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006271 bool doHwPause = false;
6272 bool doHwResume = false;
Eric Laurent81784c32012-11-19 14:55:58 -08006273
6274 // find out which tracks need to be processed
Andy Hungdae27702016-10-31 14:01:16 -07006275 for (const sp<Track> &t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08006276 if (t->isInvalid()) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07006277 ALOGW("An invalidated track shouldn't be in active list");
Eric Laurent5850c4c2016-11-10 13:04:31 -08006278 tracksToRemove->add(t);
Phil Burk43b4dcc2015-06-09 16:53:44 -07006279 continue;
6280 }
6281
Eric Laurent5850c4c2016-11-10 13:04:31 -08006282 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006283#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurent81784c32012-11-19 14:55:58 -08006284 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006285#endif
Eric Laurentfd477972013-10-25 18:10:40 -07006286 // Only consider last track started for volume and mixer state control.
6287 // In theory an older track could underrun and restart after the new one starts
6288 // but as we only care about the transition phase between two tracks on a
6289 // direct output, it is not a problem to ignore the underrun case.
Andy Hungdae27702016-10-31 14:01:16 -07006290 sp<Track> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08006291 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08006292
Kuowei Li23666472021-01-20 10:23:25 +08006293 if (track->isPausePending()) {
6294 track->pauseAck();
6295 // It is possible a track might have been flushed or stopped.
6296 // Other operations such as flush pending might occur on the next prepare.
6297 if (track->isPausing()) {
6298 track->setPaused();
6299 }
6300 // Always perform pause, as an immediate flush will change
6301 // the pause state to be no longer isPausing().
Phil Burk6fc2a7c2015-04-30 16:08:10 -07006302 if (mHwSupportsPause && last && !mHwPaused) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006303 doHwPause = true;
6304 mHwPaused = true;
6305 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08006306 } else if (track->isFlushPending()) {
6307 track->flushAck();
6308 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07006309 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006310 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07006311 } else if (track->isResumePending()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006312 track->resumeAck();
Eric Laurent3df841a2016-07-15 15:15:40 -07006313 if (last) {
6314 mLeftVolFloat = mRightVolFloat = -1.0;
6315 if (mHwPaused) {
6316 doHwResume = true;
6317 mHwPaused = false;
6318 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08006319 }
6320 }
6321
Eric Laurent81784c32012-11-19 14:55:58 -08006322 // The first time a track is added we wait
Phil Burk99adee32014-12-10 16:46:30 -08006323 // for all its buffers to be filled before processing it.
6324 // Allow draining the buffer in case the client
6325 // app does not call stop() and relies on underrun to stop:
6326 // hence the test on (track->mRetryCount > 1).
Andy Hung455982f2021-04-27 17:46:12 -07006327 // If track->mRetryCount <= 1 then track is about to be disabled, paused, removed,
6328 // so we accept any nonzero amount of data delivered by the AudioTrack (which will
6329 // reset the retry counter).
Phil Burkca5e6142015-07-14 09:42:29 -07006330 // Do not use a high threshold for compressed audio.
Andy Hung455982f2021-04-27 17:46:12 -07006331
6332 // target retry count that we will use is based on the time we wait for retries.
6333 const int32_t targetRetryCount = kMaxTrackRetriesDirectMs * 1000 / mActiveSleepTimeUs;
6334 // the retry threshold is when we accept any size for PCM data. This is slightly
6335 // smaller than the retry count so we can push small bits of data without a glitch.
6336 const int32_t retryThreshold = targetRetryCount > 2 ? targetRetryCount - 1 : 1;
Eric Laurent81784c32012-11-19 14:55:58 -08006337 uint32_t minFrames;
Phil Burk99adee32014-12-10 16:46:30 -08006338 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
Andy Hung455982f2021-04-27 17:46:12 -07006339 && (track->mRetryCount > retryThreshold) && audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006340 minFrames = mNormalFrameCount;
6341 } else {
6342 minFrames = 1;
6343 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006344
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07006345 const size_t framesReady = track->framesReady();
6346 const int trackId = track->id();
6347 if (ATRACE_ENABLED()) {
6348 std::string traceName("nRdy");
6349 traceName += std::to_string(trackId);
6350 ATRACE_INT(traceName.c_str(), framesReady);
6351 }
6352 if ((framesReady >= minFrames) && track->isReady() && !track->isPaused() &&
Eric Laurentab5cdba2014-06-09 17:22:27 -07006353 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08006354 {
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07006355 ALOGVV("track(%d) s=%08x [OK]", trackId, cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08006356
6357 if (track->mFillingUpStatus == Track::FS_FILLED) {
6358 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07006359 if (last) {
6360 // make sure processVolume_l() will apply new volume even if 0
6361 mLeftVolFloat = mRightVolFloat = -1.0;
6362 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08006363 if (!mHwSupportsPause) {
6364 track->resumeAck();
Eric Laurent81784c32012-11-19 14:55:58 -08006365 }
6366 }
6367
6368 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08006369 processVolume_l(track, last);
6370 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07006371 sp<Track> previousTrack = mPreviousTrack.promote();
6372 if (previousTrack != 0) {
6373 if (track != previousTrack.get()) {
6374 // Flush any data still being written from last track
6375 mBytesRemaining = 0;
Eric Laurent0f0631e2015-07-06 18:01:25 -07006376 // Invalidate previous track to force a seek when resuming.
6377 previousTrack->invalidate();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006378 }
6379 }
6380 mPreviousTrack = track;
6381
Eric Laurentd595b7c2013-04-03 17:27:56 -07006382 // reset retry count
Andy Hung455982f2021-04-27 17:46:12 -07006383 track->mRetryCount = targetRetryCount;
Eric Laurent5850c4c2016-11-10 13:04:31 -08006384 mActiveTrack = t;
Eric Laurentd595b7c2013-04-03 17:27:56 -07006385 mixerStatus = MIXER_TRACKS_READY;
Eric Laurent5cff4032015-05-26 13:49:58 -07006386 if (mHwPaused) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08006387 doHwResume = true;
6388 mHwPaused = false;
6389 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07006390 }
Eric Laurent81784c32012-11-19 14:55:58 -08006391 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07006392 // clear effect chain input buffer if the last active track started underruns
6393 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07006394 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08006395 mEffectChains[0]->clearInputBuffer();
6396 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07006397 if (track->isStopping_1()) {
6398 track->mState = TrackBase::STOPPING_2;
Eric Laurentb369caf2015-03-30 20:51:47 -07006399 if (last && mHwPaused) {
6400 doHwResume = true;
6401 mHwPaused = false;
6402 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07006403 }
6404 if ((track->sharedBuffer() != 0) || track->isStopped() ||
6405 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08006406 // We have consumed all the buffers of this track.
6407 // Remove it from the list of active tracks.
Atneya Nair0cae0432022-05-10 18:12:12 -04006408 bool presComplete = false;
Eric Laurentfd477972013-10-25 18:10:40 -07006409 if (mStandby || !last ||
Atneya Nair0cae0432022-05-10 18:12:12 -04006410 (presComplete = track->presentationComplete(latency_l())) ||
Jindong32dc26e2019-11-11 18:10:01 +08006411 track->isPaused() || mHwPaused) {
Atneya Nair0cae0432022-05-10 18:12:12 -04006412 if (presComplete) {
6413 mOutput->presentationComplete();
6414 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07006415 if (track->isStopping_2()) {
6416 track->mState = TrackBase::STOPPED;
6417 }
Eric Laurent81784c32012-11-19 14:55:58 -08006418 if (track->isStopped()) {
6419 track->reset();
6420 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07006421 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08006422 }
6423 } else {
6424 // No buffers for this track. Give it a few chances to
6425 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07006426 // Only consider last track started for mixer state control
Brian Lindahl65e90012022-07-27 18:01:07 +02006427 bool isTimestampAdvancing = mIsTimestampAdvancing.check(mOutput);
Gareth Fennb18c1a32022-10-05 13:42:36 -07006428 if (!isTunerStream() // tuner streams remain active in underrun
6429 && --(track->mRetryCount) <= 0) {
Brian Lindahl65e90012022-07-27 18:01:07 +02006430 if (isTimestampAdvancing) { // HAL is still playing audio, give us more time.
ziyangch8f194f12021-12-01 13:48:04 -08006431 track->mRetryCount = kMaxTrackRetriesOffload;
6432 } else {
6433 ALOGV("BUFFER TIMEOUT: remove track(%d) from active list", trackId);
6434 tracksToRemove->add(track);
6435 // indicate to client process that the track was disabled because of
6436 // underrun; it will then automatically call start() when data is available
6437 track->disable();
6438 // only do hw pause when track is going to be removed due to BUFFER TIMEOUT.
6439 // unlike mixerthread, HAL can be paused for direct output
6440 ALOGW("pause because of UNDERRUN, framesReady = %zu,"
6441 "minFrames = %u, mFormat = %#x",
6442 framesReady, minFrames, mFormat);
6443 if (last && mHwSupportsPause && !mHwPaused && !mStandby) {
6444 doHwPause = true;
6445 mHwPaused = true;
6446 }
Eric Laurent0f7b5f22014-12-19 10:43:21 -08006447 }
Haynes Mathew George5c6daae2017-01-24 20:06:05 -08006448 } else if (last) {
6449 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurent81784c32012-11-19 14:55:58 -08006450 }
6451 }
6452 }
6453 }
6454
Eric Laurentd1f69b02014-12-15 14:33:13 -08006455 // if an active track did not command a flush, check for pending flush on stopped tracks
Phil Burk43b4dcc2015-06-09 16:53:44 -07006456 if (!mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006457 for (size_t i = 0; i < mTracks.size(); i++) {
6458 if (mTracks[i]->isFlushPending()) {
6459 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006460 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006461 }
6462 }
6463 }
6464
6465 // make sure the pause/flush/resume sequence is executed in the right order.
6466 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
6467 // before flush and then resume HW. This can happen in case of pause/flush/resume
6468 // if resume is received before pause is executed.
6469 if (mHwSupportsPause && !mStandby &&
Phil Burk43b4dcc2015-06-09 16:53:44 -07006470 (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006471 status_t result = mOutput->stream->pause();
6472 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Gareth Fenncd1e1622022-10-05 11:45:45 -07006473 doHwResume = !doHwPause; // resume if pause is due to flush.
Eric Laurentd1f69b02014-12-15 14:33:13 -08006474 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07006475 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006476 flushHw_l();
6477 }
6478 if (mHwSupportsPause && !mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006479 status_t result = mOutput->stream->resume();
6480 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08006481 }
Eric Laurent81784c32012-11-19 14:55:58 -08006482 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08006483 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08006484
6485 return mixerStatus;
6486}
6487
6488void AudioFlinger::DirectOutputThread::threadLoop_mix()
6489{
Eric Laurent81784c32012-11-19 14:55:58 -08006490 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08006491 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08006492 // output audio to hardware
6493 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07006494 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08006495 buffer.frameCount = frameCount;
Phil Burk062e67a2015-02-11 13:40:50 -08006496 status_t status = mActiveTrack->getNextBuffer(&buffer);
6497 if (status != NO_ERROR || buffer.raw == NULL) {
Eric Laurent51716182016-02-29 18:00:56 -08006498 // no need to pad with 0 for compressed audio
6499 if (audio_has_proportional_frames(mFormat)) {
6500 memset(curBuf, 0, frameCount * mFrameSize);
6501 }
Eric Laurent81784c32012-11-19 14:55:58 -08006502 break;
6503 }
6504 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
6505 frameCount -= buffer.frameCount;
6506 curBuf += buffer.frameCount * mFrameSize;
6507 mActiveTrack->releaseBuffer(&buffer);
6508 }
Andy Hung2098f272014-02-27 14:00:06 -08006509 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006510 mSleepTimeUs = 0;
6511 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08006512 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08006513}
6514
6515void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
6516{
Eric Laurentd1f69b02014-12-15 14:33:13 -08006517 // do not write to HAL when paused
Eric Laurent0f7b5f22014-12-19 10:43:21 -08006518 if (mHwPaused || (usesHwAvSync() && mStandby)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006519 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006520 return;
6521 }
Andy Hung85ba3332021-04-27 17:40:26 -07006522 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
6523 mSleepTimeUs = mActiveSleepTimeUs;
6524 } else {
6525 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006526 }
Andy Hung85ba3332021-04-27 17:40:26 -07006527 // Note: In S or later, we do not write zeroes for
6528 // linear or proportional PCM direct tracks in underrun.
Eric Laurent81784c32012-11-19 14:55:58 -08006529}
6530
Eric Laurentd1f69b02014-12-15 14:33:13 -08006531void AudioFlinger::DirectOutputThread::threadLoop_exit()
6532{
6533 {
6534 Mutex::Autolock _l(mLock);
Eric Laurentd1f69b02014-12-15 14:33:13 -08006535 for (size_t i = 0; i < mTracks.size(); i++) {
6536 if (mTracks[i]->isFlushPending()) {
6537 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006538 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006539 }
6540 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07006541 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006542 flushHw_l();
6543 }
6544 }
6545 PlaybackThread::threadLoop_exit();
6546}
6547
6548// must be called with thread mutex locked
6549bool AudioFlinger::DirectOutputThread::shouldStandby_l()
6550{
6551 bool trackPaused = false;
Eric Laurentb369caf2015-03-30 20:51:47 -07006552 bool trackStopped = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006553
6554 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
6555 // after a timeout and we will enter standby then.
6556 if (mTracks.size() > 0) {
6557 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
Eric Laurentb369caf2015-03-30 20:51:47 -07006558 trackStopped = mTracks[mTracks.size() - 1]->isStopped() ||
6559 mTracks[mTracks.size() - 1]->mState == TrackBase::IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006560 }
6561
Eric Laurent5cff4032015-05-26 13:49:58 -07006562 return !mStandby && !(trackPaused || (mHwPaused && !trackStopped));
Eric Laurentd1f69b02014-12-15 14:33:13 -08006563}
6564
Eric Laurent10351942014-05-08 18:49:52 -07006565// checkForNewParameter_l() must be called with ThreadBase::mLock held
6566bool AudioFlinger::DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
6567 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08006568{
6569 bool reconfig = false;
Eric Laurent10351942014-05-08 18:49:52 -07006570 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006571
Eric Laurent10351942014-05-08 18:49:52 -07006572 AudioParameter param = AudioParameter(keyValuePair);
6573 int value;
6574 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07006575 LOG_FATAL("Should not set routing device in DirectOutputThread");
Eric Laurent81784c32012-11-19 14:55:58 -08006576 }
Eric Laurent10351942014-05-08 18:49:52 -07006577 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6578 // do not accept frame count changes if tracks are open as the track buffer
6579 // size depends on frame count and correct behavior would not be garantied
6580 // if frame count is changed after track creation
6581 if (!mTracks.isEmpty()) {
6582 status = INVALID_OPERATION;
6583 } else {
6584 reconfig = true;
6585 }
6586 }
6587 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006588 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07006589 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08006590 mOutput->standby();
Andy Hungcf10d742020-04-28 15:38:24 -07006591 if (!mStandby) {
6592 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07006593 mThreadSnapshot.onEnd();
Andy Hungcf10d742020-04-28 15:38:24 -07006594 mStandby = true;
6595 }
Eric Laurent10351942014-05-08 18:49:52 -07006596 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006597 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07006598 }
6599 if (status == NO_ERROR && reconfig) {
6600 readOutputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07006601 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07006602 }
6603 }
6604
Dean Wheatley68918102021-03-19 22:09:19 +11006605 return reconfig;
Eric Laurent81784c32012-11-19 14:55:58 -08006606}
6607
6608uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
6609{
6610 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08006611 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006612 time = PlaybackThread::activeSleepTimeUs();
6613 } else {
Eric Laurent51716182016-02-29 18:00:56 -08006614 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006615 }
6616 return time;
6617}
6618
6619uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
6620{
6621 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08006622 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006623 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
6624 } else {
Eric Laurent51716182016-02-29 18:00:56 -08006625 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006626 }
6627 return time;
6628}
6629
6630uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
6631{
6632 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08006633 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006634 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
6635 } else {
Eric Laurent51716182016-02-29 18:00:56 -08006636 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006637 }
6638 return time;
6639}
6640
6641void AudioFlinger::DirectOutputThread::cacheParameters_l()
6642{
6643 PlaybackThread::cacheParameters_l();
6644
6645 // use shorter standby delay as on normal output to release
6646 // hardware resources as soon as possible
Eric Laurentb369caf2015-03-30 20:51:47 -07006647 // no delay on outputs with HW A/V sync
6648 if (usesHwAvSync()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006649 mStandbyDelayNs = 0;
Phil Burkfdb3c072016-02-09 10:47:02 -08006650 } else if ((mType == OFFLOAD) && !audio_has_proportional_frames(mFormat)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006651 mStandbyDelayNs = kOffloadStandbyDelayNs;
Eric Laurent5cff4032015-05-26 13:49:58 -07006652 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006653 mStandbyDelayNs = microseconds(mActiveSleepTimeUs*2);
Eric Laurent972a1732013-09-04 09:42:59 -07006654 }
Eric Laurent81784c32012-11-19 14:55:58 -08006655}
6656
Eric Laurente659ef42014-09-29 13:06:46 -07006657void AudioFlinger::DirectOutputThread::flushHw_l()
6658{
ziyangch8f194f12021-12-01 13:48:04 -08006659 PlaybackThread::flushHw_l();
Phil Burk062e67a2015-02-11 13:40:50 -08006660 mOutput->flush();
Eric Laurentd1f69b02014-12-15 14:33:13 -08006661 mHwPaused = false;
Phil Burk43b4dcc2015-06-09 16:53:44 -07006662 mFlushPending = false;
Dean Wheatley12473e92021-03-18 23:00:55 +11006663 mTimestampVerifier.discontinuity(discontinuityForStandbyOrFlush());
Sampath Shetty999f0e82020-01-15 10:19:06 +11006664 mTimestamp.clear();
Eric Laurente659ef42014-09-29 13:06:46 -07006665}
6666
Andy Hung10cbff12017-02-21 17:30:14 -08006667int64_t AudioFlinger::DirectOutputThread::computeWaitTimeNs_l() const {
6668 // If a VolumeShaper is active, we must wake up periodically to update volume.
6669 const int64_t NS_PER_MS = 1000000;
6670 return mVolumeShaperActive ?
6671 kMinNormalSinkBufferSizeMs * NS_PER_MS : PlaybackThread::computeWaitTimeNs_l();
6672}
6673
Eric Laurent81784c32012-11-19 14:55:58 -08006674// ----------------------------------------------------------------------------
6675
Eric Laurentbfb1b832013-01-07 09:53:42 -08006676AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
Eric Laurent4de95592013-09-26 15:28:21 -07006677 const wp<AudioFlinger::PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006678 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07006679 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07006680 mWriteAckSequence(0),
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006681 mDrainSequence(0),
6682 mAsyncError(false)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006683{
6684}
6685
6686AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
6687{
6688}
6689
6690void AudioFlinger::AsyncCallbackThread::onFirstRef()
6691{
6692 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
6693}
6694
6695bool AudioFlinger::AsyncCallbackThread::threadLoop()
6696{
6697 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07006698 uint32_t writeAckSequence;
6699 uint32_t drainSequence;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006700 bool asyncError;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006701
6702 {
6703 Mutex::Autolock _l(mLock);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08006704 while (!((mWriteAckSequence & 1) ||
6705 (mDrainSequence & 1) ||
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006706 mAsyncError ||
Haynes Mathew George24a325d2013-12-03 21:26:02 -08006707 exitPending())) {
6708 mWaitWorkCV.wait(mLock);
6709 }
6710
Eric Laurentbfb1b832013-01-07 09:53:42 -08006711 if (exitPending()) {
6712 break;
6713 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07006714 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
6715 mWriteAckSequence, mDrainSequence);
6716 writeAckSequence = mWriteAckSequence;
6717 mWriteAckSequence &= ~1;
6718 drainSequence = mDrainSequence;
6719 mDrainSequence &= ~1;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006720 asyncError = mAsyncError;
6721 mAsyncError = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006722 }
6723 {
Eric Laurent4de95592013-09-26 15:28:21 -07006724 sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
6725 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07006726 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07006727 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006728 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07006729 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07006730 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006731 }
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006732 if (asyncError) {
6733 playbackThread->onAsyncError();
6734 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006735 }
6736 }
6737 }
6738 return false;
6739}
6740
6741void AudioFlinger::AsyncCallbackThread::exit()
6742{
6743 ALOGV("AsyncCallbackThread::exit");
6744 Mutex::Autolock _l(mLock);
6745 requestExit();
6746 mWaitWorkCV.broadcast();
6747}
6748
Eric Laurent3b4529e2013-09-05 18:09:19 -07006749void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006750{
6751 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07006752 // bit 0 is cleared
6753 mWriteAckSequence = sequence << 1;
6754}
6755
6756void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
6757{
6758 Mutex::Autolock _l(mLock);
6759 // ignore unexpected callbacks
6760 if (mWriteAckSequence & 2) {
6761 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006762 mWaitWorkCV.signal();
6763 }
6764}
6765
Eric Laurent3b4529e2013-09-05 18:09:19 -07006766void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006767{
6768 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07006769 // bit 0 is cleared
6770 mDrainSequence = sequence << 1;
6771}
6772
6773void AudioFlinger::AsyncCallbackThread::resetDraining()
6774{
6775 Mutex::Autolock _l(mLock);
6776 // ignore unexpected callbacks
6777 if (mDrainSequence & 2) {
6778 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006779 mWaitWorkCV.signal();
6780 }
6781}
6782
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006783void AudioFlinger::AsyncCallbackThread::setAsyncError()
6784{
6785 Mutex::Autolock _l(mLock);
6786 mAsyncError = true;
6787 mWaitWorkCV.signal();
6788}
6789
Eric Laurentbfb1b832013-01-07 09:53:42 -08006790
6791// ----------------------------------------------------------------------------
6792AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
Gareth Fennb18c1a32022-10-05 13:42:36 -07006793 AudioStreamOut* output, audio_io_handle_t id, bool systemReady,
6794 const audio_offload_info_t& offloadInfo)
6795 : DirectOutputThread(audioFlinger, output, id, OFFLOAD, systemReady, offloadInfo),
ziyangch8f194f12021-12-01 13:48:04 -08006796 mPausedWriteLength(0), mPausedBytesRemaining(0), mKeepWakeLock(true)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006797{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07006798 //FIXME: mStandby should be set to true by ThreadBase constructo
Eric Laurentfd477972013-10-25 18:10:40 -07006799 mStandby = true;
Eric Laurent64667972016-03-30 18:19:46 -07006800 mKeepWakeLock = property_get_bool("ro.audio.offload_wakelock", true /* default_value */);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006801}
6802
Eric Laurentbfb1b832013-01-07 09:53:42 -08006803void AudioFlinger::OffloadThread::threadLoop_exit()
6804{
6805 if (mFlushPending || mHwPaused) {
6806 // If a flush is pending or track was paused, just discard buffered data
6807 flushHw_l();
6808 } else {
6809 mMixerStatus = MIXER_DRAIN_ALL;
6810 threadLoop_drain();
6811 }
Uday Gupta56604aa2014-05-13 11:19:17 -07006812 if (mUseAsyncWrite) {
6813 ALOG_ASSERT(mCallbackThread != 0);
6814 mCallbackThread->exit();
6815 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006816 PlaybackThread::threadLoop_exit();
6817}
6818
6819AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
6820 Vector< sp<Track> > *tracksToRemove
6821)
6822{
Eric Laurentbfb1b832013-01-07 09:53:42 -08006823 size_t count = mActiveTracks.size();
6824
6825 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07006826 bool doHwPause = false;
6827 bool doHwResume = false;
6828
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006829 ALOGV("OffloadThread::prepareTracks_l active tracks %zu", count);
Eric Laurentede6c3b2013-09-19 14:37:46 -07006830
Eric Laurentbfb1b832013-01-07 09:53:42 -08006831 // find out which tracks need to be processed
Andy Hungdae27702016-10-31 14:01:16 -07006832 for (const sp<Track> &t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08006833 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006834#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurentbfb1b832013-01-07 09:53:42 -08006835 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006836#endif
Eric Laurentfd477972013-10-25 18:10:40 -07006837 // Only consider last track started for volume and mixer state control.
6838 // In theory an older track could underrun and restart after the new one starts
6839 // but as we only care about the transition phase between two tracks on a
6840 // direct output, it is not a problem to ignore the underrun case.
Andy Hungdae27702016-10-31 14:01:16 -07006841 sp<Track> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08006842 bool last = l.get() == track;
Eric Laurentfd477972013-10-25 18:10:40 -07006843
Haynes Mathew George7844f672014-01-15 12:32:55 -08006844 if (track->isInvalid()) {
6845 ALOGW("An invalidated track shouldn't be in active list");
6846 tracksToRemove->add(track);
6847 continue;
6848 }
6849
6850 if (track->mState == TrackBase::IDLE) {
6851 ALOGW("An idle track shouldn't be in active list");
6852 continue;
6853 }
6854
Kuowei Li23666472021-01-20 10:23:25 +08006855 if (track->isPausePending()) {
6856 track->pauseAck();
6857 // It is possible a track might have been flushed or stopped.
6858 // Other operations such as flush pending might occur on the next prepare.
6859 if (track->isPausing()) {
6860 track->setPaused();
6861 }
6862 // Always perform pause if last, as an immediate flush will change
6863 // the pause state to be no longer isPausing().
Eric Laurentbfb1b832013-01-07 09:53:42 -08006864 if (last) {
Eric Laurent5cff4032015-05-26 13:49:58 -07006865 if (mHwSupportsPause && !mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07006866 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006867 mHwPaused = true;
6868 }
6869 // If we were part way through writing the mixbuffer to
6870 // the HAL we must save this until we resume
6871 // BUG - this will be wrong if a different track is made active,
6872 // in that case we want to discard the pending data in the
6873 // mixbuffer and tell the client to present it again when the
6874 // track is resumed
6875 mPausedWriteLength = mCurrentWriteLength;
6876 mPausedBytesRemaining = mBytesRemaining;
6877 mBytesRemaining = 0; // stop writing
6878 }
6879 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08006880 } else if (track->isFlushPending()) {
Eric Laurente93cc032016-05-05 10:15:10 -07006881 if (track->isStopping_1()) {
6882 track->mRetryCount = kMaxTrackStopRetriesOffload;
6883 } else {
6884 track->mRetryCount = kMaxTrackRetriesOffload;
6885 }
Haynes Mathew George7844f672014-01-15 12:32:55 -08006886 track->flushAck();
6887 if (last) {
6888 mFlushPending = true;
6889 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08006890 } else if (track->isResumePending()){
6891 track->resumeAck();
6892 if (last) {
6893 if (mPausedBytesRemaining) {
6894 // Need to continue write that was interrupted
6895 mCurrentWriteLength = mPausedWriteLength;
6896 mBytesRemaining = mPausedBytesRemaining;
6897 mPausedBytesRemaining = 0;
6898 }
6899 if (mHwPaused) {
6900 doHwResume = true;
6901 mHwPaused = false;
6902 // threadLoop_mix() will handle the case that we need to
6903 // resume an interrupted write
6904 }
6905 // enable write to audio HAL
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006906 mSleepTimeUs = 0;
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08006907
Eric Laurent3df841a2016-07-15 15:15:40 -07006908 mLeftVolFloat = mRightVolFloat = -1.0;
6909
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08006910 // Do not handle new data in this iteration even if track->framesReady()
6911 mixerStatus = MIXER_TRACKS_ENABLED;
6912 }
6913 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07006914 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Andy Hungc0691382018-09-12 18:01:57 -07006915 ALOGVV("OffloadThread: track(%d) s=%08x [OK]", track->id(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006916 if (track->mFillingUpStatus == Track::FS_FILLED) {
6917 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07006918 if (last) {
6919 // make sure processVolume_l() will apply new volume even if 0
6920 mLeftVolFloat = mRightVolFloat = -1.0;
6921 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006922 }
6923
6924 if (last) {
Eric Laurentd7e59222013-11-15 12:02:28 -08006925 sp<Track> previousTrack = mPreviousTrack.promote();
6926 if (previousTrack != 0) {
6927 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08006928 // Flush any data still being written from last track
6929 mBytesRemaining = 0;
6930 if (mPausedBytesRemaining) {
6931 // Last track was paused so we also need to flush saved
6932 // mixbuffer state and invalidate track so that it will
6933 // re-submit that unwritten data when it is next resumed
6934 mPausedBytesRemaining = 0;
6935 // Invalidate is a bit drastic - would be more efficient
6936 // to have a flag to tell client that some of the
6937 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08006938 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08006939 }
6940 // flush data already sent to the DSP if changing audio session as audio
6941 // comes from a different source. Also invalidate previous track to force a
6942 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08006943 if (previousTrack->sessionId() != track->sessionId()) {
6944 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08006945 }
6946 }
6947 }
6948 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006949 // reset retry count
Eric Laurente93cc032016-05-05 10:15:10 -07006950 if (track->isStopping_1()) {
6951 track->mRetryCount = kMaxTrackStopRetriesOffload;
6952 } else {
6953 track->mRetryCount = kMaxTrackRetriesOffload;
6954 }
Eric Laurent5850c4c2016-11-10 13:04:31 -08006955 mActiveTrack = t;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006956 mixerStatus = MIXER_TRACKS_READY;
6957 }
6958 } else {
Andy Hungc0691382018-09-12 18:01:57 -07006959 ALOGVV("OffloadThread: track(%d) s=%08x [NOT READY]", track->id(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006960 if (track->isStopping_1()) {
Eric Laurente93cc032016-05-05 10:15:10 -07006961 if (--(track->mRetryCount) <= 0) {
6962 // Hardware buffer can hold a large amount of audio so we must
6963 // wait for all current track's data to drain before we say
6964 // that the track is stopped.
6965 if (mBytesRemaining == 0) {
6966 // Only start draining when all data in mixbuffer
6967 // has been written
6968 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
6969 track->mState = TrackBase::STOPPING_2; // so presentation completes after
6970 // drain do not drain if no data was ever sent to HAL (mStandby == true)
6971 if (last && !mStandby) {
6972 // do not modify drain sequence if we are already draining. This happens
6973 // when resuming from pause after drain.
6974 if ((mDrainSequence & 1) == 0) {
6975 mSleepTimeUs = 0;
6976 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
6977 mixerStatus = MIXER_DRAIN_TRACK;
6978 mDrainSequence += 2;
6979 }
6980 if (mHwPaused) {
6981 // It is possible to move from PAUSED to STOPPING_1 without
6982 // a resume so we must ensure hardware is running
6983 doHwResume = true;
6984 mHwPaused = false;
6985 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006986 }
6987 }
Eric Laurente93cc032016-05-05 10:15:10 -07006988 } else if (last) {
6989 ALOGV("stopping1 underrun retries left %d", track->mRetryCount);
6990 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006991 }
6992 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07006993 // Drain has completed or we are in standby, signal presentation complete
6994 if (!(mDrainSequence & 1) || !last || mStandby) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08006995 track->mState = TrackBase::STOPPED;
Atneya Nair0cae0432022-05-10 18:12:12 -04006996 mOutput->presentationComplete();
6997 track->presentationComplete(latency_l()); // always returns true
Eric Laurentbfb1b832013-01-07 09:53:42 -08006998 track->reset();
6999 tracksToRemove->add(track);
Dean Wheatley12473e92021-03-18 23:00:55 +11007000 // OFFLOADED stop resets frame counts.
Andy Hungf3234512018-07-03 14:51:47 -07007001 if (!mUseAsyncWrite) {
7002 // If we don't get explicit drain notification we must
7003 // register discontinuity regardless of whether this is
7004 // the previous (!last) or the upcoming (last) track
7005 // to avoid skipping the discontinuity.
Dean Wheatley12473e92021-03-18 23:00:55 +11007006 mTimestampVerifier.discontinuity(
7007 mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Andy Hungf3234512018-07-03 14:51:47 -07007008 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007009 }
7010 } else {
7011 // No buffers for this track. Give it a few chances to
7012 // fill a buffer, then remove it from active list.
Brian Lindahl65e90012022-07-27 18:01:07 +02007013 bool isTimestampAdvancing = mIsTimestampAdvancing.check(mOutput);
Gareth Fennb18c1a32022-10-05 13:42:36 -07007014 if (!isTunerStream() // tuner streams remain active in underrun
7015 && --(track->mRetryCount) <= 0) {
Brian Lindahl65e90012022-07-27 18:01:07 +02007016 if (isTimestampAdvancing) { // HAL is still playing audio, give us more time.
Andy Hungf8044752016-07-27 14:58:11 -07007017 track->mRetryCount = kMaxTrackRetriesOffload;
7018 } else {
Andy Hungc0691382018-09-12 18:01:57 -07007019 ALOGV("OffloadThread: BUFFER TIMEOUT: remove track(%d) from active list",
7020 track->id());
Andy Hungf8044752016-07-27 14:58:11 -07007021 tracksToRemove->add(track);
Glenn Kastend3bb6452016-12-05 18:14:37 -08007022 // tell client process that the track was disabled because of underrun;
Andy Hungf8044752016-07-27 14:58:11 -07007023 // it will then automatically call start() when data is available
7024 track->disable();
7025 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007026 } else if (last){
7027 mixerStatus = MIXER_TRACKS_ENABLED;
7028 }
7029 }
7030 }
7031 // compute volume for this track
Wenfeng Sun79458332019-05-29 20:12:43 +08007032 if (track->isReady()) { // check ready to prevent premature start.
7033 processVolume_l(track, last);
7034 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007035 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007036
Eric Laurentea0fade2013-10-04 16:23:48 -07007037 // make sure the pause/flush/resume sequence is executed in the right order.
7038 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
7039 // before flush and then resume HW. This can happen in case of pause/flush/resume
7040 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07007041 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007042 status_t result = mOutput->stream->pause();
7043 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Gareth Fenncd1e1622022-10-05 11:45:45 -07007044 doHwResume = !doHwPause; // resume if pause is due to flush.
Eric Laurent972a1732013-09-04 09:42:59 -07007045 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007046 if (mFlushPending) {
7047 flushHw_l();
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007048 }
Eric Laurentfd477972013-10-25 18:10:40 -07007049 if (!mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007050 status_t result = mOutput->stream->resume();
7051 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07007052 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007053
Eric Laurentbfb1b832013-01-07 09:53:42 -08007054 // remove all the tracks that need to be...
7055 removeTracks_l(*tracksToRemove);
7056
7057 return mixerStatus;
7058}
7059
Eric Laurentbfb1b832013-01-07 09:53:42 -08007060// must be called with thread mutex locked
7061bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
7062{
Eric Laurent3b4529e2013-09-05 18:09:19 -07007063 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
7064 mWriteAckSequence, mDrainSequence);
7065 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08007066 return true;
7067 }
7068 return false;
7069}
7070
Eric Laurentbfb1b832013-01-07 09:53:42 -08007071bool AudioFlinger::OffloadThread::waitingAsyncCallback()
7072{
7073 Mutex::Autolock _l(mLock);
7074 return waitingAsyncCallback_l();
7075}
7076
7077void AudioFlinger::OffloadThread::flushHw_l()
7078{
Eric Laurente659ef42014-09-29 13:06:46 -07007079 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08007080 // Flush anything still waiting in the mixbuffer
7081 mCurrentWriteLength = 0;
7082 mBytesRemaining = 0;
7083 mPausedWriteLength = 0;
7084 mPausedBytesRemaining = 0;
Eric Laurent3eaf66b2016-04-01 14:44:17 -07007085 // reset bytes written count to reflect that DSP buffers are empty after flush.
7086 mBytesWritten = 0;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08007087
Eric Laurentbfb1b832013-01-07 09:53:42 -08007088 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07007089 // discard any pending drain or write ack by incrementing sequence
7090 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
7091 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007092 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07007093 mCallbackThread->setWriteBlocked(mWriteAckSequence);
7094 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007095 }
7096}
7097
Haynes Mathew George05317d22016-05-03 16:34:26 -07007098void AudioFlinger::OffloadThread::invalidateTracks(audio_stream_type_t streamType)
7099{
7100 Mutex::Autolock _l(mLock);
Eric Laurent13084622016-05-17 10:51:49 -07007101 if (PlaybackThread::invalidateTracks_l(streamType)) {
7102 mFlushPending = true;
7103 }
Haynes Mathew George05317d22016-05-03 16:34:26 -07007104}
7105
Eric Laurentbfb1b832013-01-07 09:53:42 -08007106// ----------------------------------------------------------------------------
7107
Eric Laurent81784c32012-11-19 14:55:58 -08007108AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurent72e3f392015-05-20 14:43:50 -07007109 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id, bool systemReady)
jiabinc52b1ff2019-10-31 17:20:42 -07007110 : MixerThread(audioFlinger, mainThread->getOutput(), id,
Eric Laurent72e3f392015-05-20 14:43:50 -07007111 systemReady, DUPLICATING),
Eric Laurent81784c32012-11-19 14:55:58 -08007112 mWaitTimeMs(UINT_MAX)
7113{
7114 addOutputTrack(mainThread);
7115}
7116
7117AudioFlinger::DuplicatingThread::~DuplicatingThread()
7118{
7119 for (size_t i = 0; i < mOutputTracks.size(); i++) {
7120 mOutputTracks[i]->destroy();
7121 }
7122}
7123
7124void AudioFlinger::DuplicatingThread::threadLoop_mix()
7125{
7126 // mix buffers...
7127 if (outputsReady(outputTracks)) {
Glenn Kastend79072e2016-01-06 08:41:20 -08007128 mAudioMixer->process();
Eric Laurent81784c32012-11-19 14:55:58 -08007129 } else {
Eric Laurent02b57082014-11-07 17:28:28 -08007130 if (mMixerBufferValid) {
7131 memset(mMixerBuffer, 0, mMixerBufferSize);
7132 } else {
7133 memset(mSinkBuffer, 0, mSinkBufferSize);
7134 }
Eric Laurent81784c32012-11-19 14:55:58 -08007135 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007136 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007137 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08007138 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007139 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08007140}
7141
7142void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
7143{
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007144 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08007145 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007146 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007147 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007148 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007149 }
7150 } else if (mBytesWritten != 0) {
7151 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
7152 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08007153 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08007154 } else {
7155 // flush remaining overflow buffers in output tracks
7156 writeFrames = 0;
7157 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007158 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007159 }
7160}
7161
Eric Laurentbfb1b832013-01-07 09:53:42 -08007162ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08007163{
7164 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hung1c86ebe2018-05-29 20:29:08 -07007165 const ssize_t actualWritten = outputTracks[i]->write(mSinkBuffer, writeFrames);
7166
7167 // Consider the first OutputTrack for timestamp and frame counting.
7168
7169 // The threadLoop() generally assumes writing a full sink buffer size at a time.
7170 // Here, we correct for writeFrames of 0 (a stop) or underruns because
7171 // we always claim success.
7172 if (i == 0) {
7173 const ssize_t correction = mSinkBufferSize / mFrameSize - actualWritten;
7174 ALOGD_IF(correction != 0 && writeFrames != 0,
7175 "%s: writeFrames:%u actualWritten:%zd correction:%zd mFramesWritten:%lld",
7176 __func__, writeFrames, actualWritten, correction, (long long)mFramesWritten);
7177 mFramesWritten -= correction;
7178 }
7179
7180 // TODO: Report correction for the other output tracks and show in the dump.
Eric Laurent81784c32012-11-19 14:55:58 -08007181 }
Andy Hungcf10d742020-04-28 15:38:24 -07007182 if (mStandby) {
7183 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07007184 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -07007185 mStandby = false;
7186 }
Andy Hung25c2dac2014-02-27 14:56:00 -08007187 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08007188}
7189
7190void AudioFlinger::DuplicatingThread::threadLoop_standby()
7191{
7192 // DuplicatingThread implements standby by stopping all tracks
7193 for (size_t i = 0; i < outputTracks.size(); i++) {
7194 outputTracks[i]->stop();
7195 }
7196}
7197
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07007198void AudioFlinger::DuplicatingThread::dumpInternals_l(int fd, const Vector<String16>& args __unused)
Andy Hung1bc088a2018-02-09 15:57:31 -08007199{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07007200 MixerThread::dumpInternals_l(fd, args);
Andy Hung1bc088a2018-02-09 15:57:31 -08007201
7202 std::stringstream ss;
7203 const size_t numTracks = mOutputTracks.size();
7204 ss << " " << numTracks << " OutputTracks";
7205 if (numTracks > 0) {
7206 ss << ":";
7207 for (const auto &track : mOutputTracks) {
7208 const sp<ThreadBase> thread = track->thread().promote();
Andy Hungc0691382018-09-12 18:01:57 -07007209 ss << " (" << track->id() << " : ";
Andy Hung1bc088a2018-02-09 15:57:31 -08007210 if (thread.get() != nullptr) {
7211 ss << thread.get() << ", " << thread->id();
7212 } else {
7213 ss << "null";
7214 }
7215 ss << ")";
7216 }
7217 }
7218 ss << "\n";
7219 std::string result = ss.str();
7220 write(fd, result.c_str(), result.size());
7221}
7222
Eric Laurent81784c32012-11-19 14:55:58 -08007223void AudioFlinger::DuplicatingThread::saveOutputTracks()
7224{
7225 outputTracks = mOutputTracks;
7226}
7227
7228void AudioFlinger::DuplicatingThread::clearOutputTracks()
7229{
7230 outputTracks.clear();
7231}
7232
7233void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
7234{
7235 Mutex::Autolock _l(mLock);
Andy Hungc25b84a2015-01-14 19:04:10 -08007236 // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
7237 // Adjust for thread->sampleRate() to determine minimum buffer frame count.
7238 // Then triple buffer because Threads do not run synchronously and may not be clock locked.
7239 const size_t frameCount =
7240 3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
7241 // TODO: Consider asynchronous sample rate conversion to handle clock disparity
7242 // from different OutputTracks and their associated MixerThreads (e.g. one may
7243 // nearly empty and the other may be dropping data).
7244
Svet Ganov33761132021-05-13 22:51:08 +00007245 // TODO b/182392769: use attribution source util, move to server edge
7246 AttributionSourceState attributionSource = AttributionSourceState();
7247 attributionSource.uid = VALUE_OR_FATAL(legacy2aidl_uid_t_int32_t(
Philip P. Moltmannbda45752020-07-17 16:41:18 -07007248 IPCThreadState::self()->getCallingUid()));
Svet Ganov33761132021-05-13 22:51:08 +00007249 attributionSource.pid = VALUE_OR_FATAL(legacy2aidl_pid_t_int32_t(
Philip P. Moltmannbda45752020-07-17 16:41:18 -07007250 IPCThreadState::self()->getCallingPid()));
Svet Ganov33761132021-05-13 22:51:08 +00007251 attributionSource.token = sp<BBinder>::make();
Andy Hungc25b84a2015-01-14 19:04:10 -08007252 sp<OutputTrack> outputTrack = new OutputTrack(thread,
Eric Laurent81784c32012-11-19 14:55:58 -08007253 this,
7254 mSampleRate,
Andy Hungc25b84a2015-01-14 19:04:10 -08007255 mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08007256 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08007257 frameCount,
Svet Ganov33761132021-05-13 22:51:08 +00007258 attributionSource);
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07007259 status_t status = outputTrack != 0 ? outputTrack->initCheck() : (status_t) NO_MEMORY;
7260 if (status != NO_ERROR) {
7261 ALOGE("addOutputTrack() initCheck failed %d", status);
7262 return;
Eric Laurent81784c32012-11-19 14:55:58 -08007263 }
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07007264 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
7265 mOutputTracks.add(outputTrack);
7266 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
7267 updateWaitTime_l();
Eric Laurent81784c32012-11-19 14:55:58 -08007268}
7269
7270void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
7271{
7272 Mutex::Autolock _l(mLock);
7273 for (size_t i = 0; i < mOutputTracks.size(); i++) {
7274 if (mOutputTracks[i]->thread() == thread) {
7275 mOutputTracks[i]->destroy();
7276 mOutputTracks.removeAt(i);
7277 updateWaitTime_l();
Eric Laurentf6870ae2015-05-08 10:50:03 -07007278 if (thread->getOutput() == mOutput) {
7279 mOutput = NULL;
7280 }
Eric Laurent81784c32012-11-19 14:55:58 -08007281 return;
7282 }
7283 }
Eric Laurentf6870ae2015-05-08 10:50:03 -07007284 ALOGV("removeOutputTrack(): unknown thread: %p", thread);
Eric Laurent81784c32012-11-19 14:55:58 -08007285}
7286
7287// caller must hold mLock
7288void AudioFlinger::DuplicatingThread::updateWaitTime_l()
7289{
7290 mWaitTimeMs = UINT_MAX;
7291 for (size_t i = 0; i < mOutputTracks.size(); i++) {
7292 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
7293 if (strong != 0) {
7294 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
7295 if (waitTimeMs < mWaitTimeMs) {
7296 mWaitTimeMs = waitTimeMs;
7297 }
7298 }
7299 }
7300}
7301
7302
7303bool AudioFlinger::DuplicatingThread::outputsReady(
7304 const SortedVector< sp<OutputTrack> > &outputTracks)
7305{
7306 for (size_t i = 0; i < outputTracks.size(); i++) {
7307 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
7308 if (thread == 0) {
7309 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
7310 outputTracks[i].get());
7311 return false;
7312 }
7313 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
7314 // see note at standby() declaration
7315 if (playbackThread->standby() && !playbackThread->isSuspended()) {
7316 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
7317 thread.get());
7318 return false;
7319 }
7320 }
7321 return true;
7322}
7323
Kevin Rocard12381092018-04-11 09:19:59 -07007324void AudioFlinger::DuplicatingThread::sendMetadataToBackend_l(
7325 const StreamOutHalInterface::SourceMetadata& metadata)
Kevin Rocard069c2712018-03-29 19:09:14 -07007326{
Kevin Rocard12381092018-04-11 09:19:59 -07007327 for (auto& outputTrack : outputTracks) { // not mOutputTracks
7328 outputTrack->setMetadatas(metadata.tracks);
7329 }
Kevin Rocard069c2712018-03-29 19:09:14 -07007330}
7331
Eric Laurent81784c32012-11-19 14:55:58 -08007332uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
7333{
7334 return (mWaitTimeMs * 1000) / 2;
7335}
7336
7337void AudioFlinger::DuplicatingThread::cacheParameters_l()
7338{
7339 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
7340 updateWaitTime_l();
7341
7342 MixerThread::cacheParameters_l();
7343}
7344
Eric Laurentb3f315a2021-07-13 15:09:05 +02007345// ----------------------------------------------------------------------------
7346
Eric Laurentfa0f6742021-08-17 18:39:44 +02007347AudioFlinger::SpatializerThread::SpatializerThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurentb3f315a2021-07-13 15:09:05 +02007348 AudioStreamOut* output,
7349 audio_io_handle_t id,
7350 bool systemReady,
7351 audio_config_base_t *mixerConfig)
Eric Laurent1c5e2e32021-08-18 18:50:28 +02007352 : MixerThread(audioFlinger, output, id, systemReady, SPATIALIZER, mixerConfig)
Eric Laurentb3f315a2021-07-13 15:09:05 +02007353{
7354}
7355
Eric Laurent68a40a82022-05-03 18:15:04 +02007356void AudioFlinger::SpatializerThread::onFirstRef() {
7357 PlaybackThread::onFirstRef();
7358
7359 Mutex::Autolock _l(mLock);
7360 status_t status = mOutput->stream->setLatencyModeCallback(this);
7361 if (status != INVALID_OPERATION) {
7362 updateHalSupportedLatencyModes_l();
7363 }
7364}
7365
7366status_t AudioFlinger::SpatializerThread::createAudioPatch_l(const struct audio_patch *patch,
7367 audio_patch_handle_t *handle)
7368{
7369 status_t status = MixerThread::createAudioPatch_l(patch, handle);
7370 updateHalSupportedLatencyModes_l();
7371 return status;
7372}
7373
7374void AudioFlinger::SpatializerThread::updateHalSupportedLatencyModes_l() {
7375 std::vector<audio_latency_mode_t> latencyModes;
7376 if (mOutput->stream->getRecommendedLatencyModes(&latencyModes) != NO_ERROR) {
7377 latencyModes.clear();
7378 }
7379 if (latencyModes != mSupportedLatencyModes) {
7380 mSupportedLatencyModes.swap(latencyModes);
7381 sendHalLatencyModesChangedEvent_l();
7382 }
7383}
7384
7385void AudioFlinger::SpatializerThread::onHalLatencyModesChanged_l() {
7386 mAudioFlinger->onSupportedLatencyModesChanged(mId, mSupportedLatencyModes);
7387}
7388
7389void AudioFlinger::SpatializerThread::setHalLatencyMode_l() {
7390 // if mSupportedLatencyModes is empty, the HAL stream does not support
7391 // latency mode control and we can exit.
7392 if (mSupportedLatencyModes.empty()) {
7393 return;
7394 }
7395 audio_latency_mode_t latencyMode = AUDIO_LATENCY_MODE_FREE;
7396 if (mSupportedLatencyModes.size() == 1) {
7397 // If the HAL only support one latency mode currently, confirm the choice
7398 latencyMode = mSupportedLatencyModes[0];
7399 } else if (mSupportedLatencyModes.size() > 1) {
7400 // Request low latency if:
7401 // - The low latency mode is requested by the spatializer controller
7402 // (mRequestedLatencyMode = AUDIO_LATENCY_MODE_LOW)
7403 // AND
7404 // - At least one active track is spatialized
7405 bool hasSpatializedActiveTrack = false;
7406 for (const auto& track : mActiveTracks) {
7407 if (track->isSpatialized()) {
7408 hasSpatializedActiveTrack = true;
7409 break;
7410 }
7411 }
7412 if (hasSpatializedActiveTrack && mRequestedLatencyMode == AUDIO_LATENCY_MODE_LOW) {
7413 latencyMode = AUDIO_LATENCY_MODE_LOW;
7414 }
7415 }
7416
7417 if (latencyMode != mSetLatencyMode) {
7418 status_t status = mOutput->stream->setLatencyMode(latencyMode);
7419 if (status == NO_ERROR) {
7420 mSetLatencyMode = latencyMode;
7421 }
7422 }
7423}
7424
7425status_t AudioFlinger::SpatializerThread::setRequestedLatencyMode(audio_latency_mode_t mode) {
7426 if (mode != AUDIO_LATENCY_MODE_LOW && mode != AUDIO_LATENCY_MODE_FREE) {
7427 return BAD_VALUE;
7428 }
7429 Mutex::Autolock _l(mLock);
7430 mRequestedLatencyMode = mode;
7431 return NO_ERROR;
7432}
7433
7434status_t AudioFlinger::SpatializerThread::getSupportedLatencyModes(
7435 std::vector<audio_latency_mode_t>* modes) {
7436 if (modes == nullptr) {
7437 return BAD_VALUE;
7438 }
7439 Mutex::Autolock _l(mLock);
7440 *modes = mSupportedLatencyModes;
7441 return NO_ERROR;
7442}
7443
Eric Laurentfa0f6742021-08-17 18:39:44 +02007444void AudioFlinger::SpatializerThread::checkOutputStageEffects()
Eric Laurentb3f315a2021-07-13 15:09:05 +02007445{
7446 bool hasVirtualizer = false;
7447 bool hasDownMixer = false;
7448 sp<EffectHandle> finalDownMixer;
7449 {
7450 Mutex::Autolock _l(mLock);
7451 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_STAGE);
7452 if (chain != 0) {
Eric Laurent1c5e2e32021-08-18 18:50:28 +02007453 hasVirtualizer = chain->getEffectFromType_l(FX_IID_SPATIALIZER) != nullptr;
Eric Laurentb3f315a2021-07-13 15:09:05 +02007454 hasDownMixer = chain->getEffectFromType_l(EFFECT_UIID_DOWNMIX) != nullptr;
7455 }
7456
7457 finalDownMixer = mFinalDownMixer;
7458 mFinalDownMixer.clear();
7459 }
7460
7461 if (hasVirtualizer) {
7462 if (finalDownMixer != nullptr) {
7463 int32_t ret;
7464 finalDownMixer->disable(&ret);
7465 }
7466 finalDownMixer.clear();
7467 } else if (!hasDownMixer) {
7468 std::vector<effect_descriptor_t> descriptors;
7469 status_t status = mAudioFlinger->mEffectsFactoryHal->getDescriptors(
7470 EFFECT_UIID_DOWNMIX, &descriptors);
7471 if (status != NO_ERROR) {
7472 return;
7473 }
7474 ALOG_ASSERT(!descriptors.empty(),
7475 "%s getDescriptors() returned no error but empty list", __func__);
7476
7477 finalDownMixer = createEffect_l(nullptr /*client*/, nullptr /*effectClient*/,
7478 0 /*priority*/, AUDIO_SESSION_OUTPUT_STAGE, &descriptors[0], nullptr /*enabled*/,
Eric Laurentde8caf42021-08-11 17:19:25 +02007479 &status, false /*pinned*/, false /*probe*/, false /*notifyFramesProcessed*/);
Eric Laurentb3f315a2021-07-13 15:09:05 +02007480
7481 if (finalDownMixer == nullptr || (status != NO_ERROR && status != ALREADY_EXISTS)) {
7482 ALOGW("%s error creating downmixer %d", __func__, status);
7483 finalDownMixer.clear();
7484 } else {
7485 int32_t ret;
7486 finalDownMixer->enable(&ret);
7487 }
7488 }
7489
7490 {
7491 Mutex::Autolock _l(mLock);
7492 mFinalDownMixer = finalDownMixer;
7493 }
7494}
7495
Eric Laurent68a40a82022-05-03 18:15:04 +02007496void AudioFlinger::SpatializerThread::onRecommendedLatencyModeChanged(
7497 std::vector<audio_latency_mode_t> modes) {
7498 Mutex::Autolock _l(mLock);
7499 if (modes != mSupportedLatencyModes) {
7500 mSupportedLatencyModes.swap(modes);
7501 sendHalLatencyModesChangedEvent_l();
7502 }
7503}
Eric Laurent6acd1d42017-01-04 14:23:29 -08007504
Eric Laurent81784c32012-11-19 14:55:58 -08007505// ----------------------------------------------------------------------------
7506// Record
7507// ----------------------------------------------------------------------------
7508
7509AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
7510 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08007511 audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -07007512 bool systemReady
Glenn Kasten46909e72013-02-26 09:20:22 -08007513 ) :
Andy Hungcf10d742020-04-28 15:38:24 -07007514 ThreadBase(audioFlinger, id, RECORD, systemReady, false /* isOut */),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007515 mInput(input),
Mikhail Naganov2534b382019-09-25 13:05:02 -07007516 mSource(mInput),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007517 mActiveTracks(&this->mLocalLog),
7518 mRsmpInBuffer(NULL),
Glenn Kasten1b291842016-07-18 14:55:21 -07007519 // mRsmpInFrames, mRsmpInFramesP2, and mRsmpInFramesOA are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007520 mRsmpInRear(0)
Glenn Kastenb880f5e2014-05-07 08:43:45 -07007521 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
7522 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007523 // mFastCapture below
7524 , mFastCaptureFutex(0)
7525 // mInputSource
7526 // mPipeSink
7527 // mPipeSource
7528 , mPipeFramesP2(0)
7529 // mPipeMemory
7530 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07007531 , mFastTrackAvail(false)
Eric Laurentd8365c52017-07-16 15:27:05 -07007532 , mBtNrecSuspended(false)
Eric Laurent81784c32012-11-19 14:55:58 -08007533{
Glenn Kastend7dca052015-03-05 16:05:54 -08007534 snprintf(mThreadName, kThreadNameLength, "AudioIn_%X", id);
7535 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08007536
George Burgess IVa8f90c12020-05-14 11:27:19 -07007537 if (mInput->audioHwDev != nullptr) {
Andy Hungc8fddf32018-08-08 18:32:37 -07007538 mIsMsdDevice = strcmp(
7539 mInput->audioHwDev->moduleName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0;
7540 }
7541
Glenn Kastendeca2ae2014-02-07 10:25:56 -08007542 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007543
Andy Hungc8fddf32018-08-08 18:32:37 -07007544 // TODO: We may also match on address as well as device type for
7545 // AUDIO_DEVICE_IN_BUS, AUDIO_DEVICE_IN_BLUETOOTH_A2DP, AUDIO_DEVICE_IN_REMOTE_SUBMIX
jiabinc52b1ff2019-10-31 17:20:42 -07007546 // TODO: This property should be ensure that only contains one single device type.
7547 mTimestampCorrectedDevice = (audio_devices_t)property_get_int64(
7548 "audio.timestamp.corrected_input_device",
Andy Hungc8fddf32018-08-08 18:32:37 -07007549 (int64_t)(mIsMsdDevice ? AUDIO_DEVICE_IN_BUS // turn on by default for MSD
7550 : AUDIO_DEVICE_NONE));
7551
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007552 // create an NBAIO source for the HAL input stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07007553 mInputSource = new AudioStreamInSource(input->stream);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007554 size_t numCounterOffers = 0;
7555 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07007556#if !LOG_NDEBUG
7557 ssize_t index =
7558#else
7559 (void)
7560#endif
7561 mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007562 ALOG_ASSERT(index == 0);
7563
7564 // initialize fast capture depending on configuration
7565 bool initFastCapture;
7566 switch (kUseFastCapture) {
7567 case FastCapture_Never:
7568 initFastCapture = false;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007569 ALOGV("%p kUseFastCapture = Never, initFastCapture = false", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007570 break;
7571 case FastCapture_Always:
7572 initFastCapture = true;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007573 ALOGV("%p kUseFastCapture = Always, initFastCapture = true", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007574 break;
7575 case FastCapture_Static:
Glenn Kasteneb9487e2015-07-22 09:15:17 -07007576 initFastCapture = (mFrameCount * 1000) / mSampleRate < kMinNormalCaptureBufferSizeMs;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007577 ALOGV("%p kUseFastCapture = Static, (%lld * 1000) / %u vs %u, initFastCapture = %d",
7578 this, (long long)mFrameCount, mSampleRate, kMinNormalCaptureBufferSizeMs,
7579 initFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007580 break;
7581 // case FastCapture_Dynamic:
7582 }
7583
7584 if (initFastCapture) {
Glenn Kastend198b852015-03-16 14:55:53 -07007585 // create a Pipe for FastCapture to write to, and for us and fast tracks to read from
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007586 NBAIO_Format format = mInputSource->format();
Glenn Kasten1b291842016-07-18 14:55:21 -07007587 // quadruple-buffering of 20 ms each; this ensures we can sleep for 20ms in RecordThread
7588 size_t pipeFramesP2 = roundup(4 * FMS_20 * mSampleRate / 1000);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007589 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007590 void *pipeBuffer = nullptr;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007591 const sp<MemoryDealer> roHeap(readOnlyHeap());
7592 sp<IMemory> pipeMemory;
7593 if ((roHeap == 0) ||
7594 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07007595 (pipeBuffer = pipeMemory->unsecurePointer()) == nullptr) {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007596 ALOGE("not enough memory for pipe buffer size=%zu; "
7597 "roHeap=%p, pipeMemory=%p, pipeBuffer=%p; roHeapSize: %lld",
7598 pipeSize, roHeap.get(), pipeMemory.get(), pipeBuffer,
7599 (long long)kRecordThreadReadOnlyHeapSize);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007600 goto failed;
7601 }
7602 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
7603 memset(pipeBuffer, 0, pipeSize);
7604 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
7605 const NBAIO_Format offers[1] = {format};
7606 size_t numCounterOffers = 0;
7607 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
7608 ALOG_ASSERT(index == 0);
7609 mPipeSink = pipe;
7610 PipeReader *pipeReader = new PipeReader(*pipe);
7611 numCounterOffers = 0;
7612 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
7613 ALOG_ASSERT(index == 0);
7614 mPipeSource = pipeReader;
7615 mPipeFramesP2 = pipeFramesP2;
7616 mPipeMemory = pipeMemory;
7617
7618 // create fast capture
7619 mFastCapture = new FastCapture();
7620 FastCaptureStateQueue *sq = mFastCapture->sq();
7621#ifdef STATE_QUEUE_DUMP
7622 // FIXME
7623#endif
7624 FastCaptureState *state = sq->begin();
7625 state->mCblk = NULL;
7626 state->mInputSource = mInputSource.get();
7627 state->mInputSourceGen++;
7628 state->mPipeSink = pipe;
7629 state->mPipeSinkGen++;
7630 state->mFrameCount = mFrameCount;
7631 state->mCommand = FastCaptureState::COLD_IDLE;
7632 // already done in constructor initialization list
7633 //mFastCaptureFutex = 0;
7634 state->mColdFutexAddr = &mFastCaptureFutex;
7635 state->mColdGen++;
7636 state->mDumpState = &mFastCaptureDumpState;
7637#ifdef TEE_SINK
7638 // FIXME
7639#endif
7640 mFastCaptureNBLogWriter = audioFlinger->newWriter_l(kFastCaptureLogSize, "FastCapture");
7641 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
7642 sq->end();
7643 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
7644
7645 // start the fast capture
7646 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
7647 pid_t tid = mFastCapture->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07007648 sendPrioConfigEvent(getpid(), tid, kPriorityFastCapture, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08007649 stream()->setHalThreadPriority(kPriorityFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007650#ifdef AUDIO_WATCHDOG
7651 // FIXME
7652#endif
7653
Glenn Kasten6e6704c2014-07-03 10:20:00 -07007654 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007655 }
Andy Hung8946a282018-04-19 20:04:56 -07007656#ifdef TEE_SINK
7657 mTee.set(mInputSource->format(), NBAIO_Tee::TEE_FLAG_INPUT_THREAD);
7658 mTee.setId(std::string("_") + std::to_string(mId) + "_C");
7659#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007660failed: ;
7661
7662 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08007663}
7664
Eric Laurent81784c32012-11-19 14:55:58 -08007665AudioFlinger::RecordThread::~RecordThread()
7666{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007667 if (mFastCapture != 0) {
7668 FastCaptureStateQueue *sq = mFastCapture->sq();
7669 FastCaptureState *state = sq->begin();
7670 if (state->mCommand == FastCaptureState::COLD_IDLE) {
7671 int32_t old = android_atomic_inc(&mFastCaptureFutex);
7672 if (old == -1) {
7673 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
7674 }
7675 }
7676 state->mCommand = FastCaptureState::EXIT;
7677 sq->end();
7678 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
7679 mFastCapture->join();
7680 mFastCapture.clear();
7681 }
7682 mAudioFlinger->unregisterWriter(mFastCaptureNBLogWriter);
Glenn Kasten481fb672013-09-30 14:39:28 -07007683 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung57446612015-04-19 23:56:46 -07007684 free(mRsmpInBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08007685}
7686
7687void AudioFlinger::RecordThread::onFirstRef()
7688{
Glenn Kastend7dca052015-03-05 16:05:54 -08007689 run(mThreadName, PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08007690}
7691
Eric Laurent555530a2017-02-07 18:17:24 -08007692void AudioFlinger::RecordThread::preExit()
7693{
7694 ALOGV(" preExit()");
7695 Mutex::Autolock _l(mLock);
7696 for (size_t i = 0; i < mTracks.size(); i++) {
7697 sp<RecordTrack> track = mTracks[i];
7698 track->invalidate();
7699 }
7700 mActiveTracks.clear();
7701 mStartStopCond.broadcast();
7702}
7703
Eric Laurent81784c32012-11-19 14:55:58 -08007704bool AudioFlinger::RecordThread::threadLoop()
7705{
Eric Laurent81784c32012-11-19 14:55:58 -08007706 nsecs_t lastWarning = 0;
7707
7708 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08007709
Glenn Kastenf10ffec2013-11-20 16:40:08 -08007710reacquire_wakelock:
7711 sp<RecordTrack> activeTrack;
7712 {
7713 Mutex::Autolock _l(mLock);
Andy Hungdae27702016-10-31 14:01:16 -07007714 acquireWakeLock_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08007715 }
7716
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007717 // used to request a deferred sleep, to be executed later while mutex is unlocked
7718 uint32_t sleepUs = 0;
7719
Andy Hung446f4df2019-02-21 12:26:41 -08007720 int64_t lastLoopCountRead = -2; // never matches "previous" loop, when loopCount = 0.
7721
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007722 // loop while there is work to do
Andy Hung446f4df2019-02-21 12:26:41 -08007723 for (int64_t loopCount = 0;; ++loopCount) { // loopCount used for statistics tracking
Glenn Kastenc527a7c2013-08-13 15:43:49 -07007724 Vector< sp<EffectChain> > effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07007725
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007726 // activeTracks accumulates a copy of a subset of mActiveTracks
7727 Vector< sp<RecordTrack> > activeTracks;
7728
Glenn Kasten735f45f2014-08-18 15:51:59 -07007729 // reference to the (first and only) active fast track
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007730 sp<RecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07007731
Glenn Kasten735f45f2014-08-18 15:51:59 -07007732 // reference to a fast track which is about to be removed
7733 sp<RecordTrack> fastTrackToRemove;
7734
Eric Laurent33403f02020-05-29 18:35:06 -07007735 bool silenceFastCapture = false;
7736
Eric Laurent81784c32012-11-19 14:55:58 -08007737 { // scope for mLock
7738 Mutex::Autolock _l(mLock);
Eric Laurent000a4192014-01-29 15:17:32 -08007739
Eric Laurent021cf962014-05-13 10:18:14 -07007740 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08007741
Eric Laurent000a4192014-01-29 15:17:32 -08007742 // check exitPending here because checkForNewParameters_l() and
7743 // checkForNewParameters_l() can temporarily release mLock
7744 if (exitPending()) {
7745 break;
7746 }
7747
Eric Laurent5c25d562016-07-13 17:17:45 -07007748 // sleep with mutex unlocked
7749 if (sleepUs > 0) {
Glenn Kastenf9715e42016-07-13 14:02:03 -07007750 ATRACE_BEGIN("sleepC");
Eric Laurent5c25d562016-07-13 17:17:45 -07007751 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)sleepUs));
7752 ATRACE_END();
7753 sleepUs = 0;
7754 continue;
7755 }
7756
Glenn Kasten2b806402013-11-20 16:37:38 -08007757 // if no active track(s), then standby and release wakelock
7758 size_t size = mActiveTracks.size();
7759 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07007760 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07007761 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08007762 releaseWakeLock_l();
7763 ALOGV("RecordThread: loop stopping");
7764 // go to sleep
7765 mWaitWorkCV.wait(mLock);
7766 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08007767 goto reacquire_wakelock;
7768 }
7769
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007770 bool doBroadcast = false;
Eric Laurent5c25d562016-07-13 17:17:45 -07007771 bool allStopped = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007772 for (size_t i = 0; i < size; ) {
Glenn Kasten9e982352013-08-14 14:39:50 -07007773
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007774 activeTrack = mActiveTracks[i];
7775 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07007776 if (activeTrack->isFastTrack()) {
7777 ALOG_ASSERT(fastTrackToRemove == 0);
7778 fastTrackToRemove = activeTrack;
7779 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007780 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08007781 mActiveTracks.remove(activeTrack);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007782 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07007783 continue;
7784 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007785
7786 TrackBase::track_state activeTrackState = activeTrack->mState;
7787 switch (activeTrackState) {
7788
7789 case TrackBase::PAUSING:
7790 mActiveTracks.remove(activeTrack);
Andy Hungce685402018-10-05 17:23:27 -07007791 activeTrack->mState = TrackBase::PAUSED;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007792 doBroadcast = true;
7793 size--;
7794 continue;
7795
7796 case TrackBase::STARTING_1:
7797 sleepUs = 10000;
7798 i++;
Eric Laurent5c25d562016-07-13 17:17:45 -07007799 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007800 continue;
7801
7802 case TrackBase::STARTING_2:
7803 doBroadcast = true;
Andy Hungcf10d742020-04-28 15:38:24 -07007804 if (mStandby) {
7805 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07007806 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -07007807 mStandby = false;
7808 }
Glenn Kasten9e982352013-08-14 14:39:50 -07007809 activeTrack->mState = TrackBase::ACTIVE;
Eric Laurent5c25d562016-07-13 17:17:45 -07007810 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007811 break;
7812
7813 case TrackBase::ACTIVE:
Eric Laurent5c25d562016-07-13 17:17:45 -07007814 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007815 break;
7816
Andy Hungce685402018-10-05 17:23:27 -07007817 case TrackBase::IDLE: // cannot be on ActiveTracks if idle
7818 case TrackBase::PAUSED: // cannot be on ActiveTracks if paused
7819 case TrackBase::STOPPED: // cannot be on ActiveTracks if destroyed/terminated
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007820 default:
Andy Hungce685402018-10-05 17:23:27 -07007821 LOG_ALWAYS_FATAL("%s: Unexpected active track state:%d, id:%d, tracks:%zu",
7822 __func__, activeTrackState, activeTrack->id(), size);
Glenn Kasten9e982352013-08-14 14:39:50 -07007823 }
Glenn Kasten9e982352013-08-14 14:39:50 -07007824
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007825 if (activeTrack->isFastTrack()) {
7826 ALOG_ASSERT(!mFastTrackAvail);
7827 ALOG_ASSERT(fastTrack == 0);
Eric Laurent33403f02020-05-29 18:35:06 -07007828 // if the active fast track is silenced either:
7829 // 1) silence the whole capture from fast capture buffer if this is
7830 // the only active track
7831 // 2) invalidate this track: this will cause the client to reconnect and possibly
7832 // be invalidated again until unsilenced
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02007833 bool invalidate = false;
Eric Laurent33403f02020-05-29 18:35:06 -07007834 if (activeTrack->isSilenced()) {
7835 if (size > 1) {
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02007836 invalidate = true;
Eric Laurent33403f02020-05-29 18:35:06 -07007837 } else {
7838 silenceFastCapture = true;
7839 }
7840 }
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02007841 // Invalidate fast tracks if access to audio history is required as this is not
7842 // possible with fast tracks. Once the fast track has been invalidated, no new
7843 // fast track will be created until mMaxSharedAudioHistoryMs is cleared.
7844 if (mMaxSharedAudioHistoryMs != 0) {
7845 invalidate = true;
7846 }
7847 if (invalidate) {
7848 activeTrack->invalidate();
7849 ALOG_ASSERT(fastTrackToRemove == 0);
7850 fastTrackToRemove = activeTrack;
7851 removeTrack_l(activeTrack);
7852 mActiveTracks.remove(activeTrack);
7853 size--;
7854 continue;
7855 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007856 fastTrack = activeTrack;
7857 }
Eric Laurent33403f02020-05-29 18:35:06 -07007858
7859 activeTracks.add(activeTrack);
7860 i++;
7861
Glenn Kasten9e982352013-08-14 14:39:50 -07007862 }
Eric Laurent5c25d562016-07-13 17:17:45 -07007863
Andy Hungdae27702016-10-31 14:01:16 -07007864 mActiveTracks.updatePowerState(this);
7865
Kevin Rocard069c2712018-03-29 19:09:14 -07007866 updateMetadata_l();
7867
Eric Laurent5c25d562016-07-13 17:17:45 -07007868 if (allStopped) {
7869 standbyIfNotAlreadyInStandby();
7870 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007871 if (doBroadcast) {
7872 mStartStopCond.broadcast();
7873 }
7874
7875 // sleep if there are no active tracks to process
Eric Tan39ec8d62018-07-24 09:49:29 -07007876 if (activeTracks.isEmpty()) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007877 if (sleepUs == 0) {
7878 sleepUs = kRecordThreadSleepUs;
7879 }
7880 continue;
7881 }
7882 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07007883
Eric Laurent81784c32012-11-19 14:55:58 -08007884 lockEffectChains_l(effectChains);
7885 }
7886
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007887 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07007888
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007889 size_t size = effectChains.size();
7890 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07007891 // thread mutex is not locked, but effect chain is locked
7892 effectChains[i]->process_l();
7893 }
7894
Glenn Kasten735f45f2014-08-18 15:51:59 -07007895 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007896 if (mFastCapture != 0) {
7897 FastCaptureStateQueue *sq = mFastCapture->sq();
7898 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07007899 bool didModify = false;
7900 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007901 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
7902 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
7903 if (state->mCommand == FastCaptureState::COLD_IDLE) {
7904 int32_t old = android_atomic_inc(&mFastCaptureFutex);
7905 if (old == -1) {
7906 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
7907 }
7908 }
7909 state->mCommand = FastCaptureState::READ_WRITE;
7910#if 0 // FIXME
7911 mFastCaptureDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08007912 FastThreadDumpState::kSamplingNforLowRamDevice :
7913 FastThreadDumpState::kSamplingN);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007914#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07007915 didModify = true;
7916 }
7917 audio_track_cblk_t *cblkOld = state->mCblk;
7918 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
7919 if (cblkNew != cblkOld) {
7920 state->mCblk = cblkNew;
7921 // block until acked if removing a fast track
7922 if (cblkOld != NULL) {
7923 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
7924 }
7925 didModify = true;
7926 }
jiabin01c8f562018-07-19 17:47:28 -07007927 AudioBufferProvider* abp = (fastTrack != 0 && fastTrack->isPatchTrack()) ?
7928 reinterpret_cast<AudioBufferProvider*>(fastTrack.get()) : nullptr;
7929 if (state->mFastPatchRecordBufferProvider != abp) {
7930 state->mFastPatchRecordBufferProvider = abp;
7931 state->mFastPatchRecordFormat = fastTrack == 0 ?
7932 AUDIO_FORMAT_INVALID : fastTrack->format();
7933 didModify = true;
7934 }
Eric Laurent33403f02020-05-29 18:35:06 -07007935 if (state->mSilenceCapture != silenceFastCapture) {
7936 state->mSilenceCapture = silenceFastCapture;
7937 didModify = true;
7938 }
Glenn Kasten735f45f2014-08-18 15:51:59 -07007939 sq->end(didModify);
7940 if (didModify) {
7941 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007942#if 0
7943 if (kUseFastCapture == FastCapture_Dynamic) {
7944 mNormalSource = mPipeSource;
7945 }
7946#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007947 }
7948 }
7949
Glenn Kasten735f45f2014-08-18 15:51:59 -07007950 // now run the fast track destructor with thread mutex unlocked
7951 fastTrackToRemove.clear();
7952
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007953 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
7954 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
7955 // slow, then this RecordThread will overrun by not calling HAL read often enough.
7956 // If destination is non-contiguous, first read past the nominal end of buffer, then
7957 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07007958
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007959 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007960 ssize_t framesRead;
Andy Hung446f4df2019-02-21 12:26:41 -08007961 const int64_t lastIoBeginNs = systemTime(); // start IO timing
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007962
7963 // If an NBAIO source is present, use it to read the normal capture's data
7964 if (mPipeSource != 0) {
Andy Hung156317a2018-08-02 11:49:29 -07007965 size_t framesToRead = min(mRsmpInFramesOA - rear, mRsmpInFramesP2 / 2);
Andy Hungd5b638f2018-04-30 13:56:10 -07007966
7967 // The audio fifo read() returns OVERRUN on overflow, and advances the read pointer
7968 // to the full buffer point (clearing the overflow condition). Upon OVERRUN error,
7969 // we immediately retry the read() to get data and prevent another overflow.
7970 for (int retries = 0; retries <= 2; ++retries) {
7971 ALOGW_IF(retries > 0, "overrun on read from pipe, retry #%d", retries);
7972 framesRead = mPipeSource->read((uint8_t*)mRsmpInBuffer + rear * mFrameSize,
7973 framesToRead);
7974 if (framesRead != OVERRUN) break;
7975 }
7976
Andy Hung7a3dc6b2018-05-01 16:39:51 -07007977 const ssize_t availableToRead = mPipeSource->availableToRead();
7978 if (availableToRead >= 0) {
Robert Wu06db0a32021-08-10 19:05:34 +00007979 mMonopipePipeDepthStats.add(availableToRead);
Glenn Kastena2f59b32020-08-03 16:37:24 -07007980 // PipeSource is the primary clock. It is up to the AudioRecord client to keep up.
Andy Hung7a3dc6b2018-05-01 16:39:51 -07007981 LOG_ALWAYS_FATAL_IF((size_t)availableToRead > mPipeFramesP2,
7982 "more frames to read than fifo size, %zd > %zu",
7983 availableToRead, mPipeFramesP2);
7984 const size_t pipeFramesFree = mPipeFramesP2 - availableToRead;
7985 const size_t sleepFrames = min(pipeFramesFree, mRsmpInFramesP2) / 2;
7986 ALOGVV("mPipeFramesP2:%zu mRsmpInFramesP2:%zu sleepFrames:%zu availableToRead:%zd",
7987 mPipeFramesP2, mRsmpInFramesP2, sleepFrames, availableToRead);
Glenn Kasten1b291842016-07-18 14:55:21 -07007988 sleepUs = (sleepFrames * 1000000LL) / mSampleRate;
7989 }
7990 if (framesRead < 0) {
7991 status_t status = (status_t) framesRead;
7992 switch (status) {
7993 case OVERRUN:
7994 ALOGW("overrun on read from pipe");
7995 framesRead = 0;
7996 break;
7997 case NEGOTIATE:
7998 ALOGE("re-negotiation is needed");
7999 framesRead = -1; // Will cause an attempt to recover.
8000 break;
8001 default:
8002 ALOGE("unknown error %d on read from pipe", status);
8003 break;
8004 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008005 }
8006 // otherwise use the HAL / AudioStreamIn directly
8007 } else {
Glenn Kastenec6a7032016-03-14 07:40:23 -07008008 ATRACE_BEGIN("read");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008009 size_t bytesRead;
Mikhail Naganov2534b382019-09-25 13:05:02 -07008010 status_t result = mSource->read(
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008011 (uint8_t*)mRsmpInBuffer + rear * mFrameSize, mBufferSize, &bytesRead);
Glenn Kastenec6a7032016-03-14 07:40:23 -07008012 ATRACE_END();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008013 if (result < 0) {
8014 framesRead = result;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008015 } else {
8016 framesRead = bytesRead / mFrameSize;
8017 }
8018 }
8019
Andy Hung446f4df2019-02-21 12:26:41 -08008020 const int64_t lastIoEndNs = systemTime(); // end IO timing
8021
Andy Hung3f0c9022016-01-15 17:49:46 -08008022 // Update server timestamp with server stats
8023 // systemTime() is optional if the hardware supports timestamps.
Andy Hung743f6402020-06-03 13:17:04 -07008024 if (framesRead >= 0) {
8025 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += framesRead;
8026 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = lastIoEndNs;
8027 }
Andy Hung3f0c9022016-01-15 17:49:46 -08008028
8029 // Update server timestamp with kernel stats
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008030 if (mPipeSource.get() == nullptr /* don't obtain for FastCapture, could block */) {
Andy Hung3f0c9022016-01-15 17:49:46 -08008031 int64_t position, time;
Andy Hung2e2c0bb2018-06-11 19:13:11 -07008032 if (mStandby) {
Dean Wheatley12473e92021-03-18 23:00:55 +11008033 mTimestampVerifier.discontinuity(audio_is_linear_pcm(mFormat) ?
8034 mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS :
8035 mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Mikhail Naganov2534b382019-09-25 13:05:02 -07008036 } else if (mSource->getCapturePosition(&position, &time) == NO_ERROR
Andy Hungc8fddf32018-08-08 18:32:37 -07008037 && time > mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]) {
8038
8039 mTimestampVerifier.add(position, time, mSampleRate);
8040
8041 // Correct timestamps
8042 if (isTimestampCorrectionEnabled()) {
Dean Wheatley56a583e2020-05-08 15:12:17 +10008043 ALOGVV("TS_BEFORE: %d %lld %lld",
Andy Hungc8fddf32018-08-08 18:32:37 -07008044 id(), (long long)time, (long long)position);
8045 auto correctedTimestamp = mTimestampVerifier.getLastCorrectedTimestamp();
8046 position = correctedTimestamp.mFrames;
8047 time = correctedTimestamp.mTimeNs;
Dean Wheatley56a583e2020-05-08 15:12:17 +10008048 ALOGVV("TS_AFTER: %d %lld %lld",
Andy Hungc8fddf32018-08-08 18:32:37 -07008049 id(), (long long)time, (long long)position);
8050 }
8051
Andy Hung3f0c9022016-01-15 17:49:46 -08008052 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = position;
8053 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] = time;
8054 // Note: In general record buffers should tend to be empty in
8055 // a properly running pipeline.
8056 //
8057 // Also, it is not advantageous to call get_presentation_position during the read
8058 // as the read obtains a lock, preventing the timestamp call from executing.
Andy Hung2e2c0bb2018-06-11 19:13:11 -07008059 } else {
8060 mTimestampVerifier.error();
Andy Hung3f0c9022016-01-15 17:49:46 -08008061 }
8062 }
Andy Hunge6c37112019-02-26 17:38:10 -08008063
8064 // From the timestamp, input read latency is negative output write latency.
8065 const audio_input_flags_t flags = mInput != NULL ? mInput->flags : AUDIO_INPUT_FLAG_NONE;
8066 const double latencyMs = RecordTrack::checkServerLatencySupported(mFormat, flags)
8067 ? - mTimestamp.getOutputServerLatencyMs(mSampleRate) : 0.;
8068 if (latencyMs != 0.) { // note 0. means timestamp is empty.
8069 mLatencyMs.add(latencyMs);
8070 }
8071
Andy Hung3f0c9022016-01-15 17:49:46 -08008072 // Use this to track timestamp information
8073 // ALOGD("%s", mTimestamp.toString().c_str());
8074
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008075 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07008076 ALOGE("read failed: framesRead=%zd", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008077 // Force input into standby so that it tries to recover at next read attempt
8078 inputStandBy();
8079 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008080 }
8081 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008082 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008083 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008084 ALOG_ASSERT(framesRead > 0);
Andy Hung6427e442018-08-09 12:51:02 -07008085 mFramesRead += framesRead;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008086
Andy Hung8946a282018-04-19 20:04:56 -07008087#ifdef TEE_SINK
8088 (void)mTee.write((uint8_t*)mRsmpInBuffer + rear * mFrameSize, framesRead);
8089#endif
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008090 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008091 {
8092 size_t part1 = mRsmpInFramesP2 - rear;
8093 if ((size_t) framesRead > part1) {
Andy Hung57446612015-04-19 23:56:46 -07008094 memcpy(mRsmpInBuffer, (uint8_t*)mRsmpInBuffer + mRsmpInFramesP2 * mFrameSize,
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008095 (framesRead - part1) * mFrameSize);
8096 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008097 }
Dean Wheatleyfd56e812020-11-06 22:32:21 +11008098 mRsmpInRear = audio_utils::safe_add_overflow(mRsmpInRear, (int32_t)framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008099
8100 size = activeTracks.size();
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008101
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008102 // loop over each active track
8103 for (size_t i = 0; i < size; i++) {
8104 activeTrack = activeTracks[i];
8105
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008106 // skip fast tracks, as those are handled directly by FastCapture
8107 if (activeTrack->isFastTrack()) {
8108 continue;
8109 }
8110
Andy Hung73c02e42015-03-29 01:13:58 -07008111 // TODO: This code probably should be moved to RecordTrack.
Andy Hung97a893e2015-03-29 01:03:07 -07008112 // TODO: Update the activeTrack buffer converter in case of reconfigure.
8113
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008114 enum {
8115 OVERRUN_UNKNOWN,
8116 OVERRUN_TRUE,
8117 OVERRUN_FALSE
8118 } overrun = OVERRUN_UNKNOWN;
8119
8120 // loop over getNextBuffer to handle circular sink
8121 for (;;) {
8122
8123 activeTrack->mSink.frameCount = ~0;
8124 status_t status = activeTrack->getNextBuffer(&activeTrack->mSink);
8125 size_t framesOut = activeTrack->mSink.frameCount;
8126 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
8127
Andy Hung73c02e42015-03-29 01:13:58 -07008128 // check available frames and handle overrun conditions
8129 // if the record track isn't draining fast enough.
8130 bool hasOverrun;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008131 size_t framesIn;
Andy Hung73c02e42015-03-29 01:13:58 -07008132 activeTrack->mResamplerBufferProvider->sync(&framesIn, &hasOverrun);
8133 if (hasOverrun) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008134 overrun = OVERRUN_TRUE;
8135 }
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08008136 if (framesOut == 0 || framesIn == 0) {
8137 break;
8138 }
8139
Andy Hung6770c6f2015-04-07 13:43:36 -07008140 // Don't allow framesOut to be larger than what is possible with resampling
8141 // from framesIn.
8142 // This isn't strictly necessary but helps limit buffer resizing in
8143 // RecordBufferConverter. TODO: remove when no longer needed.
8144 framesOut = min(framesOut,
8145 destinationFramesPossible(
8146 framesIn, mSampleRate, activeTrack->mSampleRate));
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008147
8148 if (activeTrack->isDirect()) {
Daniel Van Veen9e2376e2018-09-27 14:37:58 +10008149 // No RecordBufferConverter used for direct streams. Pass
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008150 // straight from RecordThread buffer to RecordTrack buffer.
8151 AudioBufferProvider::Buffer buffer;
8152 buffer.frameCount = framesOut;
8153 status_t status = activeTrack->mResamplerBufferProvider->getNextBuffer(&buffer);
8154 if (status == OK && buffer.frameCount != 0) {
8155 ALOGV_IF(buffer.frameCount != framesOut,
8156 "%s() read less than expected (%zu vs %zu)",
8157 __func__, buffer.frameCount, framesOut);
8158 framesOut = buffer.frameCount;
Daniel Van Veen9e2376e2018-09-27 14:37:58 +10008159 memcpy(activeTrack->mSink.raw, buffer.raw, buffer.frameCount * mFrameSize);
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008160 activeTrack->mResamplerBufferProvider->releaseBuffer(&buffer);
8161 } else {
8162 framesOut = 0;
8163 ALOGE("%s() cannot fill request, status: %d, frameCount: %zu",
8164 __func__, status, buffer.frameCount);
8165 }
8166 } else {
8167 // process frames from the RecordThread buffer provider to the RecordTrack
8168 // buffer
8169 framesOut = activeTrack->mRecordBufferConverter->convert(
8170 activeTrack->mSink.raw,
8171 activeTrack->mResamplerBufferProvider,
8172 framesOut);
8173 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008174
8175 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
8176 overrun = OVERRUN_FALSE;
8177 }
8178
8179 if (activeTrack->mFramesToDrop == 0) {
8180 if (framesOut > 0) {
8181 activeTrack->mSink.frameCount = framesOut;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008182 // Sanitize before releasing if the track has no access to the source data
8183 // An idle UID receives silence from non virtual devices until active
8184 if (activeTrack->isSilenced()) {
Jean-Michel Trividdf87ef2019-08-20 15:42:04 -07008185 memset(activeTrack->mSink.raw, 0, framesOut * activeTrack->frameSize());
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008186 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008187 activeTrack->releaseBuffer(&activeTrack->mSink);
8188 }
8189 } else {
8190 // FIXME could do a partial drop of framesOut
8191 if (activeTrack->mFramesToDrop > 0) {
Mikhail Naganov6d91ba52019-03-26 14:35:28 -07008192 activeTrack->mFramesToDrop -= (ssize_t)framesOut;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008193 if (activeTrack->mFramesToDrop <= 0) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08008194 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008195 }
8196 } else {
8197 activeTrack->mFramesToDrop += framesOut;
8198 if (activeTrack->mFramesToDrop >= 0 || activeTrack->mSyncStartEvent == 0 ||
8199 activeTrack->mSyncStartEvent->isCancelled()) {
8200 ALOGW("Synced record %s, session %d, trigger session %d",
8201 (activeTrack->mFramesToDrop >= 0) ? "timed out" : "cancelled",
8202 activeTrack->sessionId(),
8203 (activeTrack->mSyncStartEvent != 0) ?
Glenn Kastend848eb42016-03-08 13:42:11 -08008204 activeTrack->mSyncStartEvent->triggerSession() :
8205 AUDIO_SESSION_NONE);
Glenn Kasten25f4aa82014-02-07 10:50:43 -08008206 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008207 }
8208 }
8209 }
8210
8211 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008212 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008213 }
8214 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008215
8216 switch (overrun) {
8217 case OVERRUN_TRUE:
8218 // client isn't retrieving buffers fast enough
8219 if (!activeTrack->setOverflow()) {
8220 nsecs_t now = systemTime();
8221 // FIXME should lastWarning per track?
8222 if ((now - lastWarning) > kWarningThrottleNs) {
8223 ALOGW("RecordThread: buffer overflow");
8224 lastWarning = now;
8225 }
8226 }
8227 break;
8228 case OVERRUN_FALSE:
8229 activeTrack->clearOverflow();
8230 break;
8231 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008232 break;
8233 }
8234
Andy Hung3f0c9022016-01-15 17:49:46 -08008235 // update frame information and push timestamp out
8236 activeTrack->updateTrackFrameInfo(
Andy Hung6ae58432016-02-16 18:32:24 -08008237 activeTrack->mServerProxy->framesReleased(),
Andy Hung3f0c9022016-01-15 17:49:46 -08008238 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER],
8239 mSampleRate, mTimestamp);
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008240 }
8241
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008242unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08008243 // enable changes in effect chain
8244 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07008245 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurentcccbc762019-04-05 14:20:05 -07008246 if (audio_has_proportional_frames(mFormat)
8247 && loopCount == lastLoopCountRead + 1) {
8248 const int64_t readPeriodNs = lastIoEndNs - mLastIoEndNs;
8249 const double jitterMs =
8250 TimestampVerifier<int64_t, int64_t>::computeJitterMs(
8251 {framesRead, readPeriodNs},
8252 {0, 0} /* lastTimestamp */, mSampleRate);
8253 const double processMs = (lastIoBeginNs - mLastIoEndNs) * 1e-6;
8254
8255 Mutex::Autolock _l(mLock);
8256 mIoJitterMs.add(jitterMs);
8257 mProcessTimeMs.add(processMs);
8258 }
8259 // update timing info.
8260 mLastIoBeginNs = lastIoBeginNs;
8261 mLastIoEndNs = lastIoEndNs;
8262 lastLoopCountRead = loopCount;
Eric Laurent81784c32012-11-19 14:55:58 -08008263 }
8264
Glenn Kasten93e471f2013-08-19 08:40:07 -07008265 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08008266
8267 {
8268 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07008269 for (size_t i = 0; i < mTracks.size(); i++) {
8270 sp<RecordTrack> track = mTracks[i];
8271 track->invalidate();
8272 }
Glenn Kasten2b806402013-11-20 16:37:38 -08008273 mActiveTracks.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08008274 mStartStopCond.broadcast();
8275 }
8276
8277 releaseWakeLock();
8278
8279 ALOGV("RecordThread %p exiting", this);
8280 return false;
8281}
8282
Glenn Kasten93e471f2013-08-19 08:40:07 -07008283void AudioFlinger::RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08008284{
8285 if (!mStandby) {
8286 inputStandBy();
Andy Hungcf10d742020-04-28 15:38:24 -07008287 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07008288 mThreadSnapshot.onEnd();
Eric Laurent81784c32012-11-19 14:55:58 -08008289 mStandby = true;
8290 }
8291}
8292
8293void AudioFlinger::RecordThread::inputStandBy()
8294{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008295 // Idle the fast capture if it's currently running
8296 if (mFastCapture != 0) {
8297 FastCaptureStateQueue *sq = mFastCapture->sq();
8298 FastCaptureState *state = sq->begin();
8299 if (!(state->mCommand & FastCaptureState::IDLE)) {
8300 state->mCommand = FastCaptureState::COLD_IDLE;
8301 state->mColdFutexAddr = &mFastCaptureFutex;
8302 state->mColdGen++;
8303 mFastCaptureFutex = 0;
8304 sq->end();
8305 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
8306 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
8307#if 0
8308 if (kUseFastCapture == FastCapture_Dynamic) {
8309 // FIXME
8310 }
8311#endif
8312#ifdef AUDIO_WATCHDOG
8313 // FIXME
8314#endif
8315 } else {
8316 sq->end(false /*didModify*/);
8317 }
8318 }
Mikhail Naganov2534b382019-09-25 13:05:02 -07008319 status_t result = mSource->standby();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008320 ALOGE_IF(result != OK, "Error when putting input stream into standby: %d", result);
Andy Hungad6d52d2016-07-18 13:42:03 -07008321
8322 // If going into standby, flush the pipe source.
8323 if (mPipeSource.get() != nullptr) {
8324 const ssize_t flushed = mPipeSource->flush();
8325 if (flushed > 0) {
8326 ALOGV("Input standby flushed PipeSource %zd frames", flushed);
8327 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += flushed;
8328 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
8329 }
8330 }
Eric Laurent81784c32012-11-19 14:55:58 -08008331}
8332
Glenn Kasten05997e22014-03-13 15:08:33 -07008333// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastene198c362013-08-13 09:13:36 -07008334sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
Eric Laurent81784c32012-11-19 14:55:58 -08008335 const sp<AudioFlinger::Client>& client,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07008336 const audio_attributes_t& attr,
Eric Laurentf14db3c2017-12-08 14:20:36 -08008337 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08008338 audio_format_t format,
8339 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08008340 size_t *pFrameCount,
Glenn Kastend848eb42016-03-08 13:42:11 -08008341 audio_session_t sessionId,
Eric Laurentf14db3c2017-12-08 14:20:36 -08008342 size_t *pNotificationFrameCount,
Eric Laurent09f1ed22019-04-24 17:45:17 -07008343 pid_t creatorPid,
Svet Ganov33761132021-05-13 22:51:08 +00008344 const AttributionSourceState& attributionSource,
Eric Laurent05067782016-06-01 18:27:28 -07008345 audio_input_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08008346 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08008347 status_t *status,
Eric Laurentec376dc2021-04-08 20:41:22 +02008348 audio_port_handle_t portId,
8349 int32_t maxSharedAudioHistoryMs)
Eric Laurent81784c32012-11-19 14:55:58 -08008350{
Glenn Kasten74935e42013-12-19 08:56:45 -08008351 size_t frameCount = *pFrameCount;
Eric Laurentf14db3c2017-12-08 14:20:36 -08008352 size_t notificationFrameCount = *pNotificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08008353 sp<RecordTrack> track;
8354 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07008355 audio_input_flags_t inputFlags = mInput->flags;
Eric Laurentf14db3c2017-12-08 14:20:36 -08008356 audio_input_flags_t requestedFlags = *flags;
8357 uint32_t sampleRate;
8358
8359 lStatus = initCheck();
8360 if (lStatus != NO_ERROR) {
8361 ALOGE("createRecordTrack_l() audio driver not initialized");
8362 goto Exit;
8363 }
8364
Mikhail Naganovce9f2652018-07-16 11:09:24 -07008365 if (!audio_is_linear_pcm(mFormat) && (*flags & AUDIO_INPUT_FLAG_DIRECT) == 0) {
8366 ALOGE("createRecordTrack_l() on an encoded stream requires AUDIO_INPUT_FLAG_DIRECT");
8367 lStatus = BAD_VALUE;
8368 goto Exit;
8369 }
8370
Eric Laurentec376dc2021-04-08 20:41:22 +02008371 if (maxSharedAudioHistoryMs != 0) {
Eric Laurent063c4ed2022-09-24 00:01:57 +00008372 if (!captureHotwordAllowed(attributionSource)) {
Eric Laurentec376dc2021-04-08 20:41:22 +02008373 lStatus = PERMISSION_DENIED;
8374 goto Exit;
8375 }
Eric Laurentec376dc2021-04-08 20:41:22 +02008376 if (maxSharedAudioHistoryMs < 0
8377 || maxSharedAudioHistoryMs > AudioFlinger::kMaxSharedAudioHistoryMs) {
8378 lStatus = BAD_VALUE;
8379 goto Exit;
8380 }
8381 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08008382 if (*pSampleRate == 0) {
8383 *pSampleRate = mSampleRate;
8384 }
8385 sampleRate = *pSampleRate;
Eric Laurent05067782016-06-01 18:27:28 -07008386
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008387 // special case for FAST flag considered OK if fast capture is present and access to
8388 // audio history is not required
8389 if (hasFastCapture() && mMaxSharedAudioHistoryMs == 0) {
Eric Laurent05067782016-06-01 18:27:28 -07008390 inputFlags = (audio_input_flags_t)(inputFlags | AUDIO_INPUT_FLAG_FAST);
8391 }
8392
Eric Laurentf14db3c2017-12-08 14:20:36 -08008393 // Check if requested flags are compatible with input stream flags
Eric Laurent05067782016-06-01 18:27:28 -07008394 if ((*flags & inputFlags) != *flags) {
8395 ALOGW("createRecordTrack_l(): mismatch between requested flags (%08x) and"
8396 " input flags (%08x)",
8397 *flags, inputFlags);
8398 *flags = (audio_input_flags_t)(*flags & inputFlags);
8399 }
Eric Laurent81784c32012-11-19 14:55:58 -08008400
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008401 // client expresses a preference for FAST and no access to audio history,
8402 // but we get the final say
8403 if (*flags & AUDIO_INPUT_FLAG_FAST && maxSharedAudioHistoryMs == 0) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07008404 if (
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07008405 // we formerly checked for a callback handler (non-0 tid),
8406 // but that is no longer required for TRANSFER_OBTAIN mode
jiabinb00edc32021-08-16 16:27:54 +00008407 // No need to match hardware format, format conversion will be done in client side.
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07008408 //
Phil Burk7ed66a12019-04-18 13:20:30 -07008409 // Frame count is not specified (0), or is less than or equal the pipe depth.
8410 // It is OK to provide a higher capacity than requested.
8411 // We will force it to mPipeFramesP2 below.
8412 (frameCount <= mPipeFramesP2) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07008413 // PCM data
8414 audio_is_linear_pcm(format) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08008415 // hardware channel mask
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008416 (channelMask == mChannelMask) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08008417 // hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07008418 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07008419 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008420 hasFastCapture() &&
8421 // there are sufficient fast track slots available
8422 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07008423 ) {
Eric Laurent4c415062016-06-17 16:14:16 -07008424 // check compatibility with audio effects.
8425 Mutex::Autolock _l(mLock);
8426 // Do not accept FAST flag if the session has software effects
8427 sp<EffectChain> chain = getEffectChain_l(sessionId);
8428 if (chain != 0) {
Andy Hungd3bb0ad2016-10-11 17:16:43 -07008429 audio_input_flags_t old = *flags;
8430 chain->checkInputFlagCompatibility(flags);
8431 if (old != *flags) {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008432 ALOGV("%p AUDIO_INPUT_FLAGS denied by effect old=%#x new=%#x",
8433 this, (int)old, (int)*flags);
Eric Laurent4c415062016-06-17 16:14:16 -07008434 }
8435 }
Eric Laurent122f7e72016-06-29 11:53:29 -07008436 ALOGV_IF((*flags & AUDIO_INPUT_FLAG_FAST) != 0,
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008437 "%p AUDIO_INPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
8438 this, frameCount, mFrameCount);
Glenn Kasten90e58b12013-07-31 16:16:02 -07008439 } else {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008440 ALOGV("%p AUDIO_INPUT_FLAG_FAST denied: frameCount=%zu mFrameCount=%zu mPipeFramesP2=%zu "
8441 "format=%#x isLinear=%d mFormat=%#x channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008442 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008443 this, frameCount, mFrameCount, mPipeFramesP2,
8444 format, audio_is_linear_pcm(format), mFormat, channelMask, sampleRate, mSampleRate,
Glenn Kasten74105912014-07-03 12:28:53 -07008445 hasFastCapture(), tid, mFastTrackAvail);
Eric Laurent05067782016-06-01 18:27:28 -07008446 *flags = (audio_input_flags_t)(*flags & ~AUDIO_INPUT_FLAG_FAST);
Glenn Kasten74105912014-07-03 12:28:53 -07008447 }
8448 }
8449
Eric Laurentf14db3c2017-12-08 14:20:36 -08008450 // If FAST or RAW flags were corrected, ask caller to request new input from audio policy
8451 if ((*flags & AUDIO_INPUT_FLAG_FAST) !=
8452 (requestedFlags & AUDIO_INPUT_FLAG_FAST)) {
8453 *flags = (audio_input_flags_t) (*flags & ~(AUDIO_INPUT_FLAG_FAST | AUDIO_INPUT_FLAG_RAW));
8454 lStatus = BAD_TYPE;
8455 goto Exit;
8456 }
8457
Glenn Kasten74105912014-07-03 12:28:53 -07008458 // compute track buffer size in frames, and suggest the notification frame count
Eric Laurent05067782016-06-01 18:27:28 -07008459 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten74105912014-07-03 12:28:53 -07008460 // fast track: frame count is exactly the pipe depth
8461 frameCount = mPipeFramesP2;
8462 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
Eric Laurentf14db3c2017-12-08 14:20:36 -08008463 notificationFrameCount = mFrameCount;
Glenn Kasten74105912014-07-03 12:28:53 -07008464 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07008465 // not fast track: max notification period is resampled equivalent of one HAL buffer time
8466 // or 20 ms if there is a fast capture
8467 // TODO This could be a roundupRatio inline, and const
8468 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
8469 * sampleRate + mSampleRate - 1) / mSampleRate;
8470 // minimum number of notification periods is at least kMinNotifications,
8471 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
8472 static const size_t kMinNotifications = 3;
8473 static const uint32_t kMinMs = 30;
8474 // TODO This could be a roundupRatio inline
8475 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
8476 // TODO This could be a roundupRatio inline
8477 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
8478 maxNotificationFrames;
8479 const size_t minFrameCount = maxNotificationFrames *
8480 max(kMinNotifications, minNotificationsByMs);
8481 frameCount = max(frameCount, minFrameCount);
Eric Laurentf14db3c2017-12-08 14:20:36 -08008482 if (notificationFrameCount == 0 || notificationFrameCount > maxNotificationFrames) {
8483 notificationFrameCount = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07008484 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07008485 }
Glenn Kasten74935e42013-12-19 08:56:45 -08008486 *pFrameCount = frameCount;
Eric Laurentf14db3c2017-12-08 14:20:36 -08008487 *pNotificationFrameCount = notificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08008488
8489 { // scope for mLock
8490 Mutex::Autolock _l(mLock);
Eric Laurent2407ce32021-04-26 14:56:03 +02008491 int32_t startFrames = -1;
Eric Laurentec376dc2021-04-08 20:41:22 +02008492 if (!mSharedAudioPackageName.empty()
Eric Laurent063c4ed2022-09-24 00:01:57 +00008493 && mSharedAudioPackageName == attributionSource.packageName
Eric Laurentec376dc2021-04-08 20:41:22 +02008494 && mSharedAudioSessionId == sessionId
Eric Laurent063c4ed2022-09-24 00:01:57 +00008495 && captureHotwordAllowed(attributionSource)) {
Eric Laurent2407ce32021-04-26 14:56:03 +02008496 startFrames = mSharedAudioStartFrames;
Eric Laurentec376dc2021-04-08 20:41:22 +02008497 }
Eric Laurent81784c32012-11-19 14:55:58 -08008498
Kevin Rocard1f564ac2018-03-29 13:53:10 -07008499 track = new RecordTrack(this, client, attr, sampleRate,
Andy Hung8fe68032017-06-05 16:17:51 -07008500 format, channelMask, frameCount,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07008501 nullptr /* buffer */, (size_t)0 /* bufferSize */, sessionId, creatorPid,
Eric Laurent063c4ed2022-09-24 00:01:57 +00008502 attributionSource, *flags, TrackBase::TYPE_DEFAULT, portId,
Svet Ganov33761132021-05-13 22:51:08 +00008503 startFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08008504
Glenn Kasten03003332013-08-06 15:40:54 -07008505 lStatus = track->initCheck();
8506 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07008507 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08008508 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08008509 goto Exit;
8510 }
8511 mTracks.add(track);
8512
Eric Laurent05067782016-06-01 18:27:28 -07008513 if ((*flags & AUDIO_INPUT_FLAG_FAST) && (tid != -1)) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07008514 pid_t callingPid = IPCThreadState::self()->getCallingPid();
8515 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
8516 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07008517 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Glenn Kasten90e58b12013-07-31 16:16:02 -07008518 }
Eric Laurentec376dc2021-04-08 20:41:22 +02008519
8520 if (maxSharedAudioHistoryMs != 0) {
8521 sendResizeBufferConfigEvent_l(maxSharedAudioHistoryMs);
8522 }
Eric Laurent81784c32012-11-19 14:55:58 -08008523 }
Glenn Kasten05997e22014-03-13 15:08:33 -07008524
Eric Laurent81784c32012-11-19 14:55:58 -08008525 lStatus = NO_ERROR;
8526
8527Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07008528 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08008529 return track;
8530}
8531
8532status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
8533 AudioSystem::sync_event_t event,
Glenn Kastend848eb42016-03-08 13:42:11 -08008534 audio_session_t triggerSession)
Eric Laurent81784c32012-11-19 14:55:58 -08008535{
8536 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
8537 sp<ThreadBase> strongMe = this;
8538 status_t status = NO_ERROR;
8539
8540 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08008541 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08008542 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008543 recordTrack->mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
Eric Laurent81784c32012-11-19 14:55:58 -08008544 triggerSession,
8545 recordTrack->sessionId(),
8546 syncStartEventCallback,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008547 recordTrack);
Eric Laurent81784c32012-11-19 14:55:58 -08008548 // Sync event can be cancelled by the trigger session if the track is not in a
8549 // compatible state in which case we start record immediately
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008550 if (recordTrack->mSyncStartEvent->isCancelled()) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08008551 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08008552 } else {
8553 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
Ivan Lozano1b35dd62017-12-06 16:55:10 -08008554 recordTrack->mFramesToDrop = -(ssize_t)
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08008555 ((AudioSystem::kSyncRecordStartTimeOutMs * recordTrack->mSampleRate) / 1000);
Eric Laurent81784c32012-11-19 14:55:58 -08008556 }
8557 }
8558
8559 {
Glenn Kasten47c20702013-08-13 15:37:35 -07008560 // This section is a rendezvous between binder thread executing start() and RecordThread
Eric Laurent81784c32012-11-19 14:55:58 -08008561 AutoMutex lock(mLock);
Andy Hungce685402018-10-05 17:23:27 -07008562 if (recordTrack->isInvalid()) {
8563 recordTrack->clearSyncStartEvent();
Eric Laurentd52a28c2020-08-21 17:10:39 -07008564 ALOGW("%s track %d: invalidated before startInput", __func__, recordTrack->portId());
8565 return DEAD_OBJECT;
Andy Hungce685402018-10-05 17:23:27 -07008566 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008567 if (mActiveTracks.indexOf(recordTrack) >= 0) {
8568 if (recordTrack->mState == TrackBase::PAUSING) {
Andy Hungce685402018-10-05 17:23:27 -07008569 // We haven't stopped yet (moved to PAUSED and not in mActiveTracks)
8570 // so no need to startInput().
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008571 ALOGV("active record track PAUSING -> ACTIVE");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008572 recordTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008573 } else {
Andy Hung959b5b82021-09-24 10:46:20 -07008574 ALOGV("active record track state %d", (int)recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08008575 }
8576 return status;
8577 }
8578
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08008579 // TODO consider other ways of handling this, such as changing the state to :STARTING and
8580 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
8581 // or using a separate command thread
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008582 recordTrack->mState = TrackBase::STARTING_1;
Glenn Kasten2b806402013-11-20 16:37:38 -08008583 mActiveTracks.add(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07008584 status_t status = NO_ERROR;
8585 if (recordTrack->isExternalTrack()) {
8586 mLock.unlock();
Eric Laurent4eb58f12018-12-07 16:41:02 -08008587 status = AudioSystem::startInput(recordTrack->portId());
Eric Laurent83b88082014-06-20 18:31:16 -07008588 mLock.lock();
Andy Hungce685402018-10-05 17:23:27 -07008589 if (recordTrack->isInvalid()) {
8590 recordTrack->clearSyncStartEvent();
8591 if (status == NO_ERROR && recordTrack->mState == TrackBase::STARTING_1) {
8592 recordTrack->mState = TrackBase::STARTING_2;
8593 // STARTING_2 forces destroy to call stopInput.
8594 }
Eric Laurentd52a28c2020-08-21 17:10:39 -07008595 ALOGW("%s track %d: invalidated after startInput", __func__, recordTrack->portId());
8596 return DEAD_OBJECT;
Andy Hungce685402018-10-05 17:23:27 -07008597 }
8598 if (recordTrack->mState != TrackBase::STARTING_1) {
8599 ALOGW("%s(%d): unsynchronized mState:%d change",
Andy Hung959b5b82021-09-24 10:46:20 -07008600 __func__, recordTrack->id(), (int)recordTrack->mState);
Andy Hungce685402018-10-05 17:23:27 -07008601 // Someone else has changed state, let them take over,
8602 // leave mState in the new state.
8603 recordTrack->clearSyncStartEvent();
8604 return INVALID_OPERATION;
8605 }
8606 // we're ok, but perhaps startInput has failed
Eric Laurent83b88082014-06-20 18:31:16 -07008607 if (status != NO_ERROR) {
Andy Hungce685402018-10-05 17:23:27 -07008608 ALOGW("%s(%d): startInput failed, status %d",
8609 __func__, recordTrack->id(), status);
8610 // We are in ActiveTracks if STARTING_1 and valid, so remove from ActiveTracks,
8611 // leave in STARTING_1, so destroy() will not call stopInput.
Eric Laurent83b88082014-06-20 18:31:16 -07008612 mActiveTracks.remove(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07008613 recordTrack->clearSyncStartEvent();
Eric Laurent83b88082014-06-20 18:31:16 -07008614 return status;
8615 }
Eric Laurent09f1ed22019-04-24 17:45:17 -07008616 sendIoConfigEvent_l(
8617 AUDIO_CLIENT_STARTED, recordTrack->creatorPid(), recordTrack->portId());
Eric Laurent81784c32012-11-19 14:55:58 -08008618 }
Andy Hungc2b11cb2020-04-22 09:04:01 -07008619
8620 recordTrack->logBeginInterval(patchSourcesToString(&mPatch)); // log to MediaMetrics
8621
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008622 // Catch up with current buffer indices if thread is already running.
8623 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
8624 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
8625 // see previously buffered data before it called start(), but with greater risk of overrun.
8626
Andy Hung73c02e42015-03-29 01:13:58 -07008627 recordTrack->mResamplerBufferProvider->reset();
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008628 if (!recordTrack->isDirect()) {
8629 // clear any converter state as new data will be discontinuous
8630 recordTrack->mRecordBufferConverter->reset();
8631 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008632 recordTrack->mState = TrackBase::STARTING_2;
Eric Laurent81784c32012-11-19 14:55:58 -08008633 // signal thread to start
Eric Laurent81784c32012-11-19 14:55:58 -08008634 mWaitWorkCV.broadcast();
Eric Laurent81784c32012-11-19 14:55:58 -08008635 return status;
8636 }
Eric Laurent81784c32012-11-19 14:55:58 -08008637}
8638
Eric Laurent81784c32012-11-19 14:55:58 -08008639void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
8640{
8641 sp<SyncEvent> strongEvent = event.promote();
8642
8643 if (strongEvent != 0) {
Eric Laurent8ea16e42014-02-20 16:26:11 -08008644 sp<RefBase> ptr = strongEvent->cookie().promote();
8645 if (ptr != 0) {
8646 RecordTrack *recordTrack = (RecordTrack *)ptr.get();
8647 recordTrack->handleSyncStartEvent(strongEvent);
8648 }
Eric Laurent81784c32012-11-19 14:55:58 -08008649 }
8650}
8651
Glenn Kastena8356f62013-07-25 14:37:52 -07008652bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08008653 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07008654 AutoMutex _l(mLock);
Andy Hungce685402018-10-05 17:23:27 -07008655 // if we're invalid, we can't be on the ActiveTracks.
Jean-Michel Trivi38f86712017-04-11 14:10:17 -07008656 if (mActiveTracks.indexOf(recordTrack) < 0 || recordTrack->mState == TrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08008657 return false;
8658 }
Glenn Kasten47c20702013-08-13 15:37:35 -07008659 // note that threadLoop may still be processing the track at this point [without lock]
Eric Laurent81784c32012-11-19 14:55:58 -08008660 recordTrack->mState = TrackBase::PAUSING;
Andy Hungce685402018-10-05 17:23:27 -07008661
Andy Hungabfab202019-03-07 19:45:54 -08008662 // NOTE: Waiting here is important to keep stop synchronous.
8663 // This is needed for proper patchRecord peer release.
Andy Hungce685402018-10-05 17:23:27 -07008664 while (recordTrack->mState == TrackBase::PAUSING && !recordTrack->isInvalid()) {
8665 mWaitWorkCV.broadcast(); // signal thread to stop
8666 mStartStopCond.wait(mLock);
Eric Laurent81784c32012-11-19 14:55:58 -08008667 }
Andy Hungce685402018-10-05 17:23:27 -07008668
8669 if (recordTrack->mState == TrackBase::PAUSED) { // successful stop
Eric Laurent81784c32012-11-19 14:55:58 -08008670 ALOGV("Record stopped OK");
8671 return true;
8672 }
Andy Hungce685402018-10-05 17:23:27 -07008673
8674 // don't handle anything - we've been invalidated or restarted and in a different state
8675 ALOGW_IF("%s(%d): unsynchronized stop, state: %d",
8676 __func__, recordTrack->id(), recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08008677 return false;
8678}
8679
Glenn Kasten0f11b512014-01-31 16:18:54 -08008680bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
Eric Laurent81784c32012-11-19 14:55:58 -08008681{
8682 return false;
8683}
8684
Glenn Kasten0f11b512014-01-31 16:18:54 -08008685status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08008686{
8687#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
8688 if (!isValidSyncEvent(event)) {
8689 return BAD_VALUE;
8690 }
8691
Glenn Kastend848eb42016-03-08 13:42:11 -08008692 audio_session_t eventSession = event->triggerSession();
Eric Laurent81784c32012-11-19 14:55:58 -08008693 status_t ret = NAME_NOT_FOUND;
8694
8695 Mutex::Autolock _l(mLock);
8696
8697 for (size_t i = 0; i < mTracks.size(); i++) {
8698 sp<RecordTrack> track = mTracks[i];
8699 if (eventSession == track->sessionId()) {
8700 (void) track->setSyncEvent(event);
8701 ret = NO_ERROR;
8702 }
8703 }
8704 return ret;
8705#else
8706 return BAD_VALUE;
8707#endif
8708}
8709
jiabin653cc0a2018-01-17 17:54:10 -08008710status_t AudioFlinger::RecordThread::getActiveMicrophones(
8711 std::vector<media::MicrophoneInfo>* activeMicrophones)
8712{
8713 ALOGV("RecordThread::getActiveMicrophones");
8714 AutoMutex _l(mLock);
Jasmine Chaeaa10e42021-05-11 10:11:14 +08008715 if (!isStreamInitialized()) {
Paul McLean8a661a32021-04-12 10:21:42 -06008716 return NO_INIT;
8717 }
jiabin9ff780e2018-03-19 18:19:52 -07008718 status_t status = mInput->stream->getActiveMicrophones(activeMicrophones);
8719 return status;
jiabin653cc0a2018-01-17 17:54:10 -08008720}
8721
Paul McLean12340082019-03-19 09:35:05 -06008722status_t AudioFlinger::RecordThread::setPreferredMicrophoneDirection(
8723 audio_microphone_direction_t direction)
Paul McLean03a6e6a2018-12-04 10:54:13 -07008724{
Paul McLean12340082019-03-19 09:35:05 -06008725 ALOGV("setPreferredMicrophoneDirection(%d)", direction);
Paul McLean03a6e6a2018-12-04 10:54:13 -07008726 AutoMutex _l(mLock);
Jasmine Chaeaa10e42021-05-11 10:11:14 +08008727 if (!isStreamInitialized()) {
Paul McLean8a661a32021-04-12 10:21:42 -06008728 return NO_INIT;
8729 }
Paul McLean12340082019-03-19 09:35:05 -06008730 return mInput->stream->setPreferredMicrophoneDirection(direction);
Paul McLean03a6e6a2018-12-04 10:54:13 -07008731}
8732
Paul McLean12340082019-03-19 09:35:05 -06008733status_t AudioFlinger::RecordThread::setPreferredMicrophoneFieldDimension(float zoom)
Paul McLean03a6e6a2018-12-04 10:54:13 -07008734{
Paul McLean12340082019-03-19 09:35:05 -06008735 ALOGV("setPreferredMicrophoneFieldDimension(%f)", zoom);
Paul McLean03a6e6a2018-12-04 10:54:13 -07008736 AutoMutex _l(mLock);
Jasmine Chaeaa10e42021-05-11 10:11:14 +08008737 if (!isStreamInitialized()) {
Paul McLean8a661a32021-04-12 10:21:42 -06008738 return NO_INIT;
8739 }
Paul McLean12340082019-03-19 09:35:05 -06008740 return mInput->stream->setPreferredMicrophoneFieldDimension(zoom);
Paul McLean03a6e6a2018-12-04 10:54:13 -07008741}
8742
Eric Laurentec376dc2021-04-08 20:41:22 +02008743status_t AudioFlinger::RecordThread::shareAudioHistory(
8744 const std::string& sharedAudioPackageName, audio_session_t sharedSessionId,
8745 int64_t sharedAudioStartMs) {
8746 AutoMutex _l(mLock);
8747 return shareAudioHistory_l(sharedAudioPackageName, sharedSessionId, sharedAudioStartMs);
8748}
8749
8750status_t AudioFlinger::RecordThread::shareAudioHistory_l(
8751 const std::string& sharedAudioPackageName, audio_session_t sharedSessionId,
8752 int64_t sharedAudioStartMs) {
Eric Laurent92d0a322021-07-16 15:32:33 +02008753
Eric Laurentec376dc2021-04-08 20:41:22 +02008754 if ((hasAudioSession_l(sharedSessionId) & ThreadBase::TRACK_SESSION) == 0) {
8755 return BAD_VALUE;
8756 }
Eric Laurent2407ce32021-04-26 14:56:03 +02008757
8758 if (sharedAudioStartMs < 0
8759 || sharedAudioStartMs > INT64_MAX / mSampleRate) {
Eric Laurentec376dc2021-04-08 20:41:22 +02008760 return BAD_VALUE;
8761 }
8762
Eric Laurent2407ce32021-04-26 14:56:03 +02008763 // Current implementation of the input resampling buffer wraps around indexes at 32 bit.
8764 // As we cannot detect more than one wraparound, only accept values up current write position
8765 // after one wraparound
8766 // We assume recent wraparounds on mRsmpInRear only given it is unlikely that the requesting
8767 // app waits several hours after the start time was computed.
Eric Laurent92d0a322021-07-16 15:32:33 +02008768 int64_t sharedAudioStartFrames = sharedAudioStartMs * mSampleRate / 1000;
Eric Laurent2407ce32021-04-26 14:56:03 +02008769 const int32_t sharedOffset = audio_utils::safe_sub_overflow(mRsmpInRear,
8770 (int32_t)sharedAudioStartFrames);
Eric Laurent92d0a322021-07-16 15:32:33 +02008771 // Bring the start frame position within the input buffer to match the documented
8772 // "best effort" behavior of the API.
8773 if (sharedOffset < 0) {
8774 sharedAudioStartFrames = mRsmpInRear;
8775 } else if (sharedOffset > mRsmpInFrames) {
8776 sharedAudioStartFrames =
8777 audio_utils::safe_sub_overflow(mRsmpInRear, (int32_t)mRsmpInFrames);
Eric Laurent2407ce32021-04-26 14:56:03 +02008778 }
8779
Eric Laurentec376dc2021-04-08 20:41:22 +02008780 mSharedAudioPackageName = sharedAudioPackageName;
8781 if (mSharedAudioPackageName.empty()) {
Eric Laurent92d0a322021-07-16 15:32:33 +02008782 resetAudioHistory_l();
Eric Laurentec376dc2021-04-08 20:41:22 +02008783 } else {
8784 mSharedAudioSessionId = sharedSessionId;
Eric Laurent2407ce32021-04-26 14:56:03 +02008785 mSharedAudioStartFrames = (int32_t)sharedAudioStartFrames;
Eric Laurentec376dc2021-04-08 20:41:22 +02008786 }
8787 return NO_ERROR;
8788}
8789
Eric Laurent92d0a322021-07-16 15:32:33 +02008790void AudioFlinger::RecordThread::resetAudioHistory_l() {
8791 mSharedAudioSessionId = AUDIO_SESSION_NONE;
8792 mSharedAudioStartFrames = -1;
8793 mSharedAudioPackageName = "";
8794}
8795
Kevin Rocard069c2712018-03-29 19:09:14 -07008796void AudioFlinger::RecordThread::updateMetadata_l()
8797{
Jasmine Chaeaa10e42021-05-11 10:11:14 +08008798 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
8799 return; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -07008800 }
8801 StreamInHalInterface::SinkMetadata metadata;
8802 for (const sp<RecordTrack> &track : mActiveTracks) {
Eric Laurentb9cc0ab2021-01-29 11:46:52 +01008803 // Do not forward PatchRecord metadata to audio HAL
8804 if (track->isPatchTrack()) {
8805 continue;
8806 }
Kevin Rocard069c2712018-03-29 19:09:14 -07008807 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurent94579172020-11-20 18:41:04 +01008808 record_track_metadata_v7_t trackMetadata;
8809 trackMetadata.base = {
Kevin Rocard069c2712018-03-29 19:09:14 -07008810 .source = track->attributes().source,
8811 .gain = 1, // capture tracks do not have volumes
Eric Laurent94579172020-11-20 18:41:04 +01008812 };
8813 trackMetadata.channel_mask = track->channelMask(),
8814 strncpy(trackMetadata.tags, track->attributes().tags, AUDIO_ATTRIBUTES_TAGS_MAX_SIZE);
8815
8816 metadata.tracks.push_back(trackMetadata);
Kevin Rocard069c2712018-03-29 19:09:14 -07008817 }
8818 mInput->stream->updateSinkMetadata(metadata);
8819}
8820
Eric Laurent81784c32012-11-19 14:55:58 -08008821// destroyTrack_l() must be called with ThreadBase::mLock held
8822void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
8823{
Eric Laurentbfb1b832013-01-07 09:53:42 -08008824 track->terminate();
8825 track->mState = TrackBase::STOPPED;
Eric Laurentec376dc2021-04-08 20:41:22 +02008826
Eric Laurent81784c32012-11-19 14:55:58 -08008827 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08008828 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08008829 removeTrack_l(track);
8830 }
8831}
8832
8833void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
8834{
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008835 String8 result;
8836 track->appendDump(result, false /* active */);
8837 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.string());
8838
Eric Laurent81784c32012-11-19 14:55:58 -08008839 mTracks.remove(track);
8840 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008841 if (track->isFastTrack()) {
8842 ALOG_ASSERT(!mFastTrackAvail);
8843 mFastTrackAvail = true;
8844 }
Eric Laurent81784c32012-11-19 14:55:58 -08008845}
8846
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07008847void AudioFlinger::RecordThread::dumpInternals_l(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08008848{
Mikhail Naganov913d06c2016-11-01 12:49:22 -07008849 AudioStreamIn *input = mInput;
8850 audio_input_flags_t flags = input != NULL ? input->flags : AUDIO_INPUT_FLAG_NONE;
8851 dprintf(fd, " AudioStreamIn: %p flags %#x (%s)\n",
Andy Hung9b181952019-02-25 14:53:36 -08008852 input, flags, toString(flags).c_str());
Andy Hung6427e442018-08-09 12:51:02 -07008853 dprintf(fd, " Frames read: %lld\n", (long long)mFramesRead);
Eric Tan39ec8d62018-07-24 09:49:29 -07008854 if (mActiveTracks.isEmpty()) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07008855 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08008856 }
Andy Hungbfa64962017-06-12 14:43:19 -07008857
8858 if (input != nullptr) {
8859 dprintf(fd, " Hal stream dump:\n");
8860 (void)input->stream->dump(fd);
8861 }
8862
Glenn Kasten6e6704c2014-07-03 10:20:00 -07008863 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008864 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Glenn Kasten17c9c992015-03-02 15:53:01 -08008865
Glenn Kasten2f90c512015-12-02 11:40:09 -08008866 // Make a non-atomic copy of fast capture dump state so it won't change underneath us
8867 // while we are dumping it. It may be inconsistent, but it won't mutate!
8868 // This is a large object so we place it on the heap.
8869 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
Eric Tan2942a4e2018-09-12 17:41:27 -07008870 const std::unique_ptr<FastCaptureDumpState> copy =
8871 std::make_unique<FastCaptureDumpState>(mFastCaptureDumpState);
Glenn Kasten2f90c512015-12-02 11:40:09 -08008872 copy->dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08008873}
8874
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07008875void AudioFlinger::RecordThread::dumpTracks_l(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08008876{
Eric Laurent81784c32012-11-19 14:55:58 -08008877 String8 result;
Marco Nelissenb2208842014-02-07 14:00:50 -08008878 size_t numtracks = mTracks.size();
8879 size_t numactive = mActiveTracks.size();
8880 size_t numactiveseen = 0;
Glenn Kastenc42e9b42016-03-21 11:35:03 -07008881 dprintf(fd, " %zu Tracks", numtracks);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008882 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08008883 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07008884 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008885 result.append(prefix);
Andy Hung000adb52018-06-01 15:43:26 -07008886 mTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08008887 for (size_t i = 0; i < numtracks ; ++i) {
8888 sp<RecordTrack> track = mTracks[i];
8889 if (track != 0) {
8890 bool active = mActiveTracks.indexOf(track) >= 0;
8891 if (active) {
8892 numactiveseen++;
8893 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008894 result.append(prefix);
8895 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08008896 }
Eric Laurent81784c32012-11-19 14:55:58 -08008897 }
Marco Nelissenb2208842014-02-07 14:00:50 -08008898 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07008899 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08008900 }
8901
Marco Nelissenb2208842014-02-07 14:00:50 -08008902 if (numactiveseen != numactive) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008903 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08008904 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008905 result.append(prefix);
Andy Hung000adb52018-06-01 15:43:26 -07008906 mActiveTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08008907 for (size_t i = 0; i < numactive; ++i) {
Glenn Kasten2b806402013-11-20 16:37:38 -08008908 sp<RecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08008909 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008910 result.append(prefix);
8911 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08008912 }
Glenn Kasten2b806402013-11-20 16:37:38 -08008913 }
Eric Laurent81784c32012-11-19 14:55:58 -08008914
8915 }
8916 write(fd, result.string(), result.size());
8917}
8918
Eric Laurent5ada82e2019-08-29 17:53:54 -07008919void AudioFlinger::RecordThread::setRecordSilenced(audio_port_handle_t portId, bool silenced)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008920{
8921 Mutex::Autolock _l(mLock);
8922 for (size_t i = 0; i < mTracks.size() ; i++) {
8923 sp<RecordTrack> track = mTracks[i];
Eric Laurent5ada82e2019-08-29 17:53:54 -07008924 if (track != 0 && track->portId() == portId) {
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008925 track->setSilenced(silenced);
8926 }
8927 }
8928}
Andy Hung73c02e42015-03-29 01:13:58 -07008929
8930void AudioFlinger::RecordThread::ResamplerBufferProvider::reset()
8931{
8932 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
8933 RecordThread *recordThread = (RecordThread *) threadBase.get();
Andy Hung73c02e42015-03-29 01:13:58 -07008934 mRsmpInUnrel = 0;
Eric Laurentec376dc2021-04-08 20:41:22 +02008935 const int32_t rear = recordThread->mRsmpInRear;
8936 ssize_t deltaFrames = 0;
Eric Laurent2407ce32021-04-26 14:56:03 +02008937 if (mRecordTrack->startFrames() >= 0) {
8938 int32_t startFrames = mRecordTrack->startFrames();
8939 // Accept a recent wraparound of mRsmpInRear
8940 if (startFrames <= rear) {
8941 deltaFrames = rear - startFrames;
8942 } else {
8943 deltaFrames = (int32_t)((int64_t)rear + UINT32_MAX + 1 - startFrames);
Eric Laurentec376dc2021-04-08 20:41:22 +02008944 }
Eric Laurentec376dc2021-04-08 20:41:22 +02008945 // start frame cannot be further in the past than start of resampling buffer
8946 if ((size_t) deltaFrames > recordThread->mRsmpInFrames) {
8947 deltaFrames = recordThread->mRsmpInFrames;
8948 }
8949 }
8950 mRsmpInFront = audio_utils::safe_sub_overflow(rear, static_cast<int32_t>(deltaFrames));
Andy Hung73c02e42015-03-29 01:13:58 -07008951}
8952
8953void AudioFlinger::RecordThread::ResamplerBufferProvider::sync(
8954 size_t *framesAvailable, bool *hasOverrun)
8955{
8956 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
8957 RecordThread *recordThread = (RecordThread *) threadBase.get();
8958 const int32_t rear = recordThread->mRsmpInRear;
8959 const int32_t front = mRsmpInFront;
Hongwei Wang95e37682019-04-12 11:13:36 -07008960 const ssize_t filled = audio_utils::safe_sub_overflow(rear, front);
Andy Hung73c02e42015-03-29 01:13:58 -07008961
8962 size_t framesIn;
8963 bool overrun = false;
8964 if (filled < 0) {
8965 // should not happen, but treat like a massive overrun and re-sync
8966 framesIn = 0;
8967 mRsmpInFront = rear;
8968 overrun = true;
8969 } else if ((size_t) filled <= recordThread->mRsmpInFrames) {
8970 framesIn = (size_t) filled;
8971 } else {
8972 // client is not keeping up with server, but give it latest data
8973 framesIn = recordThread->mRsmpInFrames;
Hongwei Wang95e37682019-04-12 11:13:36 -07008974 mRsmpInFront = /* front = */ audio_utils::safe_sub_overflow(
8975 rear, static_cast<int32_t>(framesIn));
Andy Hung73c02e42015-03-29 01:13:58 -07008976 overrun = true;
8977 }
8978 if (framesAvailable != NULL) {
8979 *framesAvailable = framesIn;
8980 }
8981 if (hasOverrun != NULL) {
8982 *hasOverrun = overrun;
8983 }
8984}
8985
Eric Laurent81784c32012-11-19 14:55:58 -08008986// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008987status_t AudioFlinger::RecordThread::ResamplerBufferProvider::getNextBuffer(
Glenn Kastend79072e2016-01-06 08:41:20 -08008988 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08008989{
Andy Hung73c02e42015-03-29 01:13:58 -07008990 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008991 if (threadBase == 0) {
8992 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08008993 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008994 return NOT_ENOUGH_DATA;
8995 }
8996 RecordThread *recordThread = (RecordThread *) threadBase.get();
8997 int32_t rear = recordThread->mRsmpInRear;
Andy Hung73c02e42015-03-29 01:13:58 -07008998 int32_t front = mRsmpInFront;
Hongwei Wang95e37682019-04-12 11:13:36 -07008999 ssize_t filled = audio_utils::safe_sub_overflow(rear, front);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009000 // FIXME should not be P2 (don't want to increase latency)
9001 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08009002 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07009003 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009004
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009005 front &= recordThread->mRsmpInFramesP2 - 1;
9006 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07009007 if (part1 > (size_t) filled) {
9008 part1 = filled;
9009 }
9010 size_t ask = buffer->frameCount;
9011 ALOG_ASSERT(ask > 0);
9012 if (part1 > ask) {
9013 part1 = ask;
9014 }
9015 if (part1 == 0) {
Andy Hung73c02e42015-03-29 01:13:58 -07009016 // out of data is fine since the resampler will return a short-count.
Glenn Kasten85948432013-08-19 12:09:05 -07009017 buffer->raw = NULL;
9018 buffer->frameCount = 0;
Andy Hung73c02e42015-03-29 01:13:58 -07009019 mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07009020 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08009021 }
9022
Andy Hung57446612015-04-19 23:56:46 -07009023 buffer->raw = (uint8_t*)recordThread->mRsmpInBuffer + front * recordThread->mFrameSize;
Glenn Kasten85948432013-08-19 12:09:05 -07009024 buffer->frameCount = part1;
Andy Hung73c02e42015-03-29 01:13:58 -07009025 mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08009026 return NO_ERROR;
9027}
9028
9029// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009030void AudioFlinger::RecordThread::ResamplerBufferProvider::releaseBuffer(
9031 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08009032{
Hongwei Wang95e37682019-04-12 11:13:36 -07009033 int32_t stepCount = static_cast<int32_t>(buffer->frameCount);
Glenn Kasten85948432013-08-19 12:09:05 -07009034 if (stepCount == 0) {
9035 return;
9036 }
Andy Hung73c02e42015-03-29 01:13:58 -07009037 ALOG_ASSERT(stepCount <= mRsmpInUnrel);
9038 mRsmpInUnrel -= stepCount;
Hongwei Wang95e37682019-04-12 11:13:36 -07009039 mRsmpInFront = audio_utils::safe_add_overflow(mRsmpInFront, stepCount);
Glenn Kasten85948432013-08-19 12:09:05 -07009040 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08009041 buffer->frameCount = 0;
9042}
9043
Eric Laurentd8365c52017-07-16 15:27:05 -07009044void AudioFlinger::RecordThread::checkBtNrec()
9045{
9046 Mutex::Autolock _l(mLock);
9047 checkBtNrec_l();
9048}
9049
9050void AudioFlinger::RecordThread::checkBtNrec_l()
9051{
9052 // disable AEC and NS if the device is a BT SCO headset supporting those
9053 // pre processings
jiabinc52b1ff2019-10-31 17:20:42 -07009054 bool suspend = audio_is_bluetooth_sco_device(inDeviceType()) &&
Eric Laurentd8365c52017-07-16 15:27:05 -07009055 mAudioFlinger->btNrecIsOff();
9056 if (mBtNrecSuspended.exchange(suspend) != suspend) {
9057 for (size_t i = 0; i < mEffectChains.size(); i++) {
9058 setEffectSuspended_l(FX_IID_AEC, suspend, mEffectChains[i]->sessionId());
9059 setEffectSuspended_l(FX_IID_NS, suspend, mEffectChains[i]->sessionId());
9060 }
9061 }
9062}
9063
Andy Hung97a893e2015-03-29 01:03:07 -07009064
Eric Laurent10351942014-05-08 18:49:52 -07009065bool AudioFlinger::RecordThread::checkForNewParameter_l(const String8& keyValuePair,
9066 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08009067{
9068 bool reconfig = false;
9069
Eric Laurent10351942014-05-08 18:49:52 -07009070 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08009071
Eric Laurent10351942014-05-08 18:49:52 -07009072 audio_format_t reqFormat = mFormat;
9073 uint32_t samplingRate = mSampleRate;
Glenn Kastene1635ec2015-06-08 15:46:49 -07009074 // 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 -07009075 audio_channel_mask_t channelMask = audio_channel_in_mask_from_count(mChannelCount);
9076
9077 AudioParameter param = AudioParameter(keyValuePair);
9078 int value;
Haynes Mathew George9ce67b52015-09-30 11:40:47 -07009079
9080 // scope for AutoPark extends to end of method
9081 AutoPark<FastCapture> park(mFastCapture);
9082
Eric Laurent10351942014-05-08 18:49:52 -07009083 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
9084 // channel count change can be requested. Do we mandate the first client defines the
9085 // HAL sampling rate and channel count or do we allow changes on the fly?
9086 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
9087 samplingRate = value;
9088 reconfig = true;
9089 }
9090 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung97a893e2015-03-29 01:03:07 -07009091 if (!audio_is_linear_pcm((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07009092 status = BAD_VALUE;
9093 } else {
9094 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08009095 reconfig = true;
9096 }
Eric Laurent10351942014-05-08 18:49:52 -07009097 }
9098 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
9099 audio_channel_mask_t mask = (audio_channel_mask_t) value;
Andy Hungd330ee42015-04-20 13:23:41 -07009100 if (!audio_is_input_channel(mask) ||
Andy Hung936845a2021-06-08 00:09:06 -07009101 audio_channel_count_from_in_mask(mask) > FCC_LIMIT) {
Eric Laurent10351942014-05-08 18:49:52 -07009102 status = BAD_VALUE;
9103 } else {
9104 channelMask = mask;
9105 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08009106 }
Eric Laurent10351942014-05-08 18:49:52 -07009107 }
9108 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
9109 // do not accept frame count changes if tracks are open as the track buffer
9110 // size depends on frame count and correct behavior would not be guaranteed
9111 // if frame count is changed after track creation
9112 if (mActiveTracks.size() > 0) {
9113 status = INVALID_OPERATION;
9114 } else {
9115 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08009116 }
Eric Laurent10351942014-05-08 18:49:52 -07009117 }
9118 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07009119 LOG_FATAL("Should not set routing device in RecordThread");
Eric Laurent10351942014-05-08 18:49:52 -07009120 }
9121 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
9122 mAudioSource != (audio_source_t)value) {
jiabinc52b1ff2019-10-31 17:20:42 -07009123 LOG_FATAL("Should not set audio source in RecordThread");
Eric Laurent10351942014-05-08 18:49:52 -07009124 }
Glenn Kastene198c362013-08-13 09:13:36 -07009125
Eric Laurent10351942014-05-08 18:49:52 -07009126 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009127 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07009128 if (status == INVALID_OPERATION) {
9129 inputStandBy();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009130 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07009131 }
9132 if (reconfig) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009133 if (status == BAD_VALUE) {
Mikhail Naganov560637e2021-03-31 22:40:13 +00009134 audio_config_base_t config = AUDIO_CONFIG_BASE_INITIALIZER;
9135 if (mInput->stream->getAudioProperties(&config) == OK &&
9136 audio_is_linear_pcm(config.format) && audio_is_linear_pcm(reqFormat) &&
9137 config.sample_rate <= (AUDIO_RESAMPLER_DOWN_RATIO_MAX * samplingRate) &&
Andy Hung936845a2021-06-08 00:09:06 -07009138 audio_channel_count_from_in_mask(config.channel_mask) <= FCC_LIMIT) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009139 status = NO_ERROR;
9140 }
Eric Laurent81784c32012-11-19 14:55:58 -08009141 }
Eric Laurent10351942014-05-08 18:49:52 -07009142 if (status == NO_ERROR) {
9143 readInputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07009144 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08009145 }
9146 }
Eric Laurent81784c32012-11-19 14:55:58 -08009147 }
Eric Laurent10351942014-05-08 18:49:52 -07009148
Eric Laurent81784c32012-11-19 14:55:58 -08009149 return reconfig;
9150}
9151
9152String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
9153{
Eric Laurent81784c32012-11-19 14:55:58 -08009154 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009155 if (initCheck() == NO_ERROR) {
9156 String8 out_s8;
9157 if (mInput->stream->getParameters(keys, &out_s8) == OK) {
9158 return out_s8;
9159 }
Eric Laurent81784c32012-11-19 14:55:58 -08009160 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009161 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08009162}
9163
Mikhail Naganov88536df2021-07-26 17:30:29 -07009164void AudioFlinger::RecordThread::ioConfigChanged(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -07009165 audio_port_handle_t portId) {
Mikhail Naganov88536df2021-07-26 17:30:29 -07009166 sp<AudioIoDescriptor> desc;
Eric Laurent81784c32012-11-19 14:55:58 -08009167 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07009168 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07009169 case AUDIO_INPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07009170 case AUDIO_INPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07009171 desc = sp<AudioIoDescriptor>::make(mId, mPatch, true /*isInput*/,
9172 mSampleRate, mFormat, mChannelMask, mFrameCount, mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08009173 break;
Eric Laurent09f1ed22019-04-24 17:45:17 -07009174 case AUDIO_CLIENT_STARTED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07009175 desc = sp<AudioIoDescriptor>::make(mId, mPatch, portId);
Eric Laurent09f1ed22019-04-24 17:45:17 -07009176 break;
Eric Laurent73e26b62015-04-27 16:55:58 -07009177 case AUDIO_INPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08009178 default:
Mikhail Naganov88536df2021-07-26 17:30:29 -07009179 desc = sp<AudioIoDescriptor>::make(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08009180 break;
9181 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07009182 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08009183}
9184
Glenn Kastendeca2ae2014-02-07 10:25:56 -08009185void AudioFlinger::RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08009186{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009187 status_t result = mInput->stream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
9188 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
Andy Hung463be252014-07-10 16:56:07 -07009189 mFormat = mHALFormat;
Mikhail Naganovce9f2652018-07-16 11:09:24 -07009190 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
9191 if (audio_is_linear_pcm(mFormat)) {
Andy Hung936845a2021-06-08 00:09:06 -07009192 LOG_ALWAYS_FATAL_IF(mChannelCount > FCC_LIMIT, "HAL channel count %d > %d",
9193 mChannelCount, FCC_LIMIT);
Mikhail Naganovce9f2652018-07-16 11:09:24 -07009194 } else {
Andy Hung936845a2021-06-08 00:09:06 -07009195 // Can have more that FCC_LIMIT channels in encoded streams.
Mikhail Naganovce9f2652018-07-16 11:09:24 -07009196 ALOGI("HAL format %#x is not linear pcm", mFormat);
9197 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009198 result = mInput->stream->getFrameSize(&mFrameSize);
9199 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
Hayden Gomes1a89ab32020-06-12 11:05:47 -07009200 LOG_ALWAYS_FATAL_IF(mFrameSize <= 0, "Error frame size was %zu but must be greater than zero",
9201 mFrameSize);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009202 result = mInput->stream->getBufferSize(&mBufferSize);
9203 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
Glenn Kasten548efc92012-11-29 08:48:51 -08009204 mFrameCount = mBufferSize / mFrameSize;
Hayden Gomes1a89ab32020-06-12 11:05:47 -07009205 ALOGV("%p RecordThread params: mChannelCount=%u, mFormat=%#x, mFrameSize=%zu, "
9206 "mBufferSize=%zu, mFrameCount=%zu",
9207 this, mChannelCount, mFormat, mFrameSize, mBufferSize, mFrameCount);
Glenn Kasten49d00ad2014-07-21 11:22:03 -07009208
Eric Laurentec376dc2021-04-08 20:41:22 +02009209 // mRsmpInFrames must be 0 before calling resizeInputBuffer_l for the first time
9210 mRsmpInFrames = 0;
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009211 resizeInputBuffer_l(0 /*maxSharedAudioHistoryMs*/);
Eric Laurent81784c32012-11-19 14:55:58 -08009212
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08009213 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
9214 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Andy Hungea840382020-05-05 21:50:17 -07009215
9216 audio_input_flags_t flags = mInput->flags;
9217 mediametrics::LogItem item(mThreadMetrics.getMetricsId());
9218 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
9219 .set(AMEDIAMETRICS_PROP_ENCODING, formatToString(mFormat).c_str())
9220 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
9221 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
9222 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
9223 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
9224 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mFrameCount)
9225 .record();
Eric Laurent81784c32012-11-19 14:55:58 -08009226}
9227
Glenn Kasten5f972c02014-01-13 09:59:31 -08009228uint32_t AudioFlinger::RecordThread::getInputFramesLost()
Eric Laurent81784c32012-11-19 14:55:58 -08009229{
9230 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009231 uint32_t result;
9232 if (initCheck() == NO_ERROR && mInput->stream->getInputFramesLost(&result) == OK) {
9233 return result;
Eric Laurent81784c32012-11-19 14:55:58 -08009234 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009235 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08009236}
9237
Glenn Kastend848eb42016-03-08 13:42:11 -08009238KeyedVector<audio_session_t, bool> AudioFlinger::RecordThread::sessionIds() const
Eric Laurent81784c32012-11-19 14:55:58 -08009239{
Glenn Kastend848eb42016-03-08 13:42:11 -08009240 KeyedVector<audio_session_t, bool> ids;
Eric Laurent81784c32012-11-19 14:55:58 -08009241 Mutex::Autolock _l(mLock);
9242 for (size_t j = 0; j < mTracks.size(); ++j) {
9243 sp<RecordThread::RecordTrack> track = mTracks[j];
Glenn Kastend848eb42016-03-08 13:42:11 -08009244 audio_session_t sessionId = track->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08009245 if (ids.indexOfKey(sessionId) < 0) {
9246 ids.add(sessionId, true);
9247 }
9248 }
9249 return ids;
9250}
9251
9252AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
9253{
9254 Mutex::Autolock _l(mLock);
9255 AudioStreamIn *input = mInput;
9256 mInput = NULL;
9257 return input;
9258}
9259
9260// this method must always be called either with ThreadBase mLock held or inside the thread loop
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009261sp<StreamHalInterface> AudioFlinger::RecordThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08009262{
9263 if (mInput == NULL) {
9264 return NULL;
9265 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009266 return mInput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08009267}
9268
9269status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
9270{
Eric Laurent81784c32012-11-19 14:55:58 -08009271 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurentaaa44472014-09-12 17:41:50 -07009272 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08009273 chain->setInBuffer(NULL);
9274 chain->setOutBuffer(NULL);
9275
9276 checkSuspendOnAddEffectChain_l(chain);
9277
Eric Laurent1b928682014-10-02 19:41:47 -07009278 // make sure enabled pre processing effects state is communicated to the HAL as we
9279 // just moved them to a new input stream.
9280 chain->syncHalEffectsState();
9281
Eric Laurent81784c32012-11-19 14:55:58 -08009282 mEffectChains.add(chain);
9283
9284 return NO_ERROR;
9285}
9286
9287size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
9288{
9289 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
Eric Laurentb20cf7d2019-04-05 19:37:34 -07009290
9291 for (size_t i = 0; i < mEffectChains.size(); i++) {
9292 if (chain == mEffectChains[i]) {
9293 mEffectChains.removeAt(i);
9294 break;
9295 }
Eric Laurent81784c32012-11-19 14:55:58 -08009296 }
Eric Laurentb20cf7d2019-04-05 19:37:34 -07009297 return mEffectChains.size();
Eric Laurent81784c32012-11-19 14:55:58 -08009298}
9299
Eric Laurent1c333e22014-05-20 10:48:17 -07009300status_t AudioFlinger::RecordThread::createAudioPatch_l(const struct audio_patch *patch,
9301 audio_patch_handle_t *handle)
9302{
9303 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07009304
9305 // store new device and send to effects
jiabinc52b1ff2019-10-31 17:20:42 -07009306 mInDeviceTypeAddr.mType = patch->sources[0].ext.device.type;
jiabin0a488932020-08-07 17:32:40 -07009307 mInDeviceTypeAddr.setAddress(patch->sources[0].ext.device.address);
François Gaffie0c280aa2018-07-25 10:02:15 +02009308 audio_port_handle_t deviceId = patch->sources[0].id;
Eric Laurent054d9d32015-04-24 08:48:48 -07009309 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08009310 mEffectChains[i]->setInputDevice_l(inDeviceTypeAddr());
Eric Laurent054d9d32015-04-24 08:48:48 -07009311 }
9312
Eric Laurentd8365c52017-07-16 15:27:05 -07009313 checkBtNrec_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07009314
9315 // store new source and send to effects
9316 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
9317 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent1c333e22014-05-20 10:48:17 -07009318 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent054d9d32015-04-24 08:48:48 -07009319 mEffectChains[i]->setAudioSource_l(mAudioSource);
Eric Laurent1c333e22014-05-20 10:48:17 -07009320 }
Eric Laurent054d9d32015-04-24 08:48:48 -07009321 }
Eric Laurent1c333e22014-05-20 10:48:17 -07009322
Mikhail Naganov9ee05402016-10-13 15:58:17 -07009323 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07009324 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
9325 status = hwDevice->createAudioPatch(patch->num_sources,
9326 patch->sources,
9327 patch->num_sinks,
9328 patch->sinks,
9329 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07009330 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08009331 status = mInput->stream->legacyCreateAudioPatch(patch->sources[0],
9332 patch->sinks[0].ext.mix.usecase.source,
9333 patch->sources[0].ext.device.type);
Eric Laurent054d9d32015-04-24 08:48:48 -07009334 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07009335 }
Eric Laurent054d9d32015-04-24 08:48:48 -07009336
jiabinc52b1ff2019-10-31 17:20:42 -07009337 if ((mPatch.num_sources == 0) || (mPatch.sources[0].id != deviceId)) {
Eric Laurente8726fe2015-06-26 09:39:24 -07009338 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
jiabinc52b1ff2019-10-31 17:20:42 -07009339 mPatch = *patch;
Eric Laurente8726fe2015-06-26 09:39:24 -07009340 }
Eric Laurent296fb132015-05-01 11:38:42 -07009341
Andy Hungc2b11cb2020-04-22 09:04:01 -07009342 const std::string pathSourcesAsString = patchSourcesToString(patch);
Andy Hungcf10d742020-04-28 15:38:24 -07009343 mThreadMetrics.logEndInterval();
Andy Hungea840382020-05-05 21:50:17 -07009344 mThreadMetrics.logCreatePatch(pathSourcesAsString, /* outDevices */ {});
Andy Hungcf10d742020-04-28 15:38:24 -07009345 mThreadMetrics.logBeginInterval();
Andy Hungc2b11cb2020-04-22 09:04:01 -07009346 // also dispatch to active AudioRecords
9347 for (const auto &track : mActiveTracks) {
9348 track->logEndInterval();
9349 track->logBeginInterval(pathSourcesAsString);
9350 }
Eric Laurentdda206a2022-07-08 17:28:35 +02009351 // Force meteadata update after a route change
9352 mActiveTracks.setHasChanged();
9353
Eric Laurent1c333e22014-05-20 10:48:17 -07009354 return status;
9355}
9356
9357status_t AudioFlinger::RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
9358{
9359 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07009360
jiabinc52b1ff2019-10-31 17:20:42 -07009361 mPatch = audio_patch{};
9362 mInDeviceTypeAddr.reset();
Eric Laurent054d9d32015-04-24 08:48:48 -07009363
Mikhail Naganov9ee05402016-10-13 15:58:17 -07009364 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07009365 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
9366 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07009367 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08009368 status = mInput->stream->legacyReleaseAudioPatch();
Eric Laurent1c333e22014-05-20 10:48:17 -07009369 }
Eric Laurentdda206a2022-07-08 17:28:35 +02009370 // Force meteadata update after a route change
9371 mActiveTracks.setHasChanged();
9372
Eric Laurent1c333e22014-05-20 10:48:17 -07009373 return status;
9374}
9375
jiabinc52b1ff2019-10-31 17:20:42 -07009376void AudioFlinger::RecordThread::updateOutDevices(const DeviceDescriptorBaseVector& outDevices)
9377{
wendy lin56aa82b2020-12-02 15:19:55 +08009378 Mutex::Autolock _l(mLock);
jiabinc52b1ff2019-10-31 17:20:42 -07009379 mOutDevices = outDevices;
9380 mOutDeviceTypeAddrs = deviceTypeAddrsFromDescriptors(mOutDevices);
9381 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08009382 mEffectChains[i]->setDevices_l(outDeviceTypeAddrs());
jiabinc52b1ff2019-10-31 17:20:42 -07009383 }
9384}
9385
Eric Laurentec376dc2021-04-08 20:41:22 +02009386int32_t AudioFlinger::RecordThread::getOldestFront_l()
9387{
9388 if (mTracks.size() == 0) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009389 return mRsmpInRear;
Eric Laurentec376dc2021-04-08 20:41:22 +02009390 }
Eric Laurent2407ce32021-04-26 14:56:03 +02009391 int32_t oldestFront = mRsmpInRear;
9392 int32_t maxFilled = 0;
Eric Laurentec376dc2021-04-08 20:41:22 +02009393 for (size_t i = 0; i < mTracks.size(); i++) {
Eric Laurent2407ce32021-04-26 14:56:03 +02009394 int32_t front = mTracks[i]->mResamplerBufferProvider->getFront();
9395 int32_t filled;
Eric Laurent92d0a322021-07-16 15:32:33 +02009396 (void)__builtin_sub_overflow(mRsmpInRear, front, &filled);
Eric Laurent2407ce32021-04-26 14:56:03 +02009397 if (filled > maxFilled) {
9398 oldestFront = front;
9399 maxFilled = filled;
9400 }
Eric Laurentec376dc2021-04-08 20:41:22 +02009401 }
Eric Laurent92d0a322021-07-16 15:32:33 +02009402 if (maxFilled > mRsmpInFrames) {
9403 (void)__builtin_sub_overflow(mRsmpInRear, mRsmpInFrames, &oldestFront);
9404 }
Eric Laurent2407ce32021-04-26 14:56:03 +02009405 return oldestFront;
Eric Laurentec376dc2021-04-08 20:41:22 +02009406}
9407
9408void AudioFlinger::RecordThread::updateFronts_l(int32_t offset)
9409{
9410 if (offset == 0) {
9411 return;
9412 }
9413 for (size_t i = 0; i < mTracks.size(); i++) {
9414 int32_t front = mTracks[i]->mResamplerBufferProvider->getFront();
9415 front = audio_utils::safe_sub_overflow(front, offset);
9416 mTracks[i]->mResamplerBufferProvider->setFront(front);
9417 }
9418}
9419
9420void AudioFlinger::RecordThread::resizeInputBuffer_l(int32_t maxSharedAudioHistoryMs)
9421{
9422 // This is the formula for calculating the temporary buffer size.
9423 // With 7 HAL buffers, we can guarantee ability to down-sample the input by ratio of 6:1 to
9424 // 1 full output buffer, regardless of the alignment of the available input.
9425 // The value is somewhat arbitrary, and could probably be even larger.
9426 // A larger value should allow more old data to be read after a track calls start(),
9427 // without increasing latency.
9428 //
9429 // Note this is independent of the maximum downsampling ratio permitted for capture.
9430 size_t minRsmpInFrames = mFrameCount * 7;
9431
9432 // maxSharedAudioHistoryMs != 0 indicates a request to possibly make some part of the audio
9433 // capture history available to another client using the same session ID:
9434 // dimension the resampler input buffer accordingly.
9435
9436 // Get oldest client read position: getOldestFront_l() must be called before altering
9437 // mRsmpInRear, or mRsmpInFrames
9438 int32_t previousFront = getOldestFront_l();
9439 size_t previousRsmpInFramesP2 = mRsmpInFramesP2;
9440 int32_t previousRear = mRsmpInRear;
9441 mRsmpInRear = 0;
9442
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009443 ALOG_ASSERT(maxSharedAudioHistoryMs >= 0
9444 && maxSharedAudioHistoryMs <= AudioFlinger::kMaxSharedAudioHistoryMs,
9445 "resizeInputBuffer_l() called with invalid max shared history %d",
9446 maxSharedAudioHistoryMs);
Eric Laurentec376dc2021-04-08 20:41:22 +02009447 if (maxSharedAudioHistoryMs != 0) {
9448 // resizeInputBuffer_l should never be called with a non zero shared history if the
9449 // buffer was not already allocated
9450 ALOG_ASSERT(mRsmpInBuffer != nullptr && mRsmpInFrames != 0,
9451 "resizeInputBuffer_l() called with shared history and unallocated buffer");
9452 size_t rsmpInFrames = (size_t)maxSharedAudioHistoryMs * mSampleRate / 1000;
9453 // never reduce resampler input buffer size
Eric Laurent92d0a322021-07-16 15:32:33 +02009454 if (rsmpInFrames <= mRsmpInFrames) {
Eric Laurentec376dc2021-04-08 20:41:22 +02009455 return;
9456 }
9457 mRsmpInFrames = rsmpInFrames;
9458 }
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009459 mMaxSharedAudioHistoryMs = maxSharedAudioHistoryMs;
Eric Laurentec376dc2021-04-08 20:41:22 +02009460 // Note: mRsmpInFrames is 0 when called with maxSharedAudioHistoryMs equals to 0 so it is always
9461 // initialized
9462 if (mRsmpInFrames < minRsmpInFrames) {
9463 mRsmpInFrames = minRsmpInFrames;
9464 }
9465 mRsmpInFramesP2 = roundup(mRsmpInFrames);
9466
9467 // TODO optimize audio capture buffer sizes ...
9468 // Here we calculate the size of the sliding buffer used as a source
9469 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
9470 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
9471 // be better to have it derived from the pipe depth in the long term.
9472 // The current value is higher than necessary. However it should not add to latency.
9473
9474 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
9475 mRsmpInFramesOA = mRsmpInFramesP2 + mFrameCount - 1;
9476
9477 void *rsmpInBuffer;
9478 (void)posix_memalign(&rsmpInBuffer, 32, mRsmpInFramesOA * mFrameSize);
9479 // if posix_memalign fails, will segv here.
9480 memset(rsmpInBuffer, 0, mRsmpInFramesOA * mFrameSize);
9481
9482 // Copy audio history if any from old buffer before freeing it
9483 if (previousRear != 0) {
9484 ALOG_ASSERT(mRsmpInBuffer != nullptr,
9485 "resizeInputBuffer_l() called with null buffer but frames already read from HAL");
9486
9487 ssize_t unread = audio_utils::safe_sub_overflow(previousRear, previousFront);
9488 previousFront &= previousRsmpInFramesP2 - 1;
9489 size_t part1 = previousRsmpInFramesP2 - previousFront;
9490 if (part1 > (size_t) unread) {
9491 part1 = unread;
9492 }
9493 if (part1 != 0) {
9494 memcpy(rsmpInBuffer, (const uint8_t*)mRsmpInBuffer + previousFront * mFrameSize,
9495 part1 * mFrameSize);
9496 mRsmpInRear = part1;
9497 part1 = unread - part1;
9498 if (part1 != 0) {
9499 memcpy((uint8_t*)rsmpInBuffer + mRsmpInRear * mFrameSize,
9500 (const uint8_t*)mRsmpInBuffer, part1 * mFrameSize);
9501 mRsmpInRear += part1;
9502 }
9503 }
9504 // Update front for all clients according to new rear
9505 updateFronts_l(audio_utils::safe_sub_overflow(previousRear, mRsmpInRear));
9506 } else {
9507 mRsmpInRear = 0;
9508 }
9509 free(mRsmpInBuffer);
9510 mRsmpInBuffer = rsmpInBuffer;
9511}
9512
Mikhail Naganov444ecc32018-05-01 17:40:05 -07009513void AudioFlinger::RecordThread::addPatchTrack(const sp<PatchRecord>& record)
Eric Laurent83b88082014-06-20 18:31:16 -07009514{
9515 Mutex::Autolock _l(mLock);
9516 mTracks.add(record);
Mikhail Naganov2534b382019-09-25 13:05:02 -07009517 if (record->getSource()) {
9518 mSource = record->getSource();
9519 }
Eric Laurent83b88082014-06-20 18:31:16 -07009520}
9521
Mikhail Naganov444ecc32018-05-01 17:40:05 -07009522void AudioFlinger::RecordThread::deletePatchTrack(const sp<PatchRecord>& record)
Eric Laurent83b88082014-06-20 18:31:16 -07009523{
9524 Mutex::Autolock _l(mLock);
Mikhail Naganov2534b382019-09-25 13:05:02 -07009525 if (mSource == record->getSource()) {
9526 mSource = mInput;
9527 }
Eric Laurent83b88082014-06-20 18:31:16 -07009528 destroyTrack_l(record);
9529}
9530
Mikhail Naganovdc769682018-05-04 15:34:08 -07009531void AudioFlinger::RecordThread::toAudioPortConfig(struct audio_port_config *config)
Eric Laurent83b88082014-06-20 18:31:16 -07009532{
Mikhail Naganovdc769682018-05-04 15:34:08 -07009533 ThreadBase::toAudioPortConfig(config);
Eric Laurent83b88082014-06-20 18:31:16 -07009534 config->role = AUDIO_PORT_ROLE_SINK;
9535 config->ext.mix.hw_module = mInput->audioHwDev->handle();
9536 config->ext.mix.usecase.source = mAudioSource;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07009537 if (mInput && mInput->flags != AUDIO_INPUT_FLAG_NONE) {
9538 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
9539 config->flags.input = mInput->flags;
9540 }
Eric Laurent83b88082014-06-20 18:31:16 -07009541}
Eric Laurent1c333e22014-05-20 10:48:17 -07009542
Eric Laurent6acd1d42017-01-04 14:23:29 -08009543// ----------------------------------------------------------------------------
9544// Mmap
9545// ----------------------------------------------------------------------------
9546
9547AudioFlinger::MmapThreadHandle::MmapThreadHandle(const sp<MmapThread>& thread)
9548 : mThread(thread)
9549{
Phil Burk9fabbf82017-08-03 12:02:00 -07009550 assert(thread != 0); // thread must start non-null and stay non-null
Eric Laurent6acd1d42017-01-04 14:23:29 -08009551}
9552
9553AudioFlinger::MmapThreadHandle::~MmapThreadHandle()
9554{
Phil Burk9fabbf82017-08-03 12:02:00 -07009555 mThread->disconnect();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009556}
9557
9558status_t AudioFlinger::MmapThreadHandle::createMmapBuffer(int32_t minSizeFrames,
9559 struct audio_mmap_buffer_info *info)
9560{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009561 return mThread->createMmapBuffer(minSizeFrames, info);
9562}
9563
9564status_t AudioFlinger::MmapThreadHandle::getMmapPosition(struct audio_mmap_position *position)
9565{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009566 return mThread->getMmapPosition(position);
9567}
9568
jiabinb7d8c5a2020-08-26 17:24:52 -07009569status_t AudioFlinger::MmapThreadHandle::getExternalPosition(uint64_t *position,
9570 int64_t *timeNanos) {
9571 return mThread->getExternalPosition(position, timeNanos);
9572}
9573
Eric Laurenta54f1282017-07-01 19:39:32 -07009574status_t AudioFlinger::MmapThreadHandle::start(const AudioClient& client,
jiabind1f1cb62020-03-24 11:57:57 -07009575 const audio_attributes_t *attr, audio_port_handle_t *handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009576
9577{
jiabind1f1cb62020-03-24 11:57:57 -07009578 return mThread->start(client, attr, handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009579}
9580
9581status_t AudioFlinger::MmapThreadHandle::stop(audio_port_handle_t handle)
9582{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009583 return mThread->stop(handle);
9584}
9585
Eric Laurent18b57012017-02-13 16:23:52 -08009586status_t AudioFlinger::MmapThreadHandle::standby()
9587{
Eric Laurent18b57012017-02-13 16:23:52 -08009588 return mThread->standby();
9589}
9590
Eric Laurent6acd1d42017-01-04 14:23:29 -08009591
9592AudioFlinger::MmapThread::MmapThread(
9593 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
Andy Hungcf10d742020-04-28 15:38:24 -07009594 AudioHwDevice *hwDev, sp<StreamHalInterface> stream, bool systemReady, bool isOut)
Andy Hungea840382020-05-05 21:50:17 -07009595 : ThreadBase(audioFlinger, id, (isOut ? MMAP_PLAYBACK : MMAP_CAPTURE), systemReady, isOut),
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009596 mSessionId(AUDIO_SESSION_NONE),
François Gaffie0c280aa2018-07-25 10:02:15 +02009597 mPortId(AUDIO_PORT_HANDLE_NONE),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009598 mHalStream(stream), mHalDevice(hwDev->hwDevice()), mAudioHwDev(hwDev),
Eric Laurent67f97292018-04-20 18:05:41 -07009599 mActiveTracks(&this->mLocalLog),
9600 mHalVolFloat(-1.0f), // Initialize to illegal value so it always gets set properly later.
9601 mNoCallbackWarningCount(0)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009602{
Eric Laurent18b57012017-02-13 16:23:52 -08009603 mStandby = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009604 readHalParameters_l();
9605}
9606
9607AudioFlinger::MmapThread::~MmapThread()
9608{
9609}
9610
9611void AudioFlinger::MmapThread::onFirstRef()
9612{
9613 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
9614}
9615
9616void AudioFlinger::MmapThread::disconnect()
9617{
Eric Laurent331679c2018-04-16 17:03:16 -07009618 ActiveTracks<MmapTrack> activeTracks;
9619 {
9620 Mutex::Autolock _l(mLock);
9621 for (const sp<MmapTrack> &t : mActiveTracks) {
9622 activeTracks.add(t);
9623 }
9624 }
9625 for (const sp<MmapTrack> &t : activeTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08009626 stop(t->portId());
9627 }
Phil Burk9fabbf82017-08-03 12:02:00 -07009628 // This will decrement references and may cause the destruction of this thread.
Eric Laurent6acd1d42017-01-04 14:23:29 -08009629 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07009630 AudioSystem::releaseOutput(mPortId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009631 } else {
Eric Laurentfee19762018-01-29 18:44:13 -08009632 AudioSystem::releaseInput(mPortId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009633 }
9634}
9635
9636
9637void AudioFlinger::MmapThread::configure(const audio_attributes_t *attr,
9638 audio_stream_type_t streamType __unused,
9639 audio_session_t sessionId,
9640 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009641 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -08009642 audio_port_handle_t portId)
9643{
9644 mAttr = *attr;
9645 mSessionId = sessionId;
9646 mCallback = callback;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009647 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009648 mPortId = portId;
9649}
9650
9651status_t AudioFlinger::MmapThread::createMmapBuffer(int32_t minSizeFrames,
9652 struct audio_mmap_buffer_info *info)
9653{
9654 if (mHalStream == 0) {
9655 return NO_INIT;
9656 }
Eric Laurent18b57012017-02-13 16:23:52 -08009657 mStandby = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009658 return mHalStream->createMmapBuffer(minSizeFrames, info);
9659}
9660
9661status_t AudioFlinger::MmapThread::getMmapPosition(struct audio_mmap_position *position)
9662{
9663 if (mHalStream == 0) {
9664 return NO_INIT;
9665 }
9666 return mHalStream->getMmapPosition(position);
9667}
9668
Eric Laurentdda206a2022-07-08 17:28:35 +02009669status_t AudioFlinger::MmapThread::exitStandby_l()
Eric Laurent331679c2018-04-16 17:03:16 -07009670{
Eric Laurentdda206a2022-07-08 17:28:35 +02009671 // The HAL must receive track metadata before starting the stream
9672 updateMetadata_l();
Eric Laurent331679c2018-04-16 17:03:16 -07009673 status_t ret = mHalStream->start();
9674 if (ret != NO_ERROR) {
9675 ALOGE("%s: error mHalStream->start() = %d for first track", __FUNCTION__, ret);
9676 return ret;
9677 }
Andy Hungcf10d742020-04-28 15:38:24 -07009678 if (mStandby) {
9679 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07009680 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -07009681 mStandby = false;
9682 }
Eric Laurent331679c2018-04-16 17:03:16 -07009683 return NO_ERROR;
9684}
9685
Eric Laurenta54f1282017-07-01 19:39:32 -07009686status_t AudioFlinger::MmapThread::start(const AudioClient& client,
jiabind1f1cb62020-03-24 11:57:57 -07009687 const audio_attributes_t *attr,
Eric Laurent6acd1d42017-01-04 14:23:29 -08009688 audio_port_handle_t *handle)
9689{
Eric Laurenta54f1282017-07-01 19:39:32 -07009690 ALOGV("%s clientUid %d mStandby %d mPortId %d *handle %d", __FUNCTION__,
Svet Ganov33761132021-05-13 22:51:08 +00009691 client.attributionSource.uid, mStandby, mPortId, *handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009692 if (mHalStream == 0) {
9693 return NO_INIT;
9694 }
9695
9696 status_t ret;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009697
Eric Laurentdda206a2022-07-08 17:28:35 +02009698 // For the first track, reuse portId and session allocated when the stream was opened.
Eric Laurenta54f1282017-07-01 19:39:32 -07009699 if (*handle == mPortId) {
Eric Laurentdda206a2022-07-08 17:28:35 +02009700 acquireWakeLock();
9701 return NO_ERROR;
Eric Laurenta54f1282017-07-01 19:39:32 -07009702 }
9703
9704 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
9705
9706 audio_io_handle_t io = mId;
9707 if (isOutput()) {
9708 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
9709 config.sample_rate = mSampleRate;
9710 config.channel_mask = mChannelMask;
9711 config.format = mFormat;
9712 audio_stream_type_t stream = streamType();
9713 audio_output_flags_t flags =
9714 (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009715 audio_port_handle_t deviceId = mDeviceId;
Kevin Rocard153f92d2018-12-18 18:33:28 -08009716 std::vector<audio_io_handle_t> secondaryOutputs;
Eric Laurentb0a7bc92022-04-05 15:06:08 +02009717 bool isSpatialized;
Eric Laurenta54f1282017-07-01 19:39:32 -07009718 ret = AudioSystem::getOutputForAttr(&mAttr, &io,
9719 mSessionId,
9720 &stream,
Svet Ganov33761132021-05-13 22:51:08 +00009721 client.attributionSource,
Eric Laurenta54f1282017-07-01 19:39:32 -07009722 &config,
9723 flags,
9724 &deviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -08009725 &portId,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02009726 &secondaryOutputs,
9727 &isSpatialized);
Kevin Rocard153f92d2018-12-18 18:33:28 -08009728 ALOGD_IF(!secondaryOutputs.empty(),
9729 "MmapThread::start does not support secondary outputs, ignoring them");
Eric Laurent6acd1d42017-01-04 14:23:29 -08009730 } else {
Eric Laurenta54f1282017-07-01 19:39:32 -07009731 audio_config_base_t config;
9732 config.sample_rate = mSampleRate;
9733 config.channel_mask = mChannelMask;
9734 config.format = mFormat;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009735 audio_port_handle_t deviceId = mDeviceId;
Eric Laurenta54f1282017-07-01 19:39:32 -07009736 ret = AudioSystem::getInputForAttr(&mAttr, &io,
Mikhail Naganov2996f672019-04-18 12:29:59 -07009737 RECORD_RIID_INVALID,
Eric Laurenta54f1282017-07-01 19:39:32 -07009738 mSessionId,
Svet Ganov33761132021-05-13 22:51:08 +00009739 client.attributionSource,
Eric Laurenta54f1282017-07-01 19:39:32 -07009740 &config,
9741 AUDIO_INPUT_FLAG_MMAP_NOIRQ,
9742 &deviceId,
9743 &portId);
9744 }
9745 // APM should not chose a different input or output stream for the same set of attributes
9746 // and audo configuration
9747 if (ret != NO_ERROR || io != mId) {
9748 ALOGE("%s: error getting output or input from APM (error %d, io %d expected io %d)",
9749 __FUNCTION__, ret, io, mId);
9750 return BAD_VALUE;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009751 }
9752
9753 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07009754 ret = AudioSystem::startOutput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009755 } else {
jiabin09609032022-06-15 19:26:01 +00009756 {
9757 // Add the track record before starting input so that the silent status for the
9758 // client can be cached.
9759 Mutex::Autolock _l(mLock);
9760 setClientSilencedState_l(portId, false /*silenced*/);
9761 }
Eric Laurent4eb58f12018-12-07 16:41:02 -08009762 ret = AudioSystem::startInput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009763 }
9764
Eric Laurent331679c2018-04-16 17:03:16 -07009765 Mutex::Autolock _l(mLock);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009766 // abort if start is rejected by audio policy manager
9767 if (ret != NO_ERROR) {
Phil Burk7f6b40d2017-02-09 13:18:38 -08009768 ALOGE("%s: error start rejected by AudioPolicyManager = %d", __FUNCTION__, ret);
Eric Tan39ec8d62018-07-24 09:49:29 -07009769 if (!mActiveTracks.isEmpty()) {
Eric Laurent331679c2018-04-16 17:03:16 -07009770 mLock.unlock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009771 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07009772 AudioSystem::releaseOutput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009773 } else {
Eric Laurentfee19762018-01-29 18:44:13 -08009774 AudioSystem::releaseInput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009775 }
Eric Laurent331679c2018-04-16 17:03:16 -07009776 mLock.lock();
Eric Laurent18b57012017-02-13 16:23:52 -08009777 } else {
9778 mHalStream->stop();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009779 }
jiabin09609032022-06-15 19:26:01 +00009780 eraseClientSilencedState_l(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009781 return PERMISSION_DENIED;
9782 }
9783
Kevin Rocard1f564ac2018-03-29 13:53:10 -07009784 // Given that MmapThread::mAttr is mutable, should a MmapTrack have attributes ?
jiabind1f1cb62020-03-24 11:57:57 -07009785 sp<MmapTrack> track = new MmapTrack(this, attr == nullptr ? mAttr : *attr, mSampleRate, mFormat,
Svet Ganov33761132021-05-13 22:51:08 +00009786 mChannelMask, mSessionId, isOutput(),
9787 client.attributionSource,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07009788 IPCThreadState::self()->getCallingPid(), portId);
jiabin09609032022-06-15 19:26:01 +00009789 if (!isOutput()) {
9790 track->setSilenced_l(isClientSilenced_l(portId));
9791 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08009792
Eric Laurent4eb58f12018-12-07 16:41:02 -08009793 if (isOutput()) {
9794 // force volume update when a new track is added
9795 mHalVolFloat = -1.0f;
9796 } else if (!track->isSilenced_l()) {
9797 for (const sp<MmapTrack> &t : mActiveTracks) {
Svet Ganov33761132021-05-13 22:51:08 +00009798 if (t->isSilenced_l() && t->uid() != client.attributionSource.uid)
Eric Laurent4eb58f12018-12-07 16:41:02 -08009799 t->invalidate();
9800 }
9801 }
9802
Eric Laurent6acd1d42017-01-04 14:23:29 -08009803 mActiveTracks.add(track);
Eric Laurenta54f1282017-07-01 19:39:32 -07009804 sp<EffectChain> chain = getEffectChain_l(mSessionId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009805 if (chain != 0) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02009806 chain->setStrategy(getStrategyForStream(streamType()));
Eric Laurent6acd1d42017-01-04 14:23:29 -08009807 chain->incTrackCnt();
9808 chain->incActiveTrackCnt();
9809 }
9810
Andy Hungc2b11cb2020-04-22 09:04:01 -07009811 track->logBeginInterval(patchSinksToString(&mPatch)); // log to MediaMetrics
Eric Laurent6acd1d42017-01-04 14:23:29 -08009812 *handle = portId;
Eric Laurentdda206a2022-07-08 17:28:35 +02009813
9814 if (mActiveTracks.size() == 1) {
9815 ret = exitStandby_l();
9816 }
9817
Eric Laurent6acd1d42017-01-04 14:23:29 -08009818 broadcast_l();
9819
Eric Laurentdda206a2022-07-08 17:28:35 +02009820 ALOGV("%s DONE status %d handle %d stream %p", __FUNCTION__, ret, *handle, mHalStream.get());
Eric Laurent6acd1d42017-01-04 14:23:29 -08009821
Eric Laurentdda206a2022-07-08 17:28:35 +02009822 return ret;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009823}
9824
9825status_t AudioFlinger::MmapThread::stop(audio_port_handle_t handle)
9826{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009827 ALOGV("%s handle %d", __FUNCTION__, handle);
9828
9829 if (mHalStream == 0) {
9830 return NO_INIT;
9831 }
9832
Eric Laurenta54f1282017-07-01 19:39:32 -07009833 if (handle == mPortId) {
Phil Burk98ab4082020-09-25 21:46:34 +00009834 releaseWakeLock();
Eric Laurenta54f1282017-07-01 19:39:32 -07009835 return NO_ERROR;
9836 }
9837
Eric Laurent331679c2018-04-16 17:03:16 -07009838 Mutex::Autolock _l(mLock);
9839
Eric Laurent6acd1d42017-01-04 14:23:29 -08009840 sp<MmapTrack> track;
9841 for (const sp<MmapTrack> &t : mActiveTracks) {
9842 if (handle == t->portId()) {
9843 track = t;
9844 break;
9845 }
9846 }
9847 if (track == 0) {
9848 return BAD_VALUE;
9849 }
9850
9851 mActiveTracks.remove(track);
jiabin09609032022-06-15 19:26:01 +00009852 eraseClientSilencedState_l(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -08009853
Eric Laurent331679c2018-04-16 17:03:16 -07009854 mLock.unlock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009855 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07009856 AudioSystem::stopOutput(track->portId());
9857 AudioSystem::releaseOutput(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -08009858 } else {
Eric Laurentfee19762018-01-29 18:44:13 -08009859 AudioSystem::stopInput(track->portId());
9860 AudioSystem::releaseInput(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -08009861 }
Eric Laurent331679c2018-04-16 17:03:16 -07009862 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009863
9864 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
9865 if (chain != 0) {
9866 chain->decActiveTrackCnt();
9867 chain->decTrackCnt();
9868 }
9869
Eric Laurentdda206a2022-07-08 17:28:35 +02009870 if (mActiveTracks.isEmpty()) {
9871 mHalStream->stop();
9872 }
9873
Eric Laurent6acd1d42017-01-04 14:23:29 -08009874 broadcast_l();
9875
Eric Laurent6acd1d42017-01-04 14:23:29 -08009876 return NO_ERROR;
9877}
9878
Eric Laurent18b57012017-02-13 16:23:52 -08009879status_t AudioFlinger::MmapThread::standby()
9880{
9881 ALOGV("%s", __FUNCTION__);
9882
9883 if (mHalStream == 0) {
9884 return NO_INIT;
9885 }
Eric Tan39ec8d62018-07-24 09:49:29 -07009886 if (!mActiveTracks.isEmpty()) {
Eric Laurent18b57012017-02-13 16:23:52 -08009887 return INVALID_OPERATION;
9888 }
9889 mHalStream->standby();
Andy Hungcf10d742020-04-28 15:38:24 -07009890 if (!mStandby) {
9891 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07009892 mThreadSnapshot.onEnd();
Andy Hungcf10d742020-04-28 15:38:24 -07009893 mStandby = true;
9894 }
Eric Laurent18b57012017-02-13 16:23:52 -08009895 releaseWakeLock();
9896 return NO_ERROR;
9897}
9898
Eric Laurent6acd1d42017-01-04 14:23:29 -08009899
9900void AudioFlinger::MmapThread::readHalParameters_l()
9901{
9902 status_t result = mHalStream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
9903 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
9904 mFormat = mHALFormat;
9905 LOG_ALWAYS_FATAL_IF(!audio_is_linear_pcm(mFormat), "HAL format %#x is not linear pcm", mFormat);
9906 result = mHalStream->getFrameSize(&mFrameSize);
9907 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
Hayden Gomes1a89ab32020-06-12 11:05:47 -07009908 LOG_ALWAYS_FATAL_IF(mFrameSize <= 0, "Error frame size was %zu but must be greater than zero",
9909 mFrameSize);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009910 result = mHalStream->getBufferSize(&mBufferSize);
9911 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
9912 mFrameCount = mBufferSize / mFrameSize;
Andy Hungc2b11cb2020-04-22 09:04:01 -07009913
Andy Hungcf10d742020-04-28 15:38:24 -07009914 // TODO: make a readHalParameters call?
9915 mediametrics::LogItem item(mThreadMetrics.getMetricsId());
Andy Hungc2b11cb2020-04-22 09:04:01 -07009916 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
9917 .set(AMEDIAMETRICS_PROP_ENCODING, formatToString(mFormat).c_str())
9918 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
9919 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
9920 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
9921 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mFrameCount)
9922 /*
9923 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
9924 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELMASK,
9925 (int32_t)mHapticChannelMask)
9926 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELCOUNT,
9927 (int32_t)mHapticChannelCount)
9928 */
9929 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_ENCODING,
9930 formatToString(mHALFormat).c_str())
9931 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_FRAMECOUNT,
9932 (int32_t)mFrameCount) // sic - added HAL
9933 .record();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009934}
9935
9936bool AudioFlinger::MmapThread::threadLoop()
9937{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009938 checkSilentMode_l();
9939
9940 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
9941
9942 while (!exitPending())
9943 {
Eric Laurent6acd1d42017-01-04 14:23:29 -08009944 Vector< sp<EffectChain> > effectChains;
9945
Andy Hung13850be2019-03-14 11:33:09 -07009946 { // under Thread lock
9947 Mutex::Autolock _l(mLock);
9948
Eric Laurent6acd1d42017-01-04 14:23:29 -08009949 if (mSignalPending) {
9950 // A signal was raised while we were unlocked
9951 mSignalPending = false;
9952 } else {
9953 if (mConfigEvents.isEmpty()) {
9954 // we're about to wait, flush the binder command buffer
9955 IPCThreadState::self()->flushCommands();
9956
9957 if (exitPending()) {
9958 break;
9959 }
9960
Eric Laurent6acd1d42017-01-04 14:23:29 -08009961 // wait until we have something to do...
9962 ALOGV("%s going to sleep", myName.string());
9963 mWaitWorkCV.wait(mLock);
9964 ALOGV("%s waking up", myName.string());
Eric Laurent6acd1d42017-01-04 14:23:29 -08009965
9966 checkSilentMode_l();
9967
9968 continue;
9969 }
9970 }
9971
9972 processConfigEvents_l();
9973
9974 processVolume_l();
9975
9976 checkInvalidTracks_l();
9977
9978 mActiveTracks.updatePowerState(this);
9979
Kevin Rocard069c2712018-03-29 19:09:14 -07009980 updateMetadata_l();
9981
Eric Laurent6acd1d42017-01-04 14:23:29 -08009982 lockEffectChains_l(effectChains);
Andy Hung13850be2019-03-14 11:33:09 -07009983 } // release Thread lock
9984
Eric Laurent6acd1d42017-01-04 14:23:29 -08009985 for (size_t i = 0; i < effectChains.size(); i ++) {
Andy Hung13850be2019-03-14 11:33:09 -07009986 effectChains[i]->process_l(); // Thread is not locked, but effect chain is locked
Eric Laurent6acd1d42017-01-04 14:23:29 -08009987 }
Andy Hung13850be2019-03-14 11:33:09 -07009988
9989 // enable changes in effect chain, including moving to another thread.
Eric Laurent6acd1d42017-01-04 14:23:29 -08009990 unlockEffectChains(effectChains);
9991 // Effect chains will be actually deleted here if they were removed from
9992 // mEffectChains list during mixing or effects processing
9993 }
9994
9995 threadLoop_exit();
9996
9997 if (!mStandby) {
9998 threadLoop_standby();
9999 mStandby = true;
10000 }
10001
Eric Laurent6acd1d42017-01-04 14:23:29 -080010002 ALOGV("Thread %p type %d exiting", this, mType);
10003 return false;
10004}
10005
10006// checkForNewParameter_l() must be called with ThreadBase::mLock held
10007bool AudioFlinger::MmapThread::checkForNewParameter_l(const String8& keyValuePair,
10008 status_t& status)
10009{
10010 AudioParameter param = AudioParameter(keyValuePair);
10011 int value;
Eric Laurente6e9a482017-07-25 19:26:02 -070010012 bool sendToHal = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010013 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -070010014 LOG_FATAL("Should not happen set routing device in MmapThread");
Eric Laurent6acd1d42017-01-04 14:23:29 -080010015 }
Eric Laurente6e9a482017-07-25 19:26:02 -070010016 if (sendToHal) {
10017 status = mHalStream->setParameters(keyValuePair);
10018 } else {
10019 status = NO_ERROR;
10020 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010021
10022 return false;
10023}
10024
10025String8 AudioFlinger::MmapThread::getParameters(const String8& keys)
10026{
10027 Mutex::Autolock _l(mLock);
10028 String8 out_s8;
10029 if (initCheck() == NO_ERROR && mHalStream->getParameters(keys, &out_s8) == OK) {
10030 return out_s8;
10031 }
10032 return String8();
10033}
10034
Mikhail Naganov88536df2021-07-26 17:30:29 -070010035void AudioFlinger::MmapThread::ioConfigChanged(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -070010036 audio_port_handle_t portId __unused) {
Mikhail Naganov88536df2021-07-26 17:30:29 -070010037 sp<AudioIoDescriptor> desc;
10038 bool isInput = false;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010039 switch (event) {
10040 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -070010041 case AUDIO_INPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -080010042 case AUDIO_INPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -070010043 isInput = true;
10044 FALLTHROUGH_INTENDED;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010045 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -070010046 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -080010047 case AUDIO_OUTPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -070010048 desc = sp<AudioIoDescriptor>::make(mId, mPatch, isInput,
10049 mSampleRate, mFormat, mChannelMask, mFrameCount, mFrameCount);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010050 break;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010051 case AUDIO_INPUT_CLOSED:
10052 case AUDIO_OUTPUT_CLOSED:
10053 default:
Mikhail Naganov88536df2021-07-26 17:30:29 -070010054 desc = sp<AudioIoDescriptor>::make(mId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010055 break;
10056 }
10057 mAudioFlinger->ioConfigChanged(event, desc, pid);
10058}
10059
10060status_t AudioFlinger::MmapThread::createAudioPatch_l(const struct audio_patch *patch,
10061 audio_patch_handle_t *handle)
10062{
10063 status_t status = NO_ERROR;
10064
10065 // store new device and send to effects
10066 audio_devices_t type = AUDIO_DEVICE_NONE;
10067 audio_port_handle_t deviceId;
jiabinc52b1ff2019-10-31 17:20:42 -070010068 AudioDeviceTypeAddrVector sinkDeviceTypeAddrs;
10069 AudioDeviceTypeAddr sourceDeviceTypeAddr;
10070 uint32_t numDevices = 0;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010071 if (isOutput()) {
10072 for (unsigned int i = 0; i < patch->num_sinks; i++) {
jiabinc52b1ff2019-10-31 17:20:42 -070010073 LOG_ALWAYS_FATAL_IF(popcount(patch->sinks[i].ext.device.type) > 1
10074 && !mAudioHwDev->supportsAudioPatches(),
10075 "Enumerated device type(%#x) must not be used "
10076 "as it does not support audio patches",
10077 patch->sinks[i].ext.device.type);
Mikhail Naganov55773032020-10-01 15:08:13 -070010078 type = static_cast<audio_devices_t>(type | patch->sinks[i].ext.device.type);
jiabinc52b1ff2019-10-31 17:20:42 -070010079 sinkDeviceTypeAddrs.push_back(AudioDeviceTypeAddr(patch->sinks[i].ext.device.type,
10080 patch->sinks[i].ext.device.address));
Eric Laurent6acd1d42017-01-04 14:23:29 -080010081 }
10082 deviceId = patch->sinks[0].id;
jiabinc52b1ff2019-10-31 17:20:42 -070010083 numDevices = mPatch.num_sinks;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010084 } else {
10085 type = patch->sources[0].ext.device.type;
10086 deviceId = patch->sources[0].id;
jiabinc52b1ff2019-10-31 17:20:42 -070010087 numDevices = mPatch.num_sources;
10088 sourceDeviceTypeAddr.mType = patch->sources[0].ext.device.type;
jiabin0a488932020-08-07 17:32:40 -070010089 sourceDeviceTypeAddr.setAddress(patch->sources[0].ext.device.address);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010090 }
10091
10092 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -080010093 if (isOutput()) {
10094 mEffectChains[i]->setDevices_l(sinkDeviceTypeAddrs);
10095 } else {
10096 mEffectChains[i]->setInputDevice_l(sourceDeviceTypeAddr);
10097 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010098 }
10099
jiabinc52b1ff2019-10-31 17:20:42 -070010100 if (!isOutput()) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010101 // store new source and send to effects
10102 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
10103 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
10104 for (size_t i = 0; i < mEffectChains.size(); i++) {
10105 mEffectChains[i]->setAudioSource_l(mAudioSource);
10106 }
10107 }
10108 }
10109
10110 if (mAudioHwDev->supportsAudioPatches()) {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010111 status = mHalDevice->createAudioPatch(patch->num_sources, patch->sources, patch->num_sinks,
10112 patch->sinks, handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010113 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010114 audio_port_config port;
10115 std::optional<audio_source_t> source;
10116 if (isOutput()) {
10117 port = patch->sinks[0];
Eric Laurent6acd1d42017-01-04 14:23:29 -080010118 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010119 port = patch->sources[0];
10120 source = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010121 }
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010122 status = mHalStream->legacyCreateAudioPatch(port, source, type);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010123 *handle = AUDIO_PATCH_HANDLE_NONE;
10124 }
10125
jiabinc52b1ff2019-10-31 17:20:42 -070010126 if (numDevices == 0 || mDeviceId != deviceId) {
10127 if (isOutput()) {
10128 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
10129 mOutDeviceTypeAddrs = sinkDeviceTypeAddrs;
jiabin0a957d32020-04-29 10:56:20 -070010130 checkSilentMode_l();
jiabinc52b1ff2019-10-31 17:20:42 -070010131 } else {
10132 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
10133 mInDeviceTypeAddr = sourceDeviceTypeAddr;
10134 }
Phil Burk7f6b40d2017-02-09 13:18:38 -080010135 sp<MmapStreamCallback> callback = mCallback.promote();
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010136 if (mDeviceId != deviceId && callback != 0) {
Eric Laurent734046e2018-04-16 14:50:52 -070010137 mLock.unlock();
Phil Burk7f6b40d2017-02-09 13:18:38 -080010138 callback->onRoutingChanged(deviceId);
Eric Laurent734046e2018-04-16 14:50:52 -070010139 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010140 }
jiabinc52b1ff2019-10-31 17:20:42 -070010141 mPatch = *patch;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010142 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010143 }
Eric Laurentdda206a2022-07-08 17:28:35 +020010144 // Force meteadata update after a route change
10145 mActiveTracks.setHasChanged();
10146
Eric Laurent6acd1d42017-01-04 14:23:29 -080010147 return status;
10148}
10149
10150status_t AudioFlinger::MmapThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
10151{
10152 status_t status = NO_ERROR;
10153
jiabinc52b1ff2019-10-31 17:20:42 -070010154 mPatch = audio_patch{};
10155 mOutDeviceTypeAddrs.clear();
10156 mInDeviceTypeAddr.reset();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010157
10158 bool supportsAudioPatches = mHalDevice->supportsAudioPatches(&supportsAudioPatches) == OK ?
10159 supportsAudioPatches : false;
10160
10161 if (supportsAudioPatches) {
10162 status = mHalDevice->releaseAudioPatch(handle);
10163 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010164 status = mHalStream->legacyReleaseAudioPatch();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010165 }
Eric Laurentdda206a2022-07-08 17:28:35 +020010166 // Force meteadata update after a route change
10167 mActiveTracks.setHasChanged();
10168
Eric Laurent6acd1d42017-01-04 14:23:29 -080010169 return status;
10170}
10171
Mikhail Naganovdc769682018-05-04 15:34:08 -070010172void AudioFlinger::MmapThread::toAudioPortConfig(struct audio_port_config *config)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010173{
Mikhail Naganovdc769682018-05-04 15:34:08 -070010174 ThreadBase::toAudioPortConfig(config);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010175 if (isOutput()) {
10176 config->role = AUDIO_PORT_ROLE_SOURCE;
10177 config->ext.mix.hw_module = mAudioHwDev->handle();
10178 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
10179 } else {
10180 config->role = AUDIO_PORT_ROLE_SINK;
10181 config->ext.mix.hw_module = mAudioHwDev->handle();
10182 config->ext.mix.usecase.source = mAudioSource;
10183 }
10184}
10185
10186status_t AudioFlinger::MmapThread::addEffectChain_l(const sp<EffectChain>& chain)
10187{
10188 audio_session_t session = chain->sessionId();
10189
10190 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
10191 // Attach all tracks with same session ID to this chain.
10192 // indicate all active tracks in the chain
10193 for (const sp<MmapTrack> &track : mActiveTracks) {
10194 if (session == track->sessionId()) {
10195 chain->incTrackCnt();
10196 chain->incActiveTrackCnt();
10197 }
10198 }
10199
10200 chain->setThread(this);
10201 chain->setInBuffer(nullptr);
10202 chain->setOutBuffer(nullptr);
10203 chain->syncHalEffectsState();
10204
10205 mEffectChains.add(chain);
10206 checkSuspendOnAddEffectChain_l(chain);
10207 return NO_ERROR;
10208}
10209
10210size_t AudioFlinger::MmapThread::removeEffectChain_l(const sp<EffectChain>& chain)
10211{
10212 audio_session_t session = chain->sessionId();
10213
10214 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
10215
10216 for (size_t i = 0; i < mEffectChains.size(); i++) {
10217 if (chain == mEffectChains[i]) {
10218 mEffectChains.removeAt(i);
10219 // detach all active tracks from the chain
10220 // detach all tracks with same session ID from this chain
10221 for (const sp<MmapTrack> &track : mActiveTracks) {
10222 if (session == track->sessionId()) {
10223 chain->decActiveTrackCnt();
10224 chain->decTrackCnt();
10225 }
10226 }
10227 break;
10228 }
10229 }
10230 return mEffectChains.size();
10231}
10232
Eric Laurent6acd1d42017-01-04 14:23:29 -080010233void AudioFlinger::MmapThread::threadLoop_standby()
10234{
10235 mHalStream->standby();
10236}
10237
10238void AudioFlinger::MmapThread::threadLoop_exit()
10239{
Phil Burk7dce7282017-09-27 13:51:41 -070010240 // Do not call callback->onTearDown() because it is redundant for thread exit
10241 // and because it can cause a recursive mutex lock on stop().
Eric Laurent6acd1d42017-01-04 14:23:29 -080010242}
10243
10244status_t AudioFlinger::MmapThread::setSyncEvent(const sp<SyncEvent>& event __unused)
10245{
10246 return BAD_VALUE;
10247}
10248
10249bool AudioFlinger::MmapThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
10250{
10251 return false;
10252}
10253
10254status_t AudioFlinger::MmapThread::checkEffectCompatibility_l(
10255 const effect_descriptor_t *desc, audio_session_t sessionId)
10256{
10257 // No global effect sessions on mmap threads
Eric Laurent3f75a5b2019-11-12 15:55:51 -080010258 if (audio_is_global_session(sessionId)) {
10259 ALOGW("checkEffectCompatibility_l(): global effect %s on MMAP thread %s",
Eric Laurent6acd1d42017-01-04 14:23:29 -080010260 desc->name, mThreadName);
10261 return BAD_VALUE;
10262 }
10263
10264 if (!isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC)) {
10265 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on capture mmap thread",
10266 desc->name);
10267 return BAD_VALUE;
10268 }
10269 if (isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Glenn Kastend3bb6452016-12-05 18:14:37 -080010270 ALOGW("checkEffectCompatibility_l(): pre processing effect %s created on playback mmap "
10271 "thread", desc->name);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010272 return BAD_VALUE;
10273 }
10274
10275 // Only allow effects without processing load or latency
10276 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) != EFFECT_FLAG_NO_PROCESS) {
10277 return BAD_VALUE;
10278 }
10279
jiabineb3bda02020-06-30 14:07:03 -070010280 if (EffectModule::isHapticGenerator(&desc->type)) {
10281 ALOGE("%s(): HapticGenerator is not supported for MmapThread", __func__);
10282 return BAD_VALUE;
10283 }
10284
Eric Laurent6acd1d42017-01-04 14:23:29 -080010285 return NO_ERROR;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010286}
10287
10288void AudioFlinger::MmapThread::checkInvalidTracks_l()
10289{
jiabindfa32482022-10-06 19:45:50 +000010290 std::vector<audio_port_handle_t> invalidPortIds;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010291 for (const sp<MmapTrack> &track : mActiveTracks) {
10292 if (track->isInvalid()) {
jiabindfa32482022-10-06 19:45:50 +000010293 invalidPortIds.push_back(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010294 }
10295 }
jiabindfa32482022-10-06 19:45:50 +000010296 if (invalidPortIds.empty()) {
10297 return;
10298 }
10299 sp<MmapStreamCallback> callback = mCallback.promote();
10300 if (callback == nullptr) {
10301 if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
10302 ALOGW("Could not notify MMAP stream tear down: no onTearDown callback!");
10303 mNoCallbackWarningCount++;
10304 }
10305 return;
10306 }
10307 mLock.unlock();
10308 for (const auto invalidPortId : invalidPortIds) {
10309 callback->onTearDown(invalidPortId);
10310 }
10311 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010312}
10313
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -070010314void AudioFlinger::MmapThread::dumpInternals_l(int fd, const Vector<String16>& args __unused)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010315{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010316 dprintf(fd, " Attributes: content type %d usage %d source %d\n",
10317 mAttr.content_type, mAttr.usage, mAttr.source);
10318 dprintf(fd, " Session: %d port Id: %d\n", mSessionId, mPortId);
Eric Tan39ec8d62018-07-24 09:49:29 -070010319 if (mActiveTracks.isEmpty()) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010320 dprintf(fd, " No active clients\n");
10321 }
10322}
10323
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -070010324void AudioFlinger::MmapThread::dumpTracks_l(int fd, const Vector<String16>& args __unused)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010325{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010326 String8 result;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010327 size_t numtracks = mActiveTracks.size();
Andy Hung2c6c3bb2017-06-16 14:01:45 -070010328 dprintf(fd, " %zu Tracks\n", numtracks);
10329 const char *prefix = " ";
Eric Laurent6acd1d42017-01-04 14:23:29 -080010330 if (numtracks) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -070010331 result.append(prefix);
Kevin Rocard5f2136e2018-05-11 22:03:00 -070010332 mActiveTracks[0]->appendDumpHeader(result);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010333 for (size_t i = 0; i < numtracks ; ++i) {
10334 sp<MmapTrack> track = mActiveTracks[i];
Andy Hung2c6c3bb2017-06-16 14:01:45 -070010335 result.append(prefix);
10336 track->appendDump(result, true /* active */);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010337 }
10338 } else {
10339 dprintf(fd, "\n");
10340 }
10341 write(fd, result.string(), result.size());
10342}
10343
10344AudioFlinger::MmapPlaybackThread::MmapPlaybackThread(
10345 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
jiabinc52b1ff2019-10-31 17:20:42 -070010346 AudioHwDevice *hwDev, AudioStreamOut *output, bool systemReady)
Andy Hungcf10d742020-04-28 15:38:24 -070010347 : MmapThread(audioFlinger, id, hwDev, output->stream, systemReady, true /* isOut */),
Eric Laurent6acd1d42017-01-04 14:23:29 -080010348 mStreamType(AUDIO_STREAM_MUSIC),
Phil Burk56ecf3e2018-03-12 15:38:17 -070010349 mStreamVolume(1.0),
10350 mStreamMute(false),
Phil Burk56ecf3e2018-03-12 15:38:17 -070010351 mOutput(output)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010352{
10353 snprintf(mThreadName, kThreadNameLength, "AudioMmapOut_%X", id);
10354 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
10355 mMasterVolume = audioFlinger->masterVolume_l();
10356 mMasterMute = audioFlinger->masterMute_l();
10357 if (mAudioHwDev) {
10358 if (mAudioHwDev->canSetMasterVolume()) {
10359 mMasterVolume = 1.0;
10360 }
10361
10362 if (mAudioHwDev->canSetMasterMute()) {
10363 mMasterMute = false;
10364 }
10365 }
10366}
10367
10368void AudioFlinger::MmapPlaybackThread::configure(const audio_attributes_t *attr,
10369 audio_stream_type_t streamType,
10370 audio_session_t sessionId,
10371 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010372 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010373 audio_port_handle_t portId)
10374{
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010375 MmapThread::configure(attr, streamType, sessionId, callback, deviceId, portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010376 mStreamType = streamType;
10377}
10378
10379AudioStreamOut* AudioFlinger::MmapPlaybackThread::clearOutput()
10380{
10381 Mutex::Autolock _l(mLock);
10382 AudioStreamOut *output = mOutput;
10383 mOutput = NULL;
10384 return output;
10385}
10386
10387void AudioFlinger::MmapPlaybackThread::setMasterVolume(float value)
10388{
10389 Mutex::Autolock _l(mLock);
10390 // Don't apply master volume in SW if our HAL can do it for us.
10391 if (mAudioHwDev &&
10392 mAudioHwDev->canSetMasterVolume()) {
10393 mMasterVolume = 1.0;
10394 } else {
10395 mMasterVolume = value;
10396 }
10397}
10398
10399void AudioFlinger::MmapPlaybackThread::setMasterMute(bool muted)
10400{
10401 Mutex::Autolock _l(mLock);
10402 // Don't apply master mute in SW if our HAL can do it for us.
10403 if (mAudioHwDev && mAudioHwDev->canSetMasterMute()) {
10404 mMasterMute = false;
10405 } else {
10406 mMasterMute = muted;
10407 }
10408}
10409
10410void AudioFlinger::MmapPlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
10411{
10412 Mutex::Autolock _l(mLock);
10413 if (stream == mStreamType) {
10414 mStreamVolume = value;
10415 broadcast_l();
10416 }
10417}
10418
10419float AudioFlinger::MmapPlaybackThread::streamVolume(audio_stream_type_t stream) const
10420{
10421 Mutex::Autolock _l(mLock);
10422 if (stream == mStreamType) {
10423 return mStreamVolume;
10424 }
10425 return 0.0f;
10426}
10427
10428void AudioFlinger::MmapPlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
10429{
10430 Mutex::Autolock _l(mLock);
10431 if (stream == mStreamType) {
10432 mStreamMute= muted;
10433 broadcast_l();
10434 }
10435}
10436
10437void AudioFlinger::MmapPlaybackThread::invalidateTracks(audio_stream_type_t streamType)
10438{
10439 Mutex::Autolock _l(mLock);
10440 if (streamType == mStreamType) {
10441 for (const sp<MmapTrack> &track : mActiveTracks) {
10442 track->invalidate();
10443 }
10444 broadcast_l();
10445 }
10446}
10447
10448void AudioFlinger::MmapPlaybackThread::processVolume_l()
10449{
10450 float volume;
10451
10452 if (mMasterMute || mStreamMute) {
10453 volume = 0;
10454 } else {
10455 volume = mMasterVolume * mStreamVolume;
10456 }
10457
10458 if (volume != mHalVolFloat) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010459
10460 // Convert volumes from float to 8.24
10461 uint32_t vol = (uint32_t)(volume * (1 << 24));
10462
10463 // Delegate volume control to effect in track effect chain if needed
10464 // only one effect chain can be present on DirectOutputThread, so if
10465 // there is one, the track is connected to it
10466 if (!mEffectChains.isEmpty()) {
10467 mEffectChains[0]->setVolume_l(&vol, &vol);
10468 volume = (float)vol / (1 << 24);
10469 }
Eric Laurentdff774a2017-04-21 15:29:38 -070010470 // Try to use HW volume control and fall back to SW control if not implemented
Phil Burk56ecf3e2018-03-12 15:38:17 -070010471 if (mOutput->stream->setVolume(volume, volume) == NO_ERROR) {
10472 mHalVolFloat = volume; // HW volume control worked, so update value.
10473 mNoCallbackWarningCount = 0;
10474 } else {
Eric Laurentdff774a2017-04-21 15:29:38 -070010475 sp<MmapStreamCallback> callback = mCallback.promote();
10476 if (callback != 0) {
Phil Burk56ecf3e2018-03-12 15:38:17 -070010477 mHalVolFloat = volume; // SW volume control worked, so update value.
10478 mNoCallbackWarningCount = 0;
Eric Laurent734046e2018-04-16 14:50:52 -070010479 mLock.unlock();
Robert Wu4389ae62022-02-17 18:39:41 +000010480 callback->onVolumeChanged(volume);
Eric Laurent734046e2018-04-16 14:50:52 -070010481 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010482 } else {
Phil Burk56ecf3e2018-03-12 15:38:17 -070010483 if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
10484 ALOGW("Could not set MMAP stream volume: no volume callback!");
10485 mNoCallbackWarningCount++;
10486 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010487 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010488 }
Jasmine Chaeaa10e42021-05-11 10:11:14 +080010489 for (const sp<MmapTrack> &track : mActiveTracks) {
10490 track->setMetadataHasChanged();
Vlad Popaec1788e2022-08-04 11:23:30 +020010491 track->processMuteEvent_l(mAudioFlinger->getOrCreateAudioManager(),
10492 /*muteState=*/{mMasterMute,
10493 mStreamVolume == 0.f,
10494 mStreamMute,
10495 // TODO(b/241533526): adjust logic to include mute from AppOps
10496 false /*muteFromPlaybackRestricted*/,
10497 false /*muteFromClientVolume*/,
10498 false /*muteFromVolumeShaper*/});
Jasmine Chaeaa10e42021-05-11 10:11:14 +080010499 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010500 }
10501}
10502
Kevin Rocard069c2712018-03-29 19:09:14 -070010503void AudioFlinger::MmapPlaybackThread::updateMetadata_l()
10504{
Jasmine Chaeaa10e42021-05-11 10:11:14 +080010505 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
10506 return; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -070010507 }
10508 StreamOutHalInterface::SourceMetadata metadata;
10509 for (const sp<MmapTrack> &track : mActiveTracks) {
10510 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurent94579172020-11-20 18:41:04 +010010511 playback_track_metadata_v7_t trackMetadata;
10512 trackMetadata.base = {
Kevin Rocard069c2712018-03-29 19:09:14 -070010513 .usage = track->attributes().usage,
10514 .content_type = track->attributes().content_type,
10515 .gain = mHalVolFloat, // TODO: propagate from aaudio pre-mix volume
Eric Laurent94579172020-11-20 18:41:04 +010010516 };
10517 trackMetadata.channel_mask = track->channelMask(),
10518 strncpy(trackMetadata.tags, track->attributes().tags, AUDIO_ATTRIBUTES_TAGS_MAX_SIZE);
10519 metadata.tracks.push_back(trackMetadata);
Kevin Rocard069c2712018-03-29 19:09:14 -070010520 }
10521 mOutput->stream->updateSourceMetadata(metadata);
10522}
10523
Eric Laurent6acd1d42017-01-04 14:23:29 -080010524void AudioFlinger::MmapPlaybackThread::checkSilentMode_l()
10525{
10526 if (!mMasterMute) {
10527 char value[PROPERTY_VALUE_MAX];
10528 if (property_get("ro.audio.silent", value, "0") > 0) {
10529 char *endptr;
10530 unsigned long ul = strtoul(value, &endptr, 0);
10531 if (*endptr == '\0' && ul != 0) {
10532 ALOGD("Silence is golden");
10533 // The setprop command will not allow a property to be changed after
10534 // the first time it is set, so we don't have to worry about un-muting.
10535 setMasterMute_l(true);
10536 }
10537 }
10538 }
10539}
10540
Mikhail Naganov32abc2b2018-05-24 12:57:11 -070010541void AudioFlinger::MmapPlaybackThread::toAudioPortConfig(struct audio_port_config *config)
10542{
10543 MmapThread::toAudioPortConfig(config);
10544 if (mOutput && mOutput->flags != AUDIO_OUTPUT_FLAG_NONE) {
10545 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
10546 config->flags.output = mOutput->flags;
10547 }
10548}
10549
jiabinb7d8c5a2020-08-26 17:24:52 -070010550status_t AudioFlinger::MmapPlaybackThread::getExternalPosition(uint64_t *position,
10551 int64_t *timeNanos)
10552{
10553 if (mOutput == nullptr) {
10554 return NO_INIT;
10555 }
10556 struct timespec timestamp;
10557 status_t status = mOutput->getPresentationPosition(position, &timestamp);
10558 if (status == NO_ERROR) {
10559 *timeNanos = timestamp.tv_sec * NANOS_PER_SECOND + timestamp.tv_nsec;
10560 }
10561 return status;
10562}
10563
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -070010564void AudioFlinger::MmapPlaybackThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010565{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -070010566 MmapThread::dumpInternals_l(fd, args);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010567
Glenn Kastend3bb6452016-12-05 18:14:37 -080010568 dprintf(fd, " Stream type: %d Stream volume: %f HAL volume: %f Stream mute %d\n",
10569 mStreamType, mStreamVolume, mHalVolFloat, mStreamMute);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010570 dprintf(fd, " Master volume: %f Master mute %d\n", mMasterVolume, mMasterMute);
10571}
10572
10573AudioFlinger::MmapCaptureThread::MmapCaptureThread(
10574 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
jiabinc52b1ff2019-10-31 17:20:42 -070010575 AudioHwDevice *hwDev, AudioStreamIn *input, bool systemReady)
Andy Hungcf10d742020-04-28 15:38:24 -070010576 : MmapThread(audioFlinger, id, hwDev, input->stream, systemReady, false /* isOut */),
Eric Laurent6acd1d42017-01-04 14:23:29 -080010577 mInput(input)
10578{
10579 snprintf(mThreadName, kThreadNameLength, "AudioMmapIn_%X", id);
10580 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
10581}
10582
Eric Laurentdda206a2022-07-08 17:28:35 +020010583status_t AudioFlinger::MmapCaptureThread::exitStandby_l()
Eric Laurent331679c2018-04-16 17:03:16 -070010584{
Phil Burkf054fc32018-12-06 09:45:59 -080010585 {
10586 // mInput might have been cleared by clearInput()
Phil Burkf054fc32018-12-06 09:45:59 -080010587 if (mInput != nullptr && mInput->stream != nullptr) {
10588 mInput->stream->setGain(1.0f);
10589 }
10590 }
Eric Laurentdda206a2022-07-08 17:28:35 +020010591 return MmapThread::exitStandby_l();
Eric Laurent331679c2018-04-16 17:03:16 -070010592}
10593
Eric Laurent6acd1d42017-01-04 14:23:29 -080010594AudioFlinger::AudioStreamIn* AudioFlinger::MmapCaptureThread::clearInput()
10595{
10596 Mutex::Autolock _l(mLock);
10597 AudioStreamIn *input = mInput;
10598 mInput = NULL;
10599 return input;
10600}
Kevin Rocard069c2712018-03-29 19:09:14 -070010601
Eric Laurent331679c2018-04-16 17:03:16 -070010602
10603void AudioFlinger::MmapCaptureThread::processVolume_l()
10604{
10605 bool changed = false;
10606 bool silenced = false;
10607
10608 sp<MmapStreamCallback> callback = mCallback.promote();
10609 if (callback == 0) {
10610 if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
10611 ALOGW("Could not set MMAP stream silenced: no onStreamSilenced callback!");
10612 mNoCallbackWarningCount++;
10613 }
10614 }
10615
10616 // After a change occurred in track silenced state, mute capture in audio DSP if at least one
10617 // track is silenced and unmute otherwise
10618 for (size_t i = 0; i < mActiveTracks.size() && !silenced; i++) {
10619 if (!mActiveTracks[i]->getAndSetSilencedNotified_l()) {
10620 changed = true;
10621 silenced = mActiveTracks[i]->isSilenced_l();
10622 }
10623 }
10624
10625 if (changed) {
10626 mInput->stream->setGain(silenced ? 0.0f: 1.0f);
10627 }
10628}
10629
Kevin Rocard069c2712018-03-29 19:09:14 -070010630void AudioFlinger::MmapCaptureThread::updateMetadata_l()
10631{
Jasmine Chaeaa10e42021-05-11 10:11:14 +080010632 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
10633 return; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -070010634 }
10635 StreamInHalInterface::SinkMetadata metadata;
10636 for (const sp<MmapTrack> &track : mActiveTracks) {
10637 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurent94579172020-11-20 18:41:04 +010010638 record_track_metadata_v7_t trackMetadata;
10639 trackMetadata.base = {
Kevin Rocard069c2712018-03-29 19:09:14 -070010640 .source = track->attributes().source,
10641 .gain = 1, // capture tracks do not have volumes
Eric Laurent94579172020-11-20 18:41:04 +010010642 };
10643 trackMetadata.channel_mask = track->channelMask(),
10644 strncpy(trackMetadata.tags, track->attributes().tags, AUDIO_ATTRIBUTES_TAGS_MAX_SIZE);
10645 metadata.tracks.push_back(trackMetadata);
Kevin Rocard069c2712018-03-29 19:09:14 -070010646 }
10647 mInput->stream->updateSinkMetadata(metadata);
10648}
10649
Eric Laurent5ada82e2019-08-29 17:53:54 -070010650void AudioFlinger::MmapCaptureThread::setRecordSilenced(audio_port_handle_t portId, bool silenced)
Eric Laurent331679c2018-04-16 17:03:16 -070010651{
10652 Mutex::Autolock _l(mLock);
10653 for (size_t i = 0; i < mActiveTracks.size() ; i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -070010654 if (mActiveTracks[i]->portId() == portId) {
Eric Laurent331679c2018-04-16 17:03:16 -070010655 mActiveTracks[i]->setSilenced_l(silenced);
10656 broadcast_l();
10657 }
10658 }
jiabin09609032022-06-15 19:26:01 +000010659 setClientSilencedIfExists_l(portId, silenced);
Eric Laurent331679c2018-04-16 17:03:16 -070010660}
10661
Mikhail Naganov32abc2b2018-05-24 12:57:11 -070010662void AudioFlinger::MmapCaptureThread::toAudioPortConfig(struct audio_port_config *config)
10663{
10664 MmapThread::toAudioPortConfig(config);
10665 if (mInput && mInput->flags != AUDIO_INPUT_FLAG_NONE) {
10666 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
10667 config->flags.input = mInput->flags;
10668 }
10669}
10670
jiabinb7d8c5a2020-08-26 17:24:52 -070010671status_t AudioFlinger::MmapCaptureThread::getExternalPosition(
10672 uint64_t *position, int64_t *timeNanos)
10673{
10674 if (mInput == nullptr) {
10675 return NO_INIT;
10676 }
10677 return mInput->getCapturePosition((int64_t*)position, timeNanos);
10678}
10679
Glenn Kasten63238ef2015-03-02 15:50:29 -080010680} // namespace android