blob: 69c7934164d5693f7a8f01fddd7d9fee72963dda [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();
Eric Laurent52568142022-10-28 11:23:28 +0200794 configChanged = oldDevices != newDevices;
jiabinc52b1ff2019-10-31 17:20:42 -0700795 mLocalLog.log("CFG_EVENT_CREATE_AUDIO_PATCH: old device %s (%s) new device %s (%s)",
796 dumpDeviceTypes(oldDevices).c_str(), toString(oldDevices).c_str(),
797 dumpDeviceTypes(newDevices).c_str(), toString(newDevices).c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -0700798 } break;
799 case CFG_EVENT_RELEASE_AUDIO_PATCH: {
jiabinc52b1ff2019-10-31 17:20:42 -0700800 const DeviceTypeSet oldDevices = getDeviceTypes();
Eric Laurent1c333e22014-05-20 10:48:17 -0700801 ReleaseAudioPatchConfigEventData *data =
802 (ReleaseAudioPatchConfigEventData *)event->mData.get();
803 event->mStatus = releaseAudioPatch_l(data->mHandle);
jiabinc52b1ff2019-10-31 17:20:42 -0700804 const DeviceTypeSet newDevices = getDeviceTypes();
Eric Laurent52568142022-10-28 11:23:28 +0200805 configChanged = oldDevices != newDevices;
jiabinc52b1ff2019-10-31 17:20:42 -0700806 mLocalLog.log("CFG_EVENT_RELEASE_AUDIO_PATCH: old device %s (%s) new device %s (%s)",
807 dumpDeviceTypes(oldDevices).c_str(), toString(oldDevices).c_str(),
808 dumpDeviceTypes(newDevices).c_str(), toString(newDevices).c_str());
809 } break;
810 case CFG_EVENT_UPDATE_OUT_DEVICE: {
811 UpdateOutDevicesConfigEventData *data =
812 (UpdateOutDevicesConfigEventData *)event->mData.get();
813 updateOutDevices(data->mOutDevices);
Eric Laurent1c333e22014-05-20 10:48:17 -0700814 } break;
Eric Laurentec376dc2021-04-08 20:41:22 +0200815 case CFG_EVENT_RESIZE_BUFFER: {
816 ResizeBufferConfigEventData *data =
817 (ResizeBufferConfigEventData *)event->mData.get();
818 resizeInputBuffer_l(data->mMaxSharedAudioHistoryMs);
819 } break;
Eric Laurentb3f315a2021-07-13 15:09:05 +0200820
821 case CFG_EVENT_CHECK_OUTPUT_STAGE_EFFECTS: {
822 setCheckOutputStageEffects();
823 } break;
824
Eric Laurent68a40a82022-05-03 18:15:04 +0200825 case CFG_EVENT_HAL_LATENCY_MODES_CHANGED: {
826 onHalLatencyModesChanged_l();
827 } break;
828
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700829 default:
Eric Laurent10351942014-05-08 18:49:52 -0700830 ALOG_ASSERT(false, "processConfigEvents_l() unknown event type %d", event->mType);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700831 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800832 }
Eric Laurent10351942014-05-08 18:49:52 -0700833 {
834 Mutex::Autolock _l(event->mLock);
835 if (event->mWaitStatus) {
836 event->mWaitStatus = false;
837 event->mCond.signal();
838 }
839 }
840 ALOGV_IF(mConfigEvents.isEmpty(), "processConfigEvents_l() DONE thread %p", this);
841 }
842
843 if (configChanged) {
844 cacheParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800845 }
Eric Laurent81784c32012-11-19 14:55:58 -0800846}
847
Marco Nelissenb2208842014-02-07 14:00:50 -0800848String8 channelMaskToString(audio_channel_mask_t mask, bool output) {
849 String8 s;
Glenn Kastene1635ec2015-06-08 15:46:49 -0700850 const audio_channel_representation_t representation =
851 audio_channel_mask_get_representation(mask);
Andy Hungf98ec8d2015-05-19 12:53:24 -0700852
853 switch (representation) {
jiabin245cdd92018-12-07 17:55:15 -0800854 // Travel all single bit channel mask to convert channel mask to string.
Andy Hungf98ec8d2015-05-19 12:53:24 -0700855 case AUDIO_CHANNEL_REPRESENTATION_POSITION: {
856 if (output) {
857 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT) s.append("front-left, ");
858 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT) s.append("front-right, ");
859 if (mask & AUDIO_CHANNEL_OUT_FRONT_CENTER) s.append("front-center, ");
Andy Hungfba71252021-05-07 11:58:32 -0700860 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY) s.append("low-frequency, ");
Andy Hungf98ec8d2015-05-19 12:53:24 -0700861 if (mask & AUDIO_CHANNEL_OUT_BACK_LEFT) s.append("back-left, ");
862 if (mask & AUDIO_CHANNEL_OUT_BACK_RIGHT) s.append("back-right, ");
863 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT_OF_CENTER) s.append("front-left-of-center, ");
864 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT_OF_CENTER) s.append("front-right-of-center, ");
865 if (mask & AUDIO_CHANNEL_OUT_BACK_CENTER) s.append("back-center, ");
866 if (mask & AUDIO_CHANNEL_OUT_SIDE_LEFT) s.append("side-left, ");
867 if (mask & AUDIO_CHANNEL_OUT_SIDE_RIGHT) s.append("side-right, ");
868 if (mask & AUDIO_CHANNEL_OUT_TOP_CENTER) s.append("top-center ,");
869 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_LEFT) s.append("top-front-left, ");
870 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_CENTER) s.append("top-front-center, ");
871 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_RIGHT) s.append("top-front-right, ");
872 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_LEFT) s.append("top-back-left, ");
Andy Hungae81b4c2021-05-07 08:54:28 -0700873 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_CENTER) s.append("top-back-center, ");
874 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_RIGHT) s.append("top-back-right, ");
875 if (mask & AUDIO_CHANNEL_OUT_TOP_SIDE_LEFT) s.append("top-side-left, ");
876 if (mask & AUDIO_CHANNEL_OUT_TOP_SIDE_RIGHT) s.append("top-side-right, ");
877 if (mask & AUDIO_CHANNEL_OUT_BOTTOM_FRONT_LEFT) s.append("bottom-front-left, ");
878 if (mask & AUDIO_CHANNEL_OUT_BOTTOM_FRONT_CENTER) s.append("bottom-front-center, ");
879 if (mask & AUDIO_CHANNEL_OUT_BOTTOM_FRONT_RIGHT) s.append("bottom-front-right, ");
Andy Hungfba71252021-05-07 11:58:32 -0700880 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY_2) s.append("low-frequency-2, ");
Andy Hungae81b4c2021-05-07 08:54:28 -0700881 if (mask & AUDIO_CHANNEL_OUT_HAPTIC_B) s.append("haptic-B, ");
882 if (mask & AUDIO_CHANNEL_OUT_HAPTIC_A) s.append("haptic-A, ");
Andy Hungf98ec8d2015-05-19 12:53:24 -0700883 if (mask & ~AUDIO_CHANNEL_OUT_ALL) s.append("unknown, ");
884 } else {
885 if (mask & AUDIO_CHANNEL_IN_LEFT) s.append("left, ");
886 if (mask & AUDIO_CHANNEL_IN_RIGHT) s.append("right, ");
887 if (mask & AUDIO_CHANNEL_IN_FRONT) s.append("front, ");
888 if (mask & AUDIO_CHANNEL_IN_BACK) s.append("back, ");
889 if (mask & AUDIO_CHANNEL_IN_LEFT_PROCESSED) s.append("left-processed, ");
890 if (mask & AUDIO_CHANNEL_IN_RIGHT_PROCESSED) s.append("right-processed, ");
891 if (mask & AUDIO_CHANNEL_IN_FRONT_PROCESSED) s.append("front-processed, ");
892 if (mask & AUDIO_CHANNEL_IN_BACK_PROCESSED) s.append("back-processed, ");
893 if (mask & AUDIO_CHANNEL_IN_PRESSURE) s.append("pressure, ");
894 if (mask & AUDIO_CHANNEL_IN_X_AXIS) s.append("X, ");
895 if (mask & AUDIO_CHANNEL_IN_Y_AXIS) s.append("Y, ");
896 if (mask & AUDIO_CHANNEL_IN_Z_AXIS) s.append("Z, ");
Mikhail Naganovc9948492018-05-10 17:25:28 -0700897 if (mask & AUDIO_CHANNEL_IN_BACK_LEFT) s.append("back-left, ");
898 if (mask & AUDIO_CHANNEL_IN_BACK_RIGHT) s.append("back-right, ");
899 if (mask & AUDIO_CHANNEL_IN_CENTER) s.append("center, ");
Andy Hungfba71252021-05-07 11:58:32 -0700900 if (mask & AUDIO_CHANNEL_IN_LOW_FREQUENCY) s.append("low-frequency, ");
Andy Hungae81b4c2021-05-07 08:54:28 -0700901 if (mask & AUDIO_CHANNEL_IN_TOP_LEFT) s.append("top-left, ");
902 if (mask & AUDIO_CHANNEL_IN_TOP_RIGHT) s.append("top-right, ");
Andy Hungf98ec8d2015-05-19 12:53:24 -0700903 if (mask & AUDIO_CHANNEL_IN_VOICE_UPLINK) s.append("voice-uplink, ");
904 if (mask & AUDIO_CHANNEL_IN_VOICE_DNLINK) s.append("voice-dnlink, ");
905 if (mask & ~AUDIO_CHANNEL_IN_ALL) s.append("unknown, ");
906 }
907 const int len = s.length();
908 if (len > 2) {
Glenn Kasten57c4e6f2016-03-18 14:54:07 -0700909 (void) s.lockBuffer(len); // needed?
Andy Hungf98ec8d2015-05-19 12:53:24 -0700910 s.unlockBuffer(len - 2); // remove trailing ", "
911 }
912 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -0800913 }
Andy Hungf98ec8d2015-05-19 12:53:24 -0700914 case AUDIO_CHANNEL_REPRESENTATION_INDEX:
915 s.appendFormat("index mask, bits:%#x", audio_channel_mask_get_bits(mask));
916 return s;
917 default:
918 s.appendFormat("unknown mask, representation:%d bits:%#x",
919 representation, audio_channel_mask_get_bits(mask));
920 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -0800921 }
Marco Nelissenb2208842014-02-07 14:00:50 -0800922}
923
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -0700924void AudioFlinger::ThreadBase::dump(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -0800925{
Glenn Kasten1bfe09a2017-02-21 13:05:56 -0800926 dprintf(fd, "\n%s thread %p, name %s, tid %d, type %d (%s):\n", isOutput() ? "Output" : "Input",
927 this, mThreadName, getTid(), type(), threadTypeToString(type()));
928
Eric Laurent81784c32012-11-19 14:55:58 -0800929 bool locked = AudioFlinger::dumpTryLock(mLock);
930 if (!locked) {
Glenn Kasten1bfe09a2017-02-21 13:05:56 -0800931 dprintf(fd, " Thread may be deadlocked\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800932 }
933
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -0700934 dumpBase_l(fd, args);
935 dumpInternals_l(fd, args);
936 dumpTracks_l(fd, args);
937 dumpEffectChains_l(fd, args);
938
939 if (locked) {
940 mLock.unlock();
941 }
942
943 dprintf(fd, " Local log:\n");
944 mLocalLog.dump(fd, " " /* prefix */, 40 /* lines */);
Andy Hungafc51db2022-04-08 17:33:40 -0700945
946 // --all does the statistics
947 bool dumpAll = false;
948 for (const auto &arg : args) {
949 if (arg == String16("--all")) {
950 dumpAll = true;
951 }
952 }
953 if (dumpAll || type() == SPATIALIZER) {
Andy Hung44d648b2022-04-08 17:33:40 -0700954 const std::string sched = mThreadSnapshot.toString();
Andy Hungafc51db2022-04-08 17:33:40 -0700955 if (!sched.empty()) {
956 (void)write(fd, sched.c_str(), sched.size());
957 }
958 }
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -0700959}
960
961void AudioFlinger::ThreadBase::dumpBase_l(int fd, const Vector<String16>& args __unused)
962{
Elliott Hughes87cebad2014-05-22 10:14:43 -0700963 dprintf(fd, " I/O handle: %d\n", mId);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700964 dprintf(fd, " Standby: %s\n", mStandby ? "yes" : "no");
Glenn Kasten97b7b752014-09-28 13:04:24 -0700965 dprintf(fd, " Sample rate: %u Hz\n", mSampleRate);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700966 dprintf(fd, " HAL frame count: %zu\n", mFrameCount);
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700967 dprintf(fd, " HAL format: 0x%x (%s)\n", mHALFormat, formatToString(mHALFormat).c_str());
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700968 dprintf(fd, " HAL buffer size: %zu bytes\n", mBufferSize);
Glenn Kasten97b7b752014-09-28 13:04:24 -0700969 dprintf(fd, " Channel count: %u\n", mChannelCount);
970 dprintf(fd, " Channel mask: 0x%08x (%s)\n", mChannelMask,
Marco Nelissenb2208842014-02-07 14:00:50 -0800971 channelMaskToString(mChannelMask, mType != RECORD).string());
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700972 dprintf(fd, " Processing format: 0x%x (%s)\n", mFormat, formatToString(mFormat).c_str());
Glenn Kastenf87c2f52015-08-21 08:03:57 -0700973 dprintf(fd, " Processing frame size: %zu bytes\n", mFrameSize);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700974 dprintf(fd, " Pending config events:");
Marco Nelissenb2208842014-02-07 14:00:50 -0800975 size_t numConfig = mConfigEvents.size();
976 if (numConfig) {
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -0700977 const size_t SIZE = 256;
978 char buffer[SIZE];
Marco Nelissenb2208842014-02-07 14:00:50 -0800979 for (size_t i = 0; i < numConfig; i++) {
980 mConfigEvents[i]->dump(buffer, SIZE);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700981 dprintf(fd, "\n %s", buffer);
Marco Nelissenb2208842014-02-07 14:00:50 -0800982 }
Elliott Hughes87cebad2014-05-22 10:14:43 -0700983 dprintf(fd, "\n");
Marco Nelissenb2208842014-02-07 14:00:50 -0800984 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -0700985 dprintf(fd, " none\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800986 }
Andy Hung293558a2017-03-21 12:19:20 -0700987 // Note: output device may be used by capture threads for effects such as AEC.
jiabinc52b1ff2019-10-31 17:20:42 -0700988 dprintf(fd, " Output devices: %s (%s)\n",
989 dumpDeviceTypes(outDeviceTypes()).c_str(), toString(outDeviceTypes()).c_str());
990 dprintf(fd, " Input device: %#x (%s)\n",
991 inDeviceType(), toString(inDeviceType()).c_str());
Andy Hung9b181952019-02-25 14:53:36 -0800992 dprintf(fd, " Audio source: %d (%s)\n", mAudioSource, toString(mAudioSource).c_str());
Eric Laurent81784c32012-11-19 14:55:58 -0800993
Andy Hung2e2c0bb2018-06-11 19:13:11 -0700994 // Dump timestamp statistics for the Thread types that support it.
995 if (mType == RECORD
996 || mType == MIXER
997 || mType == DUPLICATING
Andy Hungf3234512018-07-03 14:51:47 -0700998 || mType == DIRECT
Andy Hung4b7f54f2022-04-28 17:45:28 -0700999 || mType == OFFLOAD
1000 || mType == SPATIALIZER) {
Andy Hung2e2c0bb2018-06-11 19:13:11 -07001001 dprintf(fd, " Timestamp stats: %s\n", mTimestampVerifier.toString().c_str());
Andy Hungc8fddf32018-08-08 18:32:37 -07001002 dprintf(fd, " Timestamp corrected: %s\n", isTimestampCorrectionEnabled() ? "yes" : "no");
Andy Hung2e2c0bb2018-06-11 19:13:11 -07001003 }
1004
Andy Hung446f4df2019-02-21 12:26:41 -08001005 if (mLastIoBeginNs > 0) { // MMAP may not set this
1006 dprintf(fd, " Last %s occurred (msecs): %lld\n",
1007 isOutput() ? "write" : "read",
1008 (long long) (systemTime() - mLastIoBeginNs) / NANOS_PER_MILLISECOND);
1009 }
1010
1011 if (mProcessTimeMs.getN() > 0) {
1012 dprintf(fd, " Process time ms stats: %s\n", mProcessTimeMs.toString().c_str());
1013 }
1014
1015 if (mIoJitterMs.getN() > 0) {
1016 dprintf(fd, " Hal %s jitter ms stats: %s\n",
1017 isOutput() ? "write" : "read",
1018 mIoJitterMs.toString().c_str());
1019 }
1020
Andy Hunge6c37112019-02-26 17:38:10 -08001021 if (mLatencyMs.getN() > 0) {
1022 dprintf(fd, " Threadloop %s latency stats: %s\n",
1023 isOutput() ? "write" : "read",
1024 mLatencyMs.toString().c_str());
1025 }
Robert Wu06db0a32021-08-10 19:05:34 +00001026
1027 if (mMonopipePipeDepthStats.getN() > 0) {
1028 dprintf(fd, " Monopipe %s pipe depth stats: %s\n",
1029 isOutput() ? "write" : "read",
1030 mMonopipePipeDepthStats.toString().c_str());
1031 }
Eric Laurent81784c32012-11-19 14:55:58 -08001032}
1033
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001034void AudioFlinger::ThreadBase::dumpEffectChains_l(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -08001035{
1036 const size_t SIZE = 256;
1037 char buffer[SIZE];
Eric Laurent81784c32012-11-19 14:55:58 -08001038
Marco Nelissenb2208842014-02-07 14:00:50 -08001039 size_t numEffectChains = mEffectChains.size();
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +00001040 snprintf(buffer, SIZE, " %zu Effect Chains\n", numEffectChains);
Eric Laurent81784c32012-11-19 14:55:58 -08001041 write(fd, buffer, strlen(buffer));
1042
Marco Nelissenb2208842014-02-07 14:00:50 -08001043 for (size_t i = 0; i < numEffectChains; ++i) {
Eric Laurent81784c32012-11-19 14:55:58 -08001044 sp<EffectChain> chain = mEffectChains[i];
1045 if (chain != 0) {
1046 chain->dump(fd, args);
1047 }
1048 }
1049}
1050
Andy Hungdae27702016-10-31 14:01:16 -07001051void AudioFlinger::ThreadBase::acquireWakeLock()
Eric Laurent81784c32012-11-19 14:55:58 -08001052{
1053 Mutex::Autolock _l(mLock);
Andy Hungdae27702016-10-31 14:01:16 -07001054 acquireWakeLock_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001055}
1056
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001057String16 AudioFlinger::ThreadBase::getWakeLockTag()
1058{
1059 switch (mType) {
Glenn Kastenbcb14862015-03-05 17:11:21 -08001060 case MIXER:
1061 return String16("AudioMix");
1062 case DIRECT:
1063 return String16("AudioDirectOut");
1064 case DUPLICATING:
1065 return String16("AudioDup");
1066 case RECORD:
1067 return String16("AudioIn");
1068 case OFFLOAD:
1069 return String16("AudioOffload");
Andy Hungea840382020-05-05 21:50:17 -07001070 case MMAP_PLAYBACK:
1071 return String16("MmapPlayback");
1072 case MMAP_CAPTURE:
1073 return String16("MmapCapture");
Eric Laurent1c5e2e32021-08-18 18:50:28 +02001074 case SPATIALIZER:
1075 return String16("AudioSpatial");
Glenn Kastenbcb14862015-03-05 17:11:21 -08001076 default:
1077 ALOG_ASSERT(false);
1078 return String16("AudioUnknown");
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001079 }
1080}
1081
Andy Hungdae27702016-10-31 14:01:16 -07001082void AudioFlinger::ThreadBase::acquireWakeLock_l()
Eric Laurent81784c32012-11-19 14:55:58 -08001083{
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001084 getPowerManager_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001085 if (mPowerManager != 0) {
1086 sp<IBinder> binder = new BBinder();
Andy Hungdae27702016-10-31 14:01:16 -07001087 // Uses AID_AUDIOSERVER for wakelock. updateWakeLockUids_l() updates with client uids.
Chris Ye6597d732020-02-28 22:38:25 -08001088 binder::Status status = mPowerManager->acquireWakeLockAsync(binder,
1089 POWERMANAGER_PARTIAL_WAKE_LOCK,
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001090 getWakeLockTag(),
Marco Nelissendcb346b2015-09-09 10:47:29 -07001091 String16("audioserver"),
Chris Ye6597d732020-02-28 22:38:25 -08001092 {} /* workSource */,
1093 {} /* historyTag */);
1094 if (status.isOk()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001095 mWakeLockToken = binder;
1096 }
Chris Ye6597d732020-02-28 22:38:25 -08001097 ALOGV("acquireWakeLock_l() %s status %d", mThreadName, status.exceptionCode());
Eric Laurent81784c32012-11-19 14:55:58 -08001098 }
Wei Jia3f273d12015-11-24 09:06:49 -08001099
Andy Hung3f0c9022016-01-15 17:49:46 -08001100 gBoottime.acquire(mWakeLockToken);
Andy Hung818e7a32016-02-16 18:08:07 -08001101 mTimestamp.mTimebaseOffset[ExtendedTimestamp::TIMEBASE_BOOTTIME] =
1102 gBoottime.getBoottimeOffset();
Eric Laurent81784c32012-11-19 14:55:58 -08001103}
1104
1105void AudioFlinger::ThreadBase::releaseWakeLock()
1106{
1107 Mutex::Autolock _l(mLock);
1108 releaseWakeLock_l();
1109}
1110
1111void AudioFlinger::ThreadBase::releaseWakeLock_l()
1112{
Andy Hung3f0c9022016-01-15 17:49:46 -08001113 gBoottime.release(mWakeLockToken);
Eric Laurent81784c32012-11-19 14:55:58 -08001114 if (mWakeLockToken != 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -08001115 ALOGV("releaseWakeLock_l() %s", mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08001116 if (mPowerManager != 0) {
Chris Ye6597d732020-02-28 22:38:25 -08001117 mPowerManager->releaseWakeLockAsync(mWakeLockToken, 0);
Eric Laurent81784c32012-11-19 14:55:58 -08001118 }
1119 mWakeLockToken.clear();
1120 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001121}
1122
1123void AudioFlinger::ThreadBase::getPowerManager_l() {
Eric Laurent72e3f392015-05-20 14:43:50 -07001124 if (mSystemReady && mPowerManager == 0) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001125 // use checkService() to avoid blocking if power service is not up yet
1126 sp<IBinder> binder =
1127 defaultServiceManager()->checkService(String16("power"));
1128 if (binder == 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -08001129 ALOGW("Thread %s cannot connect to the power manager service", mThreadName);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001130 } else {
Chris Ye6597d732020-02-28 22:38:25 -08001131 mPowerManager = interface_cast<os::IPowerManager>(binder);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001132 binder->linkToDeath(mDeathRecipient);
1133 }
1134 }
1135}
1136
Andy Hungd01b0f12016-11-07 16:10:30 -08001137void AudioFlinger::ThreadBase::updateWakeLockUids_l(const SortedVector<uid_t> &uids) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001138 getPowerManager_l();
Andy Hungdae27702016-10-31 14:01:16 -07001139
1140#if !LOG_NDEBUG
1141 std::stringstream s;
Andy Hungd01b0f12016-11-07 16:10:30 -08001142 for (uid_t uid : uids) {
Andy Hungdae27702016-10-31 14:01:16 -07001143 s << uid << " ";
1144 }
1145 ALOGD("updateWakeLockUids_l %s uids:%s", mThreadName, s.str().c_str());
1146#endif
1147
Andy Hung438e7572015-12-14 15:51:17 -08001148 if (mWakeLockToken == NULL) { // token may be NULL if AudioFlinger::systemReady() not called.
1149 if (mSystemReady) {
1150 ALOGE("no wake lock to update, but system ready!");
1151 } else {
1152 ALOGW("no wake lock to update, system not ready yet");
1153 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001154 return;
1155 }
1156 if (mPowerManager != 0) {
Andy Hung1f12a8a2016-11-07 16:10:30 -08001157 std::vector<int> uidsAsInt(uids.begin(), uids.end()); // powermanager expects uids as ints
Chris Ye6597d732020-02-28 22:38:25 -08001158 binder::Status status = mPowerManager->updateWakeLockUidsAsync(
1159 mWakeLockToken, uidsAsInt);
1160 ALOGV("updateWakeLockUids_l() %s status %d", mThreadName, status.exceptionCode());
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001161 }
1162}
1163
Eric Laurent81784c32012-11-19 14:55:58 -08001164void AudioFlinger::ThreadBase::clearPowerManager()
1165{
1166 Mutex::Autolock _l(mLock);
1167 releaseWakeLock_l();
1168 mPowerManager.clear();
1169}
1170
jiabinc52b1ff2019-10-31 17:20:42 -07001171void AudioFlinger::ThreadBase::updateOutDevices(
1172 const DeviceDescriptorBaseVector& outDevices __unused)
1173{
1174 ALOGE("%s should only be called in RecordThread", __func__);
1175}
1176
Eric Laurentec376dc2021-04-08 20:41:22 +02001177void AudioFlinger::ThreadBase::resizeInputBuffer_l(int32_t maxSharedAudioHistoryMs __unused)
1178{
1179 ALOGE("%s should only be called in RecordThread", __func__);
1180}
1181
Glenn Kasten0f11b512014-01-31 16:18:54 -08001182void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001183{
1184 sp<ThreadBase> thread = mThread.promote();
1185 if (thread != 0) {
1186 thread->clearPowerManager();
1187 }
1188 ALOGW("power manager service died !!!");
1189}
1190
Eric Laurent81784c32012-11-19 14:55:58 -08001191void AudioFlinger::ThreadBase::setEffectSuspended_l(
Glenn Kastend848eb42016-03-08 13:42:11 -08001192 const effect_uuid_t *type, bool suspend, audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001193{
1194 sp<EffectChain> chain = getEffectChain_l(sessionId);
1195 if (chain != 0) {
1196 if (type != NULL) {
1197 chain->setEffectSuspended_l(type, suspend);
1198 } else {
1199 chain->setEffectSuspendedAll_l(suspend);
1200 }
1201 }
1202
1203 updateSuspendedSessions_l(type, suspend, sessionId);
1204}
1205
1206void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1207{
1208 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
1209 if (index < 0) {
1210 return;
1211 }
1212
1213 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
1214 mSuspendedSessions.valueAt(index);
1215
1216 for (size_t i = 0; i < sessionEffects.size(); i++) {
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07001217 const sp<SuspendedSessionDesc>& desc = sessionEffects.valueAt(i);
Eric Laurent81784c32012-11-19 14:55:58 -08001218 for (int j = 0; j < desc->mRefCount; j++) {
1219 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1220 chain->setEffectSuspendedAll_l(true);
1221 } else {
1222 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
1223 desc->mType.timeLow);
1224 chain->setEffectSuspended_l(&desc->mType, true);
1225 }
1226 }
1227 }
1228}
1229
1230void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1231 bool suspend,
Glenn Kastend848eb42016-03-08 13:42:11 -08001232 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001233{
1234 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
1235
1236 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1237
1238 if (suspend) {
1239 if (index >= 0) {
1240 sessionEffects = mSuspendedSessions.valueAt(index);
1241 } else {
1242 mSuspendedSessions.add(sessionId, sessionEffects);
1243 }
1244 } else {
1245 if (index < 0) {
1246 return;
1247 }
1248 sessionEffects = mSuspendedSessions.valueAt(index);
1249 }
1250
1251
1252 int key = EffectChain::kKeyForSuspendAll;
1253 if (type != NULL) {
1254 key = type->timeLow;
1255 }
1256 index = sessionEffects.indexOfKey(key);
1257
1258 sp<SuspendedSessionDesc> desc;
1259 if (suspend) {
1260 if (index >= 0) {
1261 desc = sessionEffects.valueAt(index);
1262 } else {
1263 desc = new SuspendedSessionDesc();
1264 if (type != NULL) {
1265 desc->mType = *type;
1266 }
1267 sessionEffects.add(key, desc);
1268 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
1269 }
1270 desc->mRefCount++;
1271 } else {
1272 if (index < 0) {
1273 return;
1274 }
1275 desc = sessionEffects.valueAt(index);
1276 if (--desc->mRefCount == 0) {
1277 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
1278 sessionEffects.removeItemsAt(index);
1279 if (sessionEffects.isEmpty()) {
1280 ALOGV("updateSuspendedSessions_l() restore removing session %d",
1281 sessionId);
1282 mSuspendedSessions.removeItem(sessionId);
1283 }
1284 }
1285 }
1286 if (!sessionEffects.isEmpty()) {
1287 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1288 }
1289}
1290
Eric Laurent6b446ce2019-12-13 10:56:31 -08001291void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(bool enabled,
1292 audio_session_t sessionId,
1293 bool threadLocked) {
1294 if (!threadLocked) {
1295 mLock.lock();
1296 }
Eric Laurent81784c32012-11-19 14:55:58 -08001297
Eric Laurent81784c32012-11-19 14:55:58 -08001298 if (mType != RECORD) {
1299 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1300 // another session. This gives the priority to well behaved effect control panels
1301 // and applications not using global effects.
1302 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
1303 // global effects
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001304 if (!audio_is_global_session(sessionId)) {
Eric Laurent81784c32012-11-19 14:55:58 -08001305 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1306 }
1307 }
1308
Eric Laurent6b446ce2019-12-13 10:56:31 -08001309 if (!threadLocked) {
1310 mLock.unlock();
Eric Laurent81784c32012-11-19 14:55:58 -08001311 }
1312}
1313
Eric Laurent4c415062016-06-17 16:14:16 -07001314// checkEffectCompatibility_l() must be called with ThreadBase::mLock held
1315status_t AudioFlinger::RecordThread::checkEffectCompatibility_l(
1316 const effect_descriptor_t *desc, audio_session_t sessionId)
1317{
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001318 // No global output effect sessions on record threads
1319 if (sessionId == AUDIO_SESSION_OUTPUT_MIX
1320 || sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Eric Laurent4c415062016-06-17 16:14:16 -07001321 ALOGW("checkEffectCompatibility_l(): global effect %s on record thread %s",
1322 desc->name, mThreadName);
1323 return BAD_VALUE;
1324 }
1325 // only pre processing effects on record thread
1326 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC) {
1327 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on record thread %s",
1328 desc->name, mThreadName);
1329 return BAD_VALUE;
1330 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001331
1332 // always allow effects without processing load or latency
1333 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1334 return NO_ERROR;
1335 }
1336
Eric Laurent4c415062016-06-17 16:14:16 -07001337 audio_input_flags_t flags = mInput->flags;
1338 if (hasFastCapture() || (flags & AUDIO_INPUT_FLAG_FAST)) {
1339 if (flags & AUDIO_INPUT_FLAG_RAW) {
1340 ALOGW("checkEffectCompatibility_l(): effect %s on record thread %s in raw mode",
1341 desc->name, mThreadName);
1342 return BAD_VALUE;
1343 }
1344 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1345 ALOGW("checkEffectCompatibility_l(): non HW effect %s on record thread %s in fast mode",
1346 desc->name, mThreadName);
1347 return BAD_VALUE;
1348 }
1349 }
jiabineb3bda02020-06-30 14:07:03 -07001350
1351 if (EffectModule::isHapticGenerator(&desc->type)) {
1352 ALOGE("%s(): HapticGenerator is not supported in RecordThread", __func__);
1353 return BAD_VALUE;
1354 }
Eric Laurent4c415062016-06-17 16:14:16 -07001355 return NO_ERROR;
1356}
1357
1358// checkEffectCompatibility_l() must be called with ThreadBase::mLock held
1359status_t AudioFlinger::PlaybackThread::checkEffectCompatibility_l(
1360 const effect_descriptor_t *desc, audio_session_t sessionId)
1361{
1362 // no preprocessing on playback threads
1363 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001364 ALOGW("%s: pre processing effect %s created on playback"
1365 " thread %s", __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001366 return BAD_VALUE;
1367 }
1368
Eric Laurent3e4de772017-07-16 16:55:08 -07001369 // always allow effects without processing load or latency
1370 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1371 return NO_ERROR;
1372 }
1373
jiabineb3bda02020-06-30 14:07:03 -07001374 if (EffectModule::isHapticGenerator(&desc->type) && mHapticChannelCount == 0) {
1375 ALOGW("%s: thread doesn't support haptic playback while the effect is HapticGenerator",
1376 __func__);
1377 return BAD_VALUE;
1378 }
1379
Eric Laurentf690c462021-09-17 14:47:03 +02001380 if (memcmp(&desc->type, FX_IID_SPATIALIZER, sizeof(effect_uuid_t)) == 0
1381 && mType != SPATIALIZER) {
1382 ALOGW("%s: attempt to create a spatializer effect on a thread of type %d",
1383 __func__, mType);
1384 return BAD_VALUE;
1385 }
1386
Eric Laurent4c415062016-06-17 16:14:16 -07001387 switch (mType) {
1388 case MIXER: {
Andy Hung9aad48c2017-11-29 10:29:19 -08001389#ifndef MULTICHANNEL_EFFECT_CHAIN
Eric Laurent4c415062016-06-17 16:14:16 -07001390 // Reject any effect on mixer multichannel sinks.
1391 // TODO: fix both format and multichannel issues with effects.
1392 if (mChannelCount != FCC_2) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001393 ALOGW("%s: effect %s for multichannel(%d) on MIXER thread %s",
1394 __func__, desc->name, mChannelCount, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001395 return BAD_VALUE;
1396 }
Andy Hung9aad48c2017-11-29 10:29:19 -08001397#endif
Eric Laurent4c415062016-06-17 16:14:16 -07001398 audio_output_flags_t flags = mOutput->flags;
1399 if (hasFastMixer() || (flags & AUDIO_OUTPUT_FLAG_FAST)) {
1400 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1401 // global effects are applied only to non fast tracks if they are SW
1402 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1403 break;
1404 }
1405 } else if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1406 // only post processing on output stage session
1407 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001408 ALOGW("%s: non post processing effect %s not allowed on output stage session",
1409 __func__, desc->name);
Eric Laurent4c415062016-06-17 16:14:16 -07001410 return BAD_VALUE;
1411 }
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001412 } else if (sessionId == AUDIO_SESSION_DEVICE) {
1413 // only post processing on output stage session
1414 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001415 ALOGW("%s: non post processing effect %s not allowed on device session",
1416 __func__, desc->name);
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001417 return BAD_VALUE;
1418 }
Eric Laurent4c415062016-06-17 16:14:16 -07001419 } else {
1420 // no restriction on effects applied on non fast tracks
1421 if ((hasAudioSession_l(sessionId) & ThreadBase::FAST_SESSION) == 0) {
1422 break;
1423 }
1424 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001425
Eric Laurent4c415062016-06-17 16:14:16 -07001426 if (flags & AUDIO_OUTPUT_FLAG_RAW) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001427 ALOGW("%s: effect %s on playback thread in raw mode", __func__, desc->name);
Eric Laurent4c415062016-06-17 16:14:16 -07001428 return BAD_VALUE;
1429 }
1430 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001431 ALOGW("%s: non HW effect %s on playback thread in fast mode",
1432 __func__, desc->name);
Eric Laurent4c415062016-06-17 16:14:16 -07001433 return BAD_VALUE;
1434 }
1435 }
1436 } break;
1437 case OFFLOAD:
Jean-Michel Trivi773ee952016-07-11 16:53:18 -07001438 // nothing actionable on offload threads, if the effect:
1439 // - is offloadable: the effect can be created
1440 // - is NOT offloadable: the effect should still be created, but EffectHandle::enable()
1441 // will take care of invalidating the tracks of the thread
Eric Laurent4c415062016-06-17 16:14:16 -07001442 break;
1443 case DIRECT:
1444 // Reject any effect on Direct output threads for now, since the format of
1445 // mSinkBuffer is not guaranteed to be compatible with effect processing (PCM 16 stereo).
Eric Laurentb62d0362021-10-26 17:40:18 +02001446 ALOGW("%s: effect %s on DIRECT output thread %s",
1447 __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001448 return BAD_VALUE;
1449 case DUPLICATING:
Andy Hung9aad48c2017-11-29 10:29:19 -08001450#ifndef MULTICHANNEL_EFFECT_CHAIN
Eric Laurent4c415062016-06-17 16:14:16 -07001451 // Reject any effect on mixer multichannel sinks.
1452 // TODO: fix both format and multichannel issues with effects.
1453 if (mChannelCount != FCC_2) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001454 ALOGW("%s: effect %s for multichannel(%d) on DUPLICATING thread %s",
1455 __func__, desc->name, mChannelCount, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001456 return BAD_VALUE;
1457 }
Andy Hung9aad48c2017-11-29 10:29:19 -08001458#endif
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001459 if (audio_is_global_session(sessionId)) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001460 ALOGW("%s: global effect %s on DUPLICATING thread %s",
1461 __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001462 return BAD_VALUE;
1463 }
1464 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001465 ALOGW("%s: post processing effect %s on DUPLICATING thread %s",
1466 __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001467 return BAD_VALUE;
1468 }
1469 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) != 0) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001470 ALOGW("%s: HW tunneled effect %s on DUPLICATING thread %s",
1471 __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001472 return BAD_VALUE;
1473 }
1474 break;
Eric Laurent1c5e2e32021-08-18 18:50:28 +02001475 case SPATIALIZER:
Eric Laurentb62d0362021-10-26 17:40:18 +02001476 // Global effects (AUDIO_SESSION_OUTPUT_MIX) are not supported on spatializer mixer
1477 // as there is no common accumulation buffer for sptialized and non sptialized tracks.
1478 // Post processing effects (AUDIO_SESSION_OUTPUT_STAGE or AUDIO_SESSION_DEVICE)
1479 // are supported and added after the spatializer.
1480 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1481 ALOGW("%s: global effect %s not supported on spatializer thread %s",
1482 __func__, desc->name, mThreadName);
Eric Laurentb3f315a2021-07-13 15:09:05 +02001483 return BAD_VALUE;
Eric Laurentb62d0362021-10-26 17:40:18 +02001484 } else if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1485 // only post processing , downmixer or spatializer effects on output stage session
1486 if (memcmp(&desc->type, FX_IID_SPATIALIZER, sizeof(effect_uuid_t)) == 0
1487 || memcmp(&desc->type, EFFECT_UIID_DOWNMIX, sizeof(effect_uuid_t)) == 0) {
1488 break;
1489 }
1490 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
1491 ALOGW("%s: non post processing effect %s not allowed on output stage session",
1492 __func__, desc->name);
1493 return BAD_VALUE;
1494 }
1495 } else if (sessionId == AUDIO_SESSION_DEVICE) {
1496 // only post processing on output stage session
1497 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
1498 ALOGW("%s: non post processing effect %s not allowed on device session",
1499 __func__, desc->name);
1500 return BAD_VALUE;
1501 }
Eric Laurentb3f315a2021-07-13 15:09:05 +02001502 }
1503 break;
Eric Laurent4c415062016-06-17 16:14:16 -07001504 default:
1505 LOG_ALWAYS_FATAL("checkEffectCompatibility_l(): wrong thread type %d", mType);
1506 }
1507
1508 return NO_ERROR;
1509}
1510
Eric Laurent81784c32012-11-19 14:55:58 -08001511// ThreadBase::createEffect_l() must be called with AudioFlinger::mLock held
1512sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
1513 const sp<AudioFlinger::Client>& client,
1514 const sp<IEffectClient>& effectClient,
1515 int32_t priority,
Glenn Kastend848eb42016-03-08 13:42:11 -08001516 audio_session_t sessionId,
Eric Laurent81784c32012-11-19 14:55:58 -08001517 effect_descriptor_t *desc,
1518 int *enabled,
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001519 status_t *status,
Eric Laurent2fe0acd2020-03-13 14:30:46 -07001520 bool pinned,
Eric Laurentde8caf42021-08-11 17:19:25 +02001521 bool probe,
1522 bool notifyFramesProcessed)
Eric Laurent81784c32012-11-19 14:55:58 -08001523{
1524 sp<EffectModule> effect;
1525 sp<EffectHandle> handle;
1526 status_t lStatus;
1527 sp<EffectChain> chain;
1528 bool chainCreated = false;
1529 bool effectCreated = false;
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001530 audio_unique_id_t effectId = AUDIO_UNIQUE_ID_USE_UNSPECIFIED;
Eric Laurent81784c32012-11-19 14:55:58 -08001531
1532 lStatus = initCheck();
1533 if (lStatus != NO_ERROR) {
1534 ALOGW("createEffect_l() Audio driver not initialized.");
1535 goto Exit;
1536 }
1537
Eric Laurent81784c32012-11-19 14:55:58 -08001538 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
1539
1540 { // scope for mLock
1541 Mutex::Autolock _l(mLock);
1542
Eric Laurent4c415062016-06-17 16:14:16 -07001543 lStatus = checkEffectCompatibility_l(desc, sessionId);
Eric Laurent2fe0acd2020-03-13 14:30:46 -07001544 if (probe || lStatus != NO_ERROR) {
Eric Laurent4c415062016-06-17 16:14:16 -07001545 goto Exit;
1546 }
1547
Eric Laurent81784c32012-11-19 14:55:58 -08001548 // check for existing effect chain with the requested audio session
1549 chain = getEffectChain_l(sessionId);
1550 if (chain == 0) {
1551 // create a new chain for this session
1552 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
1553 chain = new EffectChain(this, sessionId);
1554 addEffectChain_l(chain);
1555 chain->setStrategy(getStrategyForSession_l(sessionId));
1556 chainCreated = true;
1557 } else {
1558 effect = chain->getEffectFromDesc_l(desc);
1559 }
1560
1561 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
1562
1563 if (effect == 0) {
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001564 effectId = mAudioFlinger->nextUniqueId(AUDIO_UNIQUE_ID_USE_EFFECT);
Eric Laurent81784c32012-11-19 14:55:58 -08001565 // create a new effect module if none present in the chain
Eric Laurent6b446ce2019-12-13 10:56:31 -08001566 lStatus = chain->createEffect_l(effect, desc, effectId, sessionId, pinned);
Eric Laurent81784c32012-11-19 14:55:58 -08001567 if (lStatus != NO_ERROR) {
1568 goto Exit;
1569 }
1570 effectCreated = true;
1571
jiabinc52b1ff2019-10-31 17:20:42 -07001572 // FIXME: use vector of device and address when effect interface is ready.
jiabin8f278ee2019-11-11 12:16:27 -08001573 effect->setDevices(outDeviceTypeAddrs());
1574 effect->setInputDevice(inDeviceTypeAddr());
Eric Laurent81784c32012-11-19 14:55:58 -08001575 effect->setMode(mAudioFlinger->getMode());
1576 effect->setAudioSource(mAudioSource);
1577 }
jiabin1319f5a2021-03-30 22:21:24 +00001578 if (effect->isHapticGenerator()) {
1579 // TODO(b/184194057): Use the vibrator information from the vibrator that will be used
1580 // for the HapticGenerator.
Lais Andradebc3f37a2021-07-02 00:13:19 +01001581 const std::optional<media::AudioVibratorInfo> defaultVibratorInfo =
1582 std::move(mAudioFlinger->getDefaultVibratorInfo_l());
1583 if (defaultVibratorInfo) {
jiabin1319f5a2021-03-30 22:21:24 +00001584 // Only set the vibrator info when it is a valid one.
Lais Andradebc3f37a2021-07-02 00:13:19 +01001585 effect->setVibratorInfo(*defaultVibratorInfo);
jiabin1319f5a2021-03-30 22:21:24 +00001586 }
1587 }
Eric Laurent81784c32012-11-19 14:55:58 -08001588 // create effect handle and connect it to effect module
Eric Laurentde8caf42021-08-11 17:19:25 +02001589 handle = new EffectHandle(effect, client, effectClient, priority, notifyFramesProcessed);
Glenn Kastene75da402013-11-20 13:54:52 -08001590 lStatus = handle->initCheck();
1591 if (lStatus == OK) {
1592 lStatus = effect->addHandle(handle.get());
Eric Laurentb3f315a2021-07-13 15:09:05 +02001593 sendCheckOutputStageEffectsEvent_l();
Glenn Kastene75da402013-11-20 13:54:52 -08001594 }
Eric Laurent81784c32012-11-19 14:55:58 -08001595 if (enabled != NULL) {
1596 *enabled = (int)effect->isEnabled();
1597 }
1598 }
1599
1600Exit:
Eric Laurent2fe0acd2020-03-13 14:30:46 -07001601 if (!probe && lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurent81784c32012-11-19 14:55:58 -08001602 Mutex::Autolock _l(mLock);
1603 if (effectCreated) {
1604 chain->removeEffect_l(effect);
1605 }
Eric Laurent81784c32012-11-19 14:55:58 -08001606 if (chainCreated) {
1607 removeEffectChain_l(chain);
1608 }
haobo101735295ff7b0d2017-03-17 17:44:03 +08001609 // handle must be cleared by caller to avoid deadlock.
Eric Laurent81784c32012-11-19 14:55:58 -08001610 }
1611
Glenn Kasten9156ef32013-08-06 15:39:08 -07001612 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001613 return handle;
1614}
1615
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001616void AudioFlinger::ThreadBase::disconnectEffectHandle(EffectHandle *handle,
1617 bool unpinIfLast)
1618{
1619 bool remove = false;
1620 sp<EffectModule> effect;
1621 {
1622 Mutex::Autolock _l(mLock);
Eric Laurent41709552019-12-16 19:34:05 -08001623 sp<EffectBase> effectBase = handle->effect().promote();
1624 if (effectBase == nullptr) {
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001625 return;
1626 }
Eric Laurentb82e6b72019-11-22 17:25:04 -08001627 effect = effectBase->asEffectModule();
1628 if (effect == nullptr) {
1629 return;
1630 }
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001631 // restore suspended effects if the disconnected handle was enabled and the last one.
1632 remove = (effect->removeHandle(handle) == 0) && (!effect->isPinned() || unpinIfLast);
1633 if (remove) {
1634 removeEffect_l(effect, true);
1635 }
Eric Laurentb3f315a2021-07-13 15:09:05 +02001636 sendCheckOutputStageEffectsEvent_l();
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001637 }
1638 if (remove) {
1639 mAudioFlinger->updateOrphanEffectChains(effect);
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001640 if (handle->enabled()) {
Eric Laurent6b446ce2019-12-13 10:56:31 -08001641 effect->checkSuspendOnEffectEnabled(false, false /*threadLocked*/);
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001642 }
1643 }
1644}
1645
Eric Laurent6b446ce2019-12-13 10:56:31 -08001646void AudioFlinger::ThreadBase::onEffectEnable(const sp<EffectModule>& effect) {
Andy Hungea840382020-05-05 21:50:17 -07001647 if (isOffloadOrMmap()) {
Eric Laurent6b446ce2019-12-13 10:56:31 -08001648 Mutex::Autolock _l(mLock);
1649 broadcast_l();
1650 }
1651 if (!effect->isOffloadable()) {
1652 if (mType == ThreadBase::OFFLOAD) {
1653 PlaybackThread *t = (PlaybackThread *)this;
1654 t->invalidateTracks(AUDIO_STREAM_MUSIC);
1655 }
1656 if (effect->sessionId() == AUDIO_SESSION_OUTPUT_MIX) {
1657 mAudioFlinger->onNonOffloadableGlobalEffectEnable();
1658 }
1659 }
1660}
1661
1662void AudioFlinger::ThreadBase::onEffectDisable() {
Andy Hungea840382020-05-05 21:50:17 -07001663 if (isOffloadOrMmap()) {
Eric Laurent6b446ce2019-12-13 10:56:31 -08001664 Mutex::Autolock _l(mLock);
1665 broadcast_l();
1666 }
1667}
1668
Glenn Kastend848eb42016-03-08 13:42:11 -08001669sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(audio_session_t sessionId,
1670 int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08001671{
1672 Mutex::Autolock _l(mLock);
1673 return getEffect_l(sessionId, effectId);
1674}
1675
Glenn Kastend848eb42016-03-08 13:42:11 -08001676sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(audio_session_t sessionId,
1677 int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08001678{
1679 sp<EffectChain> chain = getEffectChain_l(sessionId);
1680 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
1681}
1682
Eric Laurent6c796322019-04-09 14:13:17 -07001683std::vector<int> AudioFlinger::ThreadBase::getEffectIds_l(audio_session_t sessionId)
1684{
1685 sp<EffectChain> chain = getEffectChain_l(sessionId);
1686 return chain != nullptr ? chain->getEffectIds() : std::vector<int>{};
1687}
1688
Eric Laurent81784c32012-11-19 14:55:58 -08001689// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
1690// PlaybackThread::mLock held
1691status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
1692{
1693 // check for existing effect chain with the requested audio session
Glenn Kastend848eb42016-03-08 13:42:11 -08001694 audio_session_t sessionId = effect->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08001695 sp<EffectChain> chain = getEffectChain_l(sessionId);
1696 bool chainCreated = false;
1697
Eric Laurent5baf2af2013-09-12 17:37:00 -07001698 ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(),
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001699 "addEffect_l() on offloaded thread %p: effect %s does not support offload flags %#x",
Eric Laurent5baf2af2013-09-12 17:37:00 -07001700 this, effect->desc().name, effect->desc().flags);
1701
Eric Laurent81784c32012-11-19 14:55:58 -08001702 if (chain == 0) {
1703 // create a new chain for this session
1704 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
1705 chain = new EffectChain(this, sessionId);
1706 addEffectChain_l(chain);
1707 chain->setStrategy(getStrategyForSession_l(sessionId));
1708 chainCreated = true;
1709 }
1710 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
1711
1712 if (chain->getEffectFromId_l(effect->id()) != 0) {
1713 ALOGW("addEffect_l() %p effect %s already present in chain %p",
1714 this, effect->desc().name, chain.get());
1715 return BAD_VALUE;
1716 }
1717
Eric Laurent5baf2af2013-09-12 17:37:00 -07001718 effect->setOffloaded(mType == OFFLOAD, mId);
1719
Eric Laurent81784c32012-11-19 14:55:58 -08001720 status_t status = chain->addEffect_l(effect);
1721 if (status != NO_ERROR) {
1722 if (chainCreated) {
1723 removeEffectChain_l(chain);
1724 }
1725 return status;
1726 }
1727
jiabin8f278ee2019-11-11 12:16:27 -08001728 effect->setDevices(outDeviceTypeAddrs());
1729 effect->setInputDevice(inDeviceTypeAddr());
Eric Laurent81784c32012-11-19 14:55:58 -08001730 effect->setMode(mAudioFlinger->getMode());
1731 effect->setAudioSource(mAudioSource);
Eric Laurentd8365c52017-07-16 15:27:05 -07001732
Eric Laurent81784c32012-11-19 14:55:58 -08001733 return NO_ERROR;
1734}
1735
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001736void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect, bool release) {
Eric Laurent81784c32012-11-19 14:55:58 -08001737
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001738 ALOGV("%s %p effect %p", __FUNCTION__, this, effect.get());
Eric Laurent81784c32012-11-19 14:55:58 -08001739 effect_descriptor_t desc = effect->desc();
1740 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
1741 detachAuxEffect_l(effect->id());
1742 }
1743
Andy Hungfda44002021-06-03 17:23:16 -07001744 sp<EffectChain> chain = effect->getCallback()->chain().promote();
Eric Laurent81784c32012-11-19 14:55:58 -08001745 if (chain != 0) {
1746 // remove effect chain if removing last effect
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001747 if (chain->removeEffect_l(effect, release) == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08001748 removeEffectChain_l(chain);
1749 }
1750 } else {
1751 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
1752 }
1753}
1754
1755void AudioFlinger::ThreadBase::lockEffectChains_l(
1756 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1757{
1758 effectChains = mEffectChains;
1759 for (size_t i = 0; i < mEffectChains.size(); i++) {
1760 mEffectChains[i]->lock();
1761 }
1762}
1763
1764void AudioFlinger::ThreadBase::unlockEffectChains(
1765 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1766{
1767 for (size_t i = 0; i < effectChains.size(); i++) {
1768 effectChains[i]->unlock();
1769 }
1770}
1771
Glenn Kastend848eb42016-03-08 13:42:11 -08001772sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001773{
1774 Mutex::Autolock _l(mLock);
1775 return getEffectChain_l(sessionId);
1776}
1777
Glenn Kastend848eb42016-03-08 13:42:11 -08001778sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(audio_session_t sessionId)
1779 const
Eric Laurent81784c32012-11-19 14:55:58 -08001780{
1781 size_t size = mEffectChains.size();
1782 for (size_t i = 0; i < size; i++) {
1783 if (mEffectChains[i]->sessionId() == sessionId) {
1784 return mEffectChains[i];
1785 }
1786 }
1787 return 0;
1788}
1789
1790void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
1791{
1792 Mutex::Autolock _l(mLock);
1793 size_t size = mEffectChains.size();
1794 for (size_t i = 0; i < size; i++) {
1795 mEffectChains[i]->setMode_l(mode);
1796 }
1797}
1798
Mikhail Naganovdc769682018-05-04 15:34:08 -07001799void AudioFlinger::ThreadBase::toAudioPortConfig(struct audio_port_config *config)
Eric Laurent83b88082014-06-20 18:31:16 -07001800{
1801 config->type = AUDIO_PORT_TYPE_MIX;
1802 config->ext.mix.handle = mId;
1803 config->sample_rate = mSampleRate;
1804 config->format = mFormat;
1805 config->channel_mask = mChannelMask;
1806 config->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
1807 AUDIO_PORT_CONFIG_FORMAT;
1808}
1809
Eric Laurent72e3f392015-05-20 14:43:50 -07001810void AudioFlinger::ThreadBase::systemReady()
1811{
1812 Mutex::Autolock _l(mLock);
1813 if (mSystemReady) {
1814 return;
1815 }
1816 mSystemReady = true;
1817
1818 for (size_t i = 0; i < mPendingConfigEvents.size(); i++) {
1819 sendConfigEvent_l(mPendingConfigEvents.editItemAt(i));
1820 }
1821 mPendingConfigEvents.clear();
1822}
1823
Andy Hungdae27702016-10-31 14:01:16 -07001824template <typename T>
1825ssize_t AudioFlinger::ThreadBase::ActiveTracks<T>::add(const sp<T> &track) {
1826 ssize_t index = mActiveTracks.indexOf(track);
1827 if (index >= 0) {
1828 ALOGW("ActiveTracks<T>::add track %p already there", track.get());
1829 return index;
1830 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001831 logTrack("add", track);
Andy Hungdae27702016-10-31 14:01:16 -07001832 mActiveTracksGeneration++;
1833 mLatestActiveTrack = track;
1834 ++mBatteryCounter[track->uid()].second;
Kevin Rocard069c2712018-03-29 19:09:14 -07001835 mHasChanged = true;
Andy Hungdae27702016-10-31 14:01:16 -07001836 return mActiveTracks.add(track);
1837}
1838
1839template <typename T>
1840ssize_t AudioFlinger::ThreadBase::ActiveTracks<T>::remove(const sp<T> &track) {
1841 ssize_t index = mActiveTracks.remove(track);
1842 if (index < 0) {
1843 ALOGW("ActiveTracks<T>::remove nonexistent track %p", track.get());
1844 return index;
1845 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001846 logTrack("remove", track);
Andy Hungdae27702016-10-31 14:01:16 -07001847 mActiveTracksGeneration++;
1848 --mBatteryCounter[track->uid()].second;
1849 // mLatestActiveTrack is not cleared even if is the same as track.
Kevin Rocard069c2712018-03-29 19:09:14 -07001850 mHasChanged = true;
Andy Hung8946a282018-04-19 20:04:56 -07001851#ifdef TEE_SINK
1852 track->dumpTee(-1 /* fd */, "_REMOVE");
1853#endif
Andy Hungc2b11cb2020-04-22 09:04:01 -07001854 track->logEndInterval(); // log to MediaMetrics
Andy Hungdae27702016-10-31 14:01:16 -07001855 return index;
1856}
1857
1858template <typename T>
1859void AudioFlinger::ThreadBase::ActiveTracks<T>::clear() {
1860 for (const sp<T> &track : mActiveTracks) {
1861 BatteryNotifier::getInstance().noteStopAudio(track->uid());
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001862 logTrack("clear", track);
Andy Hungdae27702016-10-31 14:01:16 -07001863 }
1864 mLastActiveTracksGeneration = mActiveTracksGeneration;
Kevin Rocard069c2712018-03-29 19:09:14 -07001865 if (!mActiveTracks.empty()) { mHasChanged = true; }
Andy Hungdae27702016-10-31 14:01:16 -07001866 mActiveTracks.clear();
1867 mLatestActiveTrack.clear();
1868 mBatteryCounter.clear();
1869}
1870
1871template <typename T>
1872void AudioFlinger::ThreadBase::ActiveTracks<T>::updatePowerState(
1873 sp<ThreadBase> thread, bool force) {
1874 // Updates ActiveTracks client uids to the thread wakelock.
1875 if (mActiveTracksGeneration != mLastActiveTracksGeneration || force) {
1876 thread->updateWakeLockUids_l(getWakeLockUids());
1877 mLastActiveTracksGeneration = mActiveTracksGeneration;
1878 }
1879
1880 // Updates BatteryNotifier uids
1881 for (auto it = mBatteryCounter.begin(); it != mBatteryCounter.end();) {
1882 const uid_t uid = it->first;
1883 ssize_t &previous = it->second.first;
1884 ssize_t &current = it->second.second;
1885 if (current > 0) {
1886 if (previous == 0) {
1887 BatteryNotifier::getInstance().noteStartAudio(uid);
1888 }
1889 previous = current;
1890 ++it;
1891 } else if (current == 0) {
1892 if (previous > 0) {
1893 BatteryNotifier::getInstance().noteStopAudio(uid);
1894 }
1895 it = mBatteryCounter.erase(it); // std::map<> is stable on iterator erase.
1896 } else /* (current < 0) */ {
1897 LOG_ALWAYS_FATAL("negative battery count %zd", current);
1898 }
1899 }
1900}
Eric Laurent83b88082014-06-20 18:31:16 -07001901
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001902template <typename T>
Kevin Rocard069c2712018-03-29 19:09:14 -07001903bool AudioFlinger::ThreadBase::ActiveTracks<T>::readAndClearHasChanged() {
Jasmine Chaeaa10e42021-05-11 10:11:14 +08001904 bool hasChanged = mHasChanged;
Kevin Rocard069c2712018-03-29 19:09:14 -07001905 mHasChanged = false;
Jasmine Chaeaa10e42021-05-11 10:11:14 +08001906
1907 for (const sp<T> &track : mActiveTracks) {
1908 // Do not short-circuit as all hasChanged states must be reset
1909 // as all the metadata are going to be sent
1910 hasChanged |= track->readAndClearHasChanged();
1911 }
Kevin Rocard069c2712018-03-29 19:09:14 -07001912 return hasChanged;
1913}
1914
1915template <typename T>
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001916void AudioFlinger::ThreadBase::ActiveTracks<T>::logTrack(
1917 const char *funcName, const sp<T> &track) const {
1918 if (mLocalLog != nullptr) {
1919 String8 result;
1920 track->appendDump(result, false /* active */);
1921 mLocalLog->log("AT::%-10s(%p) %s", funcName, track.get(), result.string());
1922 }
1923}
1924
Eric Laurent6acd1d42017-01-04 14:23:29 -08001925void AudioFlinger::ThreadBase::broadcast_l()
1926{
1927 // Thread could be blocked waiting for async
1928 // so signal it to handle state changes immediately
1929 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
1930 // be lost so we also flag to prevent it blocking on mWaitWorkCV
1931 mSignalPending = true;
1932 mWaitWorkCV.broadcast();
1933}
1934
Andy Hungd0979812019-02-21 15:51:44 -08001935// Call only from threadLoop() or when it is idle.
1936// Do not call from high performance code as this may do binder rpc to the MediaMetrics service.
1937void AudioFlinger::ThreadBase::sendStatistics(bool force)
1938{
1939 // Do not log if we have no stats.
1940 // We choose the timestamp verifier because it is the most likely item to be present.
1941 const int64_t nstats = mTimestampVerifier.getN() - mLastRecordedTimestampVerifierN;
1942 if (nstats == 0) {
1943 return;
1944 }
1945
1946 // Don't log more frequently than once per 12 hours.
1947 // We use BOOTTIME to include suspend time.
1948 const int64_t timeNs = systemTime(SYSTEM_TIME_BOOTTIME);
1949 const int64_t sinceNs = timeNs - mLastRecordedTimeNs; // ok if mLastRecordedTimeNs = 0
1950 if (!force && sinceNs <= 12 * NANOS_PER_HOUR) {
1951 return;
1952 }
1953
1954 mLastRecordedTimestampVerifierN = mTimestampVerifier.getN();
1955 mLastRecordedTimeNs = timeNs;
1956
Ray Essickf27e9872019-12-07 06:28:46 -08001957 std::unique_ptr<mediametrics::Item> item(mediametrics::Item::create("audiothread"));
Andy Hungd0979812019-02-21 15:51:44 -08001958
1959#define MM_PREFIX "android.media.audiothread." // avoid cut-n-paste errors.
1960
1961 // thread configuration
1962 item->setInt32(MM_PREFIX "id", (int32_t)mId); // IO handle
1963 // item->setInt32(MM_PREFIX "portId", (int32_t)mPortId);
1964 item->setCString(MM_PREFIX "type", threadTypeToString(mType));
1965 item->setInt32(MM_PREFIX "sampleRate", (int32_t)mSampleRate);
1966 item->setInt64(MM_PREFIX "channelMask", (int64_t)mChannelMask);
1967 item->setCString(MM_PREFIX "encoding", toString(mFormat).c_str());
1968 item->setInt32(MM_PREFIX "frameCount", (int32_t)mFrameCount);
jiabinc52b1ff2019-10-31 17:20:42 -07001969 item->setCString(MM_PREFIX "outDevice", toString(outDeviceTypes()).c_str());
1970 item->setCString(MM_PREFIX "inDevice", toString(inDeviceType()).c_str());
Andy Hungd0979812019-02-21 15:51:44 -08001971
1972 // thread statistics
1973 if (mIoJitterMs.getN() > 0) {
1974 item->setDouble(MM_PREFIX "ioJitterMs.mean", mIoJitterMs.getMean());
1975 item->setDouble(MM_PREFIX "ioJitterMs.std", mIoJitterMs.getStdDev());
1976 }
1977 if (mProcessTimeMs.getN() > 0) {
1978 item->setDouble(MM_PREFIX "processTimeMs.mean", mProcessTimeMs.getMean());
1979 item->setDouble(MM_PREFIX "processTimeMs.std", mProcessTimeMs.getStdDev());
1980 }
1981 const auto tsjitter = mTimestampVerifier.getJitterMs();
1982 if (tsjitter.getN() > 0) {
1983 item->setDouble(MM_PREFIX "timestampJitterMs.mean", tsjitter.getMean());
1984 item->setDouble(MM_PREFIX "timestampJitterMs.std", tsjitter.getStdDev());
1985 }
1986 if (mLatencyMs.getN() > 0) {
1987 item->setDouble(MM_PREFIX "latencyMs.mean", mLatencyMs.getMean());
1988 item->setDouble(MM_PREFIX "latencyMs.std", mLatencyMs.getStdDev());
1989 }
Robert Wu06db0a32021-08-10 19:05:34 +00001990 if (mMonopipePipeDepthStats.getN() > 0) {
1991 item->setDouble(MM_PREFIX "monopipePipeDepthStats.mean",
1992 mMonopipePipeDepthStats.getMean());
1993 item->setDouble(MM_PREFIX "monopipePipeDepthStats.std",
1994 mMonopipePipeDepthStats.getStdDev());
1995 }
Andy Hungd0979812019-02-21 15:51:44 -08001996
1997 item->selfrecord();
1998}
1999
Eric Laurentd66d7a12021-07-13 13:35:32 +02002000product_strategy_t AudioFlinger::ThreadBase::getStrategyForStream(audio_stream_type_t stream) const
2001{
2002 if (!mAudioFlinger->isAudioPolicyReady()) {
2003 return PRODUCT_STRATEGY_NONE;
2004 }
2005 return AudioSystem::getStrategyForStream(stream);
2006}
2007
Eric Laurent81784c32012-11-19 14:55:58 -08002008// ----------------------------------------------------------------------------
2009// Playback
2010// ----------------------------------------------------------------------------
2011
2012AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
2013 AudioStreamOut* output,
2014 audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -07002015 type_t type,
Eric Laurentf1f22e72021-07-13 14:04:14 +02002016 bool systemReady,
2017 audio_config_base_t *mixerConfig)
Andy Hungcf10d742020-04-28 15:38:24 -07002018 : ThreadBase(audioFlinger, id, type, systemReady, true /* isOut */),
Andy Hung2098f272014-02-27 14:00:06 -08002019 mNormalFrameCount(0), mSinkBuffer(NULL),
Eric Laurent1c5e2e32021-08-18 18:50:28 +02002020 mMixerBufferEnabled(AudioFlinger::kEnableExtendedPrecision || type == SPATIALIZER),
Andy Hung69aed5f2014-02-25 17:24:40 -08002021 mMixerBuffer(NULL),
2022 mMixerBufferSize(0),
2023 mMixerBufferFormat(AUDIO_FORMAT_INVALID),
2024 mMixerBufferValid(false),
Eric Laurent1c5e2e32021-08-18 18:50:28 +02002025 mEffectBufferEnabled(AudioFlinger::kEnableExtendedPrecision || type == SPATIALIZER),
Andy Hung98ef9782014-03-04 14:46:50 -08002026 mEffectBuffer(NULL),
2027 mEffectBufferSize(0),
2028 mEffectBufferFormat(AUDIO_FORMAT_INVALID),
2029 mEffectBufferValid(false),
Glenn Kastenc1fac192013-08-06 07:41:36 -07002030 mSuspended(0), mBytesWritten(0),
Andy Hungc54b1ff2016-02-23 14:07:07 -08002031 mFramesWritten(0),
Andy Hung238fa3d2016-07-28 10:53:22 -07002032 mSuspendedFrames(0),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002033 mActiveTracks(&this->mLocalLog),
Eric Laurent81784c32012-11-19 14:55:58 -08002034 // mStreamTypes[] initialized in constructor body
Andy Hung1bc088a2018-02-09 15:57:31 -08002035 mTracks(type == MIXER),
Eric Laurent81784c32012-11-19 14:55:58 -08002036 mOutput(output),
Andy Hung446f4df2019-02-21 12:26:41 -08002037 mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
Eric Laurent81784c32012-11-19 14:55:58 -08002038 mMixerStatus(MIXER_IDLE),
2039 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002040 mStandbyDelayNs(AudioFlinger::mStandbyTimeInNsecs),
Eric Laurentbfb1b832013-01-07 09:53:42 -08002041 mBytesRemaining(0),
2042 mCurrentWriteLength(0),
2043 mUseAsyncWrite(false),
Eric Laurent3b4529e2013-09-05 18:09:19 -07002044 mWriteAckSequence(0),
2045 mDrainSequence(0),
Eric Laurent81784c32012-11-19 14:55:58 -08002046 mScreenState(AudioFlinger::mScreenState),
2047 // index 0 is reserved for normal mixer's submix
Glenn Kastendc2c50b2016-04-21 08:13:14 -07002048 mFastTrackAvailMask(((1 << FastMixerState::sMaxFastTracks) - 1) & ~1),
Eric Laurent7c29ec92017-09-20 17:54:22 -07002049 mHwSupportsPause(false), mHwPaused(false), mFlushPending(false),
Eric Laurent74c38dc2020-12-23 18:19:44 +01002050 mLeftVolFloat(-1.0), mRightVolFloat(-1.0),
Brian Lindahl65e90012022-07-27 18:01:07 +02002051 mDownStreamPatch{},
2052 mIsTimestampAdvancing(kMinimumTimeBetweenTimestampChecksNs)
Eric Laurent81784c32012-11-19 14:55:58 -08002053{
Glenn Kastend7dca052015-03-05 16:05:54 -08002054 snprintf(mThreadName, kThreadNameLength, "AudioOut_%X", id);
2055 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08002056
2057 // Assumes constructor is called by AudioFlinger with it's mLock held, but
2058 // it would be safer to explicitly pass initial masterVolume/masterMute as
2059 // parameter.
2060 //
2061 // If the HAL we are using has support for master volume or master mute,
2062 // then do not attenuate or mute during mixing (just leave the volume at 1.0
2063 // and the mute set to false).
2064 mMasterVolume = audioFlinger->masterVolume_l();
2065 mMasterMute = audioFlinger->masterMute_l();
George Burgess IV5e4d86f2020-02-18 12:55:36 -08002066 if (mOutput->audioHwDev) {
Eric Laurent81784c32012-11-19 14:55:58 -08002067 if (mOutput->audioHwDev->canSetMasterVolume()) {
2068 mMasterVolume = 1.0;
2069 }
2070
2071 if (mOutput->audioHwDev->canSetMasterMute()) {
2072 mMasterMute = false;
2073 }
Andy Hungc8fddf32018-08-08 18:32:37 -07002074 mIsMsdDevice = strcmp(
2075 mOutput->audioHwDev->moduleName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002076 }
2077
Eric Laurentf1f22e72021-07-13 14:04:14 +02002078 if (mixerConfig != nullptr && mixerConfig->channel_mask != AUDIO_CHANNEL_NONE) {
2079 mMixerChannelMask = mixerConfig->channel_mask;
2080 }
2081
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002082 readOutputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002083
Eric Laurent1c5e2e32021-08-18 18:50:28 +02002084 if (mType != SPATIALIZER
Eric Laurentb3f315a2021-07-13 15:09:05 +02002085 && mMixerChannelMask != mChannelMask) {
2086 LOG_ALWAYS_FATAL("HAL channel mask %#x does not match mixer channel mask %#x",
2087 mChannelMask, mMixerChannelMask);
2088 }
2089
Andy Hungc8fddf32018-08-08 18:32:37 -07002090 // TODO: We may also match on address as well as device type for
2091 // AUDIO_DEVICE_OUT_BUS, AUDIO_DEVICE_OUT_ALL_A2DP, AUDIO_DEVICE_OUT_REMOTE_SUBMIX
Dean Wheatleyf8726f02019-12-02 14:12:01 +11002092 if (type == MIXER || type == DIRECT || type == OFFLOAD) {
jiabinc52b1ff2019-10-31 17:20:42 -07002093 // TODO: This property should be ensure that only contains one single device type.
2094 mTimestampCorrectedDevice = (audio_devices_t)property_get_int64(
2095 "audio.timestamp.corrected_output_device",
Andy Hungc8fddf32018-08-08 18:32:37 -07002096 (int64_t)(mIsMsdDevice ? AUDIO_DEVICE_OUT_BUS // turn on by default for MSD
2097 : AUDIO_DEVICE_NONE));
2098 }
2099
Mikhail Naganovf33115d2020-09-25 23:03:05 +00002100 for (int i = AUDIO_STREAM_MIN; i < AUDIO_STREAM_FOR_POLICY_CNT; ++i) {
2101 const audio_stream_type_t stream{static_cast<audio_stream_type_t>(i)};
Eric Laurent98e38192018-02-15 18:31:53 -08002102 mStreamTypes[stream].volume = 0.0f;
Eric Laurent81784c32012-11-19 14:55:58 -08002103 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
2104 }
Eric Laurent35f8c7c2020-02-08 11:42:35 -08002105 // Audio patch and call assistant volume are always max
Eric Laurent98e38192018-02-15 18:31:53 -08002106 mStreamTypes[AUDIO_STREAM_PATCH].volume = 1.0f;
2107 mStreamTypes[AUDIO_STREAM_PATCH].mute = false;
Eric Laurent35f8c7c2020-02-08 11:42:35 -08002108 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].volume = 1.0f;
2109 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].mute = false;
Eric Laurent81784c32012-11-19 14:55:58 -08002110}
2111
2112AudioFlinger::PlaybackThread::~PlaybackThread()
2113{
Glenn Kasten9e58b552013-01-18 15:09:48 -08002114 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung010a1a12014-03-13 13:57:33 -07002115 free(mSinkBuffer);
Andy Hung69aed5f2014-02-25 17:24:40 -08002116 free(mMixerBuffer);
Andy Hung98ef9782014-03-04 14:46:50 -08002117 free(mEffectBuffer);
Eric Laurentb62d0362021-10-26 17:40:18 +02002118 free(mPostSpatializerBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08002119}
2120
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002121// Thread virtuals
2122
2123void AudioFlinger::PlaybackThread::onFirstRef()
Eric Laurent81784c32012-11-19 14:55:58 -08002124{
Jasmine Chaeaa10e42021-05-11 10:11:14 +08002125 if (!isStreamInitialized()) {
jiabinf6eb4c32020-02-25 14:06:25 -08002126 ALOGE("The stream is not open yet"); // This should not happen.
2127 } else {
2128 // setEventCallback will need a strong pointer as a parameter. Calling it
2129 // here instead of constructor of PlaybackThread so that the onFirstRef
2130 // callback would not be made on an incompletely constructed object.
2131 if (mOutput->stream->setEventCallback(this) != OK) {
jiabinf1a36052020-08-19 14:33:31 -07002132 ALOGD("Failed to add event callback");
jiabinf6eb4c32020-02-25 14:06:25 -08002133 }
2134 }
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002135 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
Andy Hung44d648b2022-04-08 17:33:40 -07002136 mThreadSnapshot.setTid(getTid());
Eric Laurent81784c32012-11-19 14:55:58 -08002137}
2138
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002139// ThreadBase virtuals
2140void AudioFlinger::PlaybackThread::preExit()
2141{
2142 ALOGV(" preExit()");
Ytai Ben-Tsvi7e0183f2022-02-04 10:49:54 -08002143 status_t result = mOutput->stream->exit();
2144 ALOGE_IF(result != OK, "Error when calling exit(): %d", result);
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002145}
2146
2147void AudioFlinger::PlaybackThread::dumpTracks_l(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08002148{
Eric Laurent81784c32012-11-19 14:55:58 -08002149 String8 result;
2150
Marco Nelissenb2208842014-02-07 14:00:50 -08002151 result.appendFormat(" Stream volumes in dB: ");
Eric Laurent81784c32012-11-19 14:55:58 -08002152 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
2153 const stream_type_t *st = &mStreamTypes[i];
2154 if (i > 0) {
2155 result.appendFormat(", ");
2156 }
2157 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
2158 if (st->mute) {
2159 result.append("M");
2160 }
2161 }
2162 result.append("\n");
2163 write(fd, result.string(), result.length());
2164 result.clear();
2165
Eric Laurent81784c32012-11-19 14:55:58 -08002166 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
2167 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
Elliott Hughes87cebad2014-05-22 10:14:43 -07002168 dprintf(fd, " Normal mixer raw underrun counters: partial=%u empty=%u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08002169 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Marco Nelissenb2208842014-02-07 14:00:50 -08002170
2171 size_t numtracks = mTracks.size();
2172 size_t numactive = mActiveTracks.size();
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002173 dprintf(fd, " %zu Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08002174 size_t numactiveseen = 0;
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002175 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08002176 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002177 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002178 result.append(prefix);
Andy Hungf6ab58d2018-05-25 12:50:39 -07002179 mTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08002180 for (size_t i = 0; i < numtracks; ++i) {
2181 sp<Track> track = mTracks[i];
2182 if (track != 0) {
2183 bool active = mActiveTracks.indexOf(track) >= 0;
2184 if (active) {
2185 numactiveseen++;
2186 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002187 result.append(prefix);
2188 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08002189 }
2190 }
2191 } else {
2192 result.append("\n");
2193 }
2194 if (numactiveseen != numactive) {
2195 // some tracks in the active list were not in the tracks list
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002196 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08002197 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002198 result.append(prefix);
Andy Hungf6ab58d2018-05-25 12:50:39 -07002199 mActiveTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08002200 for (size_t i = 0; i < numactive; ++i) {
Andy Hungdae27702016-10-31 14:01:16 -07002201 sp<Track> track = mActiveTracks[i];
2202 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002203 result.append(prefix);
2204 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08002205 }
2206 }
2207 }
2208
2209 write(fd, result.string(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08002210}
2211
Andy Hung61589a42021-06-16 09:37:53 -07002212void AudioFlinger::PlaybackThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -08002213{
Andy Hung04cb8f72020-03-20 13:44:33 -07002214 dprintf(fd, " Master volume: %f\n", mMasterVolume);
Mikhail Naganovdfb411f2018-09-11 13:39:56 -07002215 dprintf(fd, " Master mute: %s\n", mMasterMute ? "on" : "off");
Eric Laurentf1f22e72021-07-13 14:04:14 +02002216 dprintf(fd, " Mixer channel Mask: %#x (%s)\n",
2217 mMixerChannelMask, channelMaskToString(mMixerChannelMask, true /* output */).c_str());
jiabin245cdd92018-12-07 17:55:15 -08002218 if (mHapticChannelMask != AUDIO_CHANNEL_NONE) {
2219 dprintf(fd, " Haptic channel mask: %#x (%s)\n", mHapticChannelMask,
2220 channelMaskToString(mHapticChannelMask, true /* output */).c_str());
2221 }
Elliott Hughes87cebad2014-05-22 10:14:43 -07002222 dprintf(fd, " Normal frame count: %zu\n", mNormalFrameCount);
Elliott Hughes87cebad2014-05-22 10:14:43 -07002223 dprintf(fd, " Total writes: %d\n", mNumWrites);
2224 dprintf(fd, " Delayed writes: %d\n", mNumDelayedWrites);
2225 dprintf(fd, " Blocked in write: %s\n", mInWrite ? "yes" : "no");
2226 dprintf(fd, " Suspend count: %d\n", mSuspended);
2227 dprintf(fd, " Sink buffer : %p\n", mSinkBuffer);
2228 dprintf(fd, " Mixer buffer: %p\n", mMixerBuffer);
2229 dprintf(fd, " Effect buffer: %p\n", mEffectBuffer);
2230 dprintf(fd, " Fast track availMask=%#x\n", mFastTrackAvailMask);
Eric Laurent42537be2016-01-08 17:16:42 -08002231 dprintf(fd, " Standby delay ns=%lld\n", (long long)mStandbyDelayNs);
Glenn Kasten97b7b752014-09-28 13:04:24 -07002232 AudioStreamOut *output = mOutput;
2233 audio_output_flags_t flags = output != NULL ? output->flags : AUDIO_OUTPUT_FLAG_NONE;
Mikhail Naganov913d06c2016-11-01 12:49:22 -07002234 dprintf(fd, " AudioStreamOut: %p flags %#x (%s)\n",
Andy Hung9b181952019-02-25 14:53:36 -08002235 output, flags, toString(flags).c_str());
Andy Hungb54c8542016-09-21 12:55:15 -07002236 dprintf(fd, " Frames written: %lld\n", (long long)mFramesWritten);
2237 dprintf(fd, " Suspended frames: %lld\n", (long long)mSuspendedFrames);
2238 if (mPipeSink.get() != nullptr) {
2239 dprintf(fd, " PipeSink frames written: %lld\n", (long long)mPipeSink->framesWritten());
2240 }
2241 if (output != nullptr) {
2242 dprintf(fd, " Hal stream dump:\n");
Andy Hung61589a42021-06-16 09:37:53 -07002243 (void)output->stream->dump(fd, args);
Andy Hungb54c8542016-09-21 12:55:15 -07002244 }
Eric Laurent81784c32012-11-19 14:55:58 -08002245}
2246
Eric Laurent81784c32012-11-19 14:55:58 -08002247// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
2248sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
2249 const sp<AudioFlinger::Client>& client,
2250 audio_stream_type_t streamType,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07002251 const audio_attributes_t& attr,
Eric Laurent21da6472017-11-09 16:29:26 -08002252 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08002253 audio_format_t format,
2254 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08002255 size_t *pFrameCount,
Eric Laurent21da6472017-11-09 16:29:26 -08002256 size_t *pNotificationFrameCount,
2257 uint32_t notificationsPerBuffer,
2258 float speed,
Eric Laurent81784c32012-11-19 14:55:58 -08002259 const sp<IMemory>& sharedBuffer,
Glenn Kastend848eb42016-03-08 13:42:11 -08002260 audio_session_t sessionId,
Eric Laurent05067782016-06-01 18:27:28 -07002261 audio_output_flags_t *flags,
Eric Laurent09f1ed22019-04-24 17:45:17 -07002262 pid_t creatorPid,
Svet Ganov33761132021-05-13 22:51:08 +00002263 const AttributionSourceState& attributionSource,
Eric Laurent81784c32012-11-19 14:55:58 -08002264 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002265 status_t *status,
jiabinf6eb4c32020-02-25 14:06:25 -08002266 audio_port_handle_t portId,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02002267 const sp<media::IAudioTrackCallback>& callback,
2268 bool isSpatialized)
Eric Laurent81784c32012-11-19 14:55:58 -08002269{
Glenn Kasten74935e42013-12-19 08:56:45 -08002270 size_t frameCount = *pFrameCount;
Eric Laurent21da6472017-11-09 16:29:26 -08002271 size_t notificationFrameCount = *pNotificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08002272 sp<Track> track;
2273 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07002274 audio_output_flags_t outputFlags = mOutput->flags;
Eric Laurent21da6472017-11-09 16:29:26 -08002275 audio_output_flags_t requestedFlags = *flags;
Eric Laurent9b11c022018-06-06 19:19:22 -07002276 uint32_t sampleRate;
2277
2278 if (sharedBuffer != 0 && checkIMemory(sharedBuffer) != NO_ERROR) {
2279 lStatus = BAD_VALUE;
2280 goto Exit;
2281 }
Eric Laurent21da6472017-11-09 16:29:26 -08002282
2283 if (*pSampleRate == 0) {
2284 *pSampleRate = mSampleRate;
2285 }
Eric Laurent9b11c022018-06-06 19:19:22 -07002286 sampleRate = *pSampleRate;
Eric Laurent05067782016-06-01 18:27:28 -07002287
2288 // special case for FAST flag considered OK if fast mixer is present
2289 if (hasFastMixer()) {
2290 outputFlags = (audio_output_flags_t)(outputFlags | AUDIO_OUTPUT_FLAG_FAST);
2291 }
2292
2293 // Check if requested flags are compatible with output stream flags
2294 if ((*flags & outputFlags) != *flags) {
2295 ALOGW("createTrack_l(): mismatch between requested flags (%08x) and output flags (%08x)",
2296 *flags, outputFlags);
2297 *flags = (audio_output_flags_t)(*flags & outputFlags);
2298 }
Eric Laurent81784c32012-11-19 14:55:58 -08002299
Eric Laurent81784c32012-11-19 14:55:58 -08002300 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07002301 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
Eric Laurent81784c32012-11-19 14:55:58 -08002302 if (
Eric Laurent81784c32012-11-19 14:55:58 -08002303 // PCM data
2304 audio_is_linear_pcm(format) &&
Andy Hung1f439e12015-05-19 12:57:41 -07002305 // TODO: extract as a data library function that checks that a computationally
2306 // expensive downmixer is not required: isFastOutputChannelConversion()
jiabin245cdd92018-12-07 17:55:15 -08002307 (channelMask == (mChannelMask | mHapticChannelMask) ||
Andy Hung1f439e12015-05-19 12:57:41 -07002308 mChannelMask != AUDIO_CHANNEL_OUT_STEREO ||
2309 (channelMask == AUDIO_CHANNEL_OUT_MONO
2310 /* && mChannelMask == AUDIO_CHANNEL_OUT_STEREO */)) &&
Eric Laurent81784c32012-11-19 14:55:58 -08002311 // hardware sample rate
2312 (sampleRate == mSampleRate) &&
Eric Laurent81784c32012-11-19 14:55:58 -08002313 // normal mixer has an associated fast mixer
2314 hasFastMixer() &&
2315 // there are sufficient fast track slots available
2316 (mFastTrackAvailMask != 0)
2317 // FIXME test that MixerThread for this fast track has a capable output HAL
2318 // FIXME add a permission test also?
2319 ) {
Andy Hunge0a269a2016-03-23 15:13:42 -07002320 // static tracks can have any nonzero framecount, streaming tracks check against minimum.
2321 if (sharedBuffer == 0) {
Glenn Kasten03490092014-05-27 12:30:54 -07002322 // read the fast track multiplier property the first time it is needed
2323 int ok = pthread_once(&sFastTrackMultiplierOnce, sFastTrackMultiplierInit);
2324 if (ok != 0) {
2325 ALOGE("%s pthread_once failed: %d", __func__, ok);
2326 }
Andy Hunge0a269a2016-03-23 15:13:42 -07002327 frameCount = max(frameCount, mFrameCount * sFastTrackMultiplier); // incl framecount 0
Eric Laurent81784c32012-11-19 14:55:58 -08002328 }
Eric Laurent4c415062016-06-17 16:14:16 -07002329
2330 // check compatibility with audio effects.
2331 { // scope for mLock
2332 Mutex::Autolock _l(mLock);
Andy Hungd3bb0ad2016-10-11 17:16:43 -07002333 for (audio_session_t session : {
Eric Laurent3f75a5b2019-11-12 15:55:51 -08002334 AUDIO_SESSION_DEVICE,
Andy Hungd3bb0ad2016-10-11 17:16:43 -07002335 AUDIO_SESSION_OUTPUT_STAGE,
2336 AUDIO_SESSION_OUTPUT_MIX,
2337 sessionId,
2338 }) {
2339 sp<EffectChain> chain = getEffectChain_l(session);
2340 if (chain.get() != nullptr) {
2341 audio_output_flags_t old = *flags;
2342 chain->checkOutputFlagCompatibility(flags);
2343 if (old != *flags) {
2344 ALOGV("AUDIO_OUTPUT_FLAGS denied by effect, session=%d old=%#x new=%#x",
2345 (int)session, (int)old, (int)*flags);
2346 }
Eric Laurent4c415062016-06-17 16:14:16 -07002347 }
2348 }
2349 }
Eric Laurent122f7e72016-06-29 11:53:29 -07002350 ALOGV_IF((*flags & AUDIO_OUTPUT_FLAG_FAST) != 0,
Eric Laurent4c415062016-06-17 16:14:16 -07002351 "AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
2352 frameCount, mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08002353 } else {
Robert Wu4c7bb7d2021-08-12 18:50:13 +00002354 ALOGD("AUDIO_OUTPUT_FLAG_FAST denied: sharedBuffer=%p frameCount=%zu "
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002355 "mFrameCount=%zu format=%#x mFormat=%#x isLinear=%d channelMask=%#x "
Andy Hung6146c082014-03-18 11:56:15 -07002356 "sampleRate=%u mSampleRate=%u "
Eric Laurent81784c32012-11-19 14:55:58 -08002357 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
Glenn Kastend79072e2016-01-06 08:41:20 -08002358 sharedBuffer.get(), frameCount, mFrameCount, format, mFormat,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07002359 audio_is_linear_pcm(format), channelMask, sampleRate,
2360 mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
Eric Laurent4c415062016-06-17 16:14:16 -07002361 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_FAST);
Andy Hung0e48d252015-01-26 11:43:15 -08002362 }
2363 }
Eric Laurent21da6472017-11-09 16:29:26 -08002364
2365 if (!audio_has_proportional_frames(format)) {
2366 if (sharedBuffer != 0) {
2367 // Same comment as below about ignoring frameCount parameter for set()
2368 frameCount = sharedBuffer->size();
2369 } else if (frameCount == 0) {
2370 frameCount = mNormalFrameCount;
2371 }
2372 if (notificationFrameCount != frameCount) {
2373 notificationFrameCount = frameCount;
2374 }
2375 } else if (sharedBuffer != 0) {
2376 // FIXME: Ensure client side memory buffers need
2377 // not have additional alignment beyond sample
2378 // (e.g. 16 bit stereo accessed as 32 bit frame).
2379 size_t alignment = audio_bytes_per_sample(format);
2380 if (alignment & 1) {
2381 // for AUDIO_FORMAT_PCM_24_BIT_PACKED (not exposed through Java).
2382 alignment = 1;
2383 }
2384 uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
2385 size_t frameSize = channelCount * audio_bytes_per_sample(format);
2386 if (channelCount > 1) {
2387 // More than 2 channels does not require stronger alignment than stereo
2388 alignment <<= 1;
2389 }
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07002390 if (((uintptr_t)sharedBuffer->unsecurePointer() & (alignment - 1)) != 0) {
Eric Laurent21da6472017-11-09 16:29:26 -08002391 ALOGE("Invalid buffer alignment: address %p, channel count %u",
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07002392 sharedBuffer->unsecurePointer(), channelCount);
Eric Laurent21da6472017-11-09 16:29:26 -08002393 lStatus = BAD_VALUE;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002394 goto Exit;
2395 }
Eric Laurent21da6472017-11-09 16:29:26 -08002396
2397 // When initializing a shared buffer AudioTrack via constructors,
2398 // there's no frameCount parameter.
2399 // But when initializing a shared buffer AudioTrack via set(),
2400 // there _is_ a frameCount parameter. We silently ignore it.
2401 frameCount = sharedBuffer->size() / frameSize;
2402 } else {
2403 size_t minFrameCount = 0;
2404 // For fast tracks we try to respect the application's request for notifications per buffer.
2405 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
2406 if (notificationsPerBuffer > 0) {
2407 // Avoid possible arithmetic overflow during multiplication.
2408 if (notificationsPerBuffer > SIZE_MAX / mFrameCount) {
2409 ALOGE("Requested notificationPerBuffer=%u ignored for HAL frameCount=%zu",
2410 notificationsPerBuffer, mFrameCount);
2411 } else {
2412 minFrameCount = mFrameCount * notificationsPerBuffer;
2413 }
2414 }
2415 } else {
2416 // For normal PCM streaming tracks, update minimum frame count.
2417 // Buffer depth is forced to be at least 2 x the normal mixer frame count and
2418 // cover audio hardware latency.
2419 // This is probably too conservative, but legacy application code may depend on it.
2420 // If you change this calculation, also review the start threshold which is related.
2421 uint32_t latencyMs = latency_l();
2422 if (latencyMs == 0) {
2423 ALOGE("Error when retrieving output stream latency");
2424 lStatus = UNKNOWN_ERROR;
2425 goto Exit;
2426 }
2427
2428 minFrameCount = AudioSystem::calculateMinFrameCount(latencyMs, mNormalFrameCount,
2429 mSampleRate, sampleRate, speed /*, 0 mNotificationsPerBufferReq*/);
2430
Eric Laurent81784c32012-11-19 14:55:58 -08002431 }
Eric Laurent21da6472017-11-09 16:29:26 -08002432 if (frameCount < minFrameCount) {
Eric Laurent81784c32012-11-19 14:55:58 -08002433 frameCount = minFrameCount;
2434 }
Eric Laurent81784c32012-11-19 14:55:58 -08002435 }
Eric Laurent21da6472017-11-09 16:29:26 -08002436
2437 // Make sure that application is notified with sufficient margin before underrun.
2438 // The client can divide the AudioTrack buffer into sub-buffers,
2439 // and expresses its desire to server as the notification frame count.
2440 if (sharedBuffer == 0 && audio_is_linear_pcm(format)) {
2441 size_t maxNotificationFrames;
2442 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
2443 // notify every HAL buffer, regardless of the size of the track buffer
2444 maxNotificationFrames = mFrameCount;
2445 } else {
Andy Hungfa117802019-04-12 13:50:39 -07002446 // Triple buffer the notification period for a triple buffered mixer period;
2447 // otherwise, double buffering for the notification period is fine.
2448 //
2449 // TODO: This should be moved to AudioTrack to modify the notification period
2450 // on AudioTrack::setBufferSizeInFrames() changes.
2451 const int nBuffering =
2452 (uint64_t{frameCount} * mSampleRate)
2453 / (uint64_t{mNormalFrameCount} * sampleRate) == 3 ? 3 : 2;
2454
Eric Laurent21da6472017-11-09 16:29:26 -08002455 maxNotificationFrames = frameCount / nBuffering;
2456 // If client requested a fast track but this was denied, then use the smaller maximum.
2457 if (requestedFlags & AUDIO_OUTPUT_FLAG_FAST) {
2458 size_t maxNotificationFramesFastDenied = FMS_20 * sampleRate / 1000;
2459 if (maxNotificationFrames > maxNotificationFramesFastDenied) {
2460 maxNotificationFrames = maxNotificationFramesFastDenied;
2461 }
2462 }
2463 }
2464 if (notificationFrameCount == 0 || notificationFrameCount > maxNotificationFrames) {
2465 if (notificationFrameCount == 0) {
2466 ALOGD("Client defaulted notificationFrames to %zu for frameCount %zu",
2467 maxNotificationFrames, frameCount);
2468 } else {
2469 ALOGW("Client adjusted notificationFrames from %zu to %zu for frameCount %zu",
2470 notificationFrameCount, maxNotificationFrames, frameCount);
2471 }
2472 notificationFrameCount = maxNotificationFrames;
2473 }
2474 }
2475
Glenn Kasten74935e42013-12-19 08:56:45 -08002476 *pFrameCount = frameCount;
Eric Laurent21da6472017-11-09 16:29:26 -08002477 *pNotificationFrameCount = notificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08002478
Glenn Kastenc3df8382014-03-13 15:05:25 -07002479 switch (mType) {
2480
2481 case DIRECT:
Phil Burkfdb3c072016-02-09 10:47:02 -08002482 if (audio_is_linear_pcm(format)) { // TODO maybe use audio_has_proportional_frames()?
Eric Laurent81784c32012-11-19 14:55:58 -08002483 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002484 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
2485 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08002486 sampleRate, format, channelMask, mOutput, mFormat);
2487 lStatus = BAD_VALUE;
2488 goto Exit;
2489 }
2490 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002491 break;
2492
2493 case OFFLOAD:
Eric Laurentbfb1b832013-01-07 09:53:42 -08002494 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002495 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
2496 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002497 sampleRate, format, channelMask, mOutput, mFormat);
2498 lStatus = BAD_VALUE;
2499 goto Exit;
2500 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002501 break;
2502
2503 default:
Glenn Kasten993fa062014-05-02 11:14:34 -07002504 if (!audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002505 ALOGE("createTrack_l() Bad parameter: format %#x \""
2506 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002507 format, mOutput, mFormat);
2508 lStatus = BAD_VALUE;
2509 goto Exit;
2510 }
Andy Hungcd044842014-08-07 11:04:34 -07002511 if (sampleRate > mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Eric Laurent81784c32012-11-19 14:55:58 -08002512 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
2513 lStatus = BAD_VALUE;
2514 goto Exit;
2515 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002516 break;
2517
Eric Laurent81784c32012-11-19 14:55:58 -08002518 }
2519
2520 lStatus = initCheck();
2521 if (lStatus != NO_ERROR) {
Glenn Kasten15e57982013-09-24 11:52:37 -07002522 ALOGE("createTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08002523 goto Exit;
2524 }
2525
2526 { // scope for mLock
2527 Mutex::Autolock _l(mLock);
2528
2529 // all tracks in same audio session must share the same routing strategy otherwise
2530 // conflicts will happen when tracks are moved from one output to another by audio policy
2531 // manager
Eric Laurentd66d7a12021-07-13 13:35:32 +02002532 product_strategy_t strategy = getStrategyForStream(streamType);
Eric Laurent81784c32012-11-19 14:55:58 -08002533 for (size_t i = 0; i < mTracks.size(); ++i) {
2534 sp<Track> t = mTracks[i];
Eric Laurent83b88082014-06-20 18:31:16 -07002535 if (t != 0 && t->isExternalTrack()) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02002536 product_strategy_t actual = getStrategyForStream(t->streamType());
Eric Laurent81784c32012-11-19 14:55:58 -08002537 if (sessionId == t->sessionId() && strategy != actual) {
2538 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
2539 strategy, actual);
2540 lStatus = BAD_VALUE;
2541 goto Exit;
2542 }
2543 }
2544 }
2545
yucliuc9c49cd2020-07-13 16:25:21 -07002546 // Set DIRECT flag if current thread is DirectOutputThread. This can
2547 // happen when the playback is rerouted to direct output thread by
2548 // dynamic audio policy.
2549 // Do NOT report the flag changes back to client, since the client
2550 // doesn't explicitly request a direct flag.
2551 audio_output_flags_t trackFlags = *flags;
2552 if (mType == DIRECT) {
2553 trackFlags = static_cast<audio_output_flags_t>(trackFlags | AUDIO_OUTPUT_FLAG_DIRECT);
2554 }
2555
Kevin Rocard1f564ac2018-03-29 13:53:10 -07002556 track = new Track(this, client, streamType, attr, sampleRate, format,
Andy Hung8fe68032017-06-05 16:17:51 -07002557 channelMask, frameCount,
2558 nullptr /* buffer */, (size_t)0 /* bufferSize */, sharedBuffer,
Svet Ganov33761132021-05-13 22:51:08 +00002559 sessionId, creatorPid, attributionSource, trackFlags,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02002560 TrackBase::TYPE_DEFAULT, portId, SIZE_MAX /*frameCountToBeReady*/,
2561 speed, isSpatialized);
Glenn Kasten03003332013-08-06 15:40:54 -07002562
Glenn Kasten03003332013-08-06 15:40:54 -07002563 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
2564 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08002565 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08002566 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08002567 goto Exit;
2568 }
2569 mTracks.add(track);
jiabinf6eb4c32020-02-25 14:06:25 -08002570 {
2571 Mutex::Autolock _atCbL(mAudioTrackCbLock);
2572 if (callback.get() != nullptr) {
jiabin18a4b1c2020-09-17 11:40:42 -07002573 mAudioTrackCallbacks.emplace(track, callback);
jiabinf6eb4c32020-02-25 14:06:25 -08002574 }
2575 }
Eric Laurent81784c32012-11-19 14:55:58 -08002576
2577 sp<EffectChain> chain = getEffectChain_l(sessionId);
2578 if (chain != 0) {
2579 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
2580 track->setMainBuffer(chain->inBuffer());
Eric Laurentd66d7a12021-07-13 13:35:32 +02002581 chain->setStrategy(getStrategyForStream(track->streamType()));
Eric Laurent81784c32012-11-19 14:55:58 -08002582 chain->incTrackCnt();
2583 }
2584
Eric Laurent05067782016-06-01 18:27:28 -07002585 if ((*flags & AUDIO_OUTPUT_FLAG_FAST) && (tid != -1)) {
Eric Laurent81784c32012-11-19 14:55:58 -08002586 pid_t callingPid = IPCThreadState::self()->getCallingPid();
2587 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
2588 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07002589 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08002590 }
2591 }
2592
2593 lStatus = NO_ERROR;
2594
2595Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07002596 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08002597 return track;
2598}
2599
Andy Hung1bc088a2018-02-09 15:57:31 -08002600template<typename T>
Andy Hung1bc088a2018-02-09 15:57:31 -08002601ssize_t AudioFlinger::PlaybackThread::Tracks<T>::remove(const sp<T> &track)
2602{
Andy Hungc0691382018-09-12 18:01:57 -07002603 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08002604 const ssize_t index = mTracks.remove(track);
2605 if (index >= 0) {
Andy Hungc0691382018-09-12 18:01:57 -07002606 if (mSaveDeletedTrackIds) {
Andy Hung1bc088a2018-02-09 15:57:31 -08002607 // We can't directly access mAudioMixer since the caller may be outside of threadLoop.
Andy Hungc0691382018-09-12 18:01:57 -07002608 // Instead, we add to mDeletedTrackIds which is solely used for mAudioMixer update,
Andy Hung1bc088a2018-02-09 15:57:31 -08002609 // to be handled when MixerThread::prepareTracks_l() next changes mAudioMixer.
Andy Hungc0691382018-09-12 18:01:57 -07002610 mDeletedTrackIds.emplace(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08002611 }
Andy Hung1bc088a2018-02-09 15:57:31 -08002612 }
2613 return index;
2614}
2615
Eric Laurent81784c32012-11-19 14:55:58 -08002616uint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const
2617{
2618 return latency;
2619}
2620
2621uint32_t AudioFlinger::PlaybackThread::latency() const
2622{
2623 Mutex::Autolock _l(mLock);
2624 return latency_l();
2625}
2626uint32_t AudioFlinger::PlaybackThread::latency_l() const
2627{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002628 uint32_t latency;
2629 if (initCheck() == NO_ERROR && mOutput->stream->getLatency(&latency) == OK) {
2630 return correctLatency_l(latency);
Eric Laurent81784c32012-11-19 14:55:58 -08002631 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002632 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002633}
2634
2635void AudioFlinger::PlaybackThread::setMasterVolume(float value)
2636{
2637 Mutex::Autolock _l(mLock);
2638 // Don't apply master volume in SW if our HAL can do it for us.
2639 if (mOutput && mOutput->audioHwDev &&
2640 mOutput->audioHwDev->canSetMasterVolume()) {
2641 mMasterVolume = 1.0;
2642 } else {
2643 mMasterVolume = value;
2644 }
2645}
2646
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01002647void AudioFlinger::PlaybackThread::setMasterBalance(float balance)
2648{
2649 mMasterBalance.store(balance);
2650}
2651
Eric Laurent81784c32012-11-19 14:55:58 -08002652void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
2653{
Eric Laurent6acd1d42017-01-04 14:23:29 -08002654 if (isDuplicating()) {
2655 return;
2656 }
Eric Laurent81784c32012-11-19 14:55:58 -08002657 Mutex::Autolock _l(mLock);
2658 // Don't apply master mute in SW if our HAL can do it for us.
2659 if (mOutput && mOutput->audioHwDev &&
2660 mOutput->audioHwDev->canSetMasterMute()) {
2661 mMasterMute = false;
2662 } else {
2663 mMasterMute = muted;
2664 }
2665}
2666
2667void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
2668{
2669 Mutex::Autolock _l(mLock);
2670 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002671 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002672}
2673
2674void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
2675{
2676 Mutex::Autolock _l(mLock);
2677 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002678 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002679}
2680
2681float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
2682{
2683 Mutex::Autolock _l(mLock);
2684 return mStreamTypes[stream].volume;
2685}
2686
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09002687void AudioFlinger::PlaybackThread::setVolumeForOutput_l(float left, float right) const
2688{
2689 mOutput->stream->setVolume(left, right);
2690}
2691
Eric Laurent81784c32012-11-19 14:55:58 -08002692// addTrack_l() must be called with ThreadBase::mLock held
2693status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
2694{
2695 status_t status = ALREADY_EXISTS;
2696
Eric Laurent81784c32012-11-19 14:55:58 -08002697 if (mActiveTracks.indexOf(track) < 0) {
2698 // the track is newly added, make sure it fills up all its
2699 // buffers before playing. This is to ensure the client will
2700 // effectively get the latency it requested.
Eric Laurent83b88082014-06-20 18:31:16 -07002701 if (track->isExternalTrack()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002702 TrackBase::track_state state = track->mState;
2703 mLock.unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002704 status = AudioSystem::startOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002705 mLock.lock();
2706 // abort track was stopped/paused while we released the lock
2707 if (state != track->mState) {
2708 if (status == NO_ERROR) {
2709 mLock.unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002710 AudioSystem::stopOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002711 mLock.lock();
2712 }
2713 return INVALID_OPERATION;
2714 }
2715 // abort if start is rejected by audio policy manager
2716 if (status != NO_ERROR) {
2717 return PERMISSION_DENIED;
2718 }
2719#ifdef ADD_BATTERY_DATA
2720 // to track the speaker usage
2721 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
2722#endif
Eric Laurent09f1ed22019-04-24 17:45:17 -07002723 sendIoConfigEvent_l(AUDIO_CLIENT_STARTED, track->creatorPid(), track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002724 }
2725
Eric Laurent51716182016-02-29 18:00:56 -08002726 // set retry count for buffer fill
2727 if (track->isOffloaded()) {
Eric Laurente93cc032016-05-05 10:15:10 -07002728 if (track->isStopping_1()) {
2729 track->mRetryCount = kMaxTrackStopRetriesOffload;
2730 } else {
2731 track->mRetryCount = kMaxTrackStartupRetriesOffload;
2732 }
2733 track->mFillingUpStatus = mStandby ? Track::FS_FILLING : Track::FS_FILLED;
Eric Laurent51716182016-02-29 18:00:56 -08002734 } else {
2735 track->mRetryCount = kMaxTrackStartupRetries;
Eric Laurente93cc032016-05-05 10:15:10 -07002736 track->mFillingUpStatus =
2737 track->sharedBuffer() != 0 ? Track::FS_FILLED : Track::FS_FILLING;
Eric Laurent51716182016-02-29 18:00:56 -08002738 }
2739
jiabineb3bda02020-06-30 14:07:03 -07002740 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2741 if (mHapticChannelMask != AUDIO_CHANNEL_NONE
2742 && ((track->channelMask() & AUDIO_CHANNEL_HAPTIC_ALL) != AUDIO_CHANNEL_NONE
2743 || (chain != nullptr && chain->containsHapticGeneratingEffect_l()))) {
jiabin57303cc2018-12-18 15:45:57 -08002744 // Unlock due to VibratorService will lock for this call and will
2745 // call Tracks.mute/unmute which also require thread's lock.
2746 mLock.unlock();
Simon Bowden62823412022-10-17 14:52:26 +00002747 const os::HapticScale intensity = AudioFlinger::onExternalVibrationStart(
jiabin57303cc2018-12-18 15:45:57 -08002748 track->getExternalVibration());
Lais Andradebc3f37a2021-07-02 00:13:19 +01002749 std::optional<media::AudioVibratorInfo> vibratorInfo;
2750 {
2751 // TODO(b/184194780): Use the vibrator information from the vibrator that will be
2752 // used to play this track.
2753 Mutex::Autolock _l(mAudioFlinger->mLock);
2754 vibratorInfo = std::move(mAudioFlinger->getDefaultVibratorInfo_l());
2755 }
jiabin57303cc2018-12-18 15:45:57 -08002756 mLock.lock();
Simon Bowden62823412022-10-17 14:52:26 +00002757 track->setHapticIntensity(intensity);
Lais Andradebc3f37a2021-07-02 00:13:19 +01002758 if (vibratorInfo) {
2759 track->setHapticMaxAmplitude(vibratorInfo->maxAmplitude);
2760 }
2761
jiabin57303cc2018-12-18 15:45:57 -08002762 // Haptic playback should be enabled by vibrator service.
2763 if (track->getHapticPlaybackEnabled()) {
2764 // Disable haptic playback of all active track to ensure only
2765 // one track playing haptic if current track should play haptic.
2766 for (const auto &t : mActiveTracks) {
2767 t->setHapticPlaybackEnabled(false);
2768 }
jiabin245cdd92018-12-07 17:55:15 -08002769 }
jiabine70bc7f2020-06-30 22:07:55 -07002770
2771 // Set haptic intensity for effect
2772 if (chain != nullptr) {
2773 chain->setHapticIntensity_l(track->id(), intensity);
2774 }
jiabin245cdd92018-12-07 17:55:15 -08002775 }
2776
Eric Laurent81784c32012-11-19 14:55:58 -08002777 track->mResetDone = false;
Andy Hung59de4262021-06-14 10:53:54 -07002778 track->resetPresentationComplete();
Eric Laurent81784c32012-11-19 14:55:58 -08002779 mActiveTracks.add(track);
Eric Laurentd0107bc2013-06-11 14:38:48 -07002780 if (chain != 0) {
2781 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
2782 track->sessionId());
2783 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08002784 }
2785
Andy Hungc2b11cb2020-04-22 09:04:01 -07002786 track->logBeginInterval(patchSinksToString(&mPatch)); // log to MediaMetrics
Eric Laurent81784c32012-11-19 14:55:58 -08002787 status = NO_ERROR;
2788 }
2789
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08002790 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002791 return status;
2792}
2793
Eric Laurentbfb1b832013-01-07 09:53:42 -08002794bool AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002795{
Eric Laurentbfb1b832013-01-07 09:53:42 -08002796 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08002797 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002798 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
2799 track->mState = TrackBase::STOPPED;
2800 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08002801 removeTrack_l(track);
Eric Laurentab5cdba2014-06-09 17:22:27 -07002802 } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002803 track->mState = TrackBase::STOPPING_1;
Eric Laurent81784c32012-11-19 14:55:58 -08002804 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002805
2806 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08002807}
2808
2809void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
2810{
2811 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Andy Hung2148bf02016-11-28 19:01:02 -08002812
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002813 String8 result;
2814 track->appendDump(result, false /* active */);
2815 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.string());
Andy Hung2148bf02016-11-28 19:01:02 -08002816
Eric Laurent81784c32012-11-19 14:55:58 -08002817 mTracks.remove(track);
jiabin18a4b1c2020-09-17 11:40:42 -07002818 {
2819 Mutex::Autolock _atCbL(mAudioTrackCbLock);
2820 mAudioTrackCallbacks.erase(track);
2821 }
Eric Laurent81784c32012-11-19 14:55:58 -08002822 if (track->isFastTrack()) {
2823 int index = track->mFastIndex;
Glenn Kastendc2c50b2016-04-21 08:13:14 -07002824 ALOG_ASSERT(0 < index && index < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08002825 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
2826 mFastTrackAvailMask |= 1 << index;
2827 // redundant as track is about to be destroyed, for dumpsys only
2828 track->mFastIndex = -1;
2829 }
2830 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2831 if (chain != 0) {
2832 chain->decTrackCnt();
2833 }
2834}
2835
2836String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
2837{
Eric Laurent81784c32012-11-19 14:55:58 -08002838 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002839 String8 out_s8;
2840 if (initCheck() == NO_ERROR && mOutput->stream->getParameters(keys, &out_s8) == OK) {
2841 return out_s8;
Eric Laurent81784c32012-11-19 14:55:58 -08002842 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002843 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08002844}
2845
Mikhail Naganovac917ac2018-11-28 14:03:52 -08002846status_t AudioFlinger::DirectOutputThread::selectPresentation(int presentationId, int programId) {
2847 Mutex::Autolock _l(mLock);
Jasmine Chaeaa10e42021-05-11 10:11:14 +08002848 if (!isStreamInitialized()) {
Mikhail Naganovac917ac2018-11-28 14:03:52 -08002849 return NO_INIT;
2850 }
2851 return mOutput->stream->selectPresentation(presentationId, programId);
2852}
2853
Mikhail Naganov88536df2021-07-26 17:30:29 -07002854void AudioFlinger::PlaybackThread::ioConfigChanged(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -07002855 audio_port_handle_t portId) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002856 ALOGV("PlaybackThread::ioConfigChanged, thread %p, event %d", this, event);
Mikhail Naganov88536df2021-07-26 17:30:29 -07002857 sp<AudioIoDescriptor> desc;
2858 const struct audio_patch patch = isMsdDevice() ? mDownStreamPatch : mPatch;
Eric Laurent81784c32012-11-19 14:55:58 -08002859 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002860 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07002861 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07002862 case AUDIO_OUTPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07002863 desc = sp<AudioIoDescriptor>::make(mId, patch, false /*isInput*/,
2864 mSampleRate, mFormat, mChannelMask,
2865 // FIXME AudioFlinger::frameCount(audio_io_handle_t) instead of mNormalFrameCount?
2866 mNormalFrameCount, mFrameCount, latency_l());
Eric Laurent81784c32012-11-19 14:55:58 -08002867 break;
Eric Laurent09f1ed22019-04-24 17:45:17 -07002868 case AUDIO_CLIENT_STARTED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07002869 desc = sp<AudioIoDescriptor>::make(mId, patch, portId);
Eric Laurent09f1ed22019-04-24 17:45:17 -07002870 break;
Eric Laurent73e26b62015-04-27 16:55:58 -07002871 case AUDIO_OUTPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08002872 default:
Mikhail Naganov88536df2021-07-26 17:30:29 -07002873 desc = sp<AudioIoDescriptor>::make(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08002874 break;
2875 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002876 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08002877}
2878
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002879void AudioFlinger::PlaybackThread::onWriteReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002880{
Eric Laurent3b4529e2013-09-05 18:09:19 -07002881 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002882}
2883
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002884void AudioFlinger::PlaybackThread::onDrainReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002885{
Eric Laurent3b4529e2013-09-05 18:09:19 -07002886 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002887}
2888
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002889void AudioFlinger::PlaybackThread::onError()
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002890{
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002891 mCallbackThread->setAsyncError();
2892}
2893
jiabinf6eb4c32020-02-25 14:06:25 -08002894void AudioFlinger::PlaybackThread::onCodecFormatChanged(
2895 const std::basic_string<uint8_t>& metadataBs)
2896{
2897 std::thread([this, metadataBs]() {
2898 audio_utils::metadata::Data metadata =
2899 audio_utils::metadata::dataFromByteString(metadataBs);
2900 if (metadata.empty()) {
2901 ALOGW("Can not transform the buffer to audio metadata, %s, %d",
2902 reinterpret_cast<char*>(const_cast<uint8_t*>(metadataBs.data())),
2903 (int)metadataBs.size());
2904 return;
2905 }
2906
2907 audio_utils::metadata::ByteString metaDataStr =
2908 audio_utils::metadata::byteStringFromData(metadata);
2909 std::vector metadataVec(metaDataStr.begin(), metaDataStr.end());
2910 Mutex::Autolock _l(mAudioTrackCbLock);
jiabin18a4b1c2020-09-17 11:40:42 -07002911 for (const auto& callbackPair : mAudioTrackCallbacks) {
2912 callbackPair.second->onCodecFormatChanged(metadataVec);
jiabinf6eb4c32020-02-25 14:06:25 -08002913 }
2914 }).detach();
2915}
2916
Eric Laurent3b4529e2013-09-05 18:09:19 -07002917void AudioFlinger::PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002918{
2919 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002920 // reject out of sequence requests
2921 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
2922 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002923 mWaitWorkCV.signal();
2924 }
2925}
2926
Eric Laurent3b4529e2013-09-05 18:09:19 -07002927void AudioFlinger::PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002928{
2929 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002930 // reject out of sequence requests
2931 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
Andy Hungf3234512018-07-03 14:51:47 -07002932 // Register discontinuity when HW drain is completed because that can cause
2933 // the timestamp frame position to reset to 0 for direct and offload threads.
2934 // (Out of sequence requests are ignored, since the discontinuity would be handled
2935 // elsewhere, e.g. in flush).
Dean Wheatley12473e92021-03-18 23:00:55 +11002936 mTimestampVerifier.discontinuity(mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002937 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002938 mWaitWorkCV.signal();
2939 }
2940}
2941
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002942void AudioFlinger::PlaybackThread::readOutputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08002943{
Glenn Kastenadad3d72014-02-21 14:51:43 -08002944 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Mikhail Naganov560637e2021-03-31 22:40:13 +00002945 const audio_config_base_t audioConfig = mOutput->getAudioProperties();
2946 mSampleRate = audioConfig.sample_rate;
2947 mChannelMask = audioConfig.channel_mask;
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002948 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002949 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002950 }
Eric Laurentb3f315a2021-07-13 15:09:05 +02002951 if (hasMixer() && !isValidPcmSinkChannelMask(mChannelMask)) {
Andy Hung9a592762014-07-21 21:56:01 -07002952 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output",
2953 mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002954 }
Eric Laurentf1f22e72021-07-13 14:04:14 +02002955
2956 if (mMixerChannelMask == AUDIO_CHANNEL_NONE) {
2957 mMixerChannelMask = mChannelMask;
2958 }
2959
Andy Hunge5412692014-05-16 11:25:07 -07002960 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01002961 mBalance.setChannelMask(mChannelMask);
Phil Burkca5e6142015-07-14 09:42:29 -07002962
Eric Laurentf1f22e72021-07-13 14:04:14 +02002963 uint32_t mixerChannelCount = audio_channel_count_from_out_mask(mMixerChannelMask);
2964
Phil Burkca5e6142015-07-14 09:42:29 -07002965 // Get actual HAL format.
Mikhail Naganov560637e2021-03-31 22:40:13 +00002966 status_t result = mOutput->stream->getAudioProperties(nullptr, nullptr, &mHALFormat);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002967 LOG_ALWAYS_FATAL_IF(result != OK, "Error when retrieving output stream format: %d", result);
Phil Burkca5e6142015-07-14 09:42:29 -07002968 // Get format from the shim, which will be different than the HAL format
2969 // if playing compressed audio over HDMI passthrough.
Mikhail Naganov560637e2021-03-31 22:40:13 +00002970 mFormat = audioConfig.format;
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002971 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002972 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002973 }
Eric Laurentb3f315a2021-07-13 15:09:05 +02002974 if (hasMixer() && !isValidPcmSinkFormat(mFormat)) {
Andy Hung6146c082014-03-18 11:56:15 -07002975 LOG_FATAL("HAL format %#x not supported for mixed output",
2976 mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002977 }
Phil Burk062e67a2015-02-11 13:40:50 -08002978 mFrameSize = mOutput->getFrameSize();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002979 result = mOutput->stream->getBufferSize(&mBufferSize);
2980 LOG_ALWAYS_FATAL_IF(result != OK,
2981 "Error when retrieving output stream buffer size: %d", result);
Glenn Kasten70949c42013-08-06 07:40:12 -07002982 mFrameCount = mBufferSize / mFrameSize;
Eric Laurentb3f315a2021-07-13 15:09:05 +02002983 if (hasMixer() && (mFrameCount & 15)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002984 ALOGW("HAL output buffer size is %zu frames but AudioMixer requires multiples of 16 frames",
Eric Laurent81784c32012-11-19 14:55:58 -08002985 mFrameCount);
2986 }
2987
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002988 if (mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING) {
2989 if (mOutput->stream->setCallback(this) == OK) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002990 mUseAsyncWrite = true;
Eric Laurent4de95592013-09-26 15:28:21 -07002991 mCallbackThread = new AudioFlinger::AsyncCallbackThread(this);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002992 }
2993 }
2994
Eric Laurentd1f69b02014-12-15 14:33:13 -08002995 mHwSupportsPause = false;
2996 if (mOutput->flags & AUDIO_OUTPUT_FLAG_DIRECT) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002997 bool supportsPause = false, supportsResume = false;
2998 if (mOutput->stream->supportsPauseAndResume(&supportsPause, &supportsResume) == OK) {
2999 if (supportsPause && supportsResume) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08003000 mHwSupportsPause = true;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003001 } else if (supportsPause) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08003002 ALOGW("direct output implements pause but not resume");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003003 } else if (supportsResume) {
3004 ALOGW("direct output implements resume but not pause");
Eric Laurentd1f69b02014-12-15 14:33:13 -08003005 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08003006 }
3007 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07003008 if (!mHwSupportsPause && mOutput->flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) {
3009 LOG_ALWAYS_FATAL("HW_AV_SYNC requested but HAL does not implement pause and resume");
3010 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08003011
Andy Hungfbfc3952015-01-15 13:33:51 -08003012 if (mType == DUPLICATING && mMixerBufferEnabled && mEffectBufferEnabled) {
3013 // For best precision, we use float instead of the associated output
3014 // device format (typically PCM 16 bit).
3015
3016 mFormat = AUDIO_FORMAT_PCM_FLOAT;
3017 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
3018 mBufferSize = mFrameSize * mFrameCount;
3019
3020 // TODO: We currently use the associated output device channel mask and sample rate.
3021 // (1) Perhaps use the ORed channel mask of all downstream MixerThreads
3022 // (if a valid mask) to avoid premature downmix.
3023 // (2) Perhaps use the maximum sample rate of all downstream MixerThreads
3024 // instead of the output device sample rate to avoid loss of high frequency information.
3025 // This may need to be updated as MixerThread/OutputTracks are added and not here.
3026 }
3027
Andy Hung09a50072014-02-27 14:30:47 -08003028 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08003029 double multiplier = 1.0;
Andy Hungd3639922022-04-28 18:00:49 -07003030 // Note: mType == SPATIALIZER does not support FastMixer.
Eric Laurent81784c32012-11-19 14:55:58 -08003031 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
3032 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08003033 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
3034 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Haynes Mathew George227a14b2016-05-09 12:45:48 -07003035
Eric Laurent81784c32012-11-19 14:55:58 -08003036 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
3037 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
3038 maxNormalFrameCount = maxNormalFrameCount & ~15;
3039 if (maxNormalFrameCount < minNormalFrameCount) {
3040 maxNormalFrameCount = minNormalFrameCount;
3041 }
3042 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
3043 if (multiplier <= 1.0) {
3044 multiplier = 1.0;
3045 } else if (multiplier <= 2.0) {
3046 if (2 * mFrameCount <= maxNormalFrameCount) {
3047 multiplier = 2.0;
3048 } else {
3049 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
3050 }
3051 } else {
Haynes Mathew George227a14b2016-05-09 12:45:48 -07003052 multiplier = floor(multiplier);
Eric Laurent81784c32012-11-19 14:55:58 -08003053 }
3054 }
3055 mNormalFrameCount = multiplier * mFrameCount;
3056 // round up to nearest 16 frames to satisfy AudioMixer
Eric Laurentb3f315a2021-07-13 15:09:05 +02003057 if (hasMixer()) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07003058 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
3059 }
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003060 ALOGI("HAL output buffer size %zu frames, normal sink buffer size %zu frames", mFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08003061 mNormalFrameCount);
3062
Andy Hung08fb1742015-05-31 23:22:10 -07003063 // Check if we want to throttle the processing to no more than 2x normal rate
3064 mThreadThrottle = property_get_bool("af.thread.throttle", true /* default_value */);
Andy Hung40eb1a12015-06-18 13:42:02 -07003065 mThreadThrottleTimeMs = 0;
3066 mThreadThrottleEndMs = 0;
Andy Hung08fb1742015-05-31 23:22:10 -07003067 mHalfBufferMs = mNormalFrameCount * 1000 / (2 * mSampleRate);
3068
Andy Hung010a1a12014-03-13 13:57:33 -07003069 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
3070 // Originally this was int16_t[] array, need to remove legacy implications.
3071 free(mSinkBuffer);
3072 mSinkBuffer = NULL;
Eric Laurent39095982021-08-24 18:29:27 +02003073
Andy Hung5b10a202014-03-13 13:59:29 -07003074 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
3075 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
3076 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07003077 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08003078
Andy Hung69aed5f2014-02-25 17:24:40 -08003079 // We resize the mMixerBuffer according to the requirements of the sink buffer which
3080 // drives the output.
3081 free(mMixerBuffer);
3082 mMixerBuffer = NULL;
3083 if (mMixerBufferEnabled) {
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01003084 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // no longer valid: AUDIO_FORMAT_PCM_16_BIT.
Eric Laurentf1f22e72021-07-13 14:04:14 +02003085 mMixerBufferSize = mNormalFrameCount * mixerChannelCount
Andy Hung69aed5f2014-02-25 17:24:40 -08003086 * audio_bytes_per_sample(mMixerBufferFormat);
3087 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
3088 }
Andy Hung98ef9782014-03-04 14:46:50 -08003089 free(mEffectBuffer);
3090 mEffectBuffer = NULL;
3091 if (mEffectBufferEnabled) {
rago94a1ee82017-07-21 15:11:02 -07003092 mEffectBufferFormat = EFFECT_BUFFER_FORMAT;
Eric Laurentf1f22e72021-07-13 14:04:14 +02003093 mEffectBufferSize = mNormalFrameCount * mixerChannelCount
Andy Hung98ef9782014-03-04 14:46:50 -08003094 * audio_bytes_per_sample(mEffectBufferFormat);
3095 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
3096 }
Andy Hung69aed5f2014-02-25 17:24:40 -08003097
Eric Laurentb62d0362021-10-26 17:40:18 +02003098 if (mType == SPATIALIZER) {
3099 free(mPostSpatializerBuffer);
3100 mPostSpatializerBuffer = nullptr;
3101 mPostSpatializerBufferSize = mNormalFrameCount * mChannelCount
3102 * audio_bytes_per_sample(mEffectBufferFormat);
3103 (void)posix_memalign(&mPostSpatializerBuffer, 32, mPostSpatializerBufferSize);
3104 }
3105
Mikhail Naganov55773032020-10-01 15:08:13 -07003106 mHapticChannelMask = static_cast<audio_channel_mask_t>(mChannelMask & AUDIO_CHANNEL_HAPTIC_ALL);
3107 mChannelMask = static_cast<audio_channel_mask_t>(mChannelMask & ~mHapticChannelMask);
jiabin245cdd92018-12-07 17:55:15 -08003108 mHapticChannelCount = audio_channel_count_from_out_mask(mHapticChannelMask);
3109 mChannelCount -= mHapticChannelCount;
Eric Laurentf1f22e72021-07-13 14:04:14 +02003110 mMixerChannelMask = static_cast<audio_channel_mask_t>(mMixerChannelMask & ~mHapticChannelMask);
jiabin245cdd92018-12-07 17:55:15 -08003111
Eric Laurent81784c32012-11-19 14:55:58 -08003112 // force reconfiguration of effect chains and engines to take new buffer size and audio
3113 // parameters into account
Glenn Kastendeca2ae2014-02-07 10:25:56 -08003114 // Note that mLock is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08003115 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
3116 // matter.
3117 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
3118 Vector< sp<EffectChain> > effectChains = mEffectChains;
3119 for (size_t i = 0; i < effectChains.size(); i ++) {
Eric Laurent6c796322019-04-09 14:13:17 -07003120 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(),
3121 this/* srcThread */, this/* dstThread */);
Eric Laurent81784c32012-11-19 14:55:58 -08003122 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08003123
George Burgess IV5e4d86f2020-02-18 12:55:36 -08003124 audio_output_flags_t flags = mOutput->flags;
Andy Hungcf10d742020-04-28 15:38:24 -07003125 mediametrics::LogItem item(mThreadMetrics.getMetricsId()); // TODO: method in ThreadMetrics?
Andy Hungb68f5eb2019-12-03 16:49:17 -08003126 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
3127 .set(AMEDIAMETRICS_PROP_ENCODING, formatToString(mFormat).c_str())
3128 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
3129 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
3130 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
3131 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mNormalFrameCount)
3132 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
3133 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELMASK,
3134 (int32_t)mHapticChannelMask)
3135 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELCOUNT,
3136 (int32_t)mHapticChannelCount)
3137 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_ENCODING,
3138 formatToString(mHALFormat).c_str())
3139 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_FRAMECOUNT,
3140 (int32_t)mFrameCount) // sic - added HAL
3141 ;
3142 uint32_t latencyMs;
3143 if (mOutput->stream->getLatency(&latencyMs) == NO_ERROR) {
3144 item.set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_LATENCYMS, (double)latencyMs);
3145 }
3146 item.record();
Eric Laurent81784c32012-11-19 14:55:58 -08003147}
3148
Kevin Rocard069c2712018-03-29 19:09:14 -07003149void AudioFlinger::PlaybackThread::updateMetadata_l()
3150{
Jasmine Chaeaa10e42021-05-11 10:11:14 +08003151 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
Kevin Rocard12381092018-04-11 09:19:59 -07003152 return; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -07003153 }
3154 StreamOutHalInterface::SourceMetadata metadata;
Kevin Rocard12381092018-04-11 09:19:59 -07003155 auto backInserter = std::back_inserter(metadata.tracks);
Kevin Rocard069c2712018-03-29 19:09:14 -07003156 for (const sp<Track> &track : mActiveTracks) {
3157 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurent49e39282022-06-24 18:42:45 +02003158 track->copyMetadataTo(backInserter);
Kevin Rocard069c2712018-03-29 19:09:14 -07003159 }
Kevin Rocard12381092018-04-11 09:19:59 -07003160 sendMetadataToBackend_l(metadata);
Kevin Rocard80ee2722018-04-11 15:53:48 +00003161}
Kevin Rocardc86a7f72018-04-03 09:00:09 -07003162
Kevin Rocard12381092018-04-11 09:19:59 -07003163void AudioFlinger::PlaybackThread::sendMetadataToBackend_l(
3164 const StreamOutHalInterface::SourceMetadata& metadata)
3165{
3166 mOutput->stream->updateSourceMetadata(metadata);
3167};
3168
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003169status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
Eric Laurent81784c32012-11-19 14:55:58 -08003170{
3171 if (halFrames == NULL || dspFrames == NULL) {
3172 return BAD_VALUE;
3173 }
3174 Mutex::Autolock _l(mLock);
3175 if (initCheck() != NO_ERROR) {
3176 return INVALID_OPERATION;
3177 }
Andy Hung818e7a32016-02-16 18:08:07 -08003178 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08003179 *halFrames = framesWritten;
3180
3181 if (isSuspended()) {
3182 // return an estimation of rendered frames when the output is suspended
3183 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08003184 *dspFrames = (uint32_t)
3185 (framesWritten >= (int64_t)latencyFrames ? framesWritten - latencyFrames : 0);
Eric Laurent81784c32012-11-19 14:55:58 -08003186 return NO_ERROR;
3187 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003188 status_t status;
3189 uint32_t frames;
Phil Burk062e67a2015-02-11 13:40:50 -08003190 status = mOutput->getRenderPosition(&frames);
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003191 *dspFrames = (size_t)frames;
3192 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08003193 }
3194}
3195
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08003196product_strategy_t AudioFlinger::PlaybackThread::getStrategyForSession_l(audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08003197{
3198 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
3199 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
3200 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02003201 return getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurent81784c32012-11-19 14:55:58 -08003202 }
3203 for (size_t i = 0; i < mTracks.size(); i++) {
3204 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08003205 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02003206 return getStrategyForStream(track->streamType());
Eric Laurent81784c32012-11-19 14:55:58 -08003207 }
3208 }
Eric Laurentd66d7a12021-07-13 13:35:32 +02003209 return getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurent81784c32012-11-19 14:55:58 -08003210}
3211
3212
Phil Burk062e67a2015-02-11 13:40:50 -08003213AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurent81784c32012-11-19 14:55:58 -08003214{
3215 Mutex::Autolock _l(mLock);
3216 return mOutput;
3217}
3218
Phil Burk062e67a2015-02-11 13:40:50 -08003219AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
Eric Laurent81784c32012-11-19 14:55:58 -08003220{
3221 Mutex::Autolock _l(mLock);
3222 AudioStreamOut *output = mOutput;
3223 mOutput = NULL;
3224 // FIXME FastMixer might also have a raw ptr to mOutputSink;
3225 // must push a NULL and wait for ack
3226 mOutputSink.clear();
3227 mPipeSink.clear();
3228 mNormalSink.clear();
3229 return output;
3230}
3231
3232// this method must always be called either with ThreadBase mLock held or inside the thread loop
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003233sp<StreamHalInterface> AudioFlinger::PlaybackThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08003234{
3235 if (mOutput == NULL) {
3236 return NULL;
3237 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003238 return mOutput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08003239}
3240
3241uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
3242{
3243 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
3244}
3245
3246status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
3247{
3248 if (!isValidSyncEvent(event)) {
3249 return BAD_VALUE;
3250 }
3251
3252 Mutex::Autolock _l(mLock);
3253
3254 for (size_t i = 0; i < mTracks.size(); ++i) {
3255 sp<Track> track = mTracks[i];
3256 if (event->triggerSession() == track->sessionId()) {
3257 (void) track->setSyncEvent(event);
3258 return NO_ERROR;
3259 }
3260 }
3261
3262 return NAME_NOT_FOUND;
3263}
3264
3265bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
3266{
3267 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
3268}
3269
3270void AudioFlinger::PlaybackThread::threadLoop_removeTracks(
3271 const Vector< sp<Track> >& tracksToRemove)
3272{
Andy Hungfe726a62018-09-27 15:17:25 -07003273 // Miscellaneous track cleanup when removed from the active list,
3274 // called without Thread lock but synchronized with threadLoop processing.
Eric Laurentbfb1b832013-01-07 09:53:42 -08003275#ifdef ADD_BATTERY_DATA
Andy Hungfe726a62018-09-27 15:17:25 -07003276 for (const auto& track : tracksToRemove) {
3277 if (track->isExternalTrack()) {
3278 // to track the speaker usage
3279 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Eric Laurent81784c32012-11-19 14:55:58 -08003280 }
3281 }
Andy Hungfe726a62018-09-27 15:17:25 -07003282#else
3283 (void)tracksToRemove; // suppress unused warning
3284#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003285}
3286
3287void AudioFlinger::PlaybackThread::checkSilentMode_l()
3288{
3289 if (!mMasterMute) {
3290 char value[PROPERTY_VALUE_MAX];
jiabin0a957d32020-04-29 10:56:20 -07003291 if (mOutDeviceTypeAddrs.empty()) {
3292 ALOGD("ro.audio.silent is ignored since no output device is set");
3293 return;
3294 }
jiabinc52b1ff2019-10-31 17:20:42 -07003295 if (isSingleDeviceType(outDeviceTypes(), AUDIO_DEVICE_OUT_REMOTE_SUBMIX)) {
Jean-Michel Trivi32f37c22016-03-31 16:00:32 -07003296 ALOGD("ro.audio.silent will be ignored for threads on AUDIO_DEVICE_OUT_REMOTE_SUBMIX");
3297 return;
3298 }
Eric Laurent81784c32012-11-19 14:55:58 -08003299 if (property_get("ro.audio.silent", value, "0") > 0) {
3300 char *endptr;
3301 unsigned long ul = strtoul(value, &endptr, 0);
3302 if (*endptr == '\0' && ul != 0) {
3303 ALOGD("Silence is golden");
3304 // The setprop command will not allow a property to be changed after
3305 // the first time it is set, so we don't have to worry about un-muting.
3306 setMasterMute_l(true);
3307 }
3308 }
3309 }
3310}
3311
3312// shared by MIXER and DIRECT, overridden by DUPLICATING
Eric Laurentbfb1b832013-01-07 09:53:42 -08003313ssize_t AudioFlinger::PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08003314{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07003315 LOG_HIST_TS();
Eric Laurent81784c32012-11-19 14:55:58 -08003316 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003317 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07003318 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08003319
3320 // If an NBAIO sink is present, use it to write the normal mixer's submix
3321 if (mNormalSink != 0) {
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003322
Andy Hung010a1a12014-03-13 13:57:33 -07003323 const size_t count = mBytesRemaining / mFrameSize;
3324
Simon Wilson2d590962012-11-29 15:18:50 -08003325 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08003326 // update the setpoint when AudioFlinger::mScreenState changes
3327 uint32_t screenState = AudioFlinger::mScreenState;
3328 if (screenState != mScreenState) {
3329 mScreenState = screenState;
3330 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
3331 if (pipe != NULL) {
3332 pipe->setAvgFrames((mScreenState & 1) ?
3333 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
3334 }
3335 }
Andy Hung010a1a12014-03-13 13:57:33 -07003336 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08003337 ATRACE_END();
Eric Laurent81784c32012-11-19 14:55:58 -08003338 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07003339 bytesWritten = framesWritten * mFrameSize;
Andy Hung8946a282018-04-19 20:04:56 -07003340#ifdef TEE_SINK
3341 mTee.write((char *)mSinkBuffer + offset, framesWritten);
3342#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003343 } else {
3344 bytesWritten = framesWritten;
3345 }
3346 // otherwise use the HAL / AudioStreamOut directly
3347 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003348 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07003349
Eric Laurentbfb1b832013-01-07 09:53:42 -08003350 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003351 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
3352 mWriteAckSequence += 2;
3353 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003354 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003355 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003356 }
Mikhail Naganovddb07bc12019-08-15 20:18:47 -07003357 ATRACE_BEGIN("write");
Glenn Kasten767094d2013-08-23 13:51:43 -07003358 // FIXME We should have an implementation of timestamps for direct output threads.
3359 // They are used e.g for multichannel PCM playback over HDMI.
Phil Burk062e67a2015-02-11 13:40:50 -08003360 bytesWritten = mOutput->write((char *)mSinkBuffer + offset, mBytesRemaining);
Mikhail Naganovddb07bc12019-08-15 20:18:47 -07003361 ATRACE_END();
Eric Laurent51716182016-02-29 18:00:56 -08003362
Eric Laurentbfb1b832013-01-07 09:53:42 -08003363 if (mUseAsyncWrite &&
3364 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
3365 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07003366 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003367 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003368 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003369 }
Eric Laurent81784c32012-11-19 14:55:58 -08003370 }
3371
Eric Laurent81784c32012-11-19 14:55:58 -08003372 mNumWrites++;
3373 mInWrite = false;
Andy Hungcf10d742020-04-28 15:38:24 -07003374 if (mStandby) {
3375 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07003376 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -07003377 mStandby = false;
3378 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003379 return bytesWritten;
3380}
3381
3382void AudioFlinger::PlaybackThread::threadLoop_drain()
3383{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003384 bool supportsDrain = false;
3385 if (mOutput->stream->supportsDrain(&supportsDrain) == OK && supportsDrain) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003386 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
3387 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003388 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
3389 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003390 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003391 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003392 }
Mikhail Naganovcbc8f612016-10-11 18:05:13 -07003393 status_t result = mOutput->stream->drain(mMixerStatus == MIXER_DRAIN_TRACK);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003394 ALOGE_IF(result != OK, "Error when draining stream: %d", result);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003395 }
3396}
3397
3398void AudioFlinger::PlaybackThread::threadLoop_exit()
3399{
Eric Laurent275e8e92014-11-30 15:14:47 -08003400 {
3401 Mutex::Autolock _l(mLock);
3402 for (size_t i = 0; i < mTracks.size(); i++) {
3403 sp<Track> track = mTracks[i];
3404 track->invalidate();
3405 }
Andy Hungdae27702016-10-31 14:01:16 -07003406 // Clear ActiveTracks to update BatteryNotifier in case active tracks remain.
3407 // After we exit there are no more track changes sent to BatteryNotifier
3408 // because that requires an active threadLoop.
3409 // TODO: should we decActiveTrackCnt() of the cleared track effect chain?
3410 mActiveTracks.clear();
Eric Laurent275e8e92014-11-30 15:14:47 -08003411 }
Eric Laurent81784c32012-11-19 14:55:58 -08003412}
3413
3414/*
3415The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08003416 - mSinkBufferSize from frame count * frame size
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003417 - mActiveSleepTimeUs from activeSleepTimeUs()
3418 - mIdleSleepTimeUs from idleSleepTimeUs()
Eric Laurent42537be2016-01-08 17:16:42 -08003419 - mStandbyDelayNs from mActiveSleepTimeUs (DIRECT only) or forced to at least
3420 kDefaultStandbyTimeInNsecs when connected to an A2DP device.
Eric Laurent81784c32012-11-19 14:55:58 -08003421 - maxPeriod from frame count and sample rate (MIXER only)
3422
3423The parameters that affect these derived values are:
3424 - frame count
3425 - frame size
3426 - sample rate
3427 - device type: A2DP or not
3428 - device latency
3429 - format: PCM or not
3430 - active sleep time
3431 - idle sleep time
3432*/
3433
3434void AudioFlinger::PlaybackThread::cacheParameters_l()
3435{
Andy Hung25c2dac2014-02-27 14:56:00 -08003436 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003437 mActiveSleepTimeUs = activeSleepTimeUs();
3438 mIdleSleepTimeUs = idleSleepTimeUs();
Eric Laurent42537be2016-01-08 17:16:42 -08003439
Eric Laurent52568142022-10-28 11:23:28 +02003440 mStandbyDelayNs = AudioFlinger::mStandbyTimeInNsecs;
3441 // Shorten standby delay on VOIP RX output to avoid delayed routing updates
3442 // after a call due to call end tone.
3443 if (mOutput != nullptr && (mOutput->flags & AUDIO_OUTPUT_FLAG_VOIP_RX) != 0) {
3444 const nsecs_t NS_PER_MS = 1000000;
3445 mStandbyDelayNs = std::min(mStandbyDelayNs, latency_l() * NS_PER_MS);
3446 }
Eric Laurent42537be2016-01-08 17:16:42 -08003447 // make sure standby delay is not too short when connected to an A2DP sink to avoid
3448 // truncating audio when going to standby.
jiabinc52b1ff2019-10-31 17:20:42 -07003449 if (!Intersection(outDeviceTypes(), getAudioDeviceOutAllA2dpSet()).empty()) {
Eric Laurent42537be2016-01-08 17:16:42 -08003450 if (mStandbyDelayNs < kDefaultStandbyTimeInNsecs) {
3451 mStandbyDelayNs = kDefaultStandbyTimeInNsecs;
3452 }
3453 }
Eric Laurent81784c32012-11-19 14:55:58 -08003454}
3455
Eric Laurent13084622016-05-17 10:51:49 -07003456bool AudioFlinger::PlaybackThread::invalidateTracks_l(audio_stream_type_t streamType)
Eric Laurent81784c32012-11-19 14:55:58 -08003457{
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003458 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %zu",
Eric Laurent81784c32012-11-19 14:55:58 -08003459 this, streamType, mTracks.size());
Eric Laurent13084622016-05-17 10:51:49 -07003460 bool trackMatch = false;
Eric Laurent81784c32012-11-19 14:55:58 -08003461 size_t size = mTracks.size();
3462 for (size_t i = 0; i < size; i++) {
3463 sp<Track> t = mTracks[i];
Eric Laurentd60560a2015-04-10 11:31:20 -07003464 if (t->streamType() == streamType && t->isExternalTrack()) {
Glenn Kasten5736c352012-12-04 12:12:34 -08003465 t->invalidate();
Eric Laurent13084622016-05-17 10:51:49 -07003466 trackMatch = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003467 }
3468 }
Eric Laurent13084622016-05-17 10:51:49 -07003469 return trackMatch;
Eric Laurent81784c32012-11-19 14:55:58 -08003470}
3471
Haynes Mathew George05317d22016-05-03 16:34:26 -07003472void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
3473{
3474 Mutex::Autolock _l(mLock);
3475 invalidateTracks_l(streamType);
3476}
3477
jiabinf042b9b2021-05-07 23:46:28 +00003478// getTrackById_l must be called with holding thread lock
3479AudioFlinger::PlaybackThread::Track* AudioFlinger::PlaybackThread::getTrackById_l(
3480 audio_port_handle_t trackPortId) {
3481 for (size_t i = 0; i < mTracks.size(); i++) {
3482 if (mTracks[i]->portId() == trackPortId) {
3483 return mTracks[i].get();
3484 }
3485 }
3486 return nullptr;
3487}
3488
Eric Laurent81784c32012-11-19 14:55:58 -08003489status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
3490{
Glenn Kastend848eb42016-03-08 13:42:11 -08003491 audio_session_t session = chain->sessionId();
Mikhail Naganov022b9952017-01-04 16:36:51 -08003492 sp<EffectBufferHalInterface> halInBuffer, halOutBuffer;
Eric Laurentb62d0362021-10-26 17:40:18 +02003493 effect_buffer_t *buffer = nullptr; // only used for non global sessions
3494
Andy Hungd3639922022-04-28 18:00:49 -07003495 if (mType == SPATIALIZER) {
Eric Laurentb62d0362021-10-26 17:40:18 +02003496 if (!audio_is_global_session(session)) {
3497 // player sessions on a spatializer output will use a dedicated input buffer and
3498 // will either output multi channel to mEffectBuffer if the track is spatilaized
3499 // or stereo to mPostSpatializerBuffer if not spatialized.
3500 uint32_t channelMask;
3501 bool isSessionSpatialized =
3502 (hasAudioSession_l(session) & ThreadBase::SPATIALIZED_SESSION) != 0;
3503 if (isSessionSpatialized) {
3504 channelMask = mMixerChannelMask;
3505 } else {
3506 channelMask = mChannelMask;
3507 }
Eric Laurentf1f22e72021-07-13 14:04:14 +02003508 size_t numSamples = mNormalFrameCount
Eric Laurentb62d0362021-10-26 17:40:18 +02003509 * (audio_channel_count_from_out_mask(channelMask) + mHapticChannelCount);
Kevin Rocard7588ff42018-01-08 11:11:30 -08003510 status_t result = mAudioFlinger->mEffectsFactoryHal->allocateBuffer(
rago94a1ee82017-07-21 15:11:02 -07003511 numSamples * sizeof(effect_buffer_t),
Mikhail Naganov022b9952017-01-04 16:36:51 -08003512 &halInBuffer);
3513 if (result != OK) return result;
Eric Laurentb62d0362021-10-26 17:40:18 +02003514
3515 result = mAudioFlinger->mEffectsFactoryHal->mirrorBuffer(
3516 isSessionSpatialized ? mEffectBuffer : mPostSpatializerBuffer,
3517 isSessionSpatialized ? mEffectBufferSize : mPostSpatializerBufferSize,
3518 &halOutBuffer);
3519 if (result != OK) return result;
3520
rago94a1ee82017-07-21 15:11:02 -07003521#ifdef FLOAT_EFFECT_CHAIN
3522 buffer = halInBuffer->audioBuffer()->f32;
3523#else
Mikhail Naganov022b9952017-01-04 16:36:51 -08003524 buffer = halInBuffer->audioBuffer()->s16;
rago94a1ee82017-07-21 15:11:02 -07003525#endif
Mikhail Naganov022b9952017-01-04 16:36:51 -08003526 ALOGV("addEffectChain_l() creating new input buffer %p session %d",
3527 buffer, session);
Eric Laurentb62d0362021-10-26 17:40:18 +02003528 } else {
3529 // A global session on a SPATIALIZER thread is either OUTPUT_STAGE or DEVICE
3530 // - OUTPUT_STAGE session uses the mEffectBuffer as input buffer and
3531 // mPostSpatializerBuffer as output buffer
3532 // - DEVICE session uses the mPostSpatializerBuffer as input and output buffer.
3533 status_t result = mAudioFlinger->mEffectsFactoryHal->mirrorBuffer(
3534 mEffectBuffer, mEffectBufferSize, &halInBuffer);
3535 if (result != OK) return result;
3536 result = mAudioFlinger->mEffectsFactoryHal->mirrorBuffer(
3537 mPostSpatializerBuffer, mPostSpatializerBufferSize, &halOutBuffer);
3538 if (result != OK) return result;
Eric Laurent81784c32012-11-19 14:55:58 -08003539
Eric Laurentb62d0362021-10-26 17:40:18 +02003540 if (session == AUDIO_SESSION_DEVICE) {
3541 halInBuffer = halOutBuffer;
3542 }
3543 }
3544 } else {
3545 status_t result = mAudioFlinger->mEffectsFactoryHal->mirrorBuffer(
3546 mEffectBufferEnabled ? mEffectBuffer : mSinkBuffer,
3547 mEffectBufferEnabled ? mEffectBufferSize : mSinkBufferSize,
3548 &halInBuffer);
3549 if (result != OK) return result;
3550 halOutBuffer = halInBuffer;
3551 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
3552 if (!audio_is_global_session(session)) {
3553 buffer = reinterpret_cast<effect_buffer_t*>(halInBuffer->externalData());
3554 // Only one effect chain can be present in direct output thread and it uses
3555 // the sink buffer as input
3556 if (mType != DIRECT) {
3557 size_t numSamples = mNormalFrameCount
3558 * (audio_channel_count_from_out_mask(mMixerChannelMask)
3559 + mHapticChannelCount);
3560 status_t result = mAudioFlinger->mEffectsFactoryHal->allocateBuffer(
3561 numSamples * sizeof(effect_buffer_t),
3562 &halInBuffer);
3563 if (result != OK) return result;
3564#ifdef FLOAT_EFFECT_CHAIN
3565 buffer = halInBuffer->audioBuffer()->f32;
3566#else
3567 buffer = halInBuffer->audioBuffer()->s16;
3568#endif
3569 ALOGV("addEffectChain_l() creating new input buffer %p session %d",
3570 buffer, session);
3571 }
3572 }
3573 }
3574
3575 if (!audio_is_global_session(session)) {
Eric Laurent81784c32012-11-19 14:55:58 -08003576 // Attach all tracks with same session ID to this chain.
3577 for (size_t i = 0; i < mTracks.size(); ++i) {
3578 sp<Track> track = mTracks[i];
3579 if (session == track->sessionId()) {
Eric Laurentb62d0362021-10-26 17:40:18 +02003580 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p",
3581 track.get(), buffer);
Eric Laurent81784c32012-11-19 14:55:58 -08003582 track->setMainBuffer(buffer);
3583 chain->incTrackCnt();
3584 }
3585 }
3586
3587 // indicate all active tracks in the chain
Andy Hungdae27702016-10-31 14:01:16 -07003588 for (const sp<Track> &track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08003589 if (session == track->sessionId()) {
Eric Laurentb62d0362021-10-26 17:40:18 +02003590 ALOGV("addEffectChain_l() activating track %p on session %d",
3591 track.get(), session);
Eric Laurent81784c32012-11-19 14:55:58 -08003592 chain->incActiveTrackCnt();
3593 }
3594 }
3595 }
Eric Laurentb62d0362021-10-26 17:40:18 +02003596
Eric Laurentaaa44472014-09-12 17:41:50 -07003597 chain->setThread(this);
Mikhail Naganov022b9952017-01-04 16:36:51 -08003598 chain->setInBuffer(halInBuffer);
3599 chain->setOutBuffer(halOutBuffer);
Eric Laurent3f75a5b2019-11-12 15:55:51 -08003600 // Effect chain for session AUDIO_SESSION_DEVICE is inserted at end of effect
3601 // chains list in order to be processed last as it contains output device effects.
3602 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted just before to apply post
3603 // processing effects specific to an output stream before effects applied to all streams
3604 // routed to a given device.
Eric Laurent81784c32012-11-19 14:55:58 -08003605 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
3606 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Glenn Kastend848eb42016-03-08 13:42:11 -08003607 // after track specific effects and before output stage.
Eric Laurent81784c32012-11-19 14:55:58 -08003608 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
Glenn Kastend848eb42016-03-08 13:42:11 -08003609 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX.
Eric Laurent81784c32012-11-19 14:55:58 -08003610 // Effect chain for other sessions are inserted at beginning of effect
3611 // chains list to be processed before output mix effects. Relative order between other
Glenn Kastend848eb42016-03-08 13:42:11 -08003612 // sessions is not important.
3613 static_assert(AUDIO_SESSION_OUTPUT_MIX == 0 &&
Eric Laurent3f75a5b2019-11-12 15:55:51 -08003614 AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX &&
3615 AUDIO_SESSION_DEVICE < AUDIO_SESSION_OUTPUT_STAGE,
Glenn Kastend848eb42016-03-08 13:42:11 -08003616 "audio_session_t constants misdefined");
Eric Laurent81784c32012-11-19 14:55:58 -08003617 size_t size = mEffectChains.size();
3618 size_t i = 0;
3619 for (i = 0; i < size; i++) {
3620 if (mEffectChains[i]->sessionId() < session) {
3621 break;
3622 }
3623 }
3624 mEffectChains.insertAt(chain, i);
3625 checkSuspendOnAddEffectChain_l(chain);
3626
3627 return NO_ERROR;
3628}
3629
3630size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
3631{
Glenn Kastend848eb42016-03-08 13:42:11 -08003632 audio_session_t session = chain->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08003633
3634 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
3635
3636 for (size_t i = 0; i < mEffectChains.size(); i++) {
3637 if (chain == mEffectChains[i]) {
3638 mEffectChains.removeAt(i);
3639 // detach all active tracks from the chain
Andy Hungdae27702016-10-31 14:01:16 -07003640 for (const sp<Track> &track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08003641 if (session == track->sessionId()) {
3642 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
3643 chain.get(), session);
3644 chain->decActiveTrackCnt();
3645 }
3646 }
3647
3648 // detach all tracks with same session ID from this chain
3649 for (size_t i = 0; i < mTracks.size(); ++i) {
3650 sp<Track> track = mTracks[i];
3651 if (session == track->sessionId()) {
rago94a1ee82017-07-21 15:11:02 -07003652 track->setMainBuffer(reinterpret_cast<effect_buffer_t*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08003653 chain->decTrackCnt();
3654 }
3655 }
3656 break;
3657 }
3658 }
3659 return mEffectChains.size();
3660}
3661
3662status_t AudioFlinger::PlaybackThread::attachAuxEffect(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003663 const sp<AudioFlinger::PlaybackThread::Track>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003664{
3665 Mutex::Autolock _l(mLock);
3666 return attachAuxEffect_l(track, EffectId);
3667}
3668
3669status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003670 const sp<AudioFlinger::PlaybackThread::Track>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003671{
3672 status_t status = NO_ERROR;
3673
3674 if (EffectId == 0) {
3675 track->setAuxBuffer(0, NULL);
3676 } else {
3677 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
3678 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
3679 if (effect != 0) {
3680 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
3681 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
3682 } else {
3683 status = INVALID_OPERATION;
3684 }
3685 } else {
3686 status = BAD_VALUE;
3687 }
3688 }
3689 return status;
3690}
3691
3692void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
3693{
3694 for (size_t i = 0; i < mTracks.size(); ++i) {
3695 sp<Track> track = mTracks[i];
3696 if (track->auxEffectId() == effectId) {
3697 attachAuxEffect_l(track, 0);
3698 }
3699 }
3700}
3701
3702bool AudioFlinger::PlaybackThread::threadLoop()
3703{
Glenn Kasten388d5712017-04-07 14:38:41 -07003704 tlNBLogWriter = mNBLogWriter.get();
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003705
Eric Laurent81784c32012-11-19 14:55:58 -08003706 Vector< sp<Track> > tracksToRemove;
3707
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003708 mStandbyTimeNs = systemTime();
Andy Hung446f4df2019-02-21 12:26:41 -08003709 int64_t lastLoopCountWritten = -2; // never matches "previous" loop, when loopCount = 0.
Eric Laurent81784c32012-11-19 14:55:58 -08003710
3711 // MIXER
3712 nsecs_t lastWarning = 0;
3713
3714 // DUPLICATING
3715 // FIXME could this be made local to while loop?
3716 writeFrames = 0;
3717
3718 cacheParameters_l();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003719 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003720
Andy Hungd3639922022-04-28 18:00:49 -07003721 if (mType == MIXER || mType == SPATIALIZER) {
Eric Laurent81784c32012-11-19 14:55:58 -08003722 sleepTimeShift = 0;
3723 }
3724
3725 CpuStats cpuStats;
3726 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
3727
3728 acquireWakeLock();
3729
Glenn Kasteneef598c2017-04-03 14:41:13 -07003730 // mNBLogWriter logging APIs can only be called by a single thread, typically the
3731 // thread associated with this PlaybackThread.
3732 // If you want to share the mNBLogWriter with other threads (for example, binder threads)
3733 // then all such threads must agree to hold a common mutex before logging.
Glenn Kasten9e58b552013-01-18 15:09:48 -08003734 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
3735 // and then that string will be logged at the next convenient opportunity.
Glenn Kasteneef598c2017-04-03 14:41:13 -07003736 // See reference to logString below.
Glenn Kasten9e58b552013-01-18 15:09:48 -08003737 const char *logString = NULL;
3738
rago1bb90822017-05-02 18:31:48 -07003739 // Estimated time for next buffer to be written to hal. This is used only on
3740 // suspended mode (for now) to help schedule the wait time until next iteration.
3741 nsecs_t timeLoopNextNs = 0;
3742
Eric Laurent664539d2013-09-23 18:24:31 -07003743 checkSilentMode_l();
Glenn Kasteneef598c2017-04-03 14:41:13 -07003744
Andy Hung2dbffc22018-08-08 18:50:41 -07003745 audio_patch_handle_t lastDownstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Andy Hungf3234512018-07-03 14:51:47 -07003746
Eric Laurentb3f315a2021-07-13 15:09:05 +02003747 sendCheckOutputStageEffectsEvent();
3748
Andy Hung446f4df2019-02-21 12:26:41 -08003749 // loopCount is used for statistics and diagnostics.
3750 for (int64_t loopCount = 0; !exitPending(); ++loopCount)
Eric Laurent81784c32012-11-19 14:55:58 -08003751 {
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08003752 // Log merge requests are performed during AudioFlinger binder transactions, but
3753 // that does not cover audio playback. It's requested here for that reason.
3754 mAudioFlinger->requestLogMerge();
3755
Eric Laurent81784c32012-11-19 14:55:58 -08003756 cpuStats.sample(myName);
3757
3758 Vector< sp<EffectChain> > effectChains;
Andy Hung6e6a2e62019-04-30 16:38:41 -07003759 audio_session_t activeHapticSessionId = AUDIO_SESSION_NONE;
Eric Laurentb62d0362021-10-26 17:40:18 +02003760 bool isHapticSessionSpatialized = false;
Andy Hungc1646382019-04-30 16:12:10 -07003761 std::vector<sp<Track>> activeTracks;
Eric Laurent81784c32012-11-19 14:55:58 -08003762
Andy Hung2dbffc22018-08-08 18:50:41 -07003763 // If the device is AUDIO_DEVICE_OUT_BUS, check for downstream latency.
3764 //
jiabinc52b1ff2019-10-31 17:20:42 -07003765 // Note: we access outDeviceTypes() outside of mLock.
3766 if (isMsdDevice() && outDeviceTypes().count(AUDIO_DEVICE_OUT_BUS) != 0) {
Andy Hung2dbffc22018-08-08 18:50:41 -07003767 // Here, we try for the AF lock, but do not block on it as the latency
3768 // is more informational.
3769 if (mAudioFlinger->mLock.tryLock() == NO_ERROR) {
3770 std::vector<PatchPanel::SoftwarePatch> swPatches;
3771 double latencyMs;
3772 status_t status = INVALID_OPERATION;
3773 audio_patch_handle_t downstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
3774 if (mAudioFlinger->mPatchPanel.getDownstreamSoftwarePatches(id(), &swPatches) == OK
3775 && swPatches.size() > 0) {
3776 status = swPatches[0].getLatencyMs_l(&latencyMs);
3777 downstreamPatchHandle = swPatches[0].getPatchHandle();
3778 }
3779 if (downstreamPatchHandle != lastDownstreamPatchHandle) {
Dean Wheatley30d28422018-11-06 10:27:40 +11003780 mDownstreamLatencyStatMs.reset();
Andy Hung2dbffc22018-08-08 18:50:41 -07003781 lastDownstreamPatchHandle = downstreamPatchHandle;
3782 }
3783 if (status == OK) {
3784 // verify downstream latency (we assume a max reasonable
Mikhail Naganov6aa0a312018-11-09 11:00:01 -08003785 // latency of 5 seconds).
3786 const double minLatency = 0., maxLatency = 5000.;
3787 if (latencyMs >= minLatency && latencyMs <= maxLatency) {
Dean Wheatley56a583e2020-05-08 15:12:17 +10003788 ALOGVV("new downstream latency %lf ms", latencyMs);
Andy Hung2dbffc22018-08-08 18:50:41 -07003789 } else {
3790 ALOGD("out of range downstream latency %lf ms", latencyMs);
Mikhail Naganov6aa0a312018-11-09 11:00:01 -08003791 if (latencyMs < minLatency) latencyMs = minLatency;
3792 else if (latencyMs > maxLatency) latencyMs = maxLatency;
Andy Hung2dbffc22018-08-08 18:50:41 -07003793 }
Dean Wheatley30d28422018-11-06 10:27:40 +11003794 mDownstreamLatencyStatMs.add(latencyMs);
Andy Hung2dbffc22018-08-08 18:50:41 -07003795 }
3796 mAudioFlinger->mLock.unlock();
3797 }
3798 } else {
3799 if (lastDownstreamPatchHandle != AUDIO_PATCH_HANDLE_NONE) {
3800 // our device is no longer AUDIO_DEVICE_OUT_BUS, reset patch handle and stats.
Dean Wheatley30d28422018-11-06 10:27:40 +11003801 mDownstreamLatencyStatMs.reset();
Andy Hung2dbffc22018-08-08 18:50:41 -07003802 lastDownstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
3803 }
3804 }
3805
Eric Laurentb3f315a2021-07-13 15:09:05 +02003806 if (mCheckOutputStageEffects.exchange(false)) {
3807 checkOutputStageEffects();
3808 }
3809
Eric Laurent81784c32012-11-19 14:55:58 -08003810 { // scope for mLock
3811
3812 Mutex::Autolock _l(mLock);
3813
Eric Laurent021cf962014-05-13 10:18:14 -07003814 processConfigEvents_l();
Eric Laurentb3f315a2021-07-13 15:09:05 +02003815 if (mCheckOutputStageEffects.load()) {
3816 continue;
3817 }
Eric Laurent10351942014-05-08 18:49:52 -07003818
Glenn Kasteneef598c2017-04-03 14:41:13 -07003819 // See comment at declaration of logString for why this is done under mLock
Glenn Kasten9e58b552013-01-18 15:09:48 -08003820 if (logString != NULL) {
3821 mNBLogWriter->logTimestamp();
3822 mNBLogWriter->log(logString);
3823 logString = NULL;
3824 }
3825
Dean Wheatley12473e92021-03-18 23:00:55 +11003826 collectTimestamps_l();
Andy Hungc8fddf32018-08-08 18:32:37 -07003827
Eric Laurent81784c32012-11-19 14:55:58 -08003828 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003829 if (mSignalPending) {
3830 // A signal was raised while we were unlocked
3831 mSignalPending = false;
3832 } else if (waitingAsyncCallback_l()) {
3833 if (exitPending()) {
3834 break;
3835 }
Marco Nelissen078538c2015-05-12 09:17:57 -07003836 bool released = false;
Eric Laurent64667972016-03-30 18:19:46 -07003837 if (!keepWakeLock()) {
Marco Nelissen078538c2015-05-12 09:17:57 -07003838 releaseWakeLock_l();
3839 released = true;
3840 }
Andy Hung10cbff12017-02-21 17:30:14 -08003841
3842 const int64_t waitNs = computeWaitTimeNs_l();
3843 ALOGV("wait async completion (wait time: %lld)", (long long)waitNs);
3844 status_t status = mWaitWorkCV.waitRelative(mLock, waitNs);
3845 if (status == TIMED_OUT) {
3846 mSignalPending = true; // if timeout recheck everything
3847 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003848 ALOGV("async completion/wake");
Marco Nelissen078538c2015-05-12 09:17:57 -07003849 if (released) {
3850 acquireWakeLock_l();
3851 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003852 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3853 mSleepTimeUs = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07003854
3855 continue;
3856 }
Eric Tan39ec8d62018-07-24 09:49:29 -07003857 if ((mActiveTracks.isEmpty() && systemTime() > mStandbyTimeNs) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08003858 isSuspended()) {
3859 // put audio hardware into standby after short delay
3860 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003861
3862 threadLoop_standby();
3863
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07003864 // This is where we go into standby
3865 if (!mStandby) {
3866 LOG_AUDIO_STATE();
Andy Hungcf10d742020-04-28 15:38:24 -07003867 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07003868 mThreadSnapshot.onEnd();
Andy Hungcf10d742020-04-28 15:38:24 -07003869 mStandby = true;
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07003870 }
Andy Hungd0979812019-02-21 15:51:44 -08003871 sendStatistics(false /* force */);
Eric Laurent81784c32012-11-19 14:55:58 -08003872 }
3873
Eric Tan39ec8d62018-07-24 09:49:29 -07003874 if (mActiveTracks.isEmpty() && mConfigEvents.isEmpty()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003875 // we're about to wait, flush the binder command buffer
3876 IPCThreadState::self()->flushCommands();
3877
3878 clearOutputTracks();
3879
3880 if (exitPending()) {
3881 break;
3882 }
3883
3884 releaseWakeLock_l();
3885 // wait until we have something to do...
3886 ALOGV("%s going to sleep", myName.string());
3887 mWaitWorkCV.wait(mLock);
3888 ALOGV("%s waking up", myName.string());
3889 acquireWakeLock_l();
3890
3891 mMixerStatus = MIXER_IDLE;
3892 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
3893 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003894 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003895 checkSilentMode_l();
3896
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003897 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3898 mSleepTimeUs = mIdleSleepTimeUs;
Andy Hungd3639922022-04-28 18:00:49 -07003899 if (mType == MIXER || mType == SPATIALIZER) {
Eric Laurent81784c32012-11-19 14:55:58 -08003900 sleepTimeShift = 0;
3901 }
3902
3903 continue;
3904 }
3905 }
Eric Laurent81784c32012-11-19 14:55:58 -08003906 // mMixerStatusIgnoringFastTracks is also updated internally
3907 mMixerStatus = prepareTracks_l(&tracksToRemove);
3908
Andy Hungdae27702016-10-31 14:01:16 -07003909 mActiveTracks.updatePowerState(this);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003910
Kevin Rocard069c2712018-03-29 19:09:14 -07003911 updateMetadata_l();
3912
Eric Laurent81784c32012-11-19 14:55:58 -08003913 // prevent any changes in effect chain list and in each effect chain
3914 // during mixing and effect process as the audio buffers could be deleted
3915 // or modified if an effect is created or deleted
3916 lockEffectChains_l(effectChains);
Andy Hung6e6a2e62019-04-30 16:38:41 -07003917
3918 // Determine which session to pick up haptic data.
3919 // This must be done under the same lock as prepareTracks_l().
jiabineb3bda02020-06-30 14:07:03 -07003920 // The haptic data from the effect is at a higher priority than the one from track.
Andy Hung6e6a2e62019-04-30 16:38:41 -07003921 // TODO: Write haptic data directly to sink buffer when mixing.
Eric Laurentb62d0362021-10-26 17:40:18 +02003922 if (mHapticChannelCount > 0) {
Andy Hung6e6a2e62019-04-30 16:38:41 -07003923 for (const auto& track : mActiveTracks) {
jiabineb3bda02020-06-30 14:07:03 -07003924 sp<EffectChain> effectChain = getEffectChain_l(track->sessionId());
Eric Laurentb62d0362021-10-26 17:40:18 +02003925 if (effectChain != nullptr
3926 && effectChain->containsHapticGeneratingEffect_l()) {
jiabineb3bda02020-06-30 14:07:03 -07003927 activeHapticSessionId = track->sessionId();
Eric Laurentb62d0362021-10-26 17:40:18 +02003928 isHapticSessionSpatialized =
Eric Laurentb0a7bc92022-04-05 15:06:08 +02003929 mType == SPATIALIZER && track->isSpatialized();
jiabineb3bda02020-06-30 14:07:03 -07003930 break;
3931 }
Eric Laurentb62d0362021-10-26 17:40:18 +02003932 if (activeHapticSessionId == AUDIO_SESSION_NONE
3933 && track->getHapticPlaybackEnabled()) {
Andy Hung6e6a2e62019-04-30 16:38:41 -07003934 activeHapticSessionId = track->sessionId();
Eric Laurentb62d0362021-10-26 17:40:18 +02003935 isHapticSessionSpatialized =
Eric Laurentb0a7bc92022-04-05 15:06:08 +02003936 mType == SPATIALIZER && track->isSpatialized();
Andy Hung6e6a2e62019-04-30 16:38:41 -07003937 }
3938 }
3939 }
3940
Andy Hungc1646382019-04-30 16:12:10 -07003941 // Acquire a local copy of active tracks with lock (release w/o lock).
3942 //
3943 // Control methods on the track acquire the ThreadBase lock (e.g. start()
3944 // stop(), pause(), etc.), but the threadLoop is entitled to call audio
3945 // data / buffer methods on tracks from activeTracks without the ThreadBase lock.
3946 activeTracks.insert(activeTracks.end(), mActiveTracks.begin(), mActiveTracks.end());
Eric Laurent68a40a82022-05-03 18:15:04 +02003947
3948 setHalLatencyMode_l();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003949 } // mLock scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08003950
Eric Laurentbfb1b832013-01-07 09:53:42 -08003951 if (mBytesRemaining == 0) {
3952 mCurrentWriteLength = 0;
3953 if (mMixerStatus == MIXER_TRACKS_READY) {
3954 // threadLoop_mix() sets mCurrentWriteLength
3955 threadLoop_mix();
3956 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
3957 && (mMixerStatus != MIXER_DRAIN_ALL)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003958 // threadLoop_sleepTime sets mSleepTimeUs to 0 if data
Eric Laurentbfb1b832013-01-07 09:53:42 -08003959 // must be written to HAL
3960 threadLoop_sleepTime();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003961 if (mSleepTimeUs == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08003962 mCurrentWriteLength = mSinkBufferSize;
Andy Hungc1646382019-04-30 16:12:10 -07003963
3964 // Tally underrun frames as we are inserting 0s here.
3965 for (const auto& track : activeTracks) {
Andy Hunge2e830f2019-12-03 12:54:46 -08003966 if (track->mFillingUpStatus == Track::FS_ACTIVE
3967 && !track->isStopped()
3968 && !track->isPaused()
3969 && !track->isTerminated()) {
3970 ALOGV("%s: track(%d) %s underrun due to thread sleep of %zu frames",
3971 __func__, track->id(), track->getTrackStateAsString(),
3972 mNormalFrameCount);
Andy Hungc1646382019-04-30 16:12:10 -07003973 track->mAudioTrackServerProxy->tallyUnderrunFrames(mNormalFrameCount);
3974 }
3975 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003976 }
3977 }
Andy Hung98ef9782014-03-04 14:46:50 -08003978 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003979 // mMixerBuffer with data if mMixerBufferValid is true and mSleepTimeUs == 0.
Andy Hung98ef9782014-03-04 14:46:50 -08003980 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
3981 // or mSinkBuffer (if there are no effects).
3982 //
3983 // This is done pre-effects computation; if effects change to
3984 // support higher precision, this needs to move.
3985 //
3986 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003987 // TODO use mSleepTimeUs == 0 as an additional condition.
Eric Laurent39095982021-08-24 18:29:27 +02003988 uint32_t mixerChannelCount = mEffectBufferValid ?
3989 audio_channel_count_from_out_mask(mMixerChannelMask) : mChannelCount;
Andy Hung98ef9782014-03-04 14:46:50 -08003990 if (mMixerBufferValid) {
3991 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
3992 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
3993
David Li88ee0902022-06-22 10:01:21 +08003994 // Apply mono blending and balancing if the effect buffer is not valid. Otherwise,
3995 // do these processes after effects are applied.
3996 if (!mEffectBufferValid) {
3997 // mono blend occurs for mixer threads only (not direct or offloaded)
3998 // and is handled here if we're going directly to the sink.
3999 if (requireMonoBlend()) {
4000 mono_blend(mMixerBuffer, mMixerBufferFormat, mChannelCount,
4001 mNormalFrameCount, true /*limit*/);
4002 }
Andy Hung2ddee192015-12-18 17:34:44 -08004003
David Li88ee0902022-06-22 10:01:21 +08004004 if (!hasFastMixer()) {
4005 // Balance must take effect after mono conversion.
4006 // We do it here if there is no FastMixer.
4007 // mBalance detects zero balance within the class for speed
4008 // (not needed here).
4009 mBalance.setBalance(mMasterBalance.load());
4010 mBalance.process((float *)mMixerBuffer, mNormalFrameCount);
4011 }
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01004012 }
4013
Andy Hung98ef9782014-03-04 14:46:50 -08004014 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
Eric Laurent39095982021-08-24 18:29:27 +02004015 mNormalFrameCount * (mixerChannelCount + mHapticChannelCount));
jiabin245cdd92018-12-07 17:55:15 -08004016
4017 // If we're going directly to the sink and there are haptic channels,
4018 // we should adjust channels as the sample data is partially interleaved
4019 // in this case.
4020 if (!mEffectBufferValid && mHapticChannelCount > 0) {
4021 adjust_channels_non_destructive(buffer, mChannelCount, buffer,
4022 mChannelCount + mHapticChannelCount,
4023 audio_bytes_per_sample(format),
4024 audio_bytes_per_frame(mChannelCount, format) * mNormalFrameCount);
4025 }
Andy Hung98ef9782014-03-04 14:46:50 -08004026 }
4027
Eric Laurentbfb1b832013-01-07 09:53:42 -08004028 mBytesRemaining = mCurrentWriteLength;
4029 if (isSuspended()) {
Andy Hung238fa3d2016-07-28 10:53:22 -07004030 // Simulate write to HAL when suspended (e.g. BT SCO phone call).
4031 mSleepTimeUs = suspendSleepTimeUs(); // assumes full buffer.
4032 const size_t framesRemaining = mBytesRemaining / mFrameSize;
4033 mBytesWritten += mBytesRemaining;
4034 mFramesWritten += framesRemaining;
4035 mSuspendedFrames += framesRemaining; // to adjust kernel HAL position
Eric Laurentbfb1b832013-01-07 09:53:42 -08004036 mBytesRemaining = 0;
4037 }
Eric Laurent81784c32012-11-19 14:55:58 -08004038
Eric Laurentbfb1b832013-01-07 09:53:42 -08004039 // only process effects if we're going to write
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004040 if (mSleepTimeUs == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004041 for (size_t i = 0; i < effectChains.size(); i ++) {
4042 effectChains[i]->process_l();
jiabin47affe52019-04-04 18:02:07 -07004043 // TODO: Write haptic data directly to sink buffer when mixing.
Andy Hung6e6a2e62019-04-30 16:38:41 -07004044 if (activeHapticSessionId != AUDIO_SESSION_NONE
4045 && activeHapticSessionId == effectChains[i]->sessionId()) {
jiabin47affe52019-04-04 18:02:07 -07004046 // Haptic data is active in this case, copy it directly from
4047 // in buffer to out buffer.
Eric Laurentb62d0362021-10-26 17:40:18 +02004048 uint32_t hapticSessionChannelCount = mEffectBufferValid ?
4049 audio_channel_count_from_out_mask(mMixerChannelMask) :
4050 mChannelCount;
4051 if (mType == SPATIALIZER && !isHapticSessionSpatialized) {
4052 hapticSessionChannelCount = mChannelCount;
4053 }
4054
jiabin47affe52019-04-04 18:02:07 -07004055 const size_t audioBufferSize = mNormalFrameCount
Eric Laurentb62d0362021-10-26 17:40:18 +02004056 * audio_bytes_per_frame(hapticSessionChannelCount,
4057 EFFECT_BUFFER_FORMAT);
jiabin47affe52019-04-04 18:02:07 -07004058 memcpy_by_audio_format(
4059 (uint8_t*)effectChains[i]->outBuffer() + audioBufferSize,
4060 EFFECT_BUFFER_FORMAT,
4061 (const uint8_t*)effectChains[i]->inBuffer() + audioBufferSize,
4062 EFFECT_BUFFER_FORMAT, mNormalFrameCount * mHapticChannelCount);
4063 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004064 }
Eric Laurent81784c32012-11-19 14:55:58 -08004065 }
4066 }
Eric Laurent59fe0102013-09-27 18:48:26 -07004067 // Process effect chains for offloaded thread even if no audio
4068 // was read from audio track: process only updates effect state
4069 // and thus does have to be synchronized with audio writes but may have
4070 // to be called while waiting for async write callback
4071 if (mType == OFFLOAD) {
4072 for (size_t i = 0; i < effectChains.size(); i ++) {
4073 effectChains[i]->process_l();
4074 }
4075 }
Eric Laurent81784c32012-11-19 14:55:58 -08004076
Andy Hung98ef9782014-03-04 14:46:50 -08004077 // Only if the Effects buffer is enabled and there is data in the
4078 // Effects buffer (buffer valid), we need to
4079 // copy into the sink buffer.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004080 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08004081 if (mEffectBufferValid) {
4082 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
Eric Laurentb62d0362021-10-26 17:40:18 +02004083 void *effectBuffer = (mType == SPATIALIZER) ? mPostSpatializerBuffer : mEffectBuffer;
Andy Hung2ddee192015-12-18 17:34:44 -08004084 if (requireMonoBlend()) {
Eric Laurentb62d0362021-10-26 17:40:18 +02004085 mono_blend(effectBuffer, mEffectBufferFormat, mChannelCount, mNormalFrameCount,
Glenn Kasten03c48d52016-01-27 17:25:17 -08004086 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08004087 }
4088
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01004089 if (!hasFastMixer()) {
4090 // Balance must take effect after mono conversion.
4091 // We do it here if there is no FastMixer.
4092 // mBalance detects zero balance within the class for speed (not needed here).
4093 mBalance.setBalance(mMasterBalance.load());
Eric Laurentb62d0362021-10-26 17:40:18 +02004094 mBalance.process((float *)effectBuffer, mNormalFrameCount);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01004095 }
4096
Eric Laurentb62d0362021-10-26 17:40:18 +02004097 // for SPATIALIZER thread, Move haptics channels from mEffectBuffer to
4098 // mPostSpatializerBuffer if the haptics track is spatialized.
4099 // Otherwise, the haptics channels are already in mPostSpatializerBuffer.
4100 // For other thread types, the haptics channels are already in mEffectBuffer.
4101 if (mType == SPATIALIZER && isHapticSessionSpatialized) {
4102 const size_t srcBufferSize = mNormalFrameCount *
4103 audio_bytes_per_frame(audio_channel_count_from_out_mask(mMixerChannelMask),
4104 mEffectBufferFormat);
4105 const size_t dstBufferSize = mNormalFrameCount
4106 * audio_bytes_per_frame(mChannelCount, mEffectBufferFormat);
4107
4108 memcpy_by_audio_format((uint8_t*)mPostSpatializerBuffer + dstBufferSize,
4109 mEffectBufferFormat,
4110 (uint8_t*)mEffectBuffer + srcBufferSize,
4111 mEffectBufferFormat,
4112 mNormalFrameCount * mHapticChannelCount);
Eric Laurent39095982021-08-24 18:29:27 +02004113 }
Atneya Nairba9a1072022-09-19 17:51:37 -07004114 const size_t framesToCopy = mNormalFrameCount * (mChannelCount + mHapticChannelCount);
4115 if (mFormat == AUDIO_FORMAT_PCM_FLOAT &&
4116 mEffectBufferFormat == AUDIO_FORMAT_PCM_FLOAT) {
4117 // Clamp PCM float values more than this distance from 0 to insulate
4118 // a HAL which doesn't handle NaN correctly.
4119 static constexpr float HAL_FLOAT_SAMPLE_LIMIT = 2.0f;
4120 memcpy_to_float_from_float_with_clamping(static_cast<float*>(mSinkBuffer),
4121 static_cast<const float*>(effectBuffer),
4122 framesToCopy, HAL_FLOAT_SAMPLE_LIMIT /* absMax */);
4123 } else {
4124 memcpy_by_audio_format(mSinkBuffer, mFormat,
4125 effectBuffer, mEffectBufferFormat, framesToCopy);
4126 }
jiabin245cdd92018-12-07 17:55:15 -08004127 // The sample data is partially interleaved when haptic channels exist,
4128 // we need to adjust channels here.
4129 if (mHapticChannelCount > 0) {
4130 adjust_channels_non_destructive(mSinkBuffer, mChannelCount, mSinkBuffer,
4131 mChannelCount + mHapticChannelCount,
4132 audio_bytes_per_sample(mFormat),
4133 audio_bytes_per_frame(mChannelCount, mFormat) * mNormalFrameCount);
4134 }
Andy Hung98ef9782014-03-04 14:46:50 -08004135 }
4136
Eric Laurent81784c32012-11-19 14:55:58 -08004137 // enable changes in effect chain
4138 unlockEffectChains(effectChains);
4139
Eric Laurentbfb1b832013-01-07 09:53:42 -08004140 if (!waitingAsyncCallback()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004141 // mSleepTimeUs == 0 means we must write to audio hardware
4142 if (mSleepTimeUs == 0) {
Andy Hung08fb1742015-05-31 23:22:10 -07004143 ssize_t ret = 0;
Andy Hung446f4df2019-02-21 12:26:41 -08004144 // writePeriodNs is updated >= 0 when ret > 0.
4145 int64_t writePeriodNs = -1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004146 if (mBytesRemaining) {
Andy Hung69488c42016-05-16 18:43:33 -07004147 // FIXME rewrite to reduce number of system calls
Andy Hung446f4df2019-02-21 12:26:41 -08004148 const int64_t lastIoBeginNs = systemTime();
Andy Hung08fb1742015-05-31 23:22:10 -07004149 ret = threadLoop_write();
Andy Hung446f4df2019-02-21 12:26:41 -08004150 const int64_t lastIoEndNs = systemTime();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004151 if (ret < 0) {
4152 mBytesRemaining = 0;
Andy Hung446f4df2019-02-21 12:26:41 -08004153 } else if (ret > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004154 mBytesWritten += ret;
4155 mBytesRemaining -= ret;
Andy Hung446f4df2019-02-21 12:26:41 -08004156 const int64_t frames = ret / mFrameSize;
4157 mFramesWritten += frames;
4158
4159 writePeriodNs = lastIoEndNs - mLastIoEndNs;
4160 // process information relating to write time.
4161 if (audio_has_proportional_frames(mFormat)) {
4162 // we are in a continuous mixing cycle
4163 if (mMixerStatus == MIXER_TRACKS_READY &&
4164 loopCount == lastLoopCountWritten + 1) {
4165
4166 const double jitterMs =
4167 TimestampVerifier<int64_t, int64_t>::computeJitterMs(
4168 {frames, writePeriodNs},
4169 {0, 0} /* lastTimestamp */, mSampleRate);
4170 const double processMs =
4171 (lastIoBeginNs - mLastIoEndNs) * 1e-6;
4172
4173 Mutex::Autolock _l(mLock);
4174 mIoJitterMs.add(jitterMs);
4175 mProcessTimeMs.add(processMs);
Robert Wu06db0a32021-08-10 19:05:34 +00004176
4177 if (mPipeSink.get() != nullptr) {
4178 // Using the Monopipe availableToWrite, we estimate the current
4179 // buffer size.
4180 MonoPipe* monoPipe = static_cast<MonoPipe*>(mPipeSink.get());
4181 const ssize_t
4182 availableToWrite = mPipeSink->availableToWrite();
4183 const size_t pipeFrames = monoPipe->maxFrames();
4184 const size_t
4185 remainingFrames = pipeFrames - max(availableToWrite, 0);
4186 mMonopipePipeDepthStats.add(remainingFrames);
4187 }
Andy Hung446f4df2019-02-21 12:26:41 -08004188 }
4189
4190 // write blocked detection
4191 const int64_t deltaWriteNs = lastIoEndNs - lastIoBeginNs;
Andy Hungd3639922022-04-28 18:00:49 -07004192 if ((mType == MIXER || mType == SPATIALIZER)
4193 && deltaWriteNs > maxPeriod) {
Andy Hung446f4df2019-02-21 12:26:41 -08004194 mNumDelayedWrites++;
4195 if ((lastIoEndNs - lastWarning) > kWarningThrottleNs) {
4196 ATRACE_NAME("underrun");
4197 ALOGW("write blocked for %lld msecs, "
4198 "%d delayed writes, thread %d",
4199 (long long)deltaWriteNs / NANOS_PER_MILLISECOND,
4200 mNumDelayedWrites, mId);
4201 lastWarning = lastIoEndNs;
4202 }
4203 }
4204 }
4205 // update timing info.
4206 mLastIoBeginNs = lastIoBeginNs;
4207 mLastIoEndNs = lastIoEndNs;
4208 lastLoopCountWritten = loopCount;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004209 }
4210 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
4211 (mMixerStatus == MIXER_DRAIN_ALL)) {
4212 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08004213 }
Andy Hungd3639922022-04-28 18:00:49 -07004214 if ((mType == MIXER || mType == SPATIALIZER) && !mStandby) {
Andy Hung08fb1742015-05-31 23:22:10 -07004215
4216 if (mThreadThrottle
4217 && mMixerStatus == MIXER_TRACKS_READY // we are mixing (active tracks)
Andy Hung446f4df2019-02-21 12:26:41 -08004218 && writePeriodNs > 0) { // we have write period info
Andy Hung08fb1742015-05-31 23:22:10 -07004219 // Limit MixerThread data processing to no more than twice the
4220 // expected processing rate.
4221 //
4222 // This helps prevent underruns with NuPlayer and other applications
4223 // which may set up buffers that are close to the minimum size, or use
4224 // deep buffers, and rely on a double-buffering sleep strategy to fill.
4225 //
4226 // The throttle smooths out sudden large data drains from the device,
4227 // e.g. when it comes out of standby, which often causes problems with
4228 // (1) mixer threads without a fast mixer (which has its own warm-up)
4229 // (2) minimum buffer sized tracks (even if the track is full,
4230 // the app won't fill fast enough to handle the sudden draw).
Haynes Mathew Georgef92b2172016-05-09 11:34:15 -07004231 //
4232 // Total time spent in last processing cycle equals time spent in
4233 // 1. threadLoop_write, as well as time spent in
4234 // 2. threadLoop_mix (significant for heavy mixing, especially
4235 // on low tier processors)
Andy Hung08fb1742015-05-31 23:22:10 -07004236
Andy Hung446f4df2019-02-21 12:26:41 -08004237 // it's OK if deltaMs is an overestimate.
4238
4239 const int32_t deltaMs = writePeriodNs / NANOS_PER_MILLISECOND;
Ivan Lozanoe02bc542017-10-26 09:51:54 -07004240
Ivan Lozanoea04d392017-11-07 14:37:07 -08004241 const int32_t throttleMs = (int32_t)mHalfBufferMs - deltaMs;
Andy Hung08fb1742015-05-31 23:22:10 -07004242 if ((signed)mHalfBufferMs >= throttleMs && throttleMs > 0) {
Andy Hungcf10d742020-04-28 15:38:24 -07004243 mThreadMetrics.logThrottleMs((double)throttleMs);
Andy Hungb68f5eb2019-12-03 16:49:17 -08004244
Andy Hung08fb1742015-05-31 23:22:10 -07004245 usleep(throttleMs * 1000);
Andy Hung40eb1a12015-06-18 13:42:02 -07004246 // notify of throttle start on verbose log
4247 ALOGV_IF(mThreadThrottleEndMs == mThreadThrottleTimeMs,
4248 "mixer(%p) throttle begin:"
4249 " ret(%zd) deltaMs(%d) requires sleep %d ms",
Andy Hung08fb1742015-05-31 23:22:10 -07004250 this, ret, deltaMs, throttleMs);
Andy Hung40eb1a12015-06-18 13:42:02 -07004251 mThreadThrottleTimeMs += throttleMs;
Andy Hung0a31ddd2016-07-06 19:10:29 -07004252 // Throttle must be attributed to the previous mixer loop's write time
4253 // to allow back-to-back throttling.
Andy Hung446f4df2019-02-21 12:26:41 -08004254 // This also ensures proper timing statistics.
4255 mLastIoEndNs = systemTime(); // we fetch the write end time again.
Andy Hung40eb1a12015-06-18 13:42:02 -07004256 } else {
4257 uint32_t diff = mThreadThrottleTimeMs - mThreadThrottleEndMs;
4258 if (diff > 0) {
4259 // notify of throttle end on debug log
Andy Hung3ea004d2016-05-05 16:48:37 -07004260 // but prevent spamming for bluetooth
jiabinc52b1ff2019-10-31 17:20:42 -07004261 ALOGD_IF(!isSingleDeviceType(
4262 outDeviceTypes(), audio_is_a2dp_out_device) &&
4263 !isSingleDeviceType(
4264 outDeviceTypes(), audio_is_hearing_aid_out_device),
Andy Hung3ea004d2016-05-05 16:48:37 -07004265 "mixer(%p) throttle end: throttle time(%u)", this, diff);
Andy Hung40eb1a12015-06-18 13:42:02 -07004266 mThreadThrottleEndMs = mThreadThrottleTimeMs;
4267 }
Andy Hung08fb1742015-05-31 23:22:10 -07004268 }
4269 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004270 }
Eric Laurent81784c32012-11-19 14:55:58 -08004271
Eric Laurentbfb1b832013-01-07 09:53:42 -08004272 } else {
Glenn Kastene7754022014-10-31 12:11:26 -07004273 ATRACE_BEGIN("sleep");
Eric Laurente93cc032016-05-05 10:15:10 -07004274 Mutex::Autolock _l(mLock);
rago1bb90822017-05-02 18:31:48 -07004275 // suspended requires accurate metering of sleep time.
4276 if (isSuspended()) {
4277 // advance by expected sleepTime
4278 timeLoopNextNs += microseconds((nsecs_t)mSleepTimeUs);
4279 const nsecs_t nowNs = systemTime();
4280
4281 // compute expected next time vs current time.
4282 // (negative deltas are treated as delays).
4283 nsecs_t deltaNs = timeLoopNextNs - nowNs;
4284 if (deltaNs < -kMaxNextBufferDelayNs) {
4285 // Delays longer than the max allowed trigger a reset.
4286 ALOGV("DelayNs: %lld, resetting timeLoopNextNs", (long long) deltaNs);
4287 deltaNs = microseconds((nsecs_t)mSleepTimeUs);
4288 timeLoopNextNs = nowNs + deltaNs;
4289 } else if (deltaNs < 0) {
4290 // Delays within the max delay allowed: zero the delta/sleepTime
4291 // to help the system catch up in the next iteration(s)
4292 ALOGV("DelayNs: %lld, catching-up", (long long) deltaNs);
4293 deltaNs = 0;
4294 }
4295 // update sleep time (which is >= 0)
4296 mSleepTimeUs = deltaNs / 1000;
4297 }
Eric Laurente93cc032016-05-05 10:15:10 -07004298 if (!mSignalPending && mConfigEvents.isEmpty() && !exitPending()) {
4299 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)mSleepTimeUs));
Eric Laurent51716182016-02-29 18:00:56 -08004300 }
Glenn Kastene7754022014-10-31 12:11:26 -07004301 ATRACE_END();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004302 }
Eric Laurent81784c32012-11-19 14:55:58 -08004303 }
4304
4305 // Finally let go of removed track(s), without the lock held
4306 // since we can't guarantee the destructors won't acquire that
4307 // same lock. This will also mutate and push a new fast mixer state.
4308 threadLoop_removeTracks(tracksToRemove);
4309 tracksToRemove.clear();
4310
4311 // FIXME I don't understand the need for this here;
4312 // it was in the original code but maybe the
4313 // assignment in saveOutputTracks() makes this unnecessary?
4314 clearOutputTracks();
4315
4316 // Effect chains will be actually deleted here if they were removed from
4317 // mEffectChains list during mixing or effects processing
4318 effectChains.clear();
4319
4320 // FIXME Note that the above .clear() is no longer necessary since effectChains
4321 // is now local to this block, but will keep it for now (at least until merge done).
4322 }
4323
Eric Laurentbfb1b832013-01-07 09:53:42 -08004324 threadLoop_exit();
4325
Eric Laurentcf817a22014-08-04 20:36:31 -07004326 if (!mStandby) {
4327 threadLoop_standby();
4328 mStandby = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004329 }
4330
4331 releaseWakeLock();
4332
4333 ALOGV("Thread %p type %d exiting", this, mType);
4334 return false;
4335}
4336
Dean Wheatley12473e92021-03-18 23:00:55 +11004337void AudioFlinger::PlaybackThread::collectTimestamps_l()
4338{
Dean Wheatley12473e92021-03-18 23:00:55 +11004339 if (mStandby) {
4340 mTimestampVerifier.discontinuity(discontinuityForStandbyOrFlush());
4341 return;
4342 } else if (mHwPaused) {
4343 mTimestampVerifier.discontinuity(mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS);
4344 return;
4345 }
4346
4347 // Gather the framesReleased counters for all active tracks,
4348 // and associate with the sink frames written out. We need
4349 // this to convert the sink timestamp to the track timestamp.
4350 bool kernelLocationUpdate = false;
4351 ExtendedTimestamp timestamp; // use private copy to fetch
4352
4353 // Always query HAL timestamp and update timestamp verifier. In standby or pause,
4354 // HAL may be draining some small duration buffered data for fade out.
4355 if (threadloop_getHalTimestamp_l(&timestamp) == OK) {
4356 mTimestampVerifier.add(timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL],
4357 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4358 mSampleRate);
4359
4360 if (isTimestampCorrectionEnabled()) {
4361 ALOGVV("TS_BEFORE: %d %lld %lld", id(),
4362 (long long)timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4363 (long long)timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]);
4364 auto correctedTimestamp = mTimestampVerifier.getLastCorrectedTimestamp();
4365 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4366 = correctedTimestamp.mFrames;
4367 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]
4368 = correctedTimestamp.mTimeNs;
4369 ALOGVV("TS_AFTER: %d %lld %lld", id(),
4370 (long long)timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4371 (long long)timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]);
4372
4373 // Note: Downstream latency only added if timestamp correction enabled.
4374 if (mDownstreamLatencyStatMs.getN() > 0) { // we have latency info.
4375 const int64_t newPosition =
4376 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4377 - int64_t(mDownstreamLatencyStatMs.getMean() * mSampleRate * 1e-3);
4378 // prevent retrograde
4379 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = max(
4380 newPosition,
4381 (mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4382 - mSuspendedFrames));
4383 }
4384 }
4385
4386 // We always fetch the timestamp here because often the downstream
4387 // sink will block while writing.
4388
4389 // We keep track of the last valid kernel position in case we are in underrun
4390 // and the normal mixer period is the same as the fast mixer period, or there
4391 // is some error from the HAL.
4392 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
4393 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
4394 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
4395 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
4396 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4397
4398 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
4399 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER];
4400 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
4401 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER];
4402 }
4403
4404 if (timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
4405 kernelLocationUpdate = true;
4406 } else {
4407 ALOGVV("getTimestamp error - no valid kernel position");
4408 }
4409
4410 // copy over kernel info
4411 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] =
4412 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4413 + mSuspendedFrames; // add frames discarded when suspended
4414 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] =
4415 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4416 } else {
4417 mTimestampVerifier.error();
4418 }
4419
4420 // mFramesWritten for non-offloaded tracks are contiguous
4421 // even after standby() is called. This is useful for the track frame
4422 // to sink frame mapping.
4423 bool serverLocationUpdate = false;
4424 if (mFramesWritten != mLastFramesWritten) {
4425 serverLocationUpdate = true;
4426 mLastFramesWritten = mFramesWritten;
4427 }
4428 // Only update timestamps if there is a meaningful change.
4429 // Either the kernel timestamp must be valid or we have written something.
4430 if (kernelLocationUpdate || serverLocationUpdate) {
4431 if (serverLocationUpdate) {
4432 // use the time before we called the HAL write - it is a bit more accurate
4433 // to when the server last read data than the current time here.
4434 //
4435 // If we haven't written anything, mLastIoBeginNs will be -1
4436 // and we use systemTime().
4437 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] = mFramesWritten;
4438 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = mLastIoBeginNs == -1
4439 ? systemTime() : mLastIoBeginNs;
4440 }
4441
4442 for (const sp<Track> &t : mActiveTracks) {
4443 if (!t->isFastTrack()) {
4444 t->updateTrackFrameInfo(
4445 t->mAudioTrackServerProxy->framesReleased(),
4446 mFramesWritten,
4447 mSampleRate,
4448 mTimestamp);
4449 }
4450 }
4451 }
4452
4453 if (audio_has_proportional_frames(mFormat)) {
4454 const double latencyMs = mTimestamp.getOutputServerLatencyMs(mSampleRate);
4455 if (latencyMs != 0.) { // note 0. means timestamp is empty.
4456 mLatencyMs.add(latencyMs);
4457 }
4458 }
4459#if 0
4460 // logFormat example
4461 if (z % 100 == 0) {
4462 timespec ts;
4463 clock_gettime(CLOCK_MONOTONIC, &ts);
4464 LOGT("This is an integer %d, this is a float %f, this is my "
4465 "pid %p %% %s %t", 42, 3.14, "and this is a timestamp", ts);
4466 LOGT("A deceptive null-terminated string %\0");
4467 }
4468 ++z;
4469#endif
4470}
4471
Eric Laurentbfb1b832013-01-07 09:53:42 -08004472// removeTracks_l() must be called with ThreadBase::mLock held
4473void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
4474{
Andy Hungfe726a62018-09-27 15:17:25 -07004475 for (const auto& track : tracksToRemove) {
4476 mActiveTracks.remove(track);
4477 ALOGV("%s(%d): removing track on session %d", __func__, track->id(), track->sessionId());
4478 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
4479 if (chain != 0) {
4480 ALOGV("%s(%d): stopping track on chain %p for session Id: %d",
4481 __func__, track->id(), chain.get(), track->sessionId());
4482 chain->decActiveTrackCnt();
4483 }
4484 // If an external client track, inform APM we're no longer active, and remove if needed.
4485 // We do this under lock so that the state is consistent if the Track is destroyed.
4486 if (track->isExternalTrack()) {
4487 AudioSystem::stopOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08004488 if (track->isTerminated()) {
Andy Hungfe726a62018-09-27 15:17:25 -07004489 AudioSystem::releaseOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08004490 }
4491 }
Andy Hungfe726a62018-09-27 15:17:25 -07004492 if (track->isTerminated()) {
4493 // remove from our tracks vector
4494 removeTrack_l(track);
4495 }
jiabineb3bda02020-06-30 14:07:03 -07004496 if (mHapticChannelCount > 0 &&
4497 ((track->channelMask() & AUDIO_CHANNEL_HAPTIC_ALL) != AUDIO_CHANNEL_NONE
4498 || (chain != nullptr && chain->containsHapticGeneratingEffect_l()))) {
jiabin57303cc2018-12-18 15:45:57 -08004499 mLock.unlock();
4500 // Unlock due to VibratorService will lock for this call and will
4501 // call Tracks.mute/unmute which also require thread's lock.
4502 AudioFlinger::onExternalVibrationStop(track->getExternalVibration());
4503 mLock.lock();
jiabine70bc7f2020-06-30 22:07:55 -07004504
4505 // When the track is stop, set the haptic intensity as MUTE
4506 // for the HapticGenerator effect.
4507 if (chain != nullptr) {
Simon Bowden62823412022-10-17 14:52:26 +00004508 chain->setHapticIntensity_l(track->id(), os::HapticScale::MUTE);
jiabine70bc7f2020-06-30 22:07:55 -07004509 }
jiabin245cdd92018-12-07 17:55:15 -08004510 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004511 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004512}
Eric Laurent81784c32012-11-19 14:55:58 -08004513
Eric Laurentaccc1472013-09-20 09:36:34 -07004514status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
4515{
4516 if (mNormalSink != 0) {
Andy Hung818e7a32016-02-16 18:08:07 -08004517 ExtendedTimestamp ets;
4518 status_t status = mNormalSink->getTimestamp(ets);
4519 if (status == NO_ERROR) {
4520 status = ets.getBestTimestamp(&timestamp);
4521 }
4522 return status;
Eric Laurentaccc1472013-09-20 09:36:34 -07004523 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004524 if ((mType == OFFLOAD || mType == DIRECT) && mOutput != NULL) {
Dean Wheatley12473e92021-03-18 23:00:55 +11004525 collectTimestamps_l();
4526 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] <= 0) {
4527 return INVALID_OPERATION;
Eric Laurentaccc1472013-09-20 09:36:34 -07004528 }
Dean Wheatley12473e92021-03-18 23:00:55 +11004529 timestamp.mPosition = mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
4530 const int64_t timeNs = mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4531 timestamp.mTime.tv_sec = timeNs / NANOS_PER_SECOND;
4532 timestamp.mTime.tv_nsec = timeNs - (timestamp.mTime.tv_sec * NANOS_PER_SECOND);
4533 return NO_ERROR;
Eric Laurentaccc1472013-09-20 09:36:34 -07004534 }
4535 return INVALID_OPERATION;
4536}
Eric Laurent1c333e22014-05-20 10:48:17 -07004537
Eric Laurenteab90452019-06-24 15:17:46 -07004538// For dedicated VoIP outputs, let the HAL apply the stream volume. Track volume is
4539// still applied by the mixer.
4540// All tracks attached to a mixer with flag VOIP_RX are tied to the same
4541// stream type STREAM_VOICE_CALL so this will only change the HAL volume once even
4542// if more than one track are active
4543status_t AudioFlinger::PlaybackThread::handleVoipVolume_l(float *volume)
4544{
4545 status_t result = NO_ERROR;
4546 if ((mOutput->flags & AUDIO_OUTPUT_FLAG_VOIP_RX) != 0) {
4547 if (*volume != mLeftVolFloat) {
4548 result = mOutput->stream->setVolume(*volume, *volume);
4549 ALOGE_IF(result != OK,
4550 "Error when setting output stream volume: %d", result);
4551 if (result == NO_ERROR) {
4552 mLeftVolFloat = *volume;
4553 }
4554 }
4555 // if stream volume was successfully sent to the HAL, mLeftVolFloat == v here and we
4556 // remove stream volume contribution from software volume.
4557 if (mLeftVolFloat == *volume) {
4558 *volume = 1.0f;
4559 }
4560 }
4561 return result;
4562}
4563
Eric Laurent054d9d32015-04-24 08:48:48 -07004564status_t AudioFlinger::MixerThread::createAudioPatch_l(const struct audio_patch *patch,
4565 audio_patch_handle_t *handle)
4566{
Andy Hungf60abce2016-08-26 11:37:54 -07004567 status_t status;
4568 if (property_get_bool("af.patch_park", false /* default_value */)) {
4569 // Park FastMixer to avoid potential DOS issues with writing to the HAL
4570 // or if HAL does not properly lock against access.
4571 AutoPark<FastMixer> park(mFastMixer);
4572 status = PlaybackThread::createAudioPatch_l(patch, handle);
4573 } else {
4574 status = PlaybackThread::createAudioPatch_l(patch, handle);
4575 }
Eric Laurent054d9d32015-04-24 08:48:48 -07004576 return status;
4577}
4578
Eric Laurent1c333e22014-05-20 10:48:17 -07004579status_t AudioFlinger::PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
4580 audio_patch_handle_t *handle)
4581{
4582 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07004583
4584 // store new device and send to effects
4585 audio_devices_t type = AUDIO_DEVICE_NONE;
jiabinc52b1ff2019-10-31 17:20:42 -07004586 AudioDeviceTypeAddrVector deviceTypeAddrs;
Eric Laurent054d9d32015-04-24 08:48:48 -07004587 for (unsigned int i = 0; i < patch->num_sinks; i++) {
jiabinc52b1ff2019-10-31 17:20:42 -07004588 LOG_ALWAYS_FATAL_IF(popcount(patch->sinks[i].ext.device.type) > 1
4589 && !mOutput->audioHwDev->supportsAudioPatches(),
4590 "Enumerated device type(%#x) must not be used "
4591 "as it does not support audio patches",
4592 patch->sinks[i].ext.device.type);
Mikhail Naganov55773032020-10-01 15:08:13 -07004593 type = static_cast<audio_devices_t>(type | patch->sinks[i].ext.device.type);
jiabinc52b1ff2019-10-31 17:20:42 -07004594 deviceTypeAddrs.push_back(AudioDeviceTypeAddr(patch->sinks[i].ext.device.type,
4595 patch->sinks[i].ext.device.address));
Eric Laurent054d9d32015-04-24 08:48:48 -07004596 }
4597
François Gaffie0c280aa2018-07-25 10:02:15 +02004598 audio_port_handle_t sinkPortId = patch->sinks[0].id;
Eric Laurent054d9d32015-04-24 08:48:48 -07004599#ifdef ADD_BATTERY_DATA
4600 // when changing the audio output device, call addBatteryData to notify
4601 // the change
jiabinc52b1ff2019-10-31 17:20:42 -07004602 if (outDeviceTypes() != deviceTypes) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004603 uint32_t params = 0;
4604 // check whether speaker is on
jiabinc52b1ff2019-10-31 17:20:42 -07004605 if (deviceTypes.count(AUDIO_DEVICE_OUT_SPEAKER) > 0) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004606 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent1c333e22014-05-20 10:48:17 -07004607 }
4608
Eric Laurent054d9d32015-04-24 08:48:48 -07004609 // check if any other device (except speaker) is on
jiabinc52b1ff2019-10-31 17:20:42 -07004610 if (!isSingleDeviceType(deviceTypes, AUDIO_DEVICE_OUT_SPEAKER)) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004611 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
4612 }
4613
4614 if (params != 0) {
4615 addBatteryData(params);
4616 }
4617 }
4618#endif
4619
4620 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08004621 mEffectChains[i]->setDevices_l(deviceTypeAddrs);
Eric Laurent054d9d32015-04-24 08:48:48 -07004622 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07004623
jiabinc52b1ff2019-10-31 17:20:42 -07004624 // mPatch.num_sinks is not set when the thread is created so that
4625 // the first patch creation triggers an ioConfigChanged callback
4626 bool configChanged = (mPatch.num_sinks == 0) ||
4627 (mPatch.sinks[0].id != sinkPortId);
Eric Laurent296fb132015-05-01 11:38:42 -07004628 mPatch = *patch;
jiabinc52b1ff2019-10-31 17:20:42 -07004629 mOutDeviceTypeAddrs = deviceTypeAddrs;
jiabin0a957d32020-04-29 10:56:20 -07004630 checkSilentMode_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07004631
Mikhail Naganov9ee05402016-10-13 15:58:17 -07004632 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07004633 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
4634 status = hwDevice->createAudioPatch(patch->num_sources,
4635 patch->sources,
4636 patch->num_sinks,
4637 patch->sinks,
4638 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07004639 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08004640 status = mOutput->stream->legacyCreateAudioPatch(patch->sinks[0], std::nullopt, type);
Eric Laurent054d9d32015-04-24 08:48:48 -07004641 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07004642 }
Andy Hungc2b11cb2020-04-22 09:04:01 -07004643 const std::string patchSinksAsString = patchSinksToString(patch);
Andy Hungcf10d742020-04-28 15:38:24 -07004644
4645 mThreadMetrics.logEndInterval();
Andy Hungea840382020-05-05 21:50:17 -07004646 mThreadMetrics.logCreatePatch(/* inDevices */ {}, patchSinksAsString);
Andy Hungcf10d742020-04-28 15:38:24 -07004647 mThreadMetrics.logBeginInterval();
Andy Hungc2b11cb2020-04-22 09:04:01 -07004648 // also dispatch to active AudioTracks for MediaMetrics
4649 for (const auto &track : mActiveTracks) {
4650 track->logEndInterval();
4651 track->logBeginInterval(patchSinksAsString);
4652 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08004653
Eric Laurente8726fe2015-06-26 09:39:24 -07004654 if (configChanged) {
4655 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
4656 }
Eric Laurentdda206a2022-07-08 17:28:35 +02004657 // Force meteadata update after a route change
4658 mActiveTracks.setHasChanged();
4659
Eric Laurent1c333e22014-05-20 10:48:17 -07004660 return status;
4661}
4662
Eric Laurent054d9d32015-04-24 08:48:48 -07004663status_t AudioFlinger::MixerThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
4664{
Andy Hungf60abce2016-08-26 11:37:54 -07004665 status_t status;
4666 if (property_get_bool("af.patch_park", false /* default_value */)) {
4667 // Park FastMixer to avoid potential DOS issues with writing to the HAL
4668 // or if HAL does not properly lock against access.
4669 AutoPark<FastMixer> park(mFastMixer);
4670 status = PlaybackThread::releaseAudioPatch_l(handle);
4671 } else {
4672 status = PlaybackThread::releaseAudioPatch_l(handle);
4673 }
Eric Laurent054d9d32015-04-24 08:48:48 -07004674 return status;
4675}
4676
Eric Laurent1c333e22014-05-20 10:48:17 -07004677status_t AudioFlinger::PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
4678{
4679 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07004680
jiabinc52b1ff2019-10-31 17:20:42 -07004681 mPatch = audio_patch{};
4682 mOutDeviceTypeAddrs.clear();
Eric Laurent054d9d32015-04-24 08:48:48 -07004683
Mikhail Naganov9ee05402016-10-13 15:58:17 -07004684 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07004685 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
4686 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07004687 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08004688 status = mOutput->stream->legacyReleaseAudioPatch();
Eric Laurent1c333e22014-05-20 10:48:17 -07004689 }
Eric Laurentdda206a2022-07-08 17:28:35 +02004690 // Force meteadata update after a route change
4691 mActiveTracks.setHasChanged();
4692
Eric Laurent1c333e22014-05-20 10:48:17 -07004693 return status;
4694}
4695
Eric Laurent83b88082014-06-20 18:31:16 -07004696void AudioFlinger::PlaybackThread::addPatchTrack(const sp<PatchTrack>& track)
4697{
4698 Mutex::Autolock _l(mLock);
4699 mTracks.add(track);
4700}
4701
4702void AudioFlinger::PlaybackThread::deletePatchTrack(const sp<PatchTrack>& track)
4703{
4704 Mutex::Autolock _l(mLock);
4705 destroyTrack_l(track);
4706}
4707
Mikhail Naganovdc769682018-05-04 15:34:08 -07004708void AudioFlinger::PlaybackThread::toAudioPortConfig(struct audio_port_config *config)
Eric Laurent83b88082014-06-20 18:31:16 -07004709{
Mikhail Naganovdc769682018-05-04 15:34:08 -07004710 ThreadBase::toAudioPortConfig(config);
Eric Laurent83b88082014-06-20 18:31:16 -07004711 config->role = AUDIO_PORT_ROLE_SOURCE;
4712 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
4713 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07004714 if (mOutput && mOutput->flags != AUDIO_OUTPUT_FLAG_NONE) {
4715 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
4716 config->flags.output = mOutput->flags;
4717 }
Eric Laurent83b88082014-06-20 18:31:16 -07004718}
4719
Eric Laurent81784c32012-11-19 14:55:58 -08004720// ----------------------------------------------------------------------------
4721
4722AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Eric Laurentf1f22e72021-07-13 14:04:14 +02004723 audio_io_handle_t id, bool systemReady, type_t type, audio_config_base_t *mixerConfig)
4724 : PlaybackThread(audioFlinger, output, id, type, systemReady, mixerConfig),
Eric Laurent81784c32012-11-19 14:55:58 -08004725 // mAudioMixer below
4726 // mFastMixer below
Andy Hung2ddee192015-12-18 17:34:44 -08004727 mFastMixerFutex(0),
4728 mMasterMono(false)
Eric Laurent81784c32012-11-19 14:55:58 -08004729 // mOutputSink below
4730 // mPipeSink below
4731 // mNormalSink below
4732{
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01004733 setMasterBalance(audioFlinger->getMasterBalance_l());
jiabinc52b1ff2019-10-31 17:20:42 -07004734 ALOGV("MixerThread() id=%d type=%d", id, type);
Glenn Kasten49f36ba2017-12-06 13:02:02 -08004735 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%#x, mFrameSize=%zu, "
Glenn Kastenc42e9b42016-03-21 11:35:03 -07004736 "mFrameCount=%zu, mNormalFrameCount=%zu",
Eric Laurent81784c32012-11-19 14:55:58 -08004737 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
4738 mNormalFrameCount);
4739 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
4740
Andy Hungfbfc3952015-01-15 13:33:51 -08004741 if (type == DUPLICATING) {
4742 // The Duplicating thread uses the AudioMixer and delivers data to OutputTracks
4743 // (downstream MixerThreads) in DuplicatingThread::threadLoop_write().
4744 // Do not create or use mFastMixer, mOutputSink, mPipeSink, or mNormalSink.
4745 return;
4746 }
Eric Laurent81784c32012-11-19 14:55:58 -08004747 // create an NBAIO sink for the HAL output stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07004748 mOutputSink = new AudioStreamOutSink(output->stream);
Eric Laurent81784c32012-11-19 14:55:58 -08004749 size_t numCounterOffers = 0;
jiabin245cdd92018-12-07 17:55:15 -08004750 const NBAIO_Format offers[1] = {Format_from_SR_C(
4751 mSampleRate, mChannelCount + mHapticChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07004752#if !LOG_NDEBUG
4753 ssize_t index =
4754#else
4755 (void)
4756#endif
4757 mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08004758 ALOG_ASSERT(index == 0);
4759
4760 // initialize fast mixer depending on configuration
4761 bool initFastMixer;
Eric Laurentb62d0362021-10-26 17:40:18 +02004762 if (mType == SPATIALIZER) {
Eric Laurent81784c32012-11-19 14:55:58 -08004763 initFastMixer = false;
Eric Laurentb62d0362021-10-26 17:40:18 +02004764 } else {
4765 switch (kUseFastMixer) {
4766 case FastMixer_Never:
4767 initFastMixer = false;
4768 break;
4769 case FastMixer_Always:
4770 initFastMixer = true;
4771 break;
4772 case FastMixer_Static:
4773 case FastMixer_Dynamic:
4774 initFastMixer = mFrameCount < mNormalFrameCount;
4775 break;
4776 }
4777 ALOGW_IF(initFastMixer == false && mFrameCount < mNormalFrameCount,
4778 "FastMixer is preferred for this sink as frameCount %zu is less than threshold %zu",
4779 mFrameCount, mNormalFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08004780 }
4781 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07004782 audio_format_t fastMixerFormat;
4783 if (mMixerBufferEnabled && mEffectBufferEnabled) {
4784 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
4785 } else {
4786 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
4787 }
4788 if (mFormat != fastMixerFormat) {
4789 // change our Sink format to accept our intermediate precision
4790 mFormat = fastMixerFormat;
4791 free(mSinkBuffer);
jiabin245cdd92018-12-07 17:55:15 -08004792 mFrameSize = audio_bytes_per_frame(mChannelCount + mHapticChannelCount, mFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07004793 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
4794 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
4795 }
Eric Laurent81784c32012-11-19 14:55:58 -08004796
4797 // create a MonoPipe to connect our submix to FastMixer
4798 NBAIO_Format format = mOutputSink->format();
Andy Hung8946a282018-04-19 20:04:56 -07004799
Andy Hung1258c1a2014-05-23 21:22:17 -07004800 // adjust format to match that of the Fast Mixer
Glenn Kasten49f36ba2017-12-06 13:02:02 -08004801 ALOGV("format changed from %#x to %#x", format.mFormat, fastMixerFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07004802 format.mFormat = fastMixerFormat;
4803 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
4804
Eric Laurent81784c32012-11-19 14:55:58 -08004805 // This pipe depth compensates for scheduling latency of the normal mixer thread.
4806 // When it wakes up after a maximum latency, it runs a few cycles quickly before
4807 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
4808 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
4809 const NBAIO_Format offers[1] = {format};
4810 size_t numCounterOffers = 0;
Andy Hung8946a282018-04-19 20:04:56 -07004811#if !LOG_NDEBUG
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07004812 ssize_t index =
4813#else
4814 (void)
4815#endif
4816 monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08004817 ALOG_ASSERT(index == 0);
4818 monoPipe->setAvgFrames((mScreenState & 1) ?
4819 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
4820 mPipeSink = monoPipe;
4821
Eric Laurent81784c32012-11-19 14:55:58 -08004822 // create fast mixer and configure it initially with just one fast track for our submix
Andy Hung8946a282018-04-19 20:04:56 -07004823 mFastMixer = new FastMixer(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08004824 FastMixerStateQueue *sq = mFastMixer->sq();
4825#ifdef STATE_QUEUE_DUMP
4826 sq->setObserverDump(&mStateQueueObserverDump);
4827 sq->setMutatorDump(&mStateQueueMutatorDump);
4828#endif
4829 FastMixerState *state = sq->begin();
4830 FastTrack *fastTrack = &state->mFastTracks[0];
4831 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
4832 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
4833 fastTrack->mVolumeProvider = NULL;
Mikhail Naganov55773032020-10-01 15:08:13 -07004834 fastTrack->mChannelMask = static_cast<audio_channel_mask_t>(
4835 mChannelMask | mHapticChannelMask); // mPipeSink channel mask for
4836 // audio to FastMixer
Andy Hunge8a1ced2014-05-09 15:02:21 -07004837 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
jiabin245cdd92018-12-07 17:55:15 -08004838 fastTrack->mHapticPlaybackEnabled = mHapticChannelMask != AUDIO_CHANNEL_NONE;
jiabine70bc7f2020-06-30 22:07:55 -07004839 fastTrack->mHapticIntensity = os::HapticScale::NONE;
Lais Andradebc3f37a2021-07-02 00:13:19 +01004840 fastTrack->mHapticMaxAmplitude = NAN;
Eric Laurent81784c32012-11-19 14:55:58 -08004841 fastTrack->mGeneration++;
4842 state->mFastTracksGen++;
4843 state->mTrackMask = 1;
4844 // fast mixer will use the HAL output sink
4845 state->mOutputSink = mOutputSink.get();
4846 state->mOutputSinkGen++;
4847 state->mFrameCount = mFrameCount;
jiabin245cdd92018-12-07 17:55:15 -08004848 // specify sink channel mask when haptic channel mask present as it can not
4849 // be calculated directly from channel count
4850 state->mSinkChannelMask = mHapticChannelMask == AUDIO_CHANNEL_NONE
Mikhail Naganov55773032020-10-01 15:08:13 -07004851 ? AUDIO_CHANNEL_NONE
4852 : static_cast<audio_channel_mask_t>(mChannelMask | mHapticChannelMask);
Eric Laurent81784c32012-11-19 14:55:58 -08004853 state->mCommand = FastMixerState::COLD_IDLE;
4854 // already done in constructor initialization list
4855 //mFastMixerFutex = 0;
4856 state->mColdFutexAddr = &mFastMixerFutex;
4857 state->mColdGen++;
4858 state->mDumpState = &mFastMixerDumpState;
Glenn Kasten9e58b552013-01-18 15:09:48 -08004859 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
4860 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08004861 sq->end();
4862 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
4863
Eric Tan0513b5d2018-09-17 10:32:48 -07004864 NBLog::thread_info_t info;
4865 info.id = mId;
4866 info.type = NBLog::FASTMIXER;
4867 mFastMixerNBLogWriter->log<NBLog::EVENT_THREAD_INFO>(info);
4868
Eric Laurent81784c32012-11-19 14:55:58 -08004869 // start the fast mixer
4870 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
4871 pid_t tid = mFastMixer->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07004872 sendPrioConfigEvent(getpid(), tid, kPriorityFastMixer, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08004873 stream()->setHalThreadPriority(kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08004874
4875#ifdef AUDIO_WATCHDOG
4876 // create and start the watchdog
4877 mAudioWatchdog = new AudioWatchdog();
4878 mAudioWatchdog->setDump(&mAudioWatchdogDump);
4879 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
4880 tid = mAudioWatchdog->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07004881 sendPrioConfigEvent(getpid(), tid, kPriorityFastMixer, false /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08004882#endif
Andy Hung8946a282018-04-19 20:04:56 -07004883 } else {
4884#ifdef TEE_SINK
4885 // Only use the MixerThread tee if there is no FastMixer.
4886 mTee.set(mOutputSink->format(), NBAIO_Tee::TEE_FLAG_OUTPUT_THREAD);
4887 mTee.setId(std::string("_") + std::to_string(mId) + "_M");
4888#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004889 }
4890
4891 switch (kUseFastMixer) {
4892 case FastMixer_Never:
4893 case FastMixer_Dynamic:
4894 mNormalSink = mOutputSink;
4895 break;
4896 case FastMixer_Always:
4897 mNormalSink = mPipeSink;
4898 break;
4899 case FastMixer_Static:
4900 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
4901 break;
4902 }
4903}
4904
4905AudioFlinger::MixerThread::~MixerThread()
4906{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004907 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004908 FastMixerStateQueue *sq = mFastMixer->sq();
4909 FastMixerState *state = sq->begin();
4910 if (state->mCommand == FastMixerState::COLD_IDLE) {
4911 int32_t old = android_atomic_inc(&mFastMixerFutex);
4912 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07004913 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08004914 }
4915 }
4916 state->mCommand = FastMixerState::EXIT;
4917 sq->end();
4918 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
4919 mFastMixer->join();
4920 // Though the fast mixer thread has exited, it's state queue is still valid.
4921 // We'll use that extract the final state which contains one remaining fast track
4922 // corresponding to our sub-mix.
4923 state = sq->begin();
4924 ALOG_ASSERT(state->mTrackMask == 1);
4925 FastTrack *fastTrack = &state->mFastTracks[0];
4926 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
4927 delete fastTrack->mBufferProvider;
4928 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004929 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08004930#ifdef AUDIO_WATCHDOG
4931 if (mAudioWatchdog != 0) {
4932 mAudioWatchdog->requestExit();
4933 mAudioWatchdog->requestExitAndWait();
4934 mAudioWatchdog.clear();
4935 }
4936#endif
4937 }
Glenn Kasten9e58b552013-01-18 15:09:48 -08004938 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08004939 delete mAudioMixer;
4940}
4941
4942
4943uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
4944{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004945 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004946 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
4947 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
4948 }
4949 return latency;
4950}
4951
Eric Laurentbfb1b832013-01-07 09:53:42 -08004952ssize_t AudioFlinger::MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08004953{
4954 // FIXME we should only do one push per cycle; confirm this is true
4955 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004956 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004957 FastMixerStateQueue *sq = mFastMixer->sq();
4958 FastMixerState *state = sq->begin();
4959 if (state->mCommand != FastMixerState::MIX_WRITE &&
4960 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
4961 if (state->mCommand == FastMixerState::COLD_IDLE) {
Eric Laurenta2ab4502015-09-09 12:25:51 -07004962
4963 // FIXME workaround for first HAL write being CPU bound on some devices
4964 ATRACE_BEGIN("write");
4965 mOutput->write((char *)mSinkBuffer, 0);
4966 ATRACE_END();
4967
Eric Laurent81784c32012-11-19 14:55:58 -08004968 int32_t old = android_atomic_inc(&mFastMixerFutex);
4969 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07004970 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08004971 }
4972#ifdef AUDIO_WATCHDOG
4973 if (mAudioWatchdog != 0) {
4974 mAudioWatchdog->resume();
4975 }
4976#endif
4977 }
4978 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kastend797a9d2015-03-02 14:19:25 -08004979#ifdef FAST_THREAD_STATISTICS
Glenn Kasten4182c4e2013-07-15 14:45:07 -07004980 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08004981 FastThreadDumpState::kSamplingNforLowRamDevice : FastThreadDumpState::kSamplingN);
Glenn Kastend797a9d2015-03-02 14:19:25 -08004982#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004983 sq->end();
4984 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
4985 if (kUseFastMixer == FastMixer_Dynamic) {
4986 mNormalSink = mPipeSink;
4987 }
4988 } else {
4989 sq->end(false /*didModify*/);
4990 }
4991 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004992 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08004993}
4994
4995void AudioFlinger::MixerThread::threadLoop_standby()
4996{
4997 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004998 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004999 FastMixerStateQueue *sq = mFastMixer->sq();
5000 FastMixerState *state = sq->begin();
5001 if (!(state->mCommand & FastMixerState::IDLE)) {
Andy Hung2148bf02016-11-28 19:01:02 -08005002 // Report any frames trapped in the Monopipe
5003 MonoPipe *monoPipe = (MonoPipe *)mPipeSink.get();
5004 const long long pipeFrames = monoPipe->maxFrames() - monoPipe->availableToWrite();
5005 mLocalLog.log("threadLoop_standby: framesWritten:%lld suspendedFrames:%lld "
5006 "monoPipeWritten:%lld monoPipeLeft:%lld",
5007 (long long)mFramesWritten, (long long)mSuspendedFrames,
5008 (long long)mPipeSink->framesWritten(), pipeFrames);
5009 mLocalLog.log("threadLoop_standby: %s", mTimestamp.toString().c_str());
5010
Eric Laurent81784c32012-11-19 14:55:58 -08005011 state->mCommand = FastMixerState::COLD_IDLE;
5012 state->mColdFutexAddr = &mFastMixerFutex;
5013 state->mColdGen++;
5014 mFastMixerFutex = 0;
5015 sq->end();
5016 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
5017 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
5018 if (kUseFastMixer == FastMixer_Dynamic) {
5019 mNormalSink = mOutputSink;
5020 }
5021#ifdef AUDIO_WATCHDOG
5022 if (mAudioWatchdog != 0) {
5023 mAudioWatchdog->pause();
5024 }
5025#endif
5026 } else {
5027 sq->end(false /*didModify*/);
5028 }
5029 }
5030 PlaybackThread::threadLoop_standby();
5031}
5032
Eric Laurentbfb1b832013-01-07 09:53:42 -08005033bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
5034{
5035 return false;
5036}
5037
5038bool AudioFlinger::PlaybackThread::shouldStandby_l()
5039{
5040 return !mStandby;
5041}
5042
5043bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
5044{
5045 Mutex::Autolock _l(mLock);
5046 return waitingAsyncCallback_l();
5047}
5048
Eric Laurent81784c32012-11-19 14:55:58 -08005049// shared by MIXER and DIRECT, overridden by DUPLICATING
5050void AudioFlinger::PlaybackThread::threadLoop_standby()
5051{
5052 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
Phil Burk062e67a2015-02-11 13:40:50 -08005053 mOutput->standby();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005054 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005055 // discard any pending drain or write ack by incrementing sequence
5056 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
5057 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005058 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005059 mCallbackThread->setWriteBlocked(mWriteAckSequence);
5060 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005061 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08005062 mHwPaused = false;
Eric Laurent68a40a82022-05-03 18:15:04 +02005063 setHalLatencyMode_l();
Eric Laurent81784c32012-11-19 14:55:58 -08005064}
5065
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08005066void AudioFlinger::PlaybackThread::onAddNewTrack_l()
5067{
5068 ALOGV("signal playback thread");
5069 broadcast_l();
5070}
5071
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005072void AudioFlinger::PlaybackThread::onAsyncError()
5073{
5074 for (int i = AUDIO_STREAM_SYSTEM; i < (int)AUDIO_STREAM_CNT; i++) {
5075 invalidateTracks((audio_stream_type_t)i);
5076 }
5077}
5078
Eric Laurent81784c32012-11-19 14:55:58 -08005079void AudioFlinger::MixerThread::threadLoop_mix()
5080{
Eric Laurent81784c32012-11-19 14:55:58 -08005081 // mix buffers...
Glenn Kastend79072e2016-01-06 08:41:20 -08005082 mAudioMixer->process();
Andy Hung25c2dac2014-02-27 14:56:00 -08005083 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005084 // increase sleep time progressively when application underrun condition clears.
5085 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
5086 // that a steady state of alternating ready/not ready conditions keeps the sleep time
5087 // such that we would underrun the audio HAL.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005088 if ((mSleepTimeUs == 0) && (sleepTimeShift > 0)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005089 sleepTimeShift--;
5090 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005091 mSleepTimeUs = 0;
5092 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08005093 //TODO: delay standby when effects have a tail
Glenn Kasten4c053ea2014-09-28 14:41:07 -07005094
Eric Laurent81784c32012-11-19 14:55:58 -08005095}
5096
5097void AudioFlinger::MixerThread::threadLoop_sleepTime()
5098{
5099 // If no tracks are ready, sleep once for the duration of an output
5100 // buffer size, then write 0s to the output
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005101 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005102 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Andy Hung06d13222018-05-03 20:13:31 -07005103 if (mPipeSink.get() != nullptr && mPipeSink == mNormalSink) {
5104 // Using the Monopipe availableToWrite, we estimate the
5105 // sleep time to retry for more data (before we underrun).
5106 MonoPipe *monoPipe = static_cast<MonoPipe *>(mPipeSink.get());
5107 const ssize_t availableToWrite = mPipeSink->availableToWrite();
5108 const size_t pipeFrames = monoPipe->maxFrames();
5109 const size_t framesLeft = pipeFrames - max(availableToWrite, 0);
5110 // HAL_framecount <= framesDelay ~ framesLeft / 2 <= Normal_Mixer_framecount
5111 const size_t framesDelay = std::min(
5112 mNormalFrameCount, max(framesLeft / 2, mFrameCount));
5113 ALOGV("pipeFrames:%zu framesLeft:%zu framesDelay:%zu",
5114 pipeFrames, framesLeft, framesDelay);
5115 mSleepTimeUs = framesDelay * MICROS_PER_SECOND / mSampleRate;
5116 } else {
5117 mSleepTimeUs = mActiveSleepTimeUs >> sleepTimeShift;
5118 if (mSleepTimeUs < kMinThreadSleepTimeUs) {
5119 mSleepTimeUs = kMinThreadSleepTimeUs;
5120 }
5121 // reduce sleep time in case of consecutive application underruns to avoid
5122 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
5123 // duration we would end up writing less data than needed by the audio HAL if
5124 // the condition persists.
5125 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
5126 sleepTimeShift++;
5127 }
Eric Laurent81784c32012-11-19 14:55:58 -08005128 }
5129 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005130 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005131 }
5132 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08005133 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
5134 // before effects processing or output.
5135 if (mMixerBufferValid) {
5136 memset(mMixerBuffer, 0, mMixerBufferSize);
Eric Laurent39095982021-08-24 18:29:27 +02005137 if (mType == SPATIALIZER) {
5138 memset(mSinkBuffer, 0, mSinkBufferSize);
5139 }
Andy Hung98ef9782014-03-04 14:46:50 -08005140 } else {
5141 memset(mSinkBuffer, 0, mSinkBufferSize);
5142 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005143 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005144 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
5145 "anticipated start");
5146 }
5147 // TODO add standby time extension fct of effect tail
5148}
5149
5150// prepareTracks_l() must be called with ThreadBase::mLock held
5151AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
5152 Vector< sp<Track> > *tracksToRemove)
5153{
Andy Hungc0691382018-09-12 18:01:57 -07005154 // clean up deleted track ids in AudioMixer before allocating new tracks
5155 (void)mTracks.processDeletedTrackIds([this](int trackId) {
5156 // for each trackId, destroy it in the AudioMixer
5157 if (mAudioMixer->exists(trackId)) {
5158 mAudioMixer->destroy(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08005159 }
5160 });
Andy Hungc0691382018-09-12 18:01:57 -07005161 mTracks.clearDeletedTrackIds();
Eric Laurent81784c32012-11-19 14:55:58 -08005162
5163 mixer_state mixerStatus = MIXER_IDLE;
5164 // find out which tracks need to be processed
5165 size_t count = mActiveTracks.size();
5166 size_t mixedTracks = 0;
5167 size_t tracksWithEffect = 0;
5168 // counts only _active_ fast tracks
5169 size_t fastTracks = 0;
5170 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
5171
5172 float masterVolume = mMasterVolume;
5173 bool masterMute = mMasterMute;
5174
5175 if (masterMute) {
5176 masterVolume = 0;
5177 }
5178 // Delegate master volume control to effect in output mix effect chain if needed
5179 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
5180 if (chain != 0) {
5181 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
5182 chain->setVolume_l(&v, &v);
5183 masterVolume = (float)((v + (1 << 23)) >> 24);
5184 chain.clear();
5185 }
5186
5187 // prepare a new state to push
5188 FastMixerStateQueue *sq = NULL;
5189 FastMixerState *state = NULL;
5190 bool didModify = false;
5191 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Andy Hungf2285312017-02-14 18:31:59 -08005192 bool coldIdle = false;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005193 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005194 sq = mFastMixer->sq();
5195 state = sq->begin();
Andy Hungf2285312017-02-14 18:31:59 -08005196 coldIdle = state->mCommand == FastMixerState::COLD_IDLE;
Eric Laurent81784c32012-11-19 14:55:58 -08005197 }
5198
Andy Hung69aed5f2014-02-25 17:24:40 -08005199 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08005200 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08005201
Andy Hungbd3b2b02018-05-21 10:53:11 -07005202 // DeferredOperations handles statistics after setting mixerStatus.
5203 class DeferredOperations {
5204 public:
Andy Hungea840382020-05-05 21:50:17 -07005205 DeferredOperations(mixer_state *mixerStatus, ThreadMetrics *threadMetrics)
5206 : mMixerStatus(mixerStatus)
5207 , mThreadMetrics(threadMetrics) {}
Andy Hungbd3b2b02018-05-21 10:53:11 -07005208
5209 // when leaving scope, tally frames properly.
5210 ~DeferredOperations() {
5211 // Tally underrun frames only if we are actually mixing (MIXER_TRACKS_READY)
5212 // because that is when the underrun occurs.
5213 // We do not distinguish between FastTracks and NormalTracks here.
Andy Hungea840382020-05-05 21:50:17 -07005214 size_t maxUnderrunFrames = 0;
Andy Hungb68f5eb2019-12-03 16:49:17 -08005215 if (*mMixerStatus == MIXER_TRACKS_READY && mUnderrunFrames.size() > 0) {
Andy Hungbd3b2b02018-05-21 10:53:11 -07005216 for (const auto &underrun : mUnderrunFrames) {
Andy Hungc2b11cb2020-04-22 09:04:01 -07005217 underrun.first->tallyUnderrunFrames(underrun.second);
Andy Hungea840382020-05-05 21:50:17 -07005218 maxUnderrunFrames = max(underrun.second, maxUnderrunFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07005219 }
5220 }
Andy Hungea840382020-05-05 21:50:17 -07005221 // send the max underrun frames for this mixer period
5222 mThreadMetrics->logUnderrunFrames(maxUnderrunFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07005223 }
5224
5225 // tallyUnderrunFrames() is called to update the track counters
5226 // with the number of underrun frames for a particular mixer period.
5227 // We defer tallying until we know the final mixer status.
5228 void tallyUnderrunFrames(sp<Track> track, size_t underrunFrames) {
5229 mUnderrunFrames.emplace_back(track, underrunFrames);
5230 }
5231
5232 private:
5233 const mixer_state * const mMixerStatus;
Andy Hungea840382020-05-05 21:50:17 -07005234 ThreadMetrics * const mThreadMetrics;
Andy Hungbd3b2b02018-05-21 10:53:11 -07005235 std::vector<std::pair<sp<Track>, size_t>> mUnderrunFrames;
Andy Hungea840382020-05-05 21:50:17 -07005236 } deferredOperations(&mixerStatus, &mThreadMetrics);
Andy Hungb68f5eb2019-12-03 16:49:17 -08005237 // implicit nested scope for variable capture
Andy Hungbd3b2b02018-05-21 10:53:11 -07005238
jiabin245cdd92018-12-07 17:55:15 -08005239 bool noFastHapticTrack = true;
Eric Laurent81784c32012-11-19 14:55:58 -08005240 for (size_t i=0 ; i<count ; i++) {
Andy Hungdae27702016-10-31 14:01:16 -07005241 const sp<Track> t = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08005242
5243 // this const just means the local variable doesn't change
5244 Track* const track = t.get();
5245
5246 // process fast tracks
5247 if (track->isFastTrack()) {
Andy Hungae22b482019-05-09 15:38:55 -07005248 LOG_ALWAYS_FATAL_IF(mFastMixer.get() == nullptr,
5249 "%s(%d): FastTrack(%d) present without FastMixer",
5250 __func__, id(), track->id());
5251
jiabin245cdd92018-12-07 17:55:15 -08005252 if (track->getHapticPlaybackEnabled()) {
5253 noFastHapticTrack = false;
5254 }
Eric Laurent81784c32012-11-19 14:55:58 -08005255
5256 // It's theoretically possible (though unlikely) for a fast track to be created
5257 // and then removed within the same normal mix cycle. This is not a problem, as
5258 // the track never becomes active so it's fast mixer slot is never touched.
5259 // The converse, of removing an (active) track and then creating a new track
5260 // at the identical fast mixer slot within the same normal mix cycle,
5261 // is impossible because the slot isn't marked available until the end of each cycle.
5262 int j = track->mFastIndex;
Glenn Kastendc2c50b2016-04-21 08:13:14 -07005263 ALOG_ASSERT(0 < j && j < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08005264 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
5265 FastTrack *fastTrack = &state->mFastTracks[j];
5266
5267 // Determine whether the track is currently in underrun condition,
5268 // and whether it had a recent underrun.
5269 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
5270 FastTrackUnderruns underruns = ftDump->mUnderruns;
5271 uint32_t recentFull = (underruns.mBitFields.mFull -
5272 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
5273 uint32_t recentPartial = (underruns.mBitFields.mPartial -
5274 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
5275 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
5276 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
5277 uint32_t recentUnderruns = recentPartial + recentEmpty;
5278 track->mObservedUnderruns = underruns;
5279 // don't count underruns that occur while stopping or pausing
5280 // or stopped which can occur when flush() is called while active
Andy Hungbd3b2b02018-05-21 10:53:11 -07005281 size_t underrunFrames = 0;
Glenn Kasten82aaf942013-07-17 16:05:07 -07005282 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
5283 recentUnderruns > 0) {
5284 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
Andy Hungbd3b2b02018-05-21 10:53:11 -07005285 underrunFrames = recentUnderruns * mFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08005286 }
Andy Hungbd3b2b02018-05-21 10:53:11 -07005287 // Immediately account for FastTrack underruns.
5288 track->mAudioTrackServerProxy->tallyUnderrunFrames(underrunFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08005289
5290 // This is similar to the state machine for normal tracks,
5291 // with a few modifications for fast tracks.
5292 bool isActive = true;
5293 switch (track->mState) {
5294 case TrackBase::STOPPING_1:
5295 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08005296 if (recentUnderruns > 0 || track->isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -08005297 track->mState = TrackBase::STOPPING_2;
5298 }
5299 break;
5300 case TrackBase::PAUSING:
5301 // ramp down is not yet implemented
5302 track->setPaused();
5303 break;
5304 case TrackBase::RESUMING:
5305 // ramp up is not yet implemented
5306 track->mState = TrackBase::ACTIVE;
5307 break;
5308 case TrackBase::ACTIVE:
5309 if (recentFull > 0 || recentPartial > 0) {
5310 // track has provided at least some frames recently: reset retry count
5311 track->mRetryCount = kMaxTrackRetries;
5312 }
5313 if (recentUnderruns == 0) {
5314 // no recent underruns: stay active
5315 break;
5316 }
5317 // there has recently been an underrun of some kind
5318 if (track->sharedBuffer() == 0) {
5319 // were any of the recent underruns "empty" (no frames available)?
5320 if (recentEmpty == 0) {
5321 // no, then ignore the partial underruns as they are allowed indefinitely
5322 break;
5323 }
5324 // there has recently been an "empty" underrun: decrement the retry counter
5325 if (--(track->mRetryCount) > 0) {
5326 break;
5327 }
5328 // indicate to client process that the track was disabled because of underrun;
5329 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08005330 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08005331 // remove from active list, but state remains ACTIVE [confusing but true]
5332 isActive = false;
5333 break;
5334 }
Chih-Hung Hsieh2b487032018-09-13 14:16:02 -07005335 FALLTHROUGH_INTENDED;
Eric Laurent81784c32012-11-19 14:55:58 -08005336 case TrackBase::STOPPING_2:
5337 case TrackBase::PAUSED:
Eric Laurent81784c32012-11-19 14:55:58 -08005338 case TrackBase::STOPPED:
5339 case TrackBase::FLUSHED: // flush() while active
5340 // Check for presentation complete if track is inactive
5341 // We have consumed all the buffers of this track.
5342 // This would be incomplete if we auto-paused on underrun
5343 {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005344 uint32_t latency = 0;
5345 status_t result = mOutput->stream->getLatency(&latency);
5346 ALOGE_IF(result != OK,
5347 "Error when retrieving output stream latency: %d", result);
5348 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08005349 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005350 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
5351 // track stays in active list until presentation is complete
5352 break;
5353 }
5354 }
5355 if (track->isStopping_2()) {
5356 track->mState = TrackBase::STOPPED;
5357 }
5358 if (track->isStopped()) {
5359 // Can't reset directly, as fast mixer is still polling this track
5360 // track->reset();
5361 // So instead mark this track as needing to be reset after push with ack
5362 resetMask |= 1 << i;
5363 }
5364 isActive = false;
5365 break;
5366 case TrackBase::IDLE:
5367 default:
Andy Hung959b5b82021-09-24 10:46:20 -07005368 LOG_ALWAYS_FATAL("unexpected track state %d", (int)track->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08005369 }
5370
5371 if (isActive) {
5372 // was it previously inactive?
5373 if (!(state->mTrackMask & (1 << j))) {
5374 ExtendedAudioBufferProvider *eabp = track;
5375 VolumeProvider *vp = track;
5376 fastTrack->mBufferProvider = eabp;
5377 fastTrack->mVolumeProvider = vp;
Eric Laurent81784c32012-11-19 14:55:58 -08005378 fastTrack->mChannelMask = track->mChannelMask;
Andy Hunge8a1ced2014-05-09 15:02:21 -07005379 fastTrack->mFormat = track->mFormat;
jiabin245cdd92018-12-07 17:55:15 -08005380 fastTrack->mHapticPlaybackEnabled = track->getHapticPlaybackEnabled();
jiabin77270b82018-12-18 15:41:29 -08005381 fastTrack->mHapticIntensity = track->getHapticIntensity();
Lais Andradebc3f37a2021-07-02 00:13:19 +01005382 fastTrack->mHapticMaxAmplitude = track->getHapticMaxAmplitude();
Eric Laurent81784c32012-11-19 14:55:58 -08005383 fastTrack->mGeneration++;
5384 state->mTrackMask |= 1 << j;
5385 didModify = true;
5386 // no acknowledgement required for newly active tracks
5387 }
Kevin Rocard12381092018-04-11 09:19:59 -07005388 sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
Eric Laurenteab90452019-06-24 15:17:46 -07005389 float volume;
5390 if (track->isPlaybackRestricted() || mStreamTypes[track->streamType()].mute) {
5391 volume = 0.f;
5392 } else {
5393 volume = masterVolume * mStreamTypes[track->streamType()].volume;
5394 }
5395
5396 handleVoipVolume_l(&volume);
5397
Eric Laurent81784c32012-11-19 14:55:58 -08005398 // cache the combined master volume and stream type volume for fast mixer; this
5399 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005400 const float vh = track->getVolumeHandler()->getVolume(
Eric Laurenteab90452019-06-24 15:17:46 -07005401 proxy->framesReleased()).first;
5402 volume *= vh;
Kevin Rocardb0eeaf122018-04-11 08:30:16 -07005403 track->mCachedVolume = volume;
Kevin Rocard12381092018-04-11 09:19:59 -07005404 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Vlad Popae2f5aef2022-07-25 16:00:20 +02005405 float vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
5406 float vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
5407
5408 track->processMuteEvent_l(mAudioFlinger->getOrCreateAudioManager(),
5409 /*muteState=*/{masterVolume == 0.f,
5410 mStreamTypes[track->streamType()].volume == 0.f,
5411 mStreamTypes[track->streamType()].mute,
5412 track->isPlaybackRestricted(),
Vlad Popa436c9172022-08-02 15:25:08 +02005413 vlf == 0.f && vrf == 0.f,
5414 vh == 0.f});
Vlad Popae2f5aef2022-07-25 16:00:20 +02005415
5416 vlf *= volume;
5417 vrf *= volume;
Eric Laurenteab90452019-06-24 15:17:46 -07005418
Kevin Rocard12381092018-04-11 09:19:59 -07005419 track->setFinalVolume((vlf + vrf) / 2.f);
Eric Laurent81784c32012-11-19 14:55:58 -08005420 ++fastTracks;
5421 } else {
5422 // was it previously active?
5423 if (state->mTrackMask & (1 << j)) {
5424 fastTrack->mBufferProvider = NULL;
5425 fastTrack->mGeneration++;
5426 state->mTrackMask &= ~(1 << j);
5427 didModify = true;
5428 // If any fast tracks were removed, we must wait for acknowledgement
5429 // because we're about to decrement the last sp<> on those tracks.
5430 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
5431 } else {
Glenn Kastenbf848af2017-12-22 11:55:01 -08005432 // ALOGW rather than LOG_ALWAYS_FATAL because it seems there are cases where an
5433 // AudioTrack may start (which may not be with a start() but with a write()
5434 // after underrun) and immediately paused or released. In that case the
5435 // FastTrack state hasn't had time to update.
5436 // TODO Remove the ALOGW when this theory is confirmed.
5437 ALOGW("fast track %d should have been active; "
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08005438 "mState=%d, mTrackMask=%#x, recentUnderruns=%u, isShared=%d",
Andy Hung959b5b82021-09-24 10:46:20 -07005439 j, (int)track->mState, state->mTrackMask, recentUnderruns,
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08005440 track->sharedBuffer() != 0);
Glenn Kastenbf848af2017-12-22 11:55:01 -08005441 // Since the FastMixer state already has the track inactive, do nothing here.
Eric Laurent81784c32012-11-19 14:55:58 -08005442 }
5443 tracksToRemove->add(track);
5444 // Avoids a misleading display in dumpsys
5445 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
5446 }
jiabin245cdd92018-12-07 17:55:15 -08005447 if (fastTrack->mHapticPlaybackEnabled != track->getHapticPlaybackEnabled()) {
5448 fastTrack->mHapticPlaybackEnabled = track->getHapticPlaybackEnabled();
5449 didModify = true;
5450 }
Eric Laurent81784c32012-11-19 14:55:58 -08005451 continue;
5452 }
5453
5454 { // local variable scope to avoid goto warning
5455
5456 audio_track_cblk_t* cblk = track->cblk();
5457
5458 // The first time a track is added we wait
5459 // for all its buffers to be filled before processing it
Andy Hungc0691382018-09-12 18:01:57 -07005460 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08005461
5462 // if an active track doesn't exist in the AudioMixer, create it.
Andy Hungc0691382018-09-12 18:01:57 -07005463 // use the trackId as the AudioMixer name.
5464 if (!mAudioMixer->exists(trackId)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08005465 status_t status = mAudioMixer->create(
Andy Hungc0691382018-09-12 18:01:57 -07005466 trackId,
Andy Hung1bc088a2018-02-09 15:57:31 -08005467 track->mChannelMask,
5468 track->mFormat,
5469 track->mSessionId);
5470 if (status != OK) {
Andy Hungc0691382018-09-12 18:01:57 -07005471 ALOGW("%s(): AudioMixer cannot create track(%d)"
5472 " mask %#x, format %#x, sessionId %d",
5473 __func__, trackId,
5474 track->mChannelMask, track->mFormat, track->mSessionId);
Andy Hung1bc088a2018-02-09 15:57:31 -08005475 tracksToRemove->add(track);
5476 track->invalidate(); // consider it dead.
5477 continue;
5478 }
5479 }
5480
Eric Laurent81784c32012-11-19 14:55:58 -08005481 // make sure that we have enough frames to mix one full buffer.
5482 // enforce this condition only once to enable draining the buffer in case the client
5483 // app does not call stop() and relies on underrun to stop:
5484 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
5485 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005486 size_t desiredFrames;
Andy Hung8edb8dc2015-03-26 19:13:55 -07005487 const uint32_t sampleRate = track->mAudioTrackServerProxy->getSampleRate();
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07005488 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07005489
5490 desiredFrames = sourceFramesNeededWithTimestretch(
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07005491 sampleRate, mNormalFrameCount, mSampleRate, playbackRate.mSpeed);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005492 // TODO: ONLY USED FOR LEGACY RESAMPLERS, remove when they are removed.
5493 // add frames already consumed but not yet released by the resampler
5494 // because mAudioTrackServerProxy->framesReady() will include these frames
Andy Hungc0691382018-09-12 18:01:57 -07005495 desiredFrames += mAudioMixer->getUnreleasedFrames(trackId);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005496
Eric Laurent81784c32012-11-19 14:55:58 -08005497 uint32_t minFrames = 1;
5498 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
5499 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005500 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08005501 }
Eric Laurent13e4c962013-12-20 17:36:01 -08005502
5503 size_t framesReady = track->framesReady();
Glenn Kastene7754022014-10-31 12:11:26 -07005504 if (ATRACE_ENABLED()) {
5505 // I wish we had formatted trace names
Andy Hung1bc088a2018-02-09 15:57:31 -08005506 std::string traceName("nRdy");
Andy Hungc0691382018-09-12 18:01:57 -07005507 traceName += std::to_string(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08005508 ATRACE_INT(traceName.c_str(), framesReady);
Glenn Kastene7754022014-10-31 12:11:26 -07005509 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005510 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08005511 !track->isPaused() && !track->isTerminated())
5512 {
Andy Hungc0691382018-09-12 18:01:57 -07005513 ALOGVV("track(%d) s=%08x [OK] on thread %p", trackId, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08005514
5515 mixedTracks++;
5516
Andy Hung69aed5f2014-02-25 17:24:40 -08005517 // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
5518 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08005519 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08005520 if (track->mainBuffer() != mSinkBuffer &&
5521 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08005522 if (mEffectBufferEnabled) {
5523 mEffectBufferValid = true; // Later can set directly.
5524 }
Eric Laurent81784c32012-11-19 14:55:58 -08005525 chain = getEffectChain_l(track->sessionId());
5526 // Delegate volume control to effect in track effect chain if needed
5527 if (chain != 0) {
5528 tracksWithEffect++;
5529 } else {
Andy Hungc0691382018-09-12 18:01:57 -07005530 ALOGW("prepareTracks_l(): track(%d) attached to effect but no chain found on "
Eric Laurent81784c32012-11-19 14:55:58 -08005531 "session %d",
Andy Hungc0691382018-09-12 18:01:57 -07005532 trackId, track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08005533 }
5534 }
5535
5536
5537 int param = AudioMixer::VOLUME;
5538 if (track->mFillingUpStatus == Track::FS_FILLED) {
5539 // no ramp for the first volume setting
5540 track->mFillingUpStatus = Track::FS_ACTIVE;
5541 if (track->mState == TrackBase::RESUMING) {
5542 track->mState = TrackBase::ACTIVE;
Revathi Uddaraju453bcb52017-08-14 14:19:40 +08005543 // If a new track is paused immediately after start, do not ramp on resume.
5544 if (cblk->mServer != 0) {
5545 param = AudioMixer::RAMP_VOLUME;
5546 }
Eric Laurent81784c32012-11-19 14:55:58 -08005547 }
Andy Hungc0691382018-09-12 18:01:57 -07005548 mAudioMixer->setParameter(trackId, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Eric Laurent7c29ec92017-09-20 17:54:22 -07005549 mLeftVolFloat = -1.0;
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005550 // FIXME should not make a decision based on mServer
5551 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005552 // If the track is stopped before the first frame was mixed,
5553 // do not apply ramp
5554 param = AudioMixer::RAMP_VOLUME;
5555 }
5556
5557 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07005558 uint32_t vl, vr; // in U8.24 integer format
5559 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Eric Laurent7c29ec92017-09-20 17:54:22 -07005560 // read original volumes with volume control
Eric Laurenteab90452019-06-24 15:17:46 -07005561 float v = masterVolume * mStreamTypes[track->streamType()].volume;
Andy Hung333ab962019-05-28 20:23:35 -07005562 // Always fetch volumeshaper volume to ensure state is updated.
5563 const sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
5564 const float vh = track->getVolumeHandler()->getVolume(
5565 track->mAudioTrackServerProxy->framesReleased()).first;
Eric Laurent7c29ec92017-09-20 17:54:22 -07005566
Eric Laurenteab90452019-06-24 15:17:46 -07005567 if (mStreamTypes[track->streamType()].mute || track->isPlaybackRestricted()) {
5568 v = 0;
5569 }
5570
5571 handleVoipVolume_l(&v);
5572
5573 if (track->isPausing()) {
Andy Hung6be49402014-05-30 10:42:03 -07005574 vl = vr = 0;
5575 vlf = vrf = vaf = 0.;
Eric Laurenteab90452019-06-24 15:17:46 -07005576 track->setPaused();
Eric Laurent81784c32012-11-19 14:55:58 -08005577 } else {
Glenn Kastenc56f3422014-03-21 17:53:17 -07005578 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07005579 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
5580 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08005581 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07005582 if (vlf > GAIN_FLOAT_UNITY) {
5583 ALOGV("Track left volume out of range: %.3g", vlf);
5584 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08005585 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07005586 if (vrf > GAIN_FLOAT_UNITY) {
5587 ALOGV("Track right volume out of range: %.3g", vrf);
5588 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08005589 }
Vlad Popae2f5aef2022-07-25 16:00:20 +02005590
5591 track->processMuteEvent_l(mAudioFlinger->getOrCreateAudioManager(),
5592 /*muteState=*/{masterVolume == 0.f,
5593 mStreamTypes[track->streamType()].volume == 0.f,
5594 mStreamTypes[track->streamType()].mute,
5595 track->isPlaybackRestricted(),
Vlad Popa436c9172022-08-02 15:25:08 +02005596 vlf == 0.f && vrf == 0.f,
5597 vh == 0.f});
Vlad Popae2f5aef2022-07-25 16:00:20 +02005598
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005599 // now apply the master volume and stream type volume and shaper volume
5600 vlf *= v * vh;
5601 vrf *= v * vh;
Eric Laurent81784c32012-11-19 14:55:58 -08005602 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07005603 // then derive vl and vr as U8.24 versions for the effect chain
5604 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
5605 vl = (uint32_t) (scaleto8_24 * vlf);
5606 vr = (uint32_t) (scaleto8_24 * vrf);
5607 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08005608 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08005609 // send level comes from shared memory and so may be corrupt
5610 if (sendLevel > MAX_GAIN_INT) {
5611 ALOGV("Track send level out of range: %04X", sendLevel);
5612 sendLevel = MAX_GAIN_INT;
5613 }
Andy Hung6be49402014-05-30 10:42:03 -07005614 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
5615 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08005616 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005617
Kevin Rocard12381092018-04-11 09:19:59 -07005618 track->setFinalVolume((vrf + vlf) / 2.f);
5619
Eric Laurent81784c32012-11-19 14:55:58 -08005620 // Delegate volume control to effect in track effect chain if needed
5621 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
5622 // Do not ramp volume if volume is controlled by effect
5623 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08005624 // Update remaining floating point volume levels
5625 vlf = (float)vl / (1 << 24);
5626 vrf = (float)vr / (1 << 24);
Eric Laurent81784c32012-11-19 14:55:58 -08005627 track->mHasVolumeController = true;
5628 } else {
5629 // force no volume ramp when volume controller was just disabled or removed
5630 // from effect chain to avoid volume spike
5631 if (track->mHasVolumeController) {
5632 param = AudioMixer::VOLUME;
5633 }
5634 track->mHasVolumeController = false;
5635 }
5636
Eric Laurent81784c32012-11-19 14:55:58 -08005637 // XXX: these things DON'T need to be done each time
Andy Hungc0691382018-09-12 18:01:57 -07005638 mAudioMixer->setBufferProvider(trackId, track);
5639 mAudioMixer->enable(trackId);
Eric Laurent81784c32012-11-19 14:55:58 -08005640
Andy Hungc0691382018-09-12 18:01:57 -07005641 mAudioMixer->setParameter(trackId, param, AudioMixer::VOLUME0, &vlf);
5642 mAudioMixer->setParameter(trackId, param, AudioMixer::VOLUME1, &vrf);
5643 mAudioMixer->setParameter(trackId, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08005644 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005645 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005646 AudioMixer::TRACK,
5647 AudioMixer::FORMAT, (void *)track->format());
5648 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005649 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005650 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00005651 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Eric Laurent39095982021-08-24 18:29:27 +02005652
Eric Laurentb0a7bc92022-04-05 15:06:08 +02005653 if (mType == SPATIALIZER && !track->isSpatialized()) {
Eric Laurent39095982021-08-24 18:29:27 +02005654 mAudioMixer->setParameter(
5655 trackId,
5656 AudioMixer::TRACK,
5657 AudioMixer::MIXER_CHANNEL_MASK,
5658 (void *)(uintptr_t)(mChannelMask | mHapticChannelMask));
5659 } else {
5660 mAudioMixer->setParameter(
5661 trackId,
5662 AudioMixer::TRACK,
5663 AudioMixer::MIXER_CHANNEL_MASK,
5664 (void *)(uintptr_t)(mMixerChannelMask | mHapticChannelMask));
5665 }
5666
Glenn Kastene3aa6592012-12-04 12:22:46 -08005667 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07005668 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Andy Hung333ab962019-05-28 20:23:35 -07005669 uint32_t reqSampleRate = proxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08005670 if (reqSampleRate == 0) {
5671 reqSampleRate = mSampleRate;
5672 } else if (reqSampleRate > maxSampleRate) {
5673 reqSampleRate = maxSampleRate;
5674 }
Eric Laurent81784c32012-11-19 14:55:58 -08005675 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005676 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005677 AudioMixer::RESAMPLE,
5678 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00005679 (void *)(uintptr_t)reqSampleRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005680
Andy Hung333ab962019-05-28 20:23:35 -07005681 AudioPlaybackRate playbackRate = proxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07005682 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005683 trackId,
Andy Hung8edb8dc2015-03-26 19:13:55 -07005684 AudioMixer::TIMESTRETCH,
5685 AudioMixer::PLAYBACK_RATE,
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07005686 &playbackRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005687
Andy Hung69aed5f2014-02-25 17:24:40 -08005688 /*
5689 * Select the appropriate output buffer for the track.
5690 *
Andy Hung98ef9782014-03-04 14:46:50 -08005691 * Tracks with effects go into their own effects chain buffer
5692 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08005693 *
5694 * Other tracks can use mMixerBuffer for higher precision
5695 * channel accumulation. If this buffer is enabled
5696 * (mMixerBufferEnabled true), then selected tracks will accumulate
5697 * into it.
5698 *
5699 */
5700 if (mMixerBufferEnabled
5701 && (track->mainBuffer() == mSinkBuffer
5702 || track->mainBuffer() == mMixerBuffer)) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02005703 if (mType == SPATIALIZER && !track->isSpatialized()) {
Eric Laurent39095982021-08-24 18:29:27 +02005704 mAudioMixer->setParameter(
5705 trackId,
5706 AudioMixer::TRACK,
Eric Laurentb62d0362021-10-26 17:40:18 +02005707 AudioMixer::MIXER_FORMAT, (void *)mEffectBufferFormat);
Eric Laurent39095982021-08-24 18:29:27 +02005708 mAudioMixer->setParameter(
5709 trackId,
5710 AudioMixer::TRACK,
Eric Laurentb62d0362021-10-26 17:40:18 +02005711 AudioMixer::MAIN_BUFFER, (void *)mPostSpatializerBuffer);
Eric Laurent39095982021-08-24 18:29:27 +02005712 } else {
5713 mAudioMixer->setParameter(
5714 trackId,
5715 AudioMixer::TRACK,
5716 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
5717 mAudioMixer->setParameter(
5718 trackId,
5719 AudioMixer::TRACK,
5720 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
5721 // TODO: override track->mainBuffer()?
5722 mMixerBufferValid = true;
5723 }
Andy Hung69aed5f2014-02-25 17:24:40 -08005724 } else {
5725 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005726 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08005727 AudioMixer::TRACK,
rago94a1ee82017-07-21 15:11:02 -07005728 AudioMixer::MIXER_FORMAT, (void *)EFFECT_BUFFER_FORMAT);
Andy Hung69aed5f2014-02-25 17:24:40 -08005729 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005730 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08005731 AudioMixer::TRACK,
5732 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
5733 }
Eric Laurent81784c32012-11-19 14:55:58 -08005734 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005735 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005736 AudioMixer::TRACK,
5737 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
jiabin245cdd92018-12-07 17:55:15 -08005738 mAudioMixer->setParameter(
5739 trackId,
5740 AudioMixer::TRACK,
5741 AudioMixer::HAPTIC_ENABLED, (void *)(uintptr_t)track->getHapticPlaybackEnabled());
jiabin77270b82018-12-18 15:41:29 -08005742 mAudioMixer->setParameter(
5743 trackId,
5744 AudioMixer::TRACK,
5745 AudioMixer::HAPTIC_INTENSITY, (void *)(uintptr_t)track->getHapticIntensity());
Lais Andradebc3f37a2021-07-02 00:13:19 +01005746 mAudioMixer->setParameter(
5747 trackId,
5748 AudioMixer::TRACK,
5749 AudioMixer::HAPTIC_MAX_AMPLITUDE, (void *)(&(track->mHapticMaxAmplitude)));
Eric Laurent81784c32012-11-19 14:55:58 -08005750
5751 // reset retry count
5752 track->mRetryCount = kMaxTrackRetries;
5753
5754 // If one track is ready, set the mixer ready if:
5755 // - the mixer was not ready during previous round OR
5756 // - no other track is not ready
5757 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
5758 mixerStatus != MIXER_TRACKS_ENABLED) {
5759 mixerStatus = MIXER_TRACKS_READY;
5760 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08005761
5762 // Enable the next few lines to instrument a test for underrun log handling.
5763 // TODO: Remove when we have a better way of testing the underrun log.
5764#if 0
5765 static int i;
5766 if ((++i & 0xf) == 0) {
5767 deferredOperations.tallyUnderrunFrames(track, 10 /* underrunFrames */);
5768 }
5769#endif
Eric Laurent81784c32012-11-19 14:55:58 -08005770 } else {
Andy Hungbd3b2b02018-05-21 10:53:11 -07005771 size_t underrunFrames = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005772 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Andy Hungb68f5eb2019-12-03 16:49:17 -08005773 ALOGV("track(%d) underrun, track state %s framesReady(%zu) < framesDesired(%zd)",
5774 trackId, track->getTrackStateAsString(), framesReady, desiredFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07005775 underrunFrames = desiredFrames;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005776 }
Andy Hungbd3b2b02018-05-21 10:53:11 -07005777 deferredOperations.tallyUnderrunFrames(track, underrunFrames);
Phil Burk2812d9e2016-01-04 10:34:30 -08005778
Eric Laurent81784c32012-11-19 14:55:58 -08005779 // clear effect chain input buffer if an active track underruns to avoid sending
5780 // previous audio buffer again to effects
5781 chain = getEffectChain_l(track->sessionId());
5782 if (chain != 0) {
5783 chain->clearInputBuffer();
5784 }
5785
Andy Hungc0691382018-09-12 18:01:57 -07005786 ALOGVV("track(%d) s=%08x [NOT READY] on thread %p", trackId, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08005787 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
5788 track->isStopped() || track->isPaused()) {
5789 // We have consumed all the buffers of this track.
5790 // Remove it from the list of active tracks.
5791 // TODO: use actual buffer filling status instead of latency when available from
5792 // audio HAL
5793 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08005794 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005795 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
5796 if (track->isStopped()) {
5797 track->reset();
5798 }
5799 tracksToRemove->add(track);
5800 }
5801 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08005802 // No buffers for this track. Give it a few chances to
5803 // fill a buffer, then remove it from active list.
5804 if (--(track->mRetryCount) <= 0) {
Andy Hungc0691382018-09-12 18:01:57 -07005805 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p",
5806 trackId, this);
Eric Laurent81784c32012-11-19 14:55:58 -08005807 tracksToRemove->add(track);
5808 // indicate to client process that the track was disabled because of underrun;
5809 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08005810 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08005811 // If one track is not ready, mark the mixer also not ready if:
5812 // - the mixer was ready during previous round OR
5813 // - no other track is ready
5814 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
5815 mixerStatus != MIXER_TRACKS_READY) {
5816 mixerStatus = MIXER_TRACKS_ENABLED;
5817 }
5818 }
Andy Hungc0691382018-09-12 18:01:57 -07005819 mAudioMixer->disable(trackId);
Eric Laurent81784c32012-11-19 14:55:58 -08005820 }
5821
5822 } // local variable scope to avoid goto warning
Eric Laurent81784c32012-11-19 14:55:58 -08005823
5824 }
5825
jiabin245cdd92018-12-07 17:55:15 -08005826 if (mHapticChannelMask != AUDIO_CHANNEL_NONE && sq != NULL) {
5827 // When there is no fast track playing haptic and FastMixer exists,
5828 // enabling the first FastTrack, which provides mixed data from normal
5829 // tracks, to play haptic data.
5830 FastTrack *fastTrack = &state->mFastTracks[0];
5831 if (fastTrack->mHapticPlaybackEnabled != noFastHapticTrack) {
5832 fastTrack->mHapticPlaybackEnabled = noFastHapticTrack;
5833 didModify = true;
5834 }
5835 }
5836
Eric Laurent81784c32012-11-19 14:55:58 -08005837 // Push the new FastMixer state if necessary
5838 bool pauseAudioWatchdog = false;
5839 if (didModify) {
5840 state->mFastTracksGen++;
5841 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
5842 if (kUseFastMixer == FastMixer_Dynamic &&
5843 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
5844 state->mCommand = FastMixerState::COLD_IDLE;
5845 state->mColdFutexAddr = &mFastMixerFutex;
5846 state->mColdGen++;
5847 mFastMixerFutex = 0;
5848 if (kUseFastMixer == FastMixer_Dynamic) {
5849 mNormalSink = mOutputSink;
5850 }
5851 // If we go into cold idle, need to wait for acknowledgement
5852 // so that fast mixer stops doing I/O.
5853 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
5854 pauseAudioWatchdog = true;
5855 }
Eric Laurent81784c32012-11-19 14:55:58 -08005856 }
5857 if (sq != NULL) {
5858 sq->end(didModify);
Andy Hungf2285312017-02-14 18:31:59 -08005859 // No need to block if the FastMixer is in COLD_IDLE as the FastThread
5860 // is not active. (We BLOCK_UNTIL_ACKED when entering COLD_IDLE
5861 // when bringing the output sink into standby.)
5862 //
5863 // We will get the latest FastMixer state when we come out of COLD_IDLE.
5864 //
5865 // This occurs with BT suspend when we idle the FastMixer with
5866 // active tracks, which may be added or removed.
5867 sq->push(coldIdle ? FastMixerStateQueue::BLOCK_NEVER : block);
Eric Laurent81784c32012-11-19 14:55:58 -08005868 }
5869#ifdef AUDIO_WATCHDOG
5870 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
5871 mAudioWatchdog->pause();
5872 }
5873#endif
5874
5875 // Now perform the deferred reset on fast tracks that have stopped
5876 while (resetMask != 0) {
5877 size_t i = __builtin_ctz(resetMask);
5878 ALOG_ASSERT(i < count);
5879 resetMask &= ~(1 << i);
Andy Hungdae27702016-10-31 14:01:16 -07005880 sp<Track> track = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08005881 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
5882 track->reset();
5883 }
5884
Andy Hung80d03d22018-04-10 10:32:11 -07005885 // Track destruction may occur outside of threadLoop once it is removed from active tracks.
5886 // Ensure the AudioMixer doesn't have a raw "buffer provider" pointer to the track if
5887 // it ceases to be active, to allow safe removal from the AudioMixer at the start
5888 // of prepareTracks_l(); this releases any outstanding buffer back to the track.
5889 // See also the implementation of destroyTrack_l().
5890 for (const auto &track : *tracksToRemove) {
Andy Hungc0691382018-09-12 18:01:57 -07005891 const int trackId = track->id();
5892 if (mAudioMixer->exists(trackId)) { // Normal tracks here, fast tracks in FastMixer.
5893 mAudioMixer->setBufferProvider(trackId, nullptr /* bufferProvider */);
Andy Hung80d03d22018-04-10 10:32:11 -07005894 }
5895 }
5896
Eric Laurent81784c32012-11-19 14:55:58 -08005897 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08005898 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08005899
Eric Laurentb3f315a2021-07-13 15:09:05 +02005900 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0 ||
5901 getEffectChain_l(AUDIO_SESSION_OUTPUT_STAGE) != 0) {
Eric Laurent97d547d2014-09-02 14:45:53 -07005902 mEffectBufferValid = true;
Marco Nelissenac302142014-10-20 13:15:38 -07005903 }
5904
5905 if (mEffectBufferValid) {
Marco Nelissen57088b52014-10-17 16:39:39 -07005906 // as long as there are effects we should clear the effects buffer, to avoid
5907 // passing a non-clean buffer to the effect chain
5908 memset(mEffectBuffer, 0, mEffectBufferSize);
Eric Laurentb62d0362021-10-26 17:40:18 +02005909 if (mType == SPATIALIZER) {
5910 memset(mPostSpatializerBuffer, 0, mPostSpatializerBufferSize);
5911 }
Eric Laurent97d547d2014-09-02 14:45:53 -07005912 }
Andy Hung69aed5f2014-02-25 17:24:40 -08005913 // sink or mix buffer must be cleared if all tracks are connected to an
5914 // effect chain as in this case the mixer will not write to the sink or mix buffer
5915 // and track effects will accumulate into it
Eric Laurent39095982021-08-24 18:29:27 +02005916 // always clear sink buffer for spatializer output as the output of the spatializer
5917 // effect will be accumulated into it
5918 if ((mBytesRemaining == 0) && (((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
5919 (mixedTracks == 0 && fastTracks > 0)) || (mType == SPATIALIZER))) {
Eric Laurent81784c32012-11-19 14:55:58 -08005920 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08005921 if (mMixerBufferValid) {
5922 memset(mMixerBuffer, 0, mMixerBufferSize);
5923 // TODO: In testing, mSinkBuffer below need not be cleared because
5924 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
5925 // after mixing.
5926 //
5927 // To enforce this guarantee:
5928 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
5929 // (mixedTracks == 0 && fastTracks > 0))
5930 // must imply MIXER_TRACKS_READY.
5931 // Later, we may clear buffers regardless, and skip much of this logic.
5932 }
Andy Hung98ef9782014-03-04 14:46:50 -08005933 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07005934 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08005935 }
5936
5937 // if any fast tracks, then status is ready
5938 mMixerStatusIgnoringFastTracks = mixerStatus;
5939 if (fastTracks > 0) {
5940 mixerStatus = MIXER_TRACKS_READY;
5941 }
5942 return mixerStatus;
5943}
5944
Eric Laurentad7dd962016-09-22 12:38:37 -07005945// trackCountForUid_l() must be called with ThreadBase::mLock held
Andy Hung1bc088a2018-02-09 15:57:31 -08005946uint32_t AudioFlinger::PlaybackThread::trackCountForUid_l(uid_t uid) const
Eric Laurentad7dd962016-09-22 12:38:37 -07005947{
5948 uint32_t trackCount = 0;
5949 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hung1f12a8a2016-11-07 16:10:30 -08005950 if (mTracks[i]->uid() == uid) {
Eric Laurentad7dd962016-09-22 12:38:37 -07005951 trackCount++;
5952 }
5953 }
5954 return trackCount;
5955}
5956
Brian Lindahl65e90012022-07-27 18:01:07 +02005957bool AudioFlinger::PlaybackThread::IsTimestampAdvancing::check(AudioStreamOut * output)
ziyangch8f194f12021-12-01 13:48:04 -08005958{
Brian Lindahl65e90012022-07-27 18:01:07 +02005959 // Check the timestamp to see if it's advancing once every 150ms. If we check too frequently, we
5960 // could falsely detect that the frame position has stalled due to underrun because we haven't
5961 // given the Audio HAL enough time to update.
5962 const nsecs_t nowNs = systemTime();
5963 if (nowNs - mPreviousNs < mMinimumTimeBetweenChecksNs) {
5964 return mLatchedValue;
5965 }
5966 mPreviousNs = nowNs;
5967 mLatchedValue = false;
5968 // Determine if the presentation position is still advancing.
ziyangch8f194f12021-12-01 13:48:04 -08005969 uint64_t position = 0;
5970 struct timespec unused;
Brian Lindahl65e90012022-07-27 18:01:07 +02005971 const status_t ret = output->getPresentationPosition(&position, &unused);
ziyangch8f194f12021-12-01 13:48:04 -08005972 if (ret == NO_ERROR) {
Brian Lindahl65e90012022-07-27 18:01:07 +02005973 if (position != mPreviousPosition) {
5974 mPreviousPosition = position;
5975 mLatchedValue = true;
ziyangch8f194f12021-12-01 13:48:04 -08005976 }
5977 }
Brian Lindahl65e90012022-07-27 18:01:07 +02005978 return mLatchedValue;
5979}
5980
5981void AudioFlinger::PlaybackThread::IsTimestampAdvancing::clear()
5982{
5983 mLatchedValue = true;
5984 mPreviousPosition = 0;
5985 mPreviousNs = 0;
ziyangch8f194f12021-12-01 13:48:04 -08005986}
5987
Andy Hung1bc088a2018-02-09 15:57:31 -08005988// isTrackAllowed_l() must be called with ThreadBase::mLock held
5989bool AudioFlinger::MixerThread::isTrackAllowed_l(
5990 audio_channel_mask_t channelMask, audio_format_t format,
5991 audio_session_t sessionId, uid_t uid) const
Eric Laurent81784c32012-11-19 14:55:58 -08005992{
Andy Hung1bc088a2018-02-09 15:57:31 -08005993 if (!PlaybackThread::isTrackAllowed_l(channelMask, format, sessionId, uid)) {
5994 return false;
Eric Laurentad7dd962016-09-22 12:38:37 -07005995 }
Andy Hung1bc088a2018-02-09 15:57:31 -08005996 // Check validity as we don't call AudioMixer::create() here.
Mikhail Naganov7ad7a252019-07-30 14:42:32 -07005997 if (!mAudioMixer->isValidFormat(format)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08005998 ALOGW("%s: invalid format: %#x", __func__, format);
5999 return false;
6000 }
Mikhail Naganov7ad7a252019-07-30 14:42:32 -07006001 if (!mAudioMixer->isValidChannelMask(channelMask)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08006002 ALOGW("%s: invalid channelMask: %#x", __func__, channelMask);
6003 return false;
6004 }
6005 return true;
Eric Laurent81784c32012-11-19 14:55:58 -08006006}
6007
Eric Laurent10351942014-05-08 18:49:52 -07006008// checkForNewParameter_l() must be called with ThreadBase::mLock held
6009bool AudioFlinger::MixerThread::checkForNewParameter_l(const String8& keyValuePair,
6010 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08006011{
Eric Laurent81784c32012-11-19 14:55:58 -08006012 bool reconfig = false;
Eric Laurent10351942014-05-08 18:49:52 -07006013 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006014
Glenn Kastenc05b8d72016-03-24 09:48:17 -07006015 AutoPark<FastMixer> park(mFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08006016
Eric Laurent10351942014-05-08 18:49:52 -07006017 AudioParameter param = AudioParameter(keyValuePair);
6018 int value;
6019 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
6020 reconfig = true;
6021 }
6022 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07006023 if (!isValidPcmSinkFormat((audio_format_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
Eric Laurent81784c32012-11-19 14:55:58 -08006027 reconfig = true;
6028 }
Eric Laurent10351942014-05-08 18:49:52 -07006029 }
6030 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07006031 if (!isValidPcmSinkChannelMask((audio_channel_mask_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07006032 status = BAD_VALUE;
6033 } else {
6034 // no need to save value, since it's constant
6035 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006036 }
Eric Laurent10351942014-05-08 18:49:52 -07006037 }
6038 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6039 // do not accept frame count changes if tracks are open as the track buffer
6040 // size depends on frame count and correct behavior would not be guaranteed
6041 // if frame count is changed after track creation
6042 if (!mTracks.isEmpty()) {
6043 status = INVALID_OPERATION;
6044 } else {
6045 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006046 }
Eric Laurent10351942014-05-08 18:49:52 -07006047 }
6048 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07006049 LOG_FATAL("Should not set routing device in MixerThread");
Eric Laurent10351942014-05-08 18:49:52 -07006050 }
Eric Laurent81784c32012-11-19 14:55:58 -08006051
Eric Laurent10351942014-05-08 18:49:52 -07006052 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006053 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07006054 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08006055 mOutput->standby();
Andy Hungcf10d742020-04-28 15:38:24 -07006056 if (!mStandby) {
6057 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07006058 mThreadSnapshot.onEnd();
Andy Hungcf10d742020-04-28 15:38:24 -07006059 mStandby = true;
6060 }
Eric Laurent10351942014-05-08 18:49:52 -07006061 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006062 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent81784c32012-11-19 14:55:58 -08006063 }
Eric Laurent10351942014-05-08 18:49:52 -07006064 if (status == NO_ERROR && reconfig) {
6065 readOutputParameters_l();
6066 delete mAudioMixer;
6067 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
Andy Hung1bc088a2018-02-09 15:57:31 -08006068 for (const auto &track : mTracks) {
Andy Hungc0691382018-09-12 18:01:57 -07006069 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08006070 status_t status = mAudioMixer->create(
Andy Hungc0691382018-09-12 18:01:57 -07006071 trackId,
Andy Hung1bc088a2018-02-09 15:57:31 -08006072 track->mChannelMask,
6073 track->mFormat,
6074 track->mSessionId);
6075 ALOGW_IF(status != NO_ERROR,
Andy Hungc0691382018-09-12 18:01:57 -07006076 "%s(): AudioMixer cannot create track(%d)"
6077 " mask %#x, format %#x, sessionId %d",
Andy Hung1bc088a2018-02-09 15:57:31 -08006078 __func__,
Andy Hungc0691382018-09-12 18:01:57 -07006079 trackId, track->mChannelMask, track->mFormat, track->mSessionId);
Eric Laurent10351942014-05-08 18:49:52 -07006080 }
Eric Laurent73e26b62015-04-27 16:55:58 -07006081 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07006082 }
Eric Laurent81784c32012-11-19 14:55:58 -08006083 }
6084
Dean Wheatley68918102021-03-19 22:09:19 +11006085 return reconfig;
Eric Laurent81784c32012-11-19 14:55:58 -08006086}
6087
6088
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07006089void AudioFlinger::MixerThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -08006090{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07006091 PlaybackThread::dumpInternals_l(fd, args);
Andy Hung40eb1a12015-06-18 13:42:02 -07006092 dprintf(fd, " Thread throttle time (msecs): %u\n", mThreadThrottleTimeMs);
Andy Hung8ed196a2018-01-05 13:21:11 -08006093 dprintf(fd, " AudioMixer tracks: %s\n", mAudioMixer->trackNames().c_str());
Andy Hung2ddee192015-12-18 17:34:44 -08006094 dprintf(fd, " Master mono: %s\n", mMasterMono ? "on" : "off");
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006095 dprintf(fd, " Master balance: %f (%s)\n", mMasterBalance.load(),
6096 (hasFastMixer() ? std::to_string(mFastMixer->getMasterBalance())
6097 : mBalance.toString()).c_str());
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006098 if (hasFastMixer()) {
6099 dprintf(fd, " FastMixer thread %p tid=%d", mFastMixer.get(), mFastMixer->getTid());
6100
6101 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
6102 // while we are dumping it. It may be inconsistent, but it won't mutate!
6103 // This is a large object so we place it on the heap.
6104 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
Eric Tan2942a4e2018-09-12 17:41:27 -07006105 const std::unique_ptr<FastMixerDumpState> copy =
6106 std::make_unique<FastMixerDumpState>(mFastMixerDumpState);
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006107 copy->dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08006108
6109#ifdef STATE_QUEUE_DUMP
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006110 // Similar for state queue
6111 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
6112 observerCopy.dump(fd);
6113 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
6114 mutatorCopy.dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08006115#endif
6116
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006117#ifdef AUDIO_WATCHDOG
6118 if (mAudioWatchdog != 0) {
6119 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
6120 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
6121 wdCopy.dump(fd);
6122 }
6123#endif
6124
6125 } else {
6126 dprintf(fd, " No FastMixer\n");
6127 }
Eric Laurent81784c32012-11-19 14:55:58 -08006128}
6129
6130uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
6131{
6132 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
6133}
6134
6135uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
6136{
6137 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
6138}
6139
6140void AudioFlinger::MixerThread::cacheParameters_l()
6141{
6142 PlaybackThread::cacheParameters_l();
6143
6144 // FIXME: Relaxed timing because of a certain device that can't meet latency
6145 // Should be reduced to 2x after the vendor fixes the driver issue
6146 // increase threshold again due to low power audio mode. The way this warning
6147 // threshold is calculated and its usefulness should be reconsidered anyway.
6148 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
6149}
6150
6151// ----------------------------------------------------------------------------
6152
6153AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
Gareth Fennb18c1a32022-10-05 13:42:36 -07006154 AudioStreamOut* output, audio_io_handle_t id, ThreadBase::type_t type, bool systemReady,
6155 const audio_offload_info_t& offloadInfo)
jiabinc52b1ff2019-10-31 17:20:42 -07006156 : PlaybackThread(audioFlinger, output, id, type, systemReady)
Gareth Fennb18c1a32022-10-05 13:42:36 -07006157 , mOffloadInfo(offloadInfo)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006158{
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006159 setMasterBalance(audioFlinger->getMasterBalance_l());
Eric Laurentbfb1b832013-01-07 09:53:42 -08006160}
6161
Eric Laurent81784c32012-11-19 14:55:58 -08006162AudioFlinger::DirectOutputThread::~DirectOutputThread()
6163{
6164}
6165
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07006166void AudioFlinger::DirectOutputThread::dumpInternals_l(int fd, const Vector<String16>& args)
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006167{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07006168 PlaybackThread::dumpInternals_l(fd, args);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006169 dprintf(fd, " Master balance: %f Left: %f Right: %f\n",
6170 mMasterBalance.load(), mMasterBalanceLeft, mMasterBalanceRight);
6171}
6172
6173void AudioFlinger::DirectOutputThread::setMasterBalance(float balance)
6174{
6175 Mutex::Autolock _l(mLock);
6176 if (mMasterBalance != balance) {
6177 mMasterBalance.store(balance);
6178 mBalance.computeStereoBalance(balance, &mMasterBalanceLeft, &mMasterBalanceRight);
6179 broadcast_l();
6180 }
6181}
6182
Eric Laurent5850c4c2016-11-10 13:04:31 -08006183void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006184{
Eric Laurentbfb1b832013-01-07 09:53:42 -08006185 float left, right;
6186
Vlad Popae2f5aef2022-07-25 16:00:20 +02006187
Andy Hung333ab962019-05-28 20:23:35 -07006188 // Ensure volumeshaper state always advances even when muted.
6189 const sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
6190 const auto [shaperVolume, shaperActive] = track->getVolumeHandler()->getVolume(
6191 proxy->framesReleased());
6192 mVolumeShaperActive = shaperActive;
6193
Vlad Popae2f5aef2022-07-25 16:00:20 +02006194 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
6195 left = float_from_gain(gain_minifloat_unpack_left(vlr));
6196 right = float_from_gain(gain_minifloat_unpack_right(vlr));
6197
6198 const bool clientVolumeMute = (left == 0.f && right == 0.f);
6199
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08006200 if (mMasterMute || mStreamTypes[track->streamType()].mute || track->isPlaybackRestricted()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08006201 left = right = 0;
6202 } else {
6203 float typeVolume = mStreamTypes[track->streamType()].volume;
Andy Hung333ab962019-05-28 20:23:35 -07006204 const float v = mMasterVolume * typeVolume * shaperVolume;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08006205
Glenn Kastenc56f3422014-03-21 17:53:17 -07006206 if (left > GAIN_FLOAT_UNITY) {
6207 left = GAIN_FLOAT_UNITY;
6208 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07006209 if (right > GAIN_FLOAT_UNITY) {
6210 right = GAIN_FLOAT_UNITY;
6211 }
Vlad Popae2f5aef2022-07-25 16:00:20 +02006212
6213 left *= v * mMasterBalanceLeft; // DirectOutputThread balance applied as track volume
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006214 right *= v * mMasterBalanceRight;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006215 }
6216
Vlad Popae8d99472022-06-30 16:02:48 +02006217 track->processMuteEvent_l(mAudioFlinger->getOrCreateAudioManager(),
6218 /*muteState=*/{mMasterMute,
6219 mStreamTypes[track->streamType()].volume == 0.f,
6220 mStreamTypes[track->streamType()].mute,
Vlad Popae2f5aef2022-07-25 16:00:20 +02006221 track->isPlaybackRestricted(),
Vlad Popa436c9172022-08-02 15:25:08 +02006222 clientVolumeMute,
6223 shaperVolume == 0.f});
Vlad Popae8d99472022-06-30 16:02:48 +02006224
Eric Laurentbfb1b832013-01-07 09:53:42 -08006225 if (lastTrack) {
Kevin Rocard12381092018-04-11 09:19:59 -07006226 track->setFinalVolume((left + right) / 2.f);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006227 if (left != mLeftVolFloat || right != mRightVolFloat) {
6228 mLeftVolFloat = left;
6229 mRightVolFloat = right;
6230
Eric Laurentbfb1b832013-01-07 09:53:42 -08006231 // Delegate volume control to effect in track effect chain if needed
6232 // only one effect chain can be present on DirectOutputThread, so if
6233 // there is one, the track is connected to it
6234 if (!mEffectChains.isEmpty()) {
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09006235 // if effect chain exists, volume is handled by it.
6236 // Convert volumes from float to 8.24
6237 uint32_t vl = (uint32_t)(left * (1 << 24));
6238 uint32_t vr = (uint32_t)(right * (1 << 24));
6239 // Direct/Offload effect chains set output volume in setVolume_l().
6240 (void)mEffectChains[0]->setVolume_l(&vl, &vr);
6241 } else {
6242 // otherwise we directly set the volume.
6243 setVolumeForOutput_l(left, right);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006244 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006245 }
6246 }
6247}
6248
Phil Burk43b4dcc2015-06-09 16:53:44 -07006249void AudioFlinger::DirectOutputThread::onAddNewTrack_l()
6250{
6251 sp<Track> previousTrack = mPreviousTrack.promote();
Andy Hungdae27702016-10-31 14:01:16 -07006252 sp<Track> latestTrack = mActiveTracks.getLatest();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006253
Eric Laurent0f0631e2015-07-06 18:01:25 -07006254 if (previousTrack != 0 && latestTrack != 0) {
6255 if (mType == DIRECT) {
6256 if (previousTrack.get() != latestTrack.get()) {
6257 mFlushPending = true;
6258 }
6259 } else /* mType == OFFLOAD */ {
6260 if (previousTrack->sessionId() != latestTrack->sessionId()) {
6261 mFlushPending = true;
6262 }
6263 }
Revathi Uddaraju20413a92016-10-13 17:16:14 +08006264 } else if (previousTrack == 0) {
6265 // there could be an old track added back during track transition for direct
6266 // output, so always issues flush to flush data of the previous track if it
6267 // was already destroyed with HAL paused, then flush can resume the playback
6268 mFlushPending = true;
Phil Burk43b4dcc2015-06-09 16:53:44 -07006269 }
6270 PlaybackThread::onAddNewTrack_l();
6271}
Eric Laurentbfb1b832013-01-07 09:53:42 -08006272
Eric Laurent81784c32012-11-19 14:55:58 -08006273AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
6274 Vector< sp<Track> > *tracksToRemove
6275)
6276{
Eric Laurentd595b7c2013-04-03 17:27:56 -07006277 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08006278 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006279 bool doHwPause = false;
6280 bool doHwResume = false;
Eric Laurent81784c32012-11-19 14:55:58 -08006281
6282 // find out which tracks need to be processed
Andy Hungdae27702016-10-31 14:01:16 -07006283 for (const sp<Track> &t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08006284 if (t->isInvalid()) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07006285 ALOGW("An invalidated track shouldn't be in active list");
Eric Laurent5850c4c2016-11-10 13:04:31 -08006286 tracksToRemove->add(t);
Phil Burk43b4dcc2015-06-09 16:53:44 -07006287 continue;
6288 }
6289
Eric Laurent5850c4c2016-11-10 13:04:31 -08006290 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006291#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurent81784c32012-11-19 14:55:58 -08006292 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006293#endif
Eric Laurentfd477972013-10-25 18:10:40 -07006294 // Only consider last track started for volume and mixer state control.
6295 // In theory an older track could underrun and restart after the new one starts
6296 // but as we only care about the transition phase between two tracks on a
6297 // direct output, it is not a problem to ignore the underrun case.
Andy Hungdae27702016-10-31 14:01:16 -07006298 sp<Track> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08006299 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08006300
Kuowei Li23666472021-01-20 10:23:25 +08006301 if (track->isPausePending()) {
6302 track->pauseAck();
6303 // It is possible a track might have been flushed or stopped.
6304 // Other operations such as flush pending might occur on the next prepare.
6305 if (track->isPausing()) {
6306 track->setPaused();
6307 }
6308 // Always perform pause, as an immediate flush will change
6309 // the pause state to be no longer isPausing().
Phil Burk6fc2a7c2015-04-30 16:08:10 -07006310 if (mHwSupportsPause && last && !mHwPaused) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006311 doHwPause = true;
6312 mHwPaused = true;
6313 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08006314 } else if (track->isFlushPending()) {
6315 track->flushAck();
6316 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07006317 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006318 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07006319 } else if (track->isResumePending()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006320 track->resumeAck();
Eric Laurent3df841a2016-07-15 15:15:40 -07006321 if (last) {
6322 mLeftVolFloat = mRightVolFloat = -1.0;
6323 if (mHwPaused) {
6324 doHwResume = true;
6325 mHwPaused = false;
6326 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08006327 }
6328 }
6329
Eric Laurent81784c32012-11-19 14:55:58 -08006330 // The first time a track is added we wait
Phil Burk99adee32014-12-10 16:46:30 -08006331 // for all its buffers to be filled before processing it.
6332 // Allow draining the buffer in case the client
6333 // app does not call stop() and relies on underrun to stop:
6334 // hence the test on (track->mRetryCount > 1).
Andy Hung455982f2021-04-27 17:46:12 -07006335 // If track->mRetryCount <= 1 then track is about to be disabled, paused, removed,
6336 // so we accept any nonzero amount of data delivered by the AudioTrack (which will
6337 // reset the retry counter).
Phil Burkca5e6142015-07-14 09:42:29 -07006338 // Do not use a high threshold for compressed audio.
Andy Hung455982f2021-04-27 17:46:12 -07006339
6340 // target retry count that we will use is based on the time we wait for retries.
6341 const int32_t targetRetryCount = kMaxTrackRetriesDirectMs * 1000 / mActiveSleepTimeUs;
6342 // the retry threshold is when we accept any size for PCM data. This is slightly
6343 // smaller than the retry count so we can push small bits of data without a glitch.
6344 const int32_t retryThreshold = targetRetryCount > 2 ? targetRetryCount - 1 : 1;
Eric Laurent81784c32012-11-19 14:55:58 -08006345 uint32_t minFrames;
Phil Burk99adee32014-12-10 16:46:30 -08006346 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
Andy Hung455982f2021-04-27 17:46:12 -07006347 && (track->mRetryCount > retryThreshold) && audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006348 minFrames = mNormalFrameCount;
6349 } else {
6350 minFrames = 1;
6351 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006352
Mikhail Naganovddb07bc12019-08-15 20:18:47 -07006353 const size_t framesReady = track->framesReady();
6354 const int trackId = track->id();
6355 if (ATRACE_ENABLED()) {
6356 std::string traceName("nRdy");
6357 traceName += std::to_string(trackId);
6358 ATRACE_INT(traceName.c_str(), framesReady);
6359 }
6360 if ((framesReady >= minFrames) && track->isReady() && !track->isPaused() &&
Eric Laurentab5cdba2014-06-09 17:22:27 -07006361 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08006362 {
Mikhail Naganovddb07bc12019-08-15 20:18:47 -07006363 ALOGVV("track(%d) s=%08x [OK]", trackId, cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08006364
6365 if (track->mFillingUpStatus == Track::FS_FILLED) {
6366 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07006367 if (last) {
6368 // make sure processVolume_l() will apply new volume even if 0
6369 mLeftVolFloat = mRightVolFloat = -1.0;
6370 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08006371 if (!mHwSupportsPause) {
6372 track->resumeAck();
Eric Laurent81784c32012-11-19 14:55:58 -08006373 }
6374 }
6375
6376 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08006377 processVolume_l(track, last);
6378 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07006379 sp<Track> previousTrack = mPreviousTrack.promote();
6380 if (previousTrack != 0) {
6381 if (track != previousTrack.get()) {
6382 // Flush any data still being written from last track
6383 mBytesRemaining = 0;
Eric Laurent0f0631e2015-07-06 18:01:25 -07006384 // Invalidate previous track to force a seek when resuming.
6385 previousTrack->invalidate();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006386 }
6387 }
6388 mPreviousTrack = track;
6389
Eric Laurentd595b7c2013-04-03 17:27:56 -07006390 // reset retry count
Andy Hung455982f2021-04-27 17:46:12 -07006391 track->mRetryCount = targetRetryCount;
Eric Laurent5850c4c2016-11-10 13:04:31 -08006392 mActiveTrack = t;
Eric Laurentd595b7c2013-04-03 17:27:56 -07006393 mixerStatus = MIXER_TRACKS_READY;
Eric Laurent5cff4032015-05-26 13:49:58 -07006394 if (mHwPaused) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08006395 doHwResume = true;
6396 mHwPaused = false;
6397 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07006398 }
Eric Laurent81784c32012-11-19 14:55:58 -08006399 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07006400 // clear effect chain input buffer if the last active track started underruns
6401 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07006402 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08006403 mEffectChains[0]->clearInputBuffer();
6404 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07006405 if (track->isStopping_1()) {
6406 track->mState = TrackBase::STOPPING_2;
Eric Laurentb369caf2015-03-30 20:51:47 -07006407 if (last && mHwPaused) {
6408 doHwResume = true;
6409 mHwPaused = false;
6410 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07006411 }
6412 if ((track->sharedBuffer() != 0) || track->isStopped() ||
6413 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08006414 // We have consumed all the buffers of this track.
6415 // Remove it from the list of active tracks.
Atneya Nair0cae0432022-05-10 18:12:12 -04006416 bool presComplete = false;
Eric Laurentfd477972013-10-25 18:10:40 -07006417 if (mStandby || !last ||
Atneya Nair0cae0432022-05-10 18:12:12 -04006418 (presComplete = track->presentationComplete(latency_l())) ||
Jindong32dc26e2019-11-11 18:10:01 +08006419 track->isPaused() || mHwPaused) {
Atneya Nair0cae0432022-05-10 18:12:12 -04006420 if (presComplete) {
6421 mOutput->presentationComplete();
6422 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07006423 if (track->isStopping_2()) {
6424 track->mState = TrackBase::STOPPED;
6425 }
Eric Laurent81784c32012-11-19 14:55:58 -08006426 if (track->isStopped()) {
6427 track->reset();
6428 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07006429 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08006430 }
6431 } else {
6432 // No buffers for this track. Give it a few chances to
6433 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07006434 // Only consider last track started for mixer state control
Brian Lindahl65e90012022-07-27 18:01:07 +02006435 bool isTimestampAdvancing = mIsTimestampAdvancing.check(mOutput);
Gareth Fennb18c1a32022-10-05 13:42:36 -07006436 if (!isTunerStream() // tuner streams remain active in underrun
6437 && --(track->mRetryCount) <= 0) {
Brian Lindahl65e90012022-07-27 18:01:07 +02006438 if (isTimestampAdvancing) { // HAL is still playing audio, give us more time.
ziyangch8f194f12021-12-01 13:48:04 -08006439 track->mRetryCount = kMaxTrackRetriesOffload;
6440 } else {
6441 ALOGV("BUFFER TIMEOUT: remove track(%d) from active list", trackId);
6442 tracksToRemove->add(track);
6443 // indicate to client process that the track was disabled because of
6444 // underrun; it will then automatically call start() when data is available
6445 track->disable();
6446 // only do hw pause when track is going to be removed due to BUFFER TIMEOUT.
6447 // unlike mixerthread, HAL can be paused for direct output
6448 ALOGW("pause because of UNDERRUN, framesReady = %zu,"
6449 "minFrames = %u, mFormat = %#x",
6450 framesReady, minFrames, mFormat);
6451 if (last && mHwSupportsPause && !mHwPaused && !mStandby) {
6452 doHwPause = true;
6453 mHwPaused = true;
6454 }
Eric Laurent0f7b5f22014-12-19 10:43:21 -08006455 }
Haynes Mathew George5c6daae2017-01-24 20:06:05 -08006456 } else if (last) {
6457 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurent81784c32012-11-19 14:55:58 -08006458 }
6459 }
6460 }
6461 }
6462
Eric Laurentd1f69b02014-12-15 14:33:13 -08006463 // if an active track did not command a flush, check for pending flush on stopped tracks
Phil Burk43b4dcc2015-06-09 16:53:44 -07006464 if (!mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006465 for (size_t i = 0; i < mTracks.size(); i++) {
6466 if (mTracks[i]->isFlushPending()) {
6467 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006468 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006469 }
6470 }
6471 }
6472
6473 // make sure the pause/flush/resume sequence is executed in the right order.
6474 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
6475 // before flush and then resume HW. This can happen in case of pause/flush/resume
6476 // if resume is received before pause is executed.
6477 if (mHwSupportsPause && !mStandby &&
Phil Burk43b4dcc2015-06-09 16:53:44 -07006478 (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006479 status_t result = mOutput->stream->pause();
6480 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Gareth Fenncd1e1622022-10-05 11:45:45 -07006481 doHwResume = !doHwPause; // resume if pause is due to flush.
Eric Laurentd1f69b02014-12-15 14:33:13 -08006482 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07006483 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006484 flushHw_l();
6485 }
6486 if (mHwSupportsPause && !mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006487 status_t result = mOutput->stream->resume();
6488 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08006489 }
Eric Laurent81784c32012-11-19 14:55:58 -08006490 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08006491 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08006492
6493 return mixerStatus;
6494}
6495
6496void AudioFlinger::DirectOutputThread::threadLoop_mix()
6497{
Eric Laurent81784c32012-11-19 14:55:58 -08006498 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08006499 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08006500 // output audio to hardware
6501 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07006502 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08006503 buffer.frameCount = frameCount;
Phil Burk062e67a2015-02-11 13:40:50 -08006504 status_t status = mActiveTrack->getNextBuffer(&buffer);
6505 if (status != NO_ERROR || buffer.raw == NULL) {
Eric Laurent51716182016-02-29 18:00:56 -08006506 // no need to pad with 0 for compressed audio
6507 if (audio_has_proportional_frames(mFormat)) {
6508 memset(curBuf, 0, frameCount * mFrameSize);
6509 }
Eric Laurent81784c32012-11-19 14:55:58 -08006510 break;
6511 }
6512 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
6513 frameCount -= buffer.frameCount;
6514 curBuf += buffer.frameCount * mFrameSize;
6515 mActiveTrack->releaseBuffer(&buffer);
6516 }
Andy Hung2098f272014-02-27 14:00:06 -08006517 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006518 mSleepTimeUs = 0;
6519 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08006520 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08006521}
6522
6523void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
6524{
Eric Laurentd1f69b02014-12-15 14:33:13 -08006525 // do not write to HAL when paused
Eric Laurent0f7b5f22014-12-19 10:43:21 -08006526 if (mHwPaused || (usesHwAvSync() && mStandby)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006527 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006528 return;
6529 }
Andy Hung85ba3332021-04-27 17:40:26 -07006530 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
6531 mSleepTimeUs = mActiveSleepTimeUs;
6532 } else {
6533 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006534 }
Andy Hung85ba3332021-04-27 17:40:26 -07006535 // Note: In S or later, we do not write zeroes for
6536 // linear or proportional PCM direct tracks in underrun.
Eric Laurent81784c32012-11-19 14:55:58 -08006537}
6538
Eric Laurentd1f69b02014-12-15 14:33:13 -08006539void AudioFlinger::DirectOutputThread::threadLoop_exit()
6540{
6541 {
6542 Mutex::Autolock _l(mLock);
Eric Laurentd1f69b02014-12-15 14:33:13 -08006543 for (size_t i = 0; i < mTracks.size(); i++) {
6544 if (mTracks[i]->isFlushPending()) {
6545 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006546 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006547 }
6548 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07006549 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006550 flushHw_l();
6551 }
6552 }
6553 PlaybackThread::threadLoop_exit();
6554}
6555
6556// must be called with thread mutex locked
6557bool AudioFlinger::DirectOutputThread::shouldStandby_l()
6558{
6559 bool trackPaused = false;
Eric Laurentb369caf2015-03-30 20:51:47 -07006560 bool trackStopped = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006561
6562 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
6563 // after a timeout and we will enter standby then.
6564 if (mTracks.size() > 0) {
6565 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
Eric Laurentb369caf2015-03-30 20:51:47 -07006566 trackStopped = mTracks[mTracks.size() - 1]->isStopped() ||
6567 mTracks[mTracks.size() - 1]->mState == TrackBase::IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006568 }
6569
Eric Laurent5cff4032015-05-26 13:49:58 -07006570 return !mStandby && !(trackPaused || (mHwPaused && !trackStopped));
Eric Laurentd1f69b02014-12-15 14:33:13 -08006571}
6572
Eric Laurent10351942014-05-08 18:49:52 -07006573// checkForNewParameter_l() must be called with ThreadBase::mLock held
6574bool AudioFlinger::DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
6575 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08006576{
6577 bool reconfig = false;
Eric Laurent10351942014-05-08 18:49:52 -07006578 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006579
Eric Laurent10351942014-05-08 18:49:52 -07006580 AudioParameter param = AudioParameter(keyValuePair);
6581 int value;
6582 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07006583 LOG_FATAL("Should not set routing device in DirectOutputThread");
Eric Laurent81784c32012-11-19 14:55:58 -08006584 }
Eric Laurent10351942014-05-08 18:49:52 -07006585 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6586 // do not accept frame count changes if tracks are open as the track buffer
6587 // size depends on frame count and correct behavior would not be garantied
6588 // if frame count is changed after track creation
6589 if (!mTracks.isEmpty()) {
6590 status = INVALID_OPERATION;
6591 } else {
6592 reconfig = true;
6593 }
6594 }
6595 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006596 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07006597 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08006598 mOutput->standby();
Andy Hungcf10d742020-04-28 15:38:24 -07006599 if (!mStandby) {
6600 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07006601 mThreadSnapshot.onEnd();
Andy Hungcf10d742020-04-28 15:38:24 -07006602 mStandby = true;
6603 }
Eric Laurent10351942014-05-08 18:49:52 -07006604 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006605 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07006606 }
6607 if (status == NO_ERROR && reconfig) {
6608 readOutputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07006609 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07006610 }
6611 }
6612
Dean Wheatley68918102021-03-19 22:09:19 +11006613 return reconfig;
Eric Laurent81784c32012-11-19 14:55:58 -08006614}
6615
6616uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
6617{
6618 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08006619 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006620 time = PlaybackThread::activeSleepTimeUs();
6621 } else {
Eric Laurent51716182016-02-29 18:00:56 -08006622 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006623 }
6624 return time;
6625}
6626
6627uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
6628{
6629 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08006630 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006631 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
6632 } else {
Eric Laurent51716182016-02-29 18:00:56 -08006633 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006634 }
6635 return time;
6636}
6637
6638uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
6639{
6640 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08006641 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006642 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
6643 } else {
Eric Laurent51716182016-02-29 18:00:56 -08006644 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006645 }
6646 return time;
6647}
6648
6649void AudioFlinger::DirectOutputThread::cacheParameters_l()
6650{
6651 PlaybackThread::cacheParameters_l();
6652
6653 // use shorter standby delay as on normal output to release
6654 // hardware resources as soon as possible
Eric Laurentb369caf2015-03-30 20:51:47 -07006655 // no delay on outputs with HW A/V sync
6656 if (usesHwAvSync()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006657 mStandbyDelayNs = 0;
Phil Burkfdb3c072016-02-09 10:47:02 -08006658 } else if ((mType == OFFLOAD) && !audio_has_proportional_frames(mFormat)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006659 mStandbyDelayNs = kOffloadStandbyDelayNs;
Eric Laurent5cff4032015-05-26 13:49:58 -07006660 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006661 mStandbyDelayNs = microseconds(mActiveSleepTimeUs*2);
Eric Laurent972a1732013-09-04 09:42:59 -07006662 }
Eric Laurent81784c32012-11-19 14:55:58 -08006663}
6664
Eric Laurente659ef42014-09-29 13:06:46 -07006665void AudioFlinger::DirectOutputThread::flushHw_l()
6666{
ziyangch8f194f12021-12-01 13:48:04 -08006667 PlaybackThread::flushHw_l();
Phil Burk062e67a2015-02-11 13:40:50 -08006668 mOutput->flush();
Eric Laurentd1f69b02014-12-15 14:33:13 -08006669 mHwPaused = false;
Phil Burk43b4dcc2015-06-09 16:53:44 -07006670 mFlushPending = false;
Dean Wheatley12473e92021-03-18 23:00:55 +11006671 mTimestampVerifier.discontinuity(discontinuityForStandbyOrFlush());
Sampath Shetty999f0e82020-01-15 10:19:06 +11006672 mTimestamp.clear();
Eric Laurente659ef42014-09-29 13:06:46 -07006673}
6674
Andy Hung10cbff12017-02-21 17:30:14 -08006675int64_t AudioFlinger::DirectOutputThread::computeWaitTimeNs_l() const {
6676 // If a VolumeShaper is active, we must wake up periodically to update volume.
6677 const int64_t NS_PER_MS = 1000000;
6678 return mVolumeShaperActive ?
6679 kMinNormalSinkBufferSizeMs * NS_PER_MS : PlaybackThread::computeWaitTimeNs_l();
6680}
6681
Eric Laurent81784c32012-11-19 14:55:58 -08006682// ----------------------------------------------------------------------------
6683
Eric Laurentbfb1b832013-01-07 09:53:42 -08006684AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
Eric Laurent4de95592013-09-26 15:28:21 -07006685 const wp<AudioFlinger::PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006686 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07006687 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07006688 mWriteAckSequence(0),
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006689 mDrainSequence(0),
6690 mAsyncError(false)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006691{
6692}
6693
6694AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
6695{
6696}
6697
6698void AudioFlinger::AsyncCallbackThread::onFirstRef()
6699{
6700 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
6701}
6702
6703bool AudioFlinger::AsyncCallbackThread::threadLoop()
6704{
6705 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07006706 uint32_t writeAckSequence;
6707 uint32_t drainSequence;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006708 bool asyncError;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006709
6710 {
6711 Mutex::Autolock _l(mLock);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08006712 while (!((mWriteAckSequence & 1) ||
6713 (mDrainSequence & 1) ||
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006714 mAsyncError ||
Haynes Mathew George24a325d2013-12-03 21:26:02 -08006715 exitPending())) {
6716 mWaitWorkCV.wait(mLock);
6717 }
6718
Eric Laurentbfb1b832013-01-07 09:53:42 -08006719 if (exitPending()) {
6720 break;
6721 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07006722 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
6723 mWriteAckSequence, mDrainSequence);
6724 writeAckSequence = mWriteAckSequence;
6725 mWriteAckSequence &= ~1;
6726 drainSequence = mDrainSequence;
6727 mDrainSequence &= ~1;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006728 asyncError = mAsyncError;
6729 mAsyncError = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006730 }
6731 {
Eric Laurent4de95592013-09-26 15:28:21 -07006732 sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
6733 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07006734 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07006735 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006736 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07006737 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07006738 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006739 }
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006740 if (asyncError) {
6741 playbackThread->onAsyncError();
6742 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006743 }
6744 }
6745 }
6746 return false;
6747}
6748
6749void AudioFlinger::AsyncCallbackThread::exit()
6750{
6751 ALOGV("AsyncCallbackThread::exit");
6752 Mutex::Autolock _l(mLock);
6753 requestExit();
6754 mWaitWorkCV.broadcast();
6755}
6756
Eric Laurent3b4529e2013-09-05 18:09:19 -07006757void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006758{
6759 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07006760 // bit 0 is cleared
6761 mWriteAckSequence = sequence << 1;
6762}
6763
6764void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
6765{
6766 Mutex::Autolock _l(mLock);
6767 // ignore unexpected callbacks
6768 if (mWriteAckSequence & 2) {
6769 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006770 mWaitWorkCV.signal();
6771 }
6772}
6773
Eric Laurent3b4529e2013-09-05 18:09:19 -07006774void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006775{
6776 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07006777 // bit 0 is cleared
6778 mDrainSequence = sequence << 1;
6779}
6780
6781void AudioFlinger::AsyncCallbackThread::resetDraining()
6782{
6783 Mutex::Autolock _l(mLock);
6784 // ignore unexpected callbacks
6785 if (mDrainSequence & 2) {
6786 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006787 mWaitWorkCV.signal();
6788 }
6789}
6790
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006791void AudioFlinger::AsyncCallbackThread::setAsyncError()
6792{
6793 Mutex::Autolock _l(mLock);
6794 mAsyncError = true;
6795 mWaitWorkCV.signal();
6796}
6797
Eric Laurentbfb1b832013-01-07 09:53:42 -08006798
6799// ----------------------------------------------------------------------------
6800AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
Gareth Fennb18c1a32022-10-05 13:42:36 -07006801 AudioStreamOut* output, audio_io_handle_t id, bool systemReady,
6802 const audio_offload_info_t& offloadInfo)
6803 : DirectOutputThread(audioFlinger, output, id, OFFLOAD, systemReady, offloadInfo),
ziyangch8f194f12021-12-01 13:48:04 -08006804 mPausedWriteLength(0), mPausedBytesRemaining(0), mKeepWakeLock(true)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006805{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07006806 //FIXME: mStandby should be set to true by ThreadBase constructo
Eric Laurentfd477972013-10-25 18:10:40 -07006807 mStandby = true;
Eric Laurent64667972016-03-30 18:19:46 -07006808 mKeepWakeLock = property_get_bool("ro.audio.offload_wakelock", true /* default_value */);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006809}
6810
Eric Laurentbfb1b832013-01-07 09:53:42 -08006811void AudioFlinger::OffloadThread::threadLoop_exit()
6812{
6813 if (mFlushPending || mHwPaused) {
6814 // If a flush is pending or track was paused, just discard buffered data
6815 flushHw_l();
6816 } else {
6817 mMixerStatus = MIXER_DRAIN_ALL;
6818 threadLoop_drain();
6819 }
Uday Gupta56604aa2014-05-13 11:19:17 -07006820 if (mUseAsyncWrite) {
6821 ALOG_ASSERT(mCallbackThread != 0);
6822 mCallbackThread->exit();
6823 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006824 PlaybackThread::threadLoop_exit();
6825}
6826
6827AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
6828 Vector< sp<Track> > *tracksToRemove
6829)
6830{
Eric Laurentbfb1b832013-01-07 09:53:42 -08006831 size_t count = mActiveTracks.size();
6832
6833 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07006834 bool doHwPause = false;
6835 bool doHwResume = false;
6836
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006837 ALOGV("OffloadThread::prepareTracks_l active tracks %zu", count);
Eric Laurentede6c3b2013-09-19 14:37:46 -07006838
Eric Laurentbfb1b832013-01-07 09:53:42 -08006839 // find out which tracks need to be processed
Andy Hungdae27702016-10-31 14:01:16 -07006840 for (const sp<Track> &t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08006841 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006842#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurentbfb1b832013-01-07 09:53:42 -08006843 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006844#endif
Eric Laurentfd477972013-10-25 18:10:40 -07006845 // Only consider last track started for volume and mixer state control.
6846 // In theory an older track could underrun and restart after the new one starts
6847 // but as we only care about the transition phase between two tracks on a
6848 // direct output, it is not a problem to ignore the underrun case.
Andy Hungdae27702016-10-31 14:01:16 -07006849 sp<Track> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08006850 bool last = l.get() == track;
Eric Laurentfd477972013-10-25 18:10:40 -07006851
Haynes Mathew George7844f672014-01-15 12:32:55 -08006852 if (track->isInvalid()) {
6853 ALOGW("An invalidated track shouldn't be in active list");
6854 tracksToRemove->add(track);
6855 continue;
6856 }
6857
6858 if (track->mState == TrackBase::IDLE) {
6859 ALOGW("An idle track shouldn't be in active list");
6860 continue;
6861 }
6862
Kuowei Li23666472021-01-20 10:23:25 +08006863 if (track->isPausePending()) {
6864 track->pauseAck();
6865 // It is possible a track might have been flushed or stopped.
6866 // Other operations such as flush pending might occur on the next prepare.
6867 if (track->isPausing()) {
6868 track->setPaused();
6869 }
6870 // Always perform pause if last, as an immediate flush will change
6871 // the pause state to be no longer isPausing().
Eric Laurentbfb1b832013-01-07 09:53:42 -08006872 if (last) {
Eric Laurent5cff4032015-05-26 13:49:58 -07006873 if (mHwSupportsPause && !mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07006874 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006875 mHwPaused = true;
6876 }
6877 // If we were part way through writing the mixbuffer to
6878 // the HAL we must save this until we resume
6879 // BUG - this will be wrong if a different track is made active,
6880 // in that case we want to discard the pending data in the
6881 // mixbuffer and tell the client to present it again when the
6882 // track is resumed
6883 mPausedWriteLength = mCurrentWriteLength;
6884 mPausedBytesRemaining = mBytesRemaining;
6885 mBytesRemaining = 0; // stop writing
6886 }
6887 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08006888 } else if (track->isFlushPending()) {
Eric Laurente93cc032016-05-05 10:15:10 -07006889 if (track->isStopping_1()) {
6890 track->mRetryCount = kMaxTrackStopRetriesOffload;
6891 } else {
6892 track->mRetryCount = kMaxTrackRetriesOffload;
6893 }
Haynes Mathew George7844f672014-01-15 12:32:55 -08006894 track->flushAck();
6895 if (last) {
6896 mFlushPending = true;
6897 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08006898 } else if (track->isResumePending()){
6899 track->resumeAck();
6900 if (last) {
6901 if (mPausedBytesRemaining) {
6902 // Need to continue write that was interrupted
6903 mCurrentWriteLength = mPausedWriteLength;
6904 mBytesRemaining = mPausedBytesRemaining;
6905 mPausedBytesRemaining = 0;
6906 }
6907 if (mHwPaused) {
6908 doHwResume = true;
6909 mHwPaused = false;
6910 // threadLoop_mix() will handle the case that we need to
6911 // resume an interrupted write
6912 }
6913 // enable write to audio HAL
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006914 mSleepTimeUs = 0;
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08006915
Eric Laurent3df841a2016-07-15 15:15:40 -07006916 mLeftVolFloat = mRightVolFloat = -1.0;
6917
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08006918 // Do not handle new data in this iteration even if track->framesReady()
6919 mixerStatus = MIXER_TRACKS_ENABLED;
6920 }
6921 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07006922 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Andy Hungc0691382018-09-12 18:01:57 -07006923 ALOGVV("OffloadThread: track(%d) s=%08x [OK]", track->id(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006924 if (track->mFillingUpStatus == Track::FS_FILLED) {
6925 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07006926 if (last) {
6927 // make sure processVolume_l() will apply new volume even if 0
6928 mLeftVolFloat = mRightVolFloat = -1.0;
6929 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006930 }
6931
6932 if (last) {
Eric Laurentd7e59222013-11-15 12:02:28 -08006933 sp<Track> previousTrack = mPreviousTrack.promote();
6934 if (previousTrack != 0) {
6935 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08006936 // Flush any data still being written from last track
6937 mBytesRemaining = 0;
6938 if (mPausedBytesRemaining) {
6939 // Last track was paused so we also need to flush saved
6940 // mixbuffer state and invalidate track so that it will
6941 // re-submit that unwritten data when it is next resumed
6942 mPausedBytesRemaining = 0;
6943 // Invalidate is a bit drastic - would be more efficient
6944 // to have a flag to tell client that some of the
6945 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08006946 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08006947 }
6948 // flush data already sent to the DSP if changing audio session as audio
6949 // comes from a different source. Also invalidate previous track to force a
6950 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08006951 if (previousTrack->sessionId() != track->sessionId()) {
6952 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08006953 }
6954 }
6955 }
6956 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006957 // reset retry count
Eric Laurente93cc032016-05-05 10:15:10 -07006958 if (track->isStopping_1()) {
6959 track->mRetryCount = kMaxTrackStopRetriesOffload;
6960 } else {
6961 track->mRetryCount = kMaxTrackRetriesOffload;
6962 }
Eric Laurent5850c4c2016-11-10 13:04:31 -08006963 mActiveTrack = t;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006964 mixerStatus = MIXER_TRACKS_READY;
6965 }
6966 } else {
Andy Hungc0691382018-09-12 18:01:57 -07006967 ALOGVV("OffloadThread: track(%d) s=%08x [NOT READY]", track->id(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006968 if (track->isStopping_1()) {
Eric Laurente93cc032016-05-05 10:15:10 -07006969 if (--(track->mRetryCount) <= 0) {
6970 // Hardware buffer can hold a large amount of audio so we must
6971 // wait for all current track's data to drain before we say
6972 // that the track is stopped.
6973 if (mBytesRemaining == 0) {
6974 // Only start draining when all data in mixbuffer
6975 // has been written
6976 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
6977 track->mState = TrackBase::STOPPING_2; // so presentation completes after
6978 // drain do not drain if no data was ever sent to HAL (mStandby == true)
6979 if (last && !mStandby) {
6980 // do not modify drain sequence if we are already draining. This happens
6981 // when resuming from pause after drain.
6982 if ((mDrainSequence & 1) == 0) {
6983 mSleepTimeUs = 0;
6984 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
6985 mixerStatus = MIXER_DRAIN_TRACK;
6986 mDrainSequence += 2;
6987 }
6988 if (mHwPaused) {
6989 // It is possible to move from PAUSED to STOPPING_1 without
6990 // a resume so we must ensure hardware is running
6991 doHwResume = true;
6992 mHwPaused = false;
6993 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006994 }
6995 }
Eric Laurente93cc032016-05-05 10:15:10 -07006996 } else if (last) {
6997 ALOGV("stopping1 underrun retries left %d", track->mRetryCount);
6998 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006999 }
7000 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07007001 // Drain has completed or we are in standby, signal presentation complete
7002 if (!(mDrainSequence & 1) || !last || mStandby) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08007003 track->mState = TrackBase::STOPPED;
Atneya Nair0cae0432022-05-10 18:12:12 -04007004 mOutput->presentationComplete();
7005 track->presentationComplete(latency_l()); // always returns true
Eric Laurentbfb1b832013-01-07 09:53:42 -08007006 track->reset();
7007 tracksToRemove->add(track);
Dean Wheatley12473e92021-03-18 23:00:55 +11007008 // OFFLOADED stop resets frame counts.
Andy Hungf3234512018-07-03 14:51:47 -07007009 if (!mUseAsyncWrite) {
7010 // If we don't get explicit drain notification we must
7011 // register discontinuity regardless of whether this is
7012 // the previous (!last) or the upcoming (last) track
7013 // to avoid skipping the discontinuity.
Dean Wheatley12473e92021-03-18 23:00:55 +11007014 mTimestampVerifier.discontinuity(
7015 mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Andy Hungf3234512018-07-03 14:51:47 -07007016 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007017 }
7018 } else {
7019 // No buffers for this track. Give it a few chances to
7020 // fill a buffer, then remove it from active list.
Brian Lindahl65e90012022-07-27 18:01:07 +02007021 bool isTimestampAdvancing = mIsTimestampAdvancing.check(mOutput);
Gareth Fennb18c1a32022-10-05 13:42:36 -07007022 if (!isTunerStream() // tuner streams remain active in underrun
7023 && --(track->mRetryCount) <= 0) {
Brian Lindahl65e90012022-07-27 18:01:07 +02007024 if (isTimestampAdvancing) { // HAL is still playing audio, give us more time.
Andy Hungf8044752016-07-27 14:58:11 -07007025 track->mRetryCount = kMaxTrackRetriesOffload;
7026 } else {
Andy Hungc0691382018-09-12 18:01:57 -07007027 ALOGV("OffloadThread: BUFFER TIMEOUT: remove track(%d) from active list",
7028 track->id());
Andy Hungf8044752016-07-27 14:58:11 -07007029 tracksToRemove->add(track);
Glenn Kastend3bb6452016-12-05 18:14:37 -08007030 // tell client process that the track was disabled because of underrun;
Andy Hungf8044752016-07-27 14:58:11 -07007031 // it will then automatically call start() when data is available
7032 track->disable();
7033 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007034 } else if (last){
7035 mixerStatus = MIXER_TRACKS_ENABLED;
7036 }
7037 }
7038 }
7039 // compute volume for this track
Wenfeng Sun79458332019-05-29 20:12:43 +08007040 if (track->isReady()) { // check ready to prevent premature start.
7041 processVolume_l(track, last);
7042 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007043 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007044
Eric Laurentea0fade2013-10-04 16:23:48 -07007045 // make sure the pause/flush/resume sequence is executed in the right order.
7046 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
7047 // before flush and then resume HW. This can happen in case of pause/flush/resume
7048 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07007049 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007050 status_t result = mOutput->stream->pause();
7051 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Gareth Fenncd1e1622022-10-05 11:45:45 -07007052 doHwResume = !doHwPause; // resume if pause is due to flush.
Eric Laurent972a1732013-09-04 09:42:59 -07007053 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007054 if (mFlushPending) {
7055 flushHw_l();
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007056 }
Eric Laurentfd477972013-10-25 18:10:40 -07007057 if (!mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007058 status_t result = mOutput->stream->resume();
7059 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07007060 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007061
Eric Laurentbfb1b832013-01-07 09:53:42 -08007062 // remove all the tracks that need to be...
7063 removeTracks_l(*tracksToRemove);
7064
7065 return mixerStatus;
7066}
7067
Eric Laurentbfb1b832013-01-07 09:53:42 -08007068// must be called with thread mutex locked
7069bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
7070{
Eric Laurent3b4529e2013-09-05 18:09:19 -07007071 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
7072 mWriteAckSequence, mDrainSequence);
7073 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08007074 return true;
7075 }
7076 return false;
7077}
7078
Eric Laurentbfb1b832013-01-07 09:53:42 -08007079bool AudioFlinger::OffloadThread::waitingAsyncCallback()
7080{
7081 Mutex::Autolock _l(mLock);
7082 return waitingAsyncCallback_l();
7083}
7084
7085void AudioFlinger::OffloadThread::flushHw_l()
7086{
Eric Laurente659ef42014-09-29 13:06:46 -07007087 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08007088 // Flush anything still waiting in the mixbuffer
7089 mCurrentWriteLength = 0;
7090 mBytesRemaining = 0;
7091 mPausedWriteLength = 0;
7092 mPausedBytesRemaining = 0;
Eric Laurent3eaf66b2016-04-01 14:44:17 -07007093 // reset bytes written count to reflect that DSP buffers are empty after flush.
7094 mBytesWritten = 0;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08007095
Eric Laurentbfb1b832013-01-07 09:53:42 -08007096 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07007097 // discard any pending drain or write ack by incrementing sequence
7098 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
7099 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007100 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07007101 mCallbackThread->setWriteBlocked(mWriteAckSequence);
7102 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007103 }
7104}
7105
Haynes Mathew George05317d22016-05-03 16:34:26 -07007106void AudioFlinger::OffloadThread::invalidateTracks(audio_stream_type_t streamType)
7107{
7108 Mutex::Autolock _l(mLock);
Eric Laurent13084622016-05-17 10:51:49 -07007109 if (PlaybackThread::invalidateTracks_l(streamType)) {
7110 mFlushPending = true;
7111 }
Haynes Mathew George05317d22016-05-03 16:34:26 -07007112}
7113
Eric Laurentbfb1b832013-01-07 09:53:42 -08007114// ----------------------------------------------------------------------------
7115
Eric Laurent81784c32012-11-19 14:55:58 -08007116AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurent72e3f392015-05-20 14:43:50 -07007117 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id, bool systemReady)
jiabinc52b1ff2019-10-31 17:20:42 -07007118 : MixerThread(audioFlinger, mainThread->getOutput(), id,
Eric Laurent72e3f392015-05-20 14:43:50 -07007119 systemReady, DUPLICATING),
Eric Laurent81784c32012-11-19 14:55:58 -08007120 mWaitTimeMs(UINT_MAX)
7121{
7122 addOutputTrack(mainThread);
7123}
7124
7125AudioFlinger::DuplicatingThread::~DuplicatingThread()
7126{
7127 for (size_t i = 0; i < mOutputTracks.size(); i++) {
7128 mOutputTracks[i]->destroy();
7129 }
7130}
7131
7132void AudioFlinger::DuplicatingThread::threadLoop_mix()
7133{
7134 // mix buffers...
7135 if (outputsReady(outputTracks)) {
Glenn Kastend79072e2016-01-06 08:41:20 -08007136 mAudioMixer->process();
Eric Laurent81784c32012-11-19 14:55:58 -08007137 } else {
Eric Laurent02b57082014-11-07 17:28:28 -08007138 if (mMixerBufferValid) {
7139 memset(mMixerBuffer, 0, mMixerBufferSize);
7140 } else {
7141 memset(mSinkBuffer, 0, mSinkBufferSize);
7142 }
Eric Laurent81784c32012-11-19 14:55:58 -08007143 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007144 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007145 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08007146 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007147 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08007148}
7149
7150void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
7151{
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007152 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08007153 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007154 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007155 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007156 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007157 }
7158 } else if (mBytesWritten != 0) {
7159 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
7160 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08007161 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08007162 } else {
7163 // flush remaining overflow buffers in output tracks
7164 writeFrames = 0;
7165 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007166 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007167 }
7168}
7169
Eric Laurentbfb1b832013-01-07 09:53:42 -08007170ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08007171{
7172 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hung1c86ebe2018-05-29 20:29:08 -07007173 const ssize_t actualWritten = outputTracks[i]->write(mSinkBuffer, writeFrames);
7174
7175 // Consider the first OutputTrack for timestamp and frame counting.
7176
7177 // The threadLoop() generally assumes writing a full sink buffer size at a time.
7178 // Here, we correct for writeFrames of 0 (a stop) or underruns because
7179 // we always claim success.
7180 if (i == 0) {
7181 const ssize_t correction = mSinkBufferSize / mFrameSize - actualWritten;
7182 ALOGD_IF(correction != 0 && writeFrames != 0,
7183 "%s: writeFrames:%u actualWritten:%zd correction:%zd mFramesWritten:%lld",
7184 __func__, writeFrames, actualWritten, correction, (long long)mFramesWritten);
7185 mFramesWritten -= correction;
7186 }
7187
7188 // TODO: Report correction for the other output tracks and show in the dump.
Eric Laurent81784c32012-11-19 14:55:58 -08007189 }
Andy Hungcf10d742020-04-28 15:38:24 -07007190 if (mStandby) {
7191 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07007192 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -07007193 mStandby = false;
7194 }
Andy Hung25c2dac2014-02-27 14:56:00 -08007195 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08007196}
7197
7198void AudioFlinger::DuplicatingThread::threadLoop_standby()
7199{
7200 // DuplicatingThread implements standby by stopping all tracks
7201 for (size_t i = 0; i < outputTracks.size(); i++) {
7202 outputTracks[i]->stop();
7203 }
7204}
7205
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07007206void AudioFlinger::DuplicatingThread::dumpInternals_l(int fd, const Vector<String16>& args __unused)
Andy Hung1bc088a2018-02-09 15:57:31 -08007207{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07007208 MixerThread::dumpInternals_l(fd, args);
Andy Hung1bc088a2018-02-09 15:57:31 -08007209
7210 std::stringstream ss;
7211 const size_t numTracks = mOutputTracks.size();
7212 ss << " " << numTracks << " OutputTracks";
7213 if (numTracks > 0) {
7214 ss << ":";
7215 for (const auto &track : mOutputTracks) {
7216 const sp<ThreadBase> thread = track->thread().promote();
Andy Hungc0691382018-09-12 18:01:57 -07007217 ss << " (" << track->id() << " : ";
Andy Hung1bc088a2018-02-09 15:57:31 -08007218 if (thread.get() != nullptr) {
7219 ss << thread.get() << ", " << thread->id();
7220 } else {
7221 ss << "null";
7222 }
7223 ss << ")";
7224 }
7225 }
7226 ss << "\n";
7227 std::string result = ss.str();
7228 write(fd, result.c_str(), result.size());
7229}
7230
Eric Laurent81784c32012-11-19 14:55:58 -08007231void AudioFlinger::DuplicatingThread::saveOutputTracks()
7232{
7233 outputTracks = mOutputTracks;
7234}
7235
7236void AudioFlinger::DuplicatingThread::clearOutputTracks()
7237{
7238 outputTracks.clear();
7239}
7240
7241void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
7242{
7243 Mutex::Autolock _l(mLock);
Andy Hungc25b84a2015-01-14 19:04:10 -08007244 // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
7245 // Adjust for thread->sampleRate() to determine minimum buffer frame count.
7246 // Then triple buffer because Threads do not run synchronously and may not be clock locked.
7247 const size_t frameCount =
7248 3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
7249 // TODO: Consider asynchronous sample rate conversion to handle clock disparity
7250 // from different OutputTracks and their associated MixerThreads (e.g. one may
7251 // nearly empty and the other may be dropping data).
7252
Svet Ganov33761132021-05-13 22:51:08 +00007253 // TODO b/182392769: use attribution source util, move to server edge
7254 AttributionSourceState attributionSource = AttributionSourceState();
7255 attributionSource.uid = VALUE_OR_FATAL(legacy2aidl_uid_t_int32_t(
Philip P. Moltmannbda45752020-07-17 16:41:18 -07007256 IPCThreadState::self()->getCallingUid()));
Svet Ganov33761132021-05-13 22:51:08 +00007257 attributionSource.pid = VALUE_OR_FATAL(legacy2aidl_pid_t_int32_t(
Philip P. Moltmannbda45752020-07-17 16:41:18 -07007258 IPCThreadState::self()->getCallingPid()));
Svet Ganov33761132021-05-13 22:51:08 +00007259 attributionSource.token = sp<BBinder>::make();
Andy Hungc25b84a2015-01-14 19:04:10 -08007260 sp<OutputTrack> outputTrack = new OutputTrack(thread,
Eric Laurent81784c32012-11-19 14:55:58 -08007261 this,
7262 mSampleRate,
Andy Hungc25b84a2015-01-14 19:04:10 -08007263 mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08007264 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08007265 frameCount,
Svet Ganov33761132021-05-13 22:51:08 +00007266 attributionSource);
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07007267 status_t status = outputTrack != 0 ? outputTrack->initCheck() : (status_t) NO_MEMORY;
7268 if (status != NO_ERROR) {
7269 ALOGE("addOutputTrack() initCheck failed %d", status);
7270 return;
Eric Laurent81784c32012-11-19 14:55:58 -08007271 }
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07007272 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
7273 mOutputTracks.add(outputTrack);
7274 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
7275 updateWaitTime_l();
Eric Laurent81784c32012-11-19 14:55:58 -08007276}
7277
7278void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
7279{
7280 Mutex::Autolock _l(mLock);
7281 for (size_t i = 0; i < mOutputTracks.size(); i++) {
7282 if (mOutputTracks[i]->thread() == thread) {
7283 mOutputTracks[i]->destroy();
7284 mOutputTracks.removeAt(i);
7285 updateWaitTime_l();
Eric Laurentf6870ae2015-05-08 10:50:03 -07007286 if (thread->getOutput() == mOutput) {
7287 mOutput = NULL;
7288 }
Eric Laurent81784c32012-11-19 14:55:58 -08007289 return;
7290 }
7291 }
Eric Laurentf6870ae2015-05-08 10:50:03 -07007292 ALOGV("removeOutputTrack(): unknown thread: %p", thread);
Eric Laurent81784c32012-11-19 14:55:58 -08007293}
7294
7295// caller must hold mLock
7296void AudioFlinger::DuplicatingThread::updateWaitTime_l()
7297{
7298 mWaitTimeMs = UINT_MAX;
7299 for (size_t i = 0; i < mOutputTracks.size(); i++) {
7300 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
7301 if (strong != 0) {
7302 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
7303 if (waitTimeMs < mWaitTimeMs) {
7304 mWaitTimeMs = waitTimeMs;
7305 }
7306 }
7307 }
7308}
7309
7310
7311bool AudioFlinger::DuplicatingThread::outputsReady(
7312 const SortedVector< sp<OutputTrack> > &outputTracks)
7313{
7314 for (size_t i = 0; i < outputTracks.size(); i++) {
7315 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
7316 if (thread == 0) {
7317 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
7318 outputTracks[i].get());
7319 return false;
7320 }
7321 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
7322 // see note at standby() declaration
7323 if (playbackThread->standby() && !playbackThread->isSuspended()) {
7324 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
7325 thread.get());
7326 return false;
7327 }
7328 }
7329 return true;
7330}
7331
Kevin Rocard12381092018-04-11 09:19:59 -07007332void AudioFlinger::DuplicatingThread::sendMetadataToBackend_l(
7333 const StreamOutHalInterface::SourceMetadata& metadata)
Kevin Rocard069c2712018-03-29 19:09:14 -07007334{
Kevin Rocard12381092018-04-11 09:19:59 -07007335 for (auto& outputTrack : outputTracks) { // not mOutputTracks
7336 outputTrack->setMetadatas(metadata.tracks);
7337 }
Kevin Rocard069c2712018-03-29 19:09:14 -07007338}
7339
Eric Laurent81784c32012-11-19 14:55:58 -08007340uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
7341{
7342 return (mWaitTimeMs * 1000) / 2;
7343}
7344
7345void AudioFlinger::DuplicatingThread::cacheParameters_l()
7346{
7347 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
7348 updateWaitTime_l();
7349
7350 MixerThread::cacheParameters_l();
7351}
7352
Eric Laurentb3f315a2021-07-13 15:09:05 +02007353// ----------------------------------------------------------------------------
7354
Eric Laurentfa0f6742021-08-17 18:39:44 +02007355AudioFlinger::SpatializerThread::SpatializerThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurentb3f315a2021-07-13 15:09:05 +02007356 AudioStreamOut* output,
7357 audio_io_handle_t id,
7358 bool systemReady,
7359 audio_config_base_t *mixerConfig)
Eric Laurent1c5e2e32021-08-18 18:50:28 +02007360 : MixerThread(audioFlinger, output, id, systemReady, SPATIALIZER, mixerConfig)
Eric Laurentb3f315a2021-07-13 15:09:05 +02007361{
7362}
7363
Eric Laurent68a40a82022-05-03 18:15:04 +02007364void AudioFlinger::SpatializerThread::onFirstRef() {
7365 PlaybackThread::onFirstRef();
7366
7367 Mutex::Autolock _l(mLock);
7368 status_t status = mOutput->stream->setLatencyModeCallback(this);
7369 if (status != INVALID_OPERATION) {
7370 updateHalSupportedLatencyModes_l();
7371 }
Andy Hungfeb4e5c2022-10-17 19:10:02 -07007372
7373 // update priority if specified.
7374 constexpr int32_t kRTPriorityMin = 1;
7375 constexpr int32_t kRTPriorityMax = 3;
7376 const int32_t priorityBoost =
7377 property_get_int32("audio.spatializer.priority", kRTPriorityMin);
7378 if (priorityBoost >= kRTPriorityMin && priorityBoost <= kRTPriorityMax) {
7379 const pid_t pid = getpid();
7380 const pid_t tid = getTid();
7381
7382 if (tid == -1) {
7383 // Unusual: PlaybackThread::onFirstRef() should set the threadLoop running.
7384 ALOGW("%s: audio.spatializer.priority %d ignored, thread not running",
7385 __func__, priorityBoost);
7386 } else {
7387 ALOGD("%s: audio.spatializer.priority %d, allowing real time for pid %d tid %d",
7388 __func__, priorityBoost, pid, tid);
7389 sendPrioConfigEvent_l(pid, tid, priorityBoost, false /*forApp*/);
7390 stream()->setHalThreadPriority(priorityBoost);
7391 }
7392 }
Eric Laurent68a40a82022-05-03 18:15:04 +02007393}
7394
7395status_t AudioFlinger::SpatializerThread::createAudioPatch_l(const struct audio_patch *patch,
7396 audio_patch_handle_t *handle)
7397{
7398 status_t status = MixerThread::createAudioPatch_l(patch, handle);
7399 updateHalSupportedLatencyModes_l();
7400 return status;
7401}
7402
7403void AudioFlinger::SpatializerThread::updateHalSupportedLatencyModes_l() {
7404 std::vector<audio_latency_mode_t> latencyModes;
7405 if (mOutput->stream->getRecommendedLatencyModes(&latencyModes) != NO_ERROR) {
7406 latencyModes.clear();
7407 }
7408 if (latencyModes != mSupportedLatencyModes) {
7409 mSupportedLatencyModes.swap(latencyModes);
7410 sendHalLatencyModesChangedEvent_l();
7411 }
7412}
7413
7414void AudioFlinger::SpatializerThread::onHalLatencyModesChanged_l() {
7415 mAudioFlinger->onSupportedLatencyModesChanged(mId, mSupportedLatencyModes);
7416}
7417
7418void AudioFlinger::SpatializerThread::setHalLatencyMode_l() {
7419 // if mSupportedLatencyModes is empty, the HAL stream does not support
7420 // latency mode control and we can exit.
7421 if (mSupportedLatencyModes.empty()) {
7422 return;
7423 }
7424 audio_latency_mode_t latencyMode = AUDIO_LATENCY_MODE_FREE;
7425 if (mSupportedLatencyModes.size() == 1) {
7426 // If the HAL only support one latency mode currently, confirm the choice
7427 latencyMode = mSupportedLatencyModes[0];
7428 } else if (mSupportedLatencyModes.size() > 1) {
7429 // Request low latency if:
7430 // - The low latency mode is requested by the spatializer controller
7431 // (mRequestedLatencyMode = AUDIO_LATENCY_MODE_LOW)
7432 // AND
7433 // - At least one active track is spatialized
7434 bool hasSpatializedActiveTrack = false;
7435 for (const auto& track : mActiveTracks) {
7436 if (track->isSpatialized()) {
7437 hasSpatializedActiveTrack = true;
7438 break;
7439 }
7440 }
7441 if (hasSpatializedActiveTrack && mRequestedLatencyMode == AUDIO_LATENCY_MODE_LOW) {
7442 latencyMode = AUDIO_LATENCY_MODE_LOW;
7443 }
7444 }
7445
7446 if (latencyMode != mSetLatencyMode) {
7447 status_t status = mOutput->stream->setLatencyMode(latencyMode);
7448 if (status == NO_ERROR) {
7449 mSetLatencyMode = latencyMode;
7450 }
7451 }
7452}
7453
7454status_t AudioFlinger::SpatializerThread::setRequestedLatencyMode(audio_latency_mode_t mode) {
7455 if (mode != AUDIO_LATENCY_MODE_LOW && mode != AUDIO_LATENCY_MODE_FREE) {
7456 return BAD_VALUE;
7457 }
7458 Mutex::Autolock _l(mLock);
7459 mRequestedLatencyMode = mode;
7460 return NO_ERROR;
7461}
7462
7463status_t AudioFlinger::SpatializerThread::getSupportedLatencyModes(
7464 std::vector<audio_latency_mode_t>* modes) {
7465 if (modes == nullptr) {
7466 return BAD_VALUE;
7467 }
7468 Mutex::Autolock _l(mLock);
7469 *modes = mSupportedLatencyModes;
7470 return NO_ERROR;
7471}
7472
Eric Laurentfa0f6742021-08-17 18:39:44 +02007473void AudioFlinger::SpatializerThread::checkOutputStageEffects()
Eric Laurentb3f315a2021-07-13 15:09:05 +02007474{
7475 bool hasVirtualizer = false;
7476 bool hasDownMixer = false;
7477 sp<EffectHandle> finalDownMixer;
7478 {
7479 Mutex::Autolock _l(mLock);
7480 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_STAGE);
7481 if (chain != 0) {
Eric Laurent1c5e2e32021-08-18 18:50:28 +02007482 hasVirtualizer = chain->getEffectFromType_l(FX_IID_SPATIALIZER) != nullptr;
Eric Laurentb3f315a2021-07-13 15:09:05 +02007483 hasDownMixer = chain->getEffectFromType_l(EFFECT_UIID_DOWNMIX) != nullptr;
7484 }
7485
7486 finalDownMixer = mFinalDownMixer;
7487 mFinalDownMixer.clear();
7488 }
7489
7490 if (hasVirtualizer) {
7491 if (finalDownMixer != nullptr) {
7492 int32_t ret;
7493 finalDownMixer->disable(&ret);
7494 }
7495 finalDownMixer.clear();
7496 } else if (!hasDownMixer) {
7497 std::vector<effect_descriptor_t> descriptors;
7498 status_t status = mAudioFlinger->mEffectsFactoryHal->getDescriptors(
7499 EFFECT_UIID_DOWNMIX, &descriptors);
7500 if (status != NO_ERROR) {
7501 return;
7502 }
7503 ALOG_ASSERT(!descriptors.empty(),
7504 "%s getDescriptors() returned no error but empty list", __func__);
7505
7506 finalDownMixer = createEffect_l(nullptr /*client*/, nullptr /*effectClient*/,
7507 0 /*priority*/, AUDIO_SESSION_OUTPUT_STAGE, &descriptors[0], nullptr /*enabled*/,
Eric Laurentde8caf42021-08-11 17:19:25 +02007508 &status, false /*pinned*/, false /*probe*/, false /*notifyFramesProcessed*/);
Eric Laurentb3f315a2021-07-13 15:09:05 +02007509
7510 if (finalDownMixer == nullptr || (status != NO_ERROR && status != ALREADY_EXISTS)) {
7511 ALOGW("%s error creating downmixer %d", __func__, status);
7512 finalDownMixer.clear();
7513 } else {
7514 int32_t ret;
7515 finalDownMixer->enable(&ret);
7516 }
7517 }
7518
7519 {
7520 Mutex::Autolock _l(mLock);
7521 mFinalDownMixer = finalDownMixer;
7522 }
7523}
7524
Eric Laurent68a40a82022-05-03 18:15:04 +02007525void AudioFlinger::SpatializerThread::onRecommendedLatencyModeChanged(
7526 std::vector<audio_latency_mode_t> modes) {
7527 Mutex::Autolock _l(mLock);
7528 if (modes != mSupportedLatencyModes) {
7529 mSupportedLatencyModes.swap(modes);
7530 sendHalLatencyModesChangedEvent_l();
7531 }
7532}
Eric Laurent6acd1d42017-01-04 14:23:29 -08007533
Eric Laurent81784c32012-11-19 14:55:58 -08007534// ----------------------------------------------------------------------------
7535// Record
7536// ----------------------------------------------------------------------------
7537
7538AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
7539 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08007540 audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -07007541 bool systemReady
Glenn Kasten46909e72013-02-26 09:20:22 -08007542 ) :
Andy Hungcf10d742020-04-28 15:38:24 -07007543 ThreadBase(audioFlinger, id, RECORD, systemReady, false /* isOut */),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007544 mInput(input),
Mikhail Naganov2534b382019-09-25 13:05:02 -07007545 mSource(mInput),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007546 mActiveTracks(&this->mLocalLog),
7547 mRsmpInBuffer(NULL),
Glenn Kasten1b291842016-07-18 14:55:21 -07007548 // mRsmpInFrames, mRsmpInFramesP2, and mRsmpInFramesOA are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007549 mRsmpInRear(0)
Glenn Kastenb880f5e2014-05-07 08:43:45 -07007550 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
7551 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007552 // mFastCapture below
7553 , mFastCaptureFutex(0)
7554 // mInputSource
7555 // mPipeSink
7556 // mPipeSource
7557 , mPipeFramesP2(0)
7558 // mPipeMemory
7559 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07007560 , mFastTrackAvail(false)
Eric Laurentd8365c52017-07-16 15:27:05 -07007561 , mBtNrecSuspended(false)
Eric Laurent81784c32012-11-19 14:55:58 -08007562{
Glenn Kastend7dca052015-03-05 16:05:54 -08007563 snprintf(mThreadName, kThreadNameLength, "AudioIn_%X", id);
7564 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08007565
George Burgess IVa8f90c12020-05-14 11:27:19 -07007566 if (mInput->audioHwDev != nullptr) {
Andy Hungc8fddf32018-08-08 18:32:37 -07007567 mIsMsdDevice = strcmp(
7568 mInput->audioHwDev->moduleName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0;
7569 }
7570
Glenn Kastendeca2ae2014-02-07 10:25:56 -08007571 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007572
Andy Hungc8fddf32018-08-08 18:32:37 -07007573 // TODO: We may also match on address as well as device type for
7574 // AUDIO_DEVICE_IN_BUS, AUDIO_DEVICE_IN_BLUETOOTH_A2DP, AUDIO_DEVICE_IN_REMOTE_SUBMIX
jiabinc52b1ff2019-10-31 17:20:42 -07007575 // TODO: This property should be ensure that only contains one single device type.
7576 mTimestampCorrectedDevice = (audio_devices_t)property_get_int64(
7577 "audio.timestamp.corrected_input_device",
Andy Hungc8fddf32018-08-08 18:32:37 -07007578 (int64_t)(mIsMsdDevice ? AUDIO_DEVICE_IN_BUS // turn on by default for MSD
7579 : AUDIO_DEVICE_NONE));
7580
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007581 // create an NBAIO source for the HAL input stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07007582 mInputSource = new AudioStreamInSource(input->stream);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007583 size_t numCounterOffers = 0;
7584 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07007585#if !LOG_NDEBUG
7586 ssize_t index =
7587#else
7588 (void)
7589#endif
7590 mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007591 ALOG_ASSERT(index == 0);
7592
7593 // initialize fast capture depending on configuration
7594 bool initFastCapture;
7595 switch (kUseFastCapture) {
7596 case FastCapture_Never:
7597 initFastCapture = false;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007598 ALOGV("%p kUseFastCapture = Never, initFastCapture = false", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007599 break;
7600 case FastCapture_Always:
7601 initFastCapture = true;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007602 ALOGV("%p kUseFastCapture = Always, initFastCapture = true", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007603 break;
7604 case FastCapture_Static:
Glenn Kasteneb9487e2015-07-22 09:15:17 -07007605 initFastCapture = (mFrameCount * 1000) / mSampleRate < kMinNormalCaptureBufferSizeMs;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007606 ALOGV("%p kUseFastCapture = Static, (%lld * 1000) / %u vs %u, initFastCapture = %d",
7607 this, (long long)mFrameCount, mSampleRate, kMinNormalCaptureBufferSizeMs,
7608 initFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007609 break;
7610 // case FastCapture_Dynamic:
7611 }
7612
7613 if (initFastCapture) {
Glenn Kastend198b852015-03-16 14:55:53 -07007614 // create a Pipe for FastCapture to write to, and for us and fast tracks to read from
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007615 NBAIO_Format format = mInputSource->format();
Glenn Kasten1b291842016-07-18 14:55:21 -07007616 // quadruple-buffering of 20 ms each; this ensures we can sleep for 20ms in RecordThread
7617 size_t pipeFramesP2 = roundup(4 * FMS_20 * mSampleRate / 1000);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007618 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007619 void *pipeBuffer = nullptr;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007620 const sp<MemoryDealer> roHeap(readOnlyHeap());
7621 sp<IMemory> pipeMemory;
7622 if ((roHeap == 0) ||
7623 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07007624 (pipeBuffer = pipeMemory->unsecurePointer()) == nullptr) {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007625 ALOGE("not enough memory for pipe buffer size=%zu; "
7626 "roHeap=%p, pipeMemory=%p, pipeBuffer=%p; roHeapSize: %lld",
7627 pipeSize, roHeap.get(), pipeMemory.get(), pipeBuffer,
7628 (long long)kRecordThreadReadOnlyHeapSize);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007629 goto failed;
7630 }
7631 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
7632 memset(pipeBuffer, 0, pipeSize);
7633 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
7634 const NBAIO_Format offers[1] = {format};
7635 size_t numCounterOffers = 0;
7636 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
7637 ALOG_ASSERT(index == 0);
7638 mPipeSink = pipe;
7639 PipeReader *pipeReader = new PipeReader(*pipe);
7640 numCounterOffers = 0;
7641 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
7642 ALOG_ASSERT(index == 0);
7643 mPipeSource = pipeReader;
7644 mPipeFramesP2 = pipeFramesP2;
7645 mPipeMemory = pipeMemory;
7646
7647 // create fast capture
7648 mFastCapture = new FastCapture();
7649 FastCaptureStateQueue *sq = mFastCapture->sq();
7650#ifdef STATE_QUEUE_DUMP
7651 // FIXME
7652#endif
7653 FastCaptureState *state = sq->begin();
7654 state->mCblk = NULL;
7655 state->mInputSource = mInputSource.get();
7656 state->mInputSourceGen++;
7657 state->mPipeSink = pipe;
7658 state->mPipeSinkGen++;
7659 state->mFrameCount = mFrameCount;
7660 state->mCommand = FastCaptureState::COLD_IDLE;
7661 // already done in constructor initialization list
7662 //mFastCaptureFutex = 0;
7663 state->mColdFutexAddr = &mFastCaptureFutex;
7664 state->mColdGen++;
7665 state->mDumpState = &mFastCaptureDumpState;
7666#ifdef TEE_SINK
7667 // FIXME
7668#endif
7669 mFastCaptureNBLogWriter = audioFlinger->newWriter_l(kFastCaptureLogSize, "FastCapture");
7670 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
7671 sq->end();
7672 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
7673
7674 // start the fast capture
7675 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
7676 pid_t tid = mFastCapture->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07007677 sendPrioConfigEvent(getpid(), tid, kPriorityFastCapture, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08007678 stream()->setHalThreadPriority(kPriorityFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007679#ifdef AUDIO_WATCHDOG
7680 // FIXME
7681#endif
7682
Glenn Kasten6e6704c2014-07-03 10:20:00 -07007683 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007684 }
Andy Hung8946a282018-04-19 20:04:56 -07007685#ifdef TEE_SINK
7686 mTee.set(mInputSource->format(), NBAIO_Tee::TEE_FLAG_INPUT_THREAD);
7687 mTee.setId(std::string("_") + std::to_string(mId) + "_C");
7688#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007689failed: ;
7690
7691 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08007692}
7693
Eric Laurent81784c32012-11-19 14:55:58 -08007694AudioFlinger::RecordThread::~RecordThread()
7695{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007696 if (mFastCapture != 0) {
7697 FastCaptureStateQueue *sq = mFastCapture->sq();
7698 FastCaptureState *state = sq->begin();
7699 if (state->mCommand == FastCaptureState::COLD_IDLE) {
7700 int32_t old = android_atomic_inc(&mFastCaptureFutex);
7701 if (old == -1) {
7702 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
7703 }
7704 }
7705 state->mCommand = FastCaptureState::EXIT;
7706 sq->end();
7707 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
7708 mFastCapture->join();
7709 mFastCapture.clear();
7710 }
7711 mAudioFlinger->unregisterWriter(mFastCaptureNBLogWriter);
Glenn Kasten481fb672013-09-30 14:39:28 -07007712 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung57446612015-04-19 23:56:46 -07007713 free(mRsmpInBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08007714}
7715
7716void AudioFlinger::RecordThread::onFirstRef()
7717{
Glenn Kastend7dca052015-03-05 16:05:54 -08007718 run(mThreadName, PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08007719}
7720
Eric Laurent555530a2017-02-07 18:17:24 -08007721void AudioFlinger::RecordThread::preExit()
7722{
7723 ALOGV(" preExit()");
7724 Mutex::Autolock _l(mLock);
7725 for (size_t i = 0; i < mTracks.size(); i++) {
7726 sp<RecordTrack> track = mTracks[i];
7727 track->invalidate();
7728 }
7729 mActiveTracks.clear();
7730 mStartStopCond.broadcast();
7731}
7732
Eric Laurent81784c32012-11-19 14:55:58 -08007733bool AudioFlinger::RecordThread::threadLoop()
7734{
Eric Laurent81784c32012-11-19 14:55:58 -08007735 nsecs_t lastWarning = 0;
7736
7737 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08007738
Glenn Kastenf10ffec2013-11-20 16:40:08 -08007739reacquire_wakelock:
7740 sp<RecordTrack> activeTrack;
7741 {
7742 Mutex::Autolock _l(mLock);
Andy Hungdae27702016-10-31 14:01:16 -07007743 acquireWakeLock_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08007744 }
7745
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007746 // used to request a deferred sleep, to be executed later while mutex is unlocked
7747 uint32_t sleepUs = 0;
7748
Andy Hung446f4df2019-02-21 12:26:41 -08007749 int64_t lastLoopCountRead = -2; // never matches "previous" loop, when loopCount = 0.
7750
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007751 // loop while there is work to do
Andy Hung446f4df2019-02-21 12:26:41 -08007752 for (int64_t loopCount = 0;; ++loopCount) { // loopCount used for statistics tracking
Glenn Kastenc527a7c2013-08-13 15:43:49 -07007753 Vector< sp<EffectChain> > effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07007754
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007755 // activeTracks accumulates a copy of a subset of mActiveTracks
7756 Vector< sp<RecordTrack> > activeTracks;
7757
Glenn Kasten735f45f2014-08-18 15:51:59 -07007758 // reference to the (first and only) active fast track
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007759 sp<RecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07007760
Glenn Kasten735f45f2014-08-18 15:51:59 -07007761 // reference to a fast track which is about to be removed
7762 sp<RecordTrack> fastTrackToRemove;
7763
Eric Laurent33403f02020-05-29 18:35:06 -07007764 bool silenceFastCapture = false;
7765
Eric Laurent81784c32012-11-19 14:55:58 -08007766 { // scope for mLock
7767 Mutex::Autolock _l(mLock);
Eric Laurent000a4192014-01-29 15:17:32 -08007768
Eric Laurent021cf962014-05-13 10:18:14 -07007769 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08007770
Eric Laurent000a4192014-01-29 15:17:32 -08007771 // check exitPending here because checkForNewParameters_l() and
7772 // checkForNewParameters_l() can temporarily release mLock
7773 if (exitPending()) {
7774 break;
7775 }
7776
Eric Laurent5c25d562016-07-13 17:17:45 -07007777 // sleep with mutex unlocked
7778 if (sleepUs > 0) {
Glenn Kastenf9715e42016-07-13 14:02:03 -07007779 ATRACE_BEGIN("sleepC");
Eric Laurent5c25d562016-07-13 17:17:45 -07007780 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)sleepUs));
7781 ATRACE_END();
7782 sleepUs = 0;
7783 continue;
7784 }
7785
Glenn Kasten2b806402013-11-20 16:37:38 -08007786 // if no active track(s), then standby and release wakelock
7787 size_t size = mActiveTracks.size();
7788 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07007789 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07007790 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08007791 releaseWakeLock_l();
7792 ALOGV("RecordThread: loop stopping");
7793 // go to sleep
7794 mWaitWorkCV.wait(mLock);
7795 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08007796 goto reacquire_wakelock;
7797 }
7798
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007799 bool doBroadcast = false;
Eric Laurent5c25d562016-07-13 17:17:45 -07007800 bool allStopped = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007801 for (size_t i = 0; i < size; ) {
Glenn Kasten9e982352013-08-14 14:39:50 -07007802
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007803 activeTrack = mActiveTracks[i];
7804 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07007805 if (activeTrack->isFastTrack()) {
7806 ALOG_ASSERT(fastTrackToRemove == 0);
7807 fastTrackToRemove = activeTrack;
7808 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007809 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08007810 mActiveTracks.remove(activeTrack);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007811 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07007812 continue;
7813 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007814
7815 TrackBase::track_state activeTrackState = activeTrack->mState;
7816 switch (activeTrackState) {
7817
7818 case TrackBase::PAUSING:
7819 mActiveTracks.remove(activeTrack);
Andy Hungce685402018-10-05 17:23:27 -07007820 activeTrack->mState = TrackBase::PAUSED;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007821 doBroadcast = true;
7822 size--;
7823 continue;
7824
7825 case TrackBase::STARTING_1:
7826 sleepUs = 10000;
7827 i++;
Eric Laurent5c25d562016-07-13 17:17:45 -07007828 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007829 continue;
7830
7831 case TrackBase::STARTING_2:
7832 doBroadcast = true;
Andy Hungcf10d742020-04-28 15:38:24 -07007833 if (mStandby) {
7834 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07007835 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -07007836 mStandby = false;
7837 }
Glenn Kasten9e982352013-08-14 14:39:50 -07007838 activeTrack->mState = TrackBase::ACTIVE;
Eric Laurent5c25d562016-07-13 17:17:45 -07007839 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007840 break;
7841
7842 case TrackBase::ACTIVE:
Eric Laurent5c25d562016-07-13 17:17:45 -07007843 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007844 break;
7845
Andy Hungce685402018-10-05 17:23:27 -07007846 case TrackBase::IDLE: // cannot be on ActiveTracks if idle
7847 case TrackBase::PAUSED: // cannot be on ActiveTracks if paused
7848 case TrackBase::STOPPED: // cannot be on ActiveTracks if destroyed/terminated
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007849 default:
Andy Hungce685402018-10-05 17:23:27 -07007850 LOG_ALWAYS_FATAL("%s: Unexpected active track state:%d, id:%d, tracks:%zu",
7851 __func__, activeTrackState, activeTrack->id(), size);
Glenn Kasten9e982352013-08-14 14:39:50 -07007852 }
Glenn Kasten9e982352013-08-14 14:39:50 -07007853
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007854 if (activeTrack->isFastTrack()) {
7855 ALOG_ASSERT(!mFastTrackAvail);
7856 ALOG_ASSERT(fastTrack == 0);
Eric Laurent33403f02020-05-29 18:35:06 -07007857 // if the active fast track is silenced either:
7858 // 1) silence the whole capture from fast capture buffer if this is
7859 // the only active track
7860 // 2) invalidate this track: this will cause the client to reconnect and possibly
7861 // be invalidated again until unsilenced
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02007862 bool invalidate = false;
Eric Laurent33403f02020-05-29 18:35:06 -07007863 if (activeTrack->isSilenced()) {
7864 if (size > 1) {
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02007865 invalidate = true;
Eric Laurent33403f02020-05-29 18:35:06 -07007866 } else {
7867 silenceFastCapture = true;
7868 }
7869 }
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02007870 // Invalidate fast tracks if access to audio history is required as this is not
7871 // possible with fast tracks. Once the fast track has been invalidated, no new
7872 // fast track will be created until mMaxSharedAudioHistoryMs is cleared.
7873 if (mMaxSharedAudioHistoryMs != 0) {
7874 invalidate = true;
7875 }
7876 if (invalidate) {
7877 activeTrack->invalidate();
7878 ALOG_ASSERT(fastTrackToRemove == 0);
7879 fastTrackToRemove = activeTrack;
7880 removeTrack_l(activeTrack);
7881 mActiveTracks.remove(activeTrack);
7882 size--;
7883 continue;
7884 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007885 fastTrack = activeTrack;
7886 }
Eric Laurent33403f02020-05-29 18:35:06 -07007887
7888 activeTracks.add(activeTrack);
7889 i++;
7890
Glenn Kasten9e982352013-08-14 14:39:50 -07007891 }
Eric Laurent5c25d562016-07-13 17:17:45 -07007892
Andy Hungdae27702016-10-31 14:01:16 -07007893 mActiveTracks.updatePowerState(this);
7894
Kevin Rocard069c2712018-03-29 19:09:14 -07007895 updateMetadata_l();
7896
Eric Laurent5c25d562016-07-13 17:17:45 -07007897 if (allStopped) {
7898 standbyIfNotAlreadyInStandby();
7899 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007900 if (doBroadcast) {
7901 mStartStopCond.broadcast();
7902 }
7903
7904 // sleep if there are no active tracks to process
Eric Tan39ec8d62018-07-24 09:49:29 -07007905 if (activeTracks.isEmpty()) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007906 if (sleepUs == 0) {
7907 sleepUs = kRecordThreadSleepUs;
7908 }
7909 continue;
7910 }
7911 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07007912
Eric Laurent81784c32012-11-19 14:55:58 -08007913 lockEffectChains_l(effectChains);
7914 }
7915
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007916 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07007917
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007918 size_t size = effectChains.size();
7919 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07007920 // thread mutex is not locked, but effect chain is locked
7921 effectChains[i]->process_l();
7922 }
7923
Glenn Kasten735f45f2014-08-18 15:51:59 -07007924 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007925 if (mFastCapture != 0) {
7926 FastCaptureStateQueue *sq = mFastCapture->sq();
7927 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07007928 bool didModify = false;
7929 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007930 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
7931 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
7932 if (state->mCommand == FastCaptureState::COLD_IDLE) {
7933 int32_t old = android_atomic_inc(&mFastCaptureFutex);
7934 if (old == -1) {
7935 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
7936 }
7937 }
7938 state->mCommand = FastCaptureState::READ_WRITE;
7939#if 0 // FIXME
7940 mFastCaptureDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08007941 FastThreadDumpState::kSamplingNforLowRamDevice :
7942 FastThreadDumpState::kSamplingN);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007943#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07007944 didModify = true;
7945 }
7946 audio_track_cblk_t *cblkOld = state->mCblk;
7947 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
7948 if (cblkNew != cblkOld) {
7949 state->mCblk = cblkNew;
7950 // block until acked if removing a fast track
7951 if (cblkOld != NULL) {
7952 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
7953 }
7954 didModify = true;
7955 }
jiabin01c8f562018-07-19 17:47:28 -07007956 AudioBufferProvider* abp = (fastTrack != 0 && fastTrack->isPatchTrack()) ?
7957 reinterpret_cast<AudioBufferProvider*>(fastTrack.get()) : nullptr;
7958 if (state->mFastPatchRecordBufferProvider != abp) {
7959 state->mFastPatchRecordBufferProvider = abp;
7960 state->mFastPatchRecordFormat = fastTrack == 0 ?
7961 AUDIO_FORMAT_INVALID : fastTrack->format();
7962 didModify = true;
7963 }
Eric Laurent33403f02020-05-29 18:35:06 -07007964 if (state->mSilenceCapture != silenceFastCapture) {
7965 state->mSilenceCapture = silenceFastCapture;
7966 didModify = true;
7967 }
Glenn Kasten735f45f2014-08-18 15:51:59 -07007968 sq->end(didModify);
7969 if (didModify) {
7970 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007971#if 0
7972 if (kUseFastCapture == FastCapture_Dynamic) {
7973 mNormalSource = mPipeSource;
7974 }
7975#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007976 }
7977 }
7978
Glenn Kasten735f45f2014-08-18 15:51:59 -07007979 // now run the fast track destructor with thread mutex unlocked
7980 fastTrackToRemove.clear();
7981
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007982 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
7983 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
7984 // slow, then this RecordThread will overrun by not calling HAL read often enough.
7985 // If destination is non-contiguous, first read past the nominal end of buffer, then
7986 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07007987
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007988 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007989 ssize_t framesRead;
Andy Hung446f4df2019-02-21 12:26:41 -08007990 const int64_t lastIoBeginNs = systemTime(); // start IO timing
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007991
7992 // If an NBAIO source is present, use it to read the normal capture's data
7993 if (mPipeSource != 0) {
Andy Hung156317a2018-08-02 11:49:29 -07007994 size_t framesToRead = min(mRsmpInFramesOA - rear, mRsmpInFramesP2 / 2);
Andy Hungd5b638f2018-04-30 13:56:10 -07007995
7996 // The audio fifo read() returns OVERRUN on overflow, and advances the read pointer
7997 // to the full buffer point (clearing the overflow condition). Upon OVERRUN error,
7998 // we immediately retry the read() to get data and prevent another overflow.
7999 for (int retries = 0; retries <= 2; ++retries) {
8000 ALOGW_IF(retries > 0, "overrun on read from pipe, retry #%d", retries);
8001 framesRead = mPipeSource->read((uint8_t*)mRsmpInBuffer + rear * mFrameSize,
8002 framesToRead);
8003 if (framesRead != OVERRUN) break;
8004 }
8005
Andy Hung7a3dc6b2018-05-01 16:39:51 -07008006 const ssize_t availableToRead = mPipeSource->availableToRead();
8007 if (availableToRead >= 0) {
Robert Wu06db0a32021-08-10 19:05:34 +00008008 mMonopipePipeDepthStats.add(availableToRead);
Glenn Kastena2f59b32020-08-03 16:37:24 -07008009 // PipeSource is the primary clock. It is up to the AudioRecord client to keep up.
Andy Hung7a3dc6b2018-05-01 16:39:51 -07008010 LOG_ALWAYS_FATAL_IF((size_t)availableToRead > mPipeFramesP2,
8011 "more frames to read than fifo size, %zd > %zu",
8012 availableToRead, mPipeFramesP2);
8013 const size_t pipeFramesFree = mPipeFramesP2 - availableToRead;
8014 const size_t sleepFrames = min(pipeFramesFree, mRsmpInFramesP2) / 2;
8015 ALOGVV("mPipeFramesP2:%zu mRsmpInFramesP2:%zu sleepFrames:%zu availableToRead:%zd",
8016 mPipeFramesP2, mRsmpInFramesP2, sleepFrames, availableToRead);
Glenn Kasten1b291842016-07-18 14:55:21 -07008017 sleepUs = (sleepFrames * 1000000LL) / mSampleRate;
8018 }
8019 if (framesRead < 0) {
8020 status_t status = (status_t) framesRead;
8021 switch (status) {
8022 case OVERRUN:
8023 ALOGW("overrun on read from pipe");
8024 framesRead = 0;
8025 break;
8026 case NEGOTIATE:
8027 ALOGE("re-negotiation is needed");
8028 framesRead = -1; // Will cause an attempt to recover.
8029 break;
8030 default:
8031 ALOGE("unknown error %d on read from pipe", status);
8032 break;
8033 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008034 }
8035 // otherwise use the HAL / AudioStreamIn directly
8036 } else {
Glenn Kastenec6a7032016-03-14 07:40:23 -07008037 ATRACE_BEGIN("read");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008038 size_t bytesRead;
Mikhail Naganov2534b382019-09-25 13:05:02 -07008039 status_t result = mSource->read(
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008040 (uint8_t*)mRsmpInBuffer + rear * mFrameSize, mBufferSize, &bytesRead);
Glenn Kastenec6a7032016-03-14 07:40:23 -07008041 ATRACE_END();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008042 if (result < 0) {
8043 framesRead = result;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008044 } else {
8045 framesRead = bytesRead / mFrameSize;
8046 }
8047 }
8048
Andy Hung446f4df2019-02-21 12:26:41 -08008049 const int64_t lastIoEndNs = systemTime(); // end IO timing
8050
Andy Hung3f0c9022016-01-15 17:49:46 -08008051 // Update server timestamp with server stats
8052 // systemTime() is optional if the hardware supports timestamps.
Andy Hung743f6402020-06-03 13:17:04 -07008053 if (framesRead >= 0) {
8054 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += framesRead;
8055 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = lastIoEndNs;
8056 }
Andy Hung3f0c9022016-01-15 17:49:46 -08008057
8058 // Update server timestamp with kernel stats
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008059 if (mPipeSource.get() == nullptr /* don't obtain for FastCapture, could block */) {
Andy Hung3f0c9022016-01-15 17:49:46 -08008060 int64_t position, time;
Andy Hung2e2c0bb2018-06-11 19:13:11 -07008061 if (mStandby) {
Dean Wheatley12473e92021-03-18 23:00:55 +11008062 mTimestampVerifier.discontinuity(audio_is_linear_pcm(mFormat) ?
8063 mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS :
8064 mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Mikhail Naganov2534b382019-09-25 13:05:02 -07008065 } else if (mSource->getCapturePosition(&position, &time) == NO_ERROR
Andy Hungc8fddf32018-08-08 18:32:37 -07008066 && time > mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]) {
8067
8068 mTimestampVerifier.add(position, time, mSampleRate);
8069
8070 // Correct timestamps
8071 if (isTimestampCorrectionEnabled()) {
Dean Wheatley56a583e2020-05-08 15:12:17 +10008072 ALOGVV("TS_BEFORE: %d %lld %lld",
Andy Hungc8fddf32018-08-08 18:32:37 -07008073 id(), (long long)time, (long long)position);
8074 auto correctedTimestamp = mTimestampVerifier.getLastCorrectedTimestamp();
8075 position = correctedTimestamp.mFrames;
8076 time = correctedTimestamp.mTimeNs;
Dean Wheatley56a583e2020-05-08 15:12:17 +10008077 ALOGVV("TS_AFTER: %d %lld %lld",
Andy Hungc8fddf32018-08-08 18:32:37 -07008078 id(), (long long)time, (long long)position);
8079 }
8080
Andy Hung3f0c9022016-01-15 17:49:46 -08008081 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = position;
8082 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] = time;
8083 // Note: In general record buffers should tend to be empty in
8084 // a properly running pipeline.
8085 //
8086 // Also, it is not advantageous to call get_presentation_position during the read
8087 // as the read obtains a lock, preventing the timestamp call from executing.
Andy Hung2e2c0bb2018-06-11 19:13:11 -07008088 } else {
8089 mTimestampVerifier.error();
Andy Hung3f0c9022016-01-15 17:49:46 -08008090 }
8091 }
Andy Hunge6c37112019-02-26 17:38:10 -08008092
8093 // From the timestamp, input read latency is negative output write latency.
8094 const audio_input_flags_t flags = mInput != NULL ? mInput->flags : AUDIO_INPUT_FLAG_NONE;
8095 const double latencyMs = RecordTrack::checkServerLatencySupported(mFormat, flags)
8096 ? - mTimestamp.getOutputServerLatencyMs(mSampleRate) : 0.;
8097 if (latencyMs != 0.) { // note 0. means timestamp is empty.
8098 mLatencyMs.add(latencyMs);
8099 }
8100
Andy Hung3f0c9022016-01-15 17:49:46 -08008101 // Use this to track timestamp information
8102 // ALOGD("%s", mTimestamp.toString().c_str());
8103
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008104 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07008105 ALOGE("read failed: framesRead=%zd", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008106 // Force input into standby so that it tries to recover at next read attempt
8107 inputStandBy();
8108 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008109 }
8110 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008111 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008112 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008113 ALOG_ASSERT(framesRead > 0);
Andy Hung6427e442018-08-09 12:51:02 -07008114 mFramesRead += framesRead;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008115
Andy Hung8946a282018-04-19 20:04:56 -07008116#ifdef TEE_SINK
8117 (void)mTee.write((uint8_t*)mRsmpInBuffer + rear * mFrameSize, framesRead);
8118#endif
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008119 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008120 {
8121 size_t part1 = mRsmpInFramesP2 - rear;
8122 if ((size_t) framesRead > part1) {
Andy Hung57446612015-04-19 23:56:46 -07008123 memcpy(mRsmpInBuffer, (uint8_t*)mRsmpInBuffer + mRsmpInFramesP2 * mFrameSize,
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008124 (framesRead - part1) * mFrameSize);
8125 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008126 }
Dean Wheatleyfd56e812020-11-06 22:32:21 +11008127 mRsmpInRear = audio_utils::safe_add_overflow(mRsmpInRear, (int32_t)framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008128
8129 size = activeTracks.size();
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008130
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008131 // loop over each active track
8132 for (size_t i = 0; i < size; i++) {
8133 activeTrack = activeTracks[i];
8134
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008135 // skip fast tracks, as those are handled directly by FastCapture
8136 if (activeTrack->isFastTrack()) {
8137 continue;
8138 }
8139
Andy Hung73c02e42015-03-29 01:13:58 -07008140 // TODO: This code probably should be moved to RecordTrack.
Andy Hung97a893e2015-03-29 01:03:07 -07008141 // TODO: Update the activeTrack buffer converter in case of reconfigure.
8142
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008143 enum {
8144 OVERRUN_UNKNOWN,
8145 OVERRUN_TRUE,
8146 OVERRUN_FALSE
8147 } overrun = OVERRUN_UNKNOWN;
8148
8149 // loop over getNextBuffer to handle circular sink
8150 for (;;) {
8151
8152 activeTrack->mSink.frameCount = ~0;
8153 status_t status = activeTrack->getNextBuffer(&activeTrack->mSink);
8154 size_t framesOut = activeTrack->mSink.frameCount;
8155 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
8156
Andy Hung73c02e42015-03-29 01:13:58 -07008157 // check available frames and handle overrun conditions
8158 // if the record track isn't draining fast enough.
8159 bool hasOverrun;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008160 size_t framesIn;
Andy Hung73c02e42015-03-29 01:13:58 -07008161 activeTrack->mResamplerBufferProvider->sync(&framesIn, &hasOverrun);
8162 if (hasOverrun) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008163 overrun = OVERRUN_TRUE;
8164 }
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08008165 if (framesOut == 0 || framesIn == 0) {
8166 break;
8167 }
8168
Andy Hung6770c6f2015-04-07 13:43:36 -07008169 // Don't allow framesOut to be larger than what is possible with resampling
8170 // from framesIn.
8171 // This isn't strictly necessary but helps limit buffer resizing in
8172 // RecordBufferConverter. TODO: remove when no longer needed.
8173 framesOut = min(framesOut,
8174 destinationFramesPossible(
8175 framesIn, mSampleRate, activeTrack->mSampleRate));
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008176
8177 if (activeTrack->isDirect()) {
Daniel Van Veen9e2376e2018-09-27 14:37:58 +10008178 // No RecordBufferConverter used for direct streams. Pass
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008179 // straight from RecordThread buffer to RecordTrack buffer.
8180 AudioBufferProvider::Buffer buffer;
8181 buffer.frameCount = framesOut;
8182 status_t status = activeTrack->mResamplerBufferProvider->getNextBuffer(&buffer);
8183 if (status == OK && buffer.frameCount != 0) {
8184 ALOGV_IF(buffer.frameCount != framesOut,
8185 "%s() read less than expected (%zu vs %zu)",
8186 __func__, buffer.frameCount, framesOut);
8187 framesOut = buffer.frameCount;
Daniel Van Veen9e2376e2018-09-27 14:37:58 +10008188 memcpy(activeTrack->mSink.raw, buffer.raw, buffer.frameCount * mFrameSize);
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008189 activeTrack->mResamplerBufferProvider->releaseBuffer(&buffer);
8190 } else {
8191 framesOut = 0;
8192 ALOGE("%s() cannot fill request, status: %d, frameCount: %zu",
8193 __func__, status, buffer.frameCount);
8194 }
8195 } else {
8196 // process frames from the RecordThread buffer provider to the RecordTrack
8197 // buffer
8198 framesOut = activeTrack->mRecordBufferConverter->convert(
8199 activeTrack->mSink.raw,
8200 activeTrack->mResamplerBufferProvider,
8201 framesOut);
8202 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008203
8204 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
8205 overrun = OVERRUN_FALSE;
8206 }
8207
8208 if (activeTrack->mFramesToDrop == 0) {
8209 if (framesOut > 0) {
8210 activeTrack->mSink.frameCount = framesOut;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008211 // Sanitize before releasing if the track has no access to the source data
8212 // An idle UID receives silence from non virtual devices until active
8213 if (activeTrack->isSilenced()) {
Jean-Michel Trividdf87ef2019-08-20 15:42:04 -07008214 memset(activeTrack->mSink.raw, 0, framesOut * activeTrack->frameSize());
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008215 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008216 activeTrack->releaseBuffer(&activeTrack->mSink);
8217 }
8218 } else {
8219 // FIXME could do a partial drop of framesOut
8220 if (activeTrack->mFramesToDrop > 0) {
Mikhail Naganov6d91ba52019-03-26 14:35:28 -07008221 activeTrack->mFramesToDrop -= (ssize_t)framesOut;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008222 if (activeTrack->mFramesToDrop <= 0) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08008223 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008224 }
8225 } else {
8226 activeTrack->mFramesToDrop += framesOut;
8227 if (activeTrack->mFramesToDrop >= 0 || activeTrack->mSyncStartEvent == 0 ||
8228 activeTrack->mSyncStartEvent->isCancelled()) {
8229 ALOGW("Synced record %s, session %d, trigger session %d",
8230 (activeTrack->mFramesToDrop >= 0) ? "timed out" : "cancelled",
8231 activeTrack->sessionId(),
8232 (activeTrack->mSyncStartEvent != 0) ?
Glenn Kastend848eb42016-03-08 13:42:11 -08008233 activeTrack->mSyncStartEvent->triggerSession() :
8234 AUDIO_SESSION_NONE);
Glenn Kasten25f4aa82014-02-07 10:50:43 -08008235 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008236 }
8237 }
8238 }
8239
8240 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008241 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008242 }
8243 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008244
8245 switch (overrun) {
8246 case OVERRUN_TRUE:
8247 // client isn't retrieving buffers fast enough
8248 if (!activeTrack->setOverflow()) {
8249 nsecs_t now = systemTime();
8250 // FIXME should lastWarning per track?
8251 if ((now - lastWarning) > kWarningThrottleNs) {
8252 ALOGW("RecordThread: buffer overflow");
8253 lastWarning = now;
8254 }
8255 }
8256 break;
8257 case OVERRUN_FALSE:
8258 activeTrack->clearOverflow();
8259 break;
8260 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008261 break;
8262 }
8263
Andy Hung3f0c9022016-01-15 17:49:46 -08008264 // update frame information and push timestamp out
8265 activeTrack->updateTrackFrameInfo(
Andy Hung6ae58432016-02-16 18:32:24 -08008266 activeTrack->mServerProxy->framesReleased(),
Andy Hung3f0c9022016-01-15 17:49:46 -08008267 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER],
8268 mSampleRate, mTimestamp);
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008269 }
8270
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008271unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08008272 // enable changes in effect chain
8273 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07008274 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurentcccbc762019-04-05 14:20:05 -07008275 if (audio_has_proportional_frames(mFormat)
8276 && loopCount == lastLoopCountRead + 1) {
8277 const int64_t readPeriodNs = lastIoEndNs - mLastIoEndNs;
8278 const double jitterMs =
8279 TimestampVerifier<int64_t, int64_t>::computeJitterMs(
8280 {framesRead, readPeriodNs},
8281 {0, 0} /* lastTimestamp */, mSampleRate);
8282 const double processMs = (lastIoBeginNs - mLastIoEndNs) * 1e-6;
8283
8284 Mutex::Autolock _l(mLock);
8285 mIoJitterMs.add(jitterMs);
8286 mProcessTimeMs.add(processMs);
8287 }
8288 // update timing info.
8289 mLastIoBeginNs = lastIoBeginNs;
8290 mLastIoEndNs = lastIoEndNs;
8291 lastLoopCountRead = loopCount;
Eric Laurent81784c32012-11-19 14:55:58 -08008292 }
8293
Glenn Kasten93e471f2013-08-19 08:40:07 -07008294 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08008295
8296 {
8297 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07008298 for (size_t i = 0; i < mTracks.size(); i++) {
8299 sp<RecordTrack> track = mTracks[i];
8300 track->invalidate();
8301 }
Glenn Kasten2b806402013-11-20 16:37:38 -08008302 mActiveTracks.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08008303 mStartStopCond.broadcast();
8304 }
8305
8306 releaseWakeLock();
8307
8308 ALOGV("RecordThread %p exiting", this);
8309 return false;
8310}
8311
Glenn Kasten93e471f2013-08-19 08:40:07 -07008312void AudioFlinger::RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08008313{
8314 if (!mStandby) {
8315 inputStandBy();
Andy Hungcf10d742020-04-28 15:38:24 -07008316 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07008317 mThreadSnapshot.onEnd();
Eric Laurent81784c32012-11-19 14:55:58 -08008318 mStandby = true;
8319 }
8320}
8321
8322void AudioFlinger::RecordThread::inputStandBy()
8323{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008324 // Idle the fast capture if it's currently running
8325 if (mFastCapture != 0) {
8326 FastCaptureStateQueue *sq = mFastCapture->sq();
8327 FastCaptureState *state = sq->begin();
8328 if (!(state->mCommand & FastCaptureState::IDLE)) {
8329 state->mCommand = FastCaptureState::COLD_IDLE;
8330 state->mColdFutexAddr = &mFastCaptureFutex;
8331 state->mColdGen++;
8332 mFastCaptureFutex = 0;
8333 sq->end();
8334 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
8335 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
8336#if 0
8337 if (kUseFastCapture == FastCapture_Dynamic) {
8338 // FIXME
8339 }
8340#endif
8341#ifdef AUDIO_WATCHDOG
8342 // FIXME
8343#endif
8344 } else {
8345 sq->end(false /*didModify*/);
8346 }
8347 }
Mikhail Naganov2534b382019-09-25 13:05:02 -07008348 status_t result = mSource->standby();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008349 ALOGE_IF(result != OK, "Error when putting input stream into standby: %d", result);
Andy Hungad6d52d2016-07-18 13:42:03 -07008350
8351 // If going into standby, flush the pipe source.
8352 if (mPipeSource.get() != nullptr) {
8353 const ssize_t flushed = mPipeSource->flush();
8354 if (flushed > 0) {
8355 ALOGV("Input standby flushed PipeSource %zd frames", flushed);
8356 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += flushed;
8357 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
8358 }
8359 }
Eric Laurent81784c32012-11-19 14:55:58 -08008360}
8361
Glenn Kasten05997e22014-03-13 15:08:33 -07008362// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastene198c362013-08-13 09:13:36 -07008363sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
Eric Laurent81784c32012-11-19 14:55:58 -08008364 const sp<AudioFlinger::Client>& client,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07008365 const audio_attributes_t& attr,
Eric Laurentf14db3c2017-12-08 14:20:36 -08008366 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08008367 audio_format_t format,
8368 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08008369 size_t *pFrameCount,
Glenn Kastend848eb42016-03-08 13:42:11 -08008370 audio_session_t sessionId,
Eric Laurentf14db3c2017-12-08 14:20:36 -08008371 size_t *pNotificationFrameCount,
Eric Laurent09f1ed22019-04-24 17:45:17 -07008372 pid_t creatorPid,
Svet Ganov33761132021-05-13 22:51:08 +00008373 const AttributionSourceState& attributionSource,
Eric Laurent05067782016-06-01 18:27:28 -07008374 audio_input_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08008375 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08008376 status_t *status,
Eric Laurentec376dc2021-04-08 20:41:22 +02008377 audio_port_handle_t portId,
8378 int32_t maxSharedAudioHistoryMs)
Eric Laurent81784c32012-11-19 14:55:58 -08008379{
Glenn Kasten74935e42013-12-19 08:56:45 -08008380 size_t frameCount = *pFrameCount;
Eric Laurentf14db3c2017-12-08 14:20:36 -08008381 size_t notificationFrameCount = *pNotificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08008382 sp<RecordTrack> track;
8383 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07008384 audio_input_flags_t inputFlags = mInput->flags;
Eric Laurentf14db3c2017-12-08 14:20:36 -08008385 audio_input_flags_t requestedFlags = *flags;
8386 uint32_t sampleRate;
Eric Laurentc5166b22022-10-21 11:36:32 +02008387 AttributionSourceState checkedAttributionSource = AudioFlinger::checkAttributionSourcePackage(
8388 attributionSource);
Eric Laurentf14db3c2017-12-08 14:20:36 -08008389
8390 lStatus = initCheck();
8391 if (lStatus != NO_ERROR) {
8392 ALOGE("createRecordTrack_l() audio driver not initialized");
8393 goto Exit;
8394 }
8395
Mikhail Naganovce9f2652018-07-16 11:09:24 -07008396 if (!audio_is_linear_pcm(mFormat) && (*flags & AUDIO_INPUT_FLAG_DIRECT) == 0) {
8397 ALOGE("createRecordTrack_l() on an encoded stream requires AUDIO_INPUT_FLAG_DIRECT");
8398 lStatus = BAD_VALUE;
8399 goto Exit;
8400 }
8401
Eric Laurentec376dc2021-04-08 20:41:22 +02008402 if (maxSharedAudioHistoryMs != 0) {
Eric Laurentc5166b22022-10-21 11:36:32 +02008403 if (!captureHotwordAllowed(checkedAttributionSource)) {
Eric Laurentec376dc2021-04-08 20:41:22 +02008404 lStatus = PERMISSION_DENIED;
8405 goto Exit;
8406 }
Eric Laurentec376dc2021-04-08 20:41:22 +02008407 if (maxSharedAudioHistoryMs < 0
8408 || maxSharedAudioHistoryMs > AudioFlinger::kMaxSharedAudioHistoryMs) {
8409 lStatus = BAD_VALUE;
8410 goto Exit;
8411 }
8412 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08008413 if (*pSampleRate == 0) {
8414 *pSampleRate = mSampleRate;
8415 }
8416 sampleRate = *pSampleRate;
Eric Laurent05067782016-06-01 18:27:28 -07008417
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008418 // special case for FAST flag considered OK if fast capture is present and access to
8419 // audio history is not required
8420 if (hasFastCapture() && mMaxSharedAudioHistoryMs == 0) {
Eric Laurent05067782016-06-01 18:27:28 -07008421 inputFlags = (audio_input_flags_t)(inputFlags | AUDIO_INPUT_FLAG_FAST);
8422 }
8423
Eric Laurentf14db3c2017-12-08 14:20:36 -08008424 // Check if requested flags are compatible with input stream flags
Eric Laurent05067782016-06-01 18:27:28 -07008425 if ((*flags & inputFlags) != *flags) {
8426 ALOGW("createRecordTrack_l(): mismatch between requested flags (%08x) and"
8427 " input flags (%08x)",
8428 *flags, inputFlags);
8429 *flags = (audio_input_flags_t)(*flags & inputFlags);
8430 }
Eric Laurent81784c32012-11-19 14:55:58 -08008431
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008432 // client expresses a preference for FAST and no access to audio history,
8433 // but we get the final say
8434 if (*flags & AUDIO_INPUT_FLAG_FAST && maxSharedAudioHistoryMs == 0) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07008435 if (
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07008436 // we formerly checked for a callback handler (non-0 tid),
8437 // but that is no longer required for TRANSFER_OBTAIN mode
jiabinb00edc32021-08-16 16:27:54 +00008438 // No need to match hardware format, format conversion will be done in client side.
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07008439 //
Phil Burk7ed66a12019-04-18 13:20:30 -07008440 // Frame count is not specified (0), or is less than or equal the pipe depth.
8441 // It is OK to provide a higher capacity than requested.
8442 // We will force it to mPipeFramesP2 below.
8443 (frameCount <= mPipeFramesP2) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07008444 // PCM data
8445 audio_is_linear_pcm(format) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08008446 // hardware channel mask
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008447 (channelMask == mChannelMask) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08008448 // hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07008449 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07008450 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008451 hasFastCapture() &&
8452 // there are sufficient fast track slots available
8453 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07008454 ) {
Eric Laurent4c415062016-06-17 16:14:16 -07008455 // check compatibility with audio effects.
8456 Mutex::Autolock _l(mLock);
8457 // Do not accept FAST flag if the session has software effects
8458 sp<EffectChain> chain = getEffectChain_l(sessionId);
8459 if (chain != 0) {
Andy Hungd3bb0ad2016-10-11 17:16:43 -07008460 audio_input_flags_t old = *flags;
8461 chain->checkInputFlagCompatibility(flags);
8462 if (old != *flags) {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008463 ALOGV("%p AUDIO_INPUT_FLAGS denied by effect old=%#x new=%#x",
8464 this, (int)old, (int)*flags);
Eric Laurent4c415062016-06-17 16:14:16 -07008465 }
8466 }
Eric Laurent122f7e72016-06-29 11:53:29 -07008467 ALOGV_IF((*flags & AUDIO_INPUT_FLAG_FAST) != 0,
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008468 "%p AUDIO_INPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
8469 this, frameCount, mFrameCount);
Glenn Kasten90e58b12013-07-31 16:16:02 -07008470 } else {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008471 ALOGV("%p AUDIO_INPUT_FLAG_FAST denied: frameCount=%zu mFrameCount=%zu mPipeFramesP2=%zu "
8472 "format=%#x isLinear=%d mFormat=%#x channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008473 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008474 this, frameCount, mFrameCount, mPipeFramesP2,
8475 format, audio_is_linear_pcm(format), mFormat, channelMask, sampleRate, mSampleRate,
Glenn Kasten74105912014-07-03 12:28:53 -07008476 hasFastCapture(), tid, mFastTrackAvail);
Eric Laurent05067782016-06-01 18:27:28 -07008477 *flags = (audio_input_flags_t)(*flags & ~AUDIO_INPUT_FLAG_FAST);
Glenn Kasten74105912014-07-03 12:28:53 -07008478 }
8479 }
8480
Eric Laurentf14db3c2017-12-08 14:20:36 -08008481 // If FAST or RAW flags were corrected, ask caller to request new input from audio policy
8482 if ((*flags & AUDIO_INPUT_FLAG_FAST) !=
8483 (requestedFlags & AUDIO_INPUT_FLAG_FAST)) {
8484 *flags = (audio_input_flags_t) (*flags & ~(AUDIO_INPUT_FLAG_FAST | AUDIO_INPUT_FLAG_RAW));
8485 lStatus = BAD_TYPE;
8486 goto Exit;
8487 }
8488
Glenn Kasten74105912014-07-03 12:28:53 -07008489 // compute track buffer size in frames, and suggest the notification frame count
Eric Laurent05067782016-06-01 18:27:28 -07008490 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten74105912014-07-03 12:28:53 -07008491 // fast track: frame count is exactly the pipe depth
8492 frameCount = mPipeFramesP2;
8493 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
Eric Laurentf14db3c2017-12-08 14:20:36 -08008494 notificationFrameCount = mFrameCount;
Glenn Kasten74105912014-07-03 12:28:53 -07008495 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07008496 // not fast track: max notification period is resampled equivalent of one HAL buffer time
8497 // or 20 ms if there is a fast capture
8498 // TODO This could be a roundupRatio inline, and const
8499 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
8500 * sampleRate + mSampleRate - 1) / mSampleRate;
8501 // minimum number of notification periods is at least kMinNotifications,
8502 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
8503 static const size_t kMinNotifications = 3;
8504 static const uint32_t kMinMs = 30;
8505 // TODO This could be a roundupRatio inline
8506 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
8507 // TODO This could be a roundupRatio inline
8508 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
8509 maxNotificationFrames;
8510 const size_t minFrameCount = maxNotificationFrames *
8511 max(kMinNotifications, minNotificationsByMs);
8512 frameCount = max(frameCount, minFrameCount);
Eric Laurentf14db3c2017-12-08 14:20:36 -08008513 if (notificationFrameCount == 0 || notificationFrameCount > maxNotificationFrames) {
8514 notificationFrameCount = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07008515 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07008516 }
Glenn Kasten74935e42013-12-19 08:56:45 -08008517 *pFrameCount = frameCount;
Eric Laurentf14db3c2017-12-08 14:20:36 -08008518 *pNotificationFrameCount = notificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08008519
8520 { // scope for mLock
8521 Mutex::Autolock _l(mLock);
Eric Laurent2407ce32021-04-26 14:56:03 +02008522 int32_t startFrames = -1;
Eric Laurentec376dc2021-04-08 20:41:22 +02008523 if (!mSharedAudioPackageName.empty()
Eric Laurentc5166b22022-10-21 11:36:32 +02008524 && mSharedAudioPackageName == checkedAttributionSource.packageName
Eric Laurentec376dc2021-04-08 20:41:22 +02008525 && mSharedAudioSessionId == sessionId
Eric Laurentc5166b22022-10-21 11:36:32 +02008526 && captureHotwordAllowed(checkedAttributionSource)) {
Eric Laurent2407ce32021-04-26 14:56:03 +02008527 startFrames = mSharedAudioStartFrames;
Eric Laurentec376dc2021-04-08 20:41:22 +02008528 }
Eric Laurent81784c32012-11-19 14:55:58 -08008529
Kevin Rocard1f564ac2018-03-29 13:53:10 -07008530 track = new RecordTrack(this, client, attr, sampleRate,
Andy Hung8fe68032017-06-05 16:17:51 -07008531 format, channelMask, frameCount,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07008532 nullptr /* buffer */, (size_t)0 /* bufferSize */, sessionId, creatorPid,
Eric Laurentc5166b22022-10-21 11:36:32 +02008533 checkedAttributionSource, *flags, TrackBase::TYPE_DEFAULT, portId,
Svet Ganov33761132021-05-13 22:51:08 +00008534 startFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08008535
Glenn Kasten03003332013-08-06 15:40:54 -07008536 lStatus = track->initCheck();
8537 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07008538 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08008539 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08008540 goto Exit;
8541 }
8542 mTracks.add(track);
8543
Eric Laurent05067782016-06-01 18:27:28 -07008544 if ((*flags & AUDIO_INPUT_FLAG_FAST) && (tid != -1)) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07008545 pid_t callingPid = IPCThreadState::self()->getCallingPid();
8546 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
8547 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07008548 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Glenn Kasten90e58b12013-07-31 16:16:02 -07008549 }
Eric Laurentec376dc2021-04-08 20:41:22 +02008550
8551 if (maxSharedAudioHistoryMs != 0) {
8552 sendResizeBufferConfigEvent_l(maxSharedAudioHistoryMs);
8553 }
Eric Laurent81784c32012-11-19 14:55:58 -08008554 }
Glenn Kasten05997e22014-03-13 15:08:33 -07008555
Eric Laurent81784c32012-11-19 14:55:58 -08008556 lStatus = NO_ERROR;
8557
8558Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07008559 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08008560 return track;
8561}
8562
8563status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
8564 AudioSystem::sync_event_t event,
Glenn Kastend848eb42016-03-08 13:42:11 -08008565 audio_session_t triggerSession)
Eric Laurent81784c32012-11-19 14:55:58 -08008566{
8567 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
8568 sp<ThreadBase> strongMe = this;
8569 status_t status = NO_ERROR;
8570
8571 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08008572 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08008573 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008574 recordTrack->mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
Eric Laurent81784c32012-11-19 14:55:58 -08008575 triggerSession,
8576 recordTrack->sessionId(),
8577 syncStartEventCallback,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008578 recordTrack);
Eric Laurent81784c32012-11-19 14:55:58 -08008579 // Sync event can be cancelled by the trigger session if the track is not in a
8580 // compatible state in which case we start record immediately
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008581 if (recordTrack->mSyncStartEvent->isCancelled()) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08008582 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08008583 } else {
8584 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
Ivan Lozano1b35dd62017-12-06 16:55:10 -08008585 recordTrack->mFramesToDrop = -(ssize_t)
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08008586 ((AudioSystem::kSyncRecordStartTimeOutMs * recordTrack->mSampleRate) / 1000);
Eric Laurent81784c32012-11-19 14:55:58 -08008587 }
8588 }
8589
8590 {
Glenn Kasten47c20702013-08-13 15:37:35 -07008591 // This section is a rendezvous between binder thread executing start() and RecordThread
Eric Laurent81784c32012-11-19 14:55:58 -08008592 AutoMutex lock(mLock);
Andy Hungce685402018-10-05 17:23:27 -07008593 if (recordTrack->isInvalid()) {
8594 recordTrack->clearSyncStartEvent();
Eric Laurentd52a28c2020-08-21 17:10:39 -07008595 ALOGW("%s track %d: invalidated before startInput", __func__, recordTrack->portId());
8596 return DEAD_OBJECT;
Andy Hungce685402018-10-05 17:23:27 -07008597 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008598 if (mActiveTracks.indexOf(recordTrack) >= 0) {
8599 if (recordTrack->mState == TrackBase::PAUSING) {
Andy Hungce685402018-10-05 17:23:27 -07008600 // We haven't stopped yet (moved to PAUSED and not in mActiveTracks)
8601 // so no need to startInput().
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008602 ALOGV("active record track PAUSING -> ACTIVE");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008603 recordTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008604 } else {
Andy Hung959b5b82021-09-24 10:46:20 -07008605 ALOGV("active record track state %d", (int)recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08008606 }
8607 return status;
8608 }
8609
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08008610 // TODO consider other ways of handling this, such as changing the state to :STARTING and
8611 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
8612 // or using a separate command thread
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008613 recordTrack->mState = TrackBase::STARTING_1;
Glenn Kasten2b806402013-11-20 16:37:38 -08008614 mActiveTracks.add(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07008615 status_t status = NO_ERROR;
8616 if (recordTrack->isExternalTrack()) {
8617 mLock.unlock();
Eric Laurent4eb58f12018-12-07 16:41:02 -08008618 status = AudioSystem::startInput(recordTrack->portId());
Eric Laurent83b88082014-06-20 18:31:16 -07008619 mLock.lock();
Andy Hungce685402018-10-05 17:23:27 -07008620 if (recordTrack->isInvalid()) {
8621 recordTrack->clearSyncStartEvent();
8622 if (status == NO_ERROR && recordTrack->mState == TrackBase::STARTING_1) {
8623 recordTrack->mState = TrackBase::STARTING_2;
8624 // STARTING_2 forces destroy to call stopInput.
8625 }
Eric Laurentd52a28c2020-08-21 17:10:39 -07008626 ALOGW("%s track %d: invalidated after startInput", __func__, recordTrack->portId());
8627 return DEAD_OBJECT;
Andy Hungce685402018-10-05 17:23:27 -07008628 }
8629 if (recordTrack->mState != TrackBase::STARTING_1) {
8630 ALOGW("%s(%d): unsynchronized mState:%d change",
Andy Hung959b5b82021-09-24 10:46:20 -07008631 __func__, recordTrack->id(), (int)recordTrack->mState);
Andy Hungce685402018-10-05 17:23:27 -07008632 // Someone else has changed state, let them take over,
8633 // leave mState in the new state.
8634 recordTrack->clearSyncStartEvent();
8635 return INVALID_OPERATION;
8636 }
8637 // we're ok, but perhaps startInput has failed
Eric Laurent83b88082014-06-20 18:31:16 -07008638 if (status != NO_ERROR) {
Andy Hungce685402018-10-05 17:23:27 -07008639 ALOGW("%s(%d): startInput failed, status %d",
8640 __func__, recordTrack->id(), status);
8641 // We are in ActiveTracks if STARTING_1 and valid, so remove from ActiveTracks,
8642 // leave in STARTING_1, so destroy() will not call stopInput.
Eric Laurent83b88082014-06-20 18:31:16 -07008643 mActiveTracks.remove(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07008644 recordTrack->clearSyncStartEvent();
Eric Laurent83b88082014-06-20 18:31:16 -07008645 return status;
8646 }
Eric Laurent09f1ed22019-04-24 17:45:17 -07008647 sendIoConfigEvent_l(
8648 AUDIO_CLIENT_STARTED, recordTrack->creatorPid(), recordTrack->portId());
Eric Laurent81784c32012-11-19 14:55:58 -08008649 }
Andy Hungc2b11cb2020-04-22 09:04:01 -07008650
8651 recordTrack->logBeginInterval(patchSourcesToString(&mPatch)); // log to MediaMetrics
8652
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008653 // Catch up with current buffer indices if thread is already running.
8654 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
8655 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
8656 // see previously buffered data before it called start(), but with greater risk of overrun.
8657
Andy Hung73c02e42015-03-29 01:13:58 -07008658 recordTrack->mResamplerBufferProvider->reset();
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008659 if (!recordTrack->isDirect()) {
8660 // clear any converter state as new data will be discontinuous
8661 recordTrack->mRecordBufferConverter->reset();
8662 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008663 recordTrack->mState = TrackBase::STARTING_2;
Eric Laurent81784c32012-11-19 14:55:58 -08008664 // signal thread to start
Eric Laurent81784c32012-11-19 14:55:58 -08008665 mWaitWorkCV.broadcast();
Eric Laurent81784c32012-11-19 14:55:58 -08008666 return status;
8667 }
Eric Laurent81784c32012-11-19 14:55:58 -08008668}
8669
Eric Laurent81784c32012-11-19 14:55:58 -08008670void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
8671{
8672 sp<SyncEvent> strongEvent = event.promote();
8673
8674 if (strongEvent != 0) {
Eric Laurent8ea16e42014-02-20 16:26:11 -08008675 sp<RefBase> ptr = strongEvent->cookie().promote();
8676 if (ptr != 0) {
8677 RecordTrack *recordTrack = (RecordTrack *)ptr.get();
8678 recordTrack->handleSyncStartEvent(strongEvent);
8679 }
Eric Laurent81784c32012-11-19 14:55:58 -08008680 }
8681}
8682
Glenn Kastena8356f62013-07-25 14:37:52 -07008683bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08008684 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07008685 AutoMutex _l(mLock);
Andy Hungce685402018-10-05 17:23:27 -07008686 // if we're invalid, we can't be on the ActiveTracks.
Jean-Michel Trivi38f86712017-04-11 14:10:17 -07008687 if (mActiveTracks.indexOf(recordTrack) < 0 || recordTrack->mState == TrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08008688 return false;
8689 }
Glenn Kasten47c20702013-08-13 15:37:35 -07008690 // note that threadLoop may still be processing the track at this point [without lock]
Eric Laurent81784c32012-11-19 14:55:58 -08008691 recordTrack->mState = TrackBase::PAUSING;
Andy Hungce685402018-10-05 17:23:27 -07008692
Andy Hungabfab202019-03-07 19:45:54 -08008693 // NOTE: Waiting here is important to keep stop synchronous.
8694 // This is needed for proper patchRecord peer release.
Andy Hungce685402018-10-05 17:23:27 -07008695 while (recordTrack->mState == TrackBase::PAUSING && !recordTrack->isInvalid()) {
8696 mWaitWorkCV.broadcast(); // signal thread to stop
8697 mStartStopCond.wait(mLock);
Eric Laurent81784c32012-11-19 14:55:58 -08008698 }
Andy Hungce685402018-10-05 17:23:27 -07008699
8700 if (recordTrack->mState == TrackBase::PAUSED) { // successful stop
Eric Laurent81784c32012-11-19 14:55:58 -08008701 ALOGV("Record stopped OK");
8702 return true;
8703 }
Andy Hungce685402018-10-05 17:23:27 -07008704
8705 // don't handle anything - we've been invalidated or restarted and in a different state
8706 ALOGW_IF("%s(%d): unsynchronized stop, state: %d",
8707 __func__, recordTrack->id(), recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08008708 return false;
8709}
8710
Glenn Kasten0f11b512014-01-31 16:18:54 -08008711bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
Eric Laurent81784c32012-11-19 14:55:58 -08008712{
8713 return false;
8714}
8715
Glenn Kasten0f11b512014-01-31 16:18:54 -08008716status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08008717{
8718#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
8719 if (!isValidSyncEvent(event)) {
8720 return BAD_VALUE;
8721 }
8722
Glenn Kastend848eb42016-03-08 13:42:11 -08008723 audio_session_t eventSession = event->triggerSession();
Eric Laurent81784c32012-11-19 14:55:58 -08008724 status_t ret = NAME_NOT_FOUND;
8725
8726 Mutex::Autolock _l(mLock);
8727
8728 for (size_t i = 0; i < mTracks.size(); i++) {
8729 sp<RecordTrack> track = mTracks[i];
8730 if (eventSession == track->sessionId()) {
8731 (void) track->setSyncEvent(event);
8732 ret = NO_ERROR;
8733 }
8734 }
8735 return ret;
8736#else
8737 return BAD_VALUE;
8738#endif
8739}
8740
jiabin653cc0a2018-01-17 17:54:10 -08008741status_t AudioFlinger::RecordThread::getActiveMicrophones(
8742 std::vector<media::MicrophoneInfo>* activeMicrophones)
8743{
8744 ALOGV("RecordThread::getActiveMicrophones");
8745 AutoMutex _l(mLock);
Jasmine Chaeaa10e42021-05-11 10:11:14 +08008746 if (!isStreamInitialized()) {
Paul McLean8a661a32021-04-12 10:21:42 -06008747 return NO_INIT;
8748 }
jiabin9ff780e2018-03-19 18:19:52 -07008749 status_t status = mInput->stream->getActiveMicrophones(activeMicrophones);
8750 return status;
jiabin653cc0a2018-01-17 17:54:10 -08008751}
8752
Paul McLean12340082019-03-19 09:35:05 -06008753status_t AudioFlinger::RecordThread::setPreferredMicrophoneDirection(
8754 audio_microphone_direction_t direction)
Paul McLean03a6e6a2018-12-04 10:54:13 -07008755{
Paul McLean12340082019-03-19 09:35:05 -06008756 ALOGV("setPreferredMicrophoneDirection(%d)", direction);
Paul McLean03a6e6a2018-12-04 10:54:13 -07008757 AutoMutex _l(mLock);
Jasmine Chaeaa10e42021-05-11 10:11:14 +08008758 if (!isStreamInitialized()) {
Paul McLean8a661a32021-04-12 10:21:42 -06008759 return NO_INIT;
8760 }
Paul McLean12340082019-03-19 09:35:05 -06008761 return mInput->stream->setPreferredMicrophoneDirection(direction);
Paul McLean03a6e6a2018-12-04 10:54:13 -07008762}
8763
Paul McLean12340082019-03-19 09:35:05 -06008764status_t AudioFlinger::RecordThread::setPreferredMicrophoneFieldDimension(float zoom)
Paul McLean03a6e6a2018-12-04 10:54:13 -07008765{
Paul McLean12340082019-03-19 09:35:05 -06008766 ALOGV("setPreferredMicrophoneFieldDimension(%f)", zoom);
Paul McLean03a6e6a2018-12-04 10:54:13 -07008767 AutoMutex _l(mLock);
Jasmine Chaeaa10e42021-05-11 10:11:14 +08008768 if (!isStreamInitialized()) {
Paul McLean8a661a32021-04-12 10:21:42 -06008769 return NO_INIT;
8770 }
Paul McLean12340082019-03-19 09:35:05 -06008771 return mInput->stream->setPreferredMicrophoneFieldDimension(zoom);
Paul McLean03a6e6a2018-12-04 10:54:13 -07008772}
8773
Eric Laurentec376dc2021-04-08 20:41:22 +02008774status_t AudioFlinger::RecordThread::shareAudioHistory(
8775 const std::string& sharedAudioPackageName, audio_session_t sharedSessionId,
8776 int64_t sharedAudioStartMs) {
8777 AutoMutex _l(mLock);
8778 return shareAudioHistory_l(sharedAudioPackageName, sharedSessionId, sharedAudioStartMs);
8779}
8780
8781status_t AudioFlinger::RecordThread::shareAudioHistory_l(
8782 const std::string& sharedAudioPackageName, audio_session_t sharedSessionId,
8783 int64_t sharedAudioStartMs) {
Eric Laurent92d0a322021-07-16 15:32:33 +02008784
Eric Laurentec376dc2021-04-08 20:41:22 +02008785 if ((hasAudioSession_l(sharedSessionId) & ThreadBase::TRACK_SESSION) == 0) {
8786 return BAD_VALUE;
8787 }
Eric Laurent2407ce32021-04-26 14:56:03 +02008788
8789 if (sharedAudioStartMs < 0
8790 || sharedAudioStartMs > INT64_MAX / mSampleRate) {
Eric Laurentec376dc2021-04-08 20:41:22 +02008791 return BAD_VALUE;
8792 }
8793
Eric Laurent2407ce32021-04-26 14:56:03 +02008794 // Current implementation of the input resampling buffer wraps around indexes at 32 bit.
8795 // As we cannot detect more than one wraparound, only accept values up current write position
8796 // after one wraparound
8797 // We assume recent wraparounds on mRsmpInRear only given it is unlikely that the requesting
8798 // app waits several hours after the start time was computed.
Eric Laurent92d0a322021-07-16 15:32:33 +02008799 int64_t sharedAudioStartFrames = sharedAudioStartMs * mSampleRate / 1000;
Eric Laurent2407ce32021-04-26 14:56:03 +02008800 const int32_t sharedOffset = audio_utils::safe_sub_overflow(mRsmpInRear,
8801 (int32_t)sharedAudioStartFrames);
Eric Laurent92d0a322021-07-16 15:32:33 +02008802 // Bring the start frame position within the input buffer to match the documented
8803 // "best effort" behavior of the API.
8804 if (sharedOffset < 0) {
8805 sharedAudioStartFrames = mRsmpInRear;
8806 } else if (sharedOffset > mRsmpInFrames) {
8807 sharedAudioStartFrames =
8808 audio_utils::safe_sub_overflow(mRsmpInRear, (int32_t)mRsmpInFrames);
Eric Laurent2407ce32021-04-26 14:56:03 +02008809 }
8810
Eric Laurentec376dc2021-04-08 20:41:22 +02008811 mSharedAudioPackageName = sharedAudioPackageName;
8812 if (mSharedAudioPackageName.empty()) {
Eric Laurent92d0a322021-07-16 15:32:33 +02008813 resetAudioHistory_l();
Eric Laurentec376dc2021-04-08 20:41:22 +02008814 } else {
8815 mSharedAudioSessionId = sharedSessionId;
Eric Laurent2407ce32021-04-26 14:56:03 +02008816 mSharedAudioStartFrames = (int32_t)sharedAudioStartFrames;
Eric Laurentec376dc2021-04-08 20:41:22 +02008817 }
8818 return NO_ERROR;
8819}
8820
Eric Laurent92d0a322021-07-16 15:32:33 +02008821void AudioFlinger::RecordThread::resetAudioHistory_l() {
8822 mSharedAudioSessionId = AUDIO_SESSION_NONE;
8823 mSharedAudioStartFrames = -1;
8824 mSharedAudioPackageName = "";
8825}
8826
Kevin Rocard069c2712018-03-29 19:09:14 -07008827void AudioFlinger::RecordThread::updateMetadata_l()
8828{
Jasmine Chaeaa10e42021-05-11 10:11:14 +08008829 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
8830 return; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -07008831 }
8832 StreamInHalInterface::SinkMetadata metadata;
Eric Laurent78b07302022-10-07 16:20:34 +02008833 auto backInserter = std::back_inserter(metadata.tracks);
Kevin Rocard069c2712018-03-29 19:09:14 -07008834 for (const sp<RecordTrack> &track : mActiveTracks) {
Eric Laurent78b07302022-10-07 16:20:34 +02008835 track->copyMetadataTo(backInserter);
Kevin Rocard069c2712018-03-29 19:09:14 -07008836 }
8837 mInput->stream->updateSinkMetadata(metadata);
8838}
8839
Eric Laurent81784c32012-11-19 14:55:58 -08008840// destroyTrack_l() must be called with ThreadBase::mLock held
8841void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
8842{
Eric Laurentbfb1b832013-01-07 09:53:42 -08008843 track->terminate();
8844 track->mState = TrackBase::STOPPED;
Eric Laurentec376dc2021-04-08 20:41:22 +02008845
Eric Laurent81784c32012-11-19 14:55:58 -08008846 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08008847 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08008848 removeTrack_l(track);
8849 }
8850}
8851
8852void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
8853{
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008854 String8 result;
8855 track->appendDump(result, false /* active */);
8856 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.string());
8857
Eric Laurent81784c32012-11-19 14:55:58 -08008858 mTracks.remove(track);
8859 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008860 if (track->isFastTrack()) {
8861 ALOG_ASSERT(!mFastTrackAvail);
8862 mFastTrackAvail = true;
8863 }
Eric Laurent81784c32012-11-19 14:55:58 -08008864}
8865
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07008866void AudioFlinger::RecordThread::dumpInternals_l(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08008867{
Mikhail Naganov913d06c2016-11-01 12:49:22 -07008868 AudioStreamIn *input = mInput;
8869 audio_input_flags_t flags = input != NULL ? input->flags : AUDIO_INPUT_FLAG_NONE;
8870 dprintf(fd, " AudioStreamIn: %p flags %#x (%s)\n",
Andy Hung9b181952019-02-25 14:53:36 -08008871 input, flags, toString(flags).c_str());
Andy Hung6427e442018-08-09 12:51:02 -07008872 dprintf(fd, " Frames read: %lld\n", (long long)mFramesRead);
Eric Tan39ec8d62018-07-24 09:49:29 -07008873 if (mActiveTracks.isEmpty()) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07008874 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08008875 }
Andy Hungbfa64962017-06-12 14:43:19 -07008876
8877 if (input != nullptr) {
8878 dprintf(fd, " Hal stream dump:\n");
8879 (void)input->stream->dump(fd);
8880 }
8881
Glenn Kasten6e6704c2014-07-03 10:20:00 -07008882 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008883 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Glenn Kasten17c9c992015-03-02 15:53:01 -08008884
Glenn Kasten2f90c512015-12-02 11:40:09 -08008885 // Make a non-atomic copy of fast capture dump state so it won't change underneath us
8886 // while we are dumping it. It may be inconsistent, but it won't mutate!
8887 // This is a large object so we place it on the heap.
8888 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
Eric Tan2942a4e2018-09-12 17:41:27 -07008889 const std::unique_ptr<FastCaptureDumpState> copy =
8890 std::make_unique<FastCaptureDumpState>(mFastCaptureDumpState);
Glenn Kasten2f90c512015-12-02 11:40:09 -08008891 copy->dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08008892}
8893
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07008894void AudioFlinger::RecordThread::dumpTracks_l(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08008895{
Eric Laurent81784c32012-11-19 14:55:58 -08008896 String8 result;
Marco Nelissenb2208842014-02-07 14:00:50 -08008897 size_t numtracks = mTracks.size();
8898 size_t numactive = mActiveTracks.size();
8899 size_t numactiveseen = 0;
Glenn Kastenc42e9b42016-03-21 11:35:03 -07008900 dprintf(fd, " %zu Tracks", numtracks);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008901 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08008902 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07008903 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008904 result.append(prefix);
Andy Hung000adb52018-06-01 15:43:26 -07008905 mTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08008906 for (size_t i = 0; i < numtracks ; ++i) {
8907 sp<RecordTrack> track = mTracks[i];
8908 if (track != 0) {
8909 bool active = mActiveTracks.indexOf(track) >= 0;
8910 if (active) {
8911 numactiveseen++;
8912 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008913 result.append(prefix);
8914 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08008915 }
Eric Laurent81784c32012-11-19 14:55:58 -08008916 }
Marco Nelissenb2208842014-02-07 14:00:50 -08008917 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07008918 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08008919 }
8920
Marco Nelissenb2208842014-02-07 14:00:50 -08008921 if (numactiveseen != numactive) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008922 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08008923 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008924 result.append(prefix);
Andy Hung000adb52018-06-01 15:43:26 -07008925 mActiveTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08008926 for (size_t i = 0; i < numactive; ++i) {
Glenn Kasten2b806402013-11-20 16:37:38 -08008927 sp<RecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08008928 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008929 result.append(prefix);
8930 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08008931 }
Glenn Kasten2b806402013-11-20 16:37:38 -08008932 }
Eric Laurent81784c32012-11-19 14:55:58 -08008933
8934 }
8935 write(fd, result.string(), result.size());
8936}
8937
Eric Laurent5ada82e2019-08-29 17:53:54 -07008938void AudioFlinger::RecordThread::setRecordSilenced(audio_port_handle_t portId, bool silenced)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008939{
8940 Mutex::Autolock _l(mLock);
8941 for (size_t i = 0; i < mTracks.size() ; i++) {
8942 sp<RecordTrack> track = mTracks[i];
Eric Laurent5ada82e2019-08-29 17:53:54 -07008943 if (track != 0 && track->portId() == portId) {
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008944 track->setSilenced(silenced);
8945 }
8946 }
8947}
Andy Hung73c02e42015-03-29 01:13:58 -07008948
8949void AudioFlinger::RecordThread::ResamplerBufferProvider::reset()
8950{
8951 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
8952 RecordThread *recordThread = (RecordThread *) threadBase.get();
Andy Hung73c02e42015-03-29 01:13:58 -07008953 mRsmpInUnrel = 0;
Eric Laurentec376dc2021-04-08 20:41:22 +02008954 const int32_t rear = recordThread->mRsmpInRear;
8955 ssize_t deltaFrames = 0;
Eric Laurent2407ce32021-04-26 14:56:03 +02008956 if (mRecordTrack->startFrames() >= 0) {
8957 int32_t startFrames = mRecordTrack->startFrames();
8958 // Accept a recent wraparound of mRsmpInRear
8959 if (startFrames <= rear) {
8960 deltaFrames = rear - startFrames;
8961 } else {
8962 deltaFrames = (int32_t)((int64_t)rear + UINT32_MAX + 1 - startFrames);
Eric Laurentec376dc2021-04-08 20:41:22 +02008963 }
Eric Laurentec376dc2021-04-08 20:41:22 +02008964 // start frame cannot be further in the past than start of resampling buffer
8965 if ((size_t) deltaFrames > recordThread->mRsmpInFrames) {
8966 deltaFrames = recordThread->mRsmpInFrames;
8967 }
8968 }
8969 mRsmpInFront = audio_utils::safe_sub_overflow(rear, static_cast<int32_t>(deltaFrames));
Andy Hung73c02e42015-03-29 01:13:58 -07008970}
8971
8972void AudioFlinger::RecordThread::ResamplerBufferProvider::sync(
8973 size_t *framesAvailable, bool *hasOverrun)
8974{
8975 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
8976 RecordThread *recordThread = (RecordThread *) threadBase.get();
8977 const int32_t rear = recordThread->mRsmpInRear;
8978 const int32_t front = mRsmpInFront;
Hongwei Wang95e37682019-04-12 11:13:36 -07008979 const ssize_t filled = audio_utils::safe_sub_overflow(rear, front);
Andy Hung73c02e42015-03-29 01:13:58 -07008980
8981 size_t framesIn;
8982 bool overrun = false;
8983 if (filled < 0) {
8984 // should not happen, but treat like a massive overrun and re-sync
8985 framesIn = 0;
8986 mRsmpInFront = rear;
8987 overrun = true;
8988 } else if ((size_t) filled <= recordThread->mRsmpInFrames) {
8989 framesIn = (size_t) filled;
8990 } else {
8991 // client is not keeping up with server, but give it latest data
8992 framesIn = recordThread->mRsmpInFrames;
Hongwei Wang95e37682019-04-12 11:13:36 -07008993 mRsmpInFront = /* front = */ audio_utils::safe_sub_overflow(
8994 rear, static_cast<int32_t>(framesIn));
Andy Hung73c02e42015-03-29 01:13:58 -07008995 overrun = true;
8996 }
8997 if (framesAvailable != NULL) {
8998 *framesAvailable = framesIn;
8999 }
9000 if (hasOverrun != NULL) {
9001 *hasOverrun = overrun;
9002 }
9003}
9004
Eric Laurent81784c32012-11-19 14:55:58 -08009005// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009006status_t AudioFlinger::RecordThread::ResamplerBufferProvider::getNextBuffer(
Glenn Kastend79072e2016-01-06 08:41:20 -08009007 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08009008{
Andy Hung73c02e42015-03-29 01:13:58 -07009009 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009010 if (threadBase == 0) {
9011 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08009012 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009013 return NOT_ENOUGH_DATA;
9014 }
9015 RecordThread *recordThread = (RecordThread *) threadBase.get();
9016 int32_t rear = recordThread->mRsmpInRear;
Andy Hung73c02e42015-03-29 01:13:58 -07009017 int32_t front = mRsmpInFront;
Hongwei Wang95e37682019-04-12 11:13:36 -07009018 ssize_t filled = audio_utils::safe_sub_overflow(rear, front);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009019 // FIXME should not be P2 (don't want to increase latency)
9020 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08009021 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07009022 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009023
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009024 front &= recordThread->mRsmpInFramesP2 - 1;
9025 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07009026 if (part1 > (size_t) filled) {
9027 part1 = filled;
9028 }
9029 size_t ask = buffer->frameCount;
9030 ALOG_ASSERT(ask > 0);
9031 if (part1 > ask) {
9032 part1 = ask;
9033 }
9034 if (part1 == 0) {
Andy Hung73c02e42015-03-29 01:13:58 -07009035 // out of data is fine since the resampler will return a short-count.
Glenn Kasten85948432013-08-19 12:09:05 -07009036 buffer->raw = NULL;
9037 buffer->frameCount = 0;
Andy Hung73c02e42015-03-29 01:13:58 -07009038 mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07009039 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08009040 }
9041
Andy Hung57446612015-04-19 23:56:46 -07009042 buffer->raw = (uint8_t*)recordThread->mRsmpInBuffer + front * recordThread->mFrameSize;
Glenn Kasten85948432013-08-19 12:09:05 -07009043 buffer->frameCount = part1;
Andy Hung73c02e42015-03-29 01:13:58 -07009044 mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08009045 return NO_ERROR;
9046}
9047
9048// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009049void AudioFlinger::RecordThread::ResamplerBufferProvider::releaseBuffer(
9050 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08009051{
Hongwei Wang95e37682019-04-12 11:13:36 -07009052 int32_t stepCount = static_cast<int32_t>(buffer->frameCount);
Glenn Kasten85948432013-08-19 12:09:05 -07009053 if (stepCount == 0) {
9054 return;
9055 }
Andy Hung73c02e42015-03-29 01:13:58 -07009056 ALOG_ASSERT(stepCount <= mRsmpInUnrel);
9057 mRsmpInUnrel -= stepCount;
Hongwei Wang95e37682019-04-12 11:13:36 -07009058 mRsmpInFront = audio_utils::safe_add_overflow(mRsmpInFront, stepCount);
Glenn Kasten85948432013-08-19 12:09:05 -07009059 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08009060 buffer->frameCount = 0;
9061}
9062
Eric Laurentd8365c52017-07-16 15:27:05 -07009063void AudioFlinger::RecordThread::checkBtNrec()
9064{
9065 Mutex::Autolock _l(mLock);
9066 checkBtNrec_l();
9067}
9068
9069void AudioFlinger::RecordThread::checkBtNrec_l()
9070{
9071 // disable AEC and NS if the device is a BT SCO headset supporting those
9072 // pre processings
jiabinc52b1ff2019-10-31 17:20:42 -07009073 bool suspend = audio_is_bluetooth_sco_device(inDeviceType()) &&
Eric Laurentd8365c52017-07-16 15:27:05 -07009074 mAudioFlinger->btNrecIsOff();
9075 if (mBtNrecSuspended.exchange(suspend) != suspend) {
9076 for (size_t i = 0; i < mEffectChains.size(); i++) {
9077 setEffectSuspended_l(FX_IID_AEC, suspend, mEffectChains[i]->sessionId());
9078 setEffectSuspended_l(FX_IID_NS, suspend, mEffectChains[i]->sessionId());
9079 }
9080 }
9081}
9082
Andy Hung97a893e2015-03-29 01:03:07 -07009083
Eric Laurent10351942014-05-08 18:49:52 -07009084bool AudioFlinger::RecordThread::checkForNewParameter_l(const String8& keyValuePair,
9085 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08009086{
9087 bool reconfig = false;
9088
Eric Laurent10351942014-05-08 18:49:52 -07009089 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08009090
Eric Laurent10351942014-05-08 18:49:52 -07009091 audio_format_t reqFormat = mFormat;
9092 uint32_t samplingRate = mSampleRate;
Glenn Kastene1635ec2015-06-08 15:46:49 -07009093 // 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 -07009094 audio_channel_mask_t channelMask = audio_channel_in_mask_from_count(mChannelCount);
9095
9096 AudioParameter param = AudioParameter(keyValuePair);
9097 int value;
Haynes Mathew George9ce67b52015-09-30 11:40:47 -07009098
9099 // scope for AutoPark extends to end of method
9100 AutoPark<FastCapture> park(mFastCapture);
9101
Eric Laurent10351942014-05-08 18:49:52 -07009102 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
9103 // channel count change can be requested. Do we mandate the first client defines the
9104 // HAL sampling rate and channel count or do we allow changes on the fly?
9105 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
9106 samplingRate = value;
9107 reconfig = true;
9108 }
9109 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung97a893e2015-03-29 01:03:07 -07009110 if (!audio_is_linear_pcm((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07009111 status = BAD_VALUE;
9112 } else {
9113 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08009114 reconfig = true;
9115 }
Eric Laurent10351942014-05-08 18:49:52 -07009116 }
9117 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
9118 audio_channel_mask_t mask = (audio_channel_mask_t) value;
Andy Hungd330ee42015-04-20 13:23:41 -07009119 if (!audio_is_input_channel(mask) ||
Andy Hung936845a2021-06-08 00:09:06 -07009120 audio_channel_count_from_in_mask(mask) > FCC_LIMIT) {
Eric Laurent10351942014-05-08 18:49:52 -07009121 status = BAD_VALUE;
9122 } else {
9123 channelMask = mask;
9124 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08009125 }
Eric Laurent10351942014-05-08 18:49:52 -07009126 }
9127 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
9128 // do not accept frame count changes if tracks are open as the track buffer
9129 // size depends on frame count and correct behavior would not be guaranteed
9130 // if frame count is changed after track creation
9131 if (mActiveTracks.size() > 0) {
9132 status = INVALID_OPERATION;
9133 } else {
9134 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08009135 }
Eric Laurent10351942014-05-08 18:49:52 -07009136 }
9137 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07009138 LOG_FATAL("Should not set routing device in RecordThread");
Eric Laurent10351942014-05-08 18:49:52 -07009139 }
9140 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
9141 mAudioSource != (audio_source_t)value) {
jiabinc52b1ff2019-10-31 17:20:42 -07009142 LOG_FATAL("Should not set audio source in RecordThread");
Eric Laurent10351942014-05-08 18:49:52 -07009143 }
Glenn Kastene198c362013-08-13 09:13:36 -07009144
Eric Laurent10351942014-05-08 18:49:52 -07009145 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009146 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07009147 if (status == INVALID_OPERATION) {
9148 inputStandBy();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009149 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07009150 }
9151 if (reconfig) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009152 if (status == BAD_VALUE) {
Mikhail Naganov560637e2021-03-31 22:40:13 +00009153 audio_config_base_t config = AUDIO_CONFIG_BASE_INITIALIZER;
9154 if (mInput->stream->getAudioProperties(&config) == OK &&
9155 audio_is_linear_pcm(config.format) && audio_is_linear_pcm(reqFormat) &&
9156 config.sample_rate <= (AUDIO_RESAMPLER_DOWN_RATIO_MAX * samplingRate) &&
Andy Hung936845a2021-06-08 00:09:06 -07009157 audio_channel_count_from_in_mask(config.channel_mask) <= FCC_LIMIT) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009158 status = NO_ERROR;
9159 }
Eric Laurent81784c32012-11-19 14:55:58 -08009160 }
Eric Laurent10351942014-05-08 18:49:52 -07009161 if (status == NO_ERROR) {
9162 readInputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07009163 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08009164 }
9165 }
Eric Laurent81784c32012-11-19 14:55:58 -08009166 }
Eric Laurent10351942014-05-08 18:49:52 -07009167
Eric Laurent81784c32012-11-19 14:55:58 -08009168 return reconfig;
9169}
9170
9171String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
9172{
Eric Laurent81784c32012-11-19 14:55:58 -08009173 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009174 if (initCheck() == NO_ERROR) {
9175 String8 out_s8;
9176 if (mInput->stream->getParameters(keys, &out_s8) == OK) {
9177 return out_s8;
9178 }
Eric Laurent81784c32012-11-19 14:55:58 -08009179 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009180 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08009181}
9182
Mikhail Naganov88536df2021-07-26 17:30:29 -07009183void AudioFlinger::RecordThread::ioConfigChanged(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -07009184 audio_port_handle_t portId) {
Mikhail Naganov88536df2021-07-26 17:30:29 -07009185 sp<AudioIoDescriptor> desc;
Eric Laurent81784c32012-11-19 14:55:58 -08009186 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07009187 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07009188 case AUDIO_INPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07009189 case AUDIO_INPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07009190 desc = sp<AudioIoDescriptor>::make(mId, mPatch, true /*isInput*/,
9191 mSampleRate, mFormat, mChannelMask, mFrameCount, mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08009192 break;
Eric Laurent09f1ed22019-04-24 17:45:17 -07009193 case AUDIO_CLIENT_STARTED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07009194 desc = sp<AudioIoDescriptor>::make(mId, mPatch, portId);
Eric Laurent09f1ed22019-04-24 17:45:17 -07009195 break;
Eric Laurent73e26b62015-04-27 16:55:58 -07009196 case AUDIO_INPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08009197 default:
Mikhail Naganov88536df2021-07-26 17:30:29 -07009198 desc = sp<AudioIoDescriptor>::make(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08009199 break;
9200 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07009201 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08009202}
9203
Glenn Kastendeca2ae2014-02-07 10:25:56 -08009204void AudioFlinger::RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08009205{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009206 status_t result = mInput->stream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
9207 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
Andy Hung463be252014-07-10 16:56:07 -07009208 mFormat = mHALFormat;
Mikhail Naganovce9f2652018-07-16 11:09:24 -07009209 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
9210 if (audio_is_linear_pcm(mFormat)) {
Andy Hung936845a2021-06-08 00:09:06 -07009211 LOG_ALWAYS_FATAL_IF(mChannelCount > FCC_LIMIT, "HAL channel count %d > %d",
9212 mChannelCount, FCC_LIMIT);
Mikhail Naganovce9f2652018-07-16 11:09:24 -07009213 } else {
Andy Hung936845a2021-06-08 00:09:06 -07009214 // Can have more that FCC_LIMIT channels in encoded streams.
Mikhail Naganovce9f2652018-07-16 11:09:24 -07009215 ALOGI("HAL format %#x is not linear pcm", mFormat);
9216 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009217 result = mInput->stream->getFrameSize(&mFrameSize);
9218 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
Hayden Gomes1a89ab32020-06-12 11:05:47 -07009219 LOG_ALWAYS_FATAL_IF(mFrameSize <= 0, "Error frame size was %zu but must be greater than zero",
9220 mFrameSize);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009221 result = mInput->stream->getBufferSize(&mBufferSize);
9222 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
Glenn Kasten548efc92012-11-29 08:48:51 -08009223 mFrameCount = mBufferSize / mFrameSize;
Hayden Gomes1a89ab32020-06-12 11:05:47 -07009224 ALOGV("%p RecordThread params: mChannelCount=%u, mFormat=%#x, mFrameSize=%zu, "
9225 "mBufferSize=%zu, mFrameCount=%zu",
9226 this, mChannelCount, mFormat, mFrameSize, mBufferSize, mFrameCount);
Glenn Kasten49d00ad2014-07-21 11:22:03 -07009227
Eric Laurentec376dc2021-04-08 20:41:22 +02009228 // mRsmpInFrames must be 0 before calling resizeInputBuffer_l for the first time
9229 mRsmpInFrames = 0;
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009230 resizeInputBuffer_l(0 /*maxSharedAudioHistoryMs*/);
Eric Laurent81784c32012-11-19 14:55:58 -08009231
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08009232 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
9233 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Andy Hungea840382020-05-05 21:50:17 -07009234
9235 audio_input_flags_t flags = mInput->flags;
9236 mediametrics::LogItem item(mThreadMetrics.getMetricsId());
9237 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
9238 .set(AMEDIAMETRICS_PROP_ENCODING, formatToString(mFormat).c_str())
9239 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
9240 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
9241 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
9242 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
9243 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mFrameCount)
9244 .record();
Eric Laurent81784c32012-11-19 14:55:58 -08009245}
9246
Glenn Kasten5f972c02014-01-13 09:59:31 -08009247uint32_t AudioFlinger::RecordThread::getInputFramesLost()
Eric Laurent81784c32012-11-19 14:55:58 -08009248{
9249 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009250 uint32_t result;
9251 if (initCheck() == NO_ERROR && mInput->stream->getInputFramesLost(&result) == OK) {
9252 return result;
Eric Laurent81784c32012-11-19 14:55:58 -08009253 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009254 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08009255}
9256
Glenn Kastend848eb42016-03-08 13:42:11 -08009257KeyedVector<audio_session_t, bool> AudioFlinger::RecordThread::sessionIds() const
Eric Laurent81784c32012-11-19 14:55:58 -08009258{
Glenn Kastend848eb42016-03-08 13:42:11 -08009259 KeyedVector<audio_session_t, bool> ids;
Eric Laurent81784c32012-11-19 14:55:58 -08009260 Mutex::Autolock _l(mLock);
9261 for (size_t j = 0; j < mTracks.size(); ++j) {
9262 sp<RecordThread::RecordTrack> track = mTracks[j];
Glenn Kastend848eb42016-03-08 13:42:11 -08009263 audio_session_t sessionId = track->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08009264 if (ids.indexOfKey(sessionId) < 0) {
9265 ids.add(sessionId, true);
9266 }
9267 }
9268 return ids;
9269}
9270
9271AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
9272{
9273 Mutex::Autolock _l(mLock);
9274 AudioStreamIn *input = mInput;
9275 mInput = NULL;
9276 return input;
9277}
9278
9279// this method must always be called either with ThreadBase mLock held or inside the thread loop
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009280sp<StreamHalInterface> AudioFlinger::RecordThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08009281{
9282 if (mInput == NULL) {
9283 return NULL;
9284 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009285 return mInput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08009286}
9287
9288status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
9289{
Eric Laurent81784c32012-11-19 14:55:58 -08009290 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurentaaa44472014-09-12 17:41:50 -07009291 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08009292 chain->setInBuffer(NULL);
9293 chain->setOutBuffer(NULL);
9294
9295 checkSuspendOnAddEffectChain_l(chain);
9296
Eric Laurent1b928682014-10-02 19:41:47 -07009297 // make sure enabled pre processing effects state is communicated to the HAL as we
9298 // just moved them to a new input stream.
9299 chain->syncHalEffectsState();
9300
Eric Laurent81784c32012-11-19 14:55:58 -08009301 mEffectChains.add(chain);
9302
9303 return NO_ERROR;
9304}
9305
9306size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
9307{
9308 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
Eric Laurentb20cf7d2019-04-05 19:37:34 -07009309
9310 for (size_t i = 0; i < mEffectChains.size(); i++) {
9311 if (chain == mEffectChains[i]) {
9312 mEffectChains.removeAt(i);
9313 break;
9314 }
Eric Laurent81784c32012-11-19 14:55:58 -08009315 }
Eric Laurentb20cf7d2019-04-05 19:37:34 -07009316 return mEffectChains.size();
Eric Laurent81784c32012-11-19 14:55:58 -08009317}
9318
Eric Laurent1c333e22014-05-20 10:48:17 -07009319status_t AudioFlinger::RecordThread::createAudioPatch_l(const struct audio_patch *patch,
9320 audio_patch_handle_t *handle)
9321{
9322 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07009323
9324 // store new device and send to effects
jiabinc52b1ff2019-10-31 17:20:42 -07009325 mInDeviceTypeAddr.mType = patch->sources[0].ext.device.type;
jiabin0a488932020-08-07 17:32:40 -07009326 mInDeviceTypeAddr.setAddress(patch->sources[0].ext.device.address);
François Gaffie0c280aa2018-07-25 10:02:15 +02009327 audio_port_handle_t deviceId = patch->sources[0].id;
Eric Laurent054d9d32015-04-24 08:48:48 -07009328 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08009329 mEffectChains[i]->setInputDevice_l(inDeviceTypeAddr());
Eric Laurent054d9d32015-04-24 08:48:48 -07009330 }
9331
Eric Laurentd8365c52017-07-16 15:27:05 -07009332 checkBtNrec_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07009333
9334 // store new source and send to effects
9335 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
9336 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent1c333e22014-05-20 10:48:17 -07009337 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent054d9d32015-04-24 08:48:48 -07009338 mEffectChains[i]->setAudioSource_l(mAudioSource);
Eric Laurent1c333e22014-05-20 10:48:17 -07009339 }
Eric Laurent054d9d32015-04-24 08:48:48 -07009340 }
Eric Laurent1c333e22014-05-20 10:48:17 -07009341
Mikhail Naganov9ee05402016-10-13 15:58:17 -07009342 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07009343 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
9344 status = hwDevice->createAudioPatch(patch->num_sources,
9345 patch->sources,
9346 patch->num_sinks,
9347 patch->sinks,
9348 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07009349 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08009350 status = mInput->stream->legacyCreateAudioPatch(patch->sources[0],
9351 patch->sinks[0].ext.mix.usecase.source,
9352 patch->sources[0].ext.device.type);
Eric Laurent054d9d32015-04-24 08:48:48 -07009353 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07009354 }
Eric Laurent054d9d32015-04-24 08:48:48 -07009355
jiabinc52b1ff2019-10-31 17:20:42 -07009356 if ((mPatch.num_sources == 0) || (mPatch.sources[0].id != deviceId)) {
Eric Laurente8726fe2015-06-26 09:39:24 -07009357 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
jiabinc52b1ff2019-10-31 17:20:42 -07009358 mPatch = *patch;
Eric Laurente8726fe2015-06-26 09:39:24 -07009359 }
Eric Laurent296fb132015-05-01 11:38:42 -07009360
Andy Hungc2b11cb2020-04-22 09:04:01 -07009361 const std::string pathSourcesAsString = patchSourcesToString(patch);
Andy Hungcf10d742020-04-28 15:38:24 -07009362 mThreadMetrics.logEndInterval();
Andy Hungea840382020-05-05 21:50:17 -07009363 mThreadMetrics.logCreatePatch(pathSourcesAsString, /* outDevices */ {});
Andy Hungcf10d742020-04-28 15:38:24 -07009364 mThreadMetrics.logBeginInterval();
Andy Hungc2b11cb2020-04-22 09:04:01 -07009365 // also dispatch to active AudioRecords
9366 for (const auto &track : mActiveTracks) {
9367 track->logEndInterval();
9368 track->logBeginInterval(pathSourcesAsString);
9369 }
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
9376status_t AudioFlinger::RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
9377{
9378 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07009379
jiabinc52b1ff2019-10-31 17:20:42 -07009380 mPatch = audio_patch{};
9381 mInDeviceTypeAddr.reset();
Eric Laurent054d9d32015-04-24 08:48:48 -07009382
Mikhail Naganov9ee05402016-10-13 15:58:17 -07009383 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07009384 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
9385 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07009386 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08009387 status = mInput->stream->legacyReleaseAudioPatch();
Eric Laurent1c333e22014-05-20 10:48:17 -07009388 }
Eric Laurentdda206a2022-07-08 17:28:35 +02009389 // Force meteadata update after a route change
9390 mActiveTracks.setHasChanged();
9391
Eric Laurent1c333e22014-05-20 10:48:17 -07009392 return status;
9393}
9394
jiabinc52b1ff2019-10-31 17:20:42 -07009395void AudioFlinger::RecordThread::updateOutDevices(const DeviceDescriptorBaseVector& outDevices)
9396{
wendy lin56aa82b2020-12-02 15:19:55 +08009397 Mutex::Autolock _l(mLock);
jiabinc52b1ff2019-10-31 17:20:42 -07009398 mOutDevices = outDevices;
9399 mOutDeviceTypeAddrs = deviceTypeAddrsFromDescriptors(mOutDevices);
9400 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08009401 mEffectChains[i]->setDevices_l(outDeviceTypeAddrs());
jiabinc52b1ff2019-10-31 17:20:42 -07009402 }
9403}
9404
Eric Laurentec376dc2021-04-08 20:41:22 +02009405int32_t AudioFlinger::RecordThread::getOldestFront_l()
9406{
9407 if (mTracks.size() == 0) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009408 return mRsmpInRear;
Eric Laurentec376dc2021-04-08 20:41:22 +02009409 }
Eric Laurent2407ce32021-04-26 14:56:03 +02009410 int32_t oldestFront = mRsmpInRear;
9411 int32_t maxFilled = 0;
Eric Laurentec376dc2021-04-08 20:41:22 +02009412 for (size_t i = 0; i < mTracks.size(); i++) {
Eric Laurent2407ce32021-04-26 14:56:03 +02009413 int32_t front = mTracks[i]->mResamplerBufferProvider->getFront();
9414 int32_t filled;
Eric Laurent92d0a322021-07-16 15:32:33 +02009415 (void)__builtin_sub_overflow(mRsmpInRear, front, &filled);
Eric Laurent2407ce32021-04-26 14:56:03 +02009416 if (filled > maxFilled) {
9417 oldestFront = front;
9418 maxFilled = filled;
9419 }
Eric Laurentec376dc2021-04-08 20:41:22 +02009420 }
Eric Laurent92d0a322021-07-16 15:32:33 +02009421 if (maxFilled > mRsmpInFrames) {
9422 (void)__builtin_sub_overflow(mRsmpInRear, mRsmpInFrames, &oldestFront);
9423 }
Eric Laurent2407ce32021-04-26 14:56:03 +02009424 return oldestFront;
Eric Laurentec376dc2021-04-08 20:41:22 +02009425}
9426
9427void AudioFlinger::RecordThread::updateFronts_l(int32_t offset)
9428{
9429 if (offset == 0) {
9430 return;
9431 }
9432 for (size_t i = 0; i < mTracks.size(); i++) {
9433 int32_t front = mTracks[i]->mResamplerBufferProvider->getFront();
9434 front = audio_utils::safe_sub_overflow(front, offset);
9435 mTracks[i]->mResamplerBufferProvider->setFront(front);
9436 }
9437}
9438
9439void AudioFlinger::RecordThread::resizeInputBuffer_l(int32_t maxSharedAudioHistoryMs)
9440{
9441 // This is the formula for calculating the temporary buffer size.
9442 // With 7 HAL buffers, we can guarantee ability to down-sample the input by ratio of 6:1 to
9443 // 1 full output buffer, regardless of the alignment of the available input.
9444 // The value is somewhat arbitrary, and could probably be even larger.
9445 // A larger value should allow more old data to be read after a track calls start(),
9446 // without increasing latency.
9447 //
9448 // Note this is independent of the maximum downsampling ratio permitted for capture.
9449 size_t minRsmpInFrames = mFrameCount * 7;
9450
9451 // maxSharedAudioHistoryMs != 0 indicates a request to possibly make some part of the audio
9452 // capture history available to another client using the same session ID:
9453 // dimension the resampler input buffer accordingly.
9454
9455 // Get oldest client read position: getOldestFront_l() must be called before altering
9456 // mRsmpInRear, or mRsmpInFrames
9457 int32_t previousFront = getOldestFront_l();
9458 size_t previousRsmpInFramesP2 = mRsmpInFramesP2;
9459 int32_t previousRear = mRsmpInRear;
9460 mRsmpInRear = 0;
9461
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009462 ALOG_ASSERT(maxSharedAudioHistoryMs >= 0
9463 && maxSharedAudioHistoryMs <= AudioFlinger::kMaxSharedAudioHistoryMs,
9464 "resizeInputBuffer_l() called with invalid max shared history %d",
9465 maxSharedAudioHistoryMs);
Eric Laurentec376dc2021-04-08 20:41:22 +02009466 if (maxSharedAudioHistoryMs != 0) {
9467 // resizeInputBuffer_l should never be called with a non zero shared history if the
9468 // buffer was not already allocated
9469 ALOG_ASSERT(mRsmpInBuffer != nullptr && mRsmpInFrames != 0,
9470 "resizeInputBuffer_l() called with shared history and unallocated buffer");
9471 size_t rsmpInFrames = (size_t)maxSharedAudioHistoryMs * mSampleRate / 1000;
9472 // never reduce resampler input buffer size
Eric Laurent92d0a322021-07-16 15:32:33 +02009473 if (rsmpInFrames <= mRsmpInFrames) {
Eric Laurentec376dc2021-04-08 20:41:22 +02009474 return;
9475 }
9476 mRsmpInFrames = rsmpInFrames;
9477 }
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009478 mMaxSharedAudioHistoryMs = maxSharedAudioHistoryMs;
Eric Laurentec376dc2021-04-08 20:41:22 +02009479 // Note: mRsmpInFrames is 0 when called with maxSharedAudioHistoryMs equals to 0 so it is always
9480 // initialized
9481 if (mRsmpInFrames < minRsmpInFrames) {
9482 mRsmpInFrames = minRsmpInFrames;
9483 }
9484 mRsmpInFramesP2 = roundup(mRsmpInFrames);
9485
9486 // TODO optimize audio capture buffer sizes ...
9487 // Here we calculate the size of the sliding buffer used as a source
9488 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
9489 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
9490 // be better to have it derived from the pipe depth in the long term.
9491 // The current value is higher than necessary. However it should not add to latency.
9492
9493 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
9494 mRsmpInFramesOA = mRsmpInFramesP2 + mFrameCount - 1;
9495
9496 void *rsmpInBuffer;
9497 (void)posix_memalign(&rsmpInBuffer, 32, mRsmpInFramesOA * mFrameSize);
9498 // if posix_memalign fails, will segv here.
9499 memset(rsmpInBuffer, 0, mRsmpInFramesOA * mFrameSize);
9500
9501 // Copy audio history if any from old buffer before freeing it
9502 if (previousRear != 0) {
9503 ALOG_ASSERT(mRsmpInBuffer != nullptr,
9504 "resizeInputBuffer_l() called with null buffer but frames already read from HAL");
9505
9506 ssize_t unread = audio_utils::safe_sub_overflow(previousRear, previousFront);
9507 previousFront &= previousRsmpInFramesP2 - 1;
9508 size_t part1 = previousRsmpInFramesP2 - previousFront;
9509 if (part1 > (size_t) unread) {
9510 part1 = unread;
9511 }
9512 if (part1 != 0) {
9513 memcpy(rsmpInBuffer, (const uint8_t*)mRsmpInBuffer + previousFront * mFrameSize,
9514 part1 * mFrameSize);
9515 mRsmpInRear = part1;
9516 part1 = unread - part1;
9517 if (part1 != 0) {
9518 memcpy((uint8_t*)rsmpInBuffer + mRsmpInRear * mFrameSize,
9519 (const uint8_t*)mRsmpInBuffer, part1 * mFrameSize);
9520 mRsmpInRear += part1;
9521 }
9522 }
9523 // Update front for all clients according to new rear
9524 updateFronts_l(audio_utils::safe_sub_overflow(previousRear, mRsmpInRear));
9525 } else {
9526 mRsmpInRear = 0;
9527 }
9528 free(mRsmpInBuffer);
9529 mRsmpInBuffer = rsmpInBuffer;
9530}
9531
Mikhail Naganov444ecc32018-05-01 17:40:05 -07009532void AudioFlinger::RecordThread::addPatchTrack(const sp<PatchRecord>& record)
Eric Laurent83b88082014-06-20 18:31:16 -07009533{
9534 Mutex::Autolock _l(mLock);
9535 mTracks.add(record);
Mikhail Naganov2534b382019-09-25 13:05:02 -07009536 if (record->getSource()) {
9537 mSource = record->getSource();
9538 }
Eric Laurent83b88082014-06-20 18:31:16 -07009539}
9540
Mikhail Naganov444ecc32018-05-01 17:40:05 -07009541void AudioFlinger::RecordThread::deletePatchTrack(const sp<PatchRecord>& record)
Eric Laurent83b88082014-06-20 18:31:16 -07009542{
9543 Mutex::Autolock _l(mLock);
Mikhail Naganov2534b382019-09-25 13:05:02 -07009544 if (mSource == record->getSource()) {
9545 mSource = mInput;
9546 }
Eric Laurent83b88082014-06-20 18:31:16 -07009547 destroyTrack_l(record);
9548}
9549
Mikhail Naganovdc769682018-05-04 15:34:08 -07009550void AudioFlinger::RecordThread::toAudioPortConfig(struct audio_port_config *config)
Eric Laurent83b88082014-06-20 18:31:16 -07009551{
Mikhail Naganovdc769682018-05-04 15:34:08 -07009552 ThreadBase::toAudioPortConfig(config);
Eric Laurent83b88082014-06-20 18:31:16 -07009553 config->role = AUDIO_PORT_ROLE_SINK;
9554 config->ext.mix.hw_module = mInput->audioHwDev->handle();
9555 config->ext.mix.usecase.source = mAudioSource;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07009556 if (mInput && mInput->flags != AUDIO_INPUT_FLAG_NONE) {
9557 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
9558 config->flags.input = mInput->flags;
9559 }
Eric Laurent83b88082014-06-20 18:31:16 -07009560}
Eric Laurent1c333e22014-05-20 10:48:17 -07009561
Eric Laurent6acd1d42017-01-04 14:23:29 -08009562// ----------------------------------------------------------------------------
9563// Mmap
9564// ----------------------------------------------------------------------------
9565
9566AudioFlinger::MmapThreadHandle::MmapThreadHandle(const sp<MmapThread>& thread)
9567 : mThread(thread)
9568{
Phil Burk9fabbf82017-08-03 12:02:00 -07009569 assert(thread != 0); // thread must start non-null and stay non-null
Eric Laurent6acd1d42017-01-04 14:23:29 -08009570}
9571
9572AudioFlinger::MmapThreadHandle::~MmapThreadHandle()
9573{
Phil Burk9fabbf82017-08-03 12:02:00 -07009574 mThread->disconnect();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009575}
9576
9577status_t AudioFlinger::MmapThreadHandle::createMmapBuffer(int32_t minSizeFrames,
9578 struct audio_mmap_buffer_info *info)
9579{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009580 return mThread->createMmapBuffer(minSizeFrames, info);
9581}
9582
9583status_t AudioFlinger::MmapThreadHandle::getMmapPosition(struct audio_mmap_position *position)
9584{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009585 return mThread->getMmapPosition(position);
9586}
9587
jiabinb7d8c5a2020-08-26 17:24:52 -07009588status_t AudioFlinger::MmapThreadHandle::getExternalPosition(uint64_t *position,
9589 int64_t *timeNanos) {
9590 return mThread->getExternalPosition(position, timeNanos);
9591}
9592
Eric Laurenta54f1282017-07-01 19:39:32 -07009593status_t AudioFlinger::MmapThreadHandle::start(const AudioClient& client,
jiabind1f1cb62020-03-24 11:57:57 -07009594 const audio_attributes_t *attr, audio_port_handle_t *handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009595
9596{
jiabind1f1cb62020-03-24 11:57:57 -07009597 return mThread->start(client, attr, handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009598}
9599
9600status_t AudioFlinger::MmapThreadHandle::stop(audio_port_handle_t handle)
9601{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009602 return mThread->stop(handle);
9603}
9604
Eric Laurent18b57012017-02-13 16:23:52 -08009605status_t AudioFlinger::MmapThreadHandle::standby()
9606{
Eric Laurent18b57012017-02-13 16:23:52 -08009607 return mThread->standby();
9608}
9609
Eric Laurent6acd1d42017-01-04 14:23:29 -08009610
9611AudioFlinger::MmapThread::MmapThread(
9612 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
Andy Hungcf10d742020-04-28 15:38:24 -07009613 AudioHwDevice *hwDev, sp<StreamHalInterface> stream, bool systemReady, bool isOut)
Andy Hungea840382020-05-05 21:50:17 -07009614 : ThreadBase(audioFlinger, id, (isOut ? MMAP_PLAYBACK : MMAP_CAPTURE), systemReady, isOut),
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009615 mSessionId(AUDIO_SESSION_NONE),
François Gaffie0c280aa2018-07-25 10:02:15 +02009616 mPortId(AUDIO_PORT_HANDLE_NONE),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009617 mHalStream(stream), mHalDevice(hwDev->hwDevice()), mAudioHwDev(hwDev),
Eric Laurent67f97292018-04-20 18:05:41 -07009618 mActiveTracks(&this->mLocalLog),
9619 mHalVolFloat(-1.0f), // Initialize to illegal value so it always gets set properly later.
9620 mNoCallbackWarningCount(0)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009621{
Eric Laurent18b57012017-02-13 16:23:52 -08009622 mStandby = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009623 readHalParameters_l();
9624}
9625
9626AudioFlinger::MmapThread::~MmapThread()
9627{
9628}
9629
9630void AudioFlinger::MmapThread::onFirstRef()
9631{
9632 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
9633}
9634
9635void AudioFlinger::MmapThread::disconnect()
9636{
Eric Laurent331679c2018-04-16 17:03:16 -07009637 ActiveTracks<MmapTrack> activeTracks;
9638 {
9639 Mutex::Autolock _l(mLock);
9640 for (const sp<MmapTrack> &t : mActiveTracks) {
9641 activeTracks.add(t);
9642 }
9643 }
9644 for (const sp<MmapTrack> &t : activeTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08009645 stop(t->portId());
9646 }
Phil Burk9fabbf82017-08-03 12:02:00 -07009647 // This will decrement references and may cause the destruction of this thread.
Eric Laurent6acd1d42017-01-04 14:23:29 -08009648 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07009649 AudioSystem::releaseOutput(mPortId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009650 } else {
Eric Laurentfee19762018-01-29 18:44:13 -08009651 AudioSystem::releaseInput(mPortId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009652 }
9653}
9654
9655
9656void AudioFlinger::MmapThread::configure(const audio_attributes_t *attr,
9657 audio_stream_type_t streamType __unused,
9658 audio_session_t sessionId,
9659 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009660 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -08009661 audio_port_handle_t portId)
9662{
9663 mAttr = *attr;
9664 mSessionId = sessionId;
9665 mCallback = callback;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009666 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009667 mPortId = portId;
9668}
9669
9670status_t AudioFlinger::MmapThread::createMmapBuffer(int32_t minSizeFrames,
9671 struct audio_mmap_buffer_info *info)
9672{
9673 if (mHalStream == 0) {
9674 return NO_INIT;
9675 }
Eric Laurent18b57012017-02-13 16:23:52 -08009676 mStandby = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009677 return mHalStream->createMmapBuffer(minSizeFrames, info);
9678}
9679
9680status_t AudioFlinger::MmapThread::getMmapPosition(struct audio_mmap_position *position)
9681{
9682 if (mHalStream == 0) {
9683 return NO_INIT;
9684 }
9685 return mHalStream->getMmapPosition(position);
9686}
9687
Eric Laurentdda206a2022-07-08 17:28:35 +02009688status_t AudioFlinger::MmapThread::exitStandby_l()
Eric Laurent331679c2018-04-16 17:03:16 -07009689{
Eric Laurentdda206a2022-07-08 17:28:35 +02009690 // The HAL must receive track metadata before starting the stream
9691 updateMetadata_l();
Eric Laurent331679c2018-04-16 17:03:16 -07009692 status_t ret = mHalStream->start();
9693 if (ret != NO_ERROR) {
9694 ALOGE("%s: error mHalStream->start() = %d for first track", __FUNCTION__, ret);
9695 return ret;
9696 }
Andy Hungcf10d742020-04-28 15:38:24 -07009697 if (mStandby) {
9698 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07009699 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -07009700 mStandby = false;
9701 }
Eric Laurent331679c2018-04-16 17:03:16 -07009702 return NO_ERROR;
9703}
9704
Eric Laurenta54f1282017-07-01 19:39:32 -07009705status_t AudioFlinger::MmapThread::start(const AudioClient& client,
jiabind1f1cb62020-03-24 11:57:57 -07009706 const audio_attributes_t *attr,
Eric Laurent6acd1d42017-01-04 14:23:29 -08009707 audio_port_handle_t *handle)
9708{
Eric Laurenta54f1282017-07-01 19:39:32 -07009709 ALOGV("%s clientUid %d mStandby %d mPortId %d *handle %d", __FUNCTION__,
Svet Ganov33761132021-05-13 22:51:08 +00009710 client.attributionSource.uid, mStandby, mPortId, *handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009711 if (mHalStream == 0) {
9712 return NO_INIT;
9713 }
9714
9715 status_t ret;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009716
Eric Laurentdda206a2022-07-08 17:28:35 +02009717 // For the first track, reuse portId and session allocated when the stream was opened.
Eric Laurenta54f1282017-07-01 19:39:32 -07009718 if (*handle == mPortId) {
Eric Laurentdda206a2022-07-08 17:28:35 +02009719 acquireWakeLock();
9720 return NO_ERROR;
Eric Laurenta54f1282017-07-01 19:39:32 -07009721 }
9722
9723 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
9724
9725 audio_io_handle_t io = mId;
9726 if (isOutput()) {
9727 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
9728 config.sample_rate = mSampleRate;
9729 config.channel_mask = mChannelMask;
9730 config.format = mFormat;
9731 audio_stream_type_t stream = streamType();
9732 audio_output_flags_t flags =
9733 (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009734 audio_port_handle_t deviceId = mDeviceId;
Kevin Rocard153f92d2018-12-18 18:33:28 -08009735 std::vector<audio_io_handle_t> secondaryOutputs;
Eric Laurentb0a7bc92022-04-05 15:06:08 +02009736 bool isSpatialized;
Eric Laurenta54f1282017-07-01 19:39:32 -07009737 ret = AudioSystem::getOutputForAttr(&mAttr, &io,
9738 mSessionId,
9739 &stream,
Svet Ganov33761132021-05-13 22:51:08 +00009740 client.attributionSource,
Eric Laurenta54f1282017-07-01 19:39:32 -07009741 &config,
9742 flags,
9743 &deviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -08009744 &portId,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02009745 &secondaryOutputs,
9746 &isSpatialized);
Kevin Rocard153f92d2018-12-18 18:33:28 -08009747 ALOGD_IF(!secondaryOutputs.empty(),
9748 "MmapThread::start does not support secondary outputs, ignoring them");
Eric Laurent6acd1d42017-01-04 14:23:29 -08009749 } else {
Eric Laurenta54f1282017-07-01 19:39:32 -07009750 audio_config_base_t config;
9751 config.sample_rate = mSampleRate;
9752 config.channel_mask = mChannelMask;
9753 config.format = mFormat;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009754 audio_port_handle_t deviceId = mDeviceId;
Eric Laurenta54f1282017-07-01 19:39:32 -07009755 ret = AudioSystem::getInputForAttr(&mAttr, &io,
Mikhail Naganov2996f672019-04-18 12:29:59 -07009756 RECORD_RIID_INVALID,
Eric Laurenta54f1282017-07-01 19:39:32 -07009757 mSessionId,
Svet Ganov33761132021-05-13 22:51:08 +00009758 client.attributionSource,
Eric Laurenta54f1282017-07-01 19:39:32 -07009759 &config,
9760 AUDIO_INPUT_FLAG_MMAP_NOIRQ,
9761 &deviceId,
9762 &portId);
9763 }
9764 // APM should not chose a different input or output stream for the same set of attributes
9765 // and audo configuration
9766 if (ret != NO_ERROR || io != mId) {
9767 ALOGE("%s: error getting output or input from APM (error %d, io %d expected io %d)",
9768 __FUNCTION__, ret, io, mId);
9769 return BAD_VALUE;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009770 }
9771
9772 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07009773 ret = AudioSystem::startOutput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009774 } else {
jiabin09609032022-06-15 19:26:01 +00009775 {
9776 // Add the track record before starting input so that the silent status for the
9777 // client can be cached.
9778 Mutex::Autolock _l(mLock);
9779 setClientSilencedState_l(portId, false /*silenced*/);
9780 }
Eric Laurent4eb58f12018-12-07 16:41:02 -08009781 ret = AudioSystem::startInput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009782 }
9783
Eric Laurent331679c2018-04-16 17:03:16 -07009784 Mutex::Autolock _l(mLock);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009785 // abort if start is rejected by audio policy manager
9786 if (ret != NO_ERROR) {
Phil Burk7f6b40d2017-02-09 13:18:38 -08009787 ALOGE("%s: error start rejected by AudioPolicyManager = %d", __FUNCTION__, ret);
Eric Tan39ec8d62018-07-24 09:49:29 -07009788 if (!mActiveTracks.isEmpty()) {
Eric Laurent331679c2018-04-16 17:03:16 -07009789 mLock.unlock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009790 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07009791 AudioSystem::releaseOutput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009792 } else {
Eric Laurentfee19762018-01-29 18:44:13 -08009793 AudioSystem::releaseInput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009794 }
Eric Laurent331679c2018-04-16 17:03:16 -07009795 mLock.lock();
Eric Laurent18b57012017-02-13 16:23:52 -08009796 } else {
9797 mHalStream->stop();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009798 }
jiabin09609032022-06-15 19:26:01 +00009799 eraseClientSilencedState_l(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009800 return PERMISSION_DENIED;
9801 }
9802
Kevin Rocard1f564ac2018-03-29 13:53:10 -07009803 // Given that MmapThread::mAttr is mutable, should a MmapTrack have attributes ?
jiabind1f1cb62020-03-24 11:57:57 -07009804 sp<MmapTrack> track = new MmapTrack(this, attr == nullptr ? mAttr : *attr, mSampleRate, mFormat,
Svet Ganov33761132021-05-13 22:51:08 +00009805 mChannelMask, mSessionId, isOutput(),
9806 client.attributionSource,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07009807 IPCThreadState::self()->getCallingPid(), portId);
jiabin09609032022-06-15 19:26:01 +00009808 if (!isOutput()) {
9809 track->setSilenced_l(isClientSilenced_l(portId));
9810 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08009811
Eric Laurent4eb58f12018-12-07 16:41:02 -08009812 if (isOutput()) {
9813 // force volume update when a new track is added
9814 mHalVolFloat = -1.0f;
9815 } else if (!track->isSilenced_l()) {
9816 for (const sp<MmapTrack> &t : mActiveTracks) {
Svet Ganov33761132021-05-13 22:51:08 +00009817 if (t->isSilenced_l() && t->uid() != client.attributionSource.uid)
Eric Laurent4eb58f12018-12-07 16:41:02 -08009818 t->invalidate();
9819 }
9820 }
9821
Eric Laurent6acd1d42017-01-04 14:23:29 -08009822 mActiveTracks.add(track);
Eric Laurenta54f1282017-07-01 19:39:32 -07009823 sp<EffectChain> chain = getEffectChain_l(mSessionId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009824 if (chain != 0) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02009825 chain->setStrategy(getStrategyForStream(streamType()));
Eric Laurent6acd1d42017-01-04 14:23:29 -08009826 chain->incTrackCnt();
9827 chain->incActiveTrackCnt();
9828 }
9829
Andy Hungc2b11cb2020-04-22 09:04:01 -07009830 track->logBeginInterval(patchSinksToString(&mPatch)); // log to MediaMetrics
Eric Laurent6acd1d42017-01-04 14:23:29 -08009831 *handle = portId;
Eric Laurentdda206a2022-07-08 17:28:35 +02009832
9833 if (mActiveTracks.size() == 1) {
9834 ret = exitStandby_l();
9835 }
9836
Eric Laurent6acd1d42017-01-04 14:23:29 -08009837 broadcast_l();
9838
Eric Laurentdda206a2022-07-08 17:28:35 +02009839 ALOGV("%s DONE status %d handle %d stream %p", __FUNCTION__, ret, *handle, mHalStream.get());
Eric Laurent6acd1d42017-01-04 14:23:29 -08009840
Eric Laurentdda206a2022-07-08 17:28:35 +02009841 return ret;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009842}
9843
9844status_t AudioFlinger::MmapThread::stop(audio_port_handle_t handle)
9845{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009846 ALOGV("%s handle %d", __FUNCTION__, handle);
9847
9848 if (mHalStream == 0) {
9849 return NO_INIT;
9850 }
9851
Eric Laurenta54f1282017-07-01 19:39:32 -07009852 if (handle == mPortId) {
Phil Burk98ab4082020-09-25 21:46:34 +00009853 releaseWakeLock();
Eric Laurenta54f1282017-07-01 19:39:32 -07009854 return NO_ERROR;
9855 }
9856
Eric Laurent331679c2018-04-16 17:03:16 -07009857 Mutex::Autolock _l(mLock);
9858
Eric Laurent6acd1d42017-01-04 14:23:29 -08009859 sp<MmapTrack> track;
9860 for (const sp<MmapTrack> &t : mActiveTracks) {
9861 if (handle == t->portId()) {
9862 track = t;
9863 break;
9864 }
9865 }
9866 if (track == 0) {
9867 return BAD_VALUE;
9868 }
9869
9870 mActiveTracks.remove(track);
jiabin09609032022-06-15 19:26:01 +00009871 eraseClientSilencedState_l(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -08009872
Eric Laurent331679c2018-04-16 17:03:16 -07009873 mLock.unlock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009874 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07009875 AudioSystem::stopOutput(track->portId());
9876 AudioSystem::releaseOutput(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -08009877 } else {
Eric Laurentfee19762018-01-29 18:44:13 -08009878 AudioSystem::stopInput(track->portId());
9879 AudioSystem::releaseInput(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -08009880 }
Eric Laurent331679c2018-04-16 17:03:16 -07009881 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009882
9883 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
9884 if (chain != 0) {
9885 chain->decActiveTrackCnt();
9886 chain->decTrackCnt();
9887 }
9888
Eric Laurentdda206a2022-07-08 17:28:35 +02009889 if (mActiveTracks.isEmpty()) {
9890 mHalStream->stop();
9891 }
9892
Eric Laurent6acd1d42017-01-04 14:23:29 -08009893 broadcast_l();
9894
Eric Laurent6acd1d42017-01-04 14:23:29 -08009895 return NO_ERROR;
9896}
9897
Eric Laurent18b57012017-02-13 16:23:52 -08009898status_t AudioFlinger::MmapThread::standby()
9899{
9900 ALOGV("%s", __FUNCTION__);
9901
9902 if (mHalStream == 0) {
9903 return NO_INIT;
9904 }
Eric Tan39ec8d62018-07-24 09:49:29 -07009905 if (!mActiveTracks.isEmpty()) {
Eric Laurent18b57012017-02-13 16:23:52 -08009906 return INVALID_OPERATION;
9907 }
9908 mHalStream->standby();
Andy Hungcf10d742020-04-28 15:38:24 -07009909 if (!mStandby) {
9910 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07009911 mThreadSnapshot.onEnd();
Andy Hungcf10d742020-04-28 15:38:24 -07009912 mStandby = true;
9913 }
Eric Laurent18b57012017-02-13 16:23:52 -08009914 releaseWakeLock();
9915 return NO_ERROR;
9916}
9917
Eric Laurent6acd1d42017-01-04 14:23:29 -08009918
9919void AudioFlinger::MmapThread::readHalParameters_l()
9920{
9921 status_t result = mHalStream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
9922 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
9923 mFormat = mHALFormat;
9924 LOG_ALWAYS_FATAL_IF(!audio_is_linear_pcm(mFormat), "HAL format %#x is not linear pcm", mFormat);
9925 result = mHalStream->getFrameSize(&mFrameSize);
9926 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
Hayden Gomes1a89ab32020-06-12 11:05:47 -07009927 LOG_ALWAYS_FATAL_IF(mFrameSize <= 0, "Error frame size was %zu but must be greater than zero",
9928 mFrameSize);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009929 result = mHalStream->getBufferSize(&mBufferSize);
9930 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
9931 mFrameCount = mBufferSize / mFrameSize;
Andy Hungc2b11cb2020-04-22 09:04:01 -07009932
Andy Hungcf10d742020-04-28 15:38:24 -07009933 // TODO: make a readHalParameters call?
9934 mediametrics::LogItem item(mThreadMetrics.getMetricsId());
Andy Hungc2b11cb2020-04-22 09:04:01 -07009935 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
9936 .set(AMEDIAMETRICS_PROP_ENCODING, formatToString(mFormat).c_str())
9937 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
9938 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
9939 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
9940 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mFrameCount)
9941 /*
9942 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
9943 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELMASK,
9944 (int32_t)mHapticChannelMask)
9945 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELCOUNT,
9946 (int32_t)mHapticChannelCount)
9947 */
9948 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_ENCODING,
9949 formatToString(mHALFormat).c_str())
9950 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_FRAMECOUNT,
9951 (int32_t)mFrameCount) // sic - added HAL
9952 .record();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009953}
9954
9955bool AudioFlinger::MmapThread::threadLoop()
9956{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009957 checkSilentMode_l();
9958
9959 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
9960
9961 while (!exitPending())
9962 {
Eric Laurent6acd1d42017-01-04 14:23:29 -08009963 Vector< sp<EffectChain> > effectChains;
9964
Andy Hung13850be2019-03-14 11:33:09 -07009965 { // under Thread lock
9966 Mutex::Autolock _l(mLock);
9967
Eric Laurent6acd1d42017-01-04 14:23:29 -08009968 if (mSignalPending) {
9969 // A signal was raised while we were unlocked
9970 mSignalPending = false;
9971 } else {
9972 if (mConfigEvents.isEmpty()) {
9973 // we're about to wait, flush the binder command buffer
9974 IPCThreadState::self()->flushCommands();
9975
9976 if (exitPending()) {
9977 break;
9978 }
9979
Eric Laurent6acd1d42017-01-04 14:23:29 -08009980 // wait until we have something to do...
9981 ALOGV("%s going to sleep", myName.string());
9982 mWaitWorkCV.wait(mLock);
9983 ALOGV("%s waking up", myName.string());
Eric Laurent6acd1d42017-01-04 14:23:29 -08009984
9985 checkSilentMode_l();
9986
9987 continue;
9988 }
9989 }
9990
9991 processConfigEvents_l();
9992
9993 processVolume_l();
9994
9995 checkInvalidTracks_l();
9996
9997 mActiveTracks.updatePowerState(this);
9998
Kevin Rocard069c2712018-03-29 19:09:14 -07009999 updateMetadata_l();
10000
Eric Laurent6acd1d42017-01-04 14:23:29 -080010001 lockEffectChains_l(effectChains);
Andy Hung13850be2019-03-14 11:33:09 -070010002 } // release Thread lock
10003
Eric Laurent6acd1d42017-01-04 14:23:29 -080010004 for (size_t i = 0; i < effectChains.size(); i ++) {
Andy Hung13850be2019-03-14 11:33:09 -070010005 effectChains[i]->process_l(); // Thread is not locked, but effect chain is locked
Eric Laurent6acd1d42017-01-04 14:23:29 -080010006 }
Andy Hung13850be2019-03-14 11:33:09 -070010007
10008 // enable changes in effect chain, including moving to another thread.
Eric Laurent6acd1d42017-01-04 14:23:29 -080010009 unlockEffectChains(effectChains);
10010 // Effect chains will be actually deleted here if they were removed from
10011 // mEffectChains list during mixing or effects processing
10012 }
10013
10014 threadLoop_exit();
10015
10016 if (!mStandby) {
10017 threadLoop_standby();
10018 mStandby = true;
10019 }
10020
Eric Laurent6acd1d42017-01-04 14:23:29 -080010021 ALOGV("Thread %p type %d exiting", this, mType);
10022 return false;
10023}
10024
10025// checkForNewParameter_l() must be called with ThreadBase::mLock held
10026bool AudioFlinger::MmapThread::checkForNewParameter_l(const String8& keyValuePair,
10027 status_t& status)
10028{
10029 AudioParameter param = AudioParameter(keyValuePair);
10030 int value;
Eric Laurente6e9a482017-07-25 19:26:02 -070010031 bool sendToHal = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010032 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -070010033 LOG_FATAL("Should not happen set routing device in MmapThread");
Eric Laurent6acd1d42017-01-04 14:23:29 -080010034 }
Eric Laurente6e9a482017-07-25 19:26:02 -070010035 if (sendToHal) {
10036 status = mHalStream->setParameters(keyValuePair);
10037 } else {
10038 status = NO_ERROR;
10039 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010040
10041 return false;
10042}
10043
10044String8 AudioFlinger::MmapThread::getParameters(const String8& keys)
10045{
10046 Mutex::Autolock _l(mLock);
10047 String8 out_s8;
10048 if (initCheck() == NO_ERROR && mHalStream->getParameters(keys, &out_s8) == OK) {
10049 return out_s8;
10050 }
10051 return String8();
10052}
10053
Mikhail Naganov88536df2021-07-26 17:30:29 -070010054void AudioFlinger::MmapThread::ioConfigChanged(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -070010055 audio_port_handle_t portId __unused) {
Mikhail Naganov88536df2021-07-26 17:30:29 -070010056 sp<AudioIoDescriptor> desc;
10057 bool isInput = false;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010058 switch (event) {
10059 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -070010060 case AUDIO_INPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -080010061 case AUDIO_INPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -070010062 isInput = true;
10063 FALLTHROUGH_INTENDED;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010064 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -070010065 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -080010066 case AUDIO_OUTPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -070010067 desc = sp<AudioIoDescriptor>::make(mId, mPatch, isInput,
10068 mSampleRate, mFormat, mChannelMask, mFrameCount, mFrameCount);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010069 break;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010070 case AUDIO_INPUT_CLOSED:
10071 case AUDIO_OUTPUT_CLOSED:
10072 default:
Mikhail Naganov88536df2021-07-26 17:30:29 -070010073 desc = sp<AudioIoDescriptor>::make(mId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010074 break;
10075 }
10076 mAudioFlinger->ioConfigChanged(event, desc, pid);
10077}
10078
10079status_t AudioFlinger::MmapThread::createAudioPatch_l(const struct audio_patch *patch,
10080 audio_patch_handle_t *handle)
10081{
10082 status_t status = NO_ERROR;
10083
10084 // store new device and send to effects
10085 audio_devices_t type = AUDIO_DEVICE_NONE;
10086 audio_port_handle_t deviceId;
jiabinc52b1ff2019-10-31 17:20:42 -070010087 AudioDeviceTypeAddrVector sinkDeviceTypeAddrs;
10088 AudioDeviceTypeAddr sourceDeviceTypeAddr;
10089 uint32_t numDevices = 0;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010090 if (isOutput()) {
10091 for (unsigned int i = 0; i < patch->num_sinks; i++) {
jiabinc52b1ff2019-10-31 17:20:42 -070010092 LOG_ALWAYS_FATAL_IF(popcount(patch->sinks[i].ext.device.type) > 1
10093 && !mAudioHwDev->supportsAudioPatches(),
10094 "Enumerated device type(%#x) must not be used "
10095 "as it does not support audio patches",
10096 patch->sinks[i].ext.device.type);
Mikhail Naganov55773032020-10-01 15:08:13 -070010097 type = static_cast<audio_devices_t>(type | patch->sinks[i].ext.device.type);
jiabinc52b1ff2019-10-31 17:20:42 -070010098 sinkDeviceTypeAddrs.push_back(AudioDeviceTypeAddr(patch->sinks[i].ext.device.type,
10099 patch->sinks[i].ext.device.address));
Eric Laurent6acd1d42017-01-04 14:23:29 -080010100 }
10101 deviceId = patch->sinks[0].id;
jiabinc52b1ff2019-10-31 17:20:42 -070010102 numDevices = mPatch.num_sinks;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010103 } else {
10104 type = patch->sources[0].ext.device.type;
10105 deviceId = patch->sources[0].id;
jiabinc52b1ff2019-10-31 17:20:42 -070010106 numDevices = mPatch.num_sources;
10107 sourceDeviceTypeAddr.mType = patch->sources[0].ext.device.type;
jiabin0a488932020-08-07 17:32:40 -070010108 sourceDeviceTypeAddr.setAddress(patch->sources[0].ext.device.address);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010109 }
10110
10111 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -080010112 if (isOutput()) {
10113 mEffectChains[i]->setDevices_l(sinkDeviceTypeAddrs);
10114 } else {
10115 mEffectChains[i]->setInputDevice_l(sourceDeviceTypeAddr);
10116 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010117 }
10118
jiabinc52b1ff2019-10-31 17:20:42 -070010119 if (!isOutput()) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010120 // store new source and send to effects
10121 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
10122 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
10123 for (size_t i = 0; i < mEffectChains.size(); i++) {
10124 mEffectChains[i]->setAudioSource_l(mAudioSource);
10125 }
10126 }
10127 }
10128
10129 if (mAudioHwDev->supportsAudioPatches()) {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010130 status = mHalDevice->createAudioPatch(patch->num_sources, patch->sources, patch->num_sinks,
10131 patch->sinks, handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010132 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010133 audio_port_config port;
10134 std::optional<audio_source_t> source;
10135 if (isOutput()) {
10136 port = patch->sinks[0];
Eric Laurent6acd1d42017-01-04 14:23:29 -080010137 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010138 port = patch->sources[0];
10139 source = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010140 }
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010141 status = mHalStream->legacyCreateAudioPatch(port, source, type);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010142 *handle = AUDIO_PATCH_HANDLE_NONE;
10143 }
10144
jiabinc52b1ff2019-10-31 17:20:42 -070010145 if (numDevices == 0 || mDeviceId != deviceId) {
10146 if (isOutput()) {
10147 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
10148 mOutDeviceTypeAddrs = sinkDeviceTypeAddrs;
jiabin0a957d32020-04-29 10:56:20 -070010149 checkSilentMode_l();
jiabinc52b1ff2019-10-31 17:20:42 -070010150 } else {
10151 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
10152 mInDeviceTypeAddr = sourceDeviceTypeAddr;
10153 }
Phil Burk7f6b40d2017-02-09 13:18:38 -080010154 sp<MmapStreamCallback> callback = mCallback.promote();
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010155 if (mDeviceId != deviceId && callback != 0) {
Eric Laurent734046e2018-04-16 14:50:52 -070010156 mLock.unlock();
Phil Burk7f6b40d2017-02-09 13:18:38 -080010157 callback->onRoutingChanged(deviceId);
Eric Laurent734046e2018-04-16 14:50:52 -070010158 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010159 }
jiabinc52b1ff2019-10-31 17:20:42 -070010160 mPatch = *patch;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010161 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010162 }
Eric Laurentdda206a2022-07-08 17:28:35 +020010163 // Force meteadata update after a route change
10164 mActiveTracks.setHasChanged();
10165
Eric Laurent6acd1d42017-01-04 14:23:29 -080010166 return status;
10167}
10168
10169status_t AudioFlinger::MmapThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
10170{
10171 status_t status = NO_ERROR;
10172
jiabinc52b1ff2019-10-31 17:20:42 -070010173 mPatch = audio_patch{};
10174 mOutDeviceTypeAddrs.clear();
10175 mInDeviceTypeAddr.reset();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010176
10177 bool supportsAudioPatches = mHalDevice->supportsAudioPatches(&supportsAudioPatches) == OK ?
10178 supportsAudioPatches : false;
10179
10180 if (supportsAudioPatches) {
10181 status = mHalDevice->releaseAudioPatch(handle);
10182 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010183 status = mHalStream->legacyReleaseAudioPatch();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010184 }
Eric Laurentdda206a2022-07-08 17:28:35 +020010185 // Force meteadata update after a route change
10186 mActiveTracks.setHasChanged();
10187
Eric Laurent6acd1d42017-01-04 14:23:29 -080010188 return status;
10189}
10190
Mikhail Naganovdc769682018-05-04 15:34:08 -070010191void AudioFlinger::MmapThread::toAudioPortConfig(struct audio_port_config *config)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010192{
Mikhail Naganovdc769682018-05-04 15:34:08 -070010193 ThreadBase::toAudioPortConfig(config);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010194 if (isOutput()) {
10195 config->role = AUDIO_PORT_ROLE_SOURCE;
10196 config->ext.mix.hw_module = mAudioHwDev->handle();
10197 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
10198 } else {
10199 config->role = AUDIO_PORT_ROLE_SINK;
10200 config->ext.mix.hw_module = mAudioHwDev->handle();
10201 config->ext.mix.usecase.source = mAudioSource;
10202 }
10203}
10204
10205status_t AudioFlinger::MmapThread::addEffectChain_l(const sp<EffectChain>& chain)
10206{
10207 audio_session_t session = chain->sessionId();
10208
10209 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
10210 // Attach all tracks with same session ID to this chain.
10211 // indicate all active tracks in the chain
10212 for (const sp<MmapTrack> &track : mActiveTracks) {
10213 if (session == track->sessionId()) {
10214 chain->incTrackCnt();
10215 chain->incActiveTrackCnt();
10216 }
10217 }
10218
10219 chain->setThread(this);
10220 chain->setInBuffer(nullptr);
10221 chain->setOutBuffer(nullptr);
10222 chain->syncHalEffectsState();
10223
10224 mEffectChains.add(chain);
10225 checkSuspendOnAddEffectChain_l(chain);
10226 return NO_ERROR;
10227}
10228
10229size_t AudioFlinger::MmapThread::removeEffectChain_l(const sp<EffectChain>& chain)
10230{
10231 audio_session_t session = chain->sessionId();
10232
10233 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
10234
10235 for (size_t i = 0; i < mEffectChains.size(); i++) {
10236 if (chain == mEffectChains[i]) {
10237 mEffectChains.removeAt(i);
10238 // detach all active tracks from the chain
10239 // detach all tracks with same session ID from this chain
10240 for (const sp<MmapTrack> &track : mActiveTracks) {
10241 if (session == track->sessionId()) {
10242 chain->decActiveTrackCnt();
10243 chain->decTrackCnt();
10244 }
10245 }
10246 break;
10247 }
10248 }
10249 return mEffectChains.size();
10250}
10251
Eric Laurent6acd1d42017-01-04 14:23:29 -080010252void AudioFlinger::MmapThread::threadLoop_standby()
10253{
10254 mHalStream->standby();
10255}
10256
10257void AudioFlinger::MmapThread::threadLoop_exit()
10258{
Phil Burk7dce7282017-09-27 13:51:41 -070010259 // Do not call callback->onTearDown() because it is redundant for thread exit
10260 // and because it can cause a recursive mutex lock on stop().
Eric Laurent6acd1d42017-01-04 14:23:29 -080010261}
10262
10263status_t AudioFlinger::MmapThread::setSyncEvent(const sp<SyncEvent>& event __unused)
10264{
10265 return BAD_VALUE;
10266}
10267
10268bool AudioFlinger::MmapThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
10269{
10270 return false;
10271}
10272
10273status_t AudioFlinger::MmapThread::checkEffectCompatibility_l(
10274 const effect_descriptor_t *desc, audio_session_t sessionId)
10275{
10276 // No global effect sessions on mmap threads
Eric Laurent3f75a5b2019-11-12 15:55:51 -080010277 if (audio_is_global_session(sessionId)) {
10278 ALOGW("checkEffectCompatibility_l(): global effect %s on MMAP thread %s",
Eric Laurent6acd1d42017-01-04 14:23:29 -080010279 desc->name, mThreadName);
10280 return BAD_VALUE;
10281 }
10282
10283 if (!isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC)) {
10284 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on capture mmap thread",
10285 desc->name);
10286 return BAD_VALUE;
10287 }
10288 if (isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Glenn Kastend3bb6452016-12-05 18:14:37 -080010289 ALOGW("checkEffectCompatibility_l(): pre processing effect %s created on playback mmap "
10290 "thread", desc->name);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010291 return BAD_VALUE;
10292 }
10293
10294 // Only allow effects without processing load or latency
10295 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) != EFFECT_FLAG_NO_PROCESS) {
10296 return BAD_VALUE;
10297 }
10298
jiabineb3bda02020-06-30 14:07:03 -070010299 if (EffectModule::isHapticGenerator(&desc->type)) {
10300 ALOGE("%s(): HapticGenerator is not supported for MmapThread", __func__);
10301 return BAD_VALUE;
10302 }
10303
Eric Laurent6acd1d42017-01-04 14:23:29 -080010304 return NO_ERROR;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010305}
10306
10307void AudioFlinger::MmapThread::checkInvalidTracks_l()
10308{
Eric Laurent039c24a2022-10-07 14:01:59 +020010309 sp<MmapStreamCallback> callback;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010310 for (const sp<MmapTrack> &track : mActiveTracks) {
10311 if (track->isInvalid()) {
Eric Laurent039c24a2022-10-07 14:01:59 +020010312 callback = mCallback.promote();
10313 if (callback == nullptr && mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
10314 ALOGW("Could not notify MMAP stream tear down: no onRoutingChanged callback!");
10315 mNoCallbackWarningCount++;
10316 }
10317 break;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010318 }
10319 }
Eric Laurent039c24a2022-10-07 14:01:59 +020010320 if (callback != 0) {
10321 mLock.unlock();
10322 callback->onRoutingChanged(AUDIO_PORT_HANDLE_NONE);
10323 mLock.lock();
jiabindfa32482022-10-06 19:45:50 +000010324 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010325}
10326
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -070010327void AudioFlinger::MmapThread::dumpInternals_l(int fd, const Vector<String16>& args __unused)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010328{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010329 dprintf(fd, " Attributes: content type %d usage %d source %d\n",
10330 mAttr.content_type, mAttr.usage, mAttr.source);
10331 dprintf(fd, " Session: %d port Id: %d\n", mSessionId, mPortId);
Eric Tan39ec8d62018-07-24 09:49:29 -070010332 if (mActiveTracks.isEmpty()) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010333 dprintf(fd, " No active clients\n");
10334 }
10335}
10336
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -070010337void AudioFlinger::MmapThread::dumpTracks_l(int fd, const Vector<String16>& args __unused)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010338{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010339 String8 result;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010340 size_t numtracks = mActiveTracks.size();
Andy Hung2c6c3bb2017-06-16 14:01:45 -070010341 dprintf(fd, " %zu Tracks\n", numtracks);
10342 const char *prefix = " ";
Eric Laurent6acd1d42017-01-04 14:23:29 -080010343 if (numtracks) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -070010344 result.append(prefix);
Kevin Rocard5f2136e2018-05-11 22:03:00 -070010345 mActiveTracks[0]->appendDumpHeader(result);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010346 for (size_t i = 0; i < numtracks ; ++i) {
10347 sp<MmapTrack> track = mActiveTracks[i];
Andy Hung2c6c3bb2017-06-16 14:01:45 -070010348 result.append(prefix);
10349 track->appendDump(result, true /* active */);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010350 }
10351 } else {
10352 dprintf(fd, "\n");
10353 }
10354 write(fd, result.string(), result.size());
10355}
10356
10357AudioFlinger::MmapPlaybackThread::MmapPlaybackThread(
10358 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
jiabinc52b1ff2019-10-31 17:20:42 -070010359 AudioHwDevice *hwDev, AudioStreamOut *output, bool systemReady)
Andy Hungcf10d742020-04-28 15:38:24 -070010360 : MmapThread(audioFlinger, id, hwDev, output->stream, systemReady, true /* isOut */),
Eric Laurent6acd1d42017-01-04 14:23:29 -080010361 mStreamType(AUDIO_STREAM_MUSIC),
Phil Burk56ecf3e2018-03-12 15:38:17 -070010362 mStreamVolume(1.0),
10363 mStreamMute(false),
Phil Burk56ecf3e2018-03-12 15:38:17 -070010364 mOutput(output)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010365{
10366 snprintf(mThreadName, kThreadNameLength, "AudioMmapOut_%X", id);
10367 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
10368 mMasterVolume = audioFlinger->masterVolume_l();
10369 mMasterMute = audioFlinger->masterMute_l();
10370 if (mAudioHwDev) {
10371 if (mAudioHwDev->canSetMasterVolume()) {
10372 mMasterVolume = 1.0;
10373 }
10374
10375 if (mAudioHwDev->canSetMasterMute()) {
10376 mMasterMute = false;
10377 }
10378 }
10379}
10380
10381void AudioFlinger::MmapPlaybackThread::configure(const audio_attributes_t *attr,
10382 audio_stream_type_t streamType,
10383 audio_session_t sessionId,
10384 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010385 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010386 audio_port_handle_t portId)
10387{
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010388 MmapThread::configure(attr, streamType, sessionId, callback, deviceId, portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010389 mStreamType = streamType;
10390}
10391
10392AudioStreamOut* AudioFlinger::MmapPlaybackThread::clearOutput()
10393{
10394 Mutex::Autolock _l(mLock);
10395 AudioStreamOut *output = mOutput;
10396 mOutput = NULL;
10397 return output;
10398}
10399
10400void AudioFlinger::MmapPlaybackThread::setMasterVolume(float value)
10401{
10402 Mutex::Autolock _l(mLock);
10403 // Don't apply master volume in SW if our HAL can do it for us.
10404 if (mAudioHwDev &&
10405 mAudioHwDev->canSetMasterVolume()) {
10406 mMasterVolume = 1.0;
10407 } else {
10408 mMasterVolume = value;
10409 }
10410}
10411
10412void AudioFlinger::MmapPlaybackThread::setMasterMute(bool muted)
10413{
10414 Mutex::Autolock _l(mLock);
10415 // Don't apply master mute in SW if our HAL can do it for us.
10416 if (mAudioHwDev && mAudioHwDev->canSetMasterMute()) {
10417 mMasterMute = false;
10418 } else {
10419 mMasterMute = muted;
10420 }
10421}
10422
10423void AudioFlinger::MmapPlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
10424{
10425 Mutex::Autolock _l(mLock);
10426 if (stream == mStreamType) {
10427 mStreamVolume = value;
10428 broadcast_l();
10429 }
10430}
10431
10432float AudioFlinger::MmapPlaybackThread::streamVolume(audio_stream_type_t stream) const
10433{
10434 Mutex::Autolock _l(mLock);
10435 if (stream == mStreamType) {
10436 return mStreamVolume;
10437 }
10438 return 0.0f;
10439}
10440
10441void AudioFlinger::MmapPlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
10442{
10443 Mutex::Autolock _l(mLock);
10444 if (stream == mStreamType) {
10445 mStreamMute= muted;
10446 broadcast_l();
10447 }
10448}
10449
10450void AudioFlinger::MmapPlaybackThread::invalidateTracks(audio_stream_type_t streamType)
10451{
10452 Mutex::Autolock _l(mLock);
10453 if (streamType == mStreamType) {
10454 for (const sp<MmapTrack> &track : mActiveTracks) {
10455 track->invalidate();
10456 }
10457 broadcast_l();
10458 }
10459}
10460
10461void AudioFlinger::MmapPlaybackThread::processVolume_l()
10462{
10463 float volume;
10464
10465 if (mMasterMute || mStreamMute) {
10466 volume = 0;
10467 } else {
10468 volume = mMasterVolume * mStreamVolume;
10469 }
10470
10471 if (volume != mHalVolFloat) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010472
10473 // Convert volumes from float to 8.24
10474 uint32_t vol = (uint32_t)(volume * (1 << 24));
10475
10476 // Delegate volume control to effect in track effect chain if needed
10477 // only one effect chain can be present on DirectOutputThread, so if
10478 // there is one, the track is connected to it
10479 if (!mEffectChains.isEmpty()) {
10480 mEffectChains[0]->setVolume_l(&vol, &vol);
10481 volume = (float)vol / (1 << 24);
10482 }
Eric Laurentdff774a2017-04-21 15:29:38 -070010483 // Try to use HW volume control and fall back to SW control if not implemented
Phil Burk56ecf3e2018-03-12 15:38:17 -070010484 if (mOutput->stream->setVolume(volume, volume) == NO_ERROR) {
10485 mHalVolFloat = volume; // HW volume control worked, so update value.
10486 mNoCallbackWarningCount = 0;
10487 } else {
Eric Laurentdff774a2017-04-21 15:29:38 -070010488 sp<MmapStreamCallback> callback = mCallback.promote();
10489 if (callback != 0) {
Phil Burk56ecf3e2018-03-12 15:38:17 -070010490 mHalVolFloat = volume; // SW volume control worked, so update value.
10491 mNoCallbackWarningCount = 0;
Eric Laurent734046e2018-04-16 14:50:52 -070010492 mLock.unlock();
Robert Wu4389ae62022-02-17 18:39:41 +000010493 callback->onVolumeChanged(volume);
Eric Laurent734046e2018-04-16 14:50:52 -070010494 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010495 } else {
Phil Burk56ecf3e2018-03-12 15:38:17 -070010496 if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
10497 ALOGW("Could not set MMAP stream volume: no volume callback!");
10498 mNoCallbackWarningCount++;
10499 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010500 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010501 }
Jasmine Chaeaa10e42021-05-11 10:11:14 +080010502 for (const sp<MmapTrack> &track : mActiveTracks) {
10503 track->setMetadataHasChanged();
Vlad Popaec1788e2022-08-04 11:23:30 +020010504 track->processMuteEvent_l(mAudioFlinger->getOrCreateAudioManager(),
10505 /*muteState=*/{mMasterMute,
10506 mStreamVolume == 0.f,
10507 mStreamMute,
10508 // TODO(b/241533526): adjust logic to include mute from AppOps
10509 false /*muteFromPlaybackRestricted*/,
10510 false /*muteFromClientVolume*/,
10511 false /*muteFromVolumeShaper*/});
Jasmine Chaeaa10e42021-05-11 10:11:14 +080010512 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010513 }
10514}
10515
Kevin Rocard069c2712018-03-29 19:09:14 -070010516void AudioFlinger::MmapPlaybackThread::updateMetadata_l()
10517{
Jasmine Chaeaa10e42021-05-11 10:11:14 +080010518 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
10519 return; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -070010520 }
10521 StreamOutHalInterface::SourceMetadata metadata;
10522 for (const sp<MmapTrack> &track : mActiveTracks) {
10523 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurent94579172020-11-20 18:41:04 +010010524 playback_track_metadata_v7_t trackMetadata;
10525 trackMetadata.base = {
Kevin Rocard069c2712018-03-29 19:09:14 -070010526 .usage = track->attributes().usage,
10527 .content_type = track->attributes().content_type,
10528 .gain = mHalVolFloat, // TODO: propagate from aaudio pre-mix volume
Eric Laurent94579172020-11-20 18:41:04 +010010529 };
10530 trackMetadata.channel_mask = track->channelMask(),
10531 strncpy(trackMetadata.tags, track->attributes().tags, AUDIO_ATTRIBUTES_TAGS_MAX_SIZE);
10532 metadata.tracks.push_back(trackMetadata);
Kevin Rocard069c2712018-03-29 19:09:14 -070010533 }
10534 mOutput->stream->updateSourceMetadata(metadata);
10535}
10536
Eric Laurent6acd1d42017-01-04 14:23:29 -080010537void AudioFlinger::MmapPlaybackThread::checkSilentMode_l()
10538{
10539 if (!mMasterMute) {
10540 char value[PROPERTY_VALUE_MAX];
10541 if (property_get("ro.audio.silent", value, "0") > 0) {
10542 char *endptr;
10543 unsigned long ul = strtoul(value, &endptr, 0);
10544 if (*endptr == '\0' && ul != 0) {
10545 ALOGD("Silence is golden");
10546 // The setprop command will not allow a property to be changed after
10547 // the first time it is set, so we don't have to worry about un-muting.
10548 setMasterMute_l(true);
10549 }
10550 }
10551 }
10552}
10553
Mikhail Naganov32abc2b2018-05-24 12:57:11 -070010554void AudioFlinger::MmapPlaybackThread::toAudioPortConfig(struct audio_port_config *config)
10555{
10556 MmapThread::toAudioPortConfig(config);
10557 if (mOutput && mOutput->flags != AUDIO_OUTPUT_FLAG_NONE) {
10558 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
10559 config->flags.output = mOutput->flags;
10560 }
10561}
10562
jiabinb7d8c5a2020-08-26 17:24:52 -070010563status_t AudioFlinger::MmapPlaybackThread::getExternalPosition(uint64_t *position,
10564 int64_t *timeNanos)
10565{
10566 if (mOutput == nullptr) {
10567 return NO_INIT;
10568 }
10569 struct timespec timestamp;
10570 status_t status = mOutput->getPresentationPosition(position, &timestamp);
10571 if (status == NO_ERROR) {
10572 *timeNanos = timestamp.tv_sec * NANOS_PER_SECOND + timestamp.tv_nsec;
10573 }
10574 return status;
10575}
10576
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -070010577void AudioFlinger::MmapPlaybackThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010578{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -070010579 MmapThread::dumpInternals_l(fd, args);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010580
Glenn Kastend3bb6452016-12-05 18:14:37 -080010581 dprintf(fd, " Stream type: %d Stream volume: %f HAL volume: %f Stream mute %d\n",
10582 mStreamType, mStreamVolume, mHalVolFloat, mStreamMute);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010583 dprintf(fd, " Master volume: %f Master mute %d\n", mMasterVolume, mMasterMute);
10584}
10585
10586AudioFlinger::MmapCaptureThread::MmapCaptureThread(
10587 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
jiabinc52b1ff2019-10-31 17:20:42 -070010588 AudioHwDevice *hwDev, AudioStreamIn *input, bool systemReady)
Andy Hungcf10d742020-04-28 15:38:24 -070010589 : MmapThread(audioFlinger, id, hwDev, input->stream, systemReady, false /* isOut */),
Eric Laurent6acd1d42017-01-04 14:23:29 -080010590 mInput(input)
10591{
10592 snprintf(mThreadName, kThreadNameLength, "AudioMmapIn_%X", id);
10593 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
10594}
10595
Eric Laurentdda206a2022-07-08 17:28:35 +020010596status_t AudioFlinger::MmapCaptureThread::exitStandby_l()
Eric Laurent331679c2018-04-16 17:03:16 -070010597{
Phil Burkf054fc32018-12-06 09:45:59 -080010598 {
10599 // mInput might have been cleared by clearInput()
Phil Burkf054fc32018-12-06 09:45:59 -080010600 if (mInput != nullptr && mInput->stream != nullptr) {
10601 mInput->stream->setGain(1.0f);
10602 }
10603 }
Eric Laurentdda206a2022-07-08 17:28:35 +020010604 return MmapThread::exitStandby_l();
Eric Laurent331679c2018-04-16 17:03:16 -070010605}
10606
Eric Laurent6acd1d42017-01-04 14:23:29 -080010607AudioFlinger::AudioStreamIn* AudioFlinger::MmapCaptureThread::clearInput()
10608{
10609 Mutex::Autolock _l(mLock);
10610 AudioStreamIn *input = mInput;
10611 mInput = NULL;
10612 return input;
10613}
Kevin Rocard069c2712018-03-29 19:09:14 -070010614
Eric Laurent331679c2018-04-16 17:03:16 -070010615
10616void AudioFlinger::MmapCaptureThread::processVolume_l()
10617{
10618 bool changed = false;
10619 bool silenced = false;
10620
10621 sp<MmapStreamCallback> callback = mCallback.promote();
10622 if (callback == 0) {
10623 if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
10624 ALOGW("Could not set MMAP stream silenced: no onStreamSilenced callback!");
10625 mNoCallbackWarningCount++;
10626 }
10627 }
10628
10629 // After a change occurred in track silenced state, mute capture in audio DSP if at least one
10630 // track is silenced and unmute otherwise
10631 for (size_t i = 0; i < mActiveTracks.size() && !silenced; i++) {
10632 if (!mActiveTracks[i]->getAndSetSilencedNotified_l()) {
10633 changed = true;
10634 silenced = mActiveTracks[i]->isSilenced_l();
10635 }
10636 }
10637
10638 if (changed) {
10639 mInput->stream->setGain(silenced ? 0.0f: 1.0f);
10640 }
10641}
10642
Kevin Rocard069c2712018-03-29 19:09:14 -070010643void AudioFlinger::MmapCaptureThread::updateMetadata_l()
10644{
Jasmine Chaeaa10e42021-05-11 10:11:14 +080010645 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
10646 return; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -070010647 }
10648 StreamInHalInterface::SinkMetadata metadata;
10649 for (const sp<MmapTrack> &track : mActiveTracks) {
10650 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurent94579172020-11-20 18:41:04 +010010651 record_track_metadata_v7_t trackMetadata;
10652 trackMetadata.base = {
Kevin Rocard069c2712018-03-29 19:09:14 -070010653 .source = track->attributes().source,
10654 .gain = 1, // capture tracks do not have volumes
Eric Laurent94579172020-11-20 18:41:04 +010010655 };
10656 trackMetadata.channel_mask = track->channelMask(),
10657 strncpy(trackMetadata.tags, track->attributes().tags, AUDIO_ATTRIBUTES_TAGS_MAX_SIZE);
10658 metadata.tracks.push_back(trackMetadata);
Kevin Rocard069c2712018-03-29 19:09:14 -070010659 }
10660 mInput->stream->updateSinkMetadata(metadata);
10661}
10662
Eric Laurent5ada82e2019-08-29 17:53:54 -070010663void AudioFlinger::MmapCaptureThread::setRecordSilenced(audio_port_handle_t portId, bool silenced)
Eric Laurent331679c2018-04-16 17:03:16 -070010664{
10665 Mutex::Autolock _l(mLock);
10666 for (size_t i = 0; i < mActiveTracks.size() ; i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -070010667 if (mActiveTracks[i]->portId() == portId) {
Eric Laurent331679c2018-04-16 17:03:16 -070010668 mActiveTracks[i]->setSilenced_l(silenced);
10669 broadcast_l();
10670 }
10671 }
jiabin09609032022-06-15 19:26:01 +000010672 setClientSilencedIfExists_l(portId, silenced);
Eric Laurent331679c2018-04-16 17:03:16 -070010673}
10674
Mikhail Naganov32abc2b2018-05-24 12:57:11 -070010675void AudioFlinger::MmapCaptureThread::toAudioPortConfig(struct audio_port_config *config)
10676{
10677 MmapThread::toAudioPortConfig(config);
10678 if (mInput && mInput->flags != AUDIO_INPUT_FLAG_NONE) {
10679 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
10680 config->flags.input = mInput->flags;
10681 }
10682}
10683
jiabinb7d8c5a2020-08-26 17:24:52 -070010684status_t AudioFlinger::MmapCaptureThread::getExternalPosition(
10685 uint64_t *position, int64_t *timeNanos)
10686{
10687 if (mInput == nullptr) {
10688 return NO_INIT;
10689 }
10690 return mInput->getCapturePosition((int64_t*)position, timeNanos);
10691}
10692
Glenn Kasten63238ef2015-03-02 15:50:29 -080010693} // namespace android