blob: 745dbf2521c41281fb4c13e1eab5bbbb6f116a66 [file] [log] [blame]
Eric Laurent81784c32012-11-19 14:55:58 -08001/*
2**
3** Copyright 2012, The Android Open Source Project
4**
5** Licensed under the Apache License, Version 2.0 (the "License");
6** you may not use this file except in compliance with the License.
7** You may obtain a copy of the License at
8**
9** http://www.apache.org/licenses/LICENSE-2.0
10**
11** Unless required by applicable law or agreed to in writing, software
12** distributed under the License is distributed on an "AS IS" BASIS,
13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14** See the License for the specific language governing permissions and
15** limitations under the License.
16*/
17
18
19#define LOG_TAG "AudioFlinger"
20//#define LOG_NDEBUG 0
Alex Ray371eb972012-11-30 11:11:54 -080021#define ATRACE_TAG ATRACE_TAG_AUDIO
Eric Laurent81784c32012-11-19 14:55:58 -080022
Glenn Kasten153b9fe2013-07-15 11:23:36 -070023#include "Configuration.h"
Eric Laurent81784c32012-11-19 14:55:58 -080024#include <math.h>
25#include <fcntl.h>
Eric Tan7b651152018-07-13 10:17:19 -070026#include <memory>
Andy Hungb68f5eb2019-12-03 16:49:17 -080027#include <sstream>
Eric Tan7b651152018-07-13 10:17:19 -070028#include <string>
Glenn Kastenad8510a2015-02-17 16:24:07 -080029#include <linux/futex.h>
Eric Laurent81784c32012-11-19 14:55:58 -080030#include <sys/stat.h>
Glenn Kastenad8510a2015-02-17 16:24:07 -080031#include <sys/syscall.h>
Glenn Kastenc9a23672020-06-30 12:12:42 -070032#include <cutils/bitops.h>
Eric Laurent81784c32012-11-19 14:55:58 -080033#include <cutils/properties.h>
Vlad Popae8d99472022-06-30 16:02:48 +020034#include <binder/PersistableBundle.h>
jiabinc52b1ff2019-10-31 17:20:42 -070035#include <media/AudioContainers.h>
36#include <media/AudioDeviceTypeAddr.h>
Glenn Kasten1ab85ec2013-05-31 09:18:43 -070037#include <media/AudioParameter.h>
Andy Hungcd044842014-08-07 11:04:34 -070038#include <media/AudioResamplerPublic.h>
Andy Hung89816052017-01-11 17:08:23 -080039#include <media/RecordBufferConverter.h>
Mikhail Naganov913d06c2016-11-01 12:49:22 -070040#include <media/TypeConverter.h>
Eric Laurent81784c32012-11-19 14:55:58 -080041#include <utils/Log.h>
Alex Ray371eb972012-11-30 11:11:54 -080042#include <utils/Trace.h>
Eric Laurent81784c32012-11-19 14:55:58 -080043
44#include <private/media/AudioTrackShared.h>
Wei Jiaf2ae3e12016-10-27 17:10:59 -070045#include <private/android_filesystem_config.h>
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +010046#include <audio_utils/Balance.h>
jiabinf6eb4c32020-02-25 14:06:25 -080047#include <audio_utils/Metadata.h>
jiabin245cdd92018-12-07 17:55:15 -080048#include <audio_utils/channels.h>
Glenn Kasten6bf707f2017-02-23 16:53:58 -080049#include <audio_utils/mono_blend.h>
Eric Laurent81784c32012-11-19 14:55:58 -080050#include <audio_utils/primitives.h>
Andy Hung98ef9782014-03-04 14:46:50 -080051#include <audio_utils/format.h>
Glenn Kastenc56f3422014-03-21 17:53:17 -070052#include <audio_utils/minifloat.h>
Hongwei Wang95e37682019-04-12 11:13:36 -070053#include <audio_utils/safe_math.h>
Mikhail Naganov9fe94012016-10-14 14:57:40 -070054#include <system/audio_effects/effect_aec.h>
Eric Laurentb3f315a2021-07-13 15:09:05 +020055#include <system/audio_effects/effect_downmix.h>
56#include <system/audio_effects/effect_ns.h>
Eric Laurent1c5e2e32021-08-18 18:50:28 +020057#include <system/audio_effects/effect_spatializer.h>
Mikhail Naganovcbc8f612016-10-11 18:05:13 -070058#include <system/audio.h>
Eric Laurent81784c32012-11-19 14:55:58 -080059
60// NBAIO implementations
Glenn Kasten6dbb5e32014-05-13 10:38:42 -070061#include <media/nbaio/AudioStreamInSource.h>
Eric Laurent81784c32012-11-19 14:55:58 -080062#include <media/nbaio/AudioStreamOutSink.h>
63#include <media/nbaio/MonoPipe.h>
64#include <media/nbaio/MonoPipeReader.h>
65#include <media/nbaio/Pipe.h>
66#include <media/nbaio/PipeReader.h>
67#include <media/nbaio/SourceAudioBufferProvider.h>
Wei Jia3f273d12015-11-24 09:06:49 -080068#include <mediautils/BatteryNotifier.h>
Andy Hungafc51db2022-04-08 17:33:40 -070069#include <mediautils/Process.h>
Eric Laurent81784c32012-11-19 14:55:58 -080070
Mikhail Naganov2996f672019-04-18 12:29:59 -070071#include <audiomanager/AudioManager.h>
Eric Laurent81784c32012-11-19 14:55:58 -080072#include <powermanager/PowerManager.h>
73
Kevin Rocard7588ff42018-01-08 11:11:30 -080074#include <media/audiohal/EffectsFactoryHalInterface.h>
Kevin Rocard069c2712018-03-29 19:09:14 -070075#include <media/audiohal/StreamHalInterface.h>
Kevin Rocard7588ff42018-01-08 11:11:30 -080076
Eric Laurent81784c32012-11-19 14:55:58 -080077#include "AudioFlinger.h"
Eric Laurent81784c32012-11-19 14:55:58 -080078#include "FastMixer.h"
Glenn Kasten6dbb5e32014-05-13 10:38:42 -070079#include "FastCapture.h"
Andy Hungab7ef302018-05-15 19:35:29 -070080#include <mediautils/SchedulingPolicyService.h>
81#include <mediautils/ServiceUtilities.h>
Eric Laurent81784c32012-11-19 14:55:58 -080082
Eric Laurent81784c32012-11-19 14:55:58 -080083#ifdef ADD_BATTERY_DATA
84#include <media/IMediaPlayerService.h>
85#include <media/IMediaDeathNotifier.h>
86#endif
87
Eric Laurent81784c32012-11-19 14:55:58 -080088#ifdef DEBUG_CPU_USAGE
Eric Tan5b13ff82018-07-27 11:20:17 -070089#include <audio_utils/Statistics.h>
Eric Laurent81784c32012-11-19 14:55:58 -080090#include <cpustats/ThreadCpuUsage.h>
91#endif
92
Glenn Kastenc05b8d72016-03-24 09:48:17 -070093#include "AutoPark.h"
94
Nicolas Rouletfe1e1442017-01-30 12:02:03 -080095#include <pthread.h>
96#include "TypedLogger.h"
97
Eric Laurent81784c32012-11-19 14:55:58 -080098// ----------------------------------------------------------------------------
99
100// Note: the following macro is used for extremely verbose logging message. In
101// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
102// 0; but one side effect of this is to turn all LOGV's as well. Some messages
103// are so verbose that we want to suppress them even when we have ALOG_ASSERT
104// turned on. Do not uncomment the #def below unless you really know what you
105// are doing and want to see all of the extremely verbose messages.
106//#define VERY_VERY_VERBOSE_LOGGING
107#ifdef VERY_VERY_VERBOSE_LOGGING
108#define ALOGVV ALOGV
109#else
110#define ALOGVV(a...) do { } while(0)
111#endif
112
Andy Hung6770c6f2015-04-07 13:43:36 -0700113// TODO: Move these macro/inlines to a header file.
Glenn Kasten49d00ad2014-07-21 11:22:03 -0700114#define max(a, b) ((a) > (b) ? (a) : (b))
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700115
Andy Hung6770c6f2015-04-07 13:43:36 -0700116template <typename T>
117static inline T min(const T& a, const T& b)
118{
119 return a < b ? a : b;
120}
Glenn Kasten49d00ad2014-07-21 11:22:03 -0700121
Eric Laurent81784c32012-11-19 14:55:58 -0800122namespace android {
123
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -0700124using media::IEffectClient;
Svet Ganov33761132021-05-13 22:51:08 +0000125using content::AttributionSourceState;
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -0700126
Eric Laurent81784c32012-11-19 14:55:58 -0800127// retry counts for buffer fill timeout
128// 50 * ~20msecs = 1 second
129static const int8_t kMaxTrackRetries = 50;
130static const int8_t kMaxTrackStartupRetries = 50;
Andy Hung455982f2021-04-27 17:46:12 -0700131
Eric Laurent81784c32012-11-19 14:55:58 -0800132// allow less retry attempts on direct output thread.
133// direct outputs can be a scarce resource in audio hardware and should
134// be released as quickly as possible.
Andy Hung455982f2021-04-27 17:46:12 -0700135// Notes:
136// 1) The retry duration kMaxTrackRetriesDirectMs may be increased
137// in case the data write is bursty for the AudioTrack. The application
138// should endeavor to write at least once every kMaxTrackRetriesDirectMs
139// to prevent an underrun situation. If the data is bursty, then
140// the application can also throttle the data sent to be even.
141// 2) For compressed audio data, any data present in the AudioTrack buffer
142// will be sent and reset the retry count. This delivers data as
143// it arrives, with approximately kDirectMinSleepTimeUs = 10ms checking interval.
144// 3) For linear PCM or proportional PCM, we wait one period for a period's worth
145// of data to be available, then any remaining data is delivered.
146// This is required to ensure the last bit of data is delivered before underrun.
147//
148// Sleep time per cycle is kDirectMinSleepTimeUs for compressed tracks
149// or the size of the HAL period for proportional / linear PCM tracks.
150static const int32_t kMaxTrackRetriesDirectMs = 200;
Eric Laurent81784c32012-11-19 14:55:58 -0800151
152// don't warn about blocked writes or record buffer overflows more often than this
153static const nsecs_t kWarningThrottleNs = seconds(5);
154
155// RecordThread loop sleep time upon application overrun or audio HAL read error
156static const int kRecordThreadSleepUs = 5000;
157
Eric Laurent10351942014-05-08 18:49:52 -0700158// maximum time to wait in sendConfigEvent_l() for a status to be received
159static const nsecs_t kConfigEventTimeoutNs = seconds(2);
Eric Laurent81784c32012-11-19 14:55:58 -0800160
161// minimum sleep time for the mixer thread loop when tracks are active but in underrun
162static const uint32_t kMinThreadSleepTimeUs = 5000;
163// maximum divider applied to the active sleep time in the mixer thread loop
164static const uint32_t kMaxThreadSleepTimeShift = 2;
165
Andy Hung09a50072014-02-27 14:30:47 -0800166// minimum normal sink buffer size, expressed in milliseconds rather than frames
Glenn Kasteneb9487e2015-07-22 09:15:17 -0700167// FIXME This should be based on experimentally observed scheduling jitter
Andy Hung09a50072014-02-27 14:30:47 -0800168static const uint32_t kMinNormalSinkBufferSizeMs = 20;
169// maximum normal sink buffer size
170static const uint32_t kMaxNormalSinkBufferSizeMs = 24;
Eric Laurent81784c32012-11-19 14:55:58 -0800171
Glenn Kasteneb9487e2015-07-22 09:15:17 -0700172// minimum capture buffer size in milliseconds to _not_ need a fast capture thread
173// FIXME This should be based on experimentally observed scheduling jitter
174static const uint32_t kMinNormalCaptureBufferSizeMs = 12;
175
Eric Laurent972a1732013-09-04 09:42:59 -0700176// Offloaded output thread standby delay: allows track transition without going to standby
177static const nsecs_t kOffloadStandbyDelayNs = seconds(1);
178
Eric Laurent51716182016-02-29 18:00:56 -0800179// Direct output thread minimum sleep time in idle or active(underrun) state
180static const nsecs_t kDirectMinSleepTimeUs = 10000;
181
Brian Lindahl65e90012022-07-27 18:01:07 +0200182// Minimum amount of time between checking to see if the timestamp is advancing
183// for underrun detection. If we check too frequently, we may not detect a
184// timestamp update and will falsely detect underrun.
185static const nsecs_t kMinimumTimeBetweenTimestampChecksNs = 150 /* ms */ * 1000;
186
Glenn Kasten1b291842016-07-18 14:55:21 -0700187// The universal constant for ubiquitous 20ms value. The value of 20ms seems to provide a good
188// balance between power consumption and latency, and allows threads to be scheduled reliably
189// by the CFS scheduler.
190// FIXME Express other hardcoded references to 20ms with references to this constant and move
191// it appropriately.
192#define FMS_20 20
Eric Laurent51716182016-02-29 18:00:56 -0800193
Eric Laurent81784c32012-11-19 14:55:58 -0800194// Whether to use fast mixer
195static const enum {
196 FastMixer_Never, // never initialize or use: for debugging only
197 FastMixer_Always, // always initialize and use, even if not needed: for debugging only
198 // normal mixer multiplier is 1
199 FastMixer_Static, // initialize if needed, then use all the time if initialized,
200 // multiplier is calculated based on min & max normal mixer buffer size
201 FastMixer_Dynamic, // initialize if needed, then use dynamically depending on track load,
202 // multiplier is calculated based on min & max normal mixer buffer size
203 // FIXME for FastMixer_Dynamic:
204 // Supporting this option will require fixing HALs that can't handle large writes.
205 // For example, one HAL implementation returns an error from a large write,
206 // and another HAL implementation corrupts memory, possibly in the sample rate converter.
207 // We could either fix the HAL implementations, or provide a wrapper that breaks
208 // up large writes into smaller ones, and the wrapper would need to deal with scheduler.
209} kUseFastMixer = FastMixer_Static;
210
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700211// Whether to use fast capture
212static const enum {
213 FastCapture_Never, // never initialize or use: for debugging only
214 FastCapture_Always, // always initialize and use, even if not needed: for debugging only
215 FastCapture_Static, // initialize if needed, then use all the time if initialized
216} kUseFastCapture = FastCapture_Static;
217
Eric Laurent81784c32012-11-19 14:55:58 -0800218// Priorities for requestPriority
219static const int kPriorityAudioApp = 2;
220static const int kPriorityFastMixer = 3;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700221static const int kPriorityFastCapture = 3;
Eric Laurent81784c32012-11-19 14:55:58 -0800222
Glenn Kastenea38ee72016-04-18 11:08:01 -0700223// IAudioFlinger::createTrack() has an in/out parameter 'pFrameCount' for the total size of the
224// track buffer in shared memory. Zero on input means to use a default value. For fast tracks,
225// AudioFlinger derives the default from HAL buffer size and 'fast track multiplier'.
Glenn Kasten03490092014-05-27 12:30:54 -0700226
227// This is the default value, if not specified by property.
Glenn Kastenb5fed682013-12-03 09:06:43 -0800228static const int kFastTrackMultiplier = 2;
Eric Laurent81784c32012-11-19 14:55:58 -0800229
Glenn Kasten03490092014-05-27 12:30:54 -0700230// The minimum and maximum allowed values
231static const int kFastTrackMultiplierMin = 1;
232static const int kFastTrackMultiplierMax = 2;
233
234// The actual value to use, which can be specified per-device via property af.fast_track_multiplier.
235static int sFastTrackMultiplier = kFastTrackMultiplier;
236
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700237// See Thread::readOnlyHeap().
238// Initially this heap is used to allocate client buffers for "fast" AudioRecord.
239// Eventually it will be the single buffer that FastCapture writes into via HAL read(),
240// and that all "fast" AudioRecord clients read from. In either case, the size can be small.
Mikhail Naganov79a77822018-05-10 15:57:25 -0700241static const size_t kRecordThreadReadOnlyHeapSize = 0xD000;
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700242
Eric Laurent81784c32012-11-19 14:55:58 -0800243// ----------------------------------------------------------------------------
244
Andy Hungb68f5eb2019-12-03 16:49:17 -0800245// TODO: move all toString helpers to audio.h
246// under #ifdef __cplusplus #endif
247static std::string patchSinksToString(const struct audio_patch *patch)
248{
249 std::stringstream ss;
250 for (size_t i = 0; i < patch->num_sinks; ++i) {
Andy Hungc2b11cb2020-04-22 09:04:01 -0700251 if (i > 0) {
252 ss << "|";
253 }
Andy Hungb68f5eb2019-12-03 16:49:17 -0800254 ss << "(" << toString(patch->sinks[i].ext.device.type)
255 << ", " << patch->sinks[i].ext.device.address << ")";
256 }
257 return ss.str();
258}
259
260static std::string patchSourcesToString(const struct audio_patch *patch)
261{
262 std::stringstream ss;
263 for (size_t i = 0; i < patch->num_sources; ++i) {
Andy Hungc2b11cb2020-04-22 09:04:01 -0700264 if (i > 0) {
265 ss << "|";
266 }
Andy Hungb68f5eb2019-12-03 16:49:17 -0800267 ss << "(" << toString(patch->sources[i].ext.device.type)
268 << ", " << patch->sources[i].ext.device.address << ")";
269 }
270 return ss.str();
271}
272
Glenn Kasten03490092014-05-27 12:30:54 -0700273static pthread_once_t sFastTrackMultiplierOnce = PTHREAD_ONCE_INIT;
274
275static void sFastTrackMultiplierInit()
276{
277 char value[PROPERTY_VALUE_MAX];
278 if (property_get("af.fast_track_multiplier", value, NULL) > 0) {
279 char *endptr;
280 unsigned long ul = strtoul(value, &endptr, 0);
281 if (*endptr == '\0' && kFastTrackMultiplierMin <= ul && ul <= kFastTrackMultiplierMax) {
282 sFastTrackMultiplier = (int) ul;
283 }
284 }
285}
286
287// ----------------------------------------------------------------------------
288
Eric Laurent81784c32012-11-19 14:55:58 -0800289#ifdef ADD_BATTERY_DATA
290// To collect the amplifier usage
291static void addBatteryData(uint32_t params) {
292 sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService();
293 if (service == NULL) {
294 // it already logged
295 return;
296 }
297
298 service->addBatteryData(params);
299}
300#endif
301
Andy Hung3f0c9022016-01-15 17:49:46 -0800302// Track the CLOCK_BOOTTIME versus CLOCK_MONOTONIC timebase offset
303struct {
304 // call when you acquire a partial wakelock
305 void acquire(const sp<IBinder> &wakeLockToken) {
306 pthread_mutex_lock(&mLock);
307 if (wakeLockToken.get() == nullptr) {
308 adjustTimebaseOffset(&mBoottimeOffset, ExtendedTimestamp::TIMEBASE_BOOTTIME);
309 } else {
310 if (mCount == 0) {
311 adjustTimebaseOffset(&mBoottimeOffset, ExtendedTimestamp::TIMEBASE_BOOTTIME);
312 }
313 ++mCount;
314 }
315 pthread_mutex_unlock(&mLock);
316 }
317
318 // call when you release a partial wakelock.
319 void release(const sp<IBinder> &wakeLockToken) {
320 if (wakeLockToken.get() == nullptr) {
321 return;
322 }
323 pthread_mutex_lock(&mLock);
324 if (--mCount < 0) {
325 ALOGE("negative wakelock count");
326 mCount = 0;
327 }
328 pthread_mutex_unlock(&mLock);
329 }
330
331 // retrieves the boottime timebase offset from monotonic.
332 int64_t getBoottimeOffset() {
333 pthread_mutex_lock(&mLock);
334 int64_t boottimeOffset = mBoottimeOffset;
335 pthread_mutex_unlock(&mLock);
336 return boottimeOffset;
337 }
338
339 // Adjusts the timebase offset between TIMEBASE_MONOTONIC
340 // and the selected timebase.
341 // Currently only TIMEBASE_BOOTTIME is allowed.
342 //
343 // This only needs to be called upon acquiring the first partial wakelock
344 // after all other partial wakelocks are released.
345 //
346 // We do an empirical measurement of the offset rather than parsing
347 // /proc/timer_list since the latter is not a formal kernel ABI.
348 static void adjustTimebaseOffset(int64_t *offset, ExtendedTimestamp::Timebase timebase) {
349 int clockbase;
350 switch (timebase) {
351 case ExtendedTimestamp::TIMEBASE_BOOTTIME:
352 clockbase = SYSTEM_TIME_BOOTTIME;
353 break;
354 default:
355 LOG_ALWAYS_FATAL("invalid timebase %d", timebase);
356 break;
357 }
358 // try three times to get the clock offset, choose the one
359 // with the minimum gap in measurements.
360 const int tries = 3;
361 nsecs_t bestGap, measured;
362 for (int i = 0; i < tries; ++i) {
363 const nsecs_t tmono = systemTime(SYSTEM_TIME_MONOTONIC);
364 const nsecs_t tbase = systemTime(clockbase);
365 const nsecs_t tmono2 = systemTime(SYSTEM_TIME_MONOTONIC);
366 const nsecs_t gap = tmono2 - tmono;
367 if (i == 0 || gap < bestGap) {
368 bestGap = gap;
369 measured = tbase - ((tmono + tmono2) >> 1);
370 }
371 }
372
373 // to avoid micro-adjusting, we don't change the timebase
374 // unless it is significantly different.
375 //
376 // Assumption: It probably takes more than toleranceNs to
377 // suspend and resume the device.
378 static int64_t toleranceNs = 10000; // 10 us
379 if (llabs(*offset - measured) > toleranceNs) {
380 ALOGV("Adjusting timebase offset old: %lld new: %lld",
381 (long long)*offset, (long long)measured);
382 *offset = measured;
383 }
384 }
385
386 pthread_mutex_t mLock;
387 int32_t mCount;
388 int64_t mBoottimeOffset;
389} gBoottime = { PTHREAD_MUTEX_INITIALIZER, 0, 0 }; // static, so use POD initialization
Eric Laurent81784c32012-11-19 14:55:58 -0800390
391// ----------------------------------------------------------------------------
392// CPU Stats
393// ----------------------------------------------------------------------------
394
395class CpuStats {
396public:
397 CpuStats();
398 void sample(const String8 &title);
399#ifdef DEBUG_CPU_USAGE
400private:
401 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns
Andy Hung16698b82018-08-01 10:48:38 -0700402 audio_utils::Statistics<double> mWcStats; // statistics on thread CPU usage in wall clock ns
Eric Laurent81784c32012-11-19 14:55:58 -0800403
Andy Hung16698b82018-08-01 10:48:38 -0700404 audio_utils::Statistics<double> mHzStats; // statistics on thread CPU usage in cycles
Eric Laurent81784c32012-11-19 14:55:58 -0800405
406 int mCpuNum; // thread's current CPU number
407 int mCpukHz; // frequency of thread's current CPU in kHz
408#endif
409};
410
411CpuStats::CpuStats()
412#ifdef DEBUG_CPU_USAGE
413 : mCpuNum(-1), mCpukHz(-1)
414#endif
415{
416}
417
Glenn Kasten0f11b512014-01-31 16:18:54 -0800418void CpuStats::sample(const String8 &title
419#ifndef DEBUG_CPU_USAGE
420 __unused
421#endif
422 ) {
Eric Laurent81784c32012-11-19 14:55:58 -0800423#ifdef DEBUG_CPU_USAGE
424 // get current thread's delta CPU time in wall clock ns
425 double wcNs;
426 bool valid = mCpuUsage.sampleAndEnable(wcNs);
427
428 // record sample for wall clock statistics
429 if (valid) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700430 mWcStats.add(wcNs);
Eric Laurent81784c32012-11-19 14:55:58 -0800431 }
432
433 // get the current CPU number
434 int cpuNum = sched_getcpu();
435
436 // get the current CPU frequency in kHz
437 int cpukHz = mCpuUsage.getCpukHz(cpuNum);
438
439 // check if either CPU number or frequency changed
440 if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
441 mCpuNum = cpuNum;
442 mCpukHz = cpukHz;
443 // ignore sample for purposes of cycles
444 valid = false;
445 }
446
447 // if no change in CPU number or frequency, then record sample for cycle statistics
448 if (valid && mCpukHz > 0) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700449 const double cycles = wcNs * cpukHz * 0.000001;
450 mHzStats.add(cycles);
Eric Laurent81784c32012-11-19 14:55:58 -0800451 }
452
Eric Tan5b13ff82018-07-27 11:20:17 -0700453 const unsigned n = mWcStats.getN();
Eric Laurent81784c32012-11-19 14:55:58 -0800454 // mCpuUsage.elapsed() is expensive, so don't call it every loop
455 if ((n & 127) == 1) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700456 const long long elapsed = mCpuUsage.elapsed();
Eric Laurent81784c32012-11-19 14:55:58 -0800457 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700458 const double perLoop = elapsed / (double) n;
459 const double perLoop100 = perLoop * 0.01;
460 const double perLoop1k = perLoop * 0.001;
461 const double mean = mWcStats.getMean();
462 const double stddev = mWcStats.getStdDev();
463 const double minimum = mWcStats.getMin();
464 const double maximum = mWcStats.getMax();
465 const double meanCycles = mHzStats.getMean();
466 const double stddevCycles = mHzStats.getStdDev();
467 const double minCycles = mHzStats.getMin();
468 const double maxCycles = mHzStats.getMax();
Eric Laurent81784c32012-11-19 14:55:58 -0800469 mCpuUsage.resetElapsed();
470 mWcStats.reset();
471 mHzStats.reset();
472 ALOGD("CPU usage for %s over past %.1f secs\n"
473 " (%u mixer loops at %.1f mean ms per loop):\n"
474 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
475 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
476 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
477 title.string(),
478 elapsed * .000000001, n, perLoop * .000001,
479 mean * .001,
480 stddev * .001,
481 minimum * .001,
482 maximum * .001,
483 mean / perLoop100,
484 stddev / perLoop100,
485 minimum / perLoop100,
486 maximum / perLoop100,
487 meanCycles / perLoop1k,
488 stddevCycles / perLoop1k,
489 minCycles / perLoop1k,
490 maxCycles / perLoop1k);
491
492 }
493 }
494#endif
495};
496
497// ----------------------------------------------------------------------------
498// ThreadBase
499// ----------------------------------------------------------------------------
500
Glenn Kasten97b7b752014-09-28 13:04:24 -0700501// static
502const char *AudioFlinger::ThreadBase::threadTypeToString(AudioFlinger::ThreadBase::type_t type)
503{
504 switch (type) {
505 case MIXER:
506 return "MIXER";
507 case DIRECT:
508 return "DIRECT";
509 case DUPLICATING:
510 return "DUPLICATING";
511 case RECORD:
512 return "RECORD";
513 case OFFLOAD:
514 return "OFFLOAD";
Andy Hungea840382020-05-05 21:50:17 -0700515 case MMAP_PLAYBACK:
516 return "MMAP_PLAYBACK";
517 case MMAP_CAPTURE:
518 return "MMAP_CAPTURE";
Eric Laurent1c5e2e32021-08-18 18:50:28 +0200519 case SPATIALIZER:
520 return "SPATIALIZER";
Glenn Kasten97b7b752014-09-28 13:04:24 -0700521 default:
522 return "unknown";
523 }
524}
525
Eric Laurent81784c32012-11-19 14:55:58 -0800526AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
Andy Hungcf10d742020-04-28 15:38:24 -0700527 type_t type, bool systemReady, bool isOut)
Eric Laurent81784c32012-11-19 14:55:58 -0800528 : Thread(false /*canCallJava*/),
529 mType(type),
Glenn Kasten9b58f632013-07-16 11:37:48 -0700530 mAudioFlinger(audioFlinger),
Andy Hungcf10d742020-04-28 15:38:24 -0700531 mThreadMetrics(std::string(AMEDIAMETRICS_KEY_PREFIX_AUDIO_THREAD) + std::to_string(id),
532 isOut),
533 mIsOut(isOut),
Glenn Kasten70949c42013-08-06 07:40:12 -0700534 // mSampleRate, mFrameCount, mChannelMask, mChannelCount, mFrameSize, mFormat, mBufferSize
Glenn Kastendeca2ae2014-02-07 10:25:56 -0800535 // are set by PlaybackThread::readOutputParameters_l() or
536 // RecordThread::readInputParameters_l()
Eric Laurentfd477972013-10-25 18:10:40 -0700537 //FIXME: mStandby should be true here. Is this some kind of hack?
jiabinc52b1ff2019-10-31 17:20:42 -0700538 mStandby(false),
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700539 mAudioSource(AUDIO_SOURCE_DEFAULT), mId(id),
Eric Laurent81784c32012-11-19 14:55:58 -0800540 // mName will be set by concrete (non-virtual) subclass
Eric Laurent72e3f392015-05-20 14:43:50 -0700541 mDeathRecipient(new PMDeathRecipient(this)),
Eric Laurent6acd1d42017-01-04 14:23:29 -0800542 mSystemReady(systemReady),
543 mSignalPending(false)
Eric Laurent81784c32012-11-19 14:55:58 -0800544{
Andy Hungcf10d742020-04-28 15:38:24 -0700545 mThreadMetrics.logConstructor(getpid(), threadTypeToString(type), id);
Eric Laurent296fb132015-05-01 11:38:42 -0700546 memset(&mPatch, 0, sizeof(struct audio_patch));
Eric Laurent81784c32012-11-19 14:55:58 -0800547}
548
549AudioFlinger::ThreadBase::~ThreadBase()
550{
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700551 // mConfigEvents should be empty, but just in case it isn't, free the memory it owns
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700552 mConfigEvents.clear();
553
Eric Laurent81784c32012-11-19 14:55:58 -0800554 // do not lock the mutex in destructor
555 releaseWakeLock_l();
556 if (mPowerManager != 0) {
Marco Nelissen06b46062014-11-14 07:58:25 -0800557 sp<IBinder> binder = IInterface::asBinder(mPowerManager);
Eric Laurent81784c32012-11-19 14:55:58 -0800558 binder->unlinkToDeath(mDeathRecipient);
559 }
Andy Hungd0979812019-02-21 15:51:44 -0800560
561 sendStatistics(true /* force */);
Eric Laurent81784c32012-11-19 14:55:58 -0800562}
563
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700564status_t AudioFlinger::ThreadBase::readyToRun()
565{
566 status_t status = initCheck();
567 if (status == NO_ERROR) {
Glenn Kasten1bfe09a2017-02-21 13:05:56 -0800568 ALOGI("AudioFlinger's thread %p tid=%d ready to run", this, getTid());
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700569 } else {
570 ALOGE("No working audio driver found.");
571 }
572 return status;
573}
574
Eric Laurent81784c32012-11-19 14:55:58 -0800575void AudioFlinger::ThreadBase::exit()
576{
577 ALOGV("ThreadBase::exit");
578 // do any cleanup required for exit to succeed
579 preExit();
580 {
581 // This lock prevents the following race in thread (uniprocessor for illustration):
582 // if (!exitPending()) {
583 // // context switch from here to exit()
584 // // exit() calls requestExit(), what exitPending() observes
585 // // exit() calls signal(), which is dropped since no waiters
586 // // context switch back from exit() to here
587 // mWaitWorkCV.wait(...);
588 // // now thread is hung
589 // }
590 AutoMutex lock(mLock);
591 requestExit();
592 mWaitWorkCV.broadcast();
593 }
594 // When Thread::requestExitAndWait is made virtual and this method is renamed to
595 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
596 requestExitAndWait();
597}
598
599status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
600{
Eric Laurent81784c32012-11-19 14:55:58 -0800601 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
602 Mutex::Autolock _l(mLock);
603
Eric Laurent10351942014-05-08 18:49:52 -0700604 return sendSetParameterConfigEvent_l(keyValuePairs);
605}
606
607// sendConfigEvent_l() must be called with ThreadBase::mLock held
608// Can temporarily release the lock if waiting for a reply from processConfigEvents_l().
609status_t AudioFlinger::ThreadBase::sendConfigEvent_l(sp<ConfigEvent>& event)
610{
611 status_t status = NO_ERROR;
612
Eric Laurent72e3f392015-05-20 14:43:50 -0700613 if (event->mRequiresSystemReady && !mSystemReady) {
614 event->mWaitStatus = false;
615 mPendingConfigEvents.add(event);
616 return status;
617 }
Eric Laurent10351942014-05-08 18:49:52 -0700618 mConfigEvents.add(event);
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700619 ALOGV("sendConfigEvent_l() num events %zu event %d", mConfigEvents.size(), event->mType);
Eric Laurent81784c32012-11-19 14:55:58 -0800620 mWaitWorkCV.signal();
Eric Laurent10351942014-05-08 18:49:52 -0700621 mLock.unlock();
622 {
623 Mutex::Autolock _l(event->mLock);
624 while (event->mWaitStatus) {
625 if (event->mCond.waitRelative(event->mLock, kConfigEventTimeoutNs) != NO_ERROR) {
626 event->mStatus = TIMED_OUT;
627 event->mWaitStatus = false;
628 }
629 }
630 status = event->mStatus;
Eric Laurent81784c32012-11-19 14:55:58 -0800631 }
Eric Laurent10351942014-05-08 18:49:52 -0700632 mLock.lock();
Eric Laurent81784c32012-11-19 14:55:58 -0800633 return status;
634}
635
Mikhail Naganov88536df2021-07-26 17:30:29 -0700636void AudioFlinger::ThreadBase::sendIoConfigEvent(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -0700637 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -0800638{
639 Mutex::Autolock _l(mLock);
Eric Laurent09f1ed22019-04-24 17:45:17 -0700640 sendIoConfigEvent_l(event, pid, portId);
Eric Laurent81784c32012-11-19 14:55:58 -0800641}
642
643// sendIoConfigEvent_l() must be called with ThreadBase::mLock held
Mikhail Naganov88536df2021-07-26 17:30:29 -0700644void AudioFlinger::ThreadBase::sendIoConfigEvent_l(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -0700645 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -0800646{
Andy Hungd0979812019-02-21 15:51:44 -0800647 // The audio statistics history is exponentially weighted to forget events
648 // about five or more seconds in the past. In order to have
649 // crisper statistics for mediametrics, we reset the statistics on
650 // an IoConfigEvent, to reflect different properties for a new device.
651 mIoJitterMs.reset();
652 mLatencyMs.reset();
653 mProcessTimeMs.reset();
Robert Wu06db0a32021-08-10 19:05:34 +0000654 mMonopipePipeDepthStats.reset();
Dean Wheatley12473e92021-03-18 23:00:55 +1100655 mTimestampVerifier.discontinuity(mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS);
Andy Hungd0979812019-02-21 15:51:44 -0800656
Eric Laurent09f1ed22019-04-24 17:45:17 -0700657 sp<ConfigEvent> configEvent = (ConfigEvent *)new IoConfigEvent(event, pid, portId);
Eric Laurent10351942014-05-08 18:49:52 -0700658 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800659}
660
Mikhail Naganov83f04272017-02-07 10:45:09 -0800661void AudioFlinger::ThreadBase::sendPrioConfigEvent(pid_t pid, pid_t tid, int32_t prio, bool forApp)
Eric Laurent72e3f392015-05-20 14:43:50 -0700662{
663 Mutex::Autolock _l(mLock);
Mikhail Naganov83f04272017-02-07 10:45:09 -0800664 sendPrioConfigEvent_l(pid, tid, prio, forApp);
Eric Laurent72e3f392015-05-20 14:43:50 -0700665}
666
Eric Laurent81784c32012-11-19 14:55:58 -0800667// sendPrioConfigEvent_l() must be called with ThreadBase::mLock held
Mikhail Naganov83f04272017-02-07 10:45:09 -0800668void AudioFlinger::ThreadBase::sendPrioConfigEvent_l(
669 pid_t pid, pid_t tid, int32_t prio, bool forApp)
Eric Laurent81784c32012-11-19 14:55:58 -0800670{
Mikhail Naganov83f04272017-02-07 10:45:09 -0800671 sp<ConfigEvent> configEvent = (ConfigEvent *)new PrioConfigEvent(pid, tid, prio, forApp);
Eric Laurent10351942014-05-08 18:49:52 -0700672 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800673}
674
Eric Laurent10351942014-05-08 18:49:52 -0700675// sendSetParameterConfigEvent_l() must be called with ThreadBase::mLock held
676status_t AudioFlinger::ThreadBase::sendSetParameterConfigEvent_l(const String8& keyValuePair)
Eric Laurent81784c32012-11-19 14:55:58 -0800677{
Andy Hung2ddee192015-12-18 17:34:44 -0800678 sp<ConfigEvent> configEvent;
679 AudioParameter param(keyValuePair);
680 int value;
Mikhail Naganov00260b52016-10-13 12:54:24 -0700681 if (param.getInt(String8(AudioParameter::keyMonoOutput), value) == NO_ERROR) {
Andy Hung2ddee192015-12-18 17:34:44 -0800682 setMasterMono_l(value != 0);
683 if (param.size() == 1) {
684 return NO_ERROR; // should be a solo parameter - we don't pass down
685 }
Mikhail Naganov00260b52016-10-13 12:54:24 -0700686 param.remove(String8(AudioParameter::keyMonoOutput));
Andy Hung2ddee192015-12-18 17:34:44 -0800687 configEvent = new SetParameterConfigEvent(param.toString());
688 } else {
689 configEvent = new SetParameterConfigEvent(keyValuePair);
690 }
Eric Laurent10351942014-05-08 18:49:52 -0700691 return sendConfigEvent_l(configEvent);
Glenn Kastenf7773312013-08-13 16:00:42 -0700692}
693
Eric Laurent1c333e22014-05-20 10:48:17 -0700694status_t AudioFlinger::ThreadBase::sendCreateAudioPatchConfigEvent(
695 const struct audio_patch *patch,
696 audio_patch_handle_t *handle)
697{
698 Mutex::Autolock _l(mLock);
699 sp<ConfigEvent> configEvent = (ConfigEvent *)new CreateAudioPatchConfigEvent(*patch, *handle);
700 status_t status = sendConfigEvent_l(configEvent);
701 if (status == NO_ERROR) {
702 CreateAudioPatchConfigEventData *data =
703 (CreateAudioPatchConfigEventData *)configEvent->mData.get();
704 *handle = data->mHandle;
705 }
706 return status;
707}
708
709status_t AudioFlinger::ThreadBase::sendReleaseAudioPatchConfigEvent(
710 const audio_patch_handle_t handle)
711{
712 Mutex::Autolock _l(mLock);
713 sp<ConfigEvent> configEvent = (ConfigEvent *)new ReleaseAudioPatchConfigEvent(handle);
714 return sendConfigEvent_l(configEvent);
715}
716
jiabinc52b1ff2019-10-31 17:20:42 -0700717status_t AudioFlinger::ThreadBase::sendUpdateOutDeviceConfigEvent(
718 const DeviceDescriptorBaseVector& outDevices)
719{
720 if (type() != RECORD) {
721 // The update out device operation is only for record thread.
722 return INVALID_OPERATION;
723 }
724 Mutex::Autolock _l(mLock);
725 sp<ConfigEvent> configEvent = (ConfigEvent *)new UpdateOutDevicesConfigEvent(outDevices);
726 return sendConfigEvent_l(configEvent);
727}
728
Eric Laurentec376dc2021-04-08 20:41:22 +0200729void AudioFlinger::ThreadBase::sendResizeBufferConfigEvent_l(int32_t maxSharedAudioHistoryMs)
730{
731 ALOG_ASSERT(type() == RECORD, "sendResizeBufferConfigEvent_l() called on non record thread");
732 sp<ConfigEvent> configEvent =
733 (ConfigEvent *)new ResizeBufferConfigEvent(maxSharedAudioHistoryMs);
734 sendConfigEvent_l(configEvent);
735}
Eric Laurent1c333e22014-05-20 10:48:17 -0700736
Eric Laurentb3f315a2021-07-13 15:09:05 +0200737void AudioFlinger::ThreadBase::sendCheckOutputStageEffectsEvent()
738{
739 Mutex::Autolock _l(mLock);
740 sendCheckOutputStageEffectsEvent_l();
741}
742
743void AudioFlinger::ThreadBase::sendCheckOutputStageEffectsEvent_l()
744{
745 sp<ConfigEvent> configEvent =
746 (ConfigEvent *)new CheckOutputStageEffectsEvent();
747 sendConfigEvent_l(configEvent);
748}
749
Eric Laurent68a40a82022-05-03 18:15:04 +0200750void AudioFlinger::ThreadBase::sendHalLatencyModesChangedEvent_l()
751{
752 sp<ConfigEvent> configEvent = sp<HalLatencyModesChangedEvent>::make();
753 sendConfigEvent_l(configEvent);
754}
755
Glenn Kasten2cfbf882013-08-14 13:12:11 -0700756// post condition: mConfigEvents.isEmpty()
Eric Laurent021cf962014-05-13 10:18:14 -0700757void AudioFlinger::ThreadBase::processConfigEvents_l()
Glenn Kastenf7773312013-08-13 16:00:42 -0700758{
Eric Laurent10351942014-05-08 18:49:52 -0700759 bool configChanged = false;
760
Eric Laurent81784c32012-11-19 14:55:58 -0800761 while (!mConfigEvents.isEmpty()) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700762 ALOGV("processConfigEvents_l() remaining events %zu", mConfigEvents.size());
Eric Laurent10351942014-05-08 18:49:52 -0700763 sp<ConfigEvent> event = mConfigEvents[0];
Eric Laurent81784c32012-11-19 14:55:58 -0800764 mConfigEvents.removeAt(0);
Eric Laurent10351942014-05-08 18:49:52 -0700765 switch (event->mType) {
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700766 case CFG_EVENT_PRIO: {
Eric Laurent10351942014-05-08 18:49:52 -0700767 PrioConfigEventData *data = (PrioConfigEventData *)event->mData.get();
768 // FIXME Need to understand why this has to be done asynchronously
Mikhail Naganov83f04272017-02-07 10:45:09 -0800769 int err = requestPriority(data->mPid, data->mTid, data->mPrio, data->mForApp,
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700770 true /*asynchronous*/);
771 if (err != 0) {
772 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Eric Laurent10351942014-05-08 18:49:52 -0700773 data->mPrio, data->mPid, data->mTid, err);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700774 }
775 } break;
776 case CFG_EVENT_IO: {
Eric Laurent10351942014-05-08 18:49:52 -0700777 IoConfigEventData *data = (IoConfigEventData *)event->mData.get();
Eric Laurent09f1ed22019-04-24 17:45:17 -0700778 ioConfigChanged(data->mEvent, data->mPid, data->mPortId);
Eric Laurent10351942014-05-08 18:49:52 -0700779 } break;
780 case CFG_EVENT_SET_PARAMETER: {
781 SetParameterConfigEventData *data = (SetParameterConfigEventData *)event->mData.get();
782 if (checkForNewParameter_l(data->mKeyValuePairs, event->mStatus)) {
783 configChanged = true;
Andy Hung293558a2017-03-21 12:19:20 -0700784 mLocalLog.log("CFG_EVENT_SET_PARAMETER: (%s) configuration changed",
785 data->mKeyValuePairs.string());
Glenn Kastend5418eb2013-08-14 13:11:06 -0700786 }
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700787 } break;
Eric Laurent1c333e22014-05-20 10:48:17 -0700788 case CFG_EVENT_CREATE_AUDIO_PATCH: {
jiabinc52b1ff2019-10-31 17:20:42 -0700789 const DeviceTypeSet oldDevices = getDeviceTypes();
Eric Laurent1c333e22014-05-20 10:48:17 -0700790 CreateAudioPatchConfigEventData *data =
791 (CreateAudioPatchConfigEventData *)event->mData.get();
792 event->mStatus = createAudioPatch_l(&data->mPatch, &data->mHandle);
jiabinc52b1ff2019-10-31 17:20:42 -0700793 const DeviceTypeSet newDevices = getDeviceTypes();
794 mLocalLog.log("CFG_EVENT_CREATE_AUDIO_PATCH: old device %s (%s) new device %s (%s)",
795 dumpDeviceTypes(oldDevices).c_str(), toString(oldDevices).c_str(),
796 dumpDeviceTypes(newDevices).c_str(), toString(newDevices).c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -0700797 } break;
798 case CFG_EVENT_RELEASE_AUDIO_PATCH: {
jiabinc52b1ff2019-10-31 17:20:42 -0700799 const DeviceTypeSet oldDevices = getDeviceTypes();
Eric Laurent1c333e22014-05-20 10:48:17 -0700800 ReleaseAudioPatchConfigEventData *data =
801 (ReleaseAudioPatchConfigEventData *)event->mData.get();
802 event->mStatus = releaseAudioPatch_l(data->mHandle);
jiabinc52b1ff2019-10-31 17:20:42 -0700803 const DeviceTypeSet newDevices = getDeviceTypes();
804 mLocalLog.log("CFG_EVENT_RELEASE_AUDIO_PATCH: old device %s (%s) new device %s (%s)",
805 dumpDeviceTypes(oldDevices).c_str(), toString(oldDevices).c_str(),
806 dumpDeviceTypes(newDevices).c_str(), toString(newDevices).c_str());
807 } break;
808 case CFG_EVENT_UPDATE_OUT_DEVICE: {
809 UpdateOutDevicesConfigEventData *data =
810 (UpdateOutDevicesConfigEventData *)event->mData.get();
811 updateOutDevices(data->mOutDevices);
Eric Laurent1c333e22014-05-20 10:48:17 -0700812 } break;
Eric Laurentec376dc2021-04-08 20:41:22 +0200813 case CFG_EVENT_RESIZE_BUFFER: {
814 ResizeBufferConfigEventData *data =
815 (ResizeBufferConfigEventData *)event->mData.get();
816 resizeInputBuffer_l(data->mMaxSharedAudioHistoryMs);
817 } break;
Eric Laurentb3f315a2021-07-13 15:09:05 +0200818
819 case CFG_EVENT_CHECK_OUTPUT_STAGE_EFFECTS: {
820 setCheckOutputStageEffects();
821 } break;
822
Eric Laurent68a40a82022-05-03 18:15:04 +0200823 case CFG_EVENT_HAL_LATENCY_MODES_CHANGED: {
824 onHalLatencyModesChanged_l();
825 } break;
826
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700827 default:
Eric Laurent10351942014-05-08 18:49:52 -0700828 ALOG_ASSERT(false, "processConfigEvents_l() unknown event type %d", event->mType);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700829 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800830 }
Eric Laurent10351942014-05-08 18:49:52 -0700831 {
832 Mutex::Autolock _l(event->mLock);
833 if (event->mWaitStatus) {
834 event->mWaitStatus = false;
835 event->mCond.signal();
836 }
837 }
838 ALOGV_IF(mConfigEvents.isEmpty(), "processConfigEvents_l() DONE thread %p", this);
839 }
840
841 if (configChanged) {
842 cacheParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800843 }
Eric Laurent81784c32012-11-19 14:55:58 -0800844}
845
Marco Nelissenb2208842014-02-07 14:00:50 -0800846String8 channelMaskToString(audio_channel_mask_t mask, bool output) {
847 String8 s;
Glenn Kastene1635ec2015-06-08 15:46:49 -0700848 const audio_channel_representation_t representation =
849 audio_channel_mask_get_representation(mask);
Andy Hungf98ec8d2015-05-19 12:53:24 -0700850
851 switch (representation) {
jiabin245cdd92018-12-07 17:55:15 -0800852 // Travel all single bit channel mask to convert channel mask to string.
Andy Hungf98ec8d2015-05-19 12:53:24 -0700853 case AUDIO_CHANNEL_REPRESENTATION_POSITION: {
854 if (output) {
855 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT) s.append("front-left, ");
856 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT) s.append("front-right, ");
857 if (mask & AUDIO_CHANNEL_OUT_FRONT_CENTER) s.append("front-center, ");
Andy Hungfba71252021-05-07 11:58:32 -0700858 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY) s.append("low-frequency, ");
Andy Hungf98ec8d2015-05-19 12:53:24 -0700859 if (mask & AUDIO_CHANNEL_OUT_BACK_LEFT) s.append("back-left, ");
860 if (mask & AUDIO_CHANNEL_OUT_BACK_RIGHT) s.append("back-right, ");
861 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT_OF_CENTER) s.append("front-left-of-center, ");
862 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT_OF_CENTER) s.append("front-right-of-center, ");
863 if (mask & AUDIO_CHANNEL_OUT_BACK_CENTER) s.append("back-center, ");
864 if (mask & AUDIO_CHANNEL_OUT_SIDE_LEFT) s.append("side-left, ");
865 if (mask & AUDIO_CHANNEL_OUT_SIDE_RIGHT) s.append("side-right, ");
866 if (mask & AUDIO_CHANNEL_OUT_TOP_CENTER) s.append("top-center ,");
867 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_LEFT) s.append("top-front-left, ");
868 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_CENTER) s.append("top-front-center, ");
869 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_RIGHT) s.append("top-front-right, ");
870 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_LEFT) s.append("top-back-left, ");
Andy Hungae81b4c2021-05-07 08:54:28 -0700871 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_CENTER) s.append("top-back-center, ");
872 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_RIGHT) s.append("top-back-right, ");
873 if (mask & AUDIO_CHANNEL_OUT_TOP_SIDE_LEFT) s.append("top-side-left, ");
874 if (mask & AUDIO_CHANNEL_OUT_TOP_SIDE_RIGHT) s.append("top-side-right, ");
875 if (mask & AUDIO_CHANNEL_OUT_BOTTOM_FRONT_LEFT) s.append("bottom-front-left, ");
876 if (mask & AUDIO_CHANNEL_OUT_BOTTOM_FRONT_CENTER) s.append("bottom-front-center, ");
877 if (mask & AUDIO_CHANNEL_OUT_BOTTOM_FRONT_RIGHT) s.append("bottom-front-right, ");
Andy Hungfba71252021-05-07 11:58:32 -0700878 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY_2) s.append("low-frequency-2, ");
Andy Hungae81b4c2021-05-07 08:54:28 -0700879 if (mask & AUDIO_CHANNEL_OUT_HAPTIC_B) s.append("haptic-B, ");
880 if (mask & AUDIO_CHANNEL_OUT_HAPTIC_A) s.append("haptic-A, ");
Andy Hungf98ec8d2015-05-19 12:53:24 -0700881 if (mask & ~AUDIO_CHANNEL_OUT_ALL) s.append("unknown, ");
882 } else {
883 if (mask & AUDIO_CHANNEL_IN_LEFT) s.append("left, ");
884 if (mask & AUDIO_CHANNEL_IN_RIGHT) s.append("right, ");
885 if (mask & AUDIO_CHANNEL_IN_FRONT) s.append("front, ");
886 if (mask & AUDIO_CHANNEL_IN_BACK) s.append("back, ");
887 if (mask & AUDIO_CHANNEL_IN_LEFT_PROCESSED) s.append("left-processed, ");
888 if (mask & AUDIO_CHANNEL_IN_RIGHT_PROCESSED) s.append("right-processed, ");
889 if (mask & AUDIO_CHANNEL_IN_FRONT_PROCESSED) s.append("front-processed, ");
890 if (mask & AUDIO_CHANNEL_IN_BACK_PROCESSED) s.append("back-processed, ");
891 if (mask & AUDIO_CHANNEL_IN_PRESSURE) s.append("pressure, ");
892 if (mask & AUDIO_CHANNEL_IN_X_AXIS) s.append("X, ");
893 if (mask & AUDIO_CHANNEL_IN_Y_AXIS) s.append("Y, ");
894 if (mask & AUDIO_CHANNEL_IN_Z_AXIS) s.append("Z, ");
Mikhail Naganovc9948492018-05-10 17:25:28 -0700895 if (mask & AUDIO_CHANNEL_IN_BACK_LEFT) s.append("back-left, ");
896 if (mask & AUDIO_CHANNEL_IN_BACK_RIGHT) s.append("back-right, ");
897 if (mask & AUDIO_CHANNEL_IN_CENTER) s.append("center, ");
Andy Hungfba71252021-05-07 11:58:32 -0700898 if (mask & AUDIO_CHANNEL_IN_LOW_FREQUENCY) s.append("low-frequency, ");
Andy Hungae81b4c2021-05-07 08:54:28 -0700899 if (mask & AUDIO_CHANNEL_IN_TOP_LEFT) s.append("top-left, ");
900 if (mask & AUDIO_CHANNEL_IN_TOP_RIGHT) s.append("top-right, ");
Andy Hungf98ec8d2015-05-19 12:53:24 -0700901 if (mask & AUDIO_CHANNEL_IN_VOICE_UPLINK) s.append("voice-uplink, ");
902 if (mask & AUDIO_CHANNEL_IN_VOICE_DNLINK) s.append("voice-dnlink, ");
903 if (mask & ~AUDIO_CHANNEL_IN_ALL) s.append("unknown, ");
904 }
905 const int len = s.length();
906 if (len > 2) {
Glenn Kasten57c4e6f2016-03-18 14:54:07 -0700907 (void) s.lockBuffer(len); // needed?
Andy Hungf98ec8d2015-05-19 12:53:24 -0700908 s.unlockBuffer(len - 2); // remove trailing ", "
909 }
910 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -0800911 }
Andy Hungf98ec8d2015-05-19 12:53:24 -0700912 case AUDIO_CHANNEL_REPRESENTATION_INDEX:
913 s.appendFormat("index mask, bits:%#x", audio_channel_mask_get_bits(mask));
914 return s;
915 default:
916 s.appendFormat("unknown mask, representation:%d bits:%#x",
917 representation, audio_channel_mask_get_bits(mask));
918 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -0800919 }
Marco Nelissenb2208842014-02-07 14:00:50 -0800920}
921
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -0700922void AudioFlinger::ThreadBase::dump(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -0800923{
Glenn Kasten1bfe09a2017-02-21 13:05:56 -0800924 dprintf(fd, "\n%s thread %p, name %s, tid %d, type %d (%s):\n", isOutput() ? "Output" : "Input",
925 this, mThreadName, getTid(), type(), threadTypeToString(type()));
926
Eric Laurent81784c32012-11-19 14:55:58 -0800927 bool locked = AudioFlinger::dumpTryLock(mLock);
928 if (!locked) {
Glenn Kasten1bfe09a2017-02-21 13:05:56 -0800929 dprintf(fd, " Thread may be deadlocked\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800930 }
931
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -0700932 dumpBase_l(fd, args);
933 dumpInternals_l(fd, args);
934 dumpTracks_l(fd, args);
935 dumpEffectChains_l(fd, args);
936
937 if (locked) {
938 mLock.unlock();
939 }
940
941 dprintf(fd, " Local log:\n");
942 mLocalLog.dump(fd, " " /* prefix */, 40 /* lines */);
Andy Hungafc51db2022-04-08 17:33:40 -0700943
944 // --all does the statistics
945 bool dumpAll = false;
946 for (const auto &arg : args) {
947 if (arg == String16("--all")) {
948 dumpAll = true;
949 }
950 }
951 if (dumpAll || type() == SPATIALIZER) {
Andy Hung44d648b2022-04-08 17:33:40 -0700952 const std::string sched = mThreadSnapshot.toString();
Andy Hungafc51db2022-04-08 17:33:40 -0700953 if (!sched.empty()) {
954 (void)write(fd, sched.c_str(), sched.size());
955 }
956 }
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -0700957}
958
959void AudioFlinger::ThreadBase::dumpBase_l(int fd, const Vector<String16>& args __unused)
960{
Elliott Hughes87cebad2014-05-22 10:14:43 -0700961 dprintf(fd, " I/O handle: %d\n", mId);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700962 dprintf(fd, " Standby: %s\n", mStandby ? "yes" : "no");
Glenn Kasten97b7b752014-09-28 13:04:24 -0700963 dprintf(fd, " Sample rate: %u Hz\n", mSampleRate);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700964 dprintf(fd, " HAL frame count: %zu\n", mFrameCount);
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700965 dprintf(fd, " HAL format: 0x%x (%s)\n", mHALFormat, formatToString(mHALFormat).c_str());
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700966 dprintf(fd, " HAL buffer size: %zu bytes\n", mBufferSize);
Glenn Kasten97b7b752014-09-28 13:04:24 -0700967 dprintf(fd, " Channel count: %u\n", mChannelCount);
968 dprintf(fd, " Channel mask: 0x%08x (%s)\n", mChannelMask,
Marco Nelissenb2208842014-02-07 14:00:50 -0800969 channelMaskToString(mChannelMask, mType != RECORD).string());
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700970 dprintf(fd, " Processing format: 0x%x (%s)\n", mFormat, formatToString(mFormat).c_str());
Glenn Kastenf87c2f52015-08-21 08:03:57 -0700971 dprintf(fd, " Processing frame size: %zu bytes\n", mFrameSize);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700972 dprintf(fd, " Pending config events:");
Marco Nelissenb2208842014-02-07 14:00:50 -0800973 size_t numConfig = mConfigEvents.size();
974 if (numConfig) {
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -0700975 const size_t SIZE = 256;
976 char buffer[SIZE];
Marco Nelissenb2208842014-02-07 14:00:50 -0800977 for (size_t i = 0; i < numConfig; i++) {
978 mConfigEvents[i]->dump(buffer, SIZE);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700979 dprintf(fd, "\n %s", buffer);
Marco Nelissenb2208842014-02-07 14:00:50 -0800980 }
Elliott Hughes87cebad2014-05-22 10:14:43 -0700981 dprintf(fd, "\n");
Marco Nelissenb2208842014-02-07 14:00:50 -0800982 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -0700983 dprintf(fd, " none\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800984 }
Andy Hung293558a2017-03-21 12:19:20 -0700985 // Note: output device may be used by capture threads for effects such as AEC.
jiabinc52b1ff2019-10-31 17:20:42 -0700986 dprintf(fd, " Output devices: %s (%s)\n",
987 dumpDeviceTypes(outDeviceTypes()).c_str(), toString(outDeviceTypes()).c_str());
988 dprintf(fd, " Input device: %#x (%s)\n",
989 inDeviceType(), toString(inDeviceType()).c_str());
Andy Hung9b181952019-02-25 14:53:36 -0800990 dprintf(fd, " Audio source: %d (%s)\n", mAudioSource, toString(mAudioSource).c_str());
Eric Laurent81784c32012-11-19 14:55:58 -0800991
Andy Hung2e2c0bb2018-06-11 19:13:11 -0700992 // Dump timestamp statistics for the Thread types that support it.
993 if (mType == RECORD
994 || mType == MIXER
995 || mType == DUPLICATING
Andy Hungf3234512018-07-03 14:51:47 -0700996 || mType == DIRECT
Andy Hung4b7f54f2022-04-28 17:45:28 -0700997 || mType == OFFLOAD
998 || mType == SPATIALIZER) {
Andy Hung2e2c0bb2018-06-11 19:13:11 -0700999 dprintf(fd, " Timestamp stats: %s\n", mTimestampVerifier.toString().c_str());
Andy Hungc8fddf32018-08-08 18:32:37 -07001000 dprintf(fd, " Timestamp corrected: %s\n", isTimestampCorrectionEnabled() ? "yes" : "no");
Andy Hung2e2c0bb2018-06-11 19:13:11 -07001001 }
1002
Andy Hung446f4df2019-02-21 12:26:41 -08001003 if (mLastIoBeginNs > 0) { // MMAP may not set this
1004 dprintf(fd, " Last %s occurred (msecs): %lld\n",
1005 isOutput() ? "write" : "read",
1006 (long long) (systemTime() - mLastIoBeginNs) / NANOS_PER_MILLISECOND);
1007 }
1008
1009 if (mProcessTimeMs.getN() > 0) {
1010 dprintf(fd, " Process time ms stats: %s\n", mProcessTimeMs.toString().c_str());
1011 }
1012
1013 if (mIoJitterMs.getN() > 0) {
1014 dprintf(fd, " Hal %s jitter ms stats: %s\n",
1015 isOutput() ? "write" : "read",
1016 mIoJitterMs.toString().c_str());
1017 }
1018
Andy Hunge6c37112019-02-26 17:38:10 -08001019 if (mLatencyMs.getN() > 0) {
1020 dprintf(fd, " Threadloop %s latency stats: %s\n",
1021 isOutput() ? "write" : "read",
1022 mLatencyMs.toString().c_str());
1023 }
Robert Wu06db0a32021-08-10 19:05:34 +00001024
1025 if (mMonopipePipeDepthStats.getN() > 0) {
1026 dprintf(fd, " Monopipe %s pipe depth stats: %s\n",
1027 isOutput() ? "write" : "read",
1028 mMonopipePipeDepthStats.toString().c_str());
1029 }
Eric Laurent81784c32012-11-19 14:55:58 -08001030}
1031
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001032void AudioFlinger::ThreadBase::dumpEffectChains_l(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -08001033{
1034 const size_t SIZE = 256;
1035 char buffer[SIZE];
Eric Laurent81784c32012-11-19 14:55:58 -08001036
Marco Nelissenb2208842014-02-07 14:00:50 -08001037 size_t numEffectChains = mEffectChains.size();
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +00001038 snprintf(buffer, SIZE, " %zu Effect Chains\n", numEffectChains);
Eric Laurent81784c32012-11-19 14:55:58 -08001039 write(fd, buffer, strlen(buffer));
1040
Marco Nelissenb2208842014-02-07 14:00:50 -08001041 for (size_t i = 0; i < numEffectChains; ++i) {
Eric Laurent81784c32012-11-19 14:55:58 -08001042 sp<EffectChain> chain = mEffectChains[i];
1043 if (chain != 0) {
1044 chain->dump(fd, args);
1045 }
1046 }
1047}
1048
Andy Hungdae27702016-10-31 14:01:16 -07001049void AudioFlinger::ThreadBase::acquireWakeLock()
Eric Laurent81784c32012-11-19 14:55:58 -08001050{
1051 Mutex::Autolock _l(mLock);
Andy Hungdae27702016-10-31 14:01:16 -07001052 acquireWakeLock_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001053}
1054
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001055String16 AudioFlinger::ThreadBase::getWakeLockTag()
1056{
1057 switch (mType) {
Glenn Kastenbcb14862015-03-05 17:11:21 -08001058 case MIXER:
1059 return String16("AudioMix");
1060 case DIRECT:
1061 return String16("AudioDirectOut");
1062 case DUPLICATING:
1063 return String16("AudioDup");
1064 case RECORD:
1065 return String16("AudioIn");
1066 case OFFLOAD:
1067 return String16("AudioOffload");
Andy Hungea840382020-05-05 21:50:17 -07001068 case MMAP_PLAYBACK:
1069 return String16("MmapPlayback");
1070 case MMAP_CAPTURE:
1071 return String16("MmapCapture");
Eric Laurent1c5e2e32021-08-18 18:50:28 +02001072 case SPATIALIZER:
1073 return String16("AudioSpatial");
Glenn Kastenbcb14862015-03-05 17:11:21 -08001074 default:
1075 ALOG_ASSERT(false);
1076 return String16("AudioUnknown");
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001077 }
1078}
1079
Andy Hungdae27702016-10-31 14:01:16 -07001080void AudioFlinger::ThreadBase::acquireWakeLock_l()
Eric Laurent81784c32012-11-19 14:55:58 -08001081{
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001082 getPowerManager_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001083 if (mPowerManager != 0) {
1084 sp<IBinder> binder = new BBinder();
Andy Hungdae27702016-10-31 14:01:16 -07001085 // Uses AID_AUDIOSERVER for wakelock. updateWakeLockUids_l() updates with client uids.
Chris Ye6597d732020-02-28 22:38:25 -08001086 binder::Status status = mPowerManager->acquireWakeLockAsync(binder,
1087 POWERMANAGER_PARTIAL_WAKE_LOCK,
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001088 getWakeLockTag(),
Marco Nelissendcb346b2015-09-09 10:47:29 -07001089 String16("audioserver"),
Chris Ye6597d732020-02-28 22:38:25 -08001090 {} /* workSource */,
1091 {} /* historyTag */);
1092 if (status.isOk()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001093 mWakeLockToken = binder;
1094 }
Chris Ye6597d732020-02-28 22:38:25 -08001095 ALOGV("acquireWakeLock_l() %s status %d", mThreadName, status.exceptionCode());
Eric Laurent81784c32012-11-19 14:55:58 -08001096 }
Wei Jia3f273d12015-11-24 09:06:49 -08001097
Andy Hung3f0c9022016-01-15 17:49:46 -08001098 gBoottime.acquire(mWakeLockToken);
Andy Hung818e7a32016-02-16 18:08:07 -08001099 mTimestamp.mTimebaseOffset[ExtendedTimestamp::TIMEBASE_BOOTTIME] =
1100 gBoottime.getBoottimeOffset();
Eric Laurent81784c32012-11-19 14:55:58 -08001101}
1102
1103void AudioFlinger::ThreadBase::releaseWakeLock()
1104{
1105 Mutex::Autolock _l(mLock);
1106 releaseWakeLock_l();
1107}
1108
1109void AudioFlinger::ThreadBase::releaseWakeLock_l()
1110{
Andy Hung3f0c9022016-01-15 17:49:46 -08001111 gBoottime.release(mWakeLockToken);
Eric Laurent81784c32012-11-19 14:55:58 -08001112 if (mWakeLockToken != 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -08001113 ALOGV("releaseWakeLock_l() %s", mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08001114 if (mPowerManager != 0) {
Chris Ye6597d732020-02-28 22:38:25 -08001115 mPowerManager->releaseWakeLockAsync(mWakeLockToken, 0);
Eric Laurent81784c32012-11-19 14:55:58 -08001116 }
1117 mWakeLockToken.clear();
1118 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001119}
1120
1121void AudioFlinger::ThreadBase::getPowerManager_l() {
Eric Laurent72e3f392015-05-20 14:43:50 -07001122 if (mSystemReady && mPowerManager == 0) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001123 // use checkService() to avoid blocking if power service is not up yet
1124 sp<IBinder> binder =
1125 defaultServiceManager()->checkService(String16("power"));
1126 if (binder == 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -08001127 ALOGW("Thread %s cannot connect to the power manager service", mThreadName);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001128 } else {
Chris Ye6597d732020-02-28 22:38:25 -08001129 mPowerManager = interface_cast<os::IPowerManager>(binder);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001130 binder->linkToDeath(mDeathRecipient);
1131 }
1132 }
1133}
1134
Andy Hungd01b0f12016-11-07 16:10:30 -08001135void AudioFlinger::ThreadBase::updateWakeLockUids_l(const SortedVector<uid_t> &uids) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001136 getPowerManager_l();
Andy Hungdae27702016-10-31 14:01:16 -07001137
1138#if !LOG_NDEBUG
1139 std::stringstream s;
Andy Hungd01b0f12016-11-07 16:10:30 -08001140 for (uid_t uid : uids) {
Andy Hungdae27702016-10-31 14:01:16 -07001141 s << uid << " ";
1142 }
1143 ALOGD("updateWakeLockUids_l %s uids:%s", mThreadName, s.str().c_str());
1144#endif
1145
Andy Hung438e7572015-12-14 15:51:17 -08001146 if (mWakeLockToken == NULL) { // token may be NULL if AudioFlinger::systemReady() not called.
1147 if (mSystemReady) {
1148 ALOGE("no wake lock to update, but system ready!");
1149 } else {
1150 ALOGW("no wake lock to update, system not ready yet");
1151 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001152 return;
1153 }
1154 if (mPowerManager != 0) {
Andy Hung1f12a8a2016-11-07 16:10:30 -08001155 std::vector<int> uidsAsInt(uids.begin(), uids.end()); // powermanager expects uids as ints
Chris Ye6597d732020-02-28 22:38:25 -08001156 binder::Status status = mPowerManager->updateWakeLockUidsAsync(
1157 mWakeLockToken, uidsAsInt);
1158 ALOGV("updateWakeLockUids_l() %s status %d", mThreadName, status.exceptionCode());
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001159 }
1160}
1161
Eric Laurent81784c32012-11-19 14:55:58 -08001162void AudioFlinger::ThreadBase::clearPowerManager()
1163{
1164 Mutex::Autolock _l(mLock);
1165 releaseWakeLock_l();
1166 mPowerManager.clear();
1167}
1168
jiabinc52b1ff2019-10-31 17:20:42 -07001169void AudioFlinger::ThreadBase::updateOutDevices(
1170 const DeviceDescriptorBaseVector& outDevices __unused)
1171{
1172 ALOGE("%s should only be called in RecordThread", __func__);
1173}
1174
Eric Laurentec376dc2021-04-08 20:41:22 +02001175void AudioFlinger::ThreadBase::resizeInputBuffer_l(int32_t maxSharedAudioHistoryMs __unused)
1176{
1177 ALOGE("%s should only be called in RecordThread", __func__);
1178}
1179
Glenn Kasten0f11b512014-01-31 16:18:54 -08001180void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001181{
1182 sp<ThreadBase> thread = mThread.promote();
1183 if (thread != 0) {
1184 thread->clearPowerManager();
1185 }
1186 ALOGW("power manager service died !!!");
1187}
1188
Eric Laurent81784c32012-11-19 14:55:58 -08001189void AudioFlinger::ThreadBase::setEffectSuspended_l(
Glenn Kastend848eb42016-03-08 13:42:11 -08001190 const effect_uuid_t *type, bool suspend, audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001191{
1192 sp<EffectChain> chain = getEffectChain_l(sessionId);
1193 if (chain != 0) {
1194 if (type != NULL) {
1195 chain->setEffectSuspended_l(type, suspend);
1196 } else {
1197 chain->setEffectSuspendedAll_l(suspend);
1198 }
1199 }
1200
1201 updateSuspendedSessions_l(type, suspend, sessionId);
1202}
1203
1204void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1205{
1206 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
1207 if (index < 0) {
1208 return;
1209 }
1210
1211 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
1212 mSuspendedSessions.valueAt(index);
1213
1214 for (size_t i = 0; i < sessionEffects.size(); i++) {
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07001215 const sp<SuspendedSessionDesc>& desc = sessionEffects.valueAt(i);
Eric Laurent81784c32012-11-19 14:55:58 -08001216 for (int j = 0; j < desc->mRefCount; j++) {
1217 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1218 chain->setEffectSuspendedAll_l(true);
1219 } else {
1220 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
1221 desc->mType.timeLow);
1222 chain->setEffectSuspended_l(&desc->mType, true);
1223 }
1224 }
1225 }
1226}
1227
1228void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1229 bool suspend,
Glenn Kastend848eb42016-03-08 13:42:11 -08001230 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001231{
1232 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
1233
1234 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1235
1236 if (suspend) {
1237 if (index >= 0) {
1238 sessionEffects = mSuspendedSessions.valueAt(index);
1239 } else {
1240 mSuspendedSessions.add(sessionId, sessionEffects);
1241 }
1242 } else {
1243 if (index < 0) {
1244 return;
1245 }
1246 sessionEffects = mSuspendedSessions.valueAt(index);
1247 }
1248
1249
1250 int key = EffectChain::kKeyForSuspendAll;
1251 if (type != NULL) {
1252 key = type->timeLow;
1253 }
1254 index = sessionEffects.indexOfKey(key);
1255
1256 sp<SuspendedSessionDesc> desc;
1257 if (suspend) {
1258 if (index >= 0) {
1259 desc = sessionEffects.valueAt(index);
1260 } else {
1261 desc = new SuspendedSessionDesc();
1262 if (type != NULL) {
1263 desc->mType = *type;
1264 }
1265 sessionEffects.add(key, desc);
1266 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
1267 }
1268 desc->mRefCount++;
1269 } else {
1270 if (index < 0) {
1271 return;
1272 }
1273 desc = sessionEffects.valueAt(index);
1274 if (--desc->mRefCount == 0) {
1275 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
1276 sessionEffects.removeItemsAt(index);
1277 if (sessionEffects.isEmpty()) {
1278 ALOGV("updateSuspendedSessions_l() restore removing session %d",
1279 sessionId);
1280 mSuspendedSessions.removeItem(sessionId);
1281 }
1282 }
1283 }
1284 if (!sessionEffects.isEmpty()) {
1285 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1286 }
1287}
1288
Eric Laurent6b446ce2019-12-13 10:56:31 -08001289void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(bool enabled,
1290 audio_session_t sessionId,
1291 bool threadLocked) {
1292 if (!threadLocked) {
1293 mLock.lock();
1294 }
Eric Laurent81784c32012-11-19 14:55:58 -08001295
Eric Laurent81784c32012-11-19 14:55:58 -08001296 if (mType != RECORD) {
1297 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1298 // another session. This gives the priority to well behaved effect control panels
1299 // and applications not using global effects.
1300 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
1301 // global effects
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001302 if (!audio_is_global_session(sessionId)) {
Eric Laurent81784c32012-11-19 14:55:58 -08001303 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1304 }
1305 }
1306
Eric Laurent6b446ce2019-12-13 10:56:31 -08001307 if (!threadLocked) {
1308 mLock.unlock();
Eric Laurent81784c32012-11-19 14:55:58 -08001309 }
1310}
1311
Eric Laurent4c415062016-06-17 16:14:16 -07001312// checkEffectCompatibility_l() must be called with ThreadBase::mLock held
1313status_t AudioFlinger::RecordThread::checkEffectCompatibility_l(
1314 const effect_descriptor_t *desc, audio_session_t sessionId)
1315{
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001316 // No global output effect sessions on record threads
1317 if (sessionId == AUDIO_SESSION_OUTPUT_MIX
1318 || sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Eric Laurent4c415062016-06-17 16:14:16 -07001319 ALOGW("checkEffectCompatibility_l(): global effect %s on record thread %s",
1320 desc->name, mThreadName);
1321 return BAD_VALUE;
1322 }
1323 // only pre processing effects on record thread
1324 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC) {
1325 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on record thread %s",
1326 desc->name, mThreadName);
1327 return BAD_VALUE;
1328 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001329
1330 // always allow effects without processing load or latency
1331 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1332 return NO_ERROR;
1333 }
1334
Eric Laurent4c415062016-06-17 16:14:16 -07001335 audio_input_flags_t flags = mInput->flags;
1336 if (hasFastCapture() || (flags & AUDIO_INPUT_FLAG_FAST)) {
1337 if (flags & AUDIO_INPUT_FLAG_RAW) {
1338 ALOGW("checkEffectCompatibility_l(): effect %s on record thread %s in raw mode",
1339 desc->name, mThreadName);
1340 return BAD_VALUE;
1341 }
1342 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1343 ALOGW("checkEffectCompatibility_l(): non HW effect %s on record thread %s in fast mode",
1344 desc->name, mThreadName);
1345 return BAD_VALUE;
1346 }
1347 }
jiabineb3bda02020-06-30 14:07:03 -07001348
1349 if (EffectModule::isHapticGenerator(&desc->type)) {
1350 ALOGE("%s(): HapticGenerator is not supported in RecordThread", __func__);
1351 return BAD_VALUE;
1352 }
Eric Laurent4c415062016-06-17 16:14:16 -07001353 return NO_ERROR;
1354}
1355
1356// checkEffectCompatibility_l() must be called with ThreadBase::mLock held
1357status_t AudioFlinger::PlaybackThread::checkEffectCompatibility_l(
1358 const effect_descriptor_t *desc, audio_session_t sessionId)
1359{
1360 // no preprocessing on playback threads
1361 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001362 ALOGW("%s: pre processing effect %s created on playback"
1363 " thread %s", __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001364 return BAD_VALUE;
1365 }
1366
Eric Laurent3e4de772017-07-16 16:55:08 -07001367 // always allow effects without processing load or latency
1368 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1369 return NO_ERROR;
1370 }
1371
jiabineb3bda02020-06-30 14:07:03 -07001372 if (EffectModule::isHapticGenerator(&desc->type) && mHapticChannelCount == 0) {
1373 ALOGW("%s: thread doesn't support haptic playback while the effect is HapticGenerator",
1374 __func__);
1375 return BAD_VALUE;
1376 }
1377
Eric Laurentf690c462021-09-17 14:47:03 +02001378 if (memcmp(&desc->type, FX_IID_SPATIALIZER, sizeof(effect_uuid_t)) == 0
1379 && mType != SPATIALIZER) {
1380 ALOGW("%s: attempt to create a spatializer effect on a thread of type %d",
1381 __func__, mType);
1382 return BAD_VALUE;
1383 }
1384
Eric Laurent4c415062016-06-17 16:14:16 -07001385 switch (mType) {
1386 case MIXER: {
Andy Hung9aad48c2017-11-29 10:29:19 -08001387#ifndef MULTICHANNEL_EFFECT_CHAIN
Eric Laurent4c415062016-06-17 16:14:16 -07001388 // Reject any effect on mixer multichannel sinks.
1389 // TODO: fix both format and multichannel issues with effects.
1390 if (mChannelCount != FCC_2) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001391 ALOGW("%s: effect %s for multichannel(%d) on MIXER thread %s",
1392 __func__, desc->name, mChannelCount, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001393 return BAD_VALUE;
1394 }
Andy Hung9aad48c2017-11-29 10:29:19 -08001395#endif
Eric Laurent4c415062016-06-17 16:14:16 -07001396 audio_output_flags_t flags = mOutput->flags;
1397 if (hasFastMixer() || (flags & AUDIO_OUTPUT_FLAG_FAST)) {
1398 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1399 // global effects are applied only to non fast tracks if they are SW
1400 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1401 break;
1402 }
1403 } else if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1404 // only post processing on output stage session
1405 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001406 ALOGW("%s: non post processing effect %s not allowed on output stage session",
1407 __func__, desc->name);
Eric Laurent4c415062016-06-17 16:14:16 -07001408 return BAD_VALUE;
1409 }
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001410 } else if (sessionId == AUDIO_SESSION_DEVICE) {
1411 // only post processing on output stage session
1412 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001413 ALOGW("%s: non post processing effect %s not allowed on device session",
1414 __func__, desc->name);
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001415 return BAD_VALUE;
1416 }
Eric Laurent4c415062016-06-17 16:14:16 -07001417 } else {
1418 // no restriction on effects applied on non fast tracks
1419 if ((hasAudioSession_l(sessionId) & ThreadBase::FAST_SESSION) == 0) {
1420 break;
1421 }
1422 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001423
Eric Laurent4c415062016-06-17 16:14:16 -07001424 if (flags & AUDIO_OUTPUT_FLAG_RAW) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001425 ALOGW("%s: effect %s on playback thread in raw mode", __func__, desc->name);
Eric Laurent4c415062016-06-17 16:14:16 -07001426 return BAD_VALUE;
1427 }
1428 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001429 ALOGW("%s: non HW effect %s on playback thread in fast mode",
1430 __func__, desc->name);
Eric Laurent4c415062016-06-17 16:14:16 -07001431 return BAD_VALUE;
1432 }
1433 }
1434 } break;
1435 case OFFLOAD:
Jean-Michel Trivi773ee952016-07-11 16:53:18 -07001436 // nothing actionable on offload threads, if the effect:
1437 // - is offloadable: the effect can be created
1438 // - is NOT offloadable: the effect should still be created, but EffectHandle::enable()
1439 // will take care of invalidating the tracks of the thread
Eric Laurent4c415062016-06-17 16:14:16 -07001440 break;
1441 case DIRECT:
1442 // Reject any effect on Direct output threads for now, since the format of
1443 // mSinkBuffer is not guaranteed to be compatible with effect processing (PCM 16 stereo).
Eric Laurentb62d0362021-10-26 17:40:18 +02001444 ALOGW("%s: effect %s on DIRECT output thread %s",
1445 __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001446 return BAD_VALUE;
1447 case DUPLICATING:
Andy Hung9aad48c2017-11-29 10:29:19 -08001448#ifndef MULTICHANNEL_EFFECT_CHAIN
Eric Laurent4c415062016-06-17 16:14:16 -07001449 // Reject any effect on mixer multichannel sinks.
1450 // TODO: fix both format and multichannel issues with effects.
1451 if (mChannelCount != FCC_2) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001452 ALOGW("%s: effect %s for multichannel(%d) on DUPLICATING thread %s",
1453 __func__, desc->name, mChannelCount, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001454 return BAD_VALUE;
1455 }
Andy Hung9aad48c2017-11-29 10:29:19 -08001456#endif
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001457 if (audio_is_global_session(sessionId)) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001458 ALOGW("%s: global effect %s on DUPLICATING thread %s",
1459 __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001460 return BAD_VALUE;
1461 }
1462 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001463 ALOGW("%s: post processing effect %s on DUPLICATING thread %s",
1464 __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001465 return BAD_VALUE;
1466 }
1467 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) != 0) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001468 ALOGW("%s: HW tunneled effect %s on DUPLICATING thread %s",
1469 __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001470 return BAD_VALUE;
1471 }
1472 break;
Eric Laurent1c5e2e32021-08-18 18:50:28 +02001473 case SPATIALIZER:
Eric Laurentb62d0362021-10-26 17:40:18 +02001474 // Global effects (AUDIO_SESSION_OUTPUT_MIX) are not supported on spatializer mixer
1475 // as there is no common accumulation buffer for sptialized and non sptialized tracks.
1476 // Post processing effects (AUDIO_SESSION_OUTPUT_STAGE or AUDIO_SESSION_DEVICE)
1477 // are supported and added after the spatializer.
1478 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1479 ALOGW("%s: global effect %s not supported on spatializer thread %s",
1480 __func__, desc->name, mThreadName);
Eric Laurentb3f315a2021-07-13 15:09:05 +02001481 return BAD_VALUE;
Eric Laurentb62d0362021-10-26 17:40:18 +02001482 } else if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1483 // only post processing , downmixer or spatializer effects on output stage session
1484 if (memcmp(&desc->type, FX_IID_SPATIALIZER, sizeof(effect_uuid_t)) == 0
1485 || memcmp(&desc->type, EFFECT_UIID_DOWNMIX, sizeof(effect_uuid_t)) == 0) {
1486 break;
1487 }
1488 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
1489 ALOGW("%s: non post processing effect %s not allowed on output stage session",
1490 __func__, desc->name);
1491 return BAD_VALUE;
1492 }
1493 } else if (sessionId == AUDIO_SESSION_DEVICE) {
1494 // only post processing on output stage session
1495 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
1496 ALOGW("%s: non post processing effect %s not allowed on device session",
1497 __func__, desc->name);
1498 return BAD_VALUE;
1499 }
Eric Laurentb3f315a2021-07-13 15:09:05 +02001500 }
1501 break;
Eric Laurent4c415062016-06-17 16:14:16 -07001502 default:
1503 LOG_ALWAYS_FATAL("checkEffectCompatibility_l(): wrong thread type %d", mType);
1504 }
1505
1506 return NO_ERROR;
1507}
1508
Eric Laurent81784c32012-11-19 14:55:58 -08001509// ThreadBase::createEffect_l() must be called with AudioFlinger::mLock held
1510sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
1511 const sp<AudioFlinger::Client>& client,
1512 const sp<IEffectClient>& effectClient,
1513 int32_t priority,
Glenn Kastend848eb42016-03-08 13:42:11 -08001514 audio_session_t sessionId,
Eric Laurent81784c32012-11-19 14:55:58 -08001515 effect_descriptor_t *desc,
1516 int *enabled,
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001517 status_t *status,
Eric Laurent2fe0acd2020-03-13 14:30:46 -07001518 bool pinned,
Eric Laurentde8caf42021-08-11 17:19:25 +02001519 bool probe,
1520 bool notifyFramesProcessed)
Eric Laurent81784c32012-11-19 14:55:58 -08001521{
1522 sp<EffectModule> effect;
1523 sp<EffectHandle> handle;
1524 status_t lStatus;
1525 sp<EffectChain> chain;
1526 bool chainCreated = false;
1527 bool effectCreated = false;
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001528 audio_unique_id_t effectId = AUDIO_UNIQUE_ID_USE_UNSPECIFIED;
Eric Laurent81784c32012-11-19 14:55:58 -08001529
1530 lStatus = initCheck();
1531 if (lStatus != NO_ERROR) {
1532 ALOGW("createEffect_l() Audio driver not initialized.");
1533 goto Exit;
1534 }
1535
Eric Laurent81784c32012-11-19 14:55:58 -08001536 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
1537
1538 { // scope for mLock
1539 Mutex::Autolock _l(mLock);
1540
Eric Laurent4c415062016-06-17 16:14:16 -07001541 lStatus = checkEffectCompatibility_l(desc, sessionId);
Eric Laurent2fe0acd2020-03-13 14:30:46 -07001542 if (probe || lStatus != NO_ERROR) {
Eric Laurent4c415062016-06-17 16:14:16 -07001543 goto Exit;
1544 }
1545
Eric Laurent81784c32012-11-19 14:55:58 -08001546 // check for existing effect chain with the requested audio session
1547 chain = getEffectChain_l(sessionId);
1548 if (chain == 0) {
1549 // create a new chain for this session
1550 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
1551 chain = new EffectChain(this, sessionId);
1552 addEffectChain_l(chain);
1553 chain->setStrategy(getStrategyForSession_l(sessionId));
1554 chainCreated = true;
1555 } else {
1556 effect = chain->getEffectFromDesc_l(desc);
1557 }
1558
1559 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
1560
1561 if (effect == 0) {
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001562 effectId = mAudioFlinger->nextUniqueId(AUDIO_UNIQUE_ID_USE_EFFECT);
Eric Laurent81784c32012-11-19 14:55:58 -08001563 // create a new effect module if none present in the chain
Eric Laurent6b446ce2019-12-13 10:56:31 -08001564 lStatus = chain->createEffect_l(effect, desc, effectId, sessionId, pinned);
Eric Laurent81784c32012-11-19 14:55:58 -08001565 if (lStatus != NO_ERROR) {
1566 goto Exit;
1567 }
1568 effectCreated = true;
1569
jiabinc52b1ff2019-10-31 17:20:42 -07001570 // FIXME: use vector of device and address when effect interface is ready.
jiabin8f278ee2019-11-11 12:16:27 -08001571 effect->setDevices(outDeviceTypeAddrs());
1572 effect->setInputDevice(inDeviceTypeAddr());
Eric Laurent81784c32012-11-19 14:55:58 -08001573 effect->setMode(mAudioFlinger->getMode());
1574 effect->setAudioSource(mAudioSource);
1575 }
jiabin1319f5a2021-03-30 22:21:24 +00001576 if (effect->isHapticGenerator()) {
1577 // TODO(b/184194057): Use the vibrator information from the vibrator that will be used
1578 // for the HapticGenerator.
Lais Andradebc3f37a2021-07-02 00:13:19 +01001579 const std::optional<media::AudioVibratorInfo> defaultVibratorInfo =
1580 std::move(mAudioFlinger->getDefaultVibratorInfo_l());
1581 if (defaultVibratorInfo) {
jiabin1319f5a2021-03-30 22:21:24 +00001582 // Only set the vibrator info when it is a valid one.
Lais Andradebc3f37a2021-07-02 00:13:19 +01001583 effect->setVibratorInfo(*defaultVibratorInfo);
jiabin1319f5a2021-03-30 22:21:24 +00001584 }
1585 }
Eric Laurent81784c32012-11-19 14:55:58 -08001586 // create effect handle and connect it to effect module
Eric Laurentde8caf42021-08-11 17:19:25 +02001587 handle = new EffectHandle(effect, client, effectClient, priority, notifyFramesProcessed);
Glenn Kastene75da402013-11-20 13:54:52 -08001588 lStatus = handle->initCheck();
1589 if (lStatus == OK) {
1590 lStatus = effect->addHandle(handle.get());
Eric Laurentb3f315a2021-07-13 15:09:05 +02001591 sendCheckOutputStageEffectsEvent_l();
Glenn Kastene75da402013-11-20 13:54:52 -08001592 }
Eric Laurent81784c32012-11-19 14:55:58 -08001593 if (enabled != NULL) {
1594 *enabled = (int)effect->isEnabled();
1595 }
1596 }
1597
1598Exit:
Eric Laurent2fe0acd2020-03-13 14:30:46 -07001599 if (!probe && lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurent81784c32012-11-19 14:55:58 -08001600 Mutex::Autolock _l(mLock);
1601 if (effectCreated) {
1602 chain->removeEffect_l(effect);
1603 }
Eric Laurent81784c32012-11-19 14:55:58 -08001604 if (chainCreated) {
1605 removeEffectChain_l(chain);
1606 }
haobo101735295ff7b0d2017-03-17 17:44:03 +08001607 // handle must be cleared by caller to avoid deadlock.
Eric Laurent81784c32012-11-19 14:55:58 -08001608 }
1609
Glenn Kasten9156ef32013-08-06 15:39:08 -07001610 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001611 return handle;
1612}
1613
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001614void AudioFlinger::ThreadBase::disconnectEffectHandle(EffectHandle *handle,
1615 bool unpinIfLast)
1616{
1617 bool remove = false;
1618 sp<EffectModule> effect;
1619 {
1620 Mutex::Autolock _l(mLock);
Eric Laurent41709552019-12-16 19:34:05 -08001621 sp<EffectBase> effectBase = handle->effect().promote();
1622 if (effectBase == nullptr) {
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001623 return;
1624 }
Eric Laurentb82e6b72019-11-22 17:25:04 -08001625 effect = effectBase->asEffectModule();
1626 if (effect == nullptr) {
1627 return;
1628 }
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001629 // restore suspended effects if the disconnected handle was enabled and the last one.
1630 remove = (effect->removeHandle(handle) == 0) && (!effect->isPinned() || unpinIfLast);
1631 if (remove) {
1632 removeEffect_l(effect, true);
1633 }
Eric Laurentb3f315a2021-07-13 15:09:05 +02001634 sendCheckOutputStageEffectsEvent_l();
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001635 }
1636 if (remove) {
1637 mAudioFlinger->updateOrphanEffectChains(effect);
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001638 if (handle->enabled()) {
Eric Laurent6b446ce2019-12-13 10:56:31 -08001639 effect->checkSuspendOnEffectEnabled(false, false /*threadLocked*/);
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001640 }
1641 }
1642}
1643
Eric Laurent6b446ce2019-12-13 10:56:31 -08001644void AudioFlinger::ThreadBase::onEffectEnable(const sp<EffectModule>& effect) {
Andy Hungea840382020-05-05 21:50:17 -07001645 if (isOffloadOrMmap()) {
Eric Laurent6b446ce2019-12-13 10:56:31 -08001646 Mutex::Autolock _l(mLock);
1647 broadcast_l();
1648 }
1649 if (!effect->isOffloadable()) {
1650 if (mType == ThreadBase::OFFLOAD) {
1651 PlaybackThread *t = (PlaybackThread *)this;
1652 t->invalidateTracks(AUDIO_STREAM_MUSIC);
1653 }
1654 if (effect->sessionId() == AUDIO_SESSION_OUTPUT_MIX) {
1655 mAudioFlinger->onNonOffloadableGlobalEffectEnable();
1656 }
1657 }
1658}
1659
1660void AudioFlinger::ThreadBase::onEffectDisable() {
Andy Hungea840382020-05-05 21:50:17 -07001661 if (isOffloadOrMmap()) {
Eric Laurent6b446ce2019-12-13 10:56:31 -08001662 Mutex::Autolock _l(mLock);
1663 broadcast_l();
1664 }
1665}
1666
Glenn Kastend848eb42016-03-08 13:42:11 -08001667sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(audio_session_t sessionId,
1668 int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08001669{
1670 Mutex::Autolock _l(mLock);
1671 return getEffect_l(sessionId, effectId);
1672}
1673
Glenn Kastend848eb42016-03-08 13:42:11 -08001674sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(audio_session_t sessionId,
1675 int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08001676{
1677 sp<EffectChain> chain = getEffectChain_l(sessionId);
1678 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
1679}
1680
Eric Laurent6c796322019-04-09 14:13:17 -07001681std::vector<int> AudioFlinger::ThreadBase::getEffectIds_l(audio_session_t sessionId)
1682{
1683 sp<EffectChain> chain = getEffectChain_l(sessionId);
1684 return chain != nullptr ? chain->getEffectIds() : std::vector<int>{};
1685}
1686
Eric Laurent81784c32012-11-19 14:55:58 -08001687// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
1688// PlaybackThread::mLock held
1689status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
1690{
1691 // check for existing effect chain with the requested audio session
Glenn Kastend848eb42016-03-08 13:42:11 -08001692 audio_session_t sessionId = effect->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08001693 sp<EffectChain> chain = getEffectChain_l(sessionId);
1694 bool chainCreated = false;
1695
Eric Laurent5baf2af2013-09-12 17:37:00 -07001696 ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(),
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001697 "addEffect_l() on offloaded thread %p: effect %s does not support offload flags %#x",
Eric Laurent5baf2af2013-09-12 17:37:00 -07001698 this, effect->desc().name, effect->desc().flags);
1699
Eric Laurent81784c32012-11-19 14:55:58 -08001700 if (chain == 0) {
1701 // create a new chain for this session
1702 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
1703 chain = new EffectChain(this, sessionId);
1704 addEffectChain_l(chain);
1705 chain->setStrategy(getStrategyForSession_l(sessionId));
1706 chainCreated = true;
1707 }
1708 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
1709
1710 if (chain->getEffectFromId_l(effect->id()) != 0) {
1711 ALOGW("addEffect_l() %p effect %s already present in chain %p",
1712 this, effect->desc().name, chain.get());
1713 return BAD_VALUE;
1714 }
1715
Eric Laurent5baf2af2013-09-12 17:37:00 -07001716 effect->setOffloaded(mType == OFFLOAD, mId);
1717
Eric Laurent81784c32012-11-19 14:55:58 -08001718 status_t status = chain->addEffect_l(effect);
1719 if (status != NO_ERROR) {
1720 if (chainCreated) {
1721 removeEffectChain_l(chain);
1722 }
1723 return status;
1724 }
1725
jiabin8f278ee2019-11-11 12:16:27 -08001726 effect->setDevices(outDeviceTypeAddrs());
1727 effect->setInputDevice(inDeviceTypeAddr());
Eric Laurent81784c32012-11-19 14:55:58 -08001728 effect->setMode(mAudioFlinger->getMode());
1729 effect->setAudioSource(mAudioSource);
Eric Laurentd8365c52017-07-16 15:27:05 -07001730
Eric Laurent81784c32012-11-19 14:55:58 -08001731 return NO_ERROR;
1732}
1733
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001734void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect, bool release) {
Eric Laurent81784c32012-11-19 14:55:58 -08001735
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001736 ALOGV("%s %p effect %p", __FUNCTION__, this, effect.get());
Eric Laurent81784c32012-11-19 14:55:58 -08001737 effect_descriptor_t desc = effect->desc();
1738 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
1739 detachAuxEffect_l(effect->id());
1740 }
1741
Andy Hungfda44002021-06-03 17:23:16 -07001742 sp<EffectChain> chain = effect->getCallback()->chain().promote();
Eric Laurent81784c32012-11-19 14:55:58 -08001743 if (chain != 0) {
1744 // remove effect chain if removing last effect
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001745 if (chain->removeEffect_l(effect, release) == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08001746 removeEffectChain_l(chain);
1747 }
1748 } else {
1749 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
1750 }
1751}
1752
1753void AudioFlinger::ThreadBase::lockEffectChains_l(
1754 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1755{
1756 effectChains = mEffectChains;
1757 for (size_t i = 0; i < mEffectChains.size(); i++) {
1758 mEffectChains[i]->lock();
1759 }
1760}
1761
1762void AudioFlinger::ThreadBase::unlockEffectChains(
1763 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1764{
1765 for (size_t i = 0; i < effectChains.size(); i++) {
1766 effectChains[i]->unlock();
1767 }
1768}
1769
Glenn Kastend848eb42016-03-08 13:42:11 -08001770sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001771{
1772 Mutex::Autolock _l(mLock);
1773 return getEffectChain_l(sessionId);
1774}
1775
Glenn Kastend848eb42016-03-08 13:42:11 -08001776sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(audio_session_t sessionId)
1777 const
Eric Laurent81784c32012-11-19 14:55:58 -08001778{
1779 size_t size = mEffectChains.size();
1780 for (size_t i = 0; i < size; i++) {
1781 if (mEffectChains[i]->sessionId() == sessionId) {
1782 return mEffectChains[i];
1783 }
1784 }
1785 return 0;
1786}
1787
1788void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
1789{
1790 Mutex::Autolock _l(mLock);
1791 size_t size = mEffectChains.size();
1792 for (size_t i = 0; i < size; i++) {
1793 mEffectChains[i]->setMode_l(mode);
1794 }
1795}
1796
Mikhail Naganovdc769682018-05-04 15:34:08 -07001797void AudioFlinger::ThreadBase::toAudioPortConfig(struct audio_port_config *config)
Eric Laurent83b88082014-06-20 18:31:16 -07001798{
1799 config->type = AUDIO_PORT_TYPE_MIX;
1800 config->ext.mix.handle = mId;
1801 config->sample_rate = mSampleRate;
1802 config->format = mFormat;
1803 config->channel_mask = mChannelMask;
1804 config->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
1805 AUDIO_PORT_CONFIG_FORMAT;
1806}
1807
Eric Laurent72e3f392015-05-20 14:43:50 -07001808void AudioFlinger::ThreadBase::systemReady()
1809{
1810 Mutex::Autolock _l(mLock);
1811 if (mSystemReady) {
1812 return;
1813 }
1814 mSystemReady = true;
1815
1816 for (size_t i = 0; i < mPendingConfigEvents.size(); i++) {
1817 sendConfigEvent_l(mPendingConfigEvents.editItemAt(i));
1818 }
1819 mPendingConfigEvents.clear();
1820}
1821
Andy Hungdae27702016-10-31 14:01:16 -07001822template <typename T>
1823ssize_t AudioFlinger::ThreadBase::ActiveTracks<T>::add(const sp<T> &track) {
1824 ssize_t index = mActiveTracks.indexOf(track);
1825 if (index >= 0) {
1826 ALOGW("ActiveTracks<T>::add track %p already there", track.get());
1827 return index;
1828 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001829 logTrack("add", track);
Andy Hungdae27702016-10-31 14:01:16 -07001830 mActiveTracksGeneration++;
1831 mLatestActiveTrack = track;
1832 ++mBatteryCounter[track->uid()].second;
Kevin Rocard069c2712018-03-29 19:09:14 -07001833 mHasChanged = true;
Andy Hungdae27702016-10-31 14:01:16 -07001834 return mActiveTracks.add(track);
1835}
1836
1837template <typename T>
1838ssize_t AudioFlinger::ThreadBase::ActiveTracks<T>::remove(const sp<T> &track) {
1839 ssize_t index = mActiveTracks.remove(track);
1840 if (index < 0) {
1841 ALOGW("ActiveTracks<T>::remove nonexistent track %p", track.get());
1842 return index;
1843 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001844 logTrack("remove", track);
Andy Hungdae27702016-10-31 14:01:16 -07001845 mActiveTracksGeneration++;
1846 --mBatteryCounter[track->uid()].second;
1847 // mLatestActiveTrack is not cleared even if is the same as track.
Kevin Rocard069c2712018-03-29 19:09:14 -07001848 mHasChanged = true;
Andy Hung8946a282018-04-19 20:04:56 -07001849#ifdef TEE_SINK
1850 track->dumpTee(-1 /* fd */, "_REMOVE");
1851#endif
Andy Hungc2b11cb2020-04-22 09:04:01 -07001852 track->logEndInterval(); // log to MediaMetrics
Andy Hungdae27702016-10-31 14:01:16 -07001853 return index;
1854}
1855
1856template <typename T>
1857void AudioFlinger::ThreadBase::ActiveTracks<T>::clear() {
1858 for (const sp<T> &track : mActiveTracks) {
1859 BatteryNotifier::getInstance().noteStopAudio(track->uid());
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001860 logTrack("clear", track);
Andy Hungdae27702016-10-31 14:01:16 -07001861 }
1862 mLastActiveTracksGeneration = mActiveTracksGeneration;
Kevin Rocard069c2712018-03-29 19:09:14 -07001863 if (!mActiveTracks.empty()) { mHasChanged = true; }
Andy Hungdae27702016-10-31 14:01:16 -07001864 mActiveTracks.clear();
1865 mLatestActiveTrack.clear();
1866 mBatteryCounter.clear();
1867}
1868
1869template <typename T>
1870void AudioFlinger::ThreadBase::ActiveTracks<T>::updatePowerState(
1871 sp<ThreadBase> thread, bool force) {
1872 // Updates ActiveTracks client uids to the thread wakelock.
1873 if (mActiveTracksGeneration != mLastActiveTracksGeneration || force) {
1874 thread->updateWakeLockUids_l(getWakeLockUids());
1875 mLastActiveTracksGeneration = mActiveTracksGeneration;
1876 }
1877
1878 // Updates BatteryNotifier uids
1879 for (auto it = mBatteryCounter.begin(); it != mBatteryCounter.end();) {
1880 const uid_t uid = it->first;
1881 ssize_t &previous = it->second.first;
1882 ssize_t &current = it->second.second;
1883 if (current > 0) {
1884 if (previous == 0) {
1885 BatteryNotifier::getInstance().noteStartAudio(uid);
1886 }
1887 previous = current;
1888 ++it;
1889 } else if (current == 0) {
1890 if (previous > 0) {
1891 BatteryNotifier::getInstance().noteStopAudio(uid);
1892 }
1893 it = mBatteryCounter.erase(it); // std::map<> is stable on iterator erase.
1894 } else /* (current < 0) */ {
1895 LOG_ALWAYS_FATAL("negative battery count %zd", current);
1896 }
1897 }
1898}
Eric Laurent83b88082014-06-20 18:31:16 -07001899
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001900template <typename T>
Kevin Rocard069c2712018-03-29 19:09:14 -07001901bool AudioFlinger::ThreadBase::ActiveTracks<T>::readAndClearHasChanged() {
Jasmine Chaeaa10e42021-05-11 10:11:14 +08001902 bool hasChanged = mHasChanged;
Kevin Rocard069c2712018-03-29 19:09:14 -07001903 mHasChanged = false;
Jasmine Chaeaa10e42021-05-11 10:11:14 +08001904
1905 for (const sp<T> &track : mActiveTracks) {
1906 // Do not short-circuit as all hasChanged states must be reset
1907 // as all the metadata are going to be sent
1908 hasChanged |= track->readAndClearHasChanged();
1909 }
Kevin Rocard069c2712018-03-29 19:09:14 -07001910 return hasChanged;
1911}
1912
1913template <typename T>
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001914void AudioFlinger::ThreadBase::ActiveTracks<T>::logTrack(
1915 const char *funcName, const sp<T> &track) const {
1916 if (mLocalLog != nullptr) {
1917 String8 result;
1918 track->appendDump(result, false /* active */);
1919 mLocalLog->log("AT::%-10s(%p) %s", funcName, track.get(), result.string());
1920 }
1921}
1922
Eric Laurent6acd1d42017-01-04 14:23:29 -08001923void AudioFlinger::ThreadBase::broadcast_l()
1924{
1925 // Thread could be blocked waiting for async
1926 // so signal it to handle state changes immediately
1927 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
1928 // be lost so we also flag to prevent it blocking on mWaitWorkCV
1929 mSignalPending = true;
1930 mWaitWorkCV.broadcast();
1931}
1932
Andy Hungd0979812019-02-21 15:51:44 -08001933// Call only from threadLoop() or when it is idle.
1934// Do not call from high performance code as this may do binder rpc to the MediaMetrics service.
1935void AudioFlinger::ThreadBase::sendStatistics(bool force)
1936{
1937 // Do not log if we have no stats.
1938 // We choose the timestamp verifier because it is the most likely item to be present.
1939 const int64_t nstats = mTimestampVerifier.getN() - mLastRecordedTimestampVerifierN;
1940 if (nstats == 0) {
1941 return;
1942 }
1943
1944 // Don't log more frequently than once per 12 hours.
1945 // We use BOOTTIME to include suspend time.
1946 const int64_t timeNs = systemTime(SYSTEM_TIME_BOOTTIME);
1947 const int64_t sinceNs = timeNs - mLastRecordedTimeNs; // ok if mLastRecordedTimeNs = 0
1948 if (!force && sinceNs <= 12 * NANOS_PER_HOUR) {
1949 return;
1950 }
1951
1952 mLastRecordedTimestampVerifierN = mTimestampVerifier.getN();
1953 mLastRecordedTimeNs = timeNs;
1954
Ray Essickf27e9872019-12-07 06:28:46 -08001955 std::unique_ptr<mediametrics::Item> item(mediametrics::Item::create("audiothread"));
Andy Hungd0979812019-02-21 15:51:44 -08001956
1957#define MM_PREFIX "android.media.audiothread." // avoid cut-n-paste errors.
1958
1959 // thread configuration
1960 item->setInt32(MM_PREFIX "id", (int32_t)mId); // IO handle
1961 // item->setInt32(MM_PREFIX "portId", (int32_t)mPortId);
1962 item->setCString(MM_PREFIX "type", threadTypeToString(mType));
1963 item->setInt32(MM_PREFIX "sampleRate", (int32_t)mSampleRate);
1964 item->setInt64(MM_PREFIX "channelMask", (int64_t)mChannelMask);
1965 item->setCString(MM_PREFIX "encoding", toString(mFormat).c_str());
1966 item->setInt32(MM_PREFIX "frameCount", (int32_t)mFrameCount);
jiabinc52b1ff2019-10-31 17:20:42 -07001967 item->setCString(MM_PREFIX "outDevice", toString(outDeviceTypes()).c_str());
1968 item->setCString(MM_PREFIX "inDevice", toString(inDeviceType()).c_str());
Andy Hungd0979812019-02-21 15:51:44 -08001969
1970 // thread statistics
1971 if (mIoJitterMs.getN() > 0) {
1972 item->setDouble(MM_PREFIX "ioJitterMs.mean", mIoJitterMs.getMean());
1973 item->setDouble(MM_PREFIX "ioJitterMs.std", mIoJitterMs.getStdDev());
1974 }
1975 if (mProcessTimeMs.getN() > 0) {
1976 item->setDouble(MM_PREFIX "processTimeMs.mean", mProcessTimeMs.getMean());
1977 item->setDouble(MM_PREFIX "processTimeMs.std", mProcessTimeMs.getStdDev());
1978 }
1979 const auto tsjitter = mTimestampVerifier.getJitterMs();
1980 if (tsjitter.getN() > 0) {
1981 item->setDouble(MM_PREFIX "timestampJitterMs.mean", tsjitter.getMean());
1982 item->setDouble(MM_PREFIX "timestampJitterMs.std", tsjitter.getStdDev());
1983 }
1984 if (mLatencyMs.getN() > 0) {
1985 item->setDouble(MM_PREFIX "latencyMs.mean", mLatencyMs.getMean());
1986 item->setDouble(MM_PREFIX "latencyMs.std", mLatencyMs.getStdDev());
1987 }
Robert Wu06db0a32021-08-10 19:05:34 +00001988 if (mMonopipePipeDepthStats.getN() > 0) {
1989 item->setDouble(MM_PREFIX "monopipePipeDepthStats.mean",
1990 mMonopipePipeDepthStats.getMean());
1991 item->setDouble(MM_PREFIX "monopipePipeDepthStats.std",
1992 mMonopipePipeDepthStats.getStdDev());
1993 }
Andy Hungd0979812019-02-21 15:51:44 -08001994
1995 item->selfrecord();
1996}
1997
Eric Laurentd66d7a12021-07-13 13:35:32 +02001998product_strategy_t AudioFlinger::ThreadBase::getStrategyForStream(audio_stream_type_t stream) const
1999{
2000 if (!mAudioFlinger->isAudioPolicyReady()) {
2001 return PRODUCT_STRATEGY_NONE;
2002 }
2003 return AudioSystem::getStrategyForStream(stream);
2004}
2005
Eric Laurent81784c32012-11-19 14:55:58 -08002006// ----------------------------------------------------------------------------
2007// Playback
2008// ----------------------------------------------------------------------------
2009
2010AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
2011 AudioStreamOut* output,
2012 audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -07002013 type_t type,
Eric Laurentf1f22e72021-07-13 14:04:14 +02002014 bool systemReady,
2015 audio_config_base_t *mixerConfig)
Andy Hungcf10d742020-04-28 15:38:24 -07002016 : ThreadBase(audioFlinger, id, type, systemReady, true /* isOut */),
Andy Hung2098f272014-02-27 14:00:06 -08002017 mNormalFrameCount(0), mSinkBuffer(NULL),
Eric Laurent1c5e2e32021-08-18 18:50:28 +02002018 mMixerBufferEnabled(AudioFlinger::kEnableExtendedPrecision || type == SPATIALIZER),
Andy Hung69aed5f2014-02-25 17:24:40 -08002019 mMixerBuffer(NULL),
2020 mMixerBufferSize(0),
2021 mMixerBufferFormat(AUDIO_FORMAT_INVALID),
2022 mMixerBufferValid(false),
Eric Laurent1c5e2e32021-08-18 18:50:28 +02002023 mEffectBufferEnabled(AudioFlinger::kEnableExtendedPrecision || type == SPATIALIZER),
Andy Hung98ef9782014-03-04 14:46:50 -08002024 mEffectBuffer(NULL),
2025 mEffectBufferSize(0),
2026 mEffectBufferFormat(AUDIO_FORMAT_INVALID),
2027 mEffectBufferValid(false),
Glenn Kastenc1fac192013-08-06 07:41:36 -07002028 mSuspended(0), mBytesWritten(0),
Andy Hungc54b1ff2016-02-23 14:07:07 -08002029 mFramesWritten(0),
Andy Hung238fa3d2016-07-28 10:53:22 -07002030 mSuspendedFrames(0),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002031 mActiveTracks(&this->mLocalLog),
Eric Laurent81784c32012-11-19 14:55:58 -08002032 // mStreamTypes[] initialized in constructor body
Andy Hung1bc088a2018-02-09 15:57:31 -08002033 mTracks(type == MIXER),
Eric Laurent81784c32012-11-19 14:55:58 -08002034 mOutput(output),
Andy Hung446f4df2019-02-21 12:26:41 -08002035 mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
Eric Laurent81784c32012-11-19 14:55:58 -08002036 mMixerStatus(MIXER_IDLE),
2037 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002038 mStandbyDelayNs(AudioFlinger::mStandbyTimeInNsecs),
Eric Laurentbfb1b832013-01-07 09:53:42 -08002039 mBytesRemaining(0),
2040 mCurrentWriteLength(0),
2041 mUseAsyncWrite(false),
Eric Laurent3b4529e2013-09-05 18:09:19 -07002042 mWriteAckSequence(0),
2043 mDrainSequence(0),
Eric Laurent81784c32012-11-19 14:55:58 -08002044 mScreenState(AudioFlinger::mScreenState),
2045 // index 0 is reserved for normal mixer's submix
Glenn Kastendc2c50b2016-04-21 08:13:14 -07002046 mFastTrackAvailMask(((1 << FastMixerState::sMaxFastTracks) - 1) & ~1),
Eric Laurent7c29ec92017-09-20 17:54:22 -07002047 mHwSupportsPause(false), mHwPaused(false), mFlushPending(false),
Eric Laurent74c38dc2020-12-23 18:19:44 +01002048 mLeftVolFloat(-1.0), mRightVolFloat(-1.0),
Brian Lindahl65e90012022-07-27 18:01:07 +02002049 mDownStreamPatch{},
2050 mIsTimestampAdvancing(kMinimumTimeBetweenTimestampChecksNs)
Eric Laurent81784c32012-11-19 14:55:58 -08002051{
Glenn Kastend7dca052015-03-05 16:05:54 -08002052 snprintf(mThreadName, kThreadNameLength, "AudioOut_%X", id);
2053 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08002054
2055 // Assumes constructor is called by AudioFlinger with it's mLock held, but
2056 // it would be safer to explicitly pass initial masterVolume/masterMute as
2057 // parameter.
2058 //
2059 // If the HAL we are using has support for master volume or master mute,
2060 // then do not attenuate or mute during mixing (just leave the volume at 1.0
2061 // and the mute set to false).
2062 mMasterVolume = audioFlinger->masterVolume_l();
2063 mMasterMute = audioFlinger->masterMute_l();
George Burgess IV5e4d86f2020-02-18 12:55:36 -08002064 if (mOutput->audioHwDev) {
Eric Laurent81784c32012-11-19 14:55:58 -08002065 if (mOutput->audioHwDev->canSetMasterVolume()) {
2066 mMasterVolume = 1.0;
2067 }
2068
2069 if (mOutput->audioHwDev->canSetMasterMute()) {
2070 mMasterMute = false;
2071 }
Andy Hungc8fddf32018-08-08 18:32:37 -07002072 mIsMsdDevice = strcmp(
2073 mOutput->audioHwDev->moduleName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002074 }
2075
Eric Laurentf1f22e72021-07-13 14:04:14 +02002076 if (mixerConfig != nullptr && mixerConfig->channel_mask != AUDIO_CHANNEL_NONE) {
2077 mMixerChannelMask = mixerConfig->channel_mask;
2078 }
2079
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002080 readOutputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002081
Eric Laurent1c5e2e32021-08-18 18:50:28 +02002082 if (mType != SPATIALIZER
Eric Laurentb3f315a2021-07-13 15:09:05 +02002083 && mMixerChannelMask != mChannelMask) {
2084 LOG_ALWAYS_FATAL("HAL channel mask %#x does not match mixer channel mask %#x",
2085 mChannelMask, mMixerChannelMask);
2086 }
2087
Andy Hungc8fddf32018-08-08 18:32:37 -07002088 // TODO: We may also match on address as well as device type for
2089 // AUDIO_DEVICE_OUT_BUS, AUDIO_DEVICE_OUT_ALL_A2DP, AUDIO_DEVICE_OUT_REMOTE_SUBMIX
Dean Wheatleyf8726f02019-12-02 14:12:01 +11002090 if (type == MIXER || type == DIRECT || type == OFFLOAD) {
jiabinc52b1ff2019-10-31 17:20:42 -07002091 // TODO: This property should be ensure that only contains one single device type.
2092 mTimestampCorrectedDevice = (audio_devices_t)property_get_int64(
2093 "audio.timestamp.corrected_output_device",
Andy Hungc8fddf32018-08-08 18:32:37 -07002094 (int64_t)(mIsMsdDevice ? AUDIO_DEVICE_OUT_BUS // turn on by default for MSD
2095 : AUDIO_DEVICE_NONE));
2096 }
2097
Mikhail Naganovf33115d2020-09-25 23:03:05 +00002098 for (int i = AUDIO_STREAM_MIN; i < AUDIO_STREAM_FOR_POLICY_CNT; ++i) {
2099 const audio_stream_type_t stream{static_cast<audio_stream_type_t>(i)};
Eric Laurent98e38192018-02-15 18:31:53 -08002100 mStreamTypes[stream].volume = 0.0f;
Eric Laurent81784c32012-11-19 14:55:58 -08002101 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
2102 }
Eric Laurent35f8c7c2020-02-08 11:42:35 -08002103 // Audio patch and call assistant volume are always max
Eric Laurent98e38192018-02-15 18:31:53 -08002104 mStreamTypes[AUDIO_STREAM_PATCH].volume = 1.0f;
2105 mStreamTypes[AUDIO_STREAM_PATCH].mute = false;
Eric Laurent35f8c7c2020-02-08 11:42:35 -08002106 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].volume = 1.0f;
2107 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].mute = false;
Eric Laurent81784c32012-11-19 14:55:58 -08002108}
2109
2110AudioFlinger::PlaybackThread::~PlaybackThread()
2111{
Glenn Kasten9e58b552013-01-18 15:09:48 -08002112 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung010a1a12014-03-13 13:57:33 -07002113 free(mSinkBuffer);
Andy Hung69aed5f2014-02-25 17:24:40 -08002114 free(mMixerBuffer);
Andy Hung98ef9782014-03-04 14:46:50 -08002115 free(mEffectBuffer);
Eric Laurentb62d0362021-10-26 17:40:18 +02002116 free(mPostSpatializerBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08002117}
2118
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002119// Thread virtuals
2120
2121void AudioFlinger::PlaybackThread::onFirstRef()
Eric Laurent81784c32012-11-19 14:55:58 -08002122{
Jasmine Chaeaa10e42021-05-11 10:11:14 +08002123 if (!isStreamInitialized()) {
jiabinf6eb4c32020-02-25 14:06:25 -08002124 ALOGE("The stream is not open yet"); // This should not happen.
2125 } else {
2126 // setEventCallback will need a strong pointer as a parameter. Calling it
2127 // here instead of constructor of PlaybackThread so that the onFirstRef
2128 // callback would not be made on an incompletely constructed object.
2129 if (mOutput->stream->setEventCallback(this) != OK) {
jiabinf1a36052020-08-19 14:33:31 -07002130 ALOGD("Failed to add event callback");
jiabinf6eb4c32020-02-25 14:06:25 -08002131 }
2132 }
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002133 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
Andy Hung44d648b2022-04-08 17:33:40 -07002134 mThreadSnapshot.setTid(getTid());
Eric Laurent81784c32012-11-19 14:55:58 -08002135}
2136
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002137// ThreadBase virtuals
2138void AudioFlinger::PlaybackThread::preExit()
2139{
2140 ALOGV(" preExit()");
Ytai Ben-Tsvi7e0183f2022-02-04 10:49:54 -08002141 status_t result = mOutput->stream->exit();
2142 ALOGE_IF(result != OK, "Error when calling exit(): %d", result);
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002143}
2144
2145void AudioFlinger::PlaybackThread::dumpTracks_l(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08002146{
Eric Laurent81784c32012-11-19 14:55:58 -08002147 String8 result;
2148
Marco Nelissenb2208842014-02-07 14:00:50 -08002149 result.appendFormat(" Stream volumes in dB: ");
Eric Laurent81784c32012-11-19 14:55:58 -08002150 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
2151 const stream_type_t *st = &mStreamTypes[i];
2152 if (i > 0) {
2153 result.appendFormat(", ");
2154 }
2155 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
2156 if (st->mute) {
2157 result.append("M");
2158 }
2159 }
2160 result.append("\n");
2161 write(fd, result.string(), result.length());
2162 result.clear();
2163
Eric Laurent81784c32012-11-19 14:55:58 -08002164 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
2165 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
Elliott Hughes87cebad2014-05-22 10:14:43 -07002166 dprintf(fd, " Normal mixer raw underrun counters: partial=%u empty=%u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08002167 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Marco Nelissenb2208842014-02-07 14:00:50 -08002168
2169 size_t numtracks = mTracks.size();
2170 size_t numactive = mActiveTracks.size();
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002171 dprintf(fd, " %zu Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08002172 size_t numactiveseen = 0;
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002173 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08002174 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002175 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002176 result.append(prefix);
Andy Hungf6ab58d2018-05-25 12:50:39 -07002177 mTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08002178 for (size_t i = 0; i < numtracks; ++i) {
2179 sp<Track> track = mTracks[i];
2180 if (track != 0) {
2181 bool active = mActiveTracks.indexOf(track) >= 0;
2182 if (active) {
2183 numactiveseen++;
2184 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002185 result.append(prefix);
2186 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08002187 }
2188 }
2189 } else {
2190 result.append("\n");
2191 }
2192 if (numactiveseen != numactive) {
2193 // some tracks in the active list were not in the tracks list
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002194 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08002195 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002196 result.append(prefix);
Andy Hungf6ab58d2018-05-25 12:50:39 -07002197 mActiveTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08002198 for (size_t i = 0; i < numactive; ++i) {
Andy Hungdae27702016-10-31 14:01:16 -07002199 sp<Track> track = mActiveTracks[i];
2200 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002201 result.append(prefix);
2202 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08002203 }
2204 }
2205 }
2206
2207 write(fd, result.string(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08002208}
2209
Andy Hung61589a42021-06-16 09:37:53 -07002210void AudioFlinger::PlaybackThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -08002211{
Andy Hung04cb8f72020-03-20 13:44:33 -07002212 dprintf(fd, " Master volume: %f\n", mMasterVolume);
Mikhail Naganovdfb411f2018-09-11 13:39:56 -07002213 dprintf(fd, " Master mute: %s\n", mMasterMute ? "on" : "off");
Eric Laurentf1f22e72021-07-13 14:04:14 +02002214 dprintf(fd, " Mixer channel Mask: %#x (%s)\n",
2215 mMixerChannelMask, channelMaskToString(mMixerChannelMask, true /* output */).c_str());
jiabin245cdd92018-12-07 17:55:15 -08002216 if (mHapticChannelMask != AUDIO_CHANNEL_NONE) {
2217 dprintf(fd, " Haptic channel mask: %#x (%s)\n", mHapticChannelMask,
2218 channelMaskToString(mHapticChannelMask, true /* output */).c_str());
2219 }
Elliott Hughes87cebad2014-05-22 10:14:43 -07002220 dprintf(fd, " Normal frame count: %zu\n", mNormalFrameCount);
Elliott Hughes87cebad2014-05-22 10:14:43 -07002221 dprintf(fd, " Total writes: %d\n", mNumWrites);
2222 dprintf(fd, " Delayed writes: %d\n", mNumDelayedWrites);
2223 dprintf(fd, " Blocked in write: %s\n", mInWrite ? "yes" : "no");
2224 dprintf(fd, " Suspend count: %d\n", mSuspended);
2225 dprintf(fd, " Sink buffer : %p\n", mSinkBuffer);
2226 dprintf(fd, " Mixer buffer: %p\n", mMixerBuffer);
2227 dprintf(fd, " Effect buffer: %p\n", mEffectBuffer);
2228 dprintf(fd, " Fast track availMask=%#x\n", mFastTrackAvailMask);
Eric Laurent42537be2016-01-08 17:16:42 -08002229 dprintf(fd, " Standby delay ns=%lld\n", (long long)mStandbyDelayNs);
Glenn Kasten97b7b752014-09-28 13:04:24 -07002230 AudioStreamOut *output = mOutput;
2231 audio_output_flags_t flags = output != NULL ? output->flags : AUDIO_OUTPUT_FLAG_NONE;
Mikhail Naganov913d06c2016-11-01 12:49:22 -07002232 dprintf(fd, " AudioStreamOut: %p flags %#x (%s)\n",
Andy Hung9b181952019-02-25 14:53:36 -08002233 output, flags, toString(flags).c_str());
Andy Hungb54c8542016-09-21 12:55:15 -07002234 dprintf(fd, " Frames written: %lld\n", (long long)mFramesWritten);
2235 dprintf(fd, " Suspended frames: %lld\n", (long long)mSuspendedFrames);
2236 if (mPipeSink.get() != nullptr) {
2237 dprintf(fd, " PipeSink frames written: %lld\n", (long long)mPipeSink->framesWritten());
2238 }
2239 if (output != nullptr) {
2240 dprintf(fd, " Hal stream dump:\n");
Andy Hung61589a42021-06-16 09:37:53 -07002241 (void)output->stream->dump(fd, args);
Andy Hungb54c8542016-09-21 12:55:15 -07002242 }
Eric Laurent81784c32012-11-19 14:55:58 -08002243}
2244
Eric Laurent81784c32012-11-19 14:55:58 -08002245// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
2246sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
2247 const sp<AudioFlinger::Client>& client,
2248 audio_stream_type_t streamType,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07002249 const audio_attributes_t& attr,
Eric Laurent21da6472017-11-09 16:29:26 -08002250 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08002251 audio_format_t format,
2252 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08002253 size_t *pFrameCount,
Eric Laurent21da6472017-11-09 16:29:26 -08002254 size_t *pNotificationFrameCount,
2255 uint32_t notificationsPerBuffer,
2256 float speed,
Eric Laurent81784c32012-11-19 14:55:58 -08002257 const sp<IMemory>& sharedBuffer,
Glenn Kastend848eb42016-03-08 13:42:11 -08002258 audio_session_t sessionId,
Eric Laurent05067782016-06-01 18:27:28 -07002259 audio_output_flags_t *flags,
Eric Laurent09f1ed22019-04-24 17:45:17 -07002260 pid_t creatorPid,
Svet Ganov33761132021-05-13 22:51:08 +00002261 const AttributionSourceState& attributionSource,
Eric Laurent81784c32012-11-19 14:55:58 -08002262 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002263 status_t *status,
jiabinf6eb4c32020-02-25 14:06:25 -08002264 audio_port_handle_t portId,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02002265 const sp<media::IAudioTrackCallback>& callback,
2266 bool isSpatialized)
Eric Laurent81784c32012-11-19 14:55:58 -08002267{
Glenn Kasten74935e42013-12-19 08:56:45 -08002268 size_t frameCount = *pFrameCount;
Eric Laurent21da6472017-11-09 16:29:26 -08002269 size_t notificationFrameCount = *pNotificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08002270 sp<Track> track;
2271 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07002272 audio_output_flags_t outputFlags = mOutput->flags;
Eric Laurent21da6472017-11-09 16:29:26 -08002273 audio_output_flags_t requestedFlags = *flags;
Eric Laurent9b11c022018-06-06 19:19:22 -07002274 uint32_t sampleRate;
2275
2276 if (sharedBuffer != 0 && checkIMemory(sharedBuffer) != NO_ERROR) {
2277 lStatus = BAD_VALUE;
2278 goto Exit;
2279 }
Eric Laurent21da6472017-11-09 16:29:26 -08002280
2281 if (*pSampleRate == 0) {
2282 *pSampleRate = mSampleRate;
2283 }
Eric Laurent9b11c022018-06-06 19:19:22 -07002284 sampleRate = *pSampleRate;
Eric Laurent05067782016-06-01 18:27:28 -07002285
2286 // special case for FAST flag considered OK if fast mixer is present
2287 if (hasFastMixer()) {
2288 outputFlags = (audio_output_flags_t)(outputFlags | AUDIO_OUTPUT_FLAG_FAST);
2289 }
2290
2291 // Check if requested flags are compatible with output stream flags
2292 if ((*flags & outputFlags) != *flags) {
2293 ALOGW("createTrack_l(): mismatch between requested flags (%08x) and output flags (%08x)",
2294 *flags, outputFlags);
2295 *flags = (audio_output_flags_t)(*flags & outputFlags);
2296 }
Eric Laurent81784c32012-11-19 14:55:58 -08002297
Eric Laurent81784c32012-11-19 14:55:58 -08002298 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07002299 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
Eric Laurent81784c32012-11-19 14:55:58 -08002300 if (
Eric Laurent81784c32012-11-19 14:55:58 -08002301 // PCM data
2302 audio_is_linear_pcm(format) &&
Andy Hung1f439e12015-05-19 12:57:41 -07002303 // TODO: extract as a data library function that checks that a computationally
2304 // expensive downmixer is not required: isFastOutputChannelConversion()
jiabin245cdd92018-12-07 17:55:15 -08002305 (channelMask == (mChannelMask | mHapticChannelMask) ||
Andy Hung1f439e12015-05-19 12:57:41 -07002306 mChannelMask != AUDIO_CHANNEL_OUT_STEREO ||
2307 (channelMask == AUDIO_CHANNEL_OUT_MONO
2308 /* && mChannelMask == AUDIO_CHANNEL_OUT_STEREO */)) &&
Eric Laurent81784c32012-11-19 14:55:58 -08002309 // hardware sample rate
2310 (sampleRate == mSampleRate) &&
Eric Laurent81784c32012-11-19 14:55:58 -08002311 // normal mixer has an associated fast mixer
2312 hasFastMixer() &&
2313 // there are sufficient fast track slots available
2314 (mFastTrackAvailMask != 0)
2315 // FIXME test that MixerThread for this fast track has a capable output HAL
2316 // FIXME add a permission test also?
2317 ) {
Andy Hunge0a269a2016-03-23 15:13:42 -07002318 // static tracks can have any nonzero framecount, streaming tracks check against minimum.
2319 if (sharedBuffer == 0) {
Glenn Kasten03490092014-05-27 12:30:54 -07002320 // read the fast track multiplier property the first time it is needed
2321 int ok = pthread_once(&sFastTrackMultiplierOnce, sFastTrackMultiplierInit);
2322 if (ok != 0) {
2323 ALOGE("%s pthread_once failed: %d", __func__, ok);
2324 }
Andy Hunge0a269a2016-03-23 15:13:42 -07002325 frameCount = max(frameCount, mFrameCount * sFastTrackMultiplier); // incl framecount 0
Eric Laurent81784c32012-11-19 14:55:58 -08002326 }
Eric Laurent4c415062016-06-17 16:14:16 -07002327
2328 // check compatibility with audio effects.
2329 { // scope for mLock
2330 Mutex::Autolock _l(mLock);
Andy Hungd3bb0ad2016-10-11 17:16:43 -07002331 for (audio_session_t session : {
Eric Laurent3f75a5b2019-11-12 15:55:51 -08002332 AUDIO_SESSION_DEVICE,
Andy Hungd3bb0ad2016-10-11 17:16:43 -07002333 AUDIO_SESSION_OUTPUT_STAGE,
2334 AUDIO_SESSION_OUTPUT_MIX,
2335 sessionId,
2336 }) {
2337 sp<EffectChain> chain = getEffectChain_l(session);
2338 if (chain.get() != nullptr) {
2339 audio_output_flags_t old = *flags;
2340 chain->checkOutputFlagCompatibility(flags);
2341 if (old != *flags) {
2342 ALOGV("AUDIO_OUTPUT_FLAGS denied by effect, session=%d old=%#x new=%#x",
2343 (int)session, (int)old, (int)*flags);
2344 }
Eric Laurent4c415062016-06-17 16:14:16 -07002345 }
2346 }
2347 }
Eric Laurent122f7e72016-06-29 11:53:29 -07002348 ALOGV_IF((*flags & AUDIO_OUTPUT_FLAG_FAST) != 0,
Eric Laurent4c415062016-06-17 16:14:16 -07002349 "AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
2350 frameCount, mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08002351 } else {
Robert Wu4c7bb7d2021-08-12 18:50:13 +00002352 ALOGD("AUDIO_OUTPUT_FLAG_FAST denied: sharedBuffer=%p frameCount=%zu "
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002353 "mFrameCount=%zu format=%#x mFormat=%#x isLinear=%d channelMask=%#x "
Andy Hung6146c082014-03-18 11:56:15 -07002354 "sampleRate=%u mSampleRate=%u "
Eric Laurent81784c32012-11-19 14:55:58 -08002355 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
Glenn Kastend79072e2016-01-06 08:41:20 -08002356 sharedBuffer.get(), frameCount, mFrameCount, format, mFormat,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07002357 audio_is_linear_pcm(format), channelMask, sampleRate,
2358 mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
Eric Laurent4c415062016-06-17 16:14:16 -07002359 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_FAST);
Andy Hung0e48d252015-01-26 11:43:15 -08002360 }
2361 }
Eric Laurent21da6472017-11-09 16:29:26 -08002362
2363 if (!audio_has_proportional_frames(format)) {
2364 if (sharedBuffer != 0) {
2365 // Same comment as below about ignoring frameCount parameter for set()
2366 frameCount = sharedBuffer->size();
2367 } else if (frameCount == 0) {
2368 frameCount = mNormalFrameCount;
2369 }
2370 if (notificationFrameCount != frameCount) {
2371 notificationFrameCount = frameCount;
2372 }
2373 } else if (sharedBuffer != 0) {
2374 // FIXME: Ensure client side memory buffers need
2375 // not have additional alignment beyond sample
2376 // (e.g. 16 bit stereo accessed as 32 bit frame).
2377 size_t alignment = audio_bytes_per_sample(format);
2378 if (alignment & 1) {
2379 // for AUDIO_FORMAT_PCM_24_BIT_PACKED (not exposed through Java).
2380 alignment = 1;
2381 }
2382 uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
2383 size_t frameSize = channelCount * audio_bytes_per_sample(format);
2384 if (channelCount > 1) {
2385 // More than 2 channels does not require stronger alignment than stereo
2386 alignment <<= 1;
2387 }
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07002388 if (((uintptr_t)sharedBuffer->unsecurePointer() & (alignment - 1)) != 0) {
Eric Laurent21da6472017-11-09 16:29:26 -08002389 ALOGE("Invalid buffer alignment: address %p, channel count %u",
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07002390 sharedBuffer->unsecurePointer(), channelCount);
Eric Laurent21da6472017-11-09 16:29:26 -08002391 lStatus = BAD_VALUE;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002392 goto Exit;
2393 }
Eric Laurent21da6472017-11-09 16:29:26 -08002394
2395 // When initializing a shared buffer AudioTrack via constructors,
2396 // there's no frameCount parameter.
2397 // But when initializing a shared buffer AudioTrack via set(),
2398 // there _is_ a frameCount parameter. We silently ignore it.
2399 frameCount = sharedBuffer->size() / frameSize;
2400 } else {
2401 size_t minFrameCount = 0;
2402 // For fast tracks we try to respect the application's request for notifications per buffer.
2403 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
2404 if (notificationsPerBuffer > 0) {
2405 // Avoid possible arithmetic overflow during multiplication.
2406 if (notificationsPerBuffer > SIZE_MAX / mFrameCount) {
2407 ALOGE("Requested notificationPerBuffer=%u ignored for HAL frameCount=%zu",
2408 notificationsPerBuffer, mFrameCount);
2409 } else {
2410 minFrameCount = mFrameCount * notificationsPerBuffer;
2411 }
2412 }
2413 } else {
2414 // For normal PCM streaming tracks, update minimum frame count.
2415 // Buffer depth is forced to be at least 2 x the normal mixer frame count and
2416 // cover audio hardware latency.
2417 // This is probably too conservative, but legacy application code may depend on it.
2418 // If you change this calculation, also review the start threshold which is related.
2419 uint32_t latencyMs = latency_l();
2420 if (latencyMs == 0) {
2421 ALOGE("Error when retrieving output stream latency");
2422 lStatus = UNKNOWN_ERROR;
2423 goto Exit;
2424 }
2425
2426 minFrameCount = AudioSystem::calculateMinFrameCount(latencyMs, mNormalFrameCount,
2427 mSampleRate, sampleRate, speed /*, 0 mNotificationsPerBufferReq*/);
2428
Eric Laurent81784c32012-11-19 14:55:58 -08002429 }
Eric Laurent21da6472017-11-09 16:29:26 -08002430 if (frameCount < minFrameCount) {
Eric Laurent81784c32012-11-19 14:55:58 -08002431 frameCount = minFrameCount;
2432 }
Eric Laurent81784c32012-11-19 14:55:58 -08002433 }
Eric Laurent21da6472017-11-09 16:29:26 -08002434
2435 // Make sure that application is notified with sufficient margin before underrun.
2436 // The client can divide the AudioTrack buffer into sub-buffers,
2437 // and expresses its desire to server as the notification frame count.
2438 if (sharedBuffer == 0 && audio_is_linear_pcm(format)) {
2439 size_t maxNotificationFrames;
2440 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
2441 // notify every HAL buffer, regardless of the size of the track buffer
2442 maxNotificationFrames = mFrameCount;
2443 } else {
Andy Hungfa117802019-04-12 13:50:39 -07002444 // Triple buffer the notification period for a triple buffered mixer period;
2445 // otherwise, double buffering for the notification period is fine.
2446 //
2447 // TODO: This should be moved to AudioTrack to modify the notification period
2448 // on AudioTrack::setBufferSizeInFrames() changes.
2449 const int nBuffering =
2450 (uint64_t{frameCount} * mSampleRate)
2451 / (uint64_t{mNormalFrameCount} * sampleRate) == 3 ? 3 : 2;
2452
Eric Laurent21da6472017-11-09 16:29:26 -08002453 maxNotificationFrames = frameCount / nBuffering;
2454 // If client requested a fast track but this was denied, then use the smaller maximum.
2455 if (requestedFlags & AUDIO_OUTPUT_FLAG_FAST) {
2456 size_t maxNotificationFramesFastDenied = FMS_20 * sampleRate / 1000;
2457 if (maxNotificationFrames > maxNotificationFramesFastDenied) {
2458 maxNotificationFrames = maxNotificationFramesFastDenied;
2459 }
2460 }
2461 }
2462 if (notificationFrameCount == 0 || notificationFrameCount > maxNotificationFrames) {
2463 if (notificationFrameCount == 0) {
2464 ALOGD("Client defaulted notificationFrames to %zu for frameCount %zu",
2465 maxNotificationFrames, frameCount);
2466 } else {
2467 ALOGW("Client adjusted notificationFrames from %zu to %zu for frameCount %zu",
2468 notificationFrameCount, maxNotificationFrames, frameCount);
2469 }
2470 notificationFrameCount = maxNotificationFrames;
2471 }
2472 }
2473
Glenn Kasten74935e42013-12-19 08:56:45 -08002474 *pFrameCount = frameCount;
Eric Laurent21da6472017-11-09 16:29:26 -08002475 *pNotificationFrameCount = notificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08002476
Glenn Kastenc3df8382014-03-13 15:05:25 -07002477 switch (mType) {
2478
2479 case DIRECT:
Phil Burkfdb3c072016-02-09 10:47:02 -08002480 if (audio_is_linear_pcm(format)) { // TODO maybe use audio_has_proportional_frames()?
Eric Laurent81784c32012-11-19 14:55:58 -08002481 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002482 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
2483 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08002484 sampleRate, format, channelMask, mOutput, mFormat);
2485 lStatus = BAD_VALUE;
2486 goto Exit;
2487 }
2488 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002489 break;
2490
2491 case OFFLOAD:
Eric Laurentbfb1b832013-01-07 09:53:42 -08002492 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002493 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
2494 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002495 sampleRate, format, channelMask, mOutput, mFormat);
2496 lStatus = BAD_VALUE;
2497 goto Exit;
2498 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002499 break;
2500
2501 default:
Glenn Kasten993fa062014-05-02 11:14:34 -07002502 if (!audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002503 ALOGE("createTrack_l() Bad parameter: format %#x \""
2504 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002505 format, mOutput, mFormat);
2506 lStatus = BAD_VALUE;
2507 goto Exit;
2508 }
Andy Hungcd044842014-08-07 11:04:34 -07002509 if (sampleRate > mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Eric Laurent81784c32012-11-19 14:55:58 -08002510 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
2511 lStatus = BAD_VALUE;
2512 goto Exit;
2513 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002514 break;
2515
Eric Laurent81784c32012-11-19 14:55:58 -08002516 }
2517
2518 lStatus = initCheck();
2519 if (lStatus != NO_ERROR) {
Glenn Kasten15e57982013-09-24 11:52:37 -07002520 ALOGE("createTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08002521 goto Exit;
2522 }
2523
2524 { // scope for mLock
2525 Mutex::Autolock _l(mLock);
2526
2527 // all tracks in same audio session must share the same routing strategy otherwise
2528 // conflicts will happen when tracks are moved from one output to another by audio policy
2529 // manager
Eric Laurentd66d7a12021-07-13 13:35:32 +02002530 product_strategy_t strategy = getStrategyForStream(streamType);
Eric Laurent81784c32012-11-19 14:55:58 -08002531 for (size_t i = 0; i < mTracks.size(); ++i) {
2532 sp<Track> t = mTracks[i];
Eric Laurent83b88082014-06-20 18:31:16 -07002533 if (t != 0 && t->isExternalTrack()) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02002534 product_strategy_t actual = getStrategyForStream(t->streamType());
Eric Laurent81784c32012-11-19 14:55:58 -08002535 if (sessionId == t->sessionId() && strategy != actual) {
2536 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
2537 strategy, actual);
2538 lStatus = BAD_VALUE;
2539 goto Exit;
2540 }
2541 }
2542 }
2543
yucliuc9c49cd2020-07-13 16:25:21 -07002544 // Set DIRECT flag if current thread is DirectOutputThread. This can
2545 // happen when the playback is rerouted to direct output thread by
2546 // dynamic audio policy.
2547 // Do NOT report the flag changes back to client, since the client
2548 // doesn't explicitly request a direct flag.
2549 audio_output_flags_t trackFlags = *flags;
2550 if (mType == DIRECT) {
2551 trackFlags = static_cast<audio_output_flags_t>(trackFlags | AUDIO_OUTPUT_FLAG_DIRECT);
2552 }
2553
Kevin Rocard1f564ac2018-03-29 13:53:10 -07002554 track = new Track(this, client, streamType, attr, sampleRate, format,
Andy Hung8fe68032017-06-05 16:17:51 -07002555 channelMask, frameCount,
2556 nullptr /* buffer */, (size_t)0 /* bufferSize */, sharedBuffer,
Svet Ganov33761132021-05-13 22:51:08 +00002557 sessionId, creatorPid, attributionSource, trackFlags,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02002558 TrackBase::TYPE_DEFAULT, portId, SIZE_MAX /*frameCountToBeReady*/,
2559 speed, isSpatialized);
Glenn Kasten03003332013-08-06 15:40:54 -07002560
Glenn Kasten03003332013-08-06 15:40:54 -07002561 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
2562 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08002563 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08002564 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08002565 goto Exit;
2566 }
2567 mTracks.add(track);
jiabinf6eb4c32020-02-25 14:06:25 -08002568 {
2569 Mutex::Autolock _atCbL(mAudioTrackCbLock);
2570 if (callback.get() != nullptr) {
jiabin18a4b1c2020-09-17 11:40:42 -07002571 mAudioTrackCallbacks.emplace(track, callback);
jiabinf6eb4c32020-02-25 14:06:25 -08002572 }
2573 }
Eric Laurent81784c32012-11-19 14:55:58 -08002574
2575 sp<EffectChain> chain = getEffectChain_l(sessionId);
2576 if (chain != 0) {
2577 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
2578 track->setMainBuffer(chain->inBuffer());
Eric Laurentd66d7a12021-07-13 13:35:32 +02002579 chain->setStrategy(getStrategyForStream(track->streamType()));
Eric Laurent81784c32012-11-19 14:55:58 -08002580 chain->incTrackCnt();
2581 }
2582
Eric Laurent05067782016-06-01 18:27:28 -07002583 if ((*flags & AUDIO_OUTPUT_FLAG_FAST) && (tid != -1)) {
Eric Laurent81784c32012-11-19 14:55:58 -08002584 pid_t callingPid = IPCThreadState::self()->getCallingPid();
2585 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
2586 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07002587 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08002588 }
2589 }
2590
2591 lStatus = NO_ERROR;
2592
2593Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07002594 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08002595 return track;
2596}
2597
Andy Hung1bc088a2018-02-09 15:57:31 -08002598template<typename T>
Andy Hung1bc088a2018-02-09 15:57:31 -08002599ssize_t AudioFlinger::PlaybackThread::Tracks<T>::remove(const sp<T> &track)
2600{
Andy Hungc0691382018-09-12 18:01:57 -07002601 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08002602 const ssize_t index = mTracks.remove(track);
2603 if (index >= 0) {
Andy Hungc0691382018-09-12 18:01:57 -07002604 if (mSaveDeletedTrackIds) {
Andy Hung1bc088a2018-02-09 15:57:31 -08002605 // We can't directly access mAudioMixer since the caller may be outside of threadLoop.
Andy Hungc0691382018-09-12 18:01:57 -07002606 // Instead, we add to mDeletedTrackIds which is solely used for mAudioMixer update,
Andy Hung1bc088a2018-02-09 15:57:31 -08002607 // to be handled when MixerThread::prepareTracks_l() next changes mAudioMixer.
Andy Hungc0691382018-09-12 18:01:57 -07002608 mDeletedTrackIds.emplace(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08002609 }
Andy Hung1bc088a2018-02-09 15:57:31 -08002610 }
2611 return index;
2612}
2613
Eric Laurent81784c32012-11-19 14:55:58 -08002614uint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const
2615{
2616 return latency;
2617}
2618
2619uint32_t AudioFlinger::PlaybackThread::latency() const
2620{
2621 Mutex::Autolock _l(mLock);
2622 return latency_l();
2623}
2624uint32_t AudioFlinger::PlaybackThread::latency_l() const
2625{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002626 uint32_t latency;
2627 if (initCheck() == NO_ERROR && mOutput->stream->getLatency(&latency) == OK) {
2628 return correctLatency_l(latency);
Eric Laurent81784c32012-11-19 14:55:58 -08002629 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002630 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002631}
2632
2633void AudioFlinger::PlaybackThread::setMasterVolume(float value)
2634{
2635 Mutex::Autolock _l(mLock);
2636 // Don't apply master volume in SW if our HAL can do it for us.
2637 if (mOutput && mOutput->audioHwDev &&
2638 mOutput->audioHwDev->canSetMasterVolume()) {
2639 mMasterVolume = 1.0;
2640 } else {
2641 mMasterVolume = value;
2642 }
2643}
2644
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01002645void AudioFlinger::PlaybackThread::setMasterBalance(float balance)
2646{
2647 mMasterBalance.store(balance);
2648}
2649
Eric Laurent81784c32012-11-19 14:55:58 -08002650void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
2651{
Eric Laurent6acd1d42017-01-04 14:23:29 -08002652 if (isDuplicating()) {
2653 return;
2654 }
Eric Laurent81784c32012-11-19 14:55:58 -08002655 Mutex::Autolock _l(mLock);
2656 // Don't apply master mute in SW if our HAL can do it for us.
2657 if (mOutput && mOutput->audioHwDev &&
2658 mOutput->audioHwDev->canSetMasterMute()) {
2659 mMasterMute = false;
2660 } else {
2661 mMasterMute = muted;
2662 }
2663}
2664
2665void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
2666{
2667 Mutex::Autolock _l(mLock);
2668 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002669 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002670}
2671
2672void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
2673{
2674 Mutex::Autolock _l(mLock);
2675 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002676 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002677}
2678
2679float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
2680{
2681 Mutex::Autolock _l(mLock);
2682 return mStreamTypes[stream].volume;
2683}
2684
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09002685void AudioFlinger::PlaybackThread::setVolumeForOutput_l(float left, float right) const
2686{
2687 mOutput->stream->setVolume(left, right);
2688}
2689
Eric Laurent81784c32012-11-19 14:55:58 -08002690// addTrack_l() must be called with ThreadBase::mLock held
2691status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
2692{
2693 status_t status = ALREADY_EXISTS;
2694
Eric Laurent81784c32012-11-19 14:55:58 -08002695 if (mActiveTracks.indexOf(track) < 0) {
2696 // the track is newly added, make sure it fills up all its
2697 // buffers before playing. This is to ensure the client will
2698 // effectively get the latency it requested.
Eric Laurent83b88082014-06-20 18:31:16 -07002699 if (track->isExternalTrack()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002700 TrackBase::track_state state = track->mState;
2701 mLock.unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002702 status = AudioSystem::startOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002703 mLock.lock();
2704 // abort track was stopped/paused while we released the lock
2705 if (state != track->mState) {
2706 if (status == NO_ERROR) {
2707 mLock.unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002708 AudioSystem::stopOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002709 mLock.lock();
2710 }
2711 return INVALID_OPERATION;
2712 }
2713 // abort if start is rejected by audio policy manager
2714 if (status != NO_ERROR) {
2715 return PERMISSION_DENIED;
2716 }
2717#ifdef ADD_BATTERY_DATA
2718 // to track the speaker usage
2719 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
2720#endif
Eric Laurent09f1ed22019-04-24 17:45:17 -07002721 sendIoConfigEvent_l(AUDIO_CLIENT_STARTED, track->creatorPid(), track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002722 }
2723
Eric Laurent51716182016-02-29 18:00:56 -08002724 // set retry count for buffer fill
2725 if (track->isOffloaded()) {
Eric Laurente93cc032016-05-05 10:15:10 -07002726 if (track->isStopping_1()) {
2727 track->mRetryCount = kMaxTrackStopRetriesOffload;
2728 } else {
2729 track->mRetryCount = kMaxTrackStartupRetriesOffload;
2730 }
2731 track->mFillingUpStatus = mStandby ? Track::FS_FILLING : Track::FS_FILLED;
Eric Laurent51716182016-02-29 18:00:56 -08002732 } else {
2733 track->mRetryCount = kMaxTrackStartupRetries;
Eric Laurente93cc032016-05-05 10:15:10 -07002734 track->mFillingUpStatus =
2735 track->sharedBuffer() != 0 ? Track::FS_FILLED : Track::FS_FILLING;
Eric Laurent51716182016-02-29 18:00:56 -08002736 }
2737
jiabineb3bda02020-06-30 14:07:03 -07002738 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2739 if (mHapticChannelMask != AUDIO_CHANNEL_NONE
2740 && ((track->channelMask() & AUDIO_CHANNEL_HAPTIC_ALL) != AUDIO_CHANNEL_NONE
2741 || (chain != nullptr && chain->containsHapticGeneratingEffect_l()))) {
jiabin57303cc2018-12-18 15:45:57 -08002742 // Unlock due to VibratorService will lock for this call and will
2743 // call Tracks.mute/unmute which also require thread's lock.
2744 mLock.unlock();
2745 const int intensity = AudioFlinger::onExternalVibrationStart(
2746 track->getExternalVibration());
Lais Andradebc3f37a2021-07-02 00:13:19 +01002747 std::optional<media::AudioVibratorInfo> vibratorInfo;
2748 {
2749 // TODO(b/184194780): Use the vibrator information from the vibrator that will be
2750 // used to play this track.
2751 Mutex::Autolock _l(mAudioFlinger->mLock);
2752 vibratorInfo = std::move(mAudioFlinger->getDefaultVibratorInfo_l());
2753 }
jiabin57303cc2018-12-18 15:45:57 -08002754 mLock.lock();
jiabine70bc7f2020-06-30 22:07:55 -07002755 track->setHapticIntensity(static_cast<os::HapticScale>(intensity));
Lais Andradebc3f37a2021-07-02 00:13:19 +01002756 if (vibratorInfo) {
2757 track->setHapticMaxAmplitude(vibratorInfo->maxAmplitude);
2758 }
2759
jiabin57303cc2018-12-18 15:45:57 -08002760 // Haptic playback should be enabled by vibrator service.
2761 if (track->getHapticPlaybackEnabled()) {
2762 // Disable haptic playback of all active track to ensure only
2763 // one track playing haptic if current track should play haptic.
2764 for (const auto &t : mActiveTracks) {
2765 t->setHapticPlaybackEnabled(false);
2766 }
jiabin245cdd92018-12-07 17:55:15 -08002767 }
jiabine70bc7f2020-06-30 22:07:55 -07002768
2769 // Set haptic intensity for effect
2770 if (chain != nullptr) {
2771 chain->setHapticIntensity_l(track->id(), intensity);
2772 }
jiabin245cdd92018-12-07 17:55:15 -08002773 }
2774
Eric Laurent81784c32012-11-19 14:55:58 -08002775 track->mResetDone = false;
Andy Hung59de4262021-06-14 10:53:54 -07002776 track->resetPresentationComplete();
Eric Laurent81784c32012-11-19 14:55:58 -08002777 mActiveTracks.add(track);
Eric Laurentd0107bc2013-06-11 14:38:48 -07002778 if (chain != 0) {
2779 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
2780 track->sessionId());
2781 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08002782 }
2783
Andy Hungc2b11cb2020-04-22 09:04:01 -07002784 track->logBeginInterval(patchSinksToString(&mPatch)); // log to MediaMetrics
Eric Laurent81784c32012-11-19 14:55:58 -08002785 status = NO_ERROR;
2786 }
2787
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08002788 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002789 return status;
2790}
2791
Eric Laurentbfb1b832013-01-07 09:53:42 -08002792bool AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002793{
Eric Laurentbfb1b832013-01-07 09:53:42 -08002794 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08002795 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002796 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
2797 track->mState = TrackBase::STOPPED;
2798 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08002799 removeTrack_l(track);
Eric Laurentab5cdba2014-06-09 17:22:27 -07002800 } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002801 track->mState = TrackBase::STOPPING_1;
Eric Laurent81784c32012-11-19 14:55:58 -08002802 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002803
2804 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08002805}
2806
2807void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
2808{
2809 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Andy Hung2148bf02016-11-28 19:01:02 -08002810
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002811 String8 result;
2812 track->appendDump(result, false /* active */);
2813 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.string());
Andy Hung2148bf02016-11-28 19:01:02 -08002814
Eric Laurent81784c32012-11-19 14:55:58 -08002815 mTracks.remove(track);
jiabin18a4b1c2020-09-17 11:40:42 -07002816 {
2817 Mutex::Autolock _atCbL(mAudioTrackCbLock);
2818 mAudioTrackCallbacks.erase(track);
2819 }
Eric Laurent81784c32012-11-19 14:55:58 -08002820 if (track->isFastTrack()) {
2821 int index = track->mFastIndex;
Glenn Kastendc2c50b2016-04-21 08:13:14 -07002822 ALOG_ASSERT(0 < index && index < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08002823 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
2824 mFastTrackAvailMask |= 1 << index;
2825 // redundant as track is about to be destroyed, for dumpsys only
2826 track->mFastIndex = -1;
2827 }
2828 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2829 if (chain != 0) {
2830 chain->decTrackCnt();
2831 }
2832}
2833
2834String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
2835{
Eric Laurent81784c32012-11-19 14:55:58 -08002836 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002837 String8 out_s8;
2838 if (initCheck() == NO_ERROR && mOutput->stream->getParameters(keys, &out_s8) == OK) {
2839 return out_s8;
Eric Laurent81784c32012-11-19 14:55:58 -08002840 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002841 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08002842}
2843
Mikhail Naganovac917ac2018-11-28 14:03:52 -08002844status_t AudioFlinger::DirectOutputThread::selectPresentation(int presentationId, int programId) {
2845 Mutex::Autolock _l(mLock);
Jasmine Chaeaa10e42021-05-11 10:11:14 +08002846 if (!isStreamInitialized()) {
Mikhail Naganovac917ac2018-11-28 14:03:52 -08002847 return NO_INIT;
2848 }
2849 return mOutput->stream->selectPresentation(presentationId, programId);
2850}
2851
Mikhail Naganov88536df2021-07-26 17:30:29 -07002852void AudioFlinger::PlaybackThread::ioConfigChanged(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -07002853 audio_port_handle_t portId) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002854 ALOGV("PlaybackThread::ioConfigChanged, thread %p, event %d", this, event);
Mikhail Naganov88536df2021-07-26 17:30:29 -07002855 sp<AudioIoDescriptor> desc;
2856 const struct audio_patch patch = isMsdDevice() ? mDownStreamPatch : mPatch;
Eric Laurent81784c32012-11-19 14:55:58 -08002857 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002858 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07002859 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07002860 case AUDIO_OUTPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07002861 desc = sp<AudioIoDescriptor>::make(mId, patch, false /*isInput*/,
2862 mSampleRate, mFormat, mChannelMask,
2863 // FIXME AudioFlinger::frameCount(audio_io_handle_t) instead of mNormalFrameCount?
2864 mNormalFrameCount, mFrameCount, latency_l());
Eric Laurent81784c32012-11-19 14:55:58 -08002865 break;
Eric Laurent09f1ed22019-04-24 17:45:17 -07002866 case AUDIO_CLIENT_STARTED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07002867 desc = sp<AudioIoDescriptor>::make(mId, patch, portId);
Eric Laurent09f1ed22019-04-24 17:45:17 -07002868 break;
Eric Laurent73e26b62015-04-27 16:55:58 -07002869 case AUDIO_OUTPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08002870 default:
Mikhail Naganov88536df2021-07-26 17:30:29 -07002871 desc = sp<AudioIoDescriptor>::make(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08002872 break;
2873 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002874 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08002875}
2876
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002877void AudioFlinger::PlaybackThread::onWriteReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002878{
Eric Laurent3b4529e2013-09-05 18:09:19 -07002879 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002880}
2881
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002882void AudioFlinger::PlaybackThread::onDrainReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002883{
Eric Laurent3b4529e2013-09-05 18:09:19 -07002884 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002885}
2886
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002887void AudioFlinger::PlaybackThread::onError()
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002888{
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002889 mCallbackThread->setAsyncError();
2890}
2891
jiabinf6eb4c32020-02-25 14:06:25 -08002892void AudioFlinger::PlaybackThread::onCodecFormatChanged(
2893 const std::basic_string<uint8_t>& metadataBs)
2894{
2895 std::thread([this, metadataBs]() {
2896 audio_utils::metadata::Data metadata =
2897 audio_utils::metadata::dataFromByteString(metadataBs);
2898 if (metadata.empty()) {
2899 ALOGW("Can not transform the buffer to audio metadata, %s, %d",
2900 reinterpret_cast<char*>(const_cast<uint8_t*>(metadataBs.data())),
2901 (int)metadataBs.size());
2902 return;
2903 }
2904
2905 audio_utils::metadata::ByteString metaDataStr =
2906 audio_utils::metadata::byteStringFromData(metadata);
2907 std::vector metadataVec(metaDataStr.begin(), metaDataStr.end());
2908 Mutex::Autolock _l(mAudioTrackCbLock);
jiabin18a4b1c2020-09-17 11:40:42 -07002909 for (const auto& callbackPair : mAudioTrackCallbacks) {
2910 callbackPair.second->onCodecFormatChanged(metadataVec);
jiabinf6eb4c32020-02-25 14:06:25 -08002911 }
2912 }).detach();
2913}
2914
Eric Laurent3b4529e2013-09-05 18:09:19 -07002915void AudioFlinger::PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002916{
2917 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002918 // reject out of sequence requests
2919 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
2920 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002921 mWaitWorkCV.signal();
2922 }
2923}
2924
Eric Laurent3b4529e2013-09-05 18:09:19 -07002925void AudioFlinger::PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002926{
2927 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002928 // reject out of sequence requests
2929 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
Andy Hungf3234512018-07-03 14:51:47 -07002930 // Register discontinuity when HW drain is completed because that can cause
2931 // the timestamp frame position to reset to 0 for direct and offload threads.
2932 // (Out of sequence requests are ignored, since the discontinuity would be handled
2933 // elsewhere, e.g. in flush).
Dean Wheatley12473e92021-03-18 23:00:55 +11002934 mTimestampVerifier.discontinuity(mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002935 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002936 mWaitWorkCV.signal();
2937 }
2938}
2939
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002940void AudioFlinger::PlaybackThread::readOutputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08002941{
Glenn Kastenadad3d72014-02-21 14:51:43 -08002942 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Mikhail Naganov560637e2021-03-31 22:40:13 +00002943 const audio_config_base_t audioConfig = mOutput->getAudioProperties();
2944 mSampleRate = audioConfig.sample_rate;
2945 mChannelMask = audioConfig.channel_mask;
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002946 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002947 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002948 }
Eric Laurentb3f315a2021-07-13 15:09:05 +02002949 if (hasMixer() && !isValidPcmSinkChannelMask(mChannelMask)) {
Andy Hung9a592762014-07-21 21:56:01 -07002950 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output",
2951 mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002952 }
Eric Laurentf1f22e72021-07-13 14:04:14 +02002953
2954 if (mMixerChannelMask == AUDIO_CHANNEL_NONE) {
2955 mMixerChannelMask = mChannelMask;
2956 }
2957
Andy Hunge5412692014-05-16 11:25:07 -07002958 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01002959 mBalance.setChannelMask(mChannelMask);
Phil Burkca5e6142015-07-14 09:42:29 -07002960
Eric Laurentf1f22e72021-07-13 14:04:14 +02002961 uint32_t mixerChannelCount = audio_channel_count_from_out_mask(mMixerChannelMask);
2962
Phil Burkca5e6142015-07-14 09:42:29 -07002963 // Get actual HAL format.
Mikhail Naganov560637e2021-03-31 22:40:13 +00002964 status_t result = mOutput->stream->getAudioProperties(nullptr, nullptr, &mHALFormat);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002965 LOG_ALWAYS_FATAL_IF(result != OK, "Error when retrieving output stream format: %d", result);
Phil Burkca5e6142015-07-14 09:42:29 -07002966 // Get format from the shim, which will be different than the HAL format
2967 // if playing compressed audio over HDMI passthrough.
Mikhail Naganov560637e2021-03-31 22:40:13 +00002968 mFormat = audioConfig.format;
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002969 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002970 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002971 }
Eric Laurentb3f315a2021-07-13 15:09:05 +02002972 if (hasMixer() && !isValidPcmSinkFormat(mFormat)) {
Andy Hung6146c082014-03-18 11:56:15 -07002973 LOG_FATAL("HAL format %#x not supported for mixed output",
2974 mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002975 }
Phil Burk062e67a2015-02-11 13:40:50 -08002976 mFrameSize = mOutput->getFrameSize();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002977 result = mOutput->stream->getBufferSize(&mBufferSize);
2978 LOG_ALWAYS_FATAL_IF(result != OK,
2979 "Error when retrieving output stream buffer size: %d", result);
Glenn Kasten70949c42013-08-06 07:40:12 -07002980 mFrameCount = mBufferSize / mFrameSize;
Eric Laurentb3f315a2021-07-13 15:09:05 +02002981 if (hasMixer() && (mFrameCount & 15)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002982 ALOGW("HAL output buffer size is %zu frames but AudioMixer requires multiples of 16 frames",
Eric Laurent81784c32012-11-19 14:55:58 -08002983 mFrameCount);
2984 }
2985
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002986 if (mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING) {
2987 if (mOutput->stream->setCallback(this) == OK) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002988 mUseAsyncWrite = true;
Eric Laurent4de95592013-09-26 15:28:21 -07002989 mCallbackThread = new AudioFlinger::AsyncCallbackThread(this);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002990 }
2991 }
2992
Eric Laurentd1f69b02014-12-15 14:33:13 -08002993 mHwSupportsPause = false;
2994 if (mOutput->flags & AUDIO_OUTPUT_FLAG_DIRECT) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002995 bool supportsPause = false, supportsResume = false;
2996 if (mOutput->stream->supportsPauseAndResume(&supportsPause, &supportsResume) == OK) {
2997 if (supportsPause && supportsResume) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08002998 mHwSupportsPause = true;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002999 } else if (supportsPause) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08003000 ALOGW("direct output implements pause but not resume");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003001 } else if (supportsResume) {
3002 ALOGW("direct output implements resume but not pause");
Eric Laurentd1f69b02014-12-15 14:33:13 -08003003 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08003004 }
3005 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07003006 if (!mHwSupportsPause && mOutput->flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) {
3007 LOG_ALWAYS_FATAL("HW_AV_SYNC requested but HAL does not implement pause and resume");
3008 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08003009
Andy Hungfbfc3952015-01-15 13:33:51 -08003010 if (mType == DUPLICATING && mMixerBufferEnabled && mEffectBufferEnabled) {
3011 // For best precision, we use float instead of the associated output
3012 // device format (typically PCM 16 bit).
3013
3014 mFormat = AUDIO_FORMAT_PCM_FLOAT;
3015 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
3016 mBufferSize = mFrameSize * mFrameCount;
3017
3018 // TODO: We currently use the associated output device channel mask and sample rate.
3019 // (1) Perhaps use the ORed channel mask of all downstream MixerThreads
3020 // (if a valid mask) to avoid premature downmix.
3021 // (2) Perhaps use the maximum sample rate of all downstream MixerThreads
3022 // instead of the output device sample rate to avoid loss of high frequency information.
3023 // This may need to be updated as MixerThread/OutputTracks are added and not here.
3024 }
3025
Andy Hung09a50072014-02-27 14:30:47 -08003026 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08003027 double multiplier = 1.0;
Andy Hungd3639922022-04-28 18:00:49 -07003028 // Note: mType == SPATIALIZER does not support FastMixer.
Eric Laurent81784c32012-11-19 14:55:58 -08003029 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
3030 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08003031 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
3032 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Haynes Mathew George227a14b2016-05-09 12:45:48 -07003033
Eric Laurent81784c32012-11-19 14:55:58 -08003034 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
3035 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
3036 maxNormalFrameCount = maxNormalFrameCount & ~15;
3037 if (maxNormalFrameCount < minNormalFrameCount) {
3038 maxNormalFrameCount = minNormalFrameCount;
3039 }
3040 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
3041 if (multiplier <= 1.0) {
3042 multiplier = 1.0;
3043 } else if (multiplier <= 2.0) {
3044 if (2 * mFrameCount <= maxNormalFrameCount) {
3045 multiplier = 2.0;
3046 } else {
3047 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
3048 }
3049 } else {
Haynes Mathew George227a14b2016-05-09 12:45:48 -07003050 multiplier = floor(multiplier);
Eric Laurent81784c32012-11-19 14:55:58 -08003051 }
3052 }
3053 mNormalFrameCount = multiplier * mFrameCount;
3054 // round up to nearest 16 frames to satisfy AudioMixer
Eric Laurentb3f315a2021-07-13 15:09:05 +02003055 if (hasMixer()) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07003056 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
3057 }
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003058 ALOGI("HAL output buffer size %zu frames, normal sink buffer size %zu frames", mFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08003059 mNormalFrameCount);
3060
Andy Hung08fb1742015-05-31 23:22:10 -07003061 // Check if we want to throttle the processing to no more than 2x normal rate
3062 mThreadThrottle = property_get_bool("af.thread.throttle", true /* default_value */);
Andy Hung40eb1a12015-06-18 13:42:02 -07003063 mThreadThrottleTimeMs = 0;
3064 mThreadThrottleEndMs = 0;
Andy Hung08fb1742015-05-31 23:22:10 -07003065 mHalfBufferMs = mNormalFrameCount * 1000 / (2 * mSampleRate);
3066
Andy Hung010a1a12014-03-13 13:57:33 -07003067 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
3068 // Originally this was int16_t[] array, need to remove legacy implications.
3069 free(mSinkBuffer);
3070 mSinkBuffer = NULL;
Eric Laurent39095982021-08-24 18:29:27 +02003071
Andy Hung5b10a202014-03-13 13:59:29 -07003072 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
3073 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
3074 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07003075 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08003076
Andy Hung69aed5f2014-02-25 17:24:40 -08003077 // We resize the mMixerBuffer according to the requirements of the sink buffer which
3078 // drives the output.
3079 free(mMixerBuffer);
3080 mMixerBuffer = NULL;
3081 if (mMixerBufferEnabled) {
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01003082 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // no longer valid: AUDIO_FORMAT_PCM_16_BIT.
Eric Laurentf1f22e72021-07-13 14:04:14 +02003083 mMixerBufferSize = mNormalFrameCount * mixerChannelCount
Andy Hung69aed5f2014-02-25 17:24:40 -08003084 * audio_bytes_per_sample(mMixerBufferFormat);
3085 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
3086 }
Andy Hung98ef9782014-03-04 14:46:50 -08003087 free(mEffectBuffer);
3088 mEffectBuffer = NULL;
3089 if (mEffectBufferEnabled) {
rago94a1ee82017-07-21 15:11:02 -07003090 mEffectBufferFormat = EFFECT_BUFFER_FORMAT;
Eric Laurentf1f22e72021-07-13 14:04:14 +02003091 mEffectBufferSize = mNormalFrameCount * mixerChannelCount
Andy Hung98ef9782014-03-04 14:46:50 -08003092 * audio_bytes_per_sample(mEffectBufferFormat);
3093 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
3094 }
Andy Hung69aed5f2014-02-25 17:24:40 -08003095
Eric Laurentb62d0362021-10-26 17:40:18 +02003096 if (mType == SPATIALIZER) {
3097 free(mPostSpatializerBuffer);
3098 mPostSpatializerBuffer = nullptr;
3099 mPostSpatializerBufferSize = mNormalFrameCount * mChannelCount
3100 * audio_bytes_per_sample(mEffectBufferFormat);
3101 (void)posix_memalign(&mPostSpatializerBuffer, 32, mPostSpatializerBufferSize);
3102 }
3103
Mikhail Naganov55773032020-10-01 15:08:13 -07003104 mHapticChannelMask = static_cast<audio_channel_mask_t>(mChannelMask & AUDIO_CHANNEL_HAPTIC_ALL);
3105 mChannelMask = static_cast<audio_channel_mask_t>(mChannelMask & ~mHapticChannelMask);
jiabin245cdd92018-12-07 17:55:15 -08003106 mHapticChannelCount = audio_channel_count_from_out_mask(mHapticChannelMask);
3107 mChannelCount -= mHapticChannelCount;
Eric Laurentf1f22e72021-07-13 14:04:14 +02003108 mMixerChannelMask = static_cast<audio_channel_mask_t>(mMixerChannelMask & ~mHapticChannelMask);
jiabin245cdd92018-12-07 17:55:15 -08003109
Eric Laurent81784c32012-11-19 14:55:58 -08003110 // force reconfiguration of effect chains and engines to take new buffer size and audio
3111 // parameters into account
Glenn Kastendeca2ae2014-02-07 10:25:56 -08003112 // Note that mLock is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08003113 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
3114 // matter.
3115 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
3116 Vector< sp<EffectChain> > effectChains = mEffectChains;
3117 for (size_t i = 0; i < effectChains.size(); i ++) {
Eric Laurent6c796322019-04-09 14:13:17 -07003118 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(),
3119 this/* srcThread */, this/* dstThread */);
Eric Laurent81784c32012-11-19 14:55:58 -08003120 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08003121
George Burgess IV5e4d86f2020-02-18 12:55:36 -08003122 audio_output_flags_t flags = mOutput->flags;
Andy Hungcf10d742020-04-28 15:38:24 -07003123 mediametrics::LogItem item(mThreadMetrics.getMetricsId()); // TODO: method in ThreadMetrics?
Andy Hungb68f5eb2019-12-03 16:49:17 -08003124 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
3125 .set(AMEDIAMETRICS_PROP_ENCODING, formatToString(mFormat).c_str())
3126 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
3127 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
3128 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
3129 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mNormalFrameCount)
3130 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
3131 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELMASK,
3132 (int32_t)mHapticChannelMask)
3133 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELCOUNT,
3134 (int32_t)mHapticChannelCount)
3135 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_ENCODING,
3136 formatToString(mHALFormat).c_str())
3137 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_FRAMECOUNT,
3138 (int32_t)mFrameCount) // sic - added HAL
3139 ;
3140 uint32_t latencyMs;
3141 if (mOutput->stream->getLatency(&latencyMs) == NO_ERROR) {
3142 item.set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_LATENCYMS, (double)latencyMs);
3143 }
3144 item.record();
Eric Laurent81784c32012-11-19 14:55:58 -08003145}
3146
Kevin Rocard069c2712018-03-29 19:09:14 -07003147void AudioFlinger::PlaybackThread::updateMetadata_l()
3148{
Jasmine Chaeaa10e42021-05-11 10:11:14 +08003149 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
Kevin Rocard12381092018-04-11 09:19:59 -07003150 return; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -07003151 }
3152 StreamOutHalInterface::SourceMetadata metadata;
Kevin Rocard12381092018-04-11 09:19:59 -07003153 auto backInserter = std::back_inserter(metadata.tracks);
Kevin Rocard069c2712018-03-29 19:09:14 -07003154 for (const sp<Track> &track : mActiveTracks) {
3155 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurent49e39282022-06-24 18:42:45 +02003156 track->copyMetadataTo(backInserter);
Kevin Rocard069c2712018-03-29 19:09:14 -07003157 }
Kevin Rocard12381092018-04-11 09:19:59 -07003158 sendMetadataToBackend_l(metadata);
Kevin Rocard80ee2722018-04-11 15:53:48 +00003159}
Kevin Rocardc86a7f72018-04-03 09:00:09 -07003160
Kevin Rocard12381092018-04-11 09:19:59 -07003161void AudioFlinger::PlaybackThread::sendMetadataToBackend_l(
3162 const StreamOutHalInterface::SourceMetadata& metadata)
3163{
3164 mOutput->stream->updateSourceMetadata(metadata);
3165};
3166
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003167status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
Eric Laurent81784c32012-11-19 14:55:58 -08003168{
3169 if (halFrames == NULL || dspFrames == NULL) {
3170 return BAD_VALUE;
3171 }
3172 Mutex::Autolock _l(mLock);
3173 if (initCheck() != NO_ERROR) {
3174 return INVALID_OPERATION;
3175 }
Andy Hung818e7a32016-02-16 18:08:07 -08003176 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08003177 *halFrames = framesWritten;
3178
3179 if (isSuspended()) {
3180 // return an estimation of rendered frames when the output is suspended
3181 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08003182 *dspFrames = (uint32_t)
3183 (framesWritten >= (int64_t)latencyFrames ? framesWritten - latencyFrames : 0);
Eric Laurent81784c32012-11-19 14:55:58 -08003184 return NO_ERROR;
3185 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003186 status_t status;
3187 uint32_t frames;
Phil Burk062e67a2015-02-11 13:40:50 -08003188 status = mOutput->getRenderPosition(&frames);
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003189 *dspFrames = (size_t)frames;
3190 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08003191 }
3192}
3193
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08003194product_strategy_t AudioFlinger::PlaybackThread::getStrategyForSession_l(audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08003195{
3196 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
3197 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
3198 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02003199 return getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurent81784c32012-11-19 14:55:58 -08003200 }
3201 for (size_t i = 0; i < mTracks.size(); i++) {
3202 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08003203 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02003204 return getStrategyForStream(track->streamType());
Eric Laurent81784c32012-11-19 14:55:58 -08003205 }
3206 }
Eric Laurentd66d7a12021-07-13 13:35:32 +02003207 return getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurent81784c32012-11-19 14:55:58 -08003208}
3209
3210
Phil Burk062e67a2015-02-11 13:40:50 -08003211AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurent81784c32012-11-19 14:55:58 -08003212{
3213 Mutex::Autolock _l(mLock);
3214 return mOutput;
3215}
3216
Phil Burk062e67a2015-02-11 13:40:50 -08003217AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
Eric Laurent81784c32012-11-19 14:55:58 -08003218{
3219 Mutex::Autolock _l(mLock);
3220 AudioStreamOut *output = mOutput;
3221 mOutput = NULL;
3222 // FIXME FastMixer might also have a raw ptr to mOutputSink;
3223 // must push a NULL and wait for ack
3224 mOutputSink.clear();
3225 mPipeSink.clear();
3226 mNormalSink.clear();
3227 return output;
3228}
3229
3230// this method must always be called either with ThreadBase mLock held or inside the thread loop
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003231sp<StreamHalInterface> AudioFlinger::PlaybackThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08003232{
3233 if (mOutput == NULL) {
3234 return NULL;
3235 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003236 return mOutput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08003237}
3238
3239uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
3240{
3241 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
3242}
3243
3244status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
3245{
3246 if (!isValidSyncEvent(event)) {
3247 return BAD_VALUE;
3248 }
3249
3250 Mutex::Autolock _l(mLock);
3251
3252 for (size_t i = 0; i < mTracks.size(); ++i) {
3253 sp<Track> track = mTracks[i];
3254 if (event->triggerSession() == track->sessionId()) {
3255 (void) track->setSyncEvent(event);
3256 return NO_ERROR;
3257 }
3258 }
3259
3260 return NAME_NOT_FOUND;
3261}
3262
3263bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
3264{
3265 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
3266}
3267
3268void AudioFlinger::PlaybackThread::threadLoop_removeTracks(
3269 const Vector< sp<Track> >& tracksToRemove)
3270{
Andy Hungfe726a62018-09-27 15:17:25 -07003271 // Miscellaneous track cleanup when removed from the active list,
3272 // called without Thread lock but synchronized with threadLoop processing.
Eric Laurentbfb1b832013-01-07 09:53:42 -08003273#ifdef ADD_BATTERY_DATA
Andy Hungfe726a62018-09-27 15:17:25 -07003274 for (const auto& track : tracksToRemove) {
3275 if (track->isExternalTrack()) {
3276 // to track the speaker usage
3277 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Eric Laurent81784c32012-11-19 14:55:58 -08003278 }
3279 }
Andy Hungfe726a62018-09-27 15:17:25 -07003280#else
3281 (void)tracksToRemove; // suppress unused warning
3282#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003283}
3284
3285void AudioFlinger::PlaybackThread::checkSilentMode_l()
3286{
3287 if (!mMasterMute) {
3288 char value[PROPERTY_VALUE_MAX];
jiabin0a957d32020-04-29 10:56:20 -07003289 if (mOutDeviceTypeAddrs.empty()) {
3290 ALOGD("ro.audio.silent is ignored since no output device is set");
3291 return;
3292 }
jiabinc52b1ff2019-10-31 17:20:42 -07003293 if (isSingleDeviceType(outDeviceTypes(), AUDIO_DEVICE_OUT_REMOTE_SUBMIX)) {
Jean-Michel Trivi32f37c22016-03-31 16:00:32 -07003294 ALOGD("ro.audio.silent will be ignored for threads on AUDIO_DEVICE_OUT_REMOTE_SUBMIX");
3295 return;
3296 }
Eric Laurent81784c32012-11-19 14:55:58 -08003297 if (property_get("ro.audio.silent", value, "0") > 0) {
3298 char *endptr;
3299 unsigned long ul = strtoul(value, &endptr, 0);
3300 if (*endptr == '\0' && ul != 0) {
3301 ALOGD("Silence is golden");
3302 // The setprop command will not allow a property to be changed after
3303 // the first time it is set, so we don't have to worry about un-muting.
3304 setMasterMute_l(true);
3305 }
3306 }
3307 }
3308}
3309
3310// shared by MIXER and DIRECT, overridden by DUPLICATING
Eric Laurentbfb1b832013-01-07 09:53:42 -08003311ssize_t AudioFlinger::PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08003312{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07003313 LOG_HIST_TS();
Eric Laurent81784c32012-11-19 14:55:58 -08003314 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003315 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07003316 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08003317
3318 // If an NBAIO sink is present, use it to write the normal mixer's submix
3319 if (mNormalSink != 0) {
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003320
Andy Hung010a1a12014-03-13 13:57:33 -07003321 const size_t count = mBytesRemaining / mFrameSize;
3322
Simon Wilson2d590962012-11-29 15:18:50 -08003323 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08003324 // update the setpoint when AudioFlinger::mScreenState changes
3325 uint32_t screenState = AudioFlinger::mScreenState;
3326 if (screenState != mScreenState) {
3327 mScreenState = screenState;
3328 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
3329 if (pipe != NULL) {
3330 pipe->setAvgFrames((mScreenState & 1) ?
3331 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
3332 }
3333 }
Andy Hung010a1a12014-03-13 13:57:33 -07003334 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08003335 ATRACE_END();
Eric Laurent81784c32012-11-19 14:55:58 -08003336 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07003337 bytesWritten = framesWritten * mFrameSize;
Andy Hung8946a282018-04-19 20:04:56 -07003338#ifdef TEE_SINK
3339 mTee.write((char *)mSinkBuffer + offset, framesWritten);
3340#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003341 } else {
3342 bytesWritten = framesWritten;
3343 }
3344 // otherwise use the HAL / AudioStreamOut directly
3345 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003346 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07003347
Eric Laurentbfb1b832013-01-07 09:53:42 -08003348 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003349 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
3350 mWriteAckSequence += 2;
3351 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003352 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003353 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003354 }
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07003355 ATRACE_BEGIN("write");
Glenn Kasten767094d2013-08-23 13:51:43 -07003356 // FIXME We should have an implementation of timestamps for direct output threads.
3357 // They are used e.g for multichannel PCM playback over HDMI.
Phil Burk062e67a2015-02-11 13:40:50 -08003358 bytesWritten = mOutput->write((char *)mSinkBuffer + offset, mBytesRemaining);
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07003359 ATRACE_END();
Eric Laurent51716182016-02-29 18:00:56 -08003360
Eric Laurentbfb1b832013-01-07 09:53:42 -08003361 if (mUseAsyncWrite &&
3362 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
3363 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07003364 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003365 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003366 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003367 }
Eric Laurent81784c32012-11-19 14:55:58 -08003368 }
3369
Eric Laurent81784c32012-11-19 14:55:58 -08003370 mNumWrites++;
3371 mInWrite = false;
Andy Hungcf10d742020-04-28 15:38:24 -07003372 if (mStandby) {
3373 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07003374 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -07003375 mStandby = false;
3376 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003377 return bytesWritten;
3378}
3379
3380void AudioFlinger::PlaybackThread::threadLoop_drain()
3381{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003382 bool supportsDrain = false;
3383 if (mOutput->stream->supportsDrain(&supportsDrain) == OK && supportsDrain) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003384 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
3385 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003386 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
3387 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003388 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003389 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003390 }
Mikhail Naganovcbc8f612016-10-11 18:05:13 -07003391 status_t result = mOutput->stream->drain(mMixerStatus == MIXER_DRAIN_TRACK);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003392 ALOGE_IF(result != OK, "Error when draining stream: %d", result);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003393 }
3394}
3395
3396void AudioFlinger::PlaybackThread::threadLoop_exit()
3397{
Eric Laurent275e8e92014-11-30 15:14:47 -08003398 {
3399 Mutex::Autolock _l(mLock);
3400 for (size_t i = 0; i < mTracks.size(); i++) {
3401 sp<Track> track = mTracks[i];
3402 track->invalidate();
3403 }
Andy Hungdae27702016-10-31 14:01:16 -07003404 // Clear ActiveTracks to update BatteryNotifier in case active tracks remain.
3405 // After we exit there are no more track changes sent to BatteryNotifier
3406 // because that requires an active threadLoop.
3407 // TODO: should we decActiveTrackCnt() of the cleared track effect chain?
3408 mActiveTracks.clear();
Eric Laurent275e8e92014-11-30 15:14:47 -08003409 }
Eric Laurent81784c32012-11-19 14:55:58 -08003410}
3411
3412/*
3413The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08003414 - mSinkBufferSize from frame count * frame size
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003415 - mActiveSleepTimeUs from activeSleepTimeUs()
3416 - mIdleSleepTimeUs from idleSleepTimeUs()
Eric Laurent42537be2016-01-08 17:16:42 -08003417 - mStandbyDelayNs from mActiveSleepTimeUs (DIRECT only) or forced to at least
3418 kDefaultStandbyTimeInNsecs when connected to an A2DP device.
Eric Laurent81784c32012-11-19 14:55:58 -08003419 - maxPeriod from frame count and sample rate (MIXER only)
3420
3421The parameters that affect these derived values are:
3422 - frame count
3423 - frame size
3424 - sample rate
3425 - device type: A2DP or not
3426 - device latency
3427 - format: PCM or not
3428 - active sleep time
3429 - idle sleep time
3430*/
3431
3432void AudioFlinger::PlaybackThread::cacheParameters_l()
3433{
Andy Hung25c2dac2014-02-27 14:56:00 -08003434 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003435 mActiveSleepTimeUs = activeSleepTimeUs();
3436 mIdleSleepTimeUs = idleSleepTimeUs();
Eric Laurent42537be2016-01-08 17:16:42 -08003437
3438 // make sure standby delay is not too short when connected to an A2DP sink to avoid
3439 // truncating audio when going to standby.
3440 mStandbyDelayNs = AudioFlinger::mStandbyTimeInNsecs;
jiabinc52b1ff2019-10-31 17:20:42 -07003441 if (!Intersection(outDeviceTypes(), getAudioDeviceOutAllA2dpSet()).empty()) {
Eric Laurent42537be2016-01-08 17:16:42 -08003442 if (mStandbyDelayNs < kDefaultStandbyTimeInNsecs) {
3443 mStandbyDelayNs = kDefaultStandbyTimeInNsecs;
3444 }
3445 }
Eric Laurent81784c32012-11-19 14:55:58 -08003446}
3447
Eric Laurent13084622016-05-17 10:51:49 -07003448bool AudioFlinger::PlaybackThread::invalidateTracks_l(audio_stream_type_t streamType)
Eric Laurent81784c32012-11-19 14:55:58 -08003449{
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003450 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %zu",
Eric Laurent81784c32012-11-19 14:55:58 -08003451 this, streamType, mTracks.size());
Eric Laurent13084622016-05-17 10:51:49 -07003452 bool trackMatch = false;
Eric Laurent81784c32012-11-19 14:55:58 -08003453 size_t size = mTracks.size();
3454 for (size_t i = 0; i < size; i++) {
3455 sp<Track> t = mTracks[i];
Eric Laurentd60560a2015-04-10 11:31:20 -07003456 if (t->streamType() == streamType && t->isExternalTrack()) {
Glenn Kasten5736c352012-12-04 12:12:34 -08003457 t->invalidate();
Eric Laurent13084622016-05-17 10:51:49 -07003458 trackMatch = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003459 }
3460 }
Eric Laurent13084622016-05-17 10:51:49 -07003461 return trackMatch;
Eric Laurent81784c32012-11-19 14:55:58 -08003462}
3463
Haynes Mathew George05317d22016-05-03 16:34:26 -07003464void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
3465{
3466 Mutex::Autolock _l(mLock);
3467 invalidateTracks_l(streamType);
3468}
3469
jiabinf042b9b2021-05-07 23:46:28 +00003470// getTrackById_l must be called with holding thread lock
3471AudioFlinger::PlaybackThread::Track* AudioFlinger::PlaybackThread::getTrackById_l(
3472 audio_port_handle_t trackPortId) {
3473 for (size_t i = 0; i < mTracks.size(); i++) {
3474 if (mTracks[i]->portId() == trackPortId) {
3475 return mTracks[i].get();
3476 }
3477 }
3478 return nullptr;
3479}
3480
Eric Laurent81784c32012-11-19 14:55:58 -08003481status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
3482{
Glenn Kastend848eb42016-03-08 13:42:11 -08003483 audio_session_t session = chain->sessionId();
Mikhail Naganov022b9952017-01-04 16:36:51 -08003484 sp<EffectBufferHalInterface> halInBuffer, halOutBuffer;
Eric Laurentb62d0362021-10-26 17:40:18 +02003485 effect_buffer_t *buffer = nullptr; // only used for non global sessions
3486
Andy Hungd3639922022-04-28 18:00:49 -07003487 if (mType == SPATIALIZER) {
Eric Laurentb62d0362021-10-26 17:40:18 +02003488 if (!audio_is_global_session(session)) {
3489 // player sessions on a spatializer output will use a dedicated input buffer and
3490 // will either output multi channel to mEffectBuffer if the track is spatilaized
3491 // or stereo to mPostSpatializerBuffer if not spatialized.
3492 uint32_t channelMask;
3493 bool isSessionSpatialized =
3494 (hasAudioSession_l(session) & ThreadBase::SPATIALIZED_SESSION) != 0;
3495 if (isSessionSpatialized) {
3496 channelMask = mMixerChannelMask;
3497 } else {
3498 channelMask = mChannelMask;
3499 }
Eric Laurentf1f22e72021-07-13 14:04:14 +02003500 size_t numSamples = mNormalFrameCount
Eric Laurentb62d0362021-10-26 17:40:18 +02003501 * (audio_channel_count_from_out_mask(channelMask) + mHapticChannelCount);
Kevin Rocard7588ff42018-01-08 11:11:30 -08003502 status_t result = mAudioFlinger->mEffectsFactoryHal->allocateBuffer(
rago94a1ee82017-07-21 15:11:02 -07003503 numSamples * sizeof(effect_buffer_t),
Mikhail Naganov022b9952017-01-04 16:36:51 -08003504 &halInBuffer);
3505 if (result != OK) return result;
Eric Laurentb62d0362021-10-26 17:40:18 +02003506
3507 result = mAudioFlinger->mEffectsFactoryHal->mirrorBuffer(
3508 isSessionSpatialized ? mEffectBuffer : mPostSpatializerBuffer,
3509 isSessionSpatialized ? mEffectBufferSize : mPostSpatializerBufferSize,
3510 &halOutBuffer);
3511 if (result != OK) return result;
3512
rago94a1ee82017-07-21 15:11:02 -07003513#ifdef FLOAT_EFFECT_CHAIN
3514 buffer = halInBuffer->audioBuffer()->f32;
3515#else
Mikhail Naganov022b9952017-01-04 16:36:51 -08003516 buffer = halInBuffer->audioBuffer()->s16;
rago94a1ee82017-07-21 15:11:02 -07003517#endif
Mikhail Naganov022b9952017-01-04 16:36:51 -08003518 ALOGV("addEffectChain_l() creating new input buffer %p session %d",
3519 buffer, session);
Eric Laurentb62d0362021-10-26 17:40:18 +02003520 } else {
3521 // A global session on a SPATIALIZER thread is either OUTPUT_STAGE or DEVICE
3522 // - OUTPUT_STAGE session uses the mEffectBuffer as input buffer and
3523 // mPostSpatializerBuffer as output buffer
3524 // - DEVICE session uses the mPostSpatializerBuffer as input and output buffer.
3525 status_t result = mAudioFlinger->mEffectsFactoryHal->mirrorBuffer(
3526 mEffectBuffer, mEffectBufferSize, &halInBuffer);
3527 if (result != OK) return result;
3528 result = mAudioFlinger->mEffectsFactoryHal->mirrorBuffer(
3529 mPostSpatializerBuffer, mPostSpatializerBufferSize, &halOutBuffer);
3530 if (result != OK) return result;
Eric Laurent81784c32012-11-19 14:55:58 -08003531
Eric Laurentb62d0362021-10-26 17:40:18 +02003532 if (session == AUDIO_SESSION_DEVICE) {
3533 halInBuffer = halOutBuffer;
3534 }
3535 }
3536 } else {
3537 status_t result = mAudioFlinger->mEffectsFactoryHal->mirrorBuffer(
3538 mEffectBufferEnabled ? mEffectBuffer : mSinkBuffer,
3539 mEffectBufferEnabled ? mEffectBufferSize : mSinkBufferSize,
3540 &halInBuffer);
3541 if (result != OK) return result;
3542 halOutBuffer = halInBuffer;
3543 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
3544 if (!audio_is_global_session(session)) {
3545 buffer = reinterpret_cast<effect_buffer_t*>(halInBuffer->externalData());
3546 // Only one effect chain can be present in direct output thread and it uses
3547 // the sink buffer as input
3548 if (mType != DIRECT) {
3549 size_t numSamples = mNormalFrameCount
3550 * (audio_channel_count_from_out_mask(mMixerChannelMask)
3551 + mHapticChannelCount);
3552 status_t result = mAudioFlinger->mEffectsFactoryHal->allocateBuffer(
3553 numSamples * sizeof(effect_buffer_t),
3554 &halInBuffer);
3555 if (result != OK) return result;
3556#ifdef FLOAT_EFFECT_CHAIN
3557 buffer = halInBuffer->audioBuffer()->f32;
3558#else
3559 buffer = halInBuffer->audioBuffer()->s16;
3560#endif
3561 ALOGV("addEffectChain_l() creating new input buffer %p session %d",
3562 buffer, session);
3563 }
3564 }
3565 }
3566
3567 if (!audio_is_global_session(session)) {
Eric Laurent81784c32012-11-19 14:55:58 -08003568 // Attach all tracks with same session ID to this chain.
3569 for (size_t i = 0; i < mTracks.size(); ++i) {
3570 sp<Track> track = mTracks[i];
3571 if (session == track->sessionId()) {
Eric Laurentb62d0362021-10-26 17:40:18 +02003572 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p",
3573 track.get(), buffer);
Eric Laurent81784c32012-11-19 14:55:58 -08003574 track->setMainBuffer(buffer);
3575 chain->incTrackCnt();
3576 }
3577 }
3578
3579 // indicate all active tracks in the chain
Andy Hungdae27702016-10-31 14:01:16 -07003580 for (const sp<Track> &track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08003581 if (session == track->sessionId()) {
Eric Laurentb62d0362021-10-26 17:40:18 +02003582 ALOGV("addEffectChain_l() activating track %p on session %d",
3583 track.get(), session);
Eric Laurent81784c32012-11-19 14:55:58 -08003584 chain->incActiveTrackCnt();
3585 }
3586 }
3587 }
Eric Laurentb62d0362021-10-26 17:40:18 +02003588
Eric Laurentaaa44472014-09-12 17:41:50 -07003589 chain->setThread(this);
Mikhail Naganov022b9952017-01-04 16:36:51 -08003590 chain->setInBuffer(halInBuffer);
3591 chain->setOutBuffer(halOutBuffer);
Eric Laurent3f75a5b2019-11-12 15:55:51 -08003592 // Effect chain for session AUDIO_SESSION_DEVICE is inserted at end of effect
3593 // chains list in order to be processed last as it contains output device effects.
3594 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted just before to apply post
3595 // processing effects specific to an output stream before effects applied to all streams
3596 // routed to a given device.
Eric Laurent81784c32012-11-19 14:55:58 -08003597 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
3598 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Glenn Kastend848eb42016-03-08 13:42:11 -08003599 // after track specific effects and before output stage.
Eric Laurent81784c32012-11-19 14:55:58 -08003600 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
Glenn Kastend848eb42016-03-08 13:42:11 -08003601 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX.
Eric Laurent81784c32012-11-19 14:55:58 -08003602 // Effect chain for other sessions are inserted at beginning of effect
3603 // chains list to be processed before output mix effects. Relative order between other
Glenn Kastend848eb42016-03-08 13:42:11 -08003604 // sessions is not important.
3605 static_assert(AUDIO_SESSION_OUTPUT_MIX == 0 &&
Eric Laurent3f75a5b2019-11-12 15:55:51 -08003606 AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX &&
3607 AUDIO_SESSION_DEVICE < AUDIO_SESSION_OUTPUT_STAGE,
Glenn Kastend848eb42016-03-08 13:42:11 -08003608 "audio_session_t constants misdefined");
Eric Laurent81784c32012-11-19 14:55:58 -08003609 size_t size = mEffectChains.size();
3610 size_t i = 0;
3611 for (i = 0; i < size; i++) {
3612 if (mEffectChains[i]->sessionId() < session) {
3613 break;
3614 }
3615 }
3616 mEffectChains.insertAt(chain, i);
3617 checkSuspendOnAddEffectChain_l(chain);
3618
3619 return NO_ERROR;
3620}
3621
3622size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
3623{
Glenn Kastend848eb42016-03-08 13:42:11 -08003624 audio_session_t session = chain->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08003625
3626 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
3627
3628 for (size_t i = 0; i < mEffectChains.size(); i++) {
3629 if (chain == mEffectChains[i]) {
3630 mEffectChains.removeAt(i);
3631 // detach all active tracks from the chain
Andy Hungdae27702016-10-31 14:01:16 -07003632 for (const sp<Track> &track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08003633 if (session == track->sessionId()) {
3634 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
3635 chain.get(), session);
3636 chain->decActiveTrackCnt();
3637 }
3638 }
3639
3640 // detach all tracks with same session ID from this chain
3641 for (size_t i = 0; i < mTracks.size(); ++i) {
3642 sp<Track> track = mTracks[i];
3643 if (session == track->sessionId()) {
rago94a1ee82017-07-21 15:11:02 -07003644 track->setMainBuffer(reinterpret_cast<effect_buffer_t*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08003645 chain->decTrackCnt();
3646 }
3647 }
3648 break;
3649 }
3650 }
3651 return mEffectChains.size();
3652}
3653
3654status_t AudioFlinger::PlaybackThread::attachAuxEffect(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003655 const sp<AudioFlinger::PlaybackThread::Track>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003656{
3657 Mutex::Autolock _l(mLock);
3658 return attachAuxEffect_l(track, EffectId);
3659}
3660
3661status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003662 const sp<AudioFlinger::PlaybackThread::Track>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003663{
3664 status_t status = NO_ERROR;
3665
3666 if (EffectId == 0) {
3667 track->setAuxBuffer(0, NULL);
3668 } else {
3669 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
3670 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
3671 if (effect != 0) {
3672 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
3673 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
3674 } else {
3675 status = INVALID_OPERATION;
3676 }
3677 } else {
3678 status = BAD_VALUE;
3679 }
3680 }
3681 return status;
3682}
3683
3684void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
3685{
3686 for (size_t i = 0; i < mTracks.size(); ++i) {
3687 sp<Track> track = mTracks[i];
3688 if (track->auxEffectId() == effectId) {
3689 attachAuxEffect_l(track, 0);
3690 }
3691 }
3692}
3693
3694bool AudioFlinger::PlaybackThread::threadLoop()
3695{
Glenn Kasten388d5712017-04-07 14:38:41 -07003696 tlNBLogWriter = mNBLogWriter.get();
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003697
Eric Laurent81784c32012-11-19 14:55:58 -08003698 Vector< sp<Track> > tracksToRemove;
3699
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003700 mStandbyTimeNs = systemTime();
Andy Hung446f4df2019-02-21 12:26:41 -08003701 int64_t lastLoopCountWritten = -2; // never matches "previous" loop, when loopCount = 0.
Eric Laurent81784c32012-11-19 14:55:58 -08003702
3703 // MIXER
3704 nsecs_t lastWarning = 0;
3705
3706 // DUPLICATING
3707 // FIXME could this be made local to while loop?
3708 writeFrames = 0;
3709
3710 cacheParameters_l();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003711 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003712
Andy Hungd3639922022-04-28 18:00:49 -07003713 if (mType == MIXER || mType == SPATIALIZER) {
Eric Laurent81784c32012-11-19 14:55:58 -08003714 sleepTimeShift = 0;
3715 }
3716
3717 CpuStats cpuStats;
3718 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
3719
3720 acquireWakeLock();
3721
Glenn Kasteneef598c2017-04-03 14:41:13 -07003722 // mNBLogWriter logging APIs can only be called by a single thread, typically the
3723 // thread associated with this PlaybackThread.
3724 // If you want to share the mNBLogWriter with other threads (for example, binder threads)
3725 // then all such threads must agree to hold a common mutex before logging.
Glenn Kasten9e58b552013-01-18 15:09:48 -08003726 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
3727 // and then that string will be logged at the next convenient opportunity.
Glenn Kasteneef598c2017-04-03 14:41:13 -07003728 // See reference to logString below.
Glenn Kasten9e58b552013-01-18 15:09:48 -08003729 const char *logString = NULL;
3730
rago1bb90822017-05-02 18:31:48 -07003731 // Estimated time for next buffer to be written to hal. This is used only on
3732 // suspended mode (for now) to help schedule the wait time until next iteration.
3733 nsecs_t timeLoopNextNs = 0;
3734
Eric Laurent664539d2013-09-23 18:24:31 -07003735 checkSilentMode_l();
Glenn Kasteneef598c2017-04-03 14:41:13 -07003736
Andy Hung2dbffc22018-08-08 18:50:41 -07003737 audio_patch_handle_t lastDownstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Andy Hungf3234512018-07-03 14:51:47 -07003738
Eric Laurentb3f315a2021-07-13 15:09:05 +02003739 sendCheckOutputStageEffectsEvent();
3740
Andy Hung446f4df2019-02-21 12:26:41 -08003741 // loopCount is used for statistics and diagnostics.
3742 for (int64_t loopCount = 0; !exitPending(); ++loopCount)
Eric Laurent81784c32012-11-19 14:55:58 -08003743 {
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08003744 // Log merge requests are performed during AudioFlinger binder transactions, but
3745 // that does not cover audio playback. It's requested here for that reason.
3746 mAudioFlinger->requestLogMerge();
3747
Eric Laurent81784c32012-11-19 14:55:58 -08003748 cpuStats.sample(myName);
3749
3750 Vector< sp<EffectChain> > effectChains;
Andy Hung6e6a2e62019-04-30 16:38:41 -07003751 audio_session_t activeHapticSessionId = AUDIO_SESSION_NONE;
Eric Laurentb62d0362021-10-26 17:40:18 +02003752 bool isHapticSessionSpatialized = false;
Andy Hungc1646382019-04-30 16:12:10 -07003753 std::vector<sp<Track>> activeTracks;
Eric Laurent81784c32012-11-19 14:55:58 -08003754
Andy Hung2dbffc22018-08-08 18:50:41 -07003755 // If the device is AUDIO_DEVICE_OUT_BUS, check for downstream latency.
3756 //
jiabinc52b1ff2019-10-31 17:20:42 -07003757 // Note: we access outDeviceTypes() outside of mLock.
3758 if (isMsdDevice() && outDeviceTypes().count(AUDIO_DEVICE_OUT_BUS) != 0) {
Andy Hung2dbffc22018-08-08 18:50:41 -07003759 // Here, we try for the AF lock, but do not block on it as the latency
3760 // is more informational.
3761 if (mAudioFlinger->mLock.tryLock() == NO_ERROR) {
3762 std::vector<PatchPanel::SoftwarePatch> swPatches;
3763 double latencyMs;
3764 status_t status = INVALID_OPERATION;
3765 audio_patch_handle_t downstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
3766 if (mAudioFlinger->mPatchPanel.getDownstreamSoftwarePatches(id(), &swPatches) == OK
3767 && swPatches.size() > 0) {
3768 status = swPatches[0].getLatencyMs_l(&latencyMs);
3769 downstreamPatchHandle = swPatches[0].getPatchHandle();
3770 }
3771 if (downstreamPatchHandle != lastDownstreamPatchHandle) {
Dean Wheatley30d28422018-11-06 10:27:40 +11003772 mDownstreamLatencyStatMs.reset();
Andy Hung2dbffc22018-08-08 18:50:41 -07003773 lastDownstreamPatchHandle = downstreamPatchHandle;
3774 }
3775 if (status == OK) {
3776 // verify downstream latency (we assume a max reasonable
Mikhail Naganov6aa0a312018-11-09 11:00:01 -08003777 // latency of 5 seconds).
3778 const double minLatency = 0., maxLatency = 5000.;
3779 if (latencyMs >= minLatency && latencyMs <= maxLatency) {
Dean Wheatley56a583e2020-05-08 15:12:17 +10003780 ALOGVV("new downstream latency %lf ms", latencyMs);
Andy Hung2dbffc22018-08-08 18:50:41 -07003781 } else {
3782 ALOGD("out of range downstream latency %lf ms", latencyMs);
Mikhail Naganov6aa0a312018-11-09 11:00:01 -08003783 if (latencyMs < minLatency) latencyMs = minLatency;
3784 else if (latencyMs > maxLatency) latencyMs = maxLatency;
Andy Hung2dbffc22018-08-08 18:50:41 -07003785 }
Dean Wheatley30d28422018-11-06 10:27:40 +11003786 mDownstreamLatencyStatMs.add(latencyMs);
Andy Hung2dbffc22018-08-08 18:50:41 -07003787 }
3788 mAudioFlinger->mLock.unlock();
3789 }
3790 } else {
3791 if (lastDownstreamPatchHandle != AUDIO_PATCH_HANDLE_NONE) {
3792 // our device is no longer AUDIO_DEVICE_OUT_BUS, reset patch handle and stats.
Dean Wheatley30d28422018-11-06 10:27:40 +11003793 mDownstreamLatencyStatMs.reset();
Andy Hung2dbffc22018-08-08 18:50:41 -07003794 lastDownstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
3795 }
3796 }
3797
Eric Laurentb3f315a2021-07-13 15:09:05 +02003798 if (mCheckOutputStageEffects.exchange(false)) {
3799 checkOutputStageEffects();
3800 }
3801
Eric Laurent81784c32012-11-19 14:55:58 -08003802 { // scope for mLock
3803
3804 Mutex::Autolock _l(mLock);
3805
Eric Laurent021cf962014-05-13 10:18:14 -07003806 processConfigEvents_l();
Eric Laurentb3f315a2021-07-13 15:09:05 +02003807 if (mCheckOutputStageEffects.load()) {
3808 continue;
3809 }
Eric Laurent10351942014-05-08 18:49:52 -07003810
Glenn Kasteneef598c2017-04-03 14:41:13 -07003811 // See comment at declaration of logString for why this is done under mLock
Glenn Kasten9e58b552013-01-18 15:09:48 -08003812 if (logString != NULL) {
3813 mNBLogWriter->logTimestamp();
3814 mNBLogWriter->log(logString);
3815 logString = NULL;
3816 }
3817
Dean Wheatley12473e92021-03-18 23:00:55 +11003818 collectTimestamps_l();
Andy Hungc8fddf32018-08-08 18:32:37 -07003819
Eric Laurent81784c32012-11-19 14:55:58 -08003820 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003821 if (mSignalPending) {
3822 // A signal was raised while we were unlocked
3823 mSignalPending = false;
3824 } else if (waitingAsyncCallback_l()) {
3825 if (exitPending()) {
3826 break;
3827 }
Marco Nelissen078538c2015-05-12 09:17:57 -07003828 bool released = false;
Eric Laurent64667972016-03-30 18:19:46 -07003829 if (!keepWakeLock()) {
Marco Nelissen078538c2015-05-12 09:17:57 -07003830 releaseWakeLock_l();
3831 released = true;
3832 }
Andy Hung10cbff12017-02-21 17:30:14 -08003833
3834 const int64_t waitNs = computeWaitTimeNs_l();
3835 ALOGV("wait async completion (wait time: %lld)", (long long)waitNs);
3836 status_t status = mWaitWorkCV.waitRelative(mLock, waitNs);
3837 if (status == TIMED_OUT) {
3838 mSignalPending = true; // if timeout recheck everything
3839 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003840 ALOGV("async completion/wake");
Marco Nelissen078538c2015-05-12 09:17:57 -07003841 if (released) {
3842 acquireWakeLock_l();
3843 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003844 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3845 mSleepTimeUs = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07003846
3847 continue;
3848 }
Eric Tan39ec8d62018-07-24 09:49:29 -07003849 if ((mActiveTracks.isEmpty() && systemTime() > mStandbyTimeNs) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08003850 isSuspended()) {
3851 // put audio hardware into standby after short delay
3852 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003853
3854 threadLoop_standby();
3855
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07003856 // This is where we go into standby
3857 if (!mStandby) {
3858 LOG_AUDIO_STATE();
Andy Hungcf10d742020-04-28 15:38:24 -07003859 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07003860 mThreadSnapshot.onEnd();
Andy Hungcf10d742020-04-28 15:38:24 -07003861 mStandby = true;
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07003862 }
Andy Hungd0979812019-02-21 15:51:44 -08003863 sendStatistics(false /* force */);
Eric Laurent81784c32012-11-19 14:55:58 -08003864 }
3865
Eric Tan39ec8d62018-07-24 09:49:29 -07003866 if (mActiveTracks.isEmpty() && mConfigEvents.isEmpty()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003867 // we're about to wait, flush the binder command buffer
3868 IPCThreadState::self()->flushCommands();
3869
3870 clearOutputTracks();
3871
3872 if (exitPending()) {
3873 break;
3874 }
3875
3876 releaseWakeLock_l();
3877 // wait until we have something to do...
3878 ALOGV("%s going to sleep", myName.string());
3879 mWaitWorkCV.wait(mLock);
3880 ALOGV("%s waking up", myName.string());
3881 acquireWakeLock_l();
3882
3883 mMixerStatus = MIXER_IDLE;
3884 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
3885 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003886 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003887 checkSilentMode_l();
3888
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003889 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3890 mSleepTimeUs = mIdleSleepTimeUs;
Andy Hungd3639922022-04-28 18:00:49 -07003891 if (mType == MIXER || mType == SPATIALIZER) {
Eric Laurent81784c32012-11-19 14:55:58 -08003892 sleepTimeShift = 0;
3893 }
3894
3895 continue;
3896 }
3897 }
Eric Laurent81784c32012-11-19 14:55:58 -08003898 // mMixerStatusIgnoringFastTracks is also updated internally
3899 mMixerStatus = prepareTracks_l(&tracksToRemove);
3900
Andy Hungdae27702016-10-31 14:01:16 -07003901 mActiveTracks.updatePowerState(this);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003902
Kevin Rocard069c2712018-03-29 19:09:14 -07003903 updateMetadata_l();
3904
Eric Laurent81784c32012-11-19 14:55:58 -08003905 // prevent any changes in effect chain list and in each effect chain
3906 // during mixing and effect process as the audio buffers could be deleted
3907 // or modified if an effect is created or deleted
3908 lockEffectChains_l(effectChains);
Andy Hung6e6a2e62019-04-30 16:38:41 -07003909
3910 // Determine which session to pick up haptic data.
3911 // This must be done under the same lock as prepareTracks_l().
jiabineb3bda02020-06-30 14:07:03 -07003912 // The haptic data from the effect is at a higher priority than the one from track.
Andy Hung6e6a2e62019-04-30 16:38:41 -07003913 // TODO: Write haptic data directly to sink buffer when mixing.
Eric Laurentb62d0362021-10-26 17:40:18 +02003914 if (mHapticChannelCount > 0) {
Andy Hung6e6a2e62019-04-30 16:38:41 -07003915 for (const auto& track : mActiveTracks) {
jiabineb3bda02020-06-30 14:07:03 -07003916 sp<EffectChain> effectChain = getEffectChain_l(track->sessionId());
Eric Laurentb62d0362021-10-26 17:40:18 +02003917 if (effectChain != nullptr
3918 && effectChain->containsHapticGeneratingEffect_l()) {
jiabineb3bda02020-06-30 14:07:03 -07003919 activeHapticSessionId = track->sessionId();
Eric Laurentb62d0362021-10-26 17:40:18 +02003920 isHapticSessionSpatialized =
Eric Laurentb0a7bc92022-04-05 15:06:08 +02003921 mType == SPATIALIZER && track->isSpatialized();
jiabineb3bda02020-06-30 14:07:03 -07003922 break;
3923 }
Eric Laurentb62d0362021-10-26 17:40:18 +02003924 if (activeHapticSessionId == AUDIO_SESSION_NONE
3925 && track->getHapticPlaybackEnabled()) {
Andy Hung6e6a2e62019-04-30 16:38:41 -07003926 activeHapticSessionId = track->sessionId();
Eric Laurentb62d0362021-10-26 17:40:18 +02003927 isHapticSessionSpatialized =
Eric Laurentb0a7bc92022-04-05 15:06:08 +02003928 mType == SPATIALIZER && track->isSpatialized();
Andy Hung6e6a2e62019-04-30 16:38:41 -07003929 }
3930 }
3931 }
3932
Andy Hungc1646382019-04-30 16:12:10 -07003933 // Acquire a local copy of active tracks with lock (release w/o lock).
3934 //
3935 // Control methods on the track acquire the ThreadBase lock (e.g. start()
3936 // stop(), pause(), etc.), but the threadLoop is entitled to call audio
3937 // data / buffer methods on tracks from activeTracks without the ThreadBase lock.
3938 activeTracks.insert(activeTracks.end(), mActiveTracks.begin(), mActiveTracks.end());
Eric Laurent68a40a82022-05-03 18:15:04 +02003939
3940 setHalLatencyMode_l();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003941 } // mLock scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08003942
Eric Laurentbfb1b832013-01-07 09:53:42 -08003943 if (mBytesRemaining == 0) {
3944 mCurrentWriteLength = 0;
3945 if (mMixerStatus == MIXER_TRACKS_READY) {
3946 // threadLoop_mix() sets mCurrentWriteLength
3947 threadLoop_mix();
3948 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
3949 && (mMixerStatus != MIXER_DRAIN_ALL)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003950 // threadLoop_sleepTime sets mSleepTimeUs to 0 if data
Eric Laurentbfb1b832013-01-07 09:53:42 -08003951 // must be written to HAL
3952 threadLoop_sleepTime();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003953 if (mSleepTimeUs == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08003954 mCurrentWriteLength = mSinkBufferSize;
Andy Hungc1646382019-04-30 16:12:10 -07003955
3956 // Tally underrun frames as we are inserting 0s here.
3957 for (const auto& track : activeTracks) {
Andy Hunge2e830f2019-12-03 12:54:46 -08003958 if (track->mFillingUpStatus == Track::FS_ACTIVE
3959 && !track->isStopped()
3960 && !track->isPaused()
3961 && !track->isTerminated()) {
3962 ALOGV("%s: track(%d) %s underrun due to thread sleep of %zu frames",
3963 __func__, track->id(), track->getTrackStateAsString(),
3964 mNormalFrameCount);
Andy Hungc1646382019-04-30 16:12:10 -07003965 track->mAudioTrackServerProxy->tallyUnderrunFrames(mNormalFrameCount);
3966 }
3967 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003968 }
3969 }
Andy Hung98ef9782014-03-04 14:46:50 -08003970 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003971 // mMixerBuffer with data if mMixerBufferValid is true and mSleepTimeUs == 0.
Andy Hung98ef9782014-03-04 14:46:50 -08003972 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
3973 // or mSinkBuffer (if there are no effects).
3974 //
3975 // This is done pre-effects computation; if effects change to
3976 // support higher precision, this needs to move.
3977 //
3978 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003979 // TODO use mSleepTimeUs == 0 as an additional condition.
Eric Laurent39095982021-08-24 18:29:27 +02003980 uint32_t mixerChannelCount = mEffectBufferValid ?
3981 audio_channel_count_from_out_mask(mMixerChannelMask) : mChannelCount;
Andy Hung98ef9782014-03-04 14:46:50 -08003982 if (mMixerBufferValid) {
3983 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
3984 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
3985
David Li88ee0902022-06-22 10:01:21 +08003986 // Apply mono blending and balancing if the effect buffer is not valid. Otherwise,
3987 // do these processes after effects are applied.
3988 if (!mEffectBufferValid) {
3989 // mono blend occurs for mixer threads only (not direct or offloaded)
3990 // and is handled here if we're going directly to the sink.
3991 if (requireMonoBlend()) {
3992 mono_blend(mMixerBuffer, mMixerBufferFormat, mChannelCount,
3993 mNormalFrameCount, true /*limit*/);
3994 }
Andy Hung2ddee192015-12-18 17:34:44 -08003995
David Li88ee0902022-06-22 10:01:21 +08003996 if (!hasFastMixer()) {
3997 // Balance must take effect after mono conversion.
3998 // We do it here if there is no FastMixer.
3999 // mBalance detects zero balance within the class for speed
4000 // (not needed here).
4001 mBalance.setBalance(mMasterBalance.load());
4002 mBalance.process((float *)mMixerBuffer, mNormalFrameCount);
4003 }
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01004004 }
4005
Andy Hung98ef9782014-03-04 14:46:50 -08004006 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
Eric Laurent39095982021-08-24 18:29:27 +02004007 mNormalFrameCount * (mixerChannelCount + mHapticChannelCount));
jiabin245cdd92018-12-07 17:55:15 -08004008
4009 // If we're going directly to the sink and there are haptic channels,
4010 // we should adjust channels as the sample data is partially interleaved
4011 // in this case.
4012 if (!mEffectBufferValid && mHapticChannelCount > 0) {
4013 adjust_channels_non_destructive(buffer, mChannelCount, buffer,
4014 mChannelCount + mHapticChannelCount,
4015 audio_bytes_per_sample(format),
4016 audio_bytes_per_frame(mChannelCount, format) * mNormalFrameCount);
4017 }
Andy Hung98ef9782014-03-04 14:46:50 -08004018 }
4019
Eric Laurentbfb1b832013-01-07 09:53:42 -08004020 mBytesRemaining = mCurrentWriteLength;
4021 if (isSuspended()) {
Andy Hung238fa3d2016-07-28 10:53:22 -07004022 // Simulate write to HAL when suspended (e.g. BT SCO phone call).
4023 mSleepTimeUs = suspendSleepTimeUs(); // assumes full buffer.
4024 const size_t framesRemaining = mBytesRemaining / mFrameSize;
4025 mBytesWritten += mBytesRemaining;
4026 mFramesWritten += framesRemaining;
4027 mSuspendedFrames += framesRemaining; // to adjust kernel HAL position
Eric Laurentbfb1b832013-01-07 09:53:42 -08004028 mBytesRemaining = 0;
4029 }
Eric Laurent81784c32012-11-19 14:55:58 -08004030
Eric Laurentbfb1b832013-01-07 09:53:42 -08004031 // only process effects if we're going to write
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004032 if (mSleepTimeUs == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004033 for (size_t i = 0; i < effectChains.size(); i ++) {
4034 effectChains[i]->process_l();
jiabin47affe52019-04-04 18:02:07 -07004035 // TODO: Write haptic data directly to sink buffer when mixing.
Andy Hung6e6a2e62019-04-30 16:38:41 -07004036 if (activeHapticSessionId != AUDIO_SESSION_NONE
4037 && activeHapticSessionId == effectChains[i]->sessionId()) {
jiabin47affe52019-04-04 18:02:07 -07004038 // Haptic data is active in this case, copy it directly from
4039 // in buffer to out buffer.
Eric Laurentb62d0362021-10-26 17:40:18 +02004040 uint32_t hapticSessionChannelCount = mEffectBufferValid ?
4041 audio_channel_count_from_out_mask(mMixerChannelMask) :
4042 mChannelCount;
4043 if (mType == SPATIALIZER && !isHapticSessionSpatialized) {
4044 hapticSessionChannelCount = mChannelCount;
4045 }
4046
jiabin47affe52019-04-04 18:02:07 -07004047 const size_t audioBufferSize = mNormalFrameCount
Eric Laurentb62d0362021-10-26 17:40:18 +02004048 * audio_bytes_per_frame(hapticSessionChannelCount,
4049 EFFECT_BUFFER_FORMAT);
jiabin47affe52019-04-04 18:02:07 -07004050 memcpy_by_audio_format(
4051 (uint8_t*)effectChains[i]->outBuffer() + audioBufferSize,
4052 EFFECT_BUFFER_FORMAT,
4053 (const uint8_t*)effectChains[i]->inBuffer() + audioBufferSize,
4054 EFFECT_BUFFER_FORMAT, mNormalFrameCount * mHapticChannelCount);
4055 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004056 }
Eric Laurent81784c32012-11-19 14:55:58 -08004057 }
4058 }
Eric Laurent59fe0102013-09-27 18:48:26 -07004059 // Process effect chains for offloaded thread even if no audio
4060 // was read from audio track: process only updates effect state
4061 // and thus does have to be synchronized with audio writes but may have
4062 // to be called while waiting for async write callback
4063 if (mType == OFFLOAD) {
4064 for (size_t i = 0; i < effectChains.size(); i ++) {
4065 effectChains[i]->process_l();
4066 }
4067 }
Eric Laurent81784c32012-11-19 14:55:58 -08004068
Andy Hung98ef9782014-03-04 14:46:50 -08004069 // Only if the Effects buffer is enabled and there is data in the
4070 // Effects buffer (buffer valid), we need to
4071 // copy into the sink buffer.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004072 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08004073 if (mEffectBufferValid) {
4074 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
Eric Laurentb62d0362021-10-26 17:40:18 +02004075 void *effectBuffer = (mType == SPATIALIZER) ? mPostSpatializerBuffer : mEffectBuffer;
Andy Hung2ddee192015-12-18 17:34:44 -08004076 if (requireMonoBlend()) {
Eric Laurentb62d0362021-10-26 17:40:18 +02004077 mono_blend(effectBuffer, mEffectBufferFormat, mChannelCount, mNormalFrameCount,
Glenn Kasten03c48d52016-01-27 17:25:17 -08004078 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08004079 }
4080
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01004081 if (!hasFastMixer()) {
4082 // Balance must take effect after mono conversion.
4083 // We do it here if there is no FastMixer.
4084 // mBalance detects zero balance within the class for speed (not needed here).
4085 mBalance.setBalance(mMasterBalance.load());
Eric Laurentb62d0362021-10-26 17:40:18 +02004086 mBalance.process((float *)effectBuffer, mNormalFrameCount);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01004087 }
4088
Eric Laurentb62d0362021-10-26 17:40:18 +02004089 // for SPATIALIZER thread, Move haptics channels from mEffectBuffer to
4090 // mPostSpatializerBuffer if the haptics track is spatialized.
4091 // Otherwise, the haptics channels are already in mPostSpatializerBuffer.
4092 // For other thread types, the haptics channels are already in mEffectBuffer.
4093 if (mType == SPATIALIZER && isHapticSessionSpatialized) {
4094 const size_t srcBufferSize = mNormalFrameCount *
4095 audio_bytes_per_frame(audio_channel_count_from_out_mask(mMixerChannelMask),
4096 mEffectBufferFormat);
4097 const size_t dstBufferSize = mNormalFrameCount
4098 * audio_bytes_per_frame(mChannelCount, mEffectBufferFormat);
4099
4100 memcpy_by_audio_format((uint8_t*)mPostSpatializerBuffer + dstBufferSize,
4101 mEffectBufferFormat,
4102 (uint8_t*)mEffectBuffer + srcBufferSize,
4103 mEffectBufferFormat,
4104 mNormalFrameCount * mHapticChannelCount);
Eric Laurent39095982021-08-24 18:29:27 +02004105 }
Eric Laurentb62d0362021-10-26 17:40:18 +02004106
4107 memcpy_by_audio_format(mSinkBuffer, mFormat, effectBuffer, mEffectBufferFormat,
4108 mNormalFrameCount * (mChannelCount + mHapticChannelCount));
4109
jiabin245cdd92018-12-07 17:55:15 -08004110 // The sample data is partially interleaved when haptic channels exist,
4111 // we need to adjust channels here.
4112 if (mHapticChannelCount > 0) {
4113 adjust_channels_non_destructive(mSinkBuffer, mChannelCount, mSinkBuffer,
4114 mChannelCount + mHapticChannelCount,
4115 audio_bytes_per_sample(mFormat),
4116 audio_bytes_per_frame(mChannelCount, mFormat) * mNormalFrameCount);
4117 }
Andy Hung98ef9782014-03-04 14:46:50 -08004118 }
4119
Eric Laurent81784c32012-11-19 14:55:58 -08004120 // enable changes in effect chain
4121 unlockEffectChains(effectChains);
4122
Eric Laurentbfb1b832013-01-07 09:53:42 -08004123 if (!waitingAsyncCallback()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004124 // mSleepTimeUs == 0 means we must write to audio hardware
4125 if (mSleepTimeUs == 0) {
Andy Hung08fb1742015-05-31 23:22:10 -07004126 ssize_t ret = 0;
Andy Hung446f4df2019-02-21 12:26:41 -08004127 // writePeriodNs is updated >= 0 when ret > 0.
4128 int64_t writePeriodNs = -1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004129 if (mBytesRemaining) {
Andy Hung69488c42016-05-16 18:43:33 -07004130 // FIXME rewrite to reduce number of system calls
Andy Hung446f4df2019-02-21 12:26:41 -08004131 const int64_t lastIoBeginNs = systemTime();
Andy Hung08fb1742015-05-31 23:22:10 -07004132 ret = threadLoop_write();
Andy Hung446f4df2019-02-21 12:26:41 -08004133 const int64_t lastIoEndNs = systemTime();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004134 if (ret < 0) {
4135 mBytesRemaining = 0;
Andy Hung446f4df2019-02-21 12:26:41 -08004136 } else if (ret > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004137 mBytesWritten += ret;
4138 mBytesRemaining -= ret;
Andy Hung446f4df2019-02-21 12:26:41 -08004139 const int64_t frames = ret / mFrameSize;
4140 mFramesWritten += frames;
4141
4142 writePeriodNs = lastIoEndNs - mLastIoEndNs;
4143 // process information relating to write time.
4144 if (audio_has_proportional_frames(mFormat)) {
4145 // we are in a continuous mixing cycle
4146 if (mMixerStatus == MIXER_TRACKS_READY &&
4147 loopCount == lastLoopCountWritten + 1) {
4148
4149 const double jitterMs =
4150 TimestampVerifier<int64_t, int64_t>::computeJitterMs(
4151 {frames, writePeriodNs},
4152 {0, 0} /* lastTimestamp */, mSampleRate);
4153 const double processMs =
4154 (lastIoBeginNs - mLastIoEndNs) * 1e-6;
4155
4156 Mutex::Autolock _l(mLock);
4157 mIoJitterMs.add(jitterMs);
4158 mProcessTimeMs.add(processMs);
Robert Wu06db0a32021-08-10 19:05:34 +00004159
4160 if (mPipeSink.get() != nullptr) {
4161 // Using the Monopipe availableToWrite, we estimate the current
4162 // buffer size.
4163 MonoPipe* monoPipe = static_cast<MonoPipe*>(mPipeSink.get());
4164 const ssize_t
4165 availableToWrite = mPipeSink->availableToWrite();
4166 const size_t pipeFrames = monoPipe->maxFrames();
4167 const size_t
4168 remainingFrames = pipeFrames - max(availableToWrite, 0);
4169 mMonopipePipeDepthStats.add(remainingFrames);
4170 }
Andy Hung446f4df2019-02-21 12:26:41 -08004171 }
4172
4173 // write blocked detection
4174 const int64_t deltaWriteNs = lastIoEndNs - lastIoBeginNs;
Andy Hungd3639922022-04-28 18:00:49 -07004175 if ((mType == MIXER || mType == SPATIALIZER)
4176 && deltaWriteNs > maxPeriod) {
Andy Hung446f4df2019-02-21 12:26:41 -08004177 mNumDelayedWrites++;
4178 if ((lastIoEndNs - lastWarning) > kWarningThrottleNs) {
4179 ATRACE_NAME("underrun");
4180 ALOGW("write blocked for %lld msecs, "
4181 "%d delayed writes, thread %d",
4182 (long long)deltaWriteNs / NANOS_PER_MILLISECOND,
4183 mNumDelayedWrites, mId);
4184 lastWarning = lastIoEndNs;
4185 }
4186 }
4187 }
4188 // update timing info.
4189 mLastIoBeginNs = lastIoBeginNs;
4190 mLastIoEndNs = lastIoEndNs;
4191 lastLoopCountWritten = loopCount;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004192 }
4193 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
4194 (mMixerStatus == MIXER_DRAIN_ALL)) {
4195 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08004196 }
Andy Hungd3639922022-04-28 18:00:49 -07004197 if ((mType == MIXER || mType == SPATIALIZER) && !mStandby) {
Andy Hung08fb1742015-05-31 23:22:10 -07004198
4199 if (mThreadThrottle
4200 && mMixerStatus == MIXER_TRACKS_READY // we are mixing (active tracks)
Andy Hung446f4df2019-02-21 12:26:41 -08004201 && writePeriodNs > 0) { // we have write period info
Andy Hung08fb1742015-05-31 23:22:10 -07004202 // Limit MixerThread data processing to no more than twice the
4203 // expected processing rate.
4204 //
4205 // This helps prevent underruns with NuPlayer and other applications
4206 // which may set up buffers that are close to the minimum size, or use
4207 // deep buffers, and rely on a double-buffering sleep strategy to fill.
4208 //
4209 // The throttle smooths out sudden large data drains from the device,
4210 // e.g. when it comes out of standby, which often causes problems with
4211 // (1) mixer threads without a fast mixer (which has its own warm-up)
4212 // (2) minimum buffer sized tracks (even if the track is full,
4213 // the app won't fill fast enough to handle the sudden draw).
Haynes Mathew Georgef92b2172016-05-09 11:34:15 -07004214 //
4215 // Total time spent in last processing cycle equals time spent in
4216 // 1. threadLoop_write, as well as time spent in
4217 // 2. threadLoop_mix (significant for heavy mixing, especially
4218 // on low tier processors)
Andy Hung08fb1742015-05-31 23:22:10 -07004219
Andy Hung446f4df2019-02-21 12:26:41 -08004220 // it's OK if deltaMs is an overestimate.
4221
4222 const int32_t deltaMs = writePeriodNs / NANOS_PER_MILLISECOND;
Ivan Lozanoe02bc542017-10-26 09:51:54 -07004223
Ivan Lozanoea04d392017-11-07 14:37:07 -08004224 const int32_t throttleMs = (int32_t)mHalfBufferMs - deltaMs;
Andy Hung08fb1742015-05-31 23:22:10 -07004225 if ((signed)mHalfBufferMs >= throttleMs && throttleMs > 0) {
Andy Hungcf10d742020-04-28 15:38:24 -07004226 mThreadMetrics.logThrottleMs((double)throttleMs);
Andy Hungb68f5eb2019-12-03 16:49:17 -08004227
Andy Hung08fb1742015-05-31 23:22:10 -07004228 usleep(throttleMs * 1000);
Andy Hung40eb1a12015-06-18 13:42:02 -07004229 // notify of throttle start on verbose log
4230 ALOGV_IF(mThreadThrottleEndMs == mThreadThrottleTimeMs,
4231 "mixer(%p) throttle begin:"
4232 " ret(%zd) deltaMs(%d) requires sleep %d ms",
Andy Hung08fb1742015-05-31 23:22:10 -07004233 this, ret, deltaMs, throttleMs);
Andy Hung40eb1a12015-06-18 13:42:02 -07004234 mThreadThrottleTimeMs += throttleMs;
Andy Hung0a31ddd2016-07-06 19:10:29 -07004235 // Throttle must be attributed to the previous mixer loop's write time
4236 // to allow back-to-back throttling.
Andy Hung446f4df2019-02-21 12:26:41 -08004237 // This also ensures proper timing statistics.
4238 mLastIoEndNs = systemTime(); // we fetch the write end time again.
Andy Hung40eb1a12015-06-18 13:42:02 -07004239 } else {
4240 uint32_t diff = mThreadThrottleTimeMs - mThreadThrottleEndMs;
4241 if (diff > 0) {
4242 // notify of throttle end on debug log
Andy Hung3ea004d2016-05-05 16:48:37 -07004243 // but prevent spamming for bluetooth
jiabinc52b1ff2019-10-31 17:20:42 -07004244 ALOGD_IF(!isSingleDeviceType(
4245 outDeviceTypes(), audio_is_a2dp_out_device) &&
4246 !isSingleDeviceType(
4247 outDeviceTypes(), audio_is_hearing_aid_out_device),
Andy Hung3ea004d2016-05-05 16:48:37 -07004248 "mixer(%p) throttle end: throttle time(%u)", this, diff);
Andy Hung40eb1a12015-06-18 13:42:02 -07004249 mThreadThrottleEndMs = mThreadThrottleTimeMs;
4250 }
Andy Hung08fb1742015-05-31 23:22:10 -07004251 }
4252 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004253 }
Eric Laurent81784c32012-11-19 14:55:58 -08004254
Eric Laurentbfb1b832013-01-07 09:53:42 -08004255 } else {
Glenn Kastene7754022014-10-31 12:11:26 -07004256 ATRACE_BEGIN("sleep");
Eric Laurente93cc032016-05-05 10:15:10 -07004257 Mutex::Autolock _l(mLock);
rago1bb90822017-05-02 18:31:48 -07004258 // suspended requires accurate metering of sleep time.
4259 if (isSuspended()) {
4260 // advance by expected sleepTime
4261 timeLoopNextNs += microseconds((nsecs_t)mSleepTimeUs);
4262 const nsecs_t nowNs = systemTime();
4263
4264 // compute expected next time vs current time.
4265 // (negative deltas are treated as delays).
4266 nsecs_t deltaNs = timeLoopNextNs - nowNs;
4267 if (deltaNs < -kMaxNextBufferDelayNs) {
4268 // Delays longer than the max allowed trigger a reset.
4269 ALOGV("DelayNs: %lld, resetting timeLoopNextNs", (long long) deltaNs);
4270 deltaNs = microseconds((nsecs_t)mSleepTimeUs);
4271 timeLoopNextNs = nowNs + deltaNs;
4272 } else if (deltaNs < 0) {
4273 // Delays within the max delay allowed: zero the delta/sleepTime
4274 // to help the system catch up in the next iteration(s)
4275 ALOGV("DelayNs: %lld, catching-up", (long long) deltaNs);
4276 deltaNs = 0;
4277 }
4278 // update sleep time (which is >= 0)
4279 mSleepTimeUs = deltaNs / 1000;
4280 }
Eric Laurente93cc032016-05-05 10:15:10 -07004281 if (!mSignalPending && mConfigEvents.isEmpty() && !exitPending()) {
4282 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)mSleepTimeUs));
Eric Laurent51716182016-02-29 18:00:56 -08004283 }
Glenn Kastene7754022014-10-31 12:11:26 -07004284 ATRACE_END();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004285 }
Eric Laurent81784c32012-11-19 14:55:58 -08004286 }
4287
4288 // Finally let go of removed track(s), without the lock held
4289 // since we can't guarantee the destructors won't acquire that
4290 // same lock. This will also mutate and push a new fast mixer state.
4291 threadLoop_removeTracks(tracksToRemove);
4292 tracksToRemove.clear();
4293
4294 // FIXME I don't understand the need for this here;
4295 // it was in the original code but maybe the
4296 // assignment in saveOutputTracks() makes this unnecessary?
4297 clearOutputTracks();
4298
4299 // Effect chains will be actually deleted here if they were removed from
4300 // mEffectChains list during mixing or effects processing
4301 effectChains.clear();
4302
4303 // FIXME Note that the above .clear() is no longer necessary since effectChains
4304 // is now local to this block, but will keep it for now (at least until merge done).
4305 }
4306
Eric Laurentbfb1b832013-01-07 09:53:42 -08004307 threadLoop_exit();
4308
Eric Laurentcf817a22014-08-04 20:36:31 -07004309 if (!mStandby) {
4310 threadLoop_standby();
4311 mStandby = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004312 }
4313
4314 releaseWakeLock();
4315
4316 ALOGV("Thread %p type %d exiting", this, mType);
4317 return false;
4318}
4319
Dean Wheatley12473e92021-03-18 23:00:55 +11004320void AudioFlinger::PlaybackThread::collectTimestamps_l()
4321{
Dean Wheatley12473e92021-03-18 23:00:55 +11004322 if (mStandby) {
4323 mTimestampVerifier.discontinuity(discontinuityForStandbyOrFlush());
4324 return;
4325 } else if (mHwPaused) {
4326 mTimestampVerifier.discontinuity(mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS);
4327 return;
4328 }
4329
4330 // Gather the framesReleased counters for all active tracks,
4331 // and associate with the sink frames written out. We need
4332 // this to convert the sink timestamp to the track timestamp.
4333 bool kernelLocationUpdate = false;
4334 ExtendedTimestamp timestamp; // use private copy to fetch
4335
4336 // Always query HAL timestamp and update timestamp verifier. In standby or pause,
4337 // HAL may be draining some small duration buffered data for fade out.
4338 if (threadloop_getHalTimestamp_l(&timestamp) == OK) {
4339 mTimestampVerifier.add(timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL],
4340 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4341 mSampleRate);
4342
4343 if (isTimestampCorrectionEnabled()) {
4344 ALOGVV("TS_BEFORE: %d %lld %lld", id(),
4345 (long long)timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4346 (long long)timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]);
4347 auto correctedTimestamp = mTimestampVerifier.getLastCorrectedTimestamp();
4348 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4349 = correctedTimestamp.mFrames;
4350 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]
4351 = correctedTimestamp.mTimeNs;
4352 ALOGVV("TS_AFTER: %d %lld %lld", id(),
4353 (long long)timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4354 (long long)timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]);
4355
4356 // Note: Downstream latency only added if timestamp correction enabled.
4357 if (mDownstreamLatencyStatMs.getN() > 0) { // we have latency info.
4358 const int64_t newPosition =
4359 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4360 - int64_t(mDownstreamLatencyStatMs.getMean() * mSampleRate * 1e-3);
4361 // prevent retrograde
4362 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = max(
4363 newPosition,
4364 (mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4365 - mSuspendedFrames));
4366 }
4367 }
4368
4369 // We always fetch the timestamp here because often the downstream
4370 // sink will block while writing.
4371
4372 // We keep track of the last valid kernel position in case we are in underrun
4373 // and the normal mixer period is the same as the fast mixer period, or there
4374 // is some error from the HAL.
4375 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
4376 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
4377 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
4378 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
4379 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4380
4381 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
4382 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER];
4383 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
4384 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER];
4385 }
4386
4387 if (timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
4388 kernelLocationUpdate = true;
4389 } else {
4390 ALOGVV("getTimestamp error - no valid kernel position");
4391 }
4392
4393 // copy over kernel info
4394 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] =
4395 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4396 + mSuspendedFrames; // add frames discarded when suspended
4397 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] =
4398 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4399 } else {
4400 mTimestampVerifier.error();
4401 }
4402
4403 // mFramesWritten for non-offloaded tracks are contiguous
4404 // even after standby() is called. This is useful for the track frame
4405 // to sink frame mapping.
4406 bool serverLocationUpdate = false;
4407 if (mFramesWritten != mLastFramesWritten) {
4408 serverLocationUpdate = true;
4409 mLastFramesWritten = mFramesWritten;
4410 }
4411 // Only update timestamps if there is a meaningful change.
4412 // Either the kernel timestamp must be valid or we have written something.
4413 if (kernelLocationUpdate || serverLocationUpdate) {
4414 if (serverLocationUpdate) {
4415 // use the time before we called the HAL write - it is a bit more accurate
4416 // to when the server last read data than the current time here.
4417 //
4418 // If we haven't written anything, mLastIoBeginNs will be -1
4419 // and we use systemTime().
4420 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] = mFramesWritten;
4421 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = mLastIoBeginNs == -1
4422 ? systemTime() : mLastIoBeginNs;
4423 }
4424
4425 for (const sp<Track> &t : mActiveTracks) {
4426 if (!t->isFastTrack()) {
4427 t->updateTrackFrameInfo(
4428 t->mAudioTrackServerProxy->framesReleased(),
4429 mFramesWritten,
4430 mSampleRate,
4431 mTimestamp);
4432 }
4433 }
4434 }
4435
4436 if (audio_has_proportional_frames(mFormat)) {
4437 const double latencyMs = mTimestamp.getOutputServerLatencyMs(mSampleRate);
4438 if (latencyMs != 0.) { // note 0. means timestamp is empty.
4439 mLatencyMs.add(latencyMs);
4440 }
4441 }
4442#if 0
4443 // logFormat example
4444 if (z % 100 == 0) {
4445 timespec ts;
4446 clock_gettime(CLOCK_MONOTONIC, &ts);
4447 LOGT("This is an integer %d, this is a float %f, this is my "
4448 "pid %p %% %s %t", 42, 3.14, "and this is a timestamp", ts);
4449 LOGT("A deceptive null-terminated string %\0");
4450 }
4451 ++z;
4452#endif
4453}
4454
Eric Laurentbfb1b832013-01-07 09:53:42 -08004455// removeTracks_l() must be called with ThreadBase::mLock held
4456void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
4457{
Andy Hungfe726a62018-09-27 15:17:25 -07004458 for (const auto& track : tracksToRemove) {
4459 mActiveTracks.remove(track);
4460 ALOGV("%s(%d): removing track on session %d", __func__, track->id(), track->sessionId());
4461 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
4462 if (chain != 0) {
4463 ALOGV("%s(%d): stopping track on chain %p for session Id: %d",
4464 __func__, track->id(), chain.get(), track->sessionId());
4465 chain->decActiveTrackCnt();
4466 }
4467 // If an external client track, inform APM we're no longer active, and remove if needed.
4468 // We do this under lock so that the state is consistent if the Track is destroyed.
4469 if (track->isExternalTrack()) {
4470 AudioSystem::stopOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08004471 if (track->isTerminated()) {
Andy Hungfe726a62018-09-27 15:17:25 -07004472 AudioSystem::releaseOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08004473 }
4474 }
Andy Hungfe726a62018-09-27 15:17:25 -07004475 if (track->isTerminated()) {
4476 // remove from our tracks vector
4477 removeTrack_l(track);
4478 }
jiabineb3bda02020-06-30 14:07:03 -07004479 if (mHapticChannelCount > 0 &&
4480 ((track->channelMask() & AUDIO_CHANNEL_HAPTIC_ALL) != AUDIO_CHANNEL_NONE
4481 || (chain != nullptr && chain->containsHapticGeneratingEffect_l()))) {
jiabin57303cc2018-12-18 15:45:57 -08004482 mLock.unlock();
4483 // Unlock due to VibratorService will lock for this call and will
4484 // call Tracks.mute/unmute which also require thread's lock.
4485 AudioFlinger::onExternalVibrationStop(track->getExternalVibration());
4486 mLock.lock();
jiabine70bc7f2020-06-30 22:07:55 -07004487
4488 // When the track is stop, set the haptic intensity as MUTE
4489 // for the HapticGenerator effect.
4490 if (chain != nullptr) {
4491 chain->setHapticIntensity_l(track->id(), static_cast<int>(os::HapticScale::MUTE));
4492 }
jiabin245cdd92018-12-07 17:55:15 -08004493 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004494 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004495}
Eric Laurent81784c32012-11-19 14:55:58 -08004496
Eric Laurentaccc1472013-09-20 09:36:34 -07004497status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
4498{
4499 if (mNormalSink != 0) {
Andy Hung818e7a32016-02-16 18:08:07 -08004500 ExtendedTimestamp ets;
4501 status_t status = mNormalSink->getTimestamp(ets);
4502 if (status == NO_ERROR) {
4503 status = ets.getBestTimestamp(&timestamp);
4504 }
4505 return status;
Eric Laurentaccc1472013-09-20 09:36:34 -07004506 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004507 if ((mType == OFFLOAD || mType == DIRECT) && mOutput != NULL) {
Dean Wheatley12473e92021-03-18 23:00:55 +11004508 collectTimestamps_l();
4509 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] <= 0) {
4510 return INVALID_OPERATION;
Eric Laurentaccc1472013-09-20 09:36:34 -07004511 }
Dean Wheatley12473e92021-03-18 23:00:55 +11004512 timestamp.mPosition = mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
4513 const int64_t timeNs = mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4514 timestamp.mTime.tv_sec = timeNs / NANOS_PER_SECOND;
4515 timestamp.mTime.tv_nsec = timeNs - (timestamp.mTime.tv_sec * NANOS_PER_SECOND);
4516 return NO_ERROR;
Eric Laurentaccc1472013-09-20 09:36:34 -07004517 }
4518 return INVALID_OPERATION;
4519}
Eric Laurent1c333e22014-05-20 10:48:17 -07004520
Eric Laurenteab90452019-06-24 15:17:46 -07004521// For dedicated VoIP outputs, let the HAL apply the stream volume. Track volume is
4522// still applied by the mixer.
4523// All tracks attached to a mixer with flag VOIP_RX are tied to the same
4524// stream type STREAM_VOICE_CALL so this will only change the HAL volume once even
4525// if more than one track are active
4526status_t AudioFlinger::PlaybackThread::handleVoipVolume_l(float *volume)
4527{
4528 status_t result = NO_ERROR;
4529 if ((mOutput->flags & AUDIO_OUTPUT_FLAG_VOIP_RX) != 0) {
4530 if (*volume != mLeftVolFloat) {
4531 result = mOutput->stream->setVolume(*volume, *volume);
4532 ALOGE_IF(result != OK,
4533 "Error when setting output stream volume: %d", result);
4534 if (result == NO_ERROR) {
4535 mLeftVolFloat = *volume;
4536 }
4537 }
4538 // if stream volume was successfully sent to the HAL, mLeftVolFloat == v here and we
4539 // remove stream volume contribution from software volume.
4540 if (mLeftVolFloat == *volume) {
4541 *volume = 1.0f;
4542 }
4543 }
4544 return result;
4545}
4546
Eric Laurent054d9d32015-04-24 08:48:48 -07004547status_t AudioFlinger::MixerThread::createAudioPatch_l(const struct audio_patch *patch,
4548 audio_patch_handle_t *handle)
4549{
Andy Hungf60abce2016-08-26 11:37:54 -07004550 status_t status;
4551 if (property_get_bool("af.patch_park", false /* default_value */)) {
4552 // Park FastMixer to avoid potential DOS issues with writing to the HAL
4553 // or if HAL does not properly lock against access.
4554 AutoPark<FastMixer> park(mFastMixer);
4555 status = PlaybackThread::createAudioPatch_l(patch, handle);
4556 } else {
4557 status = PlaybackThread::createAudioPatch_l(patch, handle);
4558 }
Eric Laurent054d9d32015-04-24 08:48:48 -07004559 return status;
4560}
4561
Eric Laurent1c333e22014-05-20 10:48:17 -07004562status_t AudioFlinger::PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
4563 audio_patch_handle_t *handle)
4564{
4565 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07004566
4567 // store new device and send to effects
4568 audio_devices_t type = AUDIO_DEVICE_NONE;
jiabinc52b1ff2019-10-31 17:20:42 -07004569 AudioDeviceTypeAddrVector deviceTypeAddrs;
Eric Laurent054d9d32015-04-24 08:48:48 -07004570 for (unsigned int i = 0; i < patch->num_sinks; i++) {
jiabinc52b1ff2019-10-31 17:20:42 -07004571 LOG_ALWAYS_FATAL_IF(popcount(patch->sinks[i].ext.device.type) > 1
4572 && !mOutput->audioHwDev->supportsAudioPatches(),
4573 "Enumerated device type(%#x) must not be used "
4574 "as it does not support audio patches",
4575 patch->sinks[i].ext.device.type);
Mikhail Naganov55773032020-10-01 15:08:13 -07004576 type = static_cast<audio_devices_t>(type | patch->sinks[i].ext.device.type);
jiabinc52b1ff2019-10-31 17:20:42 -07004577 deviceTypeAddrs.push_back(AudioDeviceTypeAddr(patch->sinks[i].ext.device.type,
4578 patch->sinks[i].ext.device.address));
Eric Laurent054d9d32015-04-24 08:48:48 -07004579 }
4580
François Gaffie0c280aa2018-07-25 10:02:15 +02004581 audio_port_handle_t sinkPortId = patch->sinks[0].id;
Eric Laurent054d9d32015-04-24 08:48:48 -07004582#ifdef ADD_BATTERY_DATA
4583 // when changing the audio output device, call addBatteryData to notify
4584 // the change
jiabinc52b1ff2019-10-31 17:20:42 -07004585 if (outDeviceTypes() != deviceTypes) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004586 uint32_t params = 0;
4587 // check whether speaker is on
jiabinc52b1ff2019-10-31 17:20:42 -07004588 if (deviceTypes.count(AUDIO_DEVICE_OUT_SPEAKER) > 0) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004589 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent1c333e22014-05-20 10:48:17 -07004590 }
4591
Eric Laurent054d9d32015-04-24 08:48:48 -07004592 // check if any other device (except speaker) is on
jiabinc52b1ff2019-10-31 17:20:42 -07004593 if (!isSingleDeviceType(deviceTypes, AUDIO_DEVICE_OUT_SPEAKER)) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004594 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
4595 }
4596
4597 if (params != 0) {
4598 addBatteryData(params);
4599 }
4600 }
4601#endif
4602
4603 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08004604 mEffectChains[i]->setDevices_l(deviceTypeAddrs);
Eric Laurent054d9d32015-04-24 08:48:48 -07004605 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07004606
jiabinc52b1ff2019-10-31 17:20:42 -07004607 // mPatch.num_sinks is not set when the thread is created so that
4608 // the first patch creation triggers an ioConfigChanged callback
4609 bool configChanged = (mPatch.num_sinks == 0) ||
4610 (mPatch.sinks[0].id != sinkPortId);
Eric Laurent296fb132015-05-01 11:38:42 -07004611 mPatch = *patch;
jiabinc52b1ff2019-10-31 17:20:42 -07004612 mOutDeviceTypeAddrs = deviceTypeAddrs;
jiabin0a957d32020-04-29 10:56:20 -07004613 checkSilentMode_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07004614
Mikhail Naganov9ee05402016-10-13 15:58:17 -07004615 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07004616 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
4617 status = hwDevice->createAudioPatch(patch->num_sources,
4618 patch->sources,
4619 patch->num_sinks,
4620 patch->sinks,
4621 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07004622 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08004623 status = mOutput->stream->legacyCreateAudioPatch(patch->sinks[0], std::nullopt, type);
Eric Laurent054d9d32015-04-24 08:48:48 -07004624 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07004625 }
Andy Hungc2b11cb2020-04-22 09:04:01 -07004626 const std::string patchSinksAsString = patchSinksToString(patch);
Andy Hungcf10d742020-04-28 15:38:24 -07004627
4628 mThreadMetrics.logEndInterval();
Andy Hungea840382020-05-05 21:50:17 -07004629 mThreadMetrics.logCreatePatch(/* inDevices */ {}, patchSinksAsString);
Andy Hungcf10d742020-04-28 15:38:24 -07004630 mThreadMetrics.logBeginInterval();
Andy Hungc2b11cb2020-04-22 09:04:01 -07004631 // also dispatch to active AudioTracks for MediaMetrics
4632 for (const auto &track : mActiveTracks) {
4633 track->logEndInterval();
4634 track->logBeginInterval(patchSinksAsString);
4635 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08004636
Eric Laurente8726fe2015-06-26 09:39:24 -07004637 if (configChanged) {
4638 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
4639 }
Eric Laurentdda206a2022-07-08 17:28:35 +02004640 // Force meteadata update after a route change
4641 mActiveTracks.setHasChanged();
4642
Eric Laurent1c333e22014-05-20 10:48:17 -07004643 return status;
4644}
4645
Eric Laurent054d9d32015-04-24 08:48:48 -07004646status_t AudioFlinger::MixerThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
4647{
Andy Hungf60abce2016-08-26 11:37:54 -07004648 status_t status;
4649 if (property_get_bool("af.patch_park", false /* default_value */)) {
4650 // Park FastMixer to avoid potential DOS issues with writing to the HAL
4651 // or if HAL does not properly lock against access.
4652 AutoPark<FastMixer> park(mFastMixer);
4653 status = PlaybackThread::releaseAudioPatch_l(handle);
4654 } else {
4655 status = PlaybackThread::releaseAudioPatch_l(handle);
4656 }
Eric Laurent054d9d32015-04-24 08:48:48 -07004657 return status;
4658}
4659
Eric Laurent1c333e22014-05-20 10:48:17 -07004660status_t AudioFlinger::PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
4661{
4662 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07004663
jiabinc52b1ff2019-10-31 17:20:42 -07004664 mPatch = audio_patch{};
4665 mOutDeviceTypeAddrs.clear();
Eric Laurent054d9d32015-04-24 08:48:48 -07004666
Mikhail Naganov9ee05402016-10-13 15:58:17 -07004667 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07004668 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
4669 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07004670 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08004671 status = mOutput->stream->legacyReleaseAudioPatch();
Eric Laurent1c333e22014-05-20 10:48:17 -07004672 }
Eric Laurentdda206a2022-07-08 17:28:35 +02004673 // Force meteadata update after a route change
4674 mActiveTracks.setHasChanged();
4675
Eric Laurent1c333e22014-05-20 10:48:17 -07004676 return status;
4677}
4678
Eric Laurent83b88082014-06-20 18:31:16 -07004679void AudioFlinger::PlaybackThread::addPatchTrack(const sp<PatchTrack>& track)
4680{
4681 Mutex::Autolock _l(mLock);
4682 mTracks.add(track);
4683}
4684
4685void AudioFlinger::PlaybackThread::deletePatchTrack(const sp<PatchTrack>& track)
4686{
4687 Mutex::Autolock _l(mLock);
4688 destroyTrack_l(track);
4689}
4690
Mikhail Naganovdc769682018-05-04 15:34:08 -07004691void AudioFlinger::PlaybackThread::toAudioPortConfig(struct audio_port_config *config)
Eric Laurent83b88082014-06-20 18:31:16 -07004692{
Mikhail Naganovdc769682018-05-04 15:34:08 -07004693 ThreadBase::toAudioPortConfig(config);
Eric Laurent83b88082014-06-20 18:31:16 -07004694 config->role = AUDIO_PORT_ROLE_SOURCE;
4695 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
4696 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07004697 if (mOutput && mOutput->flags != AUDIO_OUTPUT_FLAG_NONE) {
4698 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
4699 config->flags.output = mOutput->flags;
4700 }
Eric Laurent83b88082014-06-20 18:31:16 -07004701}
4702
Eric Laurent81784c32012-11-19 14:55:58 -08004703// ----------------------------------------------------------------------------
4704
4705AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Eric Laurentf1f22e72021-07-13 14:04:14 +02004706 audio_io_handle_t id, bool systemReady, type_t type, audio_config_base_t *mixerConfig)
4707 : PlaybackThread(audioFlinger, output, id, type, systemReady, mixerConfig),
Eric Laurent81784c32012-11-19 14:55:58 -08004708 // mAudioMixer below
4709 // mFastMixer below
Andy Hung2ddee192015-12-18 17:34:44 -08004710 mFastMixerFutex(0),
4711 mMasterMono(false)
Eric Laurent81784c32012-11-19 14:55:58 -08004712 // mOutputSink below
4713 // mPipeSink below
4714 // mNormalSink below
4715{
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01004716 setMasterBalance(audioFlinger->getMasterBalance_l());
jiabinc52b1ff2019-10-31 17:20:42 -07004717 ALOGV("MixerThread() id=%d type=%d", id, type);
Glenn Kasten49f36ba2017-12-06 13:02:02 -08004718 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%#x, mFrameSize=%zu, "
Glenn Kastenc42e9b42016-03-21 11:35:03 -07004719 "mFrameCount=%zu, mNormalFrameCount=%zu",
Eric Laurent81784c32012-11-19 14:55:58 -08004720 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
4721 mNormalFrameCount);
4722 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
4723
Andy Hungfbfc3952015-01-15 13:33:51 -08004724 if (type == DUPLICATING) {
4725 // The Duplicating thread uses the AudioMixer and delivers data to OutputTracks
4726 // (downstream MixerThreads) in DuplicatingThread::threadLoop_write().
4727 // Do not create or use mFastMixer, mOutputSink, mPipeSink, or mNormalSink.
4728 return;
4729 }
Eric Laurent81784c32012-11-19 14:55:58 -08004730 // create an NBAIO sink for the HAL output stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07004731 mOutputSink = new AudioStreamOutSink(output->stream);
Eric Laurent81784c32012-11-19 14:55:58 -08004732 size_t numCounterOffers = 0;
jiabin245cdd92018-12-07 17:55:15 -08004733 const NBAIO_Format offers[1] = {Format_from_SR_C(
4734 mSampleRate, mChannelCount + mHapticChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07004735#if !LOG_NDEBUG
4736 ssize_t index =
4737#else
4738 (void)
4739#endif
4740 mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08004741 ALOG_ASSERT(index == 0);
4742
4743 // initialize fast mixer depending on configuration
4744 bool initFastMixer;
Eric Laurentb62d0362021-10-26 17:40:18 +02004745 if (mType == SPATIALIZER) {
Eric Laurent81784c32012-11-19 14:55:58 -08004746 initFastMixer = false;
Eric Laurentb62d0362021-10-26 17:40:18 +02004747 } else {
4748 switch (kUseFastMixer) {
4749 case FastMixer_Never:
4750 initFastMixer = false;
4751 break;
4752 case FastMixer_Always:
4753 initFastMixer = true;
4754 break;
4755 case FastMixer_Static:
4756 case FastMixer_Dynamic:
4757 initFastMixer = mFrameCount < mNormalFrameCount;
4758 break;
4759 }
4760 ALOGW_IF(initFastMixer == false && mFrameCount < mNormalFrameCount,
4761 "FastMixer is preferred for this sink as frameCount %zu is less than threshold %zu",
4762 mFrameCount, mNormalFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08004763 }
4764 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07004765 audio_format_t fastMixerFormat;
4766 if (mMixerBufferEnabled && mEffectBufferEnabled) {
4767 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
4768 } else {
4769 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
4770 }
4771 if (mFormat != fastMixerFormat) {
4772 // change our Sink format to accept our intermediate precision
4773 mFormat = fastMixerFormat;
4774 free(mSinkBuffer);
jiabin245cdd92018-12-07 17:55:15 -08004775 mFrameSize = audio_bytes_per_frame(mChannelCount + mHapticChannelCount, mFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07004776 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
4777 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
4778 }
Eric Laurent81784c32012-11-19 14:55:58 -08004779
4780 // create a MonoPipe to connect our submix to FastMixer
4781 NBAIO_Format format = mOutputSink->format();
Andy Hung8946a282018-04-19 20:04:56 -07004782
Andy Hung1258c1a2014-05-23 21:22:17 -07004783 // adjust format to match that of the Fast Mixer
Glenn Kasten49f36ba2017-12-06 13:02:02 -08004784 ALOGV("format changed from %#x to %#x", format.mFormat, fastMixerFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07004785 format.mFormat = fastMixerFormat;
4786 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
4787
Eric Laurent81784c32012-11-19 14:55:58 -08004788 // This pipe depth compensates for scheduling latency of the normal mixer thread.
4789 // When it wakes up after a maximum latency, it runs a few cycles quickly before
4790 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
4791 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
4792 const NBAIO_Format offers[1] = {format};
4793 size_t numCounterOffers = 0;
Andy Hung8946a282018-04-19 20:04:56 -07004794#if !LOG_NDEBUG
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07004795 ssize_t index =
4796#else
4797 (void)
4798#endif
4799 monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08004800 ALOG_ASSERT(index == 0);
4801 monoPipe->setAvgFrames((mScreenState & 1) ?
4802 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
4803 mPipeSink = monoPipe;
4804
Eric Laurent81784c32012-11-19 14:55:58 -08004805 // create fast mixer and configure it initially with just one fast track for our submix
Andy Hung8946a282018-04-19 20:04:56 -07004806 mFastMixer = new FastMixer(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08004807 FastMixerStateQueue *sq = mFastMixer->sq();
4808#ifdef STATE_QUEUE_DUMP
4809 sq->setObserverDump(&mStateQueueObserverDump);
4810 sq->setMutatorDump(&mStateQueueMutatorDump);
4811#endif
4812 FastMixerState *state = sq->begin();
4813 FastTrack *fastTrack = &state->mFastTracks[0];
4814 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
4815 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
4816 fastTrack->mVolumeProvider = NULL;
Mikhail Naganov55773032020-10-01 15:08:13 -07004817 fastTrack->mChannelMask = static_cast<audio_channel_mask_t>(
4818 mChannelMask | mHapticChannelMask); // mPipeSink channel mask for
4819 // audio to FastMixer
Andy Hunge8a1ced2014-05-09 15:02:21 -07004820 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
jiabin245cdd92018-12-07 17:55:15 -08004821 fastTrack->mHapticPlaybackEnabled = mHapticChannelMask != AUDIO_CHANNEL_NONE;
jiabine70bc7f2020-06-30 22:07:55 -07004822 fastTrack->mHapticIntensity = os::HapticScale::NONE;
Lais Andradebc3f37a2021-07-02 00:13:19 +01004823 fastTrack->mHapticMaxAmplitude = NAN;
Eric Laurent81784c32012-11-19 14:55:58 -08004824 fastTrack->mGeneration++;
4825 state->mFastTracksGen++;
4826 state->mTrackMask = 1;
4827 // fast mixer will use the HAL output sink
4828 state->mOutputSink = mOutputSink.get();
4829 state->mOutputSinkGen++;
4830 state->mFrameCount = mFrameCount;
jiabin245cdd92018-12-07 17:55:15 -08004831 // specify sink channel mask when haptic channel mask present as it can not
4832 // be calculated directly from channel count
4833 state->mSinkChannelMask = mHapticChannelMask == AUDIO_CHANNEL_NONE
Mikhail Naganov55773032020-10-01 15:08:13 -07004834 ? AUDIO_CHANNEL_NONE
4835 : static_cast<audio_channel_mask_t>(mChannelMask | mHapticChannelMask);
Eric Laurent81784c32012-11-19 14:55:58 -08004836 state->mCommand = FastMixerState::COLD_IDLE;
4837 // already done in constructor initialization list
4838 //mFastMixerFutex = 0;
4839 state->mColdFutexAddr = &mFastMixerFutex;
4840 state->mColdGen++;
4841 state->mDumpState = &mFastMixerDumpState;
Glenn Kasten9e58b552013-01-18 15:09:48 -08004842 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
4843 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08004844 sq->end();
4845 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
4846
Eric Tan0513b5d2018-09-17 10:32:48 -07004847 NBLog::thread_info_t info;
4848 info.id = mId;
4849 info.type = NBLog::FASTMIXER;
4850 mFastMixerNBLogWriter->log<NBLog::EVENT_THREAD_INFO>(info);
4851
Eric Laurent81784c32012-11-19 14:55:58 -08004852 // start the fast mixer
4853 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
4854 pid_t tid = mFastMixer->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07004855 sendPrioConfigEvent(getpid(), tid, kPriorityFastMixer, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08004856 stream()->setHalThreadPriority(kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08004857
4858#ifdef AUDIO_WATCHDOG
4859 // create and start the watchdog
4860 mAudioWatchdog = new AudioWatchdog();
4861 mAudioWatchdog->setDump(&mAudioWatchdogDump);
4862 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
4863 tid = mAudioWatchdog->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07004864 sendPrioConfigEvent(getpid(), tid, kPriorityFastMixer, false /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08004865#endif
Andy Hung8946a282018-04-19 20:04:56 -07004866 } else {
4867#ifdef TEE_SINK
4868 // Only use the MixerThread tee if there is no FastMixer.
4869 mTee.set(mOutputSink->format(), NBAIO_Tee::TEE_FLAG_OUTPUT_THREAD);
4870 mTee.setId(std::string("_") + std::to_string(mId) + "_M");
4871#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004872 }
4873
4874 switch (kUseFastMixer) {
4875 case FastMixer_Never:
4876 case FastMixer_Dynamic:
4877 mNormalSink = mOutputSink;
4878 break;
4879 case FastMixer_Always:
4880 mNormalSink = mPipeSink;
4881 break;
4882 case FastMixer_Static:
4883 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
4884 break;
4885 }
4886}
4887
4888AudioFlinger::MixerThread::~MixerThread()
4889{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004890 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004891 FastMixerStateQueue *sq = mFastMixer->sq();
4892 FastMixerState *state = sq->begin();
4893 if (state->mCommand == FastMixerState::COLD_IDLE) {
4894 int32_t old = android_atomic_inc(&mFastMixerFutex);
4895 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07004896 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08004897 }
4898 }
4899 state->mCommand = FastMixerState::EXIT;
4900 sq->end();
4901 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
4902 mFastMixer->join();
4903 // Though the fast mixer thread has exited, it's state queue is still valid.
4904 // We'll use that extract the final state which contains one remaining fast track
4905 // corresponding to our sub-mix.
4906 state = sq->begin();
4907 ALOG_ASSERT(state->mTrackMask == 1);
4908 FastTrack *fastTrack = &state->mFastTracks[0];
4909 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
4910 delete fastTrack->mBufferProvider;
4911 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004912 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08004913#ifdef AUDIO_WATCHDOG
4914 if (mAudioWatchdog != 0) {
4915 mAudioWatchdog->requestExit();
4916 mAudioWatchdog->requestExitAndWait();
4917 mAudioWatchdog.clear();
4918 }
4919#endif
4920 }
Glenn Kasten9e58b552013-01-18 15:09:48 -08004921 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08004922 delete mAudioMixer;
4923}
4924
4925
4926uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
4927{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004928 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004929 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
4930 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
4931 }
4932 return latency;
4933}
4934
Eric Laurentbfb1b832013-01-07 09:53:42 -08004935ssize_t AudioFlinger::MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08004936{
4937 // FIXME we should only do one push per cycle; confirm this is true
4938 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004939 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004940 FastMixerStateQueue *sq = mFastMixer->sq();
4941 FastMixerState *state = sq->begin();
4942 if (state->mCommand != FastMixerState::MIX_WRITE &&
4943 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
4944 if (state->mCommand == FastMixerState::COLD_IDLE) {
Eric Laurenta2ab4502015-09-09 12:25:51 -07004945
4946 // FIXME workaround for first HAL write being CPU bound on some devices
4947 ATRACE_BEGIN("write");
4948 mOutput->write((char *)mSinkBuffer, 0);
4949 ATRACE_END();
4950
Eric Laurent81784c32012-11-19 14:55:58 -08004951 int32_t old = android_atomic_inc(&mFastMixerFutex);
4952 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07004953 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08004954 }
4955#ifdef AUDIO_WATCHDOG
4956 if (mAudioWatchdog != 0) {
4957 mAudioWatchdog->resume();
4958 }
4959#endif
4960 }
4961 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kastend797a9d2015-03-02 14:19:25 -08004962#ifdef FAST_THREAD_STATISTICS
Glenn Kasten4182c4e2013-07-15 14:45:07 -07004963 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08004964 FastThreadDumpState::kSamplingNforLowRamDevice : FastThreadDumpState::kSamplingN);
Glenn Kastend797a9d2015-03-02 14:19:25 -08004965#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004966 sq->end();
4967 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
4968 if (kUseFastMixer == FastMixer_Dynamic) {
4969 mNormalSink = mPipeSink;
4970 }
4971 } else {
4972 sq->end(false /*didModify*/);
4973 }
4974 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004975 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08004976}
4977
4978void AudioFlinger::MixerThread::threadLoop_standby()
4979{
4980 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004981 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004982 FastMixerStateQueue *sq = mFastMixer->sq();
4983 FastMixerState *state = sq->begin();
4984 if (!(state->mCommand & FastMixerState::IDLE)) {
Andy Hung2148bf02016-11-28 19:01:02 -08004985 // Report any frames trapped in the Monopipe
4986 MonoPipe *monoPipe = (MonoPipe *)mPipeSink.get();
4987 const long long pipeFrames = monoPipe->maxFrames() - monoPipe->availableToWrite();
4988 mLocalLog.log("threadLoop_standby: framesWritten:%lld suspendedFrames:%lld "
4989 "monoPipeWritten:%lld monoPipeLeft:%lld",
4990 (long long)mFramesWritten, (long long)mSuspendedFrames,
4991 (long long)mPipeSink->framesWritten(), pipeFrames);
4992 mLocalLog.log("threadLoop_standby: %s", mTimestamp.toString().c_str());
4993
Eric Laurent81784c32012-11-19 14:55:58 -08004994 state->mCommand = FastMixerState::COLD_IDLE;
4995 state->mColdFutexAddr = &mFastMixerFutex;
4996 state->mColdGen++;
4997 mFastMixerFutex = 0;
4998 sq->end();
4999 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
5000 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
5001 if (kUseFastMixer == FastMixer_Dynamic) {
5002 mNormalSink = mOutputSink;
5003 }
5004#ifdef AUDIO_WATCHDOG
5005 if (mAudioWatchdog != 0) {
5006 mAudioWatchdog->pause();
5007 }
5008#endif
5009 } else {
5010 sq->end(false /*didModify*/);
5011 }
5012 }
5013 PlaybackThread::threadLoop_standby();
5014}
5015
Eric Laurentbfb1b832013-01-07 09:53:42 -08005016bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
5017{
5018 return false;
5019}
5020
5021bool AudioFlinger::PlaybackThread::shouldStandby_l()
5022{
5023 return !mStandby;
5024}
5025
5026bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
5027{
5028 Mutex::Autolock _l(mLock);
5029 return waitingAsyncCallback_l();
5030}
5031
Eric Laurent81784c32012-11-19 14:55:58 -08005032// shared by MIXER and DIRECT, overridden by DUPLICATING
5033void AudioFlinger::PlaybackThread::threadLoop_standby()
5034{
5035 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
Phil Burk062e67a2015-02-11 13:40:50 -08005036 mOutput->standby();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005037 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005038 // discard any pending drain or write ack by incrementing sequence
5039 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
5040 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005041 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005042 mCallbackThread->setWriteBlocked(mWriteAckSequence);
5043 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005044 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08005045 mHwPaused = false;
Eric Laurent68a40a82022-05-03 18:15:04 +02005046 setHalLatencyMode_l();
Eric Laurent81784c32012-11-19 14:55:58 -08005047}
5048
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08005049void AudioFlinger::PlaybackThread::onAddNewTrack_l()
5050{
5051 ALOGV("signal playback thread");
5052 broadcast_l();
5053}
5054
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005055void AudioFlinger::PlaybackThread::onAsyncError()
5056{
5057 for (int i = AUDIO_STREAM_SYSTEM; i < (int)AUDIO_STREAM_CNT; i++) {
5058 invalidateTracks((audio_stream_type_t)i);
5059 }
5060}
5061
Eric Laurent81784c32012-11-19 14:55:58 -08005062void AudioFlinger::MixerThread::threadLoop_mix()
5063{
Eric Laurent81784c32012-11-19 14:55:58 -08005064 // mix buffers...
Glenn Kastend79072e2016-01-06 08:41:20 -08005065 mAudioMixer->process();
Andy Hung25c2dac2014-02-27 14:56:00 -08005066 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005067 // increase sleep time progressively when application underrun condition clears.
5068 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
5069 // that a steady state of alternating ready/not ready conditions keeps the sleep time
5070 // such that we would underrun the audio HAL.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005071 if ((mSleepTimeUs == 0) && (sleepTimeShift > 0)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005072 sleepTimeShift--;
5073 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005074 mSleepTimeUs = 0;
5075 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08005076 //TODO: delay standby when effects have a tail
Glenn Kasten4c053ea2014-09-28 14:41:07 -07005077
Eric Laurent81784c32012-11-19 14:55:58 -08005078}
5079
5080void AudioFlinger::MixerThread::threadLoop_sleepTime()
5081{
5082 // If no tracks are ready, sleep once for the duration of an output
5083 // buffer size, then write 0s to the output
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005084 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005085 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Andy Hung06d13222018-05-03 20:13:31 -07005086 if (mPipeSink.get() != nullptr && mPipeSink == mNormalSink) {
5087 // Using the Monopipe availableToWrite, we estimate the
5088 // sleep time to retry for more data (before we underrun).
5089 MonoPipe *monoPipe = static_cast<MonoPipe *>(mPipeSink.get());
5090 const ssize_t availableToWrite = mPipeSink->availableToWrite();
5091 const size_t pipeFrames = monoPipe->maxFrames();
5092 const size_t framesLeft = pipeFrames - max(availableToWrite, 0);
5093 // HAL_framecount <= framesDelay ~ framesLeft / 2 <= Normal_Mixer_framecount
5094 const size_t framesDelay = std::min(
5095 mNormalFrameCount, max(framesLeft / 2, mFrameCount));
5096 ALOGV("pipeFrames:%zu framesLeft:%zu framesDelay:%zu",
5097 pipeFrames, framesLeft, framesDelay);
5098 mSleepTimeUs = framesDelay * MICROS_PER_SECOND / mSampleRate;
5099 } else {
5100 mSleepTimeUs = mActiveSleepTimeUs >> sleepTimeShift;
5101 if (mSleepTimeUs < kMinThreadSleepTimeUs) {
5102 mSleepTimeUs = kMinThreadSleepTimeUs;
5103 }
5104 // reduce sleep time in case of consecutive application underruns to avoid
5105 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
5106 // duration we would end up writing less data than needed by the audio HAL if
5107 // the condition persists.
5108 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
5109 sleepTimeShift++;
5110 }
Eric Laurent81784c32012-11-19 14:55:58 -08005111 }
5112 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005113 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005114 }
5115 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08005116 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
5117 // before effects processing or output.
5118 if (mMixerBufferValid) {
5119 memset(mMixerBuffer, 0, mMixerBufferSize);
Eric Laurent39095982021-08-24 18:29:27 +02005120 if (mType == SPATIALIZER) {
5121 memset(mSinkBuffer, 0, mSinkBufferSize);
5122 }
Andy Hung98ef9782014-03-04 14:46:50 -08005123 } else {
5124 memset(mSinkBuffer, 0, mSinkBufferSize);
5125 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005126 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005127 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
5128 "anticipated start");
5129 }
5130 // TODO add standby time extension fct of effect tail
5131}
5132
5133// prepareTracks_l() must be called with ThreadBase::mLock held
5134AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
5135 Vector< sp<Track> > *tracksToRemove)
5136{
Andy Hungc0691382018-09-12 18:01:57 -07005137 // clean up deleted track ids in AudioMixer before allocating new tracks
5138 (void)mTracks.processDeletedTrackIds([this](int trackId) {
5139 // for each trackId, destroy it in the AudioMixer
5140 if (mAudioMixer->exists(trackId)) {
5141 mAudioMixer->destroy(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08005142 }
5143 });
Andy Hungc0691382018-09-12 18:01:57 -07005144 mTracks.clearDeletedTrackIds();
Eric Laurent81784c32012-11-19 14:55:58 -08005145
5146 mixer_state mixerStatus = MIXER_IDLE;
5147 // find out which tracks need to be processed
5148 size_t count = mActiveTracks.size();
5149 size_t mixedTracks = 0;
5150 size_t tracksWithEffect = 0;
5151 // counts only _active_ fast tracks
5152 size_t fastTracks = 0;
5153 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
5154
5155 float masterVolume = mMasterVolume;
5156 bool masterMute = mMasterMute;
5157
5158 if (masterMute) {
5159 masterVolume = 0;
5160 }
5161 // Delegate master volume control to effect in output mix effect chain if needed
5162 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
5163 if (chain != 0) {
5164 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
5165 chain->setVolume_l(&v, &v);
5166 masterVolume = (float)((v + (1 << 23)) >> 24);
5167 chain.clear();
5168 }
5169
5170 // prepare a new state to push
5171 FastMixerStateQueue *sq = NULL;
5172 FastMixerState *state = NULL;
5173 bool didModify = false;
5174 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Andy Hungf2285312017-02-14 18:31:59 -08005175 bool coldIdle = false;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005176 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005177 sq = mFastMixer->sq();
5178 state = sq->begin();
Andy Hungf2285312017-02-14 18:31:59 -08005179 coldIdle = state->mCommand == FastMixerState::COLD_IDLE;
Eric Laurent81784c32012-11-19 14:55:58 -08005180 }
5181
Andy Hung69aed5f2014-02-25 17:24:40 -08005182 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08005183 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08005184
Andy Hungbd3b2b02018-05-21 10:53:11 -07005185 // DeferredOperations handles statistics after setting mixerStatus.
5186 class DeferredOperations {
5187 public:
Andy Hungea840382020-05-05 21:50:17 -07005188 DeferredOperations(mixer_state *mixerStatus, ThreadMetrics *threadMetrics)
5189 : mMixerStatus(mixerStatus)
5190 , mThreadMetrics(threadMetrics) {}
Andy Hungbd3b2b02018-05-21 10:53:11 -07005191
5192 // when leaving scope, tally frames properly.
5193 ~DeferredOperations() {
5194 // Tally underrun frames only if we are actually mixing (MIXER_TRACKS_READY)
5195 // because that is when the underrun occurs.
5196 // We do not distinguish between FastTracks and NormalTracks here.
Andy Hungea840382020-05-05 21:50:17 -07005197 size_t maxUnderrunFrames = 0;
Andy Hungb68f5eb2019-12-03 16:49:17 -08005198 if (*mMixerStatus == MIXER_TRACKS_READY && mUnderrunFrames.size() > 0) {
Andy Hungbd3b2b02018-05-21 10:53:11 -07005199 for (const auto &underrun : mUnderrunFrames) {
Andy Hungc2b11cb2020-04-22 09:04:01 -07005200 underrun.first->tallyUnderrunFrames(underrun.second);
Andy Hungea840382020-05-05 21:50:17 -07005201 maxUnderrunFrames = max(underrun.second, maxUnderrunFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07005202 }
5203 }
Andy Hungea840382020-05-05 21:50:17 -07005204 // send the max underrun frames for this mixer period
5205 mThreadMetrics->logUnderrunFrames(maxUnderrunFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07005206 }
5207
5208 // tallyUnderrunFrames() is called to update the track counters
5209 // with the number of underrun frames for a particular mixer period.
5210 // We defer tallying until we know the final mixer status.
5211 void tallyUnderrunFrames(sp<Track> track, size_t underrunFrames) {
5212 mUnderrunFrames.emplace_back(track, underrunFrames);
5213 }
5214
5215 private:
5216 const mixer_state * const mMixerStatus;
Andy Hungea840382020-05-05 21:50:17 -07005217 ThreadMetrics * const mThreadMetrics;
Andy Hungbd3b2b02018-05-21 10:53:11 -07005218 std::vector<std::pair<sp<Track>, size_t>> mUnderrunFrames;
Andy Hungea840382020-05-05 21:50:17 -07005219 } deferredOperations(&mixerStatus, &mThreadMetrics);
Andy Hungb68f5eb2019-12-03 16:49:17 -08005220 // implicit nested scope for variable capture
Andy Hungbd3b2b02018-05-21 10:53:11 -07005221
jiabin245cdd92018-12-07 17:55:15 -08005222 bool noFastHapticTrack = true;
Eric Laurent81784c32012-11-19 14:55:58 -08005223 for (size_t i=0 ; i<count ; i++) {
Andy Hungdae27702016-10-31 14:01:16 -07005224 const sp<Track> t = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08005225
5226 // this const just means the local variable doesn't change
5227 Track* const track = t.get();
5228
5229 // process fast tracks
5230 if (track->isFastTrack()) {
Andy Hungae22b482019-05-09 15:38:55 -07005231 LOG_ALWAYS_FATAL_IF(mFastMixer.get() == nullptr,
5232 "%s(%d): FastTrack(%d) present without FastMixer",
5233 __func__, id(), track->id());
5234
jiabin245cdd92018-12-07 17:55:15 -08005235 if (track->getHapticPlaybackEnabled()) {
5236 noFastHapticTrack = false;
5237 }
Eric Laurent81784c32012-11-19 14:55:58 -08005238
5239 // It's theoretically possible (though unlikely) for a fast track to be created
5240 // and then removed within the same normal mix cycle. This is not a problem, as
5241 // the track never becomes active so it's fast mixer slot is never touched.
5242 // The converse, of removing an (active) track and then creating a new track
5243 // at the identical fast mixer slot within the same normal mix cycle,
5244 // is impossible because the slot isn't marked available until the end of each cycle.
5245 int j = track->mFastIndex;
Glenn Kastendc2c50b2016-04-21 08:13:14 -07005246 ALOG_ASSERT(0 < j && j < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08005247 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
5248 FastTrack *fastTrack = &state->mFastTracks[j];
5249
5250 // Determine whether the track is currently in underrun condition,
5251 // and whether it had a recent underrun.
5252 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
5253 FastTrackUnderruns underruns = ftDump->mUnderruns;
5254 uint32_t recentFull = (underruns.mBitFields.mFull -
5255 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
5256 uint32_t recentPartial = (underruns.mBitFields.mPartial -
5257 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
5258 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
5259 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
5260 uint32_t recentUnderruns = recentPartial + recentEmpty;
5261 track->mObservedUnderruns = underruns;
5262 // don't count underruns that occur while stopping or pausing
5263 // or stopped which can occur when flush() is called while active
Andy Hungbd3b2b02018-05-21 10:53:11 -07005264 size_t underrunFrames = 0;
Glenn Kasten82aaf942013-07-17 16:05:07 -07005265 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
5266 recentUnderruns > 0) {
5267 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
Andy Hungbd3b2b02018-05-21 10:53:11 -07005268 underrunFrames = recentUnderruns * mFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08005269 }
Andy Hungbd3b2b02018-05-21 10:53:11 -07005270 // Immediately account for FastTrack underruns.
5271 track->mAudioTrackServerProxy->tallyUnderrunFrames(underrunFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08005272
5273 // This is similar to the state machine for normal tracks,
5274 // with a few modifications for fast tracks.
5275 bool isActive = true;
5276 switch (track->mState) {
5277 case TrackBase::STOPPING_1:
5278 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08005279 if (recentUnderruns > 0 || track->isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -08005280 track->mState = TrackBase::STOPPING_2;
5281 }
5282 break;
5283 case TrackBase::PAUSING:
5284 // ramp down is not yet implemented
5285 track->setPaused();
5286 break;
5287 case TrackBase::RESUMING:
5288 // ramp up is not yet implemented
5289 track->mState = TrackBase::ACTIVE;
5290 break;
5291 case TrackBase::ACTIVE:
5292 if (recentFull > 0 || recentPartial > 0) {
5293 // track has provided at least some frames recently: reset retry count
5294 track->mRetryCount = kMaxTrackRetries;
5295 }
5296 if (recentUnderruns == 0) {
5297 // no recent underruns: stay active
5298 break;
5299 }
5300 // there has recently been an underrun of some kind
5301 if (track->sharedBuffer() == 0) {
5302 // were any of the recent underruns "empty" (no frames available)?
5303 if (recentEmpty == 0) {
5304 // no, then ignore the partial underruns as they are allowed indefinitely
5305 break;
5306 }
5307 // there has recently been an "empty" underrun: decrement the retry counter
5308 if (--(track->mRetryCount) > 0) {
5309 break;
5310 }
5311 // indicate to client process that the track was disabled because of underrun;
5312 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08005313 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08005314 // remove from active list, but state remains ACTIVE [confusing but true]
5315 isActive = false;
5316 break;
5317 }
Chih-Hung Hsieh2b487032018-09-13 14:16:02 -07005318 FALLTHROUGH_INTENDED;
Eric Laurent81784c32012-11-19 14:55:58 -08005319 case TrackBase::STOPPING_2:
5320 case TrackBase::PAUSED:
Eric Laurent81784c32012-11-19 14:55:58 -08005321 case TrackBase::STOPPED:
5322 case TrackBase::FLUSHED: // flush() while active
5323 // Check for presentation complete if track is inactive
5324 // We have consumed all the buffers of this track.
5325 // This would be incomplete if we auto-paused on underrun
5326 {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005327 uint32_t latency = 0;
5328 status_t result = mOutput->stream->getLatency(&latency);
5329 ALOGE_IF(result != OK,
5330 "Error when retrieving output stream latency: %d", result);
5331 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08005332 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005333 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
5334 // track stays in active list until presentation is complete
5335 break;
5336 }
5337 }
5338 if (track->isStopping_2()) {
5339 track->mState = TrackBase::STOPPED;
5340 }
5341 if (track->isStopped()) {
5342 // Can't reset directly, as fast mixer is still polling this track
5343 // track->reset();
5344 // So instead mark this track as needing to be reset after push with ack
5345 resetMask |= 1 << i;
5346 }
5347 isActive = false;
5348 break;
5349 case TrackBase::IDLE:
5350 default:
Andy Hung959b5b82021-09-24 10:46:20 -07005351 LOG_ALWAYS_FATAL("unexpected track state %d", (int)track->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08005352 }
5353
5354 if (isActive) {
5355 // was it previously inactive?
5356 if (!(state->mTrackMask & (1 << j))) {
5357 ExtendedAudioBufferProvider *eabp = track;
5358 VolumeProvider *vp = track;
5359 fastTrack->mBufferProvider = eabp;
5360 fastTrack->mVolumeProvider = vp;
Eric Laurent81784c32012-11-19 14:55:58 -08005361 fastTrack->mChannelMask = track->mChannelMask;
Andy Hunge8a1ced2014-05-09 15:02:21 -07005362 fastTrack->mFormat = track->mFormat;
jiabin245cdd92018-12-07 17:55:15 -08005363 fastTrack->mHapticPlaybackEnabled = track->getHapticPlaybackEnabled();
jiabin77270b82018-12-18 15:41:29 -08005364 fastTrack->mHapticIntensity = track->getHapticIntensity();
Lais Andradebc3f37a2021-07-02 00:13:19 +01005365 fastTrack->mHapticMaxAmplitude = track->getHapticMaxAmplitude();
Eric Laurent81784c32012-11-19 14:55:58 -08005366 fastTrack->mGeneration++;
5367 state->mTrackMask |= 1 << j;
5368 didModify = true;
5369 // no acknowledgement required for newly active tracks
5370 }
Kevin Rocard12381092018-04-11 09:19:59 -07005371 sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
Eric Laurenteab90452019-06-24 15:17:46 -07005372 float volume;
5373 if (track->isPlaybackRestricted() || mStreamTypes[track->streamType()].mute) {
5374 volume = 0.f;
5375 } else {
5376 volume = masterVolume * mStreamTypes[track->streamType()].volume;
5377 }
5378
5379 handleVoipVolume_l(&volume);
5380
Eric Laurent81784c32012-11-19 14:55:58 -08005381 // cache the combined master volume and stream type volume for fast mixer; this
5382 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005383 const float vh = track->getVolumeHandler()->getVolume(
Eric Laurenteab90452019-06-24 15:17:46 -07005384 proxy->framesReleased()).first;
5385 volume *= vh;
Kevin Rocardb0eeaf122018-04-11 08:30:16 -07005386 track->mCachedVolume = volume;
Kevin Rocard12381092018-04-11 09:19:59 -07005387 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Vlad Popae2f5aef2022-07-25 16:00:20 +02005388 float vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
5389 float vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
5390
5391 track->processMuteEvent_l(mAudioFlinger->getOrCreateAudioManager(),
5392 /*muteState=*/{masterVolume == 0.f,
5393 mStreamTypes[track->streamType()].volume == 0.f,
5394 mStreamTypes[track->streamType()].mute,
5395 track->isPlaybackRestricted(),
Vlad Popa436c9172022-08-02 15:25:08 +02005396 vlf == 0.f && vrf == 0.f,
5397 vh == 0.f});
Vlad Popae2f5aef2022-07-25 16:00:20 +02005398
5399 vlf *= volume;
5400 vrf *= volume;
Eric Laurenteab90452019-06-24 15:17:46 -07005401
Kevin Rocard12381092018-04-11 09:19:59 -07005402 track->setFinalVolume((vlf + vrf) / 2.f);
Eric Laurent81784c32012-11-19 14:55:58 -08005403 ++fastTracks;
5404 } else {
5405 // was it previously active?
5406 if (state->mTrackMask & (1 << j)) {
5407 fastTrack->mBufferProvider = NULL;
5408 fastTrack->mGeneration++;
5409 state->mTrackMask &= ~(1 << j);
5410 didModify = true;
5411 // If any fast tracks were removed, we must wait for acknowledgement
5412 // because we're about to decrement the last sp<> on those tracks.
5413 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
5414 } else {
Glenn Kastenbf848af2017-12-22 11:55:01 -08005415 // ALOGW rather than LOG_ALWAYS_FATAL because it seems there are cases where an
5416 // AudioTrack may start (which may not be with a start() but with a write()
5417 // after underrun) and immediately paused or released. In that case the
5418 // FastTrack state hasn't had time to update.
5419 // TODO Remove the ALOGW when this theory is confirmed.
5420 ALOGW("fast track %d should have been active; "
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08005421 "mState=%d, mTrackMask=%#x, recentUnderruns=%u, isShared=%d",
Andy Hung959b5b82021-09-24 10:46:20 -07005422 j, (int)track->mState, state->mTrackMask, recentUnderruns,
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08005423 track->sharedBuffer() != 0);
Glenn Kastenbf848af2017-12-22 11:55:01 -08005424 // Since the FastMixer state already has the track inactive, do nothing here.
Eric Laurent81784c32012-11-19 14:55:58 -08005425 }
5426 tracksToRemove->add(track);
5427 // Avoids a misleading display in dumpsys
5428 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
5429 }
jiabin245cdd92018-12-07 17:55:15 -08005430 if (fastTrack->mHapticPlaybackEnabled != track->getHapticPlaybackEnabled()) {
5431 fastTrack->mHapticPlaybackEnabled = track->getHapticPlaybackEnabled();
5432 didModify = true;
5433 }
Eric Laurent81784c32012-11-19 14:55:58 -08005434 continue;
5435 }
5436
5437 { // local variable scope to avoid goto warning
5438
5439 audio_track_cblk_t* cblk = track->cblk();
5440
5441 // The first time a track is added we wait
5442 // for all its buffers to be filled before processing it
Andy Hungc0691382018-09-12 18:01:57 -07005443 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08005444
5445 // if an active track doesn't exist in the AudioMixer, create it.
Andy Hungc0691382018-09-12 18:01:57 -07005446 // use the trackId as the AudioMixer name.
5447 if (!mAudioMixer->exists(trackId)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08005448 status_t status = mAudioMixer->create(
Andy Hungc0691382018-09-12 18:01:57 -07005449 trackId,
Andy Hung1bc088a2018-02-09 15:57:31 -08005450 track->mChannelMask,
5451 track->mFormat,
5452 track->mSessionId);
5453 if (status != OK) {
Andy Hungc0691382018-09-12 18:01:57 -07005454 ALOGW("%s(): AudioMixer cannot create track(%d)"
5455 " mask %#x, format %#x, sessionId %d",
5456 __func__, trackId,
5457 track->mChannelMask, track->mFormat, track->mSessionId);
Andy Hung1bc088a2018-02-09 15:57:31 -08005458 tracksToRemove->add(track);
5459 track->invalidate(); // consider it dead.
5460 continue;
5461 }
5462 }
5463
Eric Laurent81784c32012-11-19 14:55:58 -08005464 // make sure that we have enough frames to mix one full buffer.
5465 // enforce this condition only once to enable draining the buffer in case the client
5466 // app does not call stop() and relies on underrun to stop:
5467 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
5468 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005469 size_t desiredFrames;
Andy Hung8edb8dc2015-03-26 19:13:55 -07005470 const uint32_t sampleRate = track->mAudioTrackServerProxy->getSampleRate();
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07005471 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07005472
5473 desiredFrames = sourceFramesNeededWithTimestretch(
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07005474 sampleRate, mNormalFrameCount, mSampleRate, playbackRate.mSpeed);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005475 // TODO: ONLY USED FOR LEGACY RESAMPLERS, remove when they are removed.
5476 // add frames already consumed but not yet released by the resampler
5477 // because mAudioTrackServerProxy->framesReady() will include these frames
Andy Hungc0691382018-09-12 18:01:57 -07005478 desiredFrames += mAudioMixer->getUnreleasedFrames(trackId);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005479
Eric Laurent81784c32012-11-19 14:55:58 -08005480 uint32_t minFrames = 1;
5481 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
5482 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005483 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08005484 }
Eric Laurent13e4c962013-12-20 17:36:01 -08005485
5486 size_t framesReady = track->framesReady();
Glenn Kastene7754022014-10-31 12:11:26 -07005487 if (ATRACE_ENABLED()) {
5488 // I wish we had formatted trace names
Andy Hung1bc088a2018-02-09 15:57:31 -08005489 std::string traceName("nRdy");
Andy Hungc0691382018-09-12 18:01:57 -07005490 traceName += std::to_string(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08005491 ATRACE_INT(traceName.c_str(), framesReady);
Glenn Kastene7754022014-10-31 12:11:26 -07005492 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005493 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08005494 !track->isPaused() && !track->isTerminated())
5495 {
Andy Hungc0691382018-09-12 18:01:57 -07005496 ALOGVV("track(%d) s=%08x [OK] on thread %p", trackId, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08005497
5498 mixedTracks++;
5499
Andy Hung69aed5f2014-02-25 17:24:40 -08005500 // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
5501 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08005502 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08005503 if (track->mainBuffer() != mSinkBuffer &&
5504 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08005505 if (mEffectBufferEnabled) {
5506 mEffectBufferValid = true; // Later can set directly.
5507 }
Eric Laurent81784c32012-11-19 14:55:58 -08005508 chain = getEffectChain_l(track->sessionId());
5509 // Delegate volume control to effect in track effect chain if needed
5510 if (chain != 0) {
5511 tracksWithEffect++;
5512 } else {
Andy Hungc0691382018-09-12 18:01:57 -07005513 ALOGW("prepareTracks_l(): track(%d) attached to effect but no chain found on "
Eric Laurent81784c32012-11-19 14:55:58 -08005514 "session %d",
Andy Hungc0691382018-09-12 18:01:57 -07005515 trackId, track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08005516 }
5517 }
5518
5519
5520 int param = AudioMixer::VOLUME;
5521 if (track->mFillingUpStatus == Track::FS_FILLED) {
5522 // no ramp for the first volume setting
5523 track->mFillingUpStatus = Track::FS_ACTIVE;
5524 if (track->mState == TrackBase::RESUMING) {
5525 track->mState = TrackBase::ACTIVE;
Revathi Uddaraju453bcb52017-08-14 14:19:40 +08005526 // If a new track is paused immediately after start, do not ramp on resume.
5527 if (cblk->mServer != 0) {
5528 param = AudioMixer::RAMP_VOLUME;
5529 }
Eric Laurent81784c32012-11-19 14:55:58 -08005530 }
Andy Hungc0691382018-09-12 18:01:57 -07005531 mAudioMixer->setParameter(trackId, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Eric Laurent7c29ec92017-09-20 17:54:22 -07005532 mLeftVolFloat = -1.0;
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005533 // FIXME should not make a decision based on mServer
5534 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005535 // If the track is stopped before the first frame was mixed,
5536 // do not apply ramp
5537 param = AudioMixer::RAMP_VOLUME;
5538 }
5539
5540 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07005541 uint32_t vl, vr; // in U8.24 integer format
5542 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Eric Laurent7c29ec92017-09-20 17:54:22 -07005543 // read original volumes with volume control
Eric Laurenteab90452019-06-24 15:17:46 -07005544 float v = masterVolume * mStreamTypes[track->streamType()].volume;
Andy Hung333ab962019-05-28 20:23:35 -07005545 // Always fetch volumeshaper volume to ensure state is updated.
5546 const sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
5547 const float vh = track->getVolumeHandler()->getVolume(
5548 track->mAudioTrackServerProxy->framesReleased()).first;
Eric Laurent7c29ec92017-09-20 17:54:22 -07005549
Eric Laurenteab90452019-06-24 15:17:46 -07005550 if (mStreamTypes[track->streamType()].mute || track->isPlaybackRestricted()) {
5551 v = 0;
5552 }
5553
5554 handleVoipVolume_l(&v);
5555
5556 if (track->isPausing()) {
Andy Hung6be49402014-05-30 10:42:03 -07005557 vl = vr = 0;
5558 vlf = vrf = vaf = 0.;
Eric Laurenteab90452019-06-24 15:17:46 -07005559 track->setPaused();
Eric Laurent81784c32012-11-19 14:55:58 -08005560 } else {
Glenn Kastenc56f3422014-03-21 17:53:17 -07005561 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07005562 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
5563 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08005564 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07005565 if (vlf > GAIN_FLOAT_UNITY) {
5566 ALOGV("Track left volume out of range: %.3g", vlf);
5567 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08005568 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07005569 if (vrf > GAIN_FLOAT_UNITY) {
5570 ALOGV("Track right volume out of range: %.3g", vrf);
5571 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08005572 }
Vlad Popae2f5aef2022-07-25 16:00:20 +02005573
5574 track->processMuteEvent_l(mAudioFlinger->getOrCreateAudioManager(),
5575 /*muteState=*/{masterVolume == 0.f,
5576 mStreamTypes[track->streamType()].volume == 0.f,
5577 mStreamTypes[track->streamType()].mute,
5578 track->isPlaybackRestricted(),
Vlad Popa436c9172022-08-02 15:25:08 +02005579 vlf == 0.f && vrf == 0.f,
5580 vh == 0.f});
Vlad Popae2f5aef2022-07-25 16:00:20 +02005581
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005582 // now apply the master volume and stream type volume and shaper volume
5583 vlf *= v * vh;
5584 vrf *= v * vh;
Eric Laurent81784c32012-11-19 14:55:58 -08005585 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07005586 // then derive vl and vr as U8.24 versions for the effect chain
5587 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
5588 vl = (uint32_t) (scaleto8_24 * vlf);
5589 vr = (uint32_t) (scaleto8_24 * vrf);
5590 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08005591 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08005592 // send level comes from shared memory and so may be corrupt
5593 if (sendLevel > MAX_GAIN_INT) {
5594 ALOGV("Track send level out of range: %04X", sendLevel);
5595 sendLevel = MAX_GAIN_INT;
5596 }
Andy Hung6be49402014-05-30 10:42:03 -07005597 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
5598 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08005599 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005600
Kevin Rocard12381092018-04-11 09:19:59 -07005601 track->setFinalVolume((vrf + vlf) / 2.f);
5602
Eric Laurent81784c32012-11-19 14:55:58 -08005603 // Delegate volume control to effect in track effect chain if needed
5604 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
5605 // Do not ramp volume if volume is controlled by effect
5606 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08005607 // Update remaining floating point volume levels
5608 vlf = (float)vl / (1 << 24);
5609 vrf = (float)vr / (1 << 24);
Eric Laurent81784c32012-11-19 14:55:58 -08005610 track->mHasVolumeController = true;
5611 } else {
5612 // force no volume ramp when volume controller was just disabled or removed
5613 // from effect chain to avoid volume spike
5614 if (track->mHasVolumeController) {
5615 param = AudioMixer::VOLUME;
5616 }
5617 track->mHasVolumeController = false;
5618 }
5619
Eric Laurent81784c32012-11-19 14:55:58 -08005620 // XXX: these things DON'T need to be done each time
Andy Hungc0691382018-09-12 18:01:57 -07005621 mAudioMixer->setBufferProvider(trackId, track);
5622 mAudioMixer->enable(trackId);
Eric Laurent81784c32012-11-19 14:55:58 -08005623
Andy Hungc0691382018-09-12 18:01:57 -07005624 mAudioMixer->setParameter(trackId, param, AudioMixer::VOLUME0, &vlf);
5625 mAudioMixer->setParameter(trackId, param, AudioMixer::VOLUME1, &vrf);
5626 mAudioMixer->setParameter(trackId, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08005627 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005628 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005629 AudioMixer::TRACK,
5630 AudioMixer::FORMAT, (void *)track->format());
5631 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005632 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005633 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00005634 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Eric Laurent39095982021-08-24 18:29:27 +02005635
Eric Laurentb0a7bc92022-04-05 15:06:08 +02005636 if (mType == SPATIALIZER && !track->isSpatialized()) {
Eric Laurent39095982021-08-24 18:29:27 +02005637 mAudioMixer->setParameter(
5638 trackId,
5639 AudioMixer::TRACK,
5640 AudioMixer::MIXER_CHANNEL_MASK,
5641 (void *)(uintptr_t)(mChannelMask | mHapticChannelMask));
5642 } else {
5643 mAudioMixer->setParameter(
5644 trackId,
5645 AudioMixer::TRACK,
5646 AudioMixer::MIXER_CHANNEL_MASK,
5647 (void *)(uintptr_t)(mMixerChannelMask | mHapticChannelMask));
5648 }
5649
Glenn Kastene3aa6592012-12-04 12:22:46 -08005650 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07005651 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Andy Hung333ab962019-05-28 20:23:35 -07005652 uint32_t reqSampleRate = proxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08005653 if (reqSampleRate == 0) {
5654 reqSampleRate = mSampleRate;
5655 } else if (reqSampleRate > maxSampleRate) {
5656 reqSampleRate = maxSampleRate;
5657 }
Eric Laurent81784c32012-11-19 14:55:58 -08005658 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005659 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005660 AudioMixer::RESAMPLE,
5661 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00005662 (void *)(uintptr_t)reqSampleRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005663
Andy Hung333ab962019-05-28 20:23:35 -07005664 AudioPlaybackRate playbackRate = proxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07005665 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005666 trackId,
Andy Hung8edb8dc2015-03-26 19:13:55 -07005667 AudioMixer::TIMESTRETCH,
5668 AudioMixer::PLAYBACK_RATE,
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07005669 &playbackRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005670
Andy Hung69aed5f2014-02-25 17:24:40 -08005671 /*
5672 * Select the appropriate output buffer for the track.
5673 *
Andy Hung98ef9782014-03-04 14:46:50 -08005674 * Tracks with effects go into their own effects chain buffer
5675 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08005676 *
5677 * Other tracks can use mMixerBuffer for higher precision
5678 * channel accumulation. If this buffer is enabled
5679 * (mMixerBufferEnabled true), then selected tracks will accumulate
5680 * into it.
5681 *
5682 */
5683 if (mMixerBufferEnabled
5684 && (track->mainBuffer() == mSinkBuffer
5685 || track->mainBuffer() == mMixerBuffer)) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02005686 if (mType == SPATIALIZER && !track->isSpatialized()) {
Eric Laurent39095982021-08-24 18:29:27 +02005687 mAudioMixer->setParameter(
5688 trackId,
5689 AudioMixer::TRACK,
Eric Laurentb62d0362021-10-26 17:40:18 +02005690 AudioMixer::MIXER_FORMAT, (void *)mEffectBufferFormat);
Eric Laurent39095982021-08-24 18:29:27 +02005691 mAudioMixer->setParameter(
5692 trackId,
5693 AudioMixer::TRACK,
Eric Laurentb62d0362021-10-26 17:40:18 +02005694 AudioMixer::MAIN_BUFFER, (void *)mPostSpatializerBuffer);
Eric Laurent39095982021-08-24 18:29:27 +02005695 } else {
5696 mAudioMixer->setParameter(
5697 trackId,
5698 AudioMixer::TRACK,
5699 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
5700 mAudioMixer->setParameter(
5701 trackId,
5702 AudioMixer::TRACK,
5703 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
5704 // TODO: override track->mainBuffer()?
5705 mMixerBufferValid = true;
5706 }
Andy Hung69aed5f2014-02-25 17:24:40 -08005707 } else {
5708 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005709 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08005710 AudioMixer::TRACK,
rago94a1ee82017-07-21 15:11:02 -07005711 AudioMixer::MIXER_FORMAT, (void *)EFFECT_BUFFER_FORMAT);
Andy Hung69aed5f2014-02-25 17:24:40 -08005712 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005713 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08005714 AudioMixer::TRACK,
5715 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
5716 }
Eric Laurent81784c32012-11-19 14:55:58 -08005717 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005718 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005719 AudioMixer::TRACK,
5720 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
jiabin245cdd92018-12-07 17:55:15 -08005721 mAudioMixer->setParameter(
5722 trackId,
5723 AudioMixer::TRACK,
5724 AudioMixer::HAPTIC_ENABLED, (void *)(uintptr_t)track->getHapticPlaybackEnabled());
jiabin77270b82018-12-18 15:41:29 -08005725 mAudioMixer->setParameter(
5726 trackId,
5727 AudioMixer::TRACK,
5728 AudioMixer::HAPTIC_INTENSITY, (void *)(uintptr_t)track->getHapticIntensity());
Lais Andradebc3f37a2021-07-02 00:13:19 +01005729 mAudioMixer->setParameter(
5730 trackId,
5731 AudioMixer::TRACK,
5732 AudioMixer::HAPTIC_MAX_AMPLITUDE, (void *)(&(track->mHapticMaxAmplitude)));
Eric Laurent81784c32012-11-19 14:55:58 -08005733
5734 // reset retry count
5735 track->mRetryCount = kMaxTrackRetries;
5736
5737 // If one track is ready, set the mixer ready if:
5738 // - the mixer was not ready during previous round OR
5739 // - no other track is not ready
5740 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
5741 mixerStatus != MIXER_TRACKS_ENABLED) {
5742 mixerStatus = MIXER_TRACKS_READY;
5743 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08005744
5745 // Enable the next few lines to instrument a test for underrun log handling.
5746 // TODO: Remove when we have a better way of testing the underrun log.
5747#if 0
5748 static int i;
5749 if ((++i & 0xf) == 0) {
5750 deferredOperations.tallyUnderrunFrames(track, 10 /* underrunFrames */);
5751 }
5752#endif
Eric Laurent81784c32012-11-19 14:55:58 -08005753 } else {
Andy Hungbd3b2b02018-05-21 10:53:11 -07005754 size_t underrunFrames = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005755 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Andy Hungb68f5eb2019-12-03 16:49:17 -08005756 ALOGV("track(%d) underrun, track state %s framesReady(%zu) < framesDesired(%zd)",
5757 trackId, track->getTrackStateAsString(), framesReady, desiredFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07005758 underrunFrames = desiredFrames;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005759 }
Andy Hungbd3b2b02018-05-21 10:53:11 -07005760 deferredOperations.tallyUnderrunFrames(track, underrunFrames);
Phil Burk2812d9e2016-01-04 10:34:30 -08005761
Eric Laurent81784c32012-11-19 14:55:58 -08005762 // clear effect chain input buffer if an active track underruns to avoid sending
5763 // previous audio buffer again to effects
5764 chain = getEffectChain_l(track->sessionId());
5765 if (chain != 0) {
5766 chain->clearInputBuffer();
5767 }
5768
Andy Hungc0691382018-09-12 18:01:57 -07005769 ALOGVV("track(%d) s=%08x [NOT READY] on thread %p", trackId, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08005770 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
5771 track->isStopped() || track->isPaused()) {
5772 // We have consumed all the buffers of this track.
5773 // Remove it from the list of active tracks.
5774 // TODO: use actual buffer filling status instead of latency when available from
5775 // audio HAL
5776 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08005777 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005778 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
5779 if (track->isStopped()) {
5780 track->reset();
5781 }
5782 tracksToRemove->add(track);
5783 }
5784 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08005785 // No buffers for this track. Give it a few chances to
5786 // fill a buffer, then remove it from active list.
5787 if (--(track->mRetryCount) <= 0) {
Andy Hungc0691382018-09-12 18:01:57 -07005788 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p",
5789 trackId, this);
Eric Laurent81784c32012-11-19 14:55:58 -08005790 tracksToRemove->add(track);
5791 // indicate to client process that the track was disabled because of underrun;
5792 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08005793 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08005794 // If one track is not ready, mark the mixer also not ready if:
5795 // - the mixer was ready during previous round OR
5796 // - no other track is ready
5797 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
5798 mixerStatus != MIXER_TRACKS_READY) {
5799 mixerStatus = MIXER_TRACKS_ENABLED;
5800 }
5801 }
Andy Hungc0691382018-09-12 18:01:57 -07005802 mAudioMixer->disable(trackId);
Eric Laurent81784c32012-11-19 14:55:58 -08005803 }
5804
5805 } // local variable scope to avoid goto warning
Eric Laurent81784c32012-11-19 14:55:58 -08005806
5807 }
5808
jiabin245cdd92018-12-07 17:55:15 -08005809 if (mHapticChannelMask != AUDIO_CHANNEL_NONE && sq != NULL) {
5810 // When there is no fast track playing haptic and FastMixer exists,
5811 // enabling the first FastTrack, which provides mixed data from normal
5812 // tracks, to play haptic data.
5813 FastTrack *fastTrack = &state->mFastTracks[0];
5814 if (fastTrack->mHapticPlaybackEnabled != noFastHapticTrack) {
5815 fastTrack->mHapticPlaybackEnabled = noFastHapticTrack;
5816 didModify = true;
5817 }
5818 }
5819
Eric Laurent81784c32012-11-19 14:55:58 -08005820 // Push the new FastMixer state if necessary
5821 bool pauseAudioWatchdog = false;
5822 if (didModify) {
5823 state->mFastTracksGen++;
5824 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
5825 if (kUseFastMixer == FastMixer_Dynamic &&
5826 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
5827 state->mCommand = FastMixerState::COLD_IDLE;
5828 state->mColdFutexAddr = &mFastMixerFutex;
5829 state->mColdGen++;
5830 mFastMixerFutex = 0;
5831 if (kUseFastMixer == FastMixer_Dynamic) {
5832 mNormalSink = mOutputSink;
5833 }
5834 // If we go into cold idle, need to wait for acknowledgement
5835 // so that fast mixer stops doing I/O.
5836 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
5837 pauseAudioWatchdog = true;
5838 }
Eric Laurent81784c32012-11-19 14:55:58 -08005839 }
5840 if (sq != NULL) {
5841 sq->end(didModify);
Andy Hungf2285312017-02-14 18:31:59 -08005842 // No need to block if the FastMixer is in COLD_IDLE as the FastThread
5843 // is not active. (We BLOCK_UNTIL_ACKED when entering COLD_IDLE
5844 // when bringing the output sink into standby.)
5845 //
5846 // We will get the latest FastMixer state when we come out of COLD_IDLE.
5847 //
5848 // This occurs with BT suspend when we idle the FastMixer with
5849 // active tracks, which may be added or removed.
5850 sq->push(coldIdle ? FastMixerStateQueue::BLOCK_NEVER : block);
Eric Laurent81784c32012-11-19 14:55:58 -08005851 }
5852#ifdef AUDIO_WATCHDOG
5853 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
5854 mAudioWatchdog->pause();
5855 }
5856#endif
5857
5858 // Now perform the deferred reset on fast tracks that have stopped
5859 while (resetMask != 0) {
5860 size_t i = __builtin_ctz(resetMask);
5861 ALOG_ASSERT(i < count);
5862 resetMask &= ~(1 << i);
Andy Hungdae27702016-10-31 14:01:16 -07005863 sp<Track> track = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08005864 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
5865 track->reset();
5866 }
5867
Andy Hung80d03d22018-04-10 10:32:11 -07005868 // Track destruction may occur outside of threadLoop once it is removed from active tracks.
5869 // Ensure the AudioMixer doesn't have a raw "buffer provider" pointer to the track if
5870 // it ceases to be active, to allow safe removal from the AudioMixer at the start
5871 // of prepareTracks_l(); this releases any outstanding buffer back to the track.
5872 // See also the implementation of destroyTrack_l().
5873 for (const auto &track : *tracksToRemove) {
Andy Hungc0691382018-09-12 18:01:57 -07005874 const int trackId = track->id();
5875 if (mAudioMixer->exists(trackId)) { // Normal tracks here, fast tracks in FastMixer.
5876 mAudioMixer->setBufferProvider(trackId, nullptr /* bufferProvider */);
Andy Hung80d03d22018-04-10 10:32:11 -07005877 }
5878 }
5879
Eric Laurent81784c32012-11-19 14:55:58 -08005880 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08005881 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08005882
Eric Laurentb3f315a2021-07-13 15:09:05 +02005883 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0 ||
5884 getEffectChain_l(AUDIO_SESSION_OUTPUT_STAGE) != 0) {
Eric Laurent97d547d2014-09-02 14:45:53 -07005885 mEffectBufferValid = true;
Marco Nelissenac302142014-10-20 13:15:38 -07005886 }
5887
5888 if (mEffectBufferValid) {
Marco Nelissen57088b52014-10-17 16:39:39 -07005889 // as long as there are effects we should clear the effects buffer, to avoid
5890 // passing a non-clean buffer to the effect chain
5891 memset(mEffectBuffer, 0, mEffectBufferSize);
Eric Laurentb62d0362021-10-26 17:40:18 +02005892 if (mType == SPATIALIZER) {
5893 memset(mPostSpatializerBuffer, 0, mPostSpatializerBufferSize);
5894 }
Eric Laurent97d547d2014-09-02 14:45:53 -07005895 }
Andy Hung69aed5f2014-02-25 17:24:40 -08005896 // sink or mix buffer must be cleared if all tracks are connected to an
5897 // effect chain as in this case the mixer will not write to the sink or mix buffer
5898 // and track effects will accumulate into it
Eric Laurent39095982021-08-24 18:29:27 +02005899 // always clear sink buffer for spatializer output as the output of the spatializer
5900 // effect will be accumulated into it
5901 if ((mBytesRemaining == 0) && (((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
5902 (mixedTracks == 0 && fastTracks > 0)) || (mType == SPATIALIZER))) {
Eric Laurent81784c32012-11-19 14:55:58 -08005903 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08005904 if (mMixerBufferValid) {
5905 memset(mMixerBuffer, 0, mMixerBufferSize);
5906 // TODO: In testing, mSinkBuffer below need not be cleared because
5907 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
5908 // after mixing.
5909 //
5910 // To enforce this guarantee:
5911 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
5912 // (mixedTracks == 0 && fastTracks > 0))
5913 // must imply MIXER_TRACKS_READY.
5914 // Later, we may clear buffers regardless, and skip much of this logic.
5915 }
Andy Hung98ef9782014-03-04 14:46:50 -08005916 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07005917 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08005918 }
5919
5920 // if any fast tracks, then status is ready
5921 mMixerStatusIgnoringFastTracks = mixerStatus;
5922 if (fastTracks > 0) {
5923 mixerStatus = MIXER_TRACKS_READY;
5924 }
5925 return mixerStatus;
5926}
5927
Eric Laurentad7dd962016-09-22 12:38:37 -07005928// trackCountForUid_l() must be called with ThreadBase::mLock held
Andy Hung1bc088a2018-02-09 15:57:31 -08005929uint32_t AudioFlinger::PlaybackThread::trackCountForUid_l(uid_t uid) const
Eric Laurentad7dd962016-09-22 12:38:37 -07005930{
5931 uint32_t trackCount = 0;
5932 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hung1f12a8a2016-11-07 16:10:30 -08005933 if (mTracks[i]->uid() == uid) {
Eric Laurentad7dd962016-09-22 12:38:37 -07005934 trackCount++;
5935 }
5936 }
5937 return trackCount;
5938}
5939
Brian Lindahl65e90012022-07-27 18:01:07 +02005940bool AudioFlinger::PlaybackThread::IsTimestampAdvancing::check(AudioStreamOut * output)
ziyangch8f194f12021-12-01 13:48:04 -08005941{
Brian Lindahl65e90012022-07-27 18:01:07 +02005942 // Check the timestamp to see if it's advancing once every 150ms. If we check too frequently, we
5943 // could falsely detect that the frame position has stalled due to underrun because we haven't
5944 // given the Audio HAL enough time to update.
5945 const nsecs_t nowNs = systemTime();
5946 if (nowNs - mPreviousNs < mMinimumTimeBetweenChecksNs) {
5947 return mLatchedValue;
5948 }
5949 mPreviousNs = nowNs;
5950 mLatchedValue = false;
5951 // Determine if the presentation position is still advancing.
ziyangch8f194f12021-12-01 13:48:04 -08005952 uint64_t position = 0;
5953 struct timespec unused;
Brian Lindahl65e90012022-07-27 18:01:07 +02005954 const status_t ret = output->getPresentationPosition(&position, &unused);
ziyangch8f194f12021-12-01 13:48:04 -08005955 if (ret == NO_ERROR) {
Brian Lindahl65e90012022-07-27 18:01:07 +02005956 if (position != mPreviousPosition) {
5957 mPreviousPosition = position;
5958 mLatchedValue = true;
ziyangch8f194f12021-12-01 13:48:04 -08005959 }
5960 }
Brian Lindahl65e90012022-07-27 18:01:07 +02005961 return mLatchedValue;
5962}
5963
5964void AudioFlinger::PlaybackThread::IsTimestampAdvancing::clear()
5965{
5966 mLatchedValue = true;
5967 mPreviousPosition = 0;
5968 mPreviousNs = 0;
ziyangch8f194f12021-12-01 13:48:04 -08005969}
5970
Andy Hung1bc088a2018-02-09 15:57:31 -08005971// isTrackAllowed_l() must be called with ThreadBase::mLock held
5972bool AudioFlinger::MixerThread::isTrackAllowed_l(
5973 audio_channel_mask_t channelMask, audio_format_t format,
5974 audio_session_t sessionId, uid_t uid) const
Eric Laurent81784c32012-11-19 14:55:58 -08005975{
Andy Hung1bc088a2018-02-09 15:57:31 -08005976 if (!PlaybackThread::isTrackAllowed_l(channelMask, format, sessionId, uid)) {
5977 return false;
Eric Laurentad7dd962016-09-22 12:38:37 -07005978 }
Andy Hung1bc088a2018-02-09 15:57:31 -08005979 // Check validity as we don't call AudioMixer::create() here.
Mikhail Naganov7ad7a252019-07-30 14:42:32 -07005980 if (!mAudioMixer->isValidFormat(format)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08005981 ALOGW("%s: invalid format: %#x", __func__, format);
5982 return false;
5983 }
Mikhail Naganov7ad7a252019-07-30 14:42:32 -07005984 if (!mAudioMixer->isValidChannelMask(channelMask)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08005985 ALOGW("%s: invalid channelMask: %#x", __func__, channelMask);
5986 return false;
5987 }
5988 return true;
Eric Laurent81784c32012-11-19 14:55:58 -08005989}
5990
Eric Laurent10351942014-05-08 18:49:52 -07005991// checkForNewParameter_l() must be called with ThreadBase::mLock held
5992bool AudioFlinger::MixerThread::checkForNewParameter_l(const String8& keyValuePair,
5993 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08005994{
Eric Laurent81784c32012-11-19 14:55:58 -08005995 bool reconfig = false;
Eric Laurent10351942014-05-08 18:49:52 -07005996 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08005997
Glenn Kastenc05b8d72016-03-24 09:48:17 -07005998 AutoPark<FastMixer> park(mFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08005999
Eric Laurent10351942014-05-08 18:49:52 -07006000 AudioParameter param = AudioParameter(keyValuePair);
6001 int value;
6002 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
6003 reconfig = true;
6004 }
6005 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07006006 if (!isValidPcmSinkFormat((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07006007 status = BAD_VALUE;
6008 } else {
6009 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08006010 reconfig = true;
6011 }
Eric Laurent10351942014-05-08 18:49:52 -07006012 }
6013 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07006014 if (!isValidPcmSinkChannelMask((audio_channel_mask_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07006015 status = BAD_VALUE;
6016 } else {
6017 // no need to save value, since it's constant
6018 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006019 }
Eric Laurent10351942014-05-08 18:49:52 -07006020 }
6021 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6022 // do not accept frame count changes if tracks are open as the track buffer
6023 // size depends on frame count and correct behavior would not be guaranteed
6024 // if frame count is changed after track creation
6025 if (!mTracks.isEmpty()) {
6026 status = INVALID_OPERATION;
6027 } else {
6028 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006029 }
Eric Laurent10351942014-05-08 18:49:52 -07006030 }
6031 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07006032 LOG_FATAL("Should not set routing device in MixerThread");
Eric Laurent10351942014-05-08 18:49:52 -07006033 }
Eric Laurent81784c32012-11-19 14:55:58 -08006034
Eric Laurent10351942014-05-08 18:49:52 -07006035 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006036 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07006037 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08006038 mOutput->standby();
Andy Hungcf10d742020-04-28 15:38:24 -07006039 if (!mStandby) {
6040 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07006041 mThreadSnapshot.onEnd();
Andy Hungcf10d742020-04-28 15:38:24 -07006042 mStandby = true;
6043 }
Eric Laurent10351942014-05-08 18:49:52 -07006044 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006045 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent81784c32012-11-19 14:55:58 -08006046 }
Eric Laurent10351942014-05-08 18:49:52 -07006047 if (status == NO_ERROR && reconfig) {
6048 readOutputParameters_l();
6049 delete mAudioMixer;
6050 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
Andy Hung1bc088a2018-02-09 15:57:31 -08006051 for (const auto &track : mTracks) {
Andy Hungc0691382018-09-12 18:01:57 -07006052 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08006053 status_t status = mAudioMixer->create(
Andy Hungc0691382018-09-12 18:01:57 -07006054 trackId,
Andy Hung1bc088a2018-02-09 15:57:31 -08006055 track->mChannelMask,
6056 track->mFormat,
6057 track->mSessionId);
6058 ALOGW_IF(status != NO_ERROR,
Andy Hungc0691382018-09-12 18:01:57 -07006059 "%s(): AudioMixer cannot create track(%d)"
6060 " mask %#x, format %#x, sessionId %d",
Andy Hung1bc088a2018-02-09 15:57:31 -08006061 __func__,
Andy Hungc0691382018-09-12 18:01:57 -07006062 trackId, track->mChannelMask, track->mFormat, track->mSessionId);
Eric Laurent10351942014-05-08 18:49:52 -07006063 }
Eric Laurent73e26b62015-04-27 16:55:58 -07006064 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07006065 }
Eric Laurent81784c32012-11-19 14:55:58 -08006066 }
6067
Dean Wheatley68918102021-03-19 22:09:19 +11006068 return reconfig;
Eric Laurent81784c32012-11-19 14:55:58 -08006069}
6070
6071
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07006072void AudioFlinger::MixerThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -08006073{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07006074 PlaybackThread::dumpInternals_l(fd, args);
Andy Hung40eb1a12015-06-18 13:42:02 -07006075 dprintf(fd, " Thread throttle time (msecs): %u\n", mThreadThrottleTimeMs);
Andy Hung8ed196a2018-01-05 13:21:11 -08006076 dprintf(fd, " AudioMixer tracks: %s\n", mAudioMixer->trackNames().c_str());
Andy Hung2ddee192015-12-18 17:34:44 -08006077 dprintf(fd, " Master mono: %s\n", mMasterMono ? "on" : "off");
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006078 dprintf(fd, " Master balance: %f (%s)\n", mMasterBalance.load(),
6079 (hasFastMixer() ? std::to_string(mFastMixer->getMasterBalance())
6080 : mBalance.toString()).c_str());
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006081 if (hasFastMixer()) {
6082 dprintf(fd, " FastMixer thread %p tid=%d", mFastMixer.get(), mFastMixer->getTid());
6083
6084 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
6085 // while we are dumping it. It may be inconsistent, but it won't mutate!
6086 // This is a large object so we place it on the heap.
6087 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
Eric Tan2942a4e2018-09-12 17:41:27 -07006088 const std::unique_ptr<FastMixerDumpState> copy =
6089 std::make_unique<FastMixerDumpState>(mFastMixerDumpState);
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006090 copy->dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08006091
6092#ifdef STATE_QUEUE_DUMP
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006093 // Similar for state queue
6094 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
6095 observerCopy.dump(fd);
6096 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
6097 mutatorCopy.dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08006098#endif
6099
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006100#ifdef AUDIO_WATCHDOG
6101 if (mAudioWatchdog != 0) {
6102 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
6103 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
6104 wdCopy.dump(fd);
6105 }
6106#endif
6107
6108 } else {
6109 dprintf(fd, " No FastMixer\n");
6110 }
Eric Laurent81784c32012-11-19 14:55:58 -08006111}
6112
6113uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
6114{
6115 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
6116}
6117
6118uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
6119{
6120 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
6121}
6122
6123void AudioFlinger::MixerThread::cacheParameters_l()
6124{
6125 PlaybackThread::cacheParameters_l();
6126
6127 // FIXME: Relaxed timing because of a certain device that can't meet latency
6128 // Should be reduced to 2x after the vendor fixes the driver issue
6129 // increase threshold again due to low power audio mode. The way this warning
6130 // threshold is calculated and its usefulness should be reconsidered anyway.
6131 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
6132}
6133
6134// ----------------------------------------------------------------------------
6135
6136AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
jiabinc52b1ff2019-10-31 17:20:42 -07006137 AudioStreamOut* output, audio_io_handle_t id, ThreadBase::type_t type, bool systemReady)
6138 : PlaybackThread(audioFlinger, output, id, type, systemReady)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006139{
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006140 setMasterBalance(audioFlinger->getMasterBalance_l());
Eric Laurentbfb1b832013-01-07 09:53:42 -08006141}
6142
Eric Laurent81784c32012-11-19 14:55:58 -08006143AudioFlinger::DirectOutputThread::~DirectOutputThread()
6144{
6145}
6146
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07006147void AudioFlinger::DirectOutputThread::dumpInternals_l(int fd, const Vector<String16>& args)
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006148{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07006149 PlaybackThread::dumpInternals_l(fd, args);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006150 dprintf(fd, " Master balance: %f Left: %f Right: %f\n",
6151 mMasterBalance.load(), mMasterBalanceLeft, mMasterBalanceRight);
6152}
6153
6154void AudioFlinger::DirectOutputThread::setMasterBalance(float balance)
6155{
6156 Mutex::Autolock _l(mLock);
6157 if (mMasterBalance != balance) {
6158 mMasterBalance.store(balance);
6159 mBalance.computeStereoBalance(balance, &mMasterBalanceLeft, &mMasterBalanceRight);
6160 broadcast_l();
6161 }
6162}
6163
Eric Laurent5850c4c2016-11-10 13:04:31 -08006164void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006165{
Eric Laurentbfb1b832013-01-07 09:53:42 -08006166 float left, right;
6167
Vlad Popae2f5aef2022-07-25 16:00:20 +02006168
Andy Hung333ab962019-05-28 20:23:35 -07006169 // Ensure volumeshaper state always advances even when muted.
6170 const sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
6171 const auto [shaperVolume, shaperActive] = track->getVolumeHandler()->getVolume(
6172 proxy->framesReleased());
6173 mVolumeShaperActive = shaperActive;
6174
Vlad Popae2f5aef2022-07-25 16:00:20 +02006175 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
6176 left = float_from_gain(gain_minifloat_unpack_left(vlr));
6177 right = float_from_gain(gain_minifloat_unpack_right(vlr));
6178
6179 const bool clientVolumeMute = (left == 0.f && right == 0.f);
6180
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08006181 if (mMasterMute || mStreamTypes[track->streamType()].mute || track->isPlaybackRestricted()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08006182 left = right = 0;
6183 } else {
6184 float typeVolume = mStreamTypes[track->streamType()].volume;
Andy Hung333ab962019-05-28 20:23:35 -07006185 const float v = mMasterVolume * typeVolume * shaperVolume;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08006186
Glenn Kastenc56f3422014-03-21 17:53:17 -07006187 if (left > GAIN_FLOAT_UNITY) {
6188 left = GAIN_FLOAT_UNITY;
6189 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07006190 if (right > GAIN_FLOAT_UNITY) {
6191 right = GAIN_FLOAT_UNITY;
6192 }
Vlad Popae2f5aef2022-07-25 16:00:20 +02006193
6194 left *= v * mMasterBalanceLeft; // DirectOutputThread balance applied as track volume
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006195 right *= v * mMasterBalanceRight;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006196 }
6197
Vlad Popae8d99472022-06-30 16:02:48 +02006198 track->processMuteEvent_l(mAudioFlinger->getOrCreateAudioManager(),
6199 /*muteState=*/{mMasterMute,
6200 mStreamTypes[track->streamType()].volume == 0.f,
6201 mStreamTypes[track->streamType()].mute,
Vlad Popae2f5aef2022-07-25 16:00:20 +02006202 track->isPlaybackRestricted(),
Vlad Popa436c9172022-08-02 15:25:08 +02006203 clientVolumeMute,
6204 shaperVolume == 0.f});
Vlad Popae8d99472022-06-30 16:02:48 +02006205
Eric Laurentbfb1b832013-01-07 09:53:42 -08006206 if (lastTrack) {
Kevin Rocard12381092018-04-11 09:19:59 -07006207 track->setFinalVolume((left + right) / 2.f);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006208 if (left != mLeftVolFloat || right != mRightVolFloat) {
6209 mLeftVolFloat = left;
6210 mRightVolFloat = right;
6211
Eric Laurentbfb1b832013-01-07 09:53:42 -08006212 // Delegate volume control to effect in track effect chain if needed
6213 // only one effect chain can be present on DirectOutputThread, so if
6214 // there is one, the track is connected to it
6215 if (!mEffectChains.isEmpty()) {
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09006216 // if effect chain exists, volume is handled by it.
6217 // Convert volumes from float to 8.24
6218 uint32_t vl = (uint32_t)(left * (1 << 24));
6219 uint32_t vr = (uint32_t)(right * (1 << 24));
6220 // Direct/Offload effect chains set output volume in setVolume_l().
6221 (void)mEffectChains[0]->setVolume_l(&vl, &vr);
6222 } else {
6223 // otherwise we directly set the volume.
6224 setVolumeForOutput_l(left, right);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006225 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006226 }
6227 }
6228}
6229
Phil Burk43b4dcc2015-06-09 16:53:44 -07006230void AudioFlinger::DirectOutputThread::onAddNewTrack_l()
6231{
6232 sp<Track> previousTrack = mPreviousTrack.promote();
Andy Hungdae27702016-10-31 14:01:16 -07006233 sp<Track> latestTrack = mActiveTracks.getLatest();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006234
Eric Laurent0f0631e2015-07-06 18:01:25 -07006235 if (previousTrack != 0 && latestTrack != 0) {
6236 if (mType == DIRECT) {
6237 if (previousTrack.get() != latestTrack.get()) {
6238 mFlushPending = true;
6239 }
6240 } else /* mType == OFFLOAD */ {
6241 if (previousTrack->sessionId() != latestTrack->sessionId()) {
6242 mFlushPending = true;
6243 }
6244 }
Revathi Uddaraju20413a92016-10-13 17:16:14 +08006245 } else if (previousTrack == 0) {
6246 // there could be an old track added back during track transition for direct
6247 // output, so always issues flush to flush data of the previous track if it
6248 // was already destroyed with HAL paused, then flush can resume the playback
6249 mFlushPending = true;
Phil Burk43b4dcc2015-06-09 16:53:44 -07006250 }
6251 PlaybackThread::onAddNewTrack_l();
6252}
Eric Laurentbfb1b832013-01-07 09:53:42 -08006253
Eric Laurent81784c32012-11-19 14:55:58 -08006254AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
6255 Vector< sp<Track> > *tracksToRemove
6256)
6257{
Eric Laurentd595b7c2013-04-03 17:27:56 -07006258 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08006259 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006260 bool doHwPause = false;
6261 bool doHwResume = false;
Eric Laurent81784c32012-11-19 14:55:58 -08006262
6263 // find out which tracks need to be processed
Andy Hungdae27702016-10-31 14:01:16 -07006264 for (const sp<Track> &t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08006265 if (t->isInvalid()) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07006266 ALOGW("An invalidated track shouldn't be in active list");
Eric Laurent5850c4c2016-11-10 13:04:31 -08006267 tracksToRemove->add(t);
Phil Burk43b4dcc2015-06-09 16:53:44 -07006268 continue;
6269 }
6270
Eric Laurent5850c4c2016-11-10 13:04:31 -08006271 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006272#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurent81784c32012-11-19 14:55:58 -08006273 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006274#endif
Eric Laurentfd477972013-10-25 18:10:40 -07006275 // Only consider last track started for volume and mixer state control.
6276 // In theory an older track could underrun and restart after the new one starts
6277 // but as we only care about the transition phase between two tracks on a
6278 // direct output, it is not a problem to ignore the underrun case.
Andy Hungdae27702016-10-31 14:01:16 -07006279 sp<Track> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08006280 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08006281
Kuowei Li23666472021-01-20 10:23:25 +08006282 if (track->isPausePending()) {
6283 track->pauseAck();
6284 // It is possible a track might have been flushed or stopped.
6285 // Other operations such as flush pending might occur on the next prepare.
6286 if (track->isPausing()) {
6287 track->setPaused();
6288 }
6289 // Always perform pause, as an immediate flush will change
6290 // the pause state to be no longer isPausing().
Phil Burk6fc2a7c2015-04-30 16:08:10 -07006291 if (mHwSupportsPause && last && !mHwPaused) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006292 doHwPause = true;
6293 mHwPaused = true;
6294 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08006295 } else if (track->isFlushPending()) {
6296 track->flushAck();
6297 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07006298 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006299 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07006300 } else if (track->isResumePending()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006301 track->resumeAck();
Eric Laurent3df841a2016-07-15 15:15:40 -07006302 if (last) {
6303 mLeftVolFloat = mRightVolFloat = -1.0;
6304 if (mHwPaused) {
6305 doHwResume = true;
6306 mHwPaused = false;
6307 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08006308 }
6309 }
6310
Eric Laurent81784c32012-11-19 14:55:58 -08006311 // The first time a track is added we wait
Phil Burk99adee32014-12-10 16:46:30 -08006312 // for all its buffers to be filled before processing it.
6313 // Allow draining the buffer in case the client
6314 // app does not call stop() and relies on underrun to stop:
6315 // hence the test on (track->mRetryCount > 1).
Andy Hung455982f2021-04-27 17:46:12 -07006316 // If track->mRetryCount <= 1 then track is about to be disabled, paused, removed,
6317 // so we accept any nonzero amount of data delivered by the AudioTrack (which will
6318 // reset the retry counter).
Phil Burkca5e6142015-07-14 09:42:29 -07006319 // Do not use a high threshold for compressed audio.
Andy Hung455982f2021-04-27 17:46:12 -07006320
6321 // target retry count that we will use is based on the time we wait for retries.
6322 const int32_t targetRetryCount = kMaxTrackRetriesDirectMs * 1000 / mActiveSleepTimeUs;
6323 // the retry threshold is when we accept any size for PCM data. This is slightly
6324 // smaller than the retry count so we can push small bits of data without a glitch.
6325 const int32_t retryThreshold = targetRetryCount > 2 ? targetRetryCount - 1 : 1;
Eric Laurent81784c32012-11-19 14:55:58 -08006326 uint32_t minFrames;
Phil Burk99adee32014-12-10 16:46:30 -08006327 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
Andy Hung455982f2021-04-27 17:46:12 -07006328 && (track->mRetryCount > retryThreshold) && audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006329 minFrames = mNormalFrameCount;
6330 } else {
6331 minFrames = 1;
6332 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006333
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07006334 const size_t framesReady = track->framesReady();
6335 const int trackId = track->id();
6336 if (ATRACE_ENABLED()) {
6337 std::string traceName("nRdy");
6338 traceName += std::to_string(trackId);
6339 ATRACE_INT(traceName.c_str(), framesReady);
6340 }
6341 if ((framesReady >= minFrames) && track->isReady() && !track->isPaused() &&
Eric Laurentab5cdba2014-06-09 17:22:27 -07006342 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08006343 {
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07006344 ALOGVV("track(%d) s=%08x [OK]", trackId, cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08006345
6346 if (track->mFillingUpStatus == Track::FS_FILLED) {
6347 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07006348 if (last) {
6349 // make sure processVolume_l() will apply new volume even if 0
6350 mLeftVolFloat = mRightVolFloat = -1.0;
6351 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08006352 if (!mHwSupportsPause) {
6353 track->resumeAck();
Eric Laurent81784c32012-11-19 14:55:58 -08006354 }
6355 }
6356
6357 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08006358 processVolume_l(track, last);
6359 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07006360 sp<Track> previousTrack = mPreviousTrack.promote();
6361 if (previousTrack != 0) {
6362 if (track != previousTrack.get()) {
6363 // Flush any data still being written from last track
6364 mBytesRemaining = 0;
Eric Laurent0f0631e2015-07-06 18:01:25 -07006365 // Invalidate previous track to force a seek when resuming.
6366 previousTrack->invalidate();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006367 }
6368 }
6369 mPreviousTrack = track;
6370
Eric Laurentd595b7c2013-04-03 17:27:56 -07006371 // reset retry count
Andy Hung455982f2021-04-27 17:46:12 -07006372 track->mRetryCount = targetRetryCount;
Eric Laurent5850c4c2016-11-10 13:04:31 -08006373 mActiveTrack = t;
Eric Laurentd595b7c2013-04-03 17:27:56 -07006374 mixerStatus = MIXER_TRACKS_READY;
Eric Laurent5cff4032015-05-26 13:49:58 -07006375 if (mHwPaused) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08006376 doHwResume = true;
6377 mHwPaused = false;
6378 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07006379 }
Eric Laurent81784c32012-11-19 14:55:58 -08006380 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07006381 // clear effect chain input buffer if the last active track started underruns
6382 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07006383 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08006384 mEffectChains[0]->clearInputBuffer();
6385 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07006386 if (track->isStopping_1()) {
6387 track->mState = TrackBase::STOPPING_2;
Eric Laurentb369caf2015-03-30 20:51:47 -07006388 if (last && mHwPaused) {
6389 doHwResume = true;
6390 mHwPaused = false;
6391 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07006392 }
6393 if ((track->sharedBuffer() != 0) || track->isStopped() ||
6394 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08006395 // We have consumed all the buffers of this track.
6396 // Remove it from the list of active tracks.
Atneya Nair0cae0432022-05-10 18:12:12 -04006397 bool presComplete = false;
Eric Laurentfd477972013-10-25 18:10:40 -07006398 if (mStandby || !last ||
Atneya Nair0cae0432022-05-10 18:12:12 -04006399 (presComplete = track->presentationComplete(latency_l())) ||
Jindong32dc26e2019-11-11 18:10:01 +08006400 track->isPaused() || mHwPaused) {
Atneya Nair0cae0432022-05-10 18:12:12 -04006401 if (presComplete) {
6402 mOutput->presentationComplete();
6403 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07006404 if (track->isStopping_2()) {
6405 track->mState = TrackBase::STOPPED;
6406 }
Eric Laurent81784c32012-11-19 14:55:58 -08006407 if (track->isStopped()) {
6408 track->reset();
6409 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07006410 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08006411 }
6412 } else {
6413 // No buffers for this track. Give it a few chances to
6414 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07006415 // Only consider last track started for mixer state control
Brian Lindahl65e90012022-07-27 18:01:07 +02006416 bool isTimestampAdvancing = mIsTimestampAdvancing.check(mOutput);
Eric Laurent81784c32012-11-19 14:55:58 -08006417 if (--(track->mRetryCount) <= 0) {
Brian Lindahl65e90012022-07-27 18:01:07 +02006418 if (isTimestampAdvancing) { // HAL is still playing audio, give us more time.
ziyangch8f194f12021-12-01 13:48:04 -08006419 track->mRetryCount = kMaxTrackRetriesOffload;
6420 } else {
6421 ALOGV("BUFFER TIMEOUT: remove track(%d) from active list", trackId);
6422 tracksToRemove->add(track);
6423 // indicate to client process that the track was disabled because of
6424 // underrun; it will then automatically call start() when data is available
6425 track->disable();
6426 // only do hw pause when track is going to be removed due to BUFFER TIMEOUT.
6427 // unlike mixerthread, HAL can be paused for direct output
6428 ALOGW("pause because of UNDERRUN, framesReady = %zu,"
6429 "minFrames = %u, mFormat = %#x",
6430 framesReady, minFrames, mFormat);
6431 if (last && mHwSupportsPause && !mHwPaused && !mStandby) {
6432 doHwPause = true;
6433 mHwPaused = true;
6434 }
Eric Laurent0f7b5f22014-12-19 10:43:21 -08006435 }
Haynes Mathew George5c6daae2017-01-24 20:06:05 -08006436 } else if (last) {
6437 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurent81784c32012-11-19 14:55:58 -08006438 }
6439 }
6440 }
6441 }
6442
Eric Laurentd1f69b02014-12-15 14:33:13 -08006443 // if an active track did not command a flush, check for pending flush on stopped tracks
Phil Burk43b4dcc2015-06-09 16:53:44 -07006444 if (!mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006445 for (size_t i = 0; i < mTracks.size(); i++) {
6446 if (mTracks[i]->isFlushPending()) {
6447 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006448 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006449 }
6450 }
6451 }
6452
6453 // make sure the pause/flush/resume sequence is executed in the right order.
6454 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
6455 // before flush and then resume HW. This can happen in case of pause/flush/resume
6456 // if resume is received before pause is executed.
6457 if (mHwSupportsPause && !mStandby &&
Phil Burk43b4dcc2015-06-09 16:53:44 -07006458 (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006459 status_t result = mOutput->stream->pause();
6460 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08006461 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07006462 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006463 flushHw_l();
6464 }
6465 if (mHwSupportsPause && !mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006466 status_t result = mOutput->stream->resume();
6467 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08006468 }
Eric Laurent81784c32012-11-19 14:55:58 -08006469 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08006470 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08006471
6472 return mixerStatus;
6473}
6474
6475void AudioFlinger::DirectOutputThread::threadLoop_mix()
6476{
Eric Laurent81784c32012-11-19 14:55:58 -08006477 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08006478 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08006479 // output audio to hardware
6480 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07006481 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08006482 buffer.frameCount = frameCount;
Phil Burk062e67a2015-02-11 13:40:50 -08006483 status_t status = mActiveTrack->getNextBuffer(&buffer);
6484 if (status != NO_ERROR || buffer.raw == NULL) {
Eric Laurent51716182016-02-29 18:00:56 -08006485 // no need to pad with 0 for compressed audio
6486 if (audio_has_proportional_frames(mFormat)) {
6487 memset(curBuf, 0, frameCount * mFrameSize);
6488 }
Eric Laurent81784c32012-11-19 14:55:58 -08006489 break;
6490 }
6491 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
6492 frameCount -= buffer.frameCount;
6493 curBuf += buffer.frameCount * mFrameSize;
6494 mActiveTrack->releaseBuffer(&buffer);
6495 }
Andy Hung2098f272014-02-27 14:00:06 -08006496 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006497 mSleepTimeUs = 0;
6498 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08006499 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08006500}
6501
6502void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
6503{
Eric Laurentd1f69b02014-12-15 14:33:13 -08006504 // do not write to HAL when paused
Eric Laurent0f7b5f22014-12-19 10:43:21 -08006505 if (mHwPaused || (usesHwAvSync() && mStandby)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006506 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006507 return;
6508 }
Andy Hung85ba3332021-04-27 17:40:26 -07006509 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
6510 mSleepTimeUs = mActiveSleepTimeUs;
6511 } else {
6512 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006513 }
Andy Hung85ba3332021-04-27 17:40:26 -07006514 // Note: In S or later, we do not write zeroes for
6515 // linear or proportional PCM direct tracks in underrun.
Eric Laurent81784c32012-11-19 14:55:58 -08006516}
6517
Eric Laurentd1f69b02014-12-15 14:33:13 -08006518void AudioFlinger::DirectOutputThread::threadLoop_exit()
6519{
6520 {
6521 Mutex::Autolock _l(mLock);
Eric Laurentd1f69b02014-12-15 14:33:13 -08006522 for (size_t i = 0; i < mTracks.size(); i++) {
6523 if (mTracks[i]->isFlushPending()) {
6524 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006525 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006526 }
6527 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07006528 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006529 flushHw_l();
6530 }
6531 }
6532 PlaybackThread::threadLoop_exit();
6533}
6534
6535// must be called with thread mutex locked
6536bool AudioFlinger::DirectOutputThread::shouldStandby_l()
6537{
6538 bool trackPaused = false;
Eric Laurentb369caf2015-03-30 20:51:47 -07006539 bool trackStopped = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006540
6541 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
6542 // after a timeout and we will enter standby then.
6543 if (mTracks.size() > 0) {
6544 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
Eric Laurentb369caf2015-03-30 20:51:47 -07006545 trackStopped = mTracks[mTracks.size() - 1]->isStopped() ||
6546 mTracks[mTracks.size() - 1]->mState == TrackBase::IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006547 }
6548
Eric Laurent5cff4032015-05-26 13:49:58 -07006549 return !mStandby && !(trackPaused || (mHwPaused && !trackStopped));
Eric Laurentd1f69b02014-12-15 14:33:13 -08006550}
6551
Eric Laurent10351942014-05-08 18:49:52 -07006552// checkForNewParameter_l() must be called with ThreadBase::mLock held
6553bool AudioFlinger::DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
6554 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08006555{
6556 bool reconfig = false;
Eric Laurent10351942014-05-08 18:49:52 -07006557 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006558
Eric Laurent10351942014-05-08 18:49:52 -07006559 AudioParameter param = AudioParameter(keyValuePair);
6560 int value;
6561 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07006562 LOG_FATAL("Should not set routing device in DirectOutputThread");
Eric Laurent81784c32012-11-19 14:55:58 -08006563 }
Eric Laurent10351942014-05-08 18:49:52 -07006564 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6565 // do not accept frame count changes if tracks are open as the track buffer
6566 // size depends on frame count and correct behavior would not be garantied
6567 // if frame count is changed after track creation
6568 if (!mTracks.isEmpty()) {
6569 status = INVALID_OPERATION;
6570 } else {
6571 reconfig = true;
6572 }
6573 }
6574 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006575 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07006576 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08006577 mOutput->standby();
Andy Hungcf10d742020-04-28 15:38:24 -07006578 if (!mStandby) {
6579 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07006580 mThreadSnapshot.onEnd();
Andy Hungcf10d742020-04-28 15:38:24 -07006581 mStandby = true;
6582 }
Eric Laurent10351942014-05-08 18:49:52 -07006583 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006584 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07006585 }
6586 if (status == NO_ERROR && reconfig) {
6587 readOutputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07006588 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07006589 }
6590 }
6591
Dean Wheatley68918102021-03-19 22:09:19 +11006592 return reconfig;
Eric Laurent81784c32012-11-19 14:55:58 -08006593}
6594
6595uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
6596{
6597 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08006598 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006599 time = PlaybackThread::activeSleepTimeUs();
6600 } else {
Eric Laurent51716182016-02-29 18:00:56 -08006601 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006602 }
6603 return time;
6604}
6605
6606uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
6607{
6608 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08006609 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006610 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
6611 } else {
Eric Laurent51716182016-02-29 18:00:56 -08006612 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006613 }
6614 return time;
6615}
6616
6617uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
6618{
6619 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08006620 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006621 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
6622 } else {
Eric Laurent51716182016-02-29 18:00:56 -08006623 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006624 }
6625 return time;
6626}
6627
6628void AudioFlinger::DirectOutputThread::cacheParameters_l()
6629{
6630 PlaybackThread::cacheParameters_l();
6631
6632 // use shorter standby delay as on normal output to release
6633 // hardware resources as soon as possible
Eric Laurentb369caf2015-03-30 20:51:47 -07006634 // no delay on outputs with HW A/V sync
6635 if (usesHwAvSync()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006636 mStandbyDelayNs = 0;
Phil Burkfdb3c072016-02-09 10:47:02 -08006637 } else if ((mType == OFFLOAD) && !audio_has_proportional_frames(mFormat)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006638 mStandbyDelayNs = kOffloadStandbyDelayNs;
Eric Laurent5cff4032015-05-26 13:49:58 -07006639 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006640 mStandbyDelayNs = microseconds(mActiveSleepTimeUs*2);
Eric Laurent972a1732013-09-04 09:42:59 -07006641 }
Eric Laurent81784c32012-11-19 14:55:58 -08006642}
6643
Eric Laurente659ef42014-09-29 13:06:46 -07006644void AudioFlinger::DirectOutputThread::flushHw_l()
6645{
ziyangch8f194f12021-12-01 13:48:04 -08006646 PlaybackThread::flushHw_l();
Phil Burk062e67a2015-02-11 13:40:50 -08006647 mOutput->flush();
Eric Laurentd1f69b02014-12-15 14:33:13 -08006648 mHwPaused = false;
Phil Burk43b4dcc2015-06-09 16:53:44 -07006649 mFlushPending = false;
Dean Wheatley12473e92021-03-18 23:00:55 +11006650 mTimestampVerifier.discontinuity(discontinuityForStandbyOrFlush());
Sampath Shetty999f0e82020-01-15 10:19:06 +11006651 mTimestamp.clear();
Eric Laurente659ef42014-09-29 13:06:46 -07006652}
6653
Andy Hung10cbff12017-02-21 17:30:14 -08006654int64_t AudioFlinger::DirectOutputThread::computeWaitTimeNs_l() const {
6655 // If a VolumeShaper is active, we must wake up periodically to update volume.
6656 const int64_t NS_PER_MS = 1000000;
6657 return mVolumeShaperActive ?
6658 kMinNormalSinkBufferSizeMs * NS_PER_MS : PlaybackThread::computeWaitTimeNs_l();
6659}
6660
Eric Laurent81784c32012-11-19 14:55:58 -08006661// ----------------------------------------------------------------------------
6662
Eric Laurentbfb1b832013-01-07 09:53:42 -08006663AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
Eric Laurent4de95592013-09-26 15:28:21 -07006664 const wp<AudioFlinger::PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006665 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07006666 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07006667 mWriteAckSequence(0),
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006668 mDrainSequence(0),
6669 mAsyncError(false)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006670{
6671}
6672
6673AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
6674{
6675}
6676
6677void AudioFlinger::AsyncCallbackThread::onFirstRef()
6678{
6679 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
6680}
6681
6682bool AudioFlinger::AsyncCallbackThread::threadLoop()
6683{
6684 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07006685 uint32_t writeAckSequence;
6686 uint32_t drainSequence;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006687 bool asyncError;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006688
6689 {
6690 Mutex::Autolock _l(mLock);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08006691 while (!((mWriteAckSequence & 1) ||
6692 (mDrainSequence & 1) ||
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006693 mAsyncError ||
Haynes Mathew George24a325d2013-12-03 21:26:02 -08006694 exitPending())) {
6695 mWaitWorkCV.wait(mLock);
6696 }
6697
Eric Laurentbfb1b832013-01-07 09:53:42 -08006698 if (exitPending()) {
6699 break;
6700 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07006701 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
6702 mWriteAckSequence, mDrainSequence);
6703 writeAckSequence = mWriteAckSequence;
6704 mWriteAckSequence &= ~1;
6705 drainSequence = mDrainSequence;
6706 mDrainSequence &= ~1;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006707 asyncError = mAsyncError;
6708 mAsyncError = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006709 }
6710 {
Eric Laurent4de95592013-09-26 15:28:21 -07006711 sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
6712 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07006713 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07006714 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006715 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07006716 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07006717 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006718 }
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006719 if (asyncError) {
6720 playbackThread->onAsyncError();
6721 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006722 }
6723 }
6724 }
6725 return false;
6726}
6727
6728void AudioFlinger::AsyncCallbackThread::exit()
6729{
6730 ALOGV("AsyncCallbackThread::exit");
6731 Mutex::Autolock _l(mLock);
6732 requestExit();
6733 mWaitWorkCV.broadcast();
6734}
6735
Eric Laurent3b4529e2013-09-05 18:09:19 -07006736void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006737{
6738 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07006739 // bit 0 is cleared
6740 mWriteAckSequence = sequence << 1;
6741}
6742
6743void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
6744{
6745 Mutex::Autolock _l(mLock);
6746 // ignore unexpected callbacks
6747 if (mWriteAckSequence & 2) {
6748 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006749 mWaitWorkCV.signal();
6750 }
6751}
6752
Eric Laurent3b4529e2013-09-05 18:09:19 -07006753void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006754{
6755 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07006756 // bit 0 is cleared
6757 mDrainSequence = sequence << 1;
6758}
6759
6760void AudioFlinger::AsyncCallbackThread::resetDraining()
6761{
6762 Mutex::Autolock _l(mLock);
6763 // ignore unexpected callbacks
6764 if (mDrainSequence & 2) {
6765 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006766 mWaitWorkCV.signal();
6767 }
6768}
6769
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006770void AudioFlinger::AsyncCallbackThread::setAsyncError()
6771{
6772 Mutex::Autolock _l(mLock);
6773 mAsyncError = true;
6774 mWaitWorkCV.signal();
6775}
6776
Eric Laurentbfb1b832013-01-07 09:53:42 -08006777
6778// ----------------------------------------------------------------------------
6779AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
jiabinc52b1ff2019-10-31 17:20:42 -07006780 AudioStreamOut* output, audio_io_handle_t id, bool systemReady)
6781 : DirectOutputThread(audioFlinger, output, id, OFFLOAD, systemReady),
ziyangch8f194f12021-12-01 13:48:04 -08006782 mPausedWriteLength(0), mPausedBytesRemaining(0), mKeepWakeLock(true)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006783{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07006784 //FIXME: mStandby should be set to true by ThreadBase constructo
Eric Laurentfd477972013-10-25 18:10:40 -07006785 mStandby = true;
Eric Laurent64667972016-03-30 18:19:46 -07006786 mKeepWakeLock = property_get_bool("ro.audio.offload_wakelock", true /* default_value */);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006787}
6788
Eric Laurentbfb1b832013-01-07 09:53:42 -08006789void AudioFlinger::OffloadThread::threadLoop_exit()
6790{
6791 if (mFlushPending || mHwPaused) {
6792 // If a flush is pending or track was paused, just discard buffered data
6793 flushHw_l();
6794 } else {
6795 mMixerStatus = MIXER_DRAIN_ALL;
6796 threadLoop_drain();
6797 }
Uday Gupta56604aa2014-05-13 11:19:17 -07006798 if (mUseAsyncWrite) {
6799 ALOG_ASSERT(mCallbackThread != 0);
6800 mCallbackThread->exit();
6801 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006802 PlaybackThread::threadLoop_exit();
6803}
6804
6805AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
6806 Vector< sp<Track> > *tracksToRemove
6807)
6808{
Eric Laurentbfb1b832013-01-07 09:53:42 -08006809 size_t count = mActiveTracks.size();
6810
6811 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07006812 bool doHwPause = false;
6813 bool doHwResume = false;
6814
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006815 ALOGV("OffloadThread::prepareTracks_l active tracks %zu", count);
Eric Laurentede6c3b2013-09-19 14:37:46 -07006816
Eric Laurentbfb1b832013-01-07 09:53:42 -08006817 // find out which tracks need to be processed
Andy Hungdae27702016-10-31 14:01:16 -07006818 for (const sp<Track> &t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08006819 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006820#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurentbfb1b832013-01-07 09:53:42 -08006821 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006822#endif
Eric Laurentfd477972013-10-25 18:10:40 -07006823 // Only consider last track started for volume and mixer state control.
6824 // In theory an older track could underrun and restart after the new one starts
6825 // but as we only care about the transition phase between two tracks on a
6826 // direct output, it is not a problem to ignore the underrun case.
Andy Hungdae27702016-10-31 14:01:16 -07006827 sp<Track> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08006828 bool last = l.get() == track;
Eric Laurentfd477972013-10-25 18:10:40 -07006829
Haynes Mathew George7844f672014-01-15 12:32:55 -08006830 if (track->isInvalid()) {
6831 ALOGW("An invalidated track shouldn't be in active list");
6832 tracksToRemove->add(track);
6833 continue;
6834 }
6835
6836 if (track->mState == TrackBase::IDLE) {
6837 ALOGW("An idle track shouldn't be in active list");
6838 continue;
6839 }
6840
Kuowei Li23666472021-01-20 10:23:25 +08006841 if (track->isPausePending()) {
6842 track->pauseAck();
6843 // It is possible a track might have been flushed or stopped.
6844 // Other operations such as flush pending might occur on the next prepare.
6845 if (track->isPausing()) {
6846 track->setPaused();
6847 }
6848 // Always perform pause if last, as an immediate flush will change
6849 // the pause state to be no longer isPausing().
Eric Laurentbfb1b832013-01-07 09:53:42 -08006850 if (last) {
Eric Laurent5cff4032015-05-26 13:49:58 -07006851 if (mHwSupportsPause && !mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07006852 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006853 mHwPaused = true;
6854 }
6855 // If we were part way through writing the mixbuffer to
6856 // the HAL we must save this until we resume
6857 // BUG - this will be wrong if a different track is made active,
6858 // in that case we want to discard the pending data in the
6859 // mixbuffer and tell the client to present it again when the
6860 // track is resumed
6861 mPausedWriteLength = mCurrentWriteLength;
6862 mPausedBytesRemaining = mBytesRemaining;
6863 mBytesRemaining = 0; // stop writing
6864 }
6865 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08006866 } else if (track->isFlushPending()) {
Eric Laurente93cc032016-05-05 10:15:10 -07006867 if (track->isStopping_1()) {
6868 track->mRetryCount = kMaxTrackStopRetriesOffload;
6869 } else {
6870 track->mRetryCount = kMaxTrackRetriesOffload;
6871 }
Haynes Mathew George7844f672014-01-15 12:32:55 -08006872 track->flushAck();
6873 if (last) {
6874 mFlushPending = true;
6875 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08006876 } else if (track->isResumePending()){
6877 track->resumeAck();
6878 if (last) {
6879 if (mPausedBytesRemaining) {
6880 // Need to continue write that was interrupted
6881 mCurrentWriteLength = mPausedWriteLength;
6882 mBytesRemaining = mPausedBytesRemaining;
6883 mPausedBytesRemaining = 0;
6884 }
6885 if (mHwPaused) {
6886 doHwResume = true;
6887 mHwPaused = false;
6888 // threadLoop_mix() will handle the case that we need to
6889 // resume an interrupted write
6890 }
6891 // enable write to audio HAL
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006892 mSleepTimeUs = 0;
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08006893
Eric Laurent3df841a2016-07-15 15:15:40 -07006894 mLeftVolFloat = mRightVolFloat = -1.0;
6895
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08006896 // Do not handle new data in this iteration even if track->framesReady()
6897 mixerStatus = MIXER_TRACKS_ENABLED;
6898 }
6899 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07006900 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Andy Hungc0691382018-09-12 18:01:57 -07006901 ALOGVV("OffloadThread: track(%d) s=%08x [OK]", track->id(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006902 if (track->mFillingUpStatus == Track::FS_FILLED) {
6903 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07006904 if (last) {
6905 // make sure processVolume_l() will apply new volume even if 0
6906 mLeftVolFloat = mRightVolFloat = -1.0;
6907 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006908 }
6909
6910 if (last) {
Eric Laurentd7e59222013-11-15 12:02:28 -08006911 sp<Track> previousTrack = mPreviousTrack.promote();
6912 if (previousTrack != 0) {
6913 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08006914 // Flush any data still being written from last track
6915 mBytesRemaining = 0;
6916 if (mPausedBytesRemaining) {
6917 // Last track was paused so we also need to flush saved
6918 // mixbuffer state and invalidate track so that it will
6919 // re-submit that unwritten data when it is next resumed
6920 mPausedBytesRemaining = 0;
6921 // Invalidate is a bit drastic - would be more efficient
6922 // to have a flag to tell client that some of the
6923 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08006924 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08006925 }
6926 // flush data already sent to the DSP if changing audio session as audio
6927 // comes from a different source. Also invalidate previous track to force a
6928 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08006929 if (previousTrack->sessionId() != track->sessionId()) {
6930 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08006931 }
6932 }
6933 }
6934 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006935 // reset retry count
Eric Laurente93cc032016-05-05 10:15:10 -07006936 if (track->isStopping_1()) {
6937 track->mRetryCount = kMaxTrackStopRetriesOffload;
6938 } else {
6939 track->mRetryCount = kMaxTrackRetriesOffload;
6940 }
Eric Laurent5850c4c2016-11-10 13:04:31 -08006941 mActiveTrack = t;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006942 mixerStatus = MIXER_TRACKS_READY;
6943 }
6944 } else {
Andy Hungc0691382018-09-12 18:01:57 -07006945 ALOGVV("OffloadThread: track(%d) s=%08x [NOT READY]", track->id(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006946 if (track->isStopping_1()) {
Eric Laurente93cc032016-05-05 10:15:10 -07006947 if (--(track->mRetryCount) <= 0) {
6948 // Hardware buffer can hold a large amount of audio so we must
6949 // wait for all current track's data to drain before we say
6950 // that the track is stopped.
6951 if (mBytesRemaining == 0) {
6952 // Only start draining when all data in mixbuffer
6953 // has been written
6954 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
6955 track->mState = TrackBase::STOPPING_2; // so presentation completes after
6956 // drain do not drain if no data was ever sent to HAL (mStandby == true)
6957 if (last && !mStandby) {
6958 // do not modify drain sequence if we are already draining. This happens
6959 // when resuming from pause after drain.
6960 if ((mDrainSequence & 1) == 0) {
6961 mSleepTimeUs = 0;
6962 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
6963 mixerStatus = MIXER_DRAIN_TRACK;
6964 mDrainSequence += 2;
6965 }
6966 if (mHwPaused) {
6967 // It is possible to move from PAUSED to STOPPING_1 without
6968 // a resume so we must ensure hardware is running
6969 doHwResume = true;
6970 mHwPaused = false;
6971 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006972 }
6973 }
Eric Laurente93cc032016-05-05 10:15:10 -07006974 } else if (last) {
6975 ALOGV("stopping1 underrun retries left %d", track->mRetryCount);
6976 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006977 }
6978 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07006979 // Drain has completed or we are in standby, signal presentation complete
6980 if (!(mDrainSequence & 1) || !last || mStandby) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08006981 track->mState = TrackBase::STOPPED;
Atneya Nair0cae0432022-05-10 18:12:12 -04006982 mOutput->presentationComplete();
6983 track->presentationComplete(latency_l()); // always returns true
Eric Laurentbfb1b832013-01-07 09:53:42 -08006984 track->reset();
6985 tracksToRemove->add(track);
Dean Wheatley12473e92021-03-18 23:00:55 +11006986 // OFFLOADED stop resets frame counts.
Andy Hungf3234512018-07-03 14:51:47 -07006987 if (!mUseAsyncWrite) {
6988 // If we don't get explicit drain notification we must
6989 // register discontinuity regardless of whether this is
6990 // the previous (!last) or the upcoming (last) track
6991 // to avoid skipping the discontinuity.
Dean Wheatley12473e92021-03-18 23:00:55 +11006992 mTimestampVerifier.discontinuity(
6993 mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Andy Hungf3234512018-07-03 14:51:47 -07006994 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006995 }
6996 } else {
6997 // No buffers for this track. Give it a few chances to
6998 // fill a buffer, then remove it from active list.
Brian Lindahl65e90012022-07-27 18:01:07 +02006999 bool isTimestampAdvancing = mIsTimestampAdvancing.check(mOutput);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007000 if (--(track->mRetryCount) <= 0) {
Brian Lindahl65e90012022-07-27 18:01:07 +02007001 if (isTimestampAdvancing) { // HAL is still playing audio, give us more time.
Andy Hungf8044752016-07-27 14:58:11 -07007002 track->mRetryCount = kMaxTrackRetriesOffload;
7003 } else {
Andy Hungc0691382018-09-12 18:01:57 -07007004 ALOGV("OffloadThread: BUFFER TIMEOUT: remove track(%d) from active list",
7005 track->id());
Andy Hungf8044752016-07-27 14:58:11 -07007006 tracksToRemove->add(track);
Glenn Kastend3bb6452016-12-05 18:14:37 -08007007 // tell client process that the track was disabled because of underrun;
Andy Hungf8044752016-07-27 14:58:11 -07007008 // it will then automatically call start() when data is available
7009 track->disable();
7010 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007011 } else if (last){
7012 mixerStatus = MIXER_TRACKS_ENABLED;
7013 }
7014 }
7015 }
7016 // compute volume for this track
Wenfeng Sun79458332019-05-29 20:12:43 +08007017 if (track->isReady()) { // check ready to prevent premature start.
7018 processVolume_l(track, last);
7019 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007020 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007021
Eric Laurentea0fade2013-10-04 16:23:48 -07007022 // make sure the pause/flush/resume sequence is executed in the right order.
7023 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
7024 // before flush and then resume HW. This can happen in case of pause/flush/resume
7025 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07007026 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007027 status_t result = mOutput->stream->pause();
7028 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07007029 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007030 if (mFlushPending) {
7031 flushHw_l();
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007032 }
Eric Laurentfd477972013-10-25 18:10:40 -07007033 if (!mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007034 status_t result = mOutput->stream->resume();
7035 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07007036 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007037
Eric Laurentbfb1b832013-01-07 09:53:42 -08007038 // remove all the tracks that need to be...
7039 removeTracks_l(*tracksToRemove);
7040
7041 return mixerStatus;
7042}
7043
Eric Laurentbfb1b832013-01-07 09:53:42 -08007044// must be called with thread mutex locked
7045bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
7046{
Eric Laurent3b4529e2013-09-05 18:09:19 -07007047 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
7048 mWriteAckSequence, mDrainSequence);
7049 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08007050 return true;
7051 }
7052 return false;
7053}
7054
Eric Laurentbfb1b832013-01-07 09:53:42 -08007055bool AudioFlinger::OffloadThread::waitingAsyncCallback()
7056{
7057 Mutex::Autolock _l(mLock);
7058 return waitingAsyncCallback_l();
7059}
7060
7061void AudioFlinger::OffloadThread::flushHw_l()
7062{
Eric Laurente659ef42014-09-29 13:06:46 -07007063 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08007064 // Flush anything still waiting in the mixbuffer
7065 mCurrentWriteLength = 0;
7066 mBytesRemaining = 0;
7067 mPausedWriteLength = 0;
7068 mPausedBytesRemaining = 0;
Eric Laurent3eaf66b2016-04-01 14:44:17 -07007069 // reset bytes written count to reflect that DSP buffers are empty after flush.
7070 mBytesWritten = 0;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08007071
Eric Laurentbfb1b832013-01-07 09:53:42 -08007072 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07007073 // discard any pending drain or write ack by incrementing sequence
7074 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
7075 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007076 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07007077 mCallbackThread->setWriteBlocked(mWriteAckSequence);
7078 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007079 }
7080}
7081
Haynes Mathew George05317d22016-05-03 16:34:26 -07007082void AudioFlinger::OffloadThread::invalidateTracks(audio_stream_type_t streamType)
7083{
7084 Mutex::Autolock _l(mLock);
Eric Laurent13084622016-05-17 10:51:49 -07007085 if (PlaybackThread::invalidateTracks_l(streamType)) {
7086 mFlushPending = true;
7087 }
Haynes Mathew George05317d22016-05-03 16:34:26 -07007088}
7089
Eric Laurentbfb1b832013-01-07 09:53:42 -08007090// ----------------------------------------------------------------------------
7091
Eric Laurent81784c32012-11-19 14:55:58 -08007092AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurent72e3f392015-05-20 14:43:50 -07007093 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id, bool systemReady)
jiabinc52b1ff2019-10-31 17:20:42 -07007094 : MixerThread(audioFlinger, mainThread->getOutput(), id,
Eric Laurent72e3f392015-05-20 14:43:50 -07007095 systemReady, DUPLICATING),
Eric Laurent81784c32012-11-19 14:55:58 -08007096 mWaitTimeMs(UINT_MAX)
7097{
7098 addOutputTrack(mainThread);
7099}
7100
7101AudioFlinger::DuplicatingThread::~DuplicatingThread()
7102{
7103 for (size_t i = 0; i < mOutputTracks.size(); i++) {
7104 mOutputTracks[i]->destroy();
7105 }
7106}
7107
7108void AudioFlinger::DuplicatingThread::threadLoop_mix()
7109{
7110 // mix buffers...
7111 if (outputsReady(outputTracks)) {
Glenn Kastend79072e2016-01-06 08:41:20 -08007112 mAudioMixer->process();
Eric Laurent81784c32012-11-19 14:55:58 -08007113 } else {
Eric Laurent02b57082014-11-07 17:28:28 -08007114 if (mMixerBufferValid) {
7115 memset(mMixerBuffer, 0, mMixerBufferSize);
7116 } else {
7117 memset(mSinkBuffer, 0, mSinkBufferSize);
7118 }
Eric Laurent81784c32012-11-19 14:55:58 -08007119 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007120 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007121 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08007122 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007123 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08007124}
7125
7126void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
7127{
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007128 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08007129 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007130 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007131 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007132 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007133 }
7134 } else if (mBytesWritten != 0) {
7135 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
7136 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08007137 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08007138 } else {
7139 // flush remaining overflow buffers in output tracks
7140 writeFrames = 0;
7141 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007142 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007143 }
7144}
7145
Eric Laurentbfb1b832013-01-07 09:53:42 -08007146ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08007147{
7148 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hung1c86ebe2018-05-29 20:29:08 -07007149 const ssize_t actualWritten = outputTracks[i]->write(mSinkBuffer, writeFrames);
7150
7151 // Consider the first OutputTrack for timestamp and frame counting.
7152
7153 // The threadLoop() generally assumes writing a full sink buffer size at a time.
7154 // Here, we correct for writeFrames of 0 (a stop) or underruns because
7155 // we always claim success.
7156 if (i == 0) {
7157 const ssize_t correction = mSinkBufferSize / mFrameSize - actualWritten;
7158 ALOGD_IF(correction != 0 && writeFrames != 0,
7159 "%s: writeFrames:%u actualWritten:%zd correction:%zd mFramesWritten:%lld",
7160 __func__, writeFrames, actualWritten, correction, (long long)mFramesWritten);
7161 mFramesWritten -= correction;
7162 }
7163
7164 // TODO: Report correction for the other output tracks and show in the dump.
Eric Laurent81784c32012-11-19 14:55:58 -08007165 }
Andy Hungcf10d742020-04-28 15:38:24 -07007166 if (mStandby) {
7167 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07007168 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -07007169 mStandby = false;
7170 }
Andy Hung25c2dac2014-02-27 14:56:00 -08007171 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08007172}
7173
7174void AudioFlinger::DuplicatingThread::threadLoop_standby()
7175{
7176 // DuplicatingThread implements standby by stopping all tracks
7177 for (size_t i = 0; i < outputTracks.size(); i++) {
7178 outputTracks[i]->stop();
7179 }
7180}
7181
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07007182void AudioFlinger::DuplicatingThread::dumpInternals_l(int fd, const Vector<String16>& args __unused)
Andy Hung1bc088a2018-02-09 15:57:31 -08007183{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07007184 MixerThread::dumpInternals_l(fd, args);
Andy Hung1bc088a2018-02-09 15:57:31 -08007185
7186 std::stringstream ss;
7187 const size_t numTracks = mOutputTracks.size();
7188 ss << " " << numTracks << " OutputTracks";
7189 if (numTracks > 0) {
7190 ss << ":";
7191 for (const auto &track : mOutputTracks) {
7192 const sp<ThreadBase> thread = track->thread().promote();
Andy Hungc0691382018-09-12 18:01:57 -07007193 ss << " (" << track->id() << " : ";
Andy Hung1bc088a2018-02-09 15:57:31 -08007194 if (thread.get() != nullptr) {
7195 ss << thread.get() << ", " << thread->id();
7196 } else {
7197 ss << "null";
7198 }
7199 ss << ")";
7200 }
7201 }
7202 ss << "\n";
7203 std::string result = ss.str();
7204 write(fd, result.c_str(), result.size());
7205}
7206
Eric Laurent81784c32012-11-19 14:55:58 -08007207void AudioFlinger::DuplicatingThread::saveOutputTracks()
7208{
7209 outputTracks = mOutputTracks;
7210}
7211
7212void AudioFlinger::DuplicatingThread::clearOutputTracks()
7213{
7214 outputTracks.clear();
7215}
7216
7217void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
7218{
7219 Mutex::Autolock _l(mLock);
Andy Hungc25b84a2015-01-14 19:04:10 -08007220 // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
7221 // Adjust for thread->sampleRate() to determine minimum buffer frame count.
7222 // Then triple buffer because Threads do not run synchronously and may not be clock locked.
7223 const size_t frameCount =
7224 3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
7225 // TODO: Consider asynchronous sample rate conversion to handle clock disparity
7226 // from different OutputTracks and their associated MixerThreads (e.g. one may
7227 // nearly empty and the other may be dropping data).
7228
Svet Ganov33761132021-05-13 22:51:08 +00007229 // TODO b/182392769: use attribution source util, move to server edge
7230 AttributionSourceState attributionSource = AttributionSourceState();
7231 attributionSource.uid = VALUE_OR_FATAL(legacy2aidl_uid_t_int32_t(
Philip P. Moltmannbda45752020-07-17 16:41:18 -07007232 IPCThreadState::self()->getCallingUid()));
Svet Ganov33761132021-05-13 22:51:08 +00007233 attributionSource.pid = VALUE_OR_FATAL(legacy2aidl_pid_t_int32_t(
Philip P. Moltmannbda45752020-07-17 16:41:18 -07007234 IPCThreadState::self()->getCallingPid()));
Svet Ganov33761132021-05-13 22:51:08 +00007235 attributionSource.token = sp<BBinder>::make();
Andy Hungc25b84a2015-01-14 19:04:10 -08007236 sp<OutputTrack> outputTrack = new OutputTrack(thread,
Eric Laurent81784c32012-11-19 14:55:58 -08007237 this,
7238 mSampleRate,
Andy Hungc25b84a2015-01-14 19:04:10 -08007239 mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08007240 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08007241 frameCount,
Svet Ganov33761132021-05-13 22:51:08 +00007242 attributionSource);
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07007243 status_t status = outputTrack != 0 ? outputTrack->initCheck() : (status_t) NO_MEMORY;
7244 if (status != NO_ERROR) {
7245 ALOGE("addOutputTrack() initCheck failed %d", status);
7246 return;
Eric Laurent81784c32012-11-19 14:55:58 -08007247 }
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07007248 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
7249 mOutputTracks.add(outputTrack);
7250 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
7251 updateWaitTime_l();
Eric Laurent81784c32012-11-19 14:55:58 -08007252}
7253
7254void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
7255{
7256 Mutex::Autolock _l(mLock);
7257 for (size_t i = 0; i < mOutputTracks.size(); i++) {
7258 if (mOutputTracks[i]->thread() == thread) {
7259 mOutputTracks[i]->destroy();
7260 mOutputTracks.removeAt(i);
7261 updateWaitTime_l();
Eric Laurentf6870ae2015-05-08 10:50:03 -07007262 if (thread->getOutput() == mOutput) {
7263 mOutput = NULL;
7264 }
Eric Laurent81784c32012-11-19 14:55:58 -08007265 return;
7266 }
7267 }
Eric Laurentf6870ae2015-05-08 10:50:03 -07007268 ALOGV("removeOutputTrack(): unknown thread: %p", thread);
Eric Laurent81784c32012-11-19 14:55:58 -08007269}
7270
7271// caller must hold mLock
7272void AudioFlinger::DuplicatingThread::updateWaitTime_l()
7273{
7274 mWaitTimeMs = UINT_MAX;
7275 for (size_t i = 0; i < mOutputTracks.size(); i++) {
7276 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
7277 if (strong != 0) {
7278 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
7279 if (waitTimeMs < mWaitTimeMs) {
7280 mWaitTimeMs = waitTimeMs;
7281 }
7282 }
7283 }
7284}
7285
7286
7287bool AudioFlinger::DuplicatingThread::outputsReady(
7288 const SortedVector< sp<OutputTrack> > &outputTracks)
7289{
7290 for (size_t i = 0; i < outputTracks.size(); i++) {
7291 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
7292 if (thread == 0) {
7293 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
7294 outputTracks[i].get());
7295 return false;
7296 }
7297 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
7298 // see note at standby() declaration
7299 if (playbackThread->standby() && !playbackThread->isSuspended()) {
7300 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
7301 thread.get());
7302 return false;
7303 }
7304 }
7305 return true;
7306}
7307
Kevin Rocard12381092018-04-11 09:19:59 -07007308void AudioFlinger::DuplicatingThread::sendMetadataToBackend_l(
7309 const StreamOutHalInterface::SourceMetadata& metadata)
Kevin Rocard069c2712018-03-29 19:09:14 -07007310{
Kevin Rocard12381092018-04-11 09:19:59 -07007311 for (auto& outputTrack : outputTracks) { // not mOutputTracks
7312 outputTrack->setMetadatas(metadata.tracks);
7313 }
Kevin Rocard069c2712018-03-29 19:09:14 -07007314}
7315
Eric Laurent81784c32012-11-19 14:55:58 -08007316uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
7317{
7318 return (mWaitTimeMs * 1000) / 2;
7319}
7320
7321void AudioFlinger::DuplicatingThread::cacheParameters_l()
7322{
7323 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
7324 updateWaitTime_l();
7325
7326 MixerThread::cacheParameters_l();
7327}
7328
Eric Laurentb3f315a2021-07-13 15:09:05 +02007329// ----------------------------------------------------------------------------
7330
Eric Laurentfa0f6742021-08-17 18:39:44 +02007331AudioFlinger::SpatializerThread::SpatializerThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurentb3f315a2021-07-13 15:09:05 +02007332 AudioStreamOut* output,
7333 audio_io_handle_t id,
7334 bool systemReady,
7335 audio_config_base_t *mixerConfig)
Eric Laurent1c5e2e32021-08-18 18:50:28 +02007336 : MixerThread(audioFlinger, output, id, systemReady, SPATIALIZER, mixerConfig)
Eric Laurentb3f315a2021-07-13 15:09:05 +02007337{
7338}
7339
Eric Laurent68a40a82022-05-03 18:15:04 +02007340void AudioFlinger::SpatializerThread::onFirstRef() {
7341 PlaybackThread::onFirstRef();
7342
7343 Mutex::Autolock _l(mLock);
7344 status_t status = mOutput->stream->setLatencyModeCallback(this);
7345 if (status != INVALID_OPERATION) {
7346 updateHalSupportedLatencyModes_l();
7347 }
7348}
7349
7350status_t AudioFlinger::SpatializerThread::createAudioPatch_l(const struct audio_patch *patch,
7351 audio_patch_handle_t *handle)
7352{
7353 status_t status = MixerThread::createAudioPatch_l(patch, handle);
7354 updateHalSupportedLatencyModes_l();
7355 return status;
7356}
7357
7358void AudioFlinger::SpatializerThread::updateHalSupportedLatencyModes_l() {
7359 std::vector<audio_latency_mode_t> latencyModes;
7360 if (mOutput->stream->getRecommendedLatencyModes(&latencyModes) != NO_ERROR) {
7361 latencyModes.clear();
7362 }
7363 if (latencyModes != mSupportedLatencyModes) {
7364 mSupportedLatencyModes.swap(latencyModes);
7365 sendHalLatencyModesChangedEvent_l();
7366 }
7367}
7368
7369void AudioFlinger::SpatializerThread::onHalLatencyModesChanged_l() {
7370 mAudioFlinger->onSupportedLatencyModesChanged(mId, mSupportedLatencyModes);
7371}
7372
7373void AudioFlinger::SpatializerThread::setHalLatencyMode_l() {
7374 // if mSupportedLatencyModes is empty, the HAL stream does not support
7375 // latency mode control and we can exit.
7376 if (mSupportedLatencyModes.empty()) {
7377 return;
7378 }
7379 audio_latency_mode_t latencyMode = AUDIO_LATENCY_MODE_FREE;
7380 if (mSupportedLatencyModes.size() == 1) {
7381 // If the HAL only support one latency mode currently, confirm the choice
7382 latencyMode = mSupportedLatencyModes[0];
7383 } else if (mSupportedLatencyModes.size() > 1) {
7384 // Request low latency if:
7385 // - The low latency mode is requested by the spatializer controller
7386 // (mRequestedLatencyMode = AUDIO_LATENCY_MODE_LOW)
7387 // AND
7388 // - At least one active track is spatialized
7389 bool hasSpatializedActiveTrack = false;
7390 for (const auto& track : mActiveTracks) {
7391 if (track->isSpatialized()) {
7392 hasSpatializedActiveTrack = true;
7393 break;
7394 }
7395 }
7396 if (hasSpatializedActiveTrack && mRequestedLatencyMode == AUDIO_LATENCY_MODE_LOW) {
7397 latencyMode = AUDIO_LATENCY_MODE_LOW;
7398 }
7399 }
7400
7401 if (latencyMode != mSetLatencyMode) {
7402 status_t status = mOutput->stream->setLatencyMode(latencyMode);
7403 if (status == NO_ERROR) {
7404 mSetLatencyMode = latencyMode;
7405 }
7406 }
7407}
7408
7409status_t AudioFlinger::SpatializerThread::setRequestedLatencyMode(audio_latency_mode_t mode) {
7410 if (mode != AUDIO_LATENCY_MODE_LOW && mode != AUDIO_LATENCY_MODE_FREE) {
7411 return BAD_VALUE;
7412 }
7413 Mutex::Autolock _l(mLock);
7414 mRequestedLatencyMode = mode;
7415 return NO_ERROR;
7416}
7417
7418status_t AudioFlinger::SpatializerThread::getSupportedLatencyModes(
7419 std::vector<audio_latency_mode_t>* modes) {
7420 if (modes == nullptr) {
7421 return BAD_VALUE;
7422 }
7423 Mutex::Autolock _l(mLock);
7424 *modes = mSupportedLatencyModes;
7425 return NO_ERROR;
7426}
7427
Eric Laurentfa0f6742021-08-17 18:39:44 +02007428void AudioFlinger::SpatializerThread::checkOutputStageEffects()
Eric Laurentb3f315a2021-07-13 15:09:05 +02007429{
7430 bool hasVirtualizer = false;
7431 bool hasDownMixer = false;
7432 sp<EffectHandle> finalDownMixer;
7433 {
7434 Mutex::Autolock _l(mLock);
7435 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_STAGE);
7436 if (chain != 0) {
Eric Laurent1c5e2e32021-08-18 18:50:28 +02007437 hasVirtualizer = chain->getEffectFromType_l(FX_IID_SPATIALIZER) != nullptr;
Eric Laurentb3f315a2021-07-13 15:09:05 +02007438 hasDownMixer = chain->getEffectFromType_l(EFFECT_UIID_DOWNMIX) != nullptr;
7439 }
7440
7441 finalDownMixer = mFinalDownMixer;
7442 mFinalDownMixer.clear();
7443 }
7444
7445 if (hasVirtualizer) {
7446 if (finalDownMixer != nullptr) {
7447 int32_t ret;
7448 finalDownMixer->disable(&ret);
7449 }
7450 finalDownMixer.clear();
7451 } else if (!hasDownMixer) {
7452 std::vector<effect_descriptor_t> descriptors;
7453 status_t status = mAudioFlinger->mEffectsFactoryHal->getDescriptors(
7454 EFFECT_UIID_DOWNMIX, &descriptors);
7455 if (status != NO_ERROR) {
7456 return;
7457 }
7458 ALOG_ASSERT(!descriptors.empty(),
7459 "%s getDescriptors() returned no error but empty list", __func__);
7460
7461 finalDownMixer = createEffect_l(nullptr /*client*/, nullptr /*effectClient*/,
7462 0 /*priority*/, AUDIO_SESSION_OUTPUT_STAGE, &descriptors[0], nullptr /*enabled*/,
Eric Laurentde8caf42021-08-11 17:19:25 +02007463 &status, false /*pinned*/, false /*probe*/, false /*notifyFramesProcessed*/);
Eric Laurentb3f315a2021-07-13 15:09:05 +02007464
7465 if (finalDownMixer == nullptr || (status != NO_ERROR && status != ALREADY_EXISTS)) {
7466 ALOGW("%s error creating downmixer %d", __func__, status);
7467 finalDownMixer.clear();
7468 } else {
7469 int32_t ret;
7470 finalDownMixer->enable(&ret);
7471 }
7472 }
7473
7474 {
7475 Mutex::Autolock _l(mLock);
7476 mFinalDownMixer = finalDownMixer;
7477 }
7478}
7479
Eric Laurent68a40a82022-05-03 18:15:04 +02007480void AudioFlinger::SpatializerThread::onRecommendedLatencyModeChanged(
7481 std::vector<audio_latency_mode_t> modes) {
7482 Mutex::Autolock _l(mLock);
7483 if (modes != mSupportedLatencyModes) {
7484 mSupportedLatencyModes.swap(modes);
7485 sendHalLatencyModesChangedEvent_l();
7486 }
7487}
Eric Laurent6acd1d42017-01-04 14:23:29 -08007488
Eric Laurent81784c32012-11-19 14:55:58 -08007489// ----------------------------------------------------------------------------
7490// Record
7491// ----------------------------------------------------------------------------
7492
7493AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
7494 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08007495 audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -07007496 bool systemReady
Glenn Kasten46909e72013-02-26 09:20:22 -08007497 ) :
Andy Hungcf10d742020-04-28 15:38:24 -07007498 ThreadBase(audioFlinger, id, RECORD, systemReady, false /* isOut */),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007499 mInput(input),
Mikhail Naganov2534b382019-09-25 13:05:02 -07007500 mSource(mInput),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007501 mActiveTracks(&this->mLocalLog),
7502 mRsmpInBuffer(NULL),
Glenn Kasten1b291842016-07-18 14:55:21 -07007503 // mRsmpInFrames, mRsmpInFramesP2, and mRsmpInFramesOA are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007504 mRsmpInRear(0)
Glenn Kastenb880f5e2014-05-07 08:43:45 -07007505 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
7506 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007507 // mFastCapture below
7508 , mFastCaptureFutex(0)
7509 // mInputSource
7510 // mPipeSink
7511 // mPipeSource
7512 , mPipeFramesP2(0)
7513 // mPipeMemory
7514 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07007515 , mFastTrackAvail(false)
Eric Laurentd8365c52017-07-16 15:27:05 -07007516 , mBtNrecSuspended(false)
Eric Laurent81784c32012-11-19 14:55:58 -08007517{
Glenn Kastend7dca052015-03-05 16:05:54 -08007518 snprintf(mThreadName, kThreadNameLength, "AudioIn_%X", id);
7519 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08007520
George Burgess IVa8f90c12020-05-14 11:27:19 -07007521 if (mInput->audioHwDev != nullptr) {
Andy Hungc8fddf32018-08-08 18:32:37 -07007522 mIsMsdDevice = strcmp(
7523 mInput->audioHwDev->moduleName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0;
7524 }
7525
Glenn Kastendeca2ae2014-02-07 10:25:56 -08007526 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007527
Andy Hungc8fddf32018-08-08 18:32:37 -07007528 // TODO: We may also match on address as well as device type for
7529 // AUDIO_DEVICE_IN_BUS, AUDIO_DEVICE_IN_BLUETOOTH_A2DP, AUDIO_DEVICE_IN_REMOTE_SUBMIX
jiabinc52b1ff2019-10-31 17:20:42 -07007530 // TODO: This property should be ensure that only contains one single device type.
7531 mTimestampCorrectedDevice = (audio_devices_t)property_get_int64(
7532 "audio.timestamp.corrected_input_device",
Andy Hungc8fddf32018-08-08 18:32:37 -07007533 (int64_t)(mIsMsdDevice ? AUDIO_DEVICE_IN_BUS // turn on by default for MSD
7534 : AUDIO_DEVICE_NONE));
7535
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007536 // create an NBAIO source for the HAL input stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07007537 mInputSource = new AudioStreamInSource(input->stream);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007538 size_t numCounterOffers = 0;
7539 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07007540#if !LOG_NDEBUG
7541 ssize_t index =
7542#else
7543 (void)
7544#endif
7545 mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007546 ALOG_ASSERT(index == 0);
7547
7548 // initialize fast capture depending on configuration
7549 bool initFastCapture;
7550 switch (kUseFastCapture) {
7551 case FastCapture_Never:
7552 initFastCapture = false;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007553 ALOGV("%p kUseFastCapture = Never, initFastCapture = false", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007554 break;
7555 case FastCapture_Always:
7556 initFastCapture = true;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007557 ALOGV("%p kUseFastCapture = Always, initFastCapture = true", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007558 break;
7559 case FastCapture_Static:
Glenn Kasteneb9487e2015-07-22 09:15:17 -07007560 initFastCapture = (mFrameCount * 1000) / mSampleRate < kMinNormalCaptureBufferSizeMs;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007561 ALOGV("%p kUseFastCapture = Static, (%lld * 1000) / %u vs %u, initFastCapture = %d",
7562 this, (long long)mFrameCount, mSampleRate, kMinNormalCaptureBufferSizeMs,
7563 initFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007564 break;
7565 // case FastCapture_Dynamic:
7566 }
7567
7568 if (initFastCapture) {
Glenn Kastend198b852015-03-16 14:55:53 -07007569 // create a Pipe for FastCapture to write to, and for us and fast tracks to read from
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007570 NBAIO_Format format = mInputSource->format();
Glenn Kasten1b291842016-07-18 14:55:21 -07007571 // quadruple-buffering of 20 ms each; this ensures we can sleep for 20ms in RecordThread
7572 size_t pipeFramesP2 = roundup(4 * FMS_20 * mSampleRate / 1000);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007573 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007574 void *pipeBuffer = nullptr;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007575 const sp<MemoryDealer> roHeap(readOnlyHeap());
7576 sp<IMemory> pipeMemory;
7577 if ((roHeap == 0) ||
7578 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07007579 (pipeBuffer = pipeMemory->unsecurePointer()) == nullptr) {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007580 ALOGE("not enough memory for pipe buffer size=%zu; "
7581 "roHeap=%p, pipeMemory=%p, pipeBuffer=%p; roHeapSize: %lld",
7582 pipeSize, roHeap.get(), pipeMemory.get(), pipeBuffer,
7583 (long long)kRecordThreadReadOnlyHeapSize);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007584 goto failed;
7585 }
7586 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
7587 memset(pipeBuffer, 0, pipeSize);
7588 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
7589 const NBAIO_Format offers[1] = {format};
7590 size_t numCounterOffers = 0;
7591 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
7592 ALOG_ASSERT(index == 0);
7593 mPipeSink = pipe;
7594 PipeReader *pipeReader = new PipeReader(*pipe);
7595 numCounterOffers = 0;
7596 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
7597 ALOG_ASSERT(index == 0);
7598 mPipeSource = pipeReader;
7599 mPipeFramesP2 = pipeFramesP2;
7600 mPipeMemory = pipeMemory;
7601
7602 // create fast capture
7603 mFastCapture = new FastCapture();
7604 FastCaptureStateQueue *sq = mFastCapture->sq();
7605#ifdef STATE_QUEUE_DUMP
7606 // FIXME
7607#endif
7608 FastCaptureState *state = sq->begin();
7609 state->mCblk = NULL;
7610 state->mInputSource = mInputSource.get();
7611 state->mInputSourceGen++;
7612 state->mPipeSink = pipe;
7613 state->mPipeSinkGen++;
7614 state->mFrameCount = mFrameCount;
7615 state->mCommand = FastCaptureState::COLD_IDLE;
7616 // already done in constructor initialization list
7617 //mFastCaptureFutex = 0;
7618 state->mColdFutexAddr = &mFastCaptureFutex;
7619 state->mColdGen++;
7620 state->mDumpState = &mFastCaptureDumpState;
7621#ifdef TEE_SINK
7622 // FIXME
7623#endif
7624 mFastCaptureNBLogWriter = audioFlinger->newWriter_l(kFastCaptureLogSize, "FastCapture");
7625 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
7626 sq->end();
7627 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
7628
7629 // start the fast capture
7630 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
7631 pid_t tid = mFastCapture->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07007632 sendPrioConfigEvent(getpid(), tid, kPriorityFastCapture, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08007633 stream()->setHalThreadPriority(kPriorityFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007634#ifdef AUDIO_WATCHDOG
7635 // FIXME
7636#endif
7637
Glenn Kasten6e6704c2014-07-03 10:20:00 -07007638 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007639 }
Andy Hung8946a282018-04-19 20:04:56 -07007640#ifdef TEE_SINK
7641 mTee.set(mInputSource->format(), NBAIO_Tee::TEE_FLAG_INPUT_THREAD);
7642 mTee.setId(std::string("_") + std::to_string(mId) + "_C");
7643#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007644failed: ;
7645
7646 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08007647}
7648
Eric Laurent81784c32012-11-19 14:55:58 -08007649AudioFlinger::RecordThread::~RecordThread()
7650{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007651 if (mFastCapture != 0) {
7652 FastCaptureStateQueue *sq = mFastCapture->sq();
7653 FastCaptureState *state = sq->begin();
7654 if (state->mCommand == FastCaptureState::COLD_IDLE) {
7655 int32_t old = android_atomic_inc(&mFastCaptureFutex);
7656 if (old == -1) {
7657 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
7658 }
7659 }
7660 state->mCommand = FastCaptureState::EXIT;
7661 sq->end();
7662 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
7663 mFastCapture->join();
7664 mFastCapture.clear();
7665 }
7666 mAudioFlinger->unregisterWriter(mFastCaptureNBLogWriter);
Glenn Kasten481fb672013-09-30 14:39:28 -07007667 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung57446612015-04-19 23:56:46 -07007668 free(mRsmpInBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08007669}
7670
7671void AudioFlinger::RecordThread::onFirstRef()
7672{
Glenn Kastend7dca052015-03-05 16:05:54 -08007673 run(mThreadName, PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08007674}
7675
Eric Laurent555530a2017-02-07 18:17:24 -08007676void AudioFlinger::RecordThread::preExit()
7677{
7678 ALOGV(" preExit()");
7679 Mutex::Autolock _l(mLock);
7680 for (size_t i = 0; i < mTracks.size(); i++) {
7681 sp<RecordTrack> track = mTracks[i];
7682 track->invalidate();
7683 }
7684 mActiveTracks.clear();
7685 mStartStopCond.broadcast();
7686}
7687
Eric Laurent81784c32012-11-19 14:55:58 -08007688bool AudioFlinger::RecordThread::threadLoop()
7689{
Eric Laurent81784c32012-11-19 14:55:58 -08007690 nsecs_t lastWarning = 0;
7691
7692 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08007693
Glenn Kastenf10ffec2013-11-20 16:40:08 -08007694reacquire_wakelock:
7695 sp<RecordTrack> activeTrack;
7696 {
7697 Mutex::Autolock _l(mLock);
Andy Hungdae27702016-10-31 14:01:16 -07007698 acquireWakeLock_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08007699 }
7700
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007701 // used to request a deferred sleep, to be executed later while mutex is unlocked
7702 uint32_t sleepUs = 0;
7703
Andy Hung446f4df2019-02-21 12:26:41 -08007704 int64_t lastLoopCountRead = -2; // never matches "previous" loop, when loopCount = 0.
7705
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007706 // loop while there is work to do
Andy Hung446f4df2019-02-21 12:26:41 -08007707 for (int64_t loopCount = 0;; ++loopCount) { // loopCount used for statistics tracking
Glenn Kastenc527a7c2013-08-13 15:43:49 -07007708 Vector< sp<EffectChain> > effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07007709
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007710 // activeTracks accumulates a copy of a subset of mActiveTracks
7711 Vector< sp<RecordTrack> > activeTracks;
7712
Glenn Kasten735f45f2014-08-18 15:51:59 -07007713 // reference to the (first and only) active fast track
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007714 sp<RecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07007715
Glenn Kasten735f45f2014-08-18 15:51:59 -07007716 // reference to a fast track which is about to be removed
7717 sp<RecordTrack> fastTrackToRemove;
7718
Eric Laurent33403f02020-05-29 18:35:06 -07007719 bool silenceFastCapture = false;
7720
Eric Laurent81784c32012-11-19 14:55:58 -08007721 { // scope for mLock
7722 Mutex::Autolock _l(mLock);
Eric Laurent000a4192014-01-29 15:17:32 -08007723
Eric Laurent021cf962014-05-13 10:18:14 -07007724 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08007725
Eric Laurent000a4192014-01-29 15:17:32 -08007726 // check exitPending here because checkForNewParameters_l() and
7727 // checkForNewParameters_l() can temporarily release mLock
7728 if (exitPending()) {
7729 break;
7730 }
7731
Eric Laurent5c25d562016-07-13 17:17:45 -07007732 // sleep with mutex unlocked
7733 if (sleepUs > 0) {
Glenn Kastenf9715e42016-07-13 14:02:03 -07007734 ATRACE_BEGIN("sleepC");
Eric Laurent5c25d562016-07-13 17:17:45 -07007735 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)sleepUs));
7736 ATRACE_END();
7737 sleepUs = 0;
7738 continue;
7739 }
7740
Glenn Kasten2b806402013-11-20 16:37:38 -08007741 // if no active track(s), then standby and release wakelock
7742 size_t size = mActiveTracks.size();
7743 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07007744 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07007745 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08007746 releaseWakeLock_l();
7747 ALOGV("RecordThread: loop stopping");
7748 // go to sleep
7749 mWaitWorkCV.wait(mLock);
7750 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08007751 goto reacquire_wakelock;
7752 }
7753
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007754 bool doBroadcast = false;
Eric Laurent5c25d562016-07-13 17:17:45 -07007755 bool allStopped = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007756 for (size_t i = 0; i < size; ) {
Glenn Kasten9e982352013-08-14 14:39:50 -07007757
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007758 activeTrack = mActiveTracks[i];
7759 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07007760 if (activeTrack->isFastTrack()) {
7761 ALOG_ASSERT(fastTrackToRemove == 0);
7762 fastTrackToRemove = activeTrack;
7763 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007764 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08007765 mActiveTracks.remove(activeTrack);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007766 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07007767 continue;
7768 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007769
7770 TrackBase::track_state activeTrackState = activeTrack->mState;
7771 switch (activeTrackState) {
7772
7773 case TrackBase::PAUSING:
7774 mActiveTracks.remove(activeTrack);
Andy Hungce685402018-10-05 17:23:27 -07007775 activeTrack->mState = TrackBase::PAUSED;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007776 doBroadcast = true;
7777 size--;
7778 continue;
7779
7780 case TrackBase::STARTING_1:
7781 sleepUs = 10000;
7782 i++;
Eric Laurent5c25d562016-07-13 17:17:45 -07007783 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007784 continue;
7785
7786 case TrackBase::STARTING_2:
7787 doBroadcast = true;
Andy Hungcf10d742020-04-28 15:38:24 -07007788 if (mStandby) {
7789 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07007790 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -07007791 mStandby = false;
7792 }
Glenn Kasten9e982352013-08-14 14:39:50 -07007793 activeTrack->mState = TrackBase::ACTIVE;
Eric Laurent5c25d562016-07-13 17:17:45 -07007794 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007795 break;
7796
7797 case TrackBase::ACTIVE:
Eric Laurent5c25d562016-07-13 17:17:45 -07007798 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007799 break;
7800
Andy Hungce685402018-10-05 17:23:27 -07007801 case TrackBase::IDLE: // cannot be on ActiveTracks if idle
7802 case TrackBase::PAUSED: // cannot be on ActiveTracks if paused
7803 case TrackBase::STOPPED: // cannot be on ActiveTracks if destroyed/terminated
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007804 default:
Andy Hungce685402018-10-05 17:23:27 -07007805 LOG_ALWAYS_FATAL("%s: Unexpected active track state:%d, id:%d, tracks:%zu",
7806 __func__, activeTrackState, activeTrack->id(), size);
Glenn Kasten9e982352013-08-14 14:39:50 -07007807 }
Glenn Kasten9e982352013-08-14 14:39:50 -07007808
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007809 if (activeTrack->isFastTrack()) {
7810 ALOG_ASSERT(!mFastTrackAvail);
7811 ALOG_ASSERT(fastTrack == 0);
Eric Laurent33403f02020-05-29 18:35:06 -07007812 // if the active fast track is silenced either:
7813 // 1) silence the whole capture from fast capture buffer if this is
7814 // the only active track
7815 // 2) invalidate this track: this will cause the client to reconnect and possibly
7816 // be invalidated again until unsilenced
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02007817 bool invalidate = false;
Eric Laurent33403f02020-05-29 18:35:06 -07007818 if (activeTrack->isSilenced()) {
7819 if (size > 1) {
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02007820 invalidate = true;
Eric Laurent33403f02020-05-29 18:35:06 -07007821 } else {
7822 silenceFastCapture = true;
7823 }
7824 }
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02007825 // Invalidate fast tracks if access to audio history is required as this is not
7826 // possible with fast tracks. Once the fast track has been invalidated, no new
7827 // fast track will be created until mMaxSharedAudioHistoryMs is cleared.
7828 if (mMaxSharedAudioHistoryMs != 0) {
7829 invalidate = true;
7830 }
7831 if (invalidate) {
7832 activeTrack->invalidate();
7833 ALOG_ASSERT(fastTrackToRemove == 0);
7834 fastTrackToRemove = activeTrack;
7835 removeTrack_l(activeTrack);
7836 mActiveTracks.remove(activeTrack);
7837 size--;
7838 continue;
7839 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007840 fastTrack = activeTrack;
7841 }
Eric Laurent33403f02020-05-29 18:35:06 -07007842
7843 activeTracks.add(activeTrack);
7844 i++;
7845
Glenn Kasten9e982352013-08-14 14:39:50 -07007846 }
Eric Laurent5c25d562016-07-13 17:17:45 -07007847
Andy Hungdae27702016-10-31 14:01:16 -07007848 mActiveTracks.updatePowerState(this);
7849
Kevin Rocard069c2712018-03-29 19:09:14 -07007850 updateMetadata_l();
7851
Eric Laurent5c25d562016-07-13 17:17:45 -07007852 if (allStopped) {
7853 standbyIfNotAlreadyInStandby();
7854 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007855 if (doBroadcast) {
7856 mStartStopCond.broadcast();
7857 }
7858
7859 // sleep if there are no active tracks to process
Eric Tan39ec8d62018-07-24 09:49:29 -07007860 if (activeTracks.isEmpty()) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007861 if (sleepUs == 0) {
7862 sleepUs = kRecordThreadSleepUs;
7863 }
7864 continue;
7865 }
7866 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07007867
Eric Laurent81784c32012-11-19 14:55:58 -08007868 lockEffectChains_l(effectChains);
7869 }
7870
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007871 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07007872
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007873 size_t size = effectChains.size();
7874 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07007875 // thread mutex is not locked, but effect chain is locked
7876 effectChains[i]->process_l();
7877 }
7878
Glenn Kasten735f45f2014-08-18 15:51:59 -07007879 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007880 if (mFastCapture != 0) {
7881 FastCaptureStateQueue *sq = mFastCapture->sq();
7882 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07007883 bool didModify = false;
7884 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007885 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
7886 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
7887 if (state->mCommand == FastCaptureState::COLD_IDLE) {
7888 int32_t old = android_atomic_inc(&mFastCaptureFutex);
7889 if (old == -1) {
7890 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
7891 }
7892 }
7893 state->mCommand = FastCaptureState::READ_WRITE;
7894#if 0 // FIXME
7895 mFastCaptureDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08007896 FastThreadDumpState::kSamplingNforLowRamDevice :
7897 FastThreadDumpState::kSamplingN);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007898#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07007899 didModify = true;
7900 }
7901 audio_track_cblk_t *cblkOld = state->mCblk;
7902 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
7903 if (cblkNew != cblkOld) {
7904 state->mCblk = cblkNew;
7905 // block until acked if removing a fast track
7906 if (cblkOld != NULL) {
7907 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
7908 }
7909 didModify = true;
7910 }
jiabin01c8f562018-07-19 17:47:28 -07007911 AudioBufferProvider* abp = (fastTrack != 0 && fastTrack->isPatchTrack()) ?
7912 reinterpret_cast<AudioBufferProvider*>(fastTrack.get()) : nullptr;
7913 if (state->mFastPatchRecordBufferProvider != abp) {
7914 state->mFastPatchRecordBufferProvider = abp;
7915 state->mFastPatchRecordFormat = fastTrack == 0 ?
7916 AUDIO_FORMAT_INVALID : fastTrack->format();
7917 didModify = true;
7918 }
Eric Laurent33403f02020-05-29 18:35:06 -07007919 if (state->mSilenceCapture != silenceFastCapture) {
7920 state->mSilenceCapture = silenceFastCapture;
7921 didModify = true;
7922 }
Glenn Kasten735f45f2014-08-18 15:51:59 -07007923 sq->end(didModify);
7924 if (didModify) {
7925 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007926#if 0
7927 if (kUseFastCapture == FastCapture_Dynamic) {
7928 mNormalSource = mPipeSource;
7929 }
7930#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007931 }
7932 }
7933
Glenn Kasten735f45f2014-08-18 15:51:59 -07007934 // now run the fast track destructor with thread mutex unlocked
7935 fastTrackToRemove.clear();
7936
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007937 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
7938 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
7939 // slow, then this RecordThread will overrun by not calling HAL read often enough.
7940 // If destination is non-contiguous, first read past the nominal end of buffer, then
7941 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07007942
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007943 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007944 ssize_t framesRead;
Andy Hung446f4df2019-02-21 12:26:41 -08007945 const int64_t lastIoBeginNs = systemTime(); // start IO timing
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007946
7947 // If an NBAIO source is present, use it to read the normal capture's data
7948 if (mPipeSource != 0) {
Andy Hung156317a2018-08-02 11:49:29 -07007949 size_t framesToRead = min(mRsmpInFramesOA - rear, mRsmpInFramesP2 / 2);
Andy Hungd5b638f2018-04-30 13:56:10 -07007950
7951 // The audio fifo read() returns OVERRUN on overflow, and advances the read pointer
7952 // to the full buffer point (clearing the overflow condition). Upon OVERRUN error,
7953 // we immediately retry the read() to get data and prevent another overflow.
7954 for (int retries = 0; retries <= 2; ++retries) {
7955 ALOGW_IF(retries > 0, "overrun on read from pipe, retry #%d", retries);
7956 framesRead = mPipeSource->read((uint8_t*)mRsmpInBuffer + rear * mFrameSize,
7957 framesToRead);
7958 if (framesRead != OVERRUN) break;
7959 }
7960
Andy Hung7a3dc6b2018-05-01 16:39:51 -07007961 const ssize_t availableToRead = mPipeSource->availableToRead();
7962 if (availableToRead >= 0) {
Robert Wu06db0a32021-08-10 19:05:34 +00007963 mMonopipePipeDepthStats.add(availableToRead);
Glenn Kastena2f59b32020-08-03 16:37:24 -07007964 // PipeSource is the primary clock. It is up to the AudioRecord client to keep up.
Andy Hung7a3dc6b2018-05-01 16:39:51 -07007965 LOG_ALWAYS_FATAL_IF((size_t)availableToRead > mPipeFramesP2,
7966 "more frames to read than fifo size, %zd > %zu",
7967 availableToRead, mPipeFramesP2);
7968 const size_t pipeFramesFree = mPipeFramesP2 - availableToRead;
7969 const size_t sleepFrames = min(pipeFramesFree, mRsmpInFramesP2) / 2;
7970 ALOGVV("mPipeFramesP2:%zu mRsmpInFramesP2:%zu sleepFrames:%zu availableToRead:%zd",
7971 mPipeFramesP2, mRsmpInFramesP2, sleepFrames, availableToRead);
Glenn Kasten1b291842016-07-18 14:55:21 -07007972 sleepUs = (sleepFrames * 1000000LL) / mSampleRate;
7973 }
7974 if (framesRead < 0) {
7975 status_t status = (status_t) framesRead;
7976 switch (status) {
7977 case OVERRUN:
7978 ALOGW("overrun on read from pipe");
7979 framesRead = 0;
7980 break;
7981 case NEGOTIATE:
7982 ALOGE("re-negotiation is needed");
7983 framesRead = -1; // Will cause an attempt to recover.
7984 break;
7985 default:
7986 ALOGE("unknown error %d on read from pipe", status);
7987 break;
7988 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007989 }
7990 // otherwise use the HAL / AudioStreamIn directly
7991 } else {
Glenn Kastenec6a7032016-03-14 07:40:23 -07007992 ATRACE_BEGIN("read");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007993 size_t bytesRead;
Mikhail Naganov2534b382019-09-25 13:05:02 -07007994 status_t result = mSource->read(
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007995 (uint8_t*)mRsmpInBuffer + rear * mFrameSize, mBufferSize, &bytesRead);
Glenn Kastenec6a7032016-03-14 07:40:23 -07007996 ATRACE_END();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007997 if (result < 0) {
7998 framesRead = result;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007999 } else {
8000 framesRead = bytesRead / mFrameSize;
8001 }
8002 }
8003
Andy Hung446f4df2019-02-21 12:26:41 -08008004 const int64_t lastIoEndNs = systemTime(); // end IO timing
8005
Andy Hung3f0c9022016-01-15 17:49:46 -08008006 // Update server timestamp with server stats
8007 // systemTime() is optional if the hardware supports timestamps.
Andy Hung743f6402020-06-03 13:17:04 -07008008 if (framesRead >= 0) {
8009 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += framesRead;
8010 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = lastIoEndNs;
8011 }
Andy Hung3f0c9022016-01-15 17:49:46 -08008012
8013 // Update server timestamp with kernel stats
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008014 if (mPipeSource.get() == nullptr /* don't obtain for FastCapture, could block */) {
Andy Hung3f0c9022016-01-15 17:49:46 -08008015 int64_t position, time;
Andy Hung2e2c0bb2018-06-11 19:13:11 -07008016 if (mStandby) {
Dean Wheatley12473e92021-03-18 23:00:55 +11008017 mTimestampVerifier.discontinuity(audio_is_linear_pcm(mFormat) ?
8018 mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS :
8019 mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Mikhail Naganov2534b382019-09-25 13:05:02 -07008020 } else if (mSource->getCapturePosition(&position, &time) == NO_ERROR
Andy Hungc8fddf32018-08-08 18:32:37 -07008021 && time > mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]) {
8022
8023 mTimestampVerifier.add(position, time, mSampleRate);
8024
8025 // Correct timestamps
8026 if (isTimestampCorrectionEnabled()) {
Dean Wheatley56a583e2020-05-08 15:12:17 +10008027 ALOGVV("TS_BEFORE: %d %lld %lld",
Andy Hungc8fddf32018-08-08 18:32:37 -07008028 id(), (long long)time, (long long)position);
8029 auto correctedTimestamp = mTimestampVerifier.getLastCorrectedTimestamp();
8030 position = correctedTimestamp.mFrames;
8031 time = correctedTimestamp.mTimeNs;
Dean Wheatley56a583e2020-05-08 15:12:17 +10008032 ALOGVV("TS_AFTER: %d %lld %lld",
Andy Hungc8fddf32018-08-08 18:32:37 -07008033 id(), (long long)time, (long long)position);
8034 }
8035
Andy Hung3f0c9022016-01-15 17:49:46 -08008036 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = position;
8037 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] = time;
8038 // Note: In general record buffers should tend to be empty in
8039 // a properly running pipeline.
8040 //
8041 // Also, it is not advantageous to call get_presentation_position during the read
8042 // as the read obtains a lock, preventing the timestamp call from executing.
Andy Hung2e2c0bb2018-06-11 19:13:11 -07008043 } else {
8044 mTimestampVerifier.error();
Andy Hung3f0c9022016-01-15 17:49:46 -08008045 }
8046 }
Andy Hunge6c37112019-02-26 17:38:10 -08008047
8048 // From the timestamp, input read latency is negative output write latency.
8049 const audio_input_flags_t flags = mInput != NULL ? mInput->flags : AUDIO_INPUT_FLAG_NONE;
8050 const double latencyMs = RecordTrack::checkServerLatencySupported(mFormat, flags)
8051 ? - mTimestamp.getOutputServerLatencyMs(mSampleRate) : 0.;
8052 if (latencyMs != 0.) { // note 0. means timestamp is empty.
8053 mLatencyMs.add(latencyMs);
8054 }
8055
Andy Hung3f0c9022016-01-15 17:49:46 -08008056 // Use this to track timestamp information
8057 // ALOGD("%s", mTimestamp.toString().c_str());
8058
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008059 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07008060 ALOGE("read failed: framesRead=%zd", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008061 // Force input into standby so that it tries to recover at next read attempt
8062 inputStandBy();
8063 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008064 }
8065 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008066 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008067 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008068 ALOG_ASSERT(framesRead > 0);
Andy Hung6427e442018-08-09 12:51:02 -07008069 mFramesRead += framesRead;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008070
Andy Hung8946a282018-04-19 20:04:56 -07008071#ifdef TEE_SINK
8072 (void)mTee.write((uint8_t*)mRsmpInBuffer + rear * mFrameSize, framesRead);
8073#endif
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008074 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008075 {
8076 size_t part1 = mRsmpInFramesP2 - rear;
8077 if ((size_t) framesRead > part1) {
Andy Hung57446612015-04-19 23:56:46 -07008078 memcpy(mRsmpInBuffer, (uint8_t*)mRsmpInBuffer + mRsmpInFramesP2 * mFrameSize,
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008079 (framesRead - part1) * mFrameSize);
8080 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008081 }
Dean Wheatleyfd56e812020-11-06 22:32:21 +11008082 mRsmpInRear = audio_utils::safe_add_overflow(mRsmpInRear, (int32_t)framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008083
8084 size = activeTracks.size();
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008085
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008086 // loop over each active track
8087 for (size_t i = 0; i < size; i++) {
8088 activeTrack = activeTracks[i];
8089
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008090 // skip fast tracks, as those are handled directly by FastCapture
8091 if (activeTrack->isFastTrack()) {
8092 continue;
8093 }
8094
Andy Hung73c02e42015-03-29 01:13:58 -07008095 // TODO: This code probably should be moved to RecordTrack.
Andy Hung97a893e2015-03-29 01:03:07 -07008096 // TODO: Update the activeTrack buffer converter in case of reconfigure.
8097
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008098 enum {
8099 OVERRUN_UNKNOWN,
8100 OVERRUN_TRUE,
8101 OVERRUN_FALSE
8102 } overrun = OVERRUN_UNKNOWN;
8103
8104 // loop over getNextBuffer to handle circular sink
8105 for (;;) {
8106
8107 activeTrack->mSink.frameCount = ~0;
8108 status_t status = activeTrack->getNextBuffer(&activeTrack->mSink);
8109 size_t framesOut = activeTrack->mSink.frameCount;
8110 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
8111
Andy Hung73c02e42015-03-29 01:13:58 -07008112 // check available frames and handle overrun conditions
8113 // if the record track isn't draining fast enough.
8114 bool hasOverrun;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008115 size_t framesIn;
Andy Hung73c02e42015-03-29 01:13:58 -07008116 activeTrack->mResamplerBufferProvider->sync(&framesIn, &hasOverrun);
8117 if (hasOverrun) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008118 overrun = OVERRUN_TRUE;
8119 }
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08008120 if (framesOut == 0 || framesIn == 0) {
8121 break;
8122 }
8123
Andy Hung6770c6f2015-04-07 13:43:36 -07008124 // Don't allow framesOut to be larger than what is possible with resampling
8125 // from framesIn.
8126 // This isn't strictly necessary but helps limit buffer resizing in
8127 // RecordBufferConverter. TODO: remove when no longer needed.
8128 framesOut = min(framesOut,
8129 destinationFramesPossible(
8130 framesIn, mSampleRate, activeTrack->mSampleRate));
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008131
8132 if (activeTrack->isDirect()) {
Daniel Van Veen9e2376e2018-09-27 14:37:58 +10008133 // No RecordBufferConverter used for direct streams. Pass
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008134 // straight from RecordThread buffer to RecordTrack buffer.
8135 AudioBufferProvider::Buffer buffer;
8136 buffer.frameCount = framesOut;
8137 status_t status = activeTrack->mResamplerBufferProvider->getNextBuffer(&buffer);
8138 if (status == OK && buffer.frameCount != 0) {
8139 ALOGV_IF(buffer.frameCount != framesOut,
8140 "%s() read less than expected (%zu vs %zu)",
8141 __func__, buffer.frameCount, framesOut);
8142 framesOut = buffer.frameCount;
Daniel Van Veen9e2376e2018-09-27 14:37:58 +10008143 memcpy(activeTrack->mSink.raw, buffer.raw, buffer.frameCount * mFrameSize);
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008144 activeTrack->mResamplerBufferProvider->releaseBuffer(&buffer);
8145 } else {
8146 framesOut = 0;
8147 ALOGE("%s() cannot fill request, status: %d, frameCount: %zu",
8148 __func__, status, buffer.frameCount);
8149 }
8150 } else {
8151 // process frames from the RecordThread buffer provider to the RecordTrack
8152 // buffer
8153 framesOut = activeTrack->mRecordBufferConverter->convert(
8154 activeTrack->mSink.raw,
8155 activeTrack->mResamplerBufferProvider,
8156 framesOut);
8157 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008158
8159 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
8160 overrun = OVERRUN_FALSE;
8161 }
8162
8163 if (activeTrack->mFramesToDrop == 0) {
8164 if (framesOut > 0) {
8165 activeTrack->mSink.frameCount = framesOut;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008166 // Sanitize before releasing if the track has no access to the source data
8167 // An idle UID receives silence from non virtual devices until active
8168 if (activeTrack->isSilenced()) {
Jean-Michel Trividdf87ef2019-08-20 15:42:04 -07008169 memset(activeTrack->mSink.raw, 0, framesOut * activeTrack->frameSize());
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008170 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008171 activeTrack->releaseBuffer(&activeTrack->mSink);
8172 }
8173 } else {
8174 // FIXME could do a partial drop of framesOut
8175 if (activeTrack->mFramesToDrop > 0) {
Mikhail Naganov6d91ba52019-03-26 14:35:28 -07008176 activeTrack->mFramesToDrop -= (ssize_t)framesOut;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008177 if (activeTrack->mFramesToDrop <= 0) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08008178 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008179 }
8180 } else {
8181 activeTrack->mFramesToDrop += framesOut;
8182 if (activeTrack->mFramesToDrop >= 0 || activeTrack->mSyncStartEvent == 0 ||
8183 activeTrack->mSyncStartEvent->isCancelled()) {
8184 ALOGW("Synced record %s, session %d, trigger session %d",
8185 (activeTrack->mFramesToDrop >= 0) ? "timed out" : "cancelled",
8186 activeTrack->sessionId(),
8187 (activeTrack->mSyncStartEvent != 0) ?
Glenn Kastend848eb42016-03-08 13:42:11 -08008188 activeTrack->mSyncStartEvent->triggerSession() :
8189 AUDIO_SESSION_NONE);
Glenn Kasten25f4aa82014-02-07 10:50:43 -08008190 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008191 }
8192 }
8193 }
8194
8195 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008196 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008197 }
8198 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008199
8200 switch (overrun) {
8201 case OVERRUN_TRUE:
8202 // client isn't retrieving buffers fast enough
8203 if (!activeTrack->setOverflow()) {
8204 nsecs_t now = systemTime();
8205 // FIXME should lastWarning per track?
8206 if ((now - lastWarning) > kWarningThrottleNs) {
8207 ALOGW("RecordThread: buffer overflow");
8208 lastWarning = now;
8209 }
8210 }
8211 break;
8212 case OVERRUN_FALSE:
8213 activeTrack->clearOverflow();
8214 break;
8215 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008216 break;
8217 }
8218
Andy Hung3f0c9022016-01-15 17:49:46 -08008219 // update frame information and push timestamp out
8220 activeTrack->updateTrackFrameInfo(
Andy Hung6ae58432016-02-16 18:32:24 -08008221 activeTrack->mServerProxy->framesReleased(),
Andy Hung3f0c9022016-01-15 17:49:46 -08008222 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER],
8223 mSampleRate, mTimestamp);
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008224 }
8225
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008226unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08008227 // enable changes in effect chain
8228 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07008229 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurentcccbc762019-04-05 14:20:05 -07008230 if (audio_has_proportional_frames(mFormat)
8231 && loopCount == lastLoopCountRead + 1) {
8232 const int64_t readPeriodNs = lastIoEndNs - mLastIoEndNs;
8233 const double jitterMs =
8234 TimestampVerifier<int64_t, int64_t>::computeJitterMs(
8235 {framesRead, readPeriodNs},
8236 {0, 0} /* lastTimestamp */, mSampleRate);
8237 const double processMs = (lastIoBeginNs - mLastIoEndNs) * 1e-6;
8238
8239 Mutex::Autolock _l(mLock);
8240 mIoJitterMs.add(jitterMs);
8241 mProcessTimeMs.add(processMs);
8242 }
8243 // update timing info.
8244 mLastIoBeginNs = lastIoBeginNs;
8245 mLastIoEndNs = lastIoEndNs;
8246 lastLoopCountRead = loopCount;
Eric Laurent81784c32012-11-19 14:55:58 -08008247 }
8248
Glenn Kasten93e471f2013-08-19 08:40:07 -07008249 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08008250
8251 {
8252 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07008253 for (size_t i = 0; i < mTracks.size(); i++) {
8254 sp<RecordTrack> track = mTracks[i];
8255 track->invalidate();
8256 }
Glenn Kasten2b806402013-11-20 16:37:38 -08008257 mActiveTracks.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08008258 mStartStopCond.broadcast();
8259 }
8260
8261 releaseWakeLock();
8262
8263 ALOGV("RecordThread %p exiting", this);
8264 return false;
8265}
8266
Glenn Kasten93e471f2013-08-19 08:40:07 -07008267void AudioFlinger::RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08008268{
8269 if (!mStandby) {
8270 inputStandBy();
Andy Hungcf10d742020-04-28 15:38:24 -07008271 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07008272 mThreadSnapshot.onEnd();
Eric Laurent81784c32012-11-19 14:55:58 -08008273 mStandby = true;
8274 }
8275}
8276
8277void AudioFlinger::RecordThread::inputStandBy()
8278{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008279 // Idle the fast capture if it's currently running
8280 if (mFastCapture != 0) {
8281 FastCaptureStateQueue *sq = mFastCapture->sq();
8282 FastCaptureState *state = sq->begin();
8283 if (!(state->mCommand & FastCaptureState::IDLE)) {
8284 state->mCommand = FastCaptureState::COLD_IDLE;
8285 state->mColdFutexAddr = &mFastCaptureFutex;
8286 state->mColdGen++;
8287 mFastCaptureFutex = 0;
8288 sq->end();
8289 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
8290 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
8291#if 0
8292 if (kUseFastCapture == FastCapture_Dynamic) {
8293 // FIXME
8294 }
8295#endif
8296#ifdef AUDIO_WATCHDOG
8297 // FIXME
8298#endif
8299 } else {
8300 sq->end(false /*didModify*/);
8301 }
8302 }
Mikhail Naganov2534b382019-09-25 13:05:02 -07008303 status_t result = mSource->standby();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008304 ALOGE_IF(result != OK, "Error when putting input stream into standby: %d", result);
Andy Hungad6d52d2016-07-18 13:42:03 -07008305
8306 // If going into standby, flush the pipe source.
8307 if (mPipeSource.get() != nullptr) {
8308 const ssize_t flushed = mPipeSource->flush();
8309 if (flushed > 0) {
8310 ALOGV("Input standby flushed PipeSource %zd frames", flushed);
8311 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += flushed;
8312 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
8313 }
8314 }
Eric Laurent81784c32012-11-19 14:55:58 -08008315}
8316
Glenn Kasten05997e22014-03-13 15:08:33 -07008317// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastene198c362013-08-13 09:13:36 -07008318sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
Eric Laurent81784c32012-11-19 14:55:58 -08008319 const sp<AudioFlinger::Client>& client,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07008320 const audio_attributes_t& attr,
Eric Laurentf14db3c2017-12-08 14:20:36 -08008321 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08008322 audio_format_t format,
8323 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08008324 size_t *pFrameCount,
Glenn Kastend848eb42016-03-08 13:42:11 -08008325 audio_session_t sessionId,
Eric Laurentf14db3c2017-12-08 14:20:36 -08008326 size_t *pNotificationFrameCount,
Eric Laurent09f1ed22019-04-24 17:45:17 -07008327 pid_t creatorPid,
Svet Ganov33761132021-05-13 22:51:08 +00008328 const AttributionSourceState& attributionSource,
Eric Laurent05067782016-06-01 18:27:28 -07008329 audio_input_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08008330 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08008331 status_t *status,
Eric Laurentec376dc2021-04-08 20:41:22 +02008332 audio_port_handle_t portId,
8333 int32_t maxSharedAudioHistoryMs)
Eric Laurent81784c32012-11-19 14:55:58 -08008334{
Glenn Kasten74935e42013-12-19 08:56:45 -08008335 size_t frameCount = *pFrameCount;
Eric Laurentf14db3c2017-12-08 14:20:36 -08008336 size_t notificationFrameCount = *pNotificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08008337 sp<RecordTrack> track;
8338 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07008339 audio_input_flags_t inputFlags = mInput->flags;
Eric Laurentf14db3c2017-12-08 14:20:36 -08008340 audio_input_flags_t requestedFlags = *flags;
8341 uint32_t sampleRate;
Svet Ganov33761132021-05-13 22:51:08 +00008342 AttributionSourceState checkedAttributionSource = AudioFlinger::checkAttributionSourcePackage(
8343 attributionSource);
Eric Laurentf14db3c2017-12-08 14:20:36 -08008344
8345 lStatus = initCheck();
8346 if (lStatus != NO_ERROR) {
8347 ALOGE("createRecordTrack_l() audio driver not initialized");
8348 goto Exit;
8349 }
8350
Mikhail Naganovce9f2652018-07-16 11:09:24 -07008351 if (!audio_is_linear_pcm(mFormat) && (*flags & AUDIO_INPUT_FLAG_DIRECT) == 0) {
8352 ALOGE("createRecordTrack_l() on an encoded stream requires AUDIO_INPUT_FLAG_DIRECT");
8353 lStatus = BAD_VALUE;
8354 goto Exit;
8355 }
8356
Eric Laurentec376dc2021-04-08 20:41:22 +02008357 if (maxSharedAudioHistoryMs != 0) {
Svet Ganov33761132021-05-13 22:51:08 +00008358 if (!captureHotwordAllowed(checkedAttributionSource)) {
Eric Laurentec376dc2021-04-08 20:41:22 +02008359 lStatus = PERMISSION_DENIED;
8360 goto Exit;
8361 }
Eric Laurentec376dc2021-04-08 20:41:22 +02008362 if (maxSharedAudioHistoryMs < 0
8363 || maxSharedAudioHistoryMs > AudioFlinger::kMaxSharedAudioHistoryMs) {
8364 lStatus = BAD_VALUE;
8365 goto Exit;
8366 }
8367 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08008368 if (*pSampleRate == 0) {
8369 *pSampleRate = mSampleRate;
8370 }
8371 sampleRate = *pSampleRate;
Eric Laurent05067782016-06-01 18:27:28 -07008372
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008373 // special case for FAST flag considered OK if fast capture is present and access to
8374 // audio history is not required
8375 if (hasFastCapture() && mMaxSharedAudioHistoryMs == 0) {
Eric Laurent05067782016-06-01 18:27:28 -07008376 inputFlags = (audio_input_flags_t)(inputFlags | AUDIO_INPUT_FLAG_FAST);
8377 }
8378
Eric Laurentf14db3c2017-12-08 14:20:36 -08008379 // Check if requested flags are compatible with input stream flags
Eric Laurent05067782016-06-01 18:27:28 -07008380 if ((*flags & inputFlags) != *flags) {
8381 ALOGW("createRecordTrack_l(): mismatch between requested flags (%08x) and"
8382 " input flags (%08x)",
8383 *flags, inputFlags);
8384 *flags = (audio_input_flags_t)(*flags & inputFlags);
8385 }
Eric Laurent81784c32012-11-19 14:55:58 -08008386
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008387 // client expresses a preference for FAST and no access to audio history,
8388 // but we get the final say
8389 if (*flags & AUDIO_INPUT_FLAG_FAST && maxSharedAudioHistoryMs == 0) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07008390 if (
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07008391 // we formerly checked for a callback handler (non-0 tid),
8392 // but that is no longer required for TRANSFER_OBTAIN mode
jiabinb00edc32021-08-16 16:27:54 +00008393 // No need to match hardware format, format conversion will be done in client side.
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07008394 //
Phil Burk7ed66a12019-04-18 13:20:30 -07008395 // Frame count is not specified (0), or is less than or equal the pipe depth.
8396 // It is OK to provide a higher capacity than requested.
8397 // We will force it to mPipeFramesP2 below.
8398 (frameCount <= mPipeFramesP2) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07008399 // PCM data
8400 audio_is_linear_pcm(format) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08008401 // hardware channel mask
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008402 (channelMask == mChannelMask) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08008403 // hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07008404 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07008405 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008406 hasFastCapture() &&
8407 // there are sufficient fast track slots available
8408 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07008409 ) {
Eric Laurent4c415062016-06-17 16:14:16 -07008410 // check compatibility with audio effects.
8411 Mutex::Autolock _l(mLock);
8412 // Do not accept FAST flag if the session has software effects
8413 sp<EffectChain> chain = getEffectChain_l(sessionId);
8414 if (chain != 0) {
Andy Hungd3bb0ad2016-10-11 17:16:43 -07008415 audio_input_flags_t old = *flags;
8416 chain->checkInputFlagCompatibility(flags);
8417 if (old != *flags) {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008418 ALOGV("%p AUDIO_INPUT_FLAGS denied by effect old=%#x new=%#x",
8419 this, (int)old, (int)*flags);
Eric Laurent4c415062016-06-17 16:14:16 -07008420 }
8421 }
Eric Laurent122f7e72016-06-29 11:53:29 -07008422 ALOGV_IF((*flags & AUDIO_INPUT_FLAG_FAST) != 0,
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008423 "%p AUDIO_INPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
8424 this, frameCount, mFrameCount);
Glenn Kasten90e58b12013-07-31 16:16:02 -07008425 } else {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008426 ALOGV("%p AUDIO_INPUT_FLAG_FAST denied: frameCount=%zu mFrameCount=%zu mPipeFramesP2=%zu "
8427 "format=%#x isLinear=%d mFormat=%#x channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008428 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008429 this, frameCount, mFrameCount, mPipeFramesP2,
8430 format, audio_is_linear_pcm(format), mFormat, channelMask, sampleRate, mSampleRate,
Glenn Kasten74105912014-07-03 12:28:53 -07008431 hasFastCapture(), tid, mFastTrackAvail);
Eric Laurent05067782016-06-01 18:27:28 -07008432 *flags = (audio_input_flags_t)(*flags & ~AUDIO_INPUT_FLAG_FAST);
Glenn Kasten74105912014-07-03 12:28:53 -07008433 }
8434 }
8435
Eric Laurentf14db3c2017-12-08 14:20:36 -08008436 // If FAST or RAW flags were corrected, ask caller to request new input from audio policy
8437 if ((*flags & AUDIO_INPUT_FLAG_FAST) !=
8438 (requestedFlags & AUDIO_INPUT_FLAG_FAST)) {
8439 *flags = (audio_input_flags_t) (*flags & ~(AUDIO_INPUT_FLAG_FAST | AUDIO_INPUT_FLAG_RAW));
8440 lStatus = BAD_TYPE;
8441 goto Exit;
8442 }
8443
Glenn Kasten74105912014-07-03 12:28:53 -07008444 // compute track buffer size in frames, and suggest the notification frame count
Eric Laurent05067782016-06-01 18:27:28 -07008445 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten74105912014-07-03 12:28:53 -07008446 // fast track: frame count is exactly the pipe depth
8447 frameCount = mPipeFramesP2;
8448 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
Eric Laurentf14db3c2017-12-08 14:20:36 -08008449 notificationFrameCount = mFrameCount;
Glenn Kasten74105912014-07-03 12:28:53 -07008450 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07008451 // not fast track: max notification period is resampled equivalent of one HAL buffer time
8452 // or 20 ms if there is a fast capture
8453 // TODO This could be a roundupRatio inline, and const
8454 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
8455 * sampleRate + mSampleRate - 1) / mSampleRate;
8456 // minimum number of notification periods is at least kMinNotifications,
8457 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
8458 static const size_t kMinNotifications = 3;
8459 static const uint32_t kMinMs = 30;
8460 // TODO This could be a roundupRatio inline
8461 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
8462 // TODO This could be a roundupRatio inline
8463 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
8464 maxNotificationFrames;
8465 const size_t minFrameCount = maxNotificationFrames *
8466 max(kMinNotifications, minNotificationsByMs);
8467 frameCount = max(frameCount, minFrameCount);
Eric Laurentf14db3c2017-12-08 14:20:36 -08008468 if (notificationFrameCount == 0 || notificationFrameCount > maxNotificationFrames) {
8469 notificationFrameCount = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07008470 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07008471 }
Glenn Kasten74935e42013-12-19 08:56:45 -08008472 *pFrameCount = frameCount;
Eric Laurentf14db3c2017-12-08 14:20:36 -08008473 *pNotificationFrameCount = notificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08008474
8475 { // scope for mLock
8476 Mutex::Autolock _l(mLock);
Eric Laurent2407ce32021-04-26 14:56:03 +02008477 int32_t startFrames = -1;
Eric Laurentec376dc2021-04-08 20:41:22 +02008478 if (!mSharedAudioPackageName.empty()
Svet Ganov33761132021-05-13 22:51:08 +00008479 && mSharedAudioPackageName == checkedAttributionSource.packageName
Eric Laurentec376dc2021-04-08 20:41:22 +02008480 && mSharedAudioSessionId == sessionId
Svet Ganov33761132021-05-13 22:51:08 +00008481 && captureHotwordAllowed(checkedAttributionSource)) {
Eric Laurent2407ce32021-04-26 14:56:03 +02008482 startFrames = mSharedAudioStartFrames;
Eric Laurentec376dc2021-04-08 20:41:22 +02008483 }
Eric Laurent81784c32012-11-19 14:55:58 -08008484
Kevin Rocard1f564ac2018-03-29 13:53:10 -07008485 track = new RecordTrack(this, client, attr, sampleRate,
Andy Hung8fe68032017-06-05 16:17:51 -07008486 format, channelMask, frameCount,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07008487 nullptr /* buffer */, (size_t)0 /* bufferSize */, sessionId, creatorPid,
Svet Ganov33761132021-05-13 22:51:08 +00008488 checkedAttributionSource, *flags, TrackBase::TYPE_DEFAULT, portId,
8489 startFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08008490
Glenn Kasten03003332013-08-06 15:40:54 -07008491 lStatus = track->initCheck();
8492 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07008493 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08008494 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08008495 goto Exit;
8496 }
8497 mTracks.add(track);
8498
Eric Laurent05067782016-06-01 18:27:28 -07008499 if ((*flags & AUDIO_INPUT_FLAG_FAST) && (tid != -1)) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07008500 pid_t callingPid = IPCThreadState::self()->getCallingPid();
8501 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
8502 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07008503 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Glenn Kasten90e58b12013-07-31 16:16:02 -07008504 }
Eric Laurentec376dc2021-04-08 20:41:22 +02008505
8506 if (maxSharedAudioHistoryMs != 0) {
8507 sendResizeBufferConfigEvent_l(maxSharedAudioHistoryMs);
8508 }
Eric Laurent81784c32012-11-19 14:55:58 -08008509 }
Glenn Kasten05997e22014-03-13 15:08:33 -07008510
Eric Laurent81784c32012-11-19 14:55:58 -08008511 lStatus = NO_ERROR;
8512
8513Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07008514 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08008515 return track;
8516}
8517
8518status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
8519 AudioSystem::sync_event_t event,
Glenn Kastend848eb42016-03-08 13:42:11 -08008520 audio_session_t triggerSession)
Eric Laurent81784c32012-11-19 14:55:58 -08008521{
8522 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
8523 sp<ThreadBase> strongMe = this;
8524 status_t status = NO_ERROR;
8525
8526 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08008527 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08008528 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008529 recordTrack->mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
Eric Laurent81784c32012-11-19 14:55:58 -08008530 triggerSession,
8531 recordTrack->sessionId(),
8532 syncStartEventCallback,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008533 recordTrack);
Eric Laurent81784c32012-11-19 14:55:58 -08008534 // Sync event can be cancelled by the trigger session if the track is not in a
8535 // compatible state in which case we start record immediately
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008536 if (recordTrack->mSyncStartEvent->isCancelled()) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08008537 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08008538 } else {
8539 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
Ivan Lozano1b35dd62017-12-06 16:55:10 -08008540 recordTrack->mFramesToDrop = -(ssize_t)
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08008541 ((AudioSystem::kSyncRecordStartTimeOutMs * recordTrack->mSampleRate) / 1000);
Eric Laurent81784c32012-11-19 14:55:58 -08008542 }
8543 }
8544
8545 {
Glenn Kasten47c20702013-08-13 15:37:35 -07008546 // This section is a rendezvous between binder thread executing start() and RecordThread
Eric Laurent81784c32012-11-19 14:55:58 -08008547 AutoMutex lock(mLock);
Andy Hungce685402018-10-05 17:23:27 -07008548 if (recordTrack->isInvalid()) {
8549 recordTrack->clearSyncStartEvent();
Eric Laurentd52a28c2020-08-21 17:10:39 -07008550 ALOGW("%s track %d: invalidated before startInput", __func__, recordTrack->portId());
8551 return DEAD_OBJECT;
Andy Hungce685402018-10-05 17:23:27 -07008552 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008553 if (mActiveTracks.indexOf(recordTrack) >= 0) {
8554 if (recordTrack->mState == TrackBase::PAUSING) {
Andy Hungce685402018-10-05 17:23:27 -07008555 // We haven't stopped yet (moved to PAUSED and not in mActiveTracks)
8556 // so no need to startInput().
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008557 ALOGV("active record track PAUSING -> ACTIVE");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008558 recordTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008559 } else {
Andy Hung959b5b82021-09-24 10:46:20 -07008560 ALOGV("active record track state %d", (int)recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08008561 }
8562 return status;
8563 }
8564
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08008565 // TODO consider other ways of handling this, such as changing the state to :STARTING and
8566 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
8567 // or using a separate command thread
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008568 recordTrack->mState = TrackBase::STARTING_1;
Glenn Kasten2b806402013-11-20 16:37:38 -08008569 mActiveTracks.add(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07008570 status_t status = NO_ERROR;
8571 if (recordTrack->isExternalTrack()) {
8572 mLock.unlock();
Eric Laurent4eb58f12018-12-07 16:41:02 -08008573 status = AudioSystem::startInput(recordTrack->portId());
Eric Laurent83b88082014-06-20 18:31:16 -07008574 mLock.lock();
Andy Hungce685402018-10-05 17:23:27 -07008575 if (recordTrack->isInvalid()) {
8576 recordTrack->clearSyncStartEvent();
8577 if (status == NO_ERROR && recordTrack->mState == TrackBase::STARTING_1) {
8578 recordTrack->mState = TrackBase::STARTING_2;
8579 // STARTING_2 forces destroy to call stopInput.
8580 }
Eric Laurentd52a28c2020-08-21 17:10:39 -07008581 ALOGW("%s track %d: invalidated after startInput", __func__, recordTrack->portId());
8582 return DEAD_OBJECT;
Andy Hungce685402018-10-05 17:23:27 -07008583 }
8584 if (recordTrack->mState != TrackBase::STARTING_1) {
8585 ALOGW("%s(%d): unsynchronized mState:%d change",
Andy Hung959b5b82021-09-24 10:46:20 -07008586 __func__, recordTrack->id(), (int)recordTrack->mState);
Andy Hungce685402018-10-05 17:23:27 -07008587 // Someone else has changed state, let them take over,
8588 // leave mState in the new state.
8589 recordTrack->clearSyncStartEvent();
8590 return INVALID_OPERATION;
8591 }
8592 // we're ok, but perhaps startInput has failed
Eric Laurent83b88082014-06-20 18:31:16 -07008593 if (status != NO_ERROR) {
Andy Hungce685402018-10-05 17:23:27 -07008594 ALOGW("%s(%d): startInput failed, status %d",
8595 __func__, recordTrack->id(), status);
8596 // We are in ActiveTracks if STARTING_1 and valid, so remove from ActiveTracks,
8597 // leave in STARTING_1, so destroy() will not call stopInput.
Eric Laurent83b88082014-06-20 18:31:16 -07008598 mActiveTracks.remove(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07008599 recordTrack->clearSyncStartEvent();
Eric Laurent83b88082014-06-20 18:31:16 -07008600 return status;
8601 }
Eric Laurent09f1ed22019-04-24 17:45:17 -07008602 sendIoConfigEvent_l(
8603 AUDIO_CLIENT_STARTED, recordTrack->creatorPid(), recordTrack->portId());
Eric Laurent81784c32012-11-19 14:55:58 -08008604 }
Andy Hungc2b11cb2020-04-22 09:04:01 -07008605
8606 recordTrack->logBeginInterval(patchSourcesToString(&mPatch)); // log to MediaMetrics
8607
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008608 // Catch up with current buffer indices if thread is already running.
8609 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
8610 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
8611 // see previously buffered data before it called start(), but with greater risk of overrun.
8612
Andy Hung73c02e42015-03-29 01:13:58 -07008613 recordTrack->mResamplerBufferProvider->reset();
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008614 if (!recordTrack->isDirect()) {
8615 // clear any converter state as new data will be discontinuous
8616 recordTrack->mRecordBufferConverter->reset();
8617 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008618 recordTrack->mState = TrackBase::STARTING_2;
Eric Laurent81784c32012-11-19 14:55:58 -08008619 // signal thread to start
Eric Laurent81784c32012-11-19 14:55:58 -08008620 mWaitWorkCV.broadcast();
Eric Laurent81784c32012-11-19 14:55:58 -08008621 return status;
8622 }
Eric Laurent81784c32012-11-19 14:55:58 -08008623}
8624
Eric Laurent81784c32012-11-19 14:55:58 -08008625void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
8626{
8627 sp<SyncEvent> strongEvent = event.promote();
8628
8629 if (strongEvent != 0) {
Eric Laurent8ea16e42014-02-20 16:26:11 -08008630 sp<RefBase> ptr = strongEvent->cookie().promote();
8631 if (ptr != 0) {
8632 RecordTrack *recordTrack = (RecordTrack *)ptr.get();
8633 recordTrack->handleSyncStartEvent(strongEvent);
8634 }
Eric Laurent81784c32012-11-19 14:55:58 -08008635 }
8636}
8637
Glenn Kastena8356f62013-07-25 14:37:52 -07008638bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08008639 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07008640 AutoMutex _l(mLock);
Andy Hungce685402018-10-05 17:23:27 -07008641 // if we're invalid, we can't be on the ActiveTracks.
Jean-Michel Trivi38f86712017-04-11 14:10:17 -07008642 if (mActiveTracks.indexOf(recordTrack) < 0 || recordTrack->mState == TrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08008643 return false;
8644 }
Glenn Kasten47c20702013-08-13 15:37:35 -07008645 // note that threadLoop may still be processing the track at this point [without lock]
Eric Laurent81784c32012-11-19 14:55:58 -08008646 recordTrack->mState = TrackBase::PAUSING;
Andy Hungce685402018-10-05 17:23:27 -07008647
Andy Hungabfab202019-03-07 19:45:54 -08008648 // NOTE: Waiting here is important to keep stop synchronous.
8649 // This is needed for proper patchRecord peer release.
Andy Hungce685402018-10-05 17:23:27 -07008650 while (recordTrack->mState == TrackBase::PAUSING && !recordTrack->isInvalid()) {
8651 mWaitWorkCV.broadcast(); // signal thread to stop
8652 mStartStopCond.wait(mLock);
Eric Laurent81784c32012-11-19 14:55:58 -08008653 }
Andy Hungce685402018-10-05 17:23:27 -07008654
8655 if (recordTrack->mState == TrackBase::PAUSED) { // successful stop
Eric Laurent81784c32012-11-19 14:55:58 -08008656 ALOGV("Record stopped OK");
8657 return true;
8658 }
Andy Hungce685402018-10-05 17:23:27 -07008659
8660 // don't handle anything - we've been invalidated or restarted and in a different state
8661 ALOGW_IF("%s(%d): unsynchronized stop, state: %d",
8662 __func__, recordTrack->id(), recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08008663 return false;
8664}
8665
Glenn Kasten0f11b512014-01-31 16:18:54 -08008666bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
Eric Laurent81784c32012-11-19 14:55:58 -08008667{
8668 return false;
8669}
8670
Glenn Kasten0f11b512014-01-31 16:18:54 -08008671status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08008672{
8673#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
8674 if (!isValidSyncEvent(event)) {
8675 return BAD_VALUE;
8676 }
8677
Glenn Kastend848eb42016-03-08 13:42:11 -08008678 audio_session_t eventSession = event->triggerSession();
Eric Laurent81784c32012-11-19 14:55:58 -08008679 status_t ret = NAME_NOT_FOUND;
8680
8681 Mutex::Autolock _l(mLock);
8682
8683 for (size_t i = 0; i < mTracks.size(); i++) {
8684 sp<RecordTrack> track = mTracks[i];
8685 if (eventSession == track->sessionId()) {
8686 (void) track->setSyncEvent(event);
8687 ret = NO_ERROR;
8688 }
8689 }
8690 return ret;
8691#else
8692 return BAD_VALUE;
8693#endif
8694}
8695
jiabin653cc0a2018-01-17 17:54:10 -08008696status_t AudioFlinger::RecordThread::getActiveMicrophones(
8697 std::vector<media::MicrophoneInfo>* activeMicrophones)
8698{
8699 ALOGV("RecordThread::getActiveMicrophones");
8700 AutoMutex _l(mLock);
Jasmine Chaeaa10e42021-05-11 10:11:14 +08008701 if (!isStreamInitialized()) {
Paul McLean8a661a32021-04-12 10:21:42 -06008702 return NO_INIT;
8703 }
jiabin9ff780e2018-03-19 18:19:52 -07008704 status_t status = mInput->stream->getActiveMicrophones(activeMicrophones);
8705 return status;
jiabin653cc0a2018-01-17 17:54:10 -08008706}
8707
Paul McLean12340082019-03-19 09:35:05 -06008708status_t AudioFlinger::RecordThread::setPreferredMicrophoneDirection(
8709 audio_microphone_direction_t direction)
Paul McLean03a6e6a2018-12-04 10:54:13 -07008710{
Paul McLean12340082019-03-19 09:35:05 -06008711 ALOGV("setPreferredMicrophoneDirection(%d)", direction);
Paul McLean03a6e6a2018-12-04 10:54:13 -07008712 AutoMutex _l(mLock);
Jasmine Chaeaa10e42021-05-11 10:11:14 +08008713 if (!isStreamInitialized()) {
Paul McLean8a661a32021-04-12 10:21:42 -06008714 return NO_INIT;
8715 }
Paul McLean12340082019-03-19 09:35:05 -06008716 return mInput->stream->setPreferredMicrophoneDirection(direction);
Paul McLean03a6e6a2018-12-04 10:54:13 -07008717}
8718
Paul McLean12340082019-03-19 09:35:05 -06008719status_t AudioFlinger::RecordThread::setPreferredMicrophoneFieldDimension(float zoom)
Paul McLean03a6e6a2018-12-04 10:54:13 -07008720{
Paul McLean12340082019-03-19 09:35:05 -06008721 ALOGV("setPreferredMicrophoneFieldDimension(%f)", zoom);
Paul McLean03a6e6a2018-12-04 10:54:13 -07008722 AutoMutex _l(mLock);
Jasmine Chaeaa10e42021-05-11 10:11:14 +08008723 if (!isStreamInitialized()) {
Paul McLean8a661a32021-04-12 10:21:42 -06008724 return NO_INIT;
8725 }
Paul McLean12340082019-03-19 09:35:05 -06008726 return mInput->stream->setPreferredMicrophoneFieldDimension(zoom);
Paul McLean03a6e6a2018-12-04 10:54:13 -07008727}
8728
Eric Laurentec376dc2021-04-08 20:41:22 +02008729status_t AudioFlinger::RecordThread::shareAudioHistory(
8730 const std::string& sharedAudioPackageName, audio_session_t sharedSessionId,
8731 int64_t sharedAudioStartMs) {
8732 AutoMutex _l(mLock);
8733 return shareAudioHistory_l(sharedAudioPackageName, sharedSessionId, sharedAudioStartMs);
8734}
8735
8736status_t AudioFlinger::RecordThread::shareAudioHistory_l(
8737 const std::string& sharedAudioPackageName, audio_session_t sharedSessionId,
8738 int64_t sharedAudioStartMs) {
Eric Laurent92d0a322021-07-16 15:32:33 +02008739
Eric Laurentec376dc2021-04-08 20:41:22 +02008740 if ((hasAudioSession_l(sharedSessionId) & ThreadBase::TRACK_SESSION) == 0) {
8741 return BAD_VALUE;
8742 }
Eric Laurent2407ce32021-04-26 14:56:03 +02008743
8744 if (sharedAudioStartMs < 0
8745 || sharedAudioStartMs > INT64_MAX / mSampleRate) {
Eric Laurentec376dc2021-04-08 20:41:22 +02008746 return BAD_VALUE;
8747 }
8748
Eric Laurent2407ce32021-04-26 14:56:03 +02008749 // Current implementation of the input resampling buffer wraps around indexes at 32 bit.
8750 // As we cannot detect more than one wraparound, only accept values up current write position
8751 // after one wraparound
8752 // We assume recent wraparounds on mRsmpInRear only given it is unlikely that the requesting
8753 // app waits several hours after the start time was computed.
Eric Laurent92d0a322021-07-16 15:32:33 +02008754 int64_t sharedAudioStartFrames = sharedAudioStartMs * mSampleRate / 1000;
Eric Laurent2407ce32021-04-26 14:56:03 +02008755 const int32_t sharedOffset = audio_utils::safe_sub_overflow(mRsmpInRear,
8756 (int32_t)sharedAudioStartFrames);
Eric Laurent92d0a322021-07-16 15:32:33 +02008757 // Bring the start frame position within the input buffer to match the documented
8758 // "best effort" behavior of the API.
8759 if (sharedOffset < 0) {
8760 sharedAudioStartFrames = mRsmpInRear;
8761 } else if (sharedOffset > mRsmpInFrames) {
8762 sharedAudioStartFrames =
8763 audio_utils::safe_sub_overflow(mRsmpInRear, (int32_t)mRsmpInFrames);
Eric Laurent2407ce32021-04-26 14:56:03 +02008764 }
8765
Eric Laurentec376dc2021-04-08 20:41:22 +02008766 mSharedAudioPackageName = sharedAudioPackageName;
8767 if (mSharedAudioPackageName.empty()) {
Eric Laurent92d0a322021-07-16 15:32:33 +02008768 resetAudioHistory_l();
Eric Laurentec376dc2021-04-08 20:41:22 +02008769 } else {
8770 mSharedAudioSessionId = sharedSessionId;
Eric Laurent2407ce32021-04-26 14:56:03 +02008771 mSharedAudioStartFrames = (int32_t)sharedAudioStartFrames;
Eric Laurentec376dc2021-04-08 20:41:22 +02008772 }
8773 return NO_ERROR;
8774}
8775
Eric Laurent92d0a322021-07-16 15:32:33 +02008776void AudioFlinger::RecordThread::resetAudioHistory_l() {
8777 mSharedAudioSessionId = AUDIO_SESSION_NONE;
8778 mSharedAudioStartFrames = -1;
8779 mSharedAudioPackageName = "";
8780}
8781
Kevin Rocard069c2712018-03-29 19:09:14 -07008782void AudioFlinger::RecordThread::updateMetadata_l()
8783{
Jasmine Chaeaa10e42021-05-11 10:11:14 +08008784 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
8785 return; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -07008786 }
8787 StreamInHalInterface::SinkMetadata metadata;
8788 for (const sp<RecordTrack> &track : mActiveTracks) {
Eric Laurentb9cc0ab2021-01-29 11:46:52 +01008789 // Do not forward PatchRecord metadata to audio HAL
8790 if (track->isPatchTrack()) {
8791 continue;
8792 }
Kevin Rocard069c2712018-03-29 19:09:14 -07008793 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurent94579172020-11-20 18:41:04 +01008794 record_track_metadata_v7_t trackMetadata;
8795 trackMetadata.base = {
Kevin Rocard069c2712018-03-29 19:09:14 -07008796 .source = track->attributes().source,
8797 .gain = 1, // capture tracks do not have volumes
Eric Laurent94579172020-11-20 18:41:04 +01008798 };
8799 trackMetadata.channel_mask = track->channelMask(),
8800 strncpy(trackMetadata.tags, track->attributes().tags, AUDIO_ATTRIBUTES_TAGS_MAX_SIZE);
8801
8802 metadata.tracks.push_back(trackMetadata);
Kevin Rocard069c2712018-03-29 19:09:14 -07008803 }
8804 mInput->stream->updateSinkMetadata(metadata);
8805}
8806
Eric Laurent81784c32012-11-19 14:55:58 -08008807// destroyTrack_l() must be called with ThreadBase::mLock held
8808void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
8809{
Eric Laurentbfb1b832013-01-07 09:53:42 -08008810 track->terminate();
8811 track->mState = TrackBase::STOPPED;
Eric Laurentec376dc2021-04-08 20:41:22 +02008812
Eric Laurent81784c32012-11-19 14:55:58 -08008813 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08008814 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08008815 removeTrack_l(track);
8816 }
8817}
8818
8819void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
8820{
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008821 String8 result;
8822 track->appendDump(result, false /* active */);
8823 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.string());
8824
Eric Laurent81784c32012-11-19 14:55:58 -08008825 mTracks.remove(track);
8826 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008827 if (track->isFastTrack()) {
8828 ALOG_ASSERT(!mFastTrackAvail);
8829 mFastTrackAvail = true;
8830 }
Eric Laurent81784c32012-11-19 14:55:58 -08008831}
8832
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07008833void AudioFlinger::RecordThread::dumpInternals_l(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08008834{
Mikhail Naganov913d06c2016-11-01 12:49:22 -07008835 AudioStreamIn *input = mInput;
8836 audio_input_flags_t flags = input != NULL ? input->flags : AUDIO_INPUT_FLAG_NONE;
8837 dprintf(fd, " AudioStreamIn: %p flags %#x (%s)\n",
Andy Hung9b181952019-02-25 14:53:36 -08008838 input, flags, toString(flags).c_str());
Andy Hung6427e442018-08-09 12:51:02 -07008839 dprintf(fd, " Frames read: %lld\n", (long long)mFramesRead);
Eric Tan39ec8d62018-07-24 09:49:29 -07008840 if (mActiveTracks.isEmpty()) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07008841 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08008842 }
Andy Hungbfa64962017-06-12 14:43:19 -07008843
8844 if (input != nullptr) {
8845 dprintf(fd, " Hal stream dump:\n");
8846 (void)input->stream->dump(fd);
8847 }
8848
Glenn Kasten6e6704c2014-07-03 10:20:00 -07008849 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008850 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Glenn Kasten17c9c992015-03-02 15:53:01 -08008851
Glenn Kasten2f90c512015-12-02 11:40:09 -08008852 // Make a non-atomic copy of fast capture dump state so it won't change underneath us
8853 // while we are dumping it. It may be inconsistent, but it won't mutate!
8854 // This is a large object so we place it on the heap.
8855 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
Eric Tan2942a4e2018-09-12 17:41:27 -07008856 const std::unique_ptr<FastCaptureDumpState> copy =
8857 std::make_unique<FastCaptureDumpState>(mFastCaptureDumpState);
Glenn Kasten2f90c512015-12-02 11:40:09 -08008858 copy->dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08008859}
8860
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07008861void AudioFlinger::RecordThread::dumpTracks_l(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08008862{
Eric Laurent81784c32012-11-19 14:55:58 -08008863 String8 result;
Marco Nelissenb2208842014-02-07 14:00:50 -08008864 size_t numtracks = mTracks.size();
8865 size_t numactive = mActiveTracks.size();
8866 size_t numactiveseen = 0;
Glenn Kastenc42e9b42016-03-21 11:35:03 -07008867 dprintf(fd, " %zu Tracks", numtracks);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008868 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08008869 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07008870 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008871 result.append(prefix);
Andy Hung000adb52018-06-01 15:43:26 -07008872 mTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08008873 for (size_t i = 0; i < numtracks ; ++i) {
8874 sp<RecordTrack> track = mTracks[i];
8875 if (track != 0) {
8876 bool active = mActiveTracks.indexOf(track) >= 0;
8877 if (active) {
8878 numactiveseen++;
8879 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008880 result.append(prefix);
8881 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08008882 }
Eric Laurent81784c32012-11-19 14:55:58 -08008883 }
Marco Nelissenb2208842014-02-07 14:00:50 -08008884 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07008885 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08008886 }
8887
Marco Nelissenb2208842014-02-07 14:00:50 -08008888 if (numactiveseen != numactive) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008889 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08008890 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008891 result.append(prefix);
Andy Hung000adb52018-06-01 15:43:26 -07008892 mActiveTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08008893 for (size_t i = 0; i < numactive; ++i) {
Glenn Kasten2b806402013-11-20 16:37:38 -08008894 sp<RecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08008895 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008896 result.append(prefix);
8897 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08008898 }
Glenn Kasten2b806402013-11-20 16:37:38 -08008899 }
Eric Laurent81784c32012-11-19 14:55:58 -08008900
8901 }
8902 write(fd, result.string(), result.size());
8903}
8904
Eric Laurent5ada82e2019-08-29 17:53:54 -07008905void AudioFlinger::RecordThread::setRecordSilenced(audio_port_handle_t portId, bool silenced)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008906{
8907 Mutex::Autolock _l(mLock);
8908 for (size_t i = 0; i < mTracks.size() ; i++) {
8909 sp<RecordTrack> track = mTracks[i];
Eric Laurent5ada82e2019-08-29 17:53:54 -07008910 if (track != 0 && track->portId() == portId) {
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008911 track->setSilenced(silenced);
8912 }
8913 }
8914}
Andy Hung73c02e42015-03-29 01:13:58 -07008915
8916void AudioFlinger::RecordThread::ResamplerBufferProvider::reset()
8917{
8918 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
8919 RecordThread *recordThread = (RecordThread *) threadBase.get();
Andy Hung73c02e42015-03-29 01:13:58 -07008920 mRsmpInUnrel = 0;
Eric Laurentec376dc2021-04-08 20:41:22 +02008921 const int32_t rear = recordThread->mRsmpInRear;
8922 ssize_t deltaFrames = 0;
Eric Laurent2407ce32021-04-26 14:56:03 +02008923 if (mRecordTrack->startFrames() >= 0) {
8924 int32_t startFrames = mRecordTrack->startFrames();
8925 // Accept a recent wraparound of mRsmpInRear
8926 if (startFrames <= rear) {
8927 deltaFrames = rear - startFrames;
8928 } else {
8929 deltaFrames = (int32_t)((int64_t)rear + UINT32_MAX + 1 - startFrames);
Eric Laurentec376dc2021-04-08 20:41:22 +02008930 }
Eric Laurentec376dc2021-04-08 20:41:22 +02008931 // start frame cannot be further in the past than start of resampling buffer
8932 if ((size_t) deltaFrames > recordThread->mRsmpInFrames) {
8933 deltaFrames = recordThread->mRsmpInFrames;
8934 }
8935 }
8936 mRsmpInFront = audio_utils::safe_sub_overflow(rear, static_cast<int32_t>(deltaFrames));
Andy Hung73c02e42015-03-29 01:13:58 -07008937}
8938
8939void AudioFlinger::RecordThread::ResamplerBufferProvider::sync(
8940 size_t *framesAvailable, bool *hasOverrun)
8941{
8942 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
8943 RecordThread *recordThread = (RecordThread *) threadBase.get();
8944 const int32_t rear = recordThread->mRsmpInRear;
8945 const int32_t front = mRsmpInFront;
Hongwei Wang95e37682019-04-12 11:13:36 -07008946 const ssize_t filled = audio_utils::safe_sub_overflow(rear, front);
Andy Hung73c02e42015-03-29 01:13:58 -07008947
8948 size_t framesIn;
8949 bool overrun = false;
8950 if (filled < 0) {
8951 // should not happen, but treat like a massive overrun and re-sync
8952 framesIn = 0;
8953 mRsmpInFront = rear;
8954 overrun = true;
8955 } else if ((size_t) filled <= recordThread->mRsmpInFrames) {
8956 framesIn = (size_t) filled;
8957 } else {
8958 // client is not keeping up with server, but give it latest data
8959 framesIn = recordThread->mRsmpInFrames;
Hongwei Wang95e37682019-04-12 11:13:36 -07008960 mRsmpInFront = /* front = */ audio_utils::safe_sub_overflow(
8961 rear, static_cast<int32_t>(framesIn));
Andy Hung73c02e42015-03-29 01:13:58 -07008962 overrun = true;
8963 }
8964 if (framesAvailable != NULL) {
8965 *framesAvailable = framesIn;
8966 }
8967 if (hasOverrun != NULL) {
8968 *hasOverrun = overrun;
8969 }
8970}
8971
Eric Laurent81784c32012-11-19 14:55:58 -08008972// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008973status_t AudioFlinger::RecordThread::ResamplerBufferProvider::getNextBuffer(
Glenn Kastend79072e2016-01-06 08:41:20 -08008974 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08008975{
Andy Hung73c02e42015-03-29 01:13:58 -07008976 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008977 if (threadBase == 0) {
8978 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08008979 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008980 return NOT_ENOUGH_DATA;
8981 }
8982 RecordThread *recordThread = (RecordThread *) threadBase.get();
8983 int32_t rear = recordThread->mRsmpInRear;
Andy Hung73c02e42015-03-29 01:13:58 -07008984 int32_t front = mRsmpInFront;
Hongwei Wang95e37682019-04-12 11:13:36 -07008985 ssize_t filled = audio_utils::safe_sub_overflow(rear, front);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008986 // FIXME should not be P2 (don't want to increase latency)
8987 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08008988 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07008989 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008990
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008991 front &= recordThread->mRsmpInFramesP2 - 1;
8992 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07008993 if (part1 > (size_t) filled) {
8994 part1 = filled;
8995 }
8996 size_t ask = buffer->frameCount;
8997 ALOG_ASSERT(ask > 0);
8998 if (part1 > ask) {
8999 part1 = ask;
9000 }
9001 if (part1 == 0) {
Andy Hung73c02e42015-03-29 01:13:58 -07009002 // out of data is fine since the resampler will return a short-count.
Glenn Kasten85948432013-08-19 12:09:05 -07009003 buffer->raw = NULL;
9004 buffer->frameCount = 0;
Andy Hung73c02e42015-03-29 01:13:58 -07009005 mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07009006 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08009007 }
9008
Andy Hung57446612015-04-19 23:56:46 -07009009 buffer->raw = (uint8_t*)recordThread->mRsmpInBuffer + front * recordThread->mFrameSize;
Glenn Kasten85948432013-08-19 12:09:05 -07009010 buffer->frameCount = part1;
Andy Hung73c02e42015-03-29 01:13:58 -07009011 mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08009012 return NO_ERROR;
9013}
9014
9015// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009016void AudioFlinger::RecordThread::ResamplerBufferProvider::releaseBuffer(
9017 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08009018{
Hongwei Wang95e37682019-04-12 11:13:36 -07009019 int32_t stepCount = static_cast<int32_t>(buffer->frameCount);
Glenn Kasten85948432013-08-19 12:09:05 -07009020 if (stepCount == 0) {
9021 return;
9022 }
Andy Hung73c02e42015-03-29 01:13:58 -07009023 ALOG_ASSERT(stepCount <= mRsmpInUnrel);
9024 mRsmpInUnrel -= stepCount;
Hongwei Wang95e37682019-04-12 11:13:36 -07009025 mRsmpInFront = audio_utils::safe_add_overflow(mRsmpInFront, stepCount);
Glenn Kasten85948432013-08-19 12:09:05 -07009026 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08009027 buffer->frameCount = 0;
9028}
9029
Eric Laurentd8365c52017-07-16 15:27:05 -07009030void AudioFlinger::RecordThread::checkBtNrec()
9031{
9032 Mutex::Autolock _l(mLock);
9033 checkBtNrec_l();
9034}
9035
9036void AudioFlinger::RecordThread::checkBtNrec_l()
9037{
9038 // disable AEC and NS if the device is a BT SCO headset supporting those
9039 // pre processings
jiabinc52b1ff2019-10-31 17:20:42 -07009040 bool suspend = audio_is_bluetooth_sco_device(inDeviceType()) &&
Eric Laurentd8365c52017-07-16 15:27:05 -07009041 mAudioFlinger->btNrecIsOff();
9042 if (mBtNrecSuspended.exchange(suspend) != suspend) {
9043 for (size_t i = 0; i < mEffectChains.size(); i++) {
9044 setEffectSuspended_l(FX_IID_AEC, suspend, mEffectChains[i]->sessionId());
9045 setEffectSuspended_l(FX_IID_NS, suspend, mEffectChains[i]->sessionId());
9046 }
9047 }
9048}
9049
Andy Hung97a893e2015-03-29 01:03:07 -07009050
Eric Laurent10351942014-05-08 18:49:52 -07009051bool AudioFlinger::RecordThread::checkForNewParameter_l(const String8& keyValuePair,
9052 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08009053{
9054 bool reconfig = false;
9055
Eric Laurent10351942014-05-08 18:49:52 -07009056 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08009057
Eric Laurent10351942014-05-08 18:49:52 -07009058 audio_format_t reqFormat = mFormat;
9059 uint32_t samplingRate = mSampleRate;
Glenn Kastene1635ec2015-06-08 15:46:49 -07009060 // 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 -07009061 audio_channel_mask_t channelMask = audio_channel_in_mask_from_count(mChannelCount);
9062
9063 AudioParameter param = AudioParameter(keyValuePair);
9064 int value;
Haynes Mathew George9ce67b52015-09-30 11:40:47 -07009065
9066 // scope for AutoPark extends to end of method
9067 AutoPark<FastCapture> park(mFastCapture);
9068
Eric Laurent10351942014-05-08 18:49:52 -07009069 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
9070 // channel count change can be requested. Do we mandate the first client defines the
9071 // HAL sampling rate and channel count or do we allow changes on the fly?
9072 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
9073 samplingRate = value;
9074 reconfig = true;
9075 }
9076 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung97a893e2015-03-29 01:03:07 -07009077 if (!audio_is_linear_pcm((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07009078 status = BAD_VALUE;
9079 } else {
9080 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08009081 reconfig = true;
9082 }
Eric Laurent10351942014-05-08 18:49:52 -07009083 }
9084 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
9085 audio_channel_mask_t mask = (audio_channel_mask_t) value;
Andy Hungd330ee42015-04-20 13:23:41 -07009086 if (!audio_is_input_channel(mask) ||
Andy Hung936845a2021-06-08 00:09:06 -07009087 audio_channel_count_from_in_mask(mask) > FCC_LIMIT) {
Eric Laurent10351942014-05-08 18:49:52 -07009088 status = BAD_VALUE;
9089 } else {
9090 channelMask = mask;
9091 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08009092 }
Eric Laurent10351942014-05-08 18:49:52 -07009093 }
9094 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
9095 // do not accept frame count changes if tracks are open as the track buffer
9096 // size depends on frame count and correct behavior would not be guaranteed
9097 // if frame count is changed after track creation
9098 if (mActiveTracks.size() > 0) {
9099 status = INVALID_OPERATION;
9100 } else {
9101 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08009102 }
Eric Laurent10351942014-05-08 18:49:52 -07009103 }
9104 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07009105 LOG_FATAL("Should not set routing device in RecordThread");
Eric Laurent10351942014-05-08 18:49:52 -07009106 }
9107 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
9108 mAudioSource != (audio_source_t)value) {
jiabinc52b1ff2019-10-31 17:20:42 -07009109 LOG_FATAL("Should not set audio source in RecordThread");
Eric Laurent10351942014-05-08 18:49:52 -07009110 }
Glenn Kastene198c362013-08-13 09:13:36 -07009111
Eric Laurent10351942014-05-08 18:49:52 -07009112 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009113 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07009114 if (status == INVALID_OPERATION) {
9115 inputStandBy();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009116 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07009117 }
9118 if (reconfig) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009119 if (status == BAD_VALUE) {
Mikhail Naganov560637e2021-03-31 22:40:13 +00009120 audio_config_base_t config = AUDIO_CONFIG_BASE_INITIALIZER;
9121 if (mInput->stream->getAudioProperties(&config) == OK &&
9122 audio_is_linear_pcm(config.format) && audio_is_linear_pcm(reqFormat) &&
9123 config.sample_rate <= (AUDIO_RESAMPLER_DOWN_RATIO_MAX * samplingRate) &&
Andy Hung936845a2021-06-08 00:09:06 -07009124 audio_channel_count_from_in_mask(config.channel_mask) <= FCC_LIMIT) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009125 status = NO_ERROR;
9126 }
Eric Laurent81784c32012-11-19 14:55:58 -08009127 }
Eric Laurent10351942014-05-08 18:49:52 -07009128 if (status == NO_ERROR) {
9129 readInputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07009130 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08009131 }
9132 }
Eric Laurent81784c32012-11-19 14:55:58 -08009133 }
Eric Laurent10351942014-05-08 18:49:52 -07009134
Eric Laurent81784c32012-11-19 14:55:58 -08009135 return reconfig;
9136}
9137
9138String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
9139{
Eric Laurent81784c32012-11-19 14:55:58 -08009140 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009141 if (initCheck() == NO_ERROR) {
9142 String8 out_s8;
9143 if (mInput->stream->getParameters(keys, &out_s8) == OK) {
9144 return out_s8;
9145 }
Eric Laurent81784c32012-11-19 14:55:58 -08009146 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009147 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08009148}
9149
Mikhail Naganov88536df2021-07-26 17:30:29 -07009150void AudioFlinger::RecordThread::ioConfigChanged(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -07009151 audio_port_handle_t portId) {
Mikhail Naganov88536df2021-07-26 17:30:29 -07009152 sp<AudioIoDescriptor> desc;
Eric Laurent81784c32012-11-19 14:55:58 -08009153 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07009154 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07009155 case AUDIO_INPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07009156 case AUDIO_INPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07009157 desc = sp<AudioIoDescriptor>::make(mId, mPatch, true /*isInput*/,
9158 mSampleRate, mFormat, mChannelMask, mFrameCount, mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08009159 break;
Eric Laurent09f1ed22019-04-24 17:45:17 -07009160 case AUDIO_CLIENT_STARTED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07009161 desc = sp<AudioIoDescriptor>::make(mId, mPatch, portId);
Eric Laurent09f1ed22019-04-24 17:45:17 -07009162 break;
Eric Laurent73e26b62015-04-27 16:55:58 -07009163 case AUDIO_INPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08009164 default:
Mikhail Naganov88536df2021-07-26 17:30:29 -07009165 desc = sp<AudioIoDescriptor>::make(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08009166 break;
9167 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07009168 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08009169}
9170
Glenn Kastendeca2ae2014-02-07 10:25:56 -08009171void AudioFlinger::RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08009172{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009173 status_t result = mInput->stream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
9174 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
Andy Hung463be252014-07-10 16:56:07 -07009175 mFormat = mHALFormat;
Mikhail Naganovce9f2652018-07-16 11:09:24 -07009176 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
9177 if (audio_is_linear_pcm(mFormat)) {
Andy Hung936845a2021-06-08 00:09:06 -07009178 LOG_ALWAYS_FATAL_IF(mChannelCount > FCC_LIMIT, "HAL channel count %d > %d",
9179 mChannelCount, FCC_LIMIT);
Mikhail Naganovce9f2652018-07-16 11:09:24 -07009180 } else {
Andy Hung936845a2021-06-08 00:09:06 -07009181 // Can have more that FCC_LIMIT channels in encoded streams.
Mikhail Naganovce9f2652018-07-16 11:09:24 -07009182 ALOGI("HAL format %#x is not linear pcm", mFormat);
9183 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009184 result = mInput->stream->getFrameSize(&mFrameSize);
9185 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
Hayden Gomes1a89ab32020-06-12 11:05:47 -07009186 LOG_ALWAYS_FATAL_IF(mFrameSize <= 0, "Error frame size was %zu but must be greater than zero",
9187 mFrameSize);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009188 result = mInput->stream->getBufferSize(&mBufferSize);
9189 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
Glenn Kasten548efc92012-11-29 08:48:51 -08009190 mFrameCount = mBufferSize / mFrameSize;
Hayden Gomes1a89ab32020-06-12 11:05:47 -07009191 ALOGV("%p RecordThread params: mChannelCount=%u, mFormat=%#x, mFrameSize=%zu, "
9192 "mBufferSize=%zu, mFrameCount=%zu",
9193 this, mChannelCount, mFormat, mFrameSize, mBufferSize, mFrameCount);
Glenn Kasten49d00ad2014-07-21 11:22:03 -07009194
Eric Laurentec376dc2021-04-08 20:41:22 +02009195 // mRsmpInFrames must be 0 before calling resizeInputBuffer_l for the first time
9196 mRsmpInFrames = 0;
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009197 resizeInputBuffer_l(0 /*maxSharedAudioHistoryMs*/);
Eric Laurent81784c32012-11-19 14:55:58 -08009198
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08009199 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
9200 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Andy Hungea840382020-05-05 21:50:17 -07009201
9202 audio_input_flags_t flags = mInput->flags;
9203 mediametrics::LogItem item(mThreadMetrics.getMetricsId());
9204 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
9205 .set(AMEDIAMETRICS_PROP_ENCODING, formatToString(mFormat).c_str())
9206 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
9207 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
9208 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
9209 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
9210 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mFrameCount)
9211 .record();
Eric Laurent81784c32012-11-19 14:55:58 -08009212}
9213
Glenn Kasten5f972c02014-01-13 09:59:31 -08009214uint32_t AudioFlinger::RecordThread::getInputFramesLost()
Eric Laurent81784c32012-11-19 14:55:58 -08009215{
9216 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009217 uint32_t result;
9218 if (initCheck() == NO_ERROR && mInput->stream->getInputFramesLost(&result) == OK) {
9219 return result;
Eric Laurent81784c32012-11-19 14:55:58 -08009220 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009221 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08009222}
9223
Glenn Kastend848eb42016-03-08 13:42:11 -08009224KeyedVector<audio_session_t, bool> AudioFlinger::RecordThread::sessionIds() const
Eric Laurent81784c32012-11-19 14:55:58 -08009225{
Glenn Kastend848eb42016-03-08 13:42:11 -08009226 KeyedVector<audio_session_t, bool> ids;
Eric Laurent81784c32012-11-19 14:55:58 -08009227 Mutex::Autolock _l(mLock);
9228 for (size_t j = 0; j < mTracks.size(); ++j) {
9229 sp<RecordThread::RecordTrack> track = mTracks[j];
Glenn Kastend848eb42016-03-08 13:42:11 -08009230 audio_session_t sessionId = track->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08009231 if (ids.indexOfKey(sessionId) < 0) {
9232 ids.add(sessionId, true);
9233 }
9234 }
9235 return ids;
9236}
9237
9238AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
9239{
9240 Mutex::Autolock _l(mLock);
9241 AudioStreamIn *input = mInput;
9242 mInput = NULL;
9243 return input;
9244}
9245
9246// this method must always be called either with ThreadBase mLock held or inside the thread loop
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009247sp<StreamHalInterface> AudioFlinger::RecordThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08009248{
9249 if (mInput == NULL) {
9250 return NULL;
9251 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009252 return mInput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08009253}
9254
9255status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
9256{
Eric Laurent81784c32012-11-19 14:55:58 -08009257 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurentaaa44472014-09-12 17:41:50 -07009258 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08009259 chain->setInBuffer(NULL);
9260 chain->setOutBuffer(NULL);
9261
9262 checkSuspendOnAddEffectChain_l(chain);
9263
Eric Laurent1b928682014-10-02 19:41:47 -07009264 // make sure enabled pre processing effects state is communicated to the HAL as we
9265 // just moved them to a new input stream.
9266 chain->syncHalEffectsState();
9267
Eric Laurent81784c32012-11-19 14:55:58 -08009268 mEffectChains.add(chain);
9269
9270 return NO_ERROR;
9271}
9272
9273size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
9274{
9275 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
Eric Laurentb20cf7d2019-04-05 19:37:34 -07009276
9277 for (size_t i = 0; i < mEffectChains.size(); i++) {
9278 if (chain == mEffectChains[i]) {
9279 mEffectChains.removeAt(i);
9280 break;
9281 }
Eric Laurent81784c32012-11-19 14:55:58 -08009282 }
Eric Laurentb20cf7d2019-04-05 19:37:34 -07009283 return mEffectChains.size();
Eric Laurent81784c32012-11-19 14:55:58 -08009284}
9285
Eric Laurent1c333e22014-05-20 10:48:17 -07009286status_t AudioFlinger::RecordThread::createAudioPatch_l(const struct audio_patch *patch,
9287 audio_patch_handle_t *handle)
9288{
9289 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07009290
9291 // store new device and send to effects
jiabinc52b1ff2019-10-31 17:20:42 -07009292 mInDeviceTypeAddr.mType = patch->sources[0].ext.device.type;
jiabin0a488932020-08-07 17:32:40 -07009293 mInDeviceTypeAddr.setAddress(patch->sources[0].ext.device.address);
François Gaffie0c280aa2018-07-25 10:02:15 +02009294 audio_port_handle_t deviceId = patch->sources[0].id;
Eric Laurent054d9d32015-04-24 08:48:48 -07009295 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08009296 mEffectChains[i]->setInputDevice_l(inDeviceTypeAddr());
Eric Laurent054d9d32015-04-24 08:48:48 -07009297 }
9298
Eric Laurentd8365c52017-07-16 15:27:05 -07009299 checkBtNrec_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07009300
9301 // store new source and send to effects
9302 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
9303 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent1c333e22014-05-20 10:48:17 -07009304 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent054d9d32015-04-24 08:48:48 -07009305 mEffectChains[i]->setAudioSource_l(mAudioSource);
Eric Laurent1c333e22014-05-20 10:48:17 -07009306 }
Eric Laurent054d9d32015-04-24 08:48:48 -07009307 }
Eric Laurent1c333e22014-05-20 10:48:17 -07009308
Mikhail Naganov9ee05402016-10-13 15:58:17 -07009309 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07009310 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
9311 status = hwDevice->createAudioPatch(patch->num_sources,
9312 patch->sources,
9313 patch->num_sinks,
9314 patch->sinks,
9315 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07009316 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08009317 status = mInput->stream->legacyCreateAudioPatch(patch->sources[0],
9318 patch->sinks[0].ext.mix.usecase.source,
9319 patch->sources[0].ext.device.type);
Eric Laurent054d9d32015-04-24 08:48:48 -07009320 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07009321 }
Eric Laurent054d9d32015-04-24 08:48:48 -07009322
jiabinc52b1ff2019-10-31 17:20:42 -07009323 if ((mPatch.num_sources == 0) || (mPatch.sources[0].id != deviceId)) {
Eric Laurente8726fe2015-06-26 09:39:24 -07009324 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
jiabinc52b1ff2019-10-31 17:20:42 -07009325 mPatch = *patch;
Eric Laurente8726fe2015-06-26 09:39:24 -07009326 }
Eric Laurent296fb132015-05-01 11:38:42 -07009327
Andy Hungc2b11cb2020-04-22 09:04:01 -07009328 const std::string pathSourcesAsString = patchSourcesToString(patch);
Andy Hungcf10d742020-04-28 15:38:24 -07009329 mThreadMetrics.logEndInterval();
Andy Hungea840382020-05-05 21:50:17 -07009330 mThreadMetrics.logCreatePatch(pathSourcesAsString, /* outDevices */ {});
Andy Hungcf10d742020-04-28 15:38:24 -07009331 mThreadMetrics.logBeginInterval();
Andy Hungc2b11cb2020-04-22 09:04:01 -07009332 // also dispatch to active AudioRecords
9333 for (const auto &track : mActiveTracks) {
9334 track->logEndInterval();
9335 track->logBeginInterval(pathSourcesAsString);
9336 }
Eric Laurentdda206a2022-07-08 17:28:35 +02009337 // Force meteadata update after a route change
9338 mActiveTracks.setHasChanged();
9339
Eric Laurent1c333e22014-05-20 10:48:17 -07009340 return status;
9341}
9342
9343status_t AudioFlinger::RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
9344{
9345 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07009346
jiabinc52b1ff2019-10-31 17:20:42 -07009347 mPatch = audio_patch{};
9348 mInDeviceTypeAddr.reset();
Eric Laurent054d9d32015-04-24 08:48:48 -07009349
Mikhail Naganov9ee05402016-10-13 15:58:17 -07009350 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07009351 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
9352 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07009353 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08009354 status = mInput->stream->legacyReleaseAudioPatch();
Eric Laurent1c333e22014-05-20 10:48:17 -07009355 }
Eric Laurentdda206a2022-07-08 17:28:35 +02009356 // Force meteadata update after a route change
9357 mActiveTracks.setHasChanged();
9358
Eric Laurent1c333e22014-05-20 10:48:17 -07009359 return status;
9360}
9361
jiabinc52b1ff2019-10-31 17:20:42 -07009362void AudioFlinger::RecordThread::updateOutDevices(const DeviceDescriptorBaseVector& outDevices)
9363{
wendy lin56aa82b2020-12-02 15:19:55 +08009364 Mutex::Autolock _l(mLock);
jiabinc52b1ff2019-10-31 17:20:42 -07009365 mOutDevices = outDevices;
9366 mOutDeviceTypeAddrs = deviceTypeAddrsFromDescriptors(mOutDevices);
9367 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08009368 mEffectChains[i]->setDevices_l(outDeviceTypeAddrs());
jiabinc52b1ff2019-10-31 17:20:42 -07009369 }
9370}
9371
Eric Laurentec376dc2021-04-08 20:41:22 +02009372int32_t AudioFlinger::RecordThread::getOldestFront_l()
9373{
9374 if (mTracks.size() == 0) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009375 return mRsmpInRear;
Eric Laurentec376dc2021-04-08 20:41:22 +02009376 }
Eric Laurent2407ce32021-04-26 14:56:03 +02009377 int32_t oldestFront = mRsmpInRear;
9378 int32_t maxFilled = 0;
Eric Laurentec376dc2021-04-08 20:41:22 +02009379 for (size_t i = 0; i < mTracks.size(); i++) {
Eric Laurent2407ce32021-04-26 14:56:03 +02009380 int32_t front = mTracks[i]->mResamplerBufferProvider->getFront();
9381 int32_t filled;
Eric Laurent92d0a322021-07-16 15:32:33 +02009382 (void)__builtin_sub_overflow(mRsmpInRear, front, &filled);
Eric Laurent2407ce32021-04-26 14:56:03 +02009383 if (filled > maxFilled) {
9384 oldestFront = front;
9385 maxFilled = filled;
9386 }
Eric Laurentec376dc2021-04-08 20:41:22 +02009387 }
Eric Laurent92d0a322021-07-16 15:32:33 +02009388 if (maxFilled > mRsmpInFrames) {
9389 (void)__builtin_sub_overflow(mRsmpInRear, mRsmpInFrames, &oldestFront);
9390 }
Eric Laurent2407ce32021-04-26 14:56:03 +02009391 return oldestFront;
Eric Laurentec376dc2021-04-08 20:41:22 +02009392}
9393
9394void AudioFlinger::RecordThread::updateFronts_l(int32_t offset)
9395{
9396 if (offset == 0) {
9397 return;
9398 }
9399 for (size_t i = 0; i < mTracks.size(); i++) {
9400 int32_t front = mTracks[i]->mResamplerBufferProvider->getFront();
9401 front = audio_utils::safe_sub_overflow(front, offset);
9402 mTracks[i]->mResamplerBufferProvider->setFront(front);
9403 }
9404}
9405
9406void AudioFlinger::RecordThread::resizeInputBuffer_l(int32_t maxSharedAudioHistoryMs)
9407{
9408 // This is the formula for calculating the temporary buffer size.
9409 // With 7 HAL buffers, we can guarantee ability to down-sample the input by ratio of 6:1 to
9410 // 1 full output buffer, regardless of the alignment of the available input.
9411 // The value is somewhat arbitrary, and could probably be even larger.
9412 // A larger value should allow more old data to be read after a track calls start(),
9413 // without increasing latency.
9414 //
9415 // Note this is independent of the maximum downsampling ratio permitted for capture.
9416 size_t minRsmpInFrames = mFrameCount * 7;
9417
9418 // maxSharedAudioHistoryMs != 0 indicates a request to possibly make some part of the audio
9419 // capture history available to another client using the same session ID:
9420 // dimension the resampler input buffer accordingly.
9421
9422 // Get oldest client read position: getOldestFront_l() must be called before altering
9423 // mRsmpInRear, or mRsmpInFrames
9424 int32_t previousFront = getOldestFront_l();
9425 size_t previousRsmpInFramesP2 = mRsmpInFramesP2;
9426 int32_t previousRear = mRsmpInRear;
9427 mRsmpInRear = 0;
9428
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009429 ALOG_ASSERT(maxSharedAudioHistoryMs >= 0
9430 && maxSharedAudioHistoryMs <= AudioFlinger::kMaxSharedAudioHistoryMs,
9431 "resizeInputBuffer_l() called with invalid max shared history %d",
9432 maxSharedAudioHistoryMs);
Eric Laurentec376dc2021-04-08 20:41:22 +02009433 if (maxSharedAudioHistoryMs != 0) {
9434 // resizeInputBuffer_l should never be called with a non zero shared history if the
9435 // buffer was not already allocated
9436 ALOG_ASSERT(mRsmpInBuffer != nullptr && mRsmpInFrames != 0,
9437 "resizeInputBuffer_l() called with shared history and unallocated buffer");
9438 size_t rsmpInFrames = (size_t)maxSharedAudioHistoryMs * mSampleRate / 1000;
9439 // never reduce resampler input buffer size
Eric Laurent92d0a322021-07-16 15:32:33 +02009440 if (rsmpInFrames <= mRsmpInFrames) {
Eric Laurentec376dc2021-04-08 20:41:22 +02009441 return;
9442 }
9443 mRsmpInFrames = rsmpInFrames;
9444 }
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009445 mMaxSharedAudioHistoryMs = maxSharedAudioHistoryMs;
Eric Laurentec376dc2021-04-08 20:41:22 +02009446 // Note: mRsmpInFrames is 0 when called with maxSharedAudioHistoryMs equals to 0 so it is always
9447 // initialized
9448 if (mRsmpInFrames < minRsmpInFrames) {
9449 mRsmpInFrames = minRsmpInFrames;
9450 }
9451 mRsmpInFramesP2 = roundup(mRsmpInFrames);
9452
9453 // TODO optimize audio capture buffer sizes ...
9454 // Here we calculate the size of the sliding buffer used as a source
9455 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
9456 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
9457 // be better to have it derived from the pipe depth in the long term.
9458 // The current value is higher than necessary. However it should not add to latency.
9459
9460 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
9461 mRsmpInFramesOA = mRsmpInFramesP2 + mFrameCount - 1;
9462
9463 void *rsmpInBuffer;
9464 (void)posix_memalign(&rsmpInBuffer, 32, mRsmpInFramesOA * mFrameSize);
9465 // if posix_memalign fails, will segv here.
9466 memset(rsmpInBuffer, 0, mRsmpInFramesOA * mFrameSize);
9467
9468 // Copy audio history if any from old buffer before freeing it
9469 if (previousRear != 0) {
9470 ALOG_ASSERT(mRsmpInBuffer != nullptr,
9471 "resizeInputBuffer_l() called with null buffer but frames already read from HAL");
9472
9473 ssize_t unread = audio_utils::safe_sub_overflow(previousRear, previousFront);
9474 previousFront &= previousRsmpInFramesP2 - 1;
9475 size_t part1 = previousRsmpInFramesP2 - previousFront;
9476 if (part1 > (size_t) unread) {
9477 part1 = unread;
9478 }
9479 if (part1 != 0) {
9480 memcpy(rsmpInBuffer, (const uint8_t*)mRsmpInBuffer + previousFront * mFrameSize,
9481 part1 * mFrameSize);
9482 mRsmpInRear = part1;
9483 part1 = unread - part1;
9484 if (part1 != 0) {
9485 memcpy((uint8_t*)rsmpInBuffer + mRsmpInRear * mFrameSize,
9486 (const uint8_t*)mRsmpInBuffer, part1 * mFrameSize);
9487 mRsmpInRear += part1;
9488 }
9489 }
9490 // Update front for all clients according to new rear
9491 updateFronts_l(audio_utils::safe_sub_overflow(previousRear, mRsmpInRear));
9492 } else {
9493 mRsmpInRear = 0;
9494 }
9495 free(mRsmpInBuffer);
9496 mRsmpInBuffer = rsmpInBuffer;
9497}
9498
Mikhail Naganov444ecc32018-05-01 17:40:05 -07009499void AudioFlinger::RecordThread::addPatchTrack(const sp<PatchRecord>& record)
Eric Laurent83b88082014-06-20 18:31:16 -07009500{
9501 Mutex::Autolock _l(mLock);
9502 mTracks.add(record);
Mikhail Naganov2534b382019-09-25 13:05:02 -07009503 if (record->getSource()) {
9504 mSource = record->getSource();
9505 }
Eric Laurent83b88082014-06-20 18:31:16 -07009506}
9507
Mikhail Naganov444ecc32018-05-01 17:40:05 -07009508void AudioFlinger::RecordThread::deletePatchTrack(const sp<PatchRecord>& record)
Eric Laurent83b88082014-06-20 18:31:16 -07009509{
9510 Mutex::Autolock _l(mLock);
Mikhail Naganov2534b382019-09-25 13:05:02 -07009511 if (mSource == record->getSource()) {
9512 mSource = mInput;
9513 }
Eric Laurent83b88082014-06-20 18:31:16 -07009514 destroyTrack_l(record);
9515}
9516
Mikhail Naganovdc769682018-05-04 15:34:08 -07009517void AudioFlinger::RecordThread::toAudioPortConfig(struct audio_port_config *config)
Eric Laurent83b88082014-06-20 18:31:16 -07009518{
Mikhail Naganovdc769682018-05-04 15:34:08 -07009519 ThreadBase::toAudioPortConfig(config);
Eric Laurent83b88082014-06-20 18:31:16 -07009520 config->role = AUDIO_PORT_ROLE_SINK;
9521 config->ext.mix.hw_module = mInput->audioHwDev->handle();
9522 config->ext.mix.usecase.source = mAudioSource;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07009523 if (mInput && mInput->flags != AUDIO_INPUT_FLAG_NONE) {
9524 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
9525 config->flags.input = mInput->flags;
9526 }
Eric Laurent83b88082014-06-20 18:31:16 -07009527}
Eric Laurent1c333e22014-05-20 10:48:17 -07009528
Eric Laurent6acd1d42017-01-04 14:23:29 -08009529// ----------------------------------------------------------------------------
9530// Mmap
9531// ----------------------------------------------------------------------------
9532
9533AudioFlinger::MmapThreadHandle::MmapThreadHandle(const sp<MmapThread>& thread)
9534 : mThread(thread)
9535{
Phil Burk9fabbf82017-08-03 12:02:00 -07009536 assert(thread != 0); // thread must start non-null and stay non-null
Eric Laurent6acd1d42017-01-04 14:23:29 -08009537}
9538
9539AudioFlinger::MmapThreadHandle::~MmapThreadHandle()
9540{
Phil Burk9fabbf82017-08-03 12:02:00 -07009541 mThread->disconnect();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009542}
9543
9544status_t AudioFlinger::MmapThreadHandle::createMmapBuffer(int32_t minSizeFrames,
9545 struct audio_mmap_buffer_info *info)
9546{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009547 return mThread->createMmapBuffer(minSizeFrames, info);
9548}
9549
9550status_t AudioFlinger::MmapThreadHandle::getMmapPosition(struct audio_mmap_position *position)
9551{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009552 return mThread->getMmapPosition(position);
9553}
9554
jiabinb7d8c5a2020-08-26 17:24:52 -07009555status_t AudioFlinger::MmapThreadHandle::getExternalPosition(uint64_t *position,
9556 int64_t *timeNanos) {
9557 return mThread->getExternalPosition(position, timeNanos);
9558}
9559
Eric Laurenta54f1282017-07-01 19:39:32 -07009560status_t AudioFlinger::MmapThreadHandle::start(const AudioClient& client,
jiabind1f1cb62020-03-24 11:57:57 -07009561 const audio_attributes_t *attr, audio_port_handle_t *handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009562
9563{
jiabind1f1cb62020-03-24 11:57:57 -07009564 return mThread->start(client, attr, handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009565}
9566
9567status_t AudioFlinger::MmapThreadHandle::stop(audio_port_handle_t handle)
9568{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009569 return mThread->stop(handle);
9570}
9571
Eric Laurent18b57012017-02-13 16:23:52 -08009572status_t AudioFlinger::MmapThreadHandle::standby()
9573{
Eric Laurent18b57012017-02-13 16:23:52 -08009574 return mThread->standby();
9575}
9576
Eric Laurent6acd1d42017-01-04 14:23:29 -08009577
9578AudioFlinger::MmapThread::MmapThread(
9579 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
Andy Hungcf10d742020-04-28 15:38:24 -07009580 AudioHwDevice *hwDev, sp<StreamHalInterface> stream, bool systemReady, bool isOut)
Andy Hungea840382020-05-05 21:50:17 -07009581 : ThreadBase(audioFlinger, id, (isOut ? MMAP_PLAYBACK : MMAP_CAPTURE), systemReady, isOut),
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009582 mSessionId(AUDIO_SESSION_NONE),
François Gaffie0c280aa2018-07-25 10:02:15 +02009583 mPortId(AUDIO_PORT_HANDLE_NONE),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009584 mHalStream(stream), mHalDevice(hwDev->hwDevice()), mAudioHwDev(hwDev),
Eric Laurent67f97292018-04-20 18:05:41 -07009585 mActiveTracks(&this->mLocalLog),
9586 mHalVolFloat(-1.0f), // Initialize to illegal value so it always gets set properly later.
9587 mNoCallbackWarningCount(0)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009588{
Eric Laurent18b57012017-02-13 16:23:52 -08009589 mStandby = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009590 readHalParameters_l();
9591}
9592
9593AudioFlinger::MmapThread::~MmapThread()
9594{
9595}
9596
9597void AudioFlinger::MmapThread::onFirstRef()
9598{
9599 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
9600}
9601
9602void AudioFlinger::MmapThread::disconnect()
9603{
Eric Laurent331679c2018-04-16 17:03:16 -07009604 ActiveTracks<MmapTrack> activeTracks;
9605 {
9606 Mutex::Autolock _l(mLock);
9607 for (const sp<MmapTrack> &t : mActiveTracks) {
9608 activeTracks.add(t);
9609 }
9610 }
9611 for (const sp<MmapTrack> &t : activeTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08009612 stop(t->portId());
9613 }
Phil Burk9fabbf82017-08-03 12:02:00 -07009614 // This will decrement references and may cause the destruction of this thread.
Eric Laurent6acd1d42017-01-04 14:23:29 -08009615 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07009616 AudioSystem::releaseOutput(mPortId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009617 } else {
Eric Laurentfee19762018-01-29 18:44:13 -08009618 AudioSystem::releaseInput(mPortId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009619 }
9620}
9621
9622
9623void AudioFlinger::MmapThread::configure(const audio_attributes_t *attr,
9624 audio_stream_type_t streamType __unused,
9625 audio_session_t sessionId,
9626 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009627 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -08009628 audio_port_handle_t portId)
9629{
9630 mAttr = *attr;
9631 mSessionId = sessionId;
9632 mCallback = callback;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009633 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009634 mPortId = portId;
9635}
9636
9637status_t AudioFlinger::MmapThread::createMmapBuffer(int32_t minSizeFrames,
9638 struct audio_mmap_buffer_info *info)
9639{
9640 if (mHalStream == 0) {
9641 return NO_INIT;
9642 }
Eric Laurent18b57012017-02-13 16:23:52 -08009643 mStandby = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009644 return mHalStream->createMmapBuffer(minSizeFrames, info);
9645}
9646
9647status_t AudioFlinger::MmapThread::getMmapPosition(struct audio_mmap_position *position)
9648{
9649 if (mHalStream == 0) {
9650 return NO_INIT;
9651 }
9652 return mHalStream->getMmapPosition(position);
9653}
9654
Eric Laurentdda206a2022-07-08 17:28:35 +02009655status_t AudioFlinger::MmapThread::exitStandby_l()
Eric Laurent331679c2018-04-16 17:03:16 -07009656{
Eric Laurentdda206a2022-07-08 17:28:35 +02009657 // The HAL must receive track metadata before starting the stream
9658 updateMetadata_l();
Eric Laurent331679c2018-04-16 17:03:16 -07009659 status_t ret = mHalStream->start();
9660 if (ret != NO_ERROR) {
9661 ALOGE("%s: error mHalStream->start() = %d for first track", __FUNCTION__, ret);
9662 return ret;
9663 }
Andy Hungcf10d742020-04-28 15:38:24 -07009664 if (mStandby) {
9665 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07009666 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -07009667 mStandby = false;
9668 }
Eric Laurent331679c2018-04-16 17:03:16 -07009669 return NO_ERROR;
9670}
9671
Eric Laurenta54f1282017-07-01 19:39:32 -07009672status_t AudioFlinger::MmapThread::start(const AudioClient& client,
jiabind1f1cb62020-03-24 11:57:57 -07009673 const audio_attributes_t *attr,
Eric Laurent6acd1d42017-01-04 14:23:29 -08009674 audio_port_handle_t *handle)
9675{
Eric Laurenta54f1282017-07-01 19:39:32 -07009676 ALOGV("%s clientUid %d mStandby %d mPortId %d *handle %d", __FUNCTION__,
Svet Ganov33761132021-05-13 22:51:08 +00009677 client.attributionSource.uid, mStandby, mPortId, *handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009678 if (mHalStream == 0) {
9679 return NO_INIT;
9680 }
9681
9682 status_t ret;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009683
Eric Laurentdda206a2022-07-08 17:28:35 +02009684 // For the first track, reuse portId and session allocated when the stream was opened.
Eric Laurenta54f1282017-07-01 19:39:32 -07009685 if (*handle == mPortId) {
Eric Laurentdda206a2022-07-08 17:28:35 +02009686 acquireWakeLock();
9687 return NO_ERROR;
Eric Laurenta54f1282017-07-01 19:39:32 -07009688 }
9689
9690 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
9691
9692 audio_io_handle_t io = mId;
9693 if (isOutput()) {
9694 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
9695 config.sample_rate = mSampleRate;
9696 config.channel_mask = mChannelMask;
9697 config.format = mFormat;
9698 audio_stream_type_t stream = streamType();
9699 audio_output_flags_t flags =
9700 (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009701 audio_port_handle_t deviceId = mDeviceId;
Kevin Rocard153f92d2018-12-18 18:33:28 -08009702 std::vector<audio_io_handle_t> secondaryOutputs;
Eric Laurentb0a7bc92022-04-05 15:06:08 +02009703 bool isSpatialized;
Eric Laurenta54f1282017-07-01 19:39:32 -07009704 ret = AudioSystem::getOutputForAttr(&mAttr, &io,
9705 mSessionId,
9706 &stream,
Svet Ganov33761132021-05-13 22:51:08 +00009707 client.attributionSource,
Eric Laurenta54f1282017-07-01 19:39:32 -07009708 &config,
9709 flags,
9710 &deviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -08009711 &portId,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02009712 &secondaryOutputs,
9713 &isSpatialized);
Kevin Rocard153f92d2018-12-18 18:33:28 -08009714 ALOGD_IF(!secondaryOutputs.empty(),
9715 "MmapThread::start does not support secondary outputs, ignoring them");
Eric Laurent6acd1d42017-01-04 14:23:29 -08009716 } else {
Eric Laurenta54f1282017-07-01 19:39:32 -07009717 audio_config_base_t config;
9718 config.sample_rate = mSampleRate;
9719 config.channel_mask = mChannelMask;
9720 config.format = mFormat;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009721 audio_port_handle_t deviceId = mDeviceId;
Eric Laurenta54f1282017-07-01 19:39:32 -07009722 ret = AudioSystem::getInputForAttr(&mAttr, &io,
Mikhail Naganov2996f672019-04-18 12:29:59 -07009723 RECORD_RIID_INVALID,
Eric Laurenta54f1282017-07-01 19:39:32 -07009724 mSessionId,
Svet Ganov33761132021-05-13 22:51:08 +00009725 client.attributionSource,
Eric Laurenta54f1282017-07-01 19:39:32 -07009726 &config,
9727 AUDIO_INPUT_FLAG_MMAP_NOIRQ,
9728 &deviceId,
9729 &portId);
9730 }
9731 // APM should not chose a different input or output stream for the same set of attributes
9732 // and audo configuration
9733 if (ret != NO_ERROR || io != mId) {
9734 ALOGE("%s: error getting output or input from APM (error %d, io %d expected io %d)",
9735 __FUNCTION__, ret, io, mId);
9736 return BAD_VALUE;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009737 }
9738
9739 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07009740 ret = AudioSystem::startOutput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009741 } else {
jiabin09609032022-06-15 19:26:01 +00009742 {
9743 // Add the track record before starting input so that the silent status for the
9744 // client can be cached.
9745 Mutex::Autolock _l(mLock);
9746 setClientSilencedState_l(portId, false /*silenced*/);
9747 }
Eric Laurent4eb58f12018-12-07 16:41:02 -08009748 ret = AudioSystem::startInput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009749 }
9750
Eric Laurent331679c2018-04-16 17:03:16 -07009751 Mutex::Autolock _l(mLock);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009752 // abort if start is rejected by audio policy manager
9753 if (ret != NO_ERROR) {
Phil Burk7f6b40d2017-02-09 13:18:38 -08009754 ALOGE("%s: error start rejected by AudioPolicyManager = %d", __FUNCTION__, ret);
Eric Tan39ec8d62018-07-24 09:49:29 -07009755 if (!mActiveTracks.isEmpty()) {
Eric Laurent331679c2018-04-16 17:03:16 -07009756 mLock.unlock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009757 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07009758 AudioSystem::releaseOutput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009759 } else {
Eric Laurentfee19762018-01-29 18:44:13 -08009760 AudioSystem::releaseInput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009761 }
Eric Laurent331679c2018-04-16 17:03:16 -07009762 mLock.lock();
Eric Laurent18b57012017-02-13 16:23:52 -08009763 } else {
9764 mHalStream->stop();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009765 }
jiabin09609032022-06-15 19:26:01 +00009766 eraseClientSilencedState_l(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009767 return PERMISSION_DENIED;
9768 }
9769
Kevin Rocard1f564ac2018-03-29 13:53:10 -07009770 // Given that MmapThread::mAttr is mutable, should a MmapTrack have attributes ?
jiabind1f1cb62020-03-24 11:57:57 -07009771 sp<MmapTrack> track = new MmapTrack(this, attr == nullptr ? mAttr : *attr, mSampleRate, mFormat,
Svet Ganov33761132021-05-13 22:51:08 +00009772 mChannelMask, mSessionId, isOutput(),
9773 client.attributionSource,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07009774 IPCThreadState::self()->getCallingPid(), portId);
jiabin09609032022-06-15 19:26:01 +00009775 if (!isOutput()) {
9776 track->setSilenced_l(isClientSilenced_l(portId));
9777 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08009778
Eric Laurent4eb58f12018-12-07 16:41:02 -08009779 if (isOutput()) {
9780 // force volume update when a new track is added
9781 mHalVolFloat = -1.0f;
9782 } else if (!track->isSilenced_l()) {
9783 for (const sp<MmapTrack> &t : mActiveTracks) {
Svet Ganov33761132021-05-13 22:51:08 +00009784 if (t->isSilenced_l() && t->uid() != client.attributionSource.uid)
Eric Laurent4eb58f12018-12-07 16:41:02 -08009785 t->invalidate();
9786 }
9787 }
9788
Eric Laurent6acd1d42017-01-04 14:23:29 -08009789 mActiveTracks.add(track);
Eric Laurenta54f1282017-07-01 19:39:32 -07009790 sp<EffectChain> chain = getEffectChain_l(mSessionId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009791 if (chain != 0) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02009792 chain->setStrategy(getStrategyForStream(streamType()));
Eric Laurent6acd1d42017-01-04 14:23:29 -08009793 chain->incTrackCnt();
9794 chain->incActiveTrackCnt();
9795 }
9796
Andy Hungc2b11cb2020-04-22 09:04:01 -07009797 track->logBeginInterval(patchSinksToString(&mPatch)); // log to MediaMetrics
Eric Laurent6acd1d42017-01-04 14:23:29 -08009798 *handle = portId;
Eric Laurentdda206a2022-07-08 17:28:35 +02009799
9800 if (mActiveTracks.size() == 1) {
9801 ret = exitStandby_l();
9802 }
9803
Eric Laurent6acd1d42017-01-04 14:23:29 -08009804 broadcast_l();
9805
Eric Laurentdda206a2022-07-08 17:28:35 +02009806 ALOGV("%s DONE status %d handle %d stream %p", __FUNCTION__, ret, *handle, mHalStream.get());
Eric Laurent6acd1d42017-01-04 14:23:29 -08009807
Eric Laurentdda206a2022-07-08 17:28:35 +02009808 return ret;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009809}
9810
9811status_t AudioFlinger::MmapThread::stop(audio_port_handle_t handle)
9812{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009813 ALOGV("%s handle %d", __FUNCTION__, handle);
9814
9815 if (mHalStream == 0) {
9816 return NO_INIT;
9817 }
9818
Eric Laurenta54f1282017-07-01 19:39:32 -07009819 if (handle == mPortId) {
Phil Burk98ab4082020-09-25 21:46:34 +00009820 releaseWakeLock();
Eric Laurenta54f1282017-07-01 19:39:32 -07009821 return NO_ERROR;
9822 }
9823
Eric Laurent331679c2018-04-16 17:03:16 -07009824 Mutex::Autolock _l(mLock);
9825
Eric Laurent6acd1d42017-01-04 14:23:29 -08009826 sp<MmapTrack> track;
9827 for (const sp<MmapTrack> &t : mActiveTracks) {
9828 if (handle == t->portId()) {
9829 track = t;
9830 break;
9831 }
9832 }
9833 if (track == 0) {
9834 return BAD_VALUE;
9835 }
9836
9837 mActiveTracks.remove(track);
jiabin09609032022-06-15 19:26:01 +00009838 eraseClientSilencedState_l(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -08009839
Eric Laurent331679c2018-04-16 17:03:16 -07009840 mLock.unlock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009841 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07009842 AudioSystem::stopOutput(track->portId());
9843 AudioSystem::releaseOutput(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -08009844 } else {
Eric Laurentfee19762018-01-29 18:44:13 -08009845 AudioSystem::stopInput(track->portId());
9846 AudioSystem::releaseInput(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -08009847 }
Eric Laurent331679c2018-04-16 17:03:16 -07009848 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009849
9850 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
9851 if (chain != 0) {
9852 chain->decActiveTrackCnt();
9853 chain->decTrackCnt();
9854 }
9855
Eric Laurentdda206a2022-07-08 17:28:35 +02009856 if (mActiveTracks.isEmpty()) {
9857 mHalStream->stop();
9858 }
9859
Eric Laurent6acd1d42017-01-04 14:23:29 -08009860 broadcast_l();
9861
Eric Laurent6acd1d42017-01-04 14:23:29 -08009862 return NO_ERROR;
9863}
9864
Eric Laurent18b57012017-02-13 16:23:52 -08009865status_t AudioFlinger::MmapThread::standby()
9866{
9867 ALOGV("%s", __FUNCTION__);
9868
9869 if (mHalStream == 0) {
9870 return NO_INIT;
9871 }
Eric Tan39ec8d62018-07-24 09:49:29 -07009872 if (!mActiveTracks.isEmpty()) {
Eric Laurent18b57012017-02-13 16:23:52 -08009873 return INVALID_OPERATION;
9874 }
9875 mHalStream->standby();
Andy Hungcf10d742020-04-28 15:38:24 -07009876 if (!mStandby) {
9877 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07009878 mThreadSnapshot.onEnd();
Andy Hungcf10d742020-04-28 15:38:24 -07009879 mStandby = true;
9880 }
Eric Laurent18b57012017-02-13 16:23:52 -08009881 releaseWakeLock();
9882 return NO_ERROR;
9883}
9884
Eric Laurent6acd1d42017-01-04 14:23:29 -08009885
9886void AudioFlinger::MmapThread::readHalParameters_l()
9887{
9888 status_t result = mHalStream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
9889 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
9890 mFormat = mHALFormat;
9891 LOG_ALWAYS_FATAL_IF(!audio_is_linear_pcm(mFormat), "HAL format %#x is not linear pcm", mFormat);
9892 result = mHalStream->getFrameSize(&mFrameSize);
9893 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
Hayden Gomes1a89ab32020-06-12 11:05:47 -07009894 LOG_ALWAYS_FATAL_IF(mFrameSize <= 0, "Error frame size was %zu but must be greater than zero",
9895 mFrameSize);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009896 result = mHalStream->getBufferSize(&mBufferSize);
9897 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
9898 mFrameCount = mBufferSize / mFrameSize;
Andy Hungc2b11cb2020-04-22 09:04:01 -07009899
Andy Hungcf10d742020-04-28 15:38:24 -07009900 // TODO: make a readHalParameters call?
9901 mediametrics::LogItem item(mThreadMetrics.getMetricsId());
Andy Hungc2b11cb2020-04-22 09:04:01 -07009902 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
9903 .set(AMEDIAMETRICS_PROP_ENCODING, formatToString(mFormat).c_str())
9904 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
9905 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
9906 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
9907 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mFrameCount)
9908 /*
9909 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
9910 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELMASK,
9911 (int32_t)mHapticChannelMask)
9912 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELCOUNT,
9913 (int32_t)mHapticChannelCount)
9914 */
9915 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_ENCODING,
9916 formatToString(mHALFormat).c_str())
9917 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_FRAMECOUNT,
9918 (int32_t)mFrameCount) // sic - added HAL
9919 .record();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009920}
9921
9922bool AudioFlinger::MmapThread::threadLoop()
9923{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009924 checkSilentMode_l();
9925
9926 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
9927
9928 while (!exitPending())
9929 {
Eric Laurent6acd1d42017-01-04 14:23:29 -08009930 Vector< sp<EffectChain> > effectChains;
9931
Andy Hung13850be2019-03-14 11:33:09 -07009932 { // under Thread lock
9933 Mutex::Autolock _l(mLock);
9934
Eric Laurent6acd1d42017-01-04 14:23:29 -08009935 if (mSignalPending) {
9936 // A signal was raised while we were unlocked
9937 mSignalPending = false;
9938 } else {
9939 if (mConfigEvents.isEmpty()) {
9940 // we're about to wait, flush the binder command buffer
9941 IPCThreadState::self()->flushCommands();
9942
9943 if (exitPending()) {
9944 break;
9945 }
9946
Eric Laurent6acd1d42017-01-04 14:23:29 -08009947 // wait until we have something to do...
9948 ALOGV("%s going to sleep", myName.string());
9949 mWaitWorkCV.wait(mLock);
9950 ALOGV("%s waking up", myName.string());
Eric Laurent6acd1d42017-01-04 14:23:29 -08009951
9952 checkSilentMode_l();
9953
9954 continue;
9955 }
9956 }
9957
9958 processConfigEvents_l();
9959
9960 processVolume_l();
9961
9962 checkInvalidTracks_l();
9963
9964 mActiveTracks.updatePowerState(this);
9965
Kevin Rocard069c2712018-03-29 19:09:14 -07009966 updateMetadata_l();
9967
Eric Laurent6acd1d42017-01-04 14:23:29 -08009968 lockEffectChains_l(effectChains);
Andy Hung13850be2019-03-14 11:33:09 -07009969 } // release Thread lock
9970
Eric Laurent6acd1d42017-01-04 14:23:29 -08009971 for (size_t i = 0; i < effectChains.size(); i ++) {
Andy Hung13850be2019-03-14 11:33:09 -07009972 effectChains[i]->process_l(); // Thread is not locked, but effect chain is locked
Eric Laurent6acd1d42017-01-04 14:23:29 -08009973 }
Andy Hung13850be2019-03-14 11:33:09 -07009974
9975 // enable changes in effect chain, including moving to another thread.
Eric Laurent6acd1d42017-01-04 14:23:29 -08009976 unlockEffectChains(effectChains);
9977 // Effect chains will be actually deleted here if they were removed from
9978 // mEffectChains list during mixing or effects processing
9979 }
9980
9981 threadLoop_exit();
9982
9983 if (!mStandby) {
9984 threadLoop_standby();
9985 mStandby = true;
9986 }
9987
Eric Laurent6acd1d42017-01-04 14:23:29 -08009988 ALOGV("Thread %p type %d exiting", this, mType);
9989 return false;
9990}
9991
9992// checkForNewParameter_l() must be called with ThreadBase::mLock held
9993bool AudioFlinger::MmapThread::checkForNewParameter_l(const String8& keyValuePair,
9994 status_t& status)
9995{
9996 AudioParameter param = AudioParameter(keyValuePair);
9997 int value;
Eric Laurente6e9a482017-07-25 19:26:02 -07009998 bool sendToHal = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009999 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -070010000 LOG_FATAL("Should not happen set routing device in MmapThread");
Eric Laurent6acd1d42017-01-04 14:23:29 -080010001 }
Eric Laurente6e9a482017-07-25 19:26:02 -070010002 if (sendToHal) {
10003 status = mHalStream->setParameters(keyValuePair);
10004 } else {
10005 status = NO_ERROR;
10006 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010007
10008 return false;
10009}
10010
10011String8 AudioFlinger::MmapThread::getParameters(const String8& keys)
10012{
10013 Mutex::Autolock _l(mLock);
10014 String8 out_s8;
10015 if (initCheck() == NO_ERROR && mHalStream->getParameters(keys, &out_s8) == OK) {
10016 return out_s8;
10017 }
10018 return String8();
10019}
10020
Mikhail Naganov88536df2021-07-26 17:30:29 -070010021void AudioFlinger::MmapThread::ioConfigChanged(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -070010022 audio_port_handle_t portId __unused) {
Mikhail Naganov88536df2021-07-26 17:30:29 -070010023 sp<AudioIoDescriptor> desc;
10024 bool isInput = false;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010025 switch (event) {
10026 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -070010027 case AUDIO_INPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -080010028 case AUDIO_INPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -070010029 isInput = true;
10030 FALLTHROUGH_INTENDED;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010031 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -070010032 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -080010033 case AUDIO_OUTPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -070010034 desc = sp<AudioIoDescriptor>::make(mId, mPatch, isInput,
10035 mSampleRate, mFormat, mChannelMask, mFrameCount, mFrameCount);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010036 break;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010037 case AUDIO_INPUT_CLOSED:
10038 case AUDIO_OUTPUT_CLOSED:
10039 default:
Mikhail Naganov88536df2021-07-26 17:30:29 -070010040 desc = sp<AudioIoDescriptor>::make(mId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010041 break;
10042 }
10043 mAudioFlinger->ioConfigChanged(event, desc, pid);
10044}
10045
10046status_t AudioFlinger::MmapThread::createAudioPatch_l(const struct audio_patch *patch,
10047 audio_patch_handle_t *handle)
10048{
10049 status_t status = NO_ERROR;
10050
10051 // store new device and send to effects
10052 audio_devices_t type = AUDIO_DEVICE_NONE;
10053 audio_port_handle_t deviceId;
jiabinc52b1ff2019-10-31 17:20:42 -070010054 AudioDeviceTypeAddrVector sinkDeviceTypeAddrs;
10055 AudioDeviceTypeAddr sourceDeviceTypeAddr;
10056 uint32_t numDevices = 0;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010057 if (isOutput()) {
10058 for (unsigned int i = 0; i < patch->num_sinks; i++) {
jiabinc52b1ff2019-10-31 17:20:42 -070010059 LOG_ALWAYS_FATAL_IF(popcount(patch->sinks[i].ext.device.type) > 1
10060 && !mAudioHwDev->supportsAudioPatches(),
10061 "Enumerated device type(%#x) must not be used "
10062 "as it does not support audio patches",
10063 patch->sinks[i].ext.device.type);
Mikhail Naganov55773032020-10-01 15:08:13 -070010064 type = static_cast<audio_devices_t>(type | patch->sinks[i].ext.device.type);
jiabinc52b1ff2019-10-31 17:20:42 -070010065 sinkDeviceTypeAddrs.push_back(AudioDeviceTypeAddr(patch->sinks[i].ext.device.type,
10066 patch->sinks[i].ext.device.address));
Eric Laurent6acd1d42017-01-04 14:23:29 -080010067 }
10068 deviceId = patch->sinks[0].id;
jiabinc52b1ff2019-10-31 17:20:42 -070010069 numDevices = mPatch.num_sinks;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010070 } else {
10071 type = patch->sources[0].ext.device.type;
10072 deviceId = patch->sources[0].id;
jiabinc52b1ff2019-10-31 17:20:42 -070010073 numDevices = mPatch.num_sources;
10074 sourceDeviceTypeAddr.mType = patch->sources[0].ext.device.type;
jiabin0a488932020-08-07 17:32:40 -070010075 sourceDeviceTypeAddr.setAddress(patch->sources[0].ext.device.address);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010076 }
10077
10078 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -080010079 if (isOutput()) {
10080 mEffectChains[i]->setDevices_l(sinkDeviceTypeAddrs);
10081 } else {
10082 mEffectChains[i]->setInputDevice_l(sourceDeviceTypeAddr);
10083 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010084 }
10085
jiabinc52b1ff2019-10-31 17:20:42 -070010086 if (!isOutput()) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010087 // store new source and send to effects
10088 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
10089 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
10090 for (size_t i = 0; i < mEffectChains.size(); i++) {
10091 mEffectChains[i]->setAudioSource_l(mAudioSource);
10092 }
10093 }
10094 }
10095
10096 if (mAudioHwDev->supportsAudioPatches()) {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010097 status = mHalDevice->createAudioPatch(patch->num_sources, patch->sources, patch->num_sinks,
10098 patch->sinks, handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010099 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010100 audio_port_config port;
10101 std::optional<audio_source_t> source;
10102 if (isOutput()) {
10103 port = patch->sinks[0];
Eric Laurent6acd1d42017-01-04 14:23:29 -080010104 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010105 port = patch->sources[0];
10106 source = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010107 }
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010108 status = mHalStream->legacyCreateAudioPatch(port, source, type);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010109 *handle = AUDIO_PATCH_HANDLE_NONE;
10110 }
10111
jiabinc52b1ff2019-10-31 17:20:42 -070010112 if (numDevices == 0 || mDeviceId != deviceId) {
10113 if (isOutput()) {
10114 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
10115 mOutDeviceTypeAddrs = sinkDeviceTypeAddrs;
jiabin0a957d32020-04-29 10:56:20 -070010116 checkSilentMode_l();
jiabinc52b1ff2019-10-31 17:20:42 -070010117 } else {
10118 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
10119 mInDeviceTypeAddr = sourceDeviceTypeAddr;
10120 }
Phil Burk7f6b40d2017-02-09 13:18:38 -080010121 sp<MmapStreamCallback> callback = mCallback.promote();
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010122 if (mDeviceId != deviceId && callback != 0) {
Eric Laurent734046e2018-04-16 14:50:52 -070010123 mLock.unlock();
Phil Burk7f6b40d2017-02-09 13:18:38 -080010124 callback->onRoutingChanged(deviceId);
Eric Laurent734046e2018-04-16 14:50:52 -070010125 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010126 }
jiabinc52b1ff2019-10-31 17:20:42 -070010127 mPatch = *patch;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010128 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010129 }
Eric Laurentdda206a2022-07-08 17:28:35 +020010130 // Force meteadata update after a route change
10131 mActiveTracks.setHasChanged();
10132
Eric Laurent6acd1d42017-01-04 14:23:29 -080010133 return status;
10134}
10135
10136status_t AudioFlinger::MmapThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
10137{
10138 status_t status = NO_ERROR;
10139
jiabinc52b1ff2019-10-31 17:20:42 -070010140 mPatch = audio_patch{};
10141 mOutDeviceTypeAddrs.clear();
10142 mInDeviceTypeAddr.reset();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010143
10144 bool supportsAudioPatches = mHalDevice->supportsAudioPatches(&supportsAudioPatches) == OK ?
10145 supportsAudioPatches : false;
10146
10147 if (supportsAudioPatches) {
10148 status = mHalDevice->releaseAudioPatch(handle);
10149 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010150 status = mHalStream->legacyReleaseAudioPatch();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010151 }
Eric Laurentdda206a2022-07-08 17:28:35 +020010152 // Force meteadata update after a route change
10153 mActiveTracks.setHasChanged();
10154
Eric Laurent6acd1d42017-01-04 14:23:29 -080010155 return status;
10156}
10157
Mikhail Naganovdc769682018-05-04 15:34:08 -070010158void AudioFlinger::MmapThread::toAudioPortConfig(struct audio_port_config *config)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010159{
Mikhail Naganovdc769682018-05-04 15:34:08 -070010160 ThreadBase::toAudioPortConfig(config);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010161 if (isOutput()) {
10162 config->role = AUDIO_PORT_ROLE_SOURCE;
10163 config->ext.mix.hw_module = mAudioHwDev->handle();
10164 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
10165 } else {
10166 config->role = AUDIO_PORT_ROLE_SINK;
10167 config->ext.mix.hw_module = mAudioHwDev->handle();
10168 config->ext.mix.usecase.source = mAudioSource;
10169 }
10170}
10171
10172status_t AudioFlinger::MmapThread::addEffectChain_l(const sp<EffectChain>& chain)
10173{
10174 audio_session_t session = chain->sessionId();
10175
10176 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
10177 // Attach all tracks with same session ID to this chain.
10178 // indicate all active tracks in the chain
10179 for (const sp<MmapTrack> &track : mActiveTracks) {
10180 if (session == track->sessionId()) {
10181 chain->incTrackCnt();
10182 chain->incActiveTrackCnt();
10183 }
10184 }
10185
10186 chain->setThread(this);
10187 chain->setInBuffer(nullptr);
10188 chain->setOutBuffer(nullptr);
10189 chain->syncHalEffectsState();
10190
10191 mEffectChains.add(chain);
10192 checkSuspendOnAddEffectChain_l(chain);
10193 return NO_ERROR;
10194}
10195
10196size_t AudioFlinger::MmapThread::removeEffectChain_l(const sp<EffectChain>& chain)
10197{
10198 audio_session_t session = chain->sessionId();
10199
10200 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
10201
10202 for (size_t i = 0; i < mEffectChains.size(); i++) {
10203 if (chain == mEffectChains[i]) {
10204 mEffectChains.removeAt(i);
10205 // detach all active tracks from the chain
10206 // detach all tracks with same session ID from this chain
10207 for (const sp<MmapTrack> &track : mActiveTracks) {
10208 if (session == track->sessionId()) {
10209 chain->decActiveTrackCnt();
10210 chain->decTrackCnt();
10211 }
10212 }
10213 break;
10214 }
10215 }
10216 return mEffectChains.size();
10217}
10218
Eric Laurent6acd1d42017-01-04 14:23:29 -080010219void AudioFlinger::MmapThread::threadLoop_standby()
10220{
10221 mHalStream->standby();
10222}
10223
10224void AudioFlinger::MmapThread::threadLoop_exit()
10225{
Phil Burk7dce7282017-09-27 13:51:41 -070010226 // Do not call callback->onTearDown() because it is redundant for thread exit
10227 // and because it can cause a recursive mutex lock on stop().
Eric Laurent6acd1d42017-01-04 14:23:29 -080010228}
10229
10230status_t AudioFlinger::MmapThread::setSyncEvent(const sp<SyncEvent>& event __unused)
10231{
10232 return BAD_VALUE;
10233}
10234
10235bool AudioFlinger::MmapThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
10236{
10237 return false;
10238}
10239
10240status_t AudioFlinger::MmapThread::checkEffectCompatibility_l(
10241 const effect_descriptor_t *desc, audio_session_t sessionId)
10242{
10243 // No global effect sessions on mmap threads
Eric Laurent3f75a5b2019-11-12 15:55:51 -080010244 if (audio_is_global_session(sessionId)) {
10245 ALOGW("checkEffectCompatibility_l(): global effect %s on MMAP thread %s",
Eric Laurent6acd1d42017-01-04 14:23:29 -080010246 desc->name, mThreadName);
10247 return BAD_VALUE;
10248 }
10249
10250 if (!isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC)) {
10251 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on capture mmap thread",
10252 desc->name);
10253 return BAD_VALUE;
10254 }
10255 if (isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Glenn Kastend3bb6452016-12-05 18:14:37 -080010256 ALOGW("checkEffectCompatibility_l(): pre processing effect %s created on playback mmap "
10257 "thread", desc->name);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010258 return BAD_VALUE;
10259 }
10260
10261 // Only allow effects without processing load or latency
10262 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) != EFFECT_FLAG_NO_PROCESS) {
10263 return BAD_VALUE;
10264 }
10265
jiabineb3bda02020-06-30 14:07:03 -070010266 if (EffectModule::isHapticGenerator(&desc->type)) {
10267 ALOGE("%s(): HapticGenerator is not supported for MmapThread", __func__);
10268 return BAD_VALUE;
10269 }
10270
Eric Laurent6acd1d42017-01-04 14:23:29 -080010271 return NO_ERROR;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010272}
10273
10274void AudioFlinger::MmapThread::checkInvalidTracks_l()
10275{
10276 for (const sp<MmapTrack> &track : mActiveTracks) {
10277 if (track->isInvalid()) {
Phil Burk7f6b40d2017-02-09 13:18:38 -080010278 sp<MmapStreamCallback> callback = mCallback.promote();
10279 if (callback != 0) {
Eric Laurent734046e2018-04-16 14:50:52 -070010280 mLock.unlock();
Eric Laurent331679c2018-04-16 17:03:16 -070010281 callback->onTearDown(track->portId());
Eric Laurent734046e2018-04-16 14:50:52 -070010282 mLock.lock();
Eric Laurent331679c2018-04-16 17:03:16 -070010283 } else if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
10284 ALOGW("Could not notify MMAP stream tear down: no onTearDown callback!");
10285 mNoCallbackWarningCount++;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010286 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010287 }
10288 }
10289}
10290
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -070010291void AudioFlinger::MmapThread::dumpInternals_l(int fd, const Vector<String16>& args __unused)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010292{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010293 dprintf(fd, " Attributes: content type %d usage %d source %d\n",
10294 mAttr.content_type, mAttr.usage, mAttr.source);
10295 dprintf(fd, " Session: %d port Id: %d\n", mSessionId, mPortId);
Eric Tan39ec8d62018-07-24 09:49:29 -070010296 if (mActiveTracks.isEmpty()) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010297 dprintf(fd, " No active clients\n");
10298 }
10299}
10300
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -070010301void AudioFlinger::MmapThread::dumpTracks_l(int fd, const Vector<String16>& args __unused)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010302{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010303 String8 result;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010304 size_t numtracks = mActiveTracks.size();
Andy Hung2c6c3bb2017-06-16 14:01:45 -070010305 dprintf(fd, " %zu Tracks\n", numtracks);
10306 const char *prefix = " ";
Eric Laurent6acd1d42017-01-04 14:23:29 -080010307 if (numtracks) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -070010308 result.append(prefix);
Kevin Rocard5f2136e2018-05-11 22:03:00 -070010309 mActiveTracks[0]->appendDumpHeader(result);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010310 for (size_t i = 0; i < numtracks ; ++i) {
10311 sp<MmapTrack> track = mActiveTracks[i];
Andy Hung2c6c3bb2017-06-16 14:01:45 -070010312 result.append(prefix);
10313 track->appendDump(result, true /* active */);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010314 }
10315 } else {
10316 dprintf(fd, "\n");
10317 }
10318 write(fd, result.string(), result.size());
10319}
10320
10321AudioFlinger::MmapPlaybackThread::MmapPlaybackThread(
10322 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
jiabinc52b1ff2019-10-31 17:20:42 -070010323 AudioHwDevice *hwDev, AudioStreamOut *output, bool systemReady)
Andy Hungcf10d742020-04-28 15:38:24 -070010324 : MmapThread(audioFlinger, id, hwDev, output->stream, systemReady, true /* isOut */),
Eric Laurent6acd1d42017-01-04 14:23:29 -080010325 mStreamType(AUDIO_STREAM_MUSIC),
Phil Burk56ecf3e2018-03-12 15:38:17 -070010326 mStreamVolume(1.0),
10327 mStreamMute(false),
Phil Burk56ecf3e2018-03-12 15:38:17 -070010328 mOutput(output)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010329{
10330 snprintf(mThreadName, kThreadNameLength, "AudioMmapOut_%X", id);
10331 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
10332 mMasterVolume = audioFlinger->masterVolume_l();
10333 mMasterMute = audioFlinger->masterMute_l();
10334 if (mAudioHwDev) {
10335 if (mAudioHwDev->canSetMasterVolume()) {
10336 mMasterVolume = 1.0;
10337 }
10338
10339 if (mAudioHwDev->canSetMasterMute()) {
10340 mMasterMute = false;
10341 }
10342 }
10343}
10344
10345void AudioFlinger::MmapPlaybackThread::configure(const audio_attributes_t *attr,
10346 audio_stream_type_t streamType,
10347 audio_session_t sessionId,
10348 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010349 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010350 audio_port_handle_t portId)
10351{
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010352 MmapThread::configure(attr, streamType, sessionId, callback, deviceId, portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010353 mStreamType = streamType;
10354}
10355
10356AudioStreamOut* AudioFlinger::MmapPlaybackThread::clearOutput()
10357{
10358 Mutex::Autolock _l(mLock);
10359 AudioStreamOut *output = mOutput;
10360 mOutput = NULL;
10361 return output;
10362}
10363
10364void AudioFlinger::MmapPlaybackThread::setMasterVolume(float value)
10365{
10366 Mutex::Autolock _l(mLock);
10367 // Don't apply master volume in SW if our HAL can do it for us.
10368 if (mAudioHwDev &&
10369 mAudioHwDev->canSetMasterVolume()) {
10370 mMasterVolume = 1.0;
10371 } else {
10372 mMasterVolume = value;
10373 }
10374}
10375
10376void AudioFlinger::MmapPlaybackThread::setMasterMute(bool muted)
10377{
10378 Mutex::Autolock _l(mLock);
10379 // Don't apply master mute in SW if our HAL can do it for us.
10380 if (mAudioHwDev && mAudioHwDev->canSetMasterMute()) {
10381 mMasterMute = false;
10382 } else {
10383 mMasterMute = muted;
10384 }
10385}
10386
10387void AudioFlinger::MmapPlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
10388{
10389 Mutex::Autolock _l(mLock);
10390 if (stream == mStreamType) {
10391 mStreamVolume = value;
10392 broadcast_l();
10393 }
10394}
10395
10396float AudioFlinger::MmapPlaybackThread::streamVolume(audio_stream_type_t stream) const
10397{
10398 Mutex::Autolock _l(mLock);
10399 if (stream == mStreamType) {
10400 return mStreamVolume;
10401 }
10402 return 0.0f;
10403}
10404
10405void AudioFlinger::MmapPlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
10406{
10407 Mutex::Autolock _l(mLock);
10408 if (stream == mStreamType) {
10409 mStreamMute= muted;
10410 broadcast_l();
10411 }
10412}
10413
10414void AudioFlinger::MmapPlaybackThread::invalidateTracks(audio_stream_type_t streamType)
10415{
10416 Mutex::Autolock _l(mLock);
10417 if (streamType == mStreamType) {
10418 for (const sp<MmapTrack> &track : mActiveTracks) {
10419 track->invalidate();
10420 }
10421 broadcast_l();
10422 }
10423}
10424
10425void AudioFlinger::MmapPlaybackThread::processVolume_l()
10426{
10427 float volume;
10428
10429 if (mMasterMute || mStreamMute) {
10430 volume = 0;
10431 } else {
10432 volume = mMasterVolume * mStreamVolume;
10433 }
10434
10435 if (volume != mHalVolFloat) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010436
10437 // Convert volumes from float to 8.24
10438 uint32_t vol = (uint32_t)(volume * (1 << 24));
10439
10440 // Delegate volume control to effect in track effect chain if needed
10441 // only one effect chain can be present on DirectOutputThread, so if
10442 // there is one, the track is connected to it
10443 if (!mEffectChains.isEmpty()) {
10444 mEffectChains[0]->setVolume_l(&vol, &vol);
10445 volume = (float)vol / (1 << 24);
10446 }
Eric Laurentdff774a2017-04-21 15:29:38 -070010447 // Try to use HW volume control and fall back to SW control if not implemented
Phil Burk56ecf3e2018-03-12 15:38:17 -070010448 if (mOutput->stream->setVolume(volume, volume) == NO_ERROR) {
10449 mHalVolFloat = volume; // HW volume control worked, so update value.
10450 mNoCallbackWarningCount = 0;
10451 } else {
Eric Laurentdff774a2017-04-21 15:29:38 -070010452 sp<MmapStreamCallback> callback = mCallback.promote();
10453 if (callback != 0) {
Phil Burk56ecf3e2018-03-12 15:38:17 -070010454 mHalVolFloat = volume; // SW volume control worked, so update value.
10455 mNoCallbackWarningCount = 0;
Eric Laurent734046e2018-04-16 14:50:52 -070010456 mLock.unlock();
Robert Wu4389ae62022-02-17 18:39:41 +000010457 callback->onVolumeChanged(volume);
Eric Laurent734046e2018-04-16 14:50:52 -070010458 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010459 } else {
Phil Burk56ecf3e2018-03-12 15:38:17 -070010460 if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
10461 ALOGW("Could not set MMAP stream volume: no volume callback!");
10462 mNoCallbackWarningCount++;
10463 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010464 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010465 }
Jasmine Chaeaa10e42021-05-11 10:11:14 +080010466 for (const sp<MmapTrack> &track : mActiveTracks) {
10467 track->setMetadataHasChanged();
10468 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010469 }
10470}
10471
Kevin Rocard069c2712018-03-29 19:09:14 -070010472void AudioFlinger::MmapPlaybackThread::updateMetadata_l()
10473{
Jasmine Chaeaa10e42021-05-11 10:11:14 +080010474 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
10475 return; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -070010476 }
10477 StreamOutHalInterface::SourceMetadata metadata;
10478 for (const sp<MmapTrack> &track : mActiveTracks) {
10479 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurent94579172020-11-20 18:41:04 +010010480 playback_track_metadata_v7_t trackMetadata;
10481 trackMetadata.base = {
Kevin Rocard069c2712018-03-29 19:09:14 -070010482 .usage = track->attributes().usage,
10483 .content_type = track->attributes().content_type,
10484 .gain = mHalVolFloat, // TODO: propagate from aaudio pre-mix volume
Eric Laurent94579172020-11-20 18:41:04 +010010485 };
10486 trackMetadata.channel_mask = track->channelMask(),
10487 strncpy(trackMetadata.tags, track->attributes().tags, AUDIO_ATTRIBUTES_TAGS_MAX_SIZE);
10488 metadata.tracks.push_back(trackMetadata);
Kevin Rocard069c2712018-03-29 19:09:14 -070010489 }
10490 mOutput->stream->updateSourceMetadata(metadata);
10491}
10492
Eric Laurent6acd1d42017-01-04 14:23:29 -080010493void AudioFlinger::MmapPlaybackThread::checkSilentMode_l()
10494{
10495 if (!mMasterMute) {
10496 char value[PROPERTY_VALUE_MAX];
10497 if (property_get("ro.audio.silent", value, "0") > 0) {
10498 char *endptr;
10499 unsigned long ul = strtoul(value, &endptr, 0);
10500 if (*endptr == '\0' && ul != 0) {
10501 ALOGD("Silence is golden");
10502 // The setprop command will not allow a property to be changed after
10503 // the first time it is set, so we don't have to worry about un-muting.
10504 setMasterMute_l(true);
10505 }
10506 }
10507 }
10508}
10509
Mikhail Naganov32abc2b2018-05-24 12:57:11 -070010510void AudioFlinger::MmapPlaybackThread::toAudioPortConfig(struct audio_port_config *config)
10511{
10512 MmapThread::toAudioPortConfig(config);
10513 if (mOutput && mOutput->flags != AUDIO_OUTPUT_FLAG_NONE) {
10514 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
10515 config->flags.output = mOutput->flags;
10516 }
10517}
10518
jiabinb7d8c5a2020-08-26 17:24:52 -070010519status_t AudioFlinger::MmapPlaybackThread::getExternalPosition(uint64_t *position,
10520 int64_t *timeNanos)
10521{
10522 if (mOutput == nullptr) {
10523 return NO_INIT;
10524 }
10525 struct timespec timestamp;
10526 status_t status = mOutput->getPresentationPosition(position, &timestamp);
10527 if (status == NO_ERROR) {
10528 *timeNanos = timestamp.tv_sec * NANOS_PER_SECOND + timestamp.tv_nsec;
10529 }
10530 return status;
10531}
10532
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -070010533void AudioFlinger::MmapPlaybackThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010534{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -070010535 MmapThread::dumpInternals_l(fd, args);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010536
Glenn Kastend3bb6452016-12-05 18:14:37 -080010537 dprintf(fd, " Stream type: %d Stream volume: %f HAL volume: %f Stream mute %d\n",
10538 mStreamType, mStreamVolume, mHalVolFloat, mStreamMute);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010539 dprintf(fd, " Master volume: %f Master mute %d\n", mMasterVolume, mMasterMute);
10540}
10541
10542AudioFlinger::MmapCaptureThread::MmapCaptureThread(
10543 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
jiabinc52b1ff2019-10-31 17:20:42 -070010544 AudioHwDevice *hwDev, AudioStreamIn *input, bool systemReady)
Andy Hungcf10d742020-04-28 15:38:24 -070010545 : MmapThread(audioFlinger, id, hwDev, input->stream, systemReady, false /* isOut */),
Eric Laurent6acd1d42017-01-04 14:23:29 -080010546 mInput(input)
10547{
10548 snprintf(mThreadName, kThreadNameLength, "AudioMmapIn_%X", id);
10549 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
10550}
10551
Eric Laurentdda206a2022-07-08 17:28:35 +020010552status_t AudioFlinger::MmapCaptureThread::exitStandby_l()
Eric Laurent331679c2018-04-16 17:03:16 -070010553{
Phil Burkf054fc32018-12-06 09:45:59 -080010554 {
10555 // mInput might have been cleared by clearInput()
Phil Burkf054fc32018-12-06 09:45:59 -080010556 if (mInput != nullptr && mInput->stream != nullptr) {
10557 mInput->stream->setGain(1.0f);
10558 }
10559 }
Eric Laurentdda206a2022-07-08 17:28:35 +020010560 return MmapThread::exitStandby_l();
Eric Laurent331679c2018-04-16 17:03:16 -070010561}
10562
Eric Laurent6acd1d42017-01-04 14:23:29 -080010563AudioFlinger::AudioStreamIn* AudioFlinger::MmapCaptureThread::clearInput()
10564{
10565 Mutex::Autolock _l(mLock);
10566 AudioStreamIn *input = mInput;
10567 mInput = NULL;
10568 return input;
10569}
Kevin Rocard069c2712018-03-29 19:09:14 -070010570
Eric Laurent331679c2018-04-16 17:03:16 -070010571
10572void AudioFlinger::MmapCaptureThread::processVolume_l()
10573{
10574 bool changed = false;
10575 bool silenced = false;
10576
10577 sp<MmapStreamCallback> callback = mCallback.promote();
10578 if (callback == 0) {
10579 if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
10580 ALOGW("Could not set MMAP stream silenced: no onStreamSilenced callback!");
10581 mNoCallbackWarningCount++;
10582 }
10583 }
10584
10585 // After a change occurred in track silenced state, mute capture in audio DSP if at least one
10586 // track is silenced and unmute otherwise
10587 for (size_t i = 0; i < mActiveTracks.size() && !silenced; i++) {
10588 if (!mActiveTracks[i]->getAndSetSilencedNotified_l()) {
10589 changed = true;
10590 silenced = mActiveTracks[i]->isSilenced_l();
10591 }
10592 }
10593
10594 if (changed) {
10595 mInput->stream->setGain(silenced ? 0.0f: 1.0f);
10596 }
10597}
10598
Kevin Rocard069c2712018-03-29 19:09:14 -070010599void AudioFlinger::MmapCaptureThread::updateMetadata_l()
10600{
Jasmine Chaeaa10e42021-05-11 10:11:14 +080010601 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
10602 return; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -070010603 }
10604 StreamInHalInterface::SinkMetadata metadata;
10605 for (const sp<MmapTrack> &track : mActiveTracks) {
10606 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurent94579172020-11-20 18:41:04 +010010607 record_track_metadata_v7_t trackMetadata;
10608 trackMetadata.base = {
Kevin Rocard069c2712018-03-29 19:09:14 -070010609 .source = track->attributes().source,
10610 .gain = 1, // capture tracks do not have volumes
Eric Laurent94579172020-11-20 18:41:04 +010010611 };
10612 trackMetadata.channel_mask = track->channelMask(),
10613 strncpy(trackMetadata.tags, track->attributes().tags, AUDIO_ATTRIBUTES_TAGS_MAX_SIZE);
10614 metadata.tracks.push_back(trackMetadata);
Kevin Rocard069c2712018-03-29 19:09:14 -070010615 }
10616 mInput->stream->updateSinkMetadata(metadata);
10617}
10618
Eric Laurent5ada82e2019-08-29 17:53:54 -070010619void AudioFlinger::MmapCaptureThread::setRecordSilenced(audio_port_handle_t portId, bool silenced)
Eric Laurent331679c2018-04-16 17:03:16 -070010620{
10621 Mutex::Autolock _l(mLock);
10622 for (size_t i = 0; i < mActiveTracks.size() ; i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -070010623 if (mActiveTracks[i]->portId() == portId) {
Eric Laurent331679c2018-04-16 17:03:16 -070010624 mActiveTracks[i]->setSilenced_l(silenced);
10625 broadcast_l();
10626 }
10627 }
jiabin09609032022-06-15 19:26:01 +000010628 setClientSilencedIfExists_l(portId, silenced);
Eric Laurent331679c2018-04-16 17:03:16 -070010629}
10630
Mikhail Naganov32abc2b2018-05-24 12:57:11 -070010631void AudioFlinger::MmapCaptureThread::toAudioPortConfig(struct audio_port_config *config)
10632{
10633 MmapThread::toAudioPortConfig(config);
10634 if (mInput && mInput->flags != AUDIO_INPUT_FLAG_NONE) {
10635 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
10636 config->flags.input = mInput->flags;
10637 }
10638}
10639
jiabinb7d8c5a2020-08-26 17:24:52 -070010640status_t AudioFlinger::MmapCaptureThread::getExternalPosition(
10641 uint64_t *position, int64_t *timeNanos)
10642{
10643 if (mInput == nullptr) {
10644 return NO_INIT;
10645 }
10646 return mInput->getCapturePosition((int64_t*)position, timeNanos);
10647}
10648
Glenn Kasten63238ef2015-03-02 15:50:29 -080010649} // namespace android