blob: f4aff6dd37bea5078d5d7465c264adf585a3644e [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>
jiabinc52b1ff2019-10-31 17:20:42 -070034#include <media/AudioContainers.h>
35#include <media/AudioDeviceTypeAddr.h>
Glenn Kasten1ab85ec2013-05-31 09:18:43 -070036#include <media/AudioParameter.h>
Andy Hungcd044842014-08-07 11:04:34 -070037#include <media/AudioResamplerPublic.h>
Andy Hung89816052017-01-11 17:08:23 -080038#include <media/RecordBufferConverter.h>
Mikhail Naganov913d06c2016-11-01 12:49:22 -070039#include <media/TypeConverter.h>
Eric Laurent81784c32012-11-19 14:55:58 -080040#include <utils/Log.h>
Alex Ray371eb972012-11-30 11:11:54 -080041#include <utils/Trace.h>
Eric Laurent81784c32012-11-19 14:55:58 -080042
43#include <private/media/AudioTrackShared.h>
Wei Jiaf2ae3e12016-10-27 17:10:59 -070044#include <private/android_filesystem_config.h>
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +010045#include <audio_utils/Balance.h>
jiabinf6eb4c32020-02-25 14:06:25 -080046#include <audio_utils/Metadata.h>
jiabin245cdd92018-12-07 17:55:15 -080047#include <audio_utils/channels.h>
Glenn Kasten6bf707f2017-02-23 16:53:58 -080048#include <audio_utils/mono_blend.h>
Eric Laurent81784c32012-11-19 14:55:58 -080049#include <audio_utils/primitives.h>
Andy Hung98ef9782014-03-04 14:46:50 -080050#include <audio_utils/format.h>
Glenn Kastenc56f3422014-03-21 17:53:17 -070051#include <audio_utils/minifloat.h>
Hongwei Wang95e37682019-04-12 11:13:36 -070052#include <audio_utils/safe_math.h>
Mikhail Naganov9fe94012016-10-14 14:57:40 -070053#include <system/audio_effects/effect_ns.h>
54#include <system/audio_effects/effect_aec.h>
Mikhail Naganovcbc8f612016-10-11 18:05:13 -070055#include <system/audio.h>
Eric Laurent81784c32012-11-19 14:55:58 -080056
57// NBAIO implementations
Glenn Kasten6dbb5e32014-05-13 10:38:42 -070058#include <media/nbaio/AudioStreamInSource.h>
Eric Laurent81784c32012-11-19 14:55:58 -080059#include <media/nbaio/AudioStreamOutSink.h>
60#include <media/nbaio/MonoPipe.h>
61#include <media/nbaio/MonoPipeReader.h>
62#include <media/nbaio/Pipe.h>
63#include <media/nbaio/PipeReader.h>
64#include <media/nbaio/SourceAudioBufferProvider.h>
Wei Jia3f273d12015-11-24 09:06:49 -080065#include <mediautils/BatteryNotifier.h>
Eric Laurent81784c32012-11-19 14:55:58 -080066
Mikhail Naganov2996f672019-04-18 12:29:59 -070067#include <audiomanager/AudioManager.h>
Eric Laurent81784c32012-11-19 14:55:58 -080068#include <powermanager/PowerManager.h>
69
Kevin Rocard7588ff42018-01-08 11:11:30 -080070#include <media/audiohal/EffectsFactoryHalInterface.h>
Kevin Rocard069c2712018-03-29 19:09:14 -070071#include <media/audiohal/StreamHalInterface.h>
Kevin Rocard7588ff42018-01-08 11:11:30 -080072
Eric Laurent81784c32012-11-19 14:55:58 -080073#include "AudioFlinger.h"
Eric Laurent81784c32012-11-19 14:55:58 -080074#include "FastMixer.h"
Glenn Kasten6dbb5e32014-05-13 10:38:42 -070075#include "FastCapture.h"
Andy Hungab7ef302018-05-15 19:35:29 -070076#include <mediautils/SchedulingPolicyService.h>
77#include <mediautils/ServiceUtilities.h>
Eric Laurent81784c32012-11-19 14:55:58 -080078
Eric Laurent81784c32012-11-19 14:55:58 -080079#ifdef ADD_BATTERY_DATA
80#include <media/IMediaPlayerService.h>
81#include <media/IMediaDeathNotifier.h>
82#endif
83
Eric Laurent81784c32012-11-19 14:55:58 -080084#ifdef DEBUG_CPU_USAGE
Eric Tan5b13ff82018-07-27 11:20:17 -070085#include <audio_utils/Statistics.h>
Eric Laurent81784c32012-11-19 14:55:58 -080086#include <cpustats/ThreadCpuUsage.h>
87#endif
88
Glenn Kastenc05b8d72016-03-24 09:48:17 -070089#include "AutoPark.h"
90
Nicolas Rouletfe1e1442017-01-30 12:02:03 -080091#include <pthread.h>
92#include "TypedLogger.h"
93
Eric Laurent81784c32012-11-19 14:55:58 -080094// ----------------------------------------------------------------------------
95
96// Note: the following macro is used for extremely verbose logging message. In
97// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
98// 0; but one side effect of this is to turn all LOGV's as well. Some messages
99// are so verbose that we want to suppress them even when we have ALOG_ASSERT
100// turned on. Do not uncomment the #def below unless you really know what you
101// are doing and want to see all of the extremely verbose messages.
102//#define VERY_VERY_VERBOSE_LOGGING
103#ifdef VERY_VERY_VERBOSE_LOGGING
104#define ALOGVV ALOGV
105#else
106#define ALOGVV(a...) do { } while(0)
107#endif
108
Andy Hung6770c6f2015-04-07 13:43:36 -0700109// TODO: Move these macro/inlines to a header file.
Glenn Kasten49d00ad2014-07-21 11:22:03 -0700110#define max(a, b) ((a) > (b) ? (a) : (b))
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700111
Andy Hung6770c6f2015-04-07 13:43:36 -0700112template <typename T>
113static inline T min(const T& a, const T& b)
114{
115 return a < b ? a : b;
116}
Glenn Kasten49d00ad2014-07-21 11:22:03 -0700117
Eric Laurent81784c32012-11-19 14:55:58 -0800118namespace android {
119
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -0700120using media::IEffectClient;
Svet Ganov33761132021-05-13 22:51:08 +0000121using content::AttributionSourceState;
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -0700122
Eric Laurent81784c32012-11-19 14:55:58 -0800123// retry counts for buffer fill timeout
124// 50 * ~20msecs = 1 second
125static const int8_t kMaxTrackRetries = 50;
126static const int8_t kMaxTrackStartupRetries = 50;
Andy Hung455982f2021-04-27 17:46:12 -0700127
Eric Laurent81784c32012-11-19 14:55:58 -0800128// allow less retry attempts on direct output thread.
129// direct outputs can be a scarce resource in audio hardware and should
130// be released as quickly as possible.
Andy Hung455982f2021-04-27 17:46:12 -0700131// Notes:
132// 1) The retry duration kMaxTrackRetriesDirectMs may be increased
133// in case the data write is bursty for the AudioTrack. The application
134// should endeavor to write at least once every kMaxTrackRetriesDirectMs
135// to prevent an underrun situation. If the data is bursty, then
136// the application can also throttle the data sent to be even.
137// 2) For compressed audio data, any data present in the AudioTrack buffer
138// will be sent and reset the retry count. This delivers data as
139// it arrives, with approximately kDirectMinSleepTimeUs = 10ms checking interval.
140// 3) For linear PCM or proportional PCM, we wait one period for a period's worth
141// of data to be available, then any remaining data is delivered.
142// This is required to ensure the last bit of data is delivered before underrun.
143//
144// Sleep time per cycle is kDirectMinSleepTimeUs for compressed tracks
145// or the size of the HAL period for proportional / linear PCM tracks.
146static const int32_t kMaxTrackRetriesDirectMs = 200;
Eric Laurent81784c32012-11-19 14:55:58 -0800147
148// don't warn about blocked writes or record buffer overflows more often than this
149static const nsecs_t kWarningThrottleNs = seconds(5);
150
151// RecordThread loop sleep time upon application overrun or audio HAL read error
152static const int kRecordThreadSleepUs = 5000;
153
Eric Laurent10351942014-05-08 18:49:52 -0700154// maximum time to wait in sendConfigEvent_l() for a status to be received
155static const nsecs_t kConfigEventTimeoutNs = seconds(2);
Eric Laurent81784c32012-11-19 14:55:58 -0800156
157// minimum sleep time for the mixer thread loop when tracks are active but in underrun
158static const uint32_t kMinThreadSleepTimeUs = 5000;
159// maximum divider applied to the active sleep time in the mixer thread loop
160static const uint32_t kMaxThreadSleepTimeShift = 2;
161
Andy Hung09a50072014-02-27 14:30:47 -0800162// minimum normal sink buffer size, expressed in milliseconds rather than frames
Glenn Kasteneb9487e2015-07-22 09:15:17 -0700163// FIXME This should be based on experimentally observed scheduling jitter
Andy Hung09a50072014-02-27 14:30:47 -0800164static const uint32_t kMinNormalSinkBufferSizeMs = 20;
165// maximum normal sink buffer size
166static const uint32_t kMaxNormalSinkBufferSizeMs = 24;
Eric Laurent81784c32012-11-19 14:55:58 -0800167
Glenn Kasteneb9487e2015-07-22 09:15:17 -0700168// minimum capture buffer size in milliseconds to _not_ need a fast capture thread
169// FIXME This should be based on experimentally observed scheduling jitter
170static const uint32_t kMinNormalCaptureBufferSizeMs = 12;
171
Eric Laurent972a1732013-09-04 09:42:59 -0700172// Offloaded output thread standby delay: allows track transition without going to standby
173static const nsecs_t kOffloadStandbyDelayNs = seconds(1);
174
Eric Laurent51716182016-02-29 18:00:56 -0800175// Direct output thread minimum sleep time in idle or active(underrun) state
176static const nsecs_t kDirectMinSleepTimeUs = 10000;
177
Glenn Kasten1b291842016-07-18 14:55:21 -0700178// The universal constant for ubiquitous 20ms value. The value of 20ms seems to provide a good
179// balance between power consumption and latency, and allows threads to be scheduled reliably
180// by the CFS scheduler.
181// FIXME Express other hardcoded references to 20ms with references to this constant and move
182// it appropriately.
183#define FMS_20 20
Eric Laurent51716182016-02-29 18:00:56 -0800184
Eric Laurent81784c32012-11-19 14:55:58 -0800185// Whether to use fast mixer
186static const enum {
187 FastMixer_Never, // never initialize or use: for debugging only
188 FastMixer_Always, // always initialize and use, even if not needed: for debugging only
189 // normal mixer multiplier is 1
190 FastMixer_Static, // initialize if needed, then use all the time if initialized,
191 // multiplier is calculated based on min & max normal mixer buffer size
192 FastMixer_Dynamic, // initialize if needed, then use dynamically depending on track load,
193 // multiplier is calculated based on min & max normal mixer buffer size
194 // FIXME for FastMixer_Dynamic:
195 // Supporting this option will require fixing HALs that can't handle large writes.
196 // For example, one HAL implementation returns an error from a large write,
197 // and another HAL implementation corrupts memory, possibly in the sample rate converter.
198 // We could either fix the HAL implementations, or provide a wrapper that breaks
199 // up large writes into smaller ones, and the wrapper would need to deal with scheduler.
200} kUseFastMixer = FastMixer_Static;
201
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700202// Whether to use fast capture
203static const enum {
204 FastCapture_Never, // never initialize or use: for debugging only
205 FastCapture_Always, // always initialize and use, even if not needed: for debugging only
206 FastCapture_Static, // initialize if needed, then use all the time if initialized
207} kUseFastCapture = FastCapture_Static;
208
Eric Laurent81784c32012-11-19 14:55:58 -0800209// Priorities for requestPriority
210static const int kPriorityAudioApp = 2;
211static const int kPriorityFastMixer = 3;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700212static const int kPriorityFastCapture = 3;
Eric Laurent81784c32012-11-19 14:55:58 -0800213
Glenn Kastenea38ee72016-04-18 11:08:01 -0700214// IAudioFlinger::createTrack() has an in/out parameter 'pFrameCount' for the total size of the
215// track buffer in shared memory. Zero on input means to use a default value. For fast tracks,
216// AudioFlinger derives the default from HAL buffer size and 'fast track multiplier'.
Glenn Kasten03490092014-05-27 12:30:54 -0700217
218// This is the default value, if not specified by property.
Glenn Kastenb5fed682013-12-03 09:06:43 -0800219static const int kFastTrackMultiplier = 2;
Eric Laurent81784c32012-11-19 14:55:58 -0800220
Glenn Kasten03490092014-05-27 12:30:54 -0700221// The minimum and maximum allowed values
222static const int kFastTrackMultiplierMin = 1;
223static const int kFastTrackMultiplierMax = 2;
224
225// The actual value to use, which can be specified per-device via property af.fast_track_multiplier.
226static int sFastTrackMultiplier = kFastTrackMultiplier;
227
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700228// See Thread::readOnlyHeap().
229// Initially this heap is used to allocate client buffers for "fast" AudioRecord.
230// Eventually it will be the single buffer that FastCapture writes into via HAL read(),
231// and that all "fast" AudioRecord clients read from. In either case, the size can be small.
Mikhail Naganov79a77822018-05-10 15:57:25 -0700232static const size_t kRecordThreadReadOnlyHeapSize = 0xD000;
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700233
Eric Laurent81784c32012-11-19 14:55:58 -0800234// ----------------------------------------------------------------------------
235
Andy Hungb68f5eb2019-12-03 16:49:17 -0800236// TODO: move all toString helpers to audio.h
237// under #ifdef __cplusplus #endif
238static std::string patchSinksToString(const struct audio_patch *patch)
239{
240 std::stringstream ss;
241 for (size_t i = 0; i < patch->num_sinks; ++i) {
Andy Hungc2b11cb2020-04-22 09:04:01 -0700242 if (i > 0) {
243 ss << "|";
244 }
Andy Hungb68f5eb2019-12-03 16:49:17 -0800245 ss << "(" << toString(patch->sinks[i].ext.device.type)
246 << ", " << patch->sinks[i].ext.device.address << ")";
247 }
248 return ss.str();
249}
250
251static std::string patchSourcesToString(const struct audio_patch *patch)
252{
253 std::stringstream ss;
254 for (size_t i = 0; i < patch->num_sources; ++i) {
Andy Hungc2b11cb2020-04-22 09:04:01 -0700255 if (i > 0) {
256 ss << "|";
257 }
Andy Hungb68f5eb2019-12-03 16:49:17 -0800258 ss << "(" << toString(patch->sources[i].ext.device.type)
259 << ", " << patch->sources[i].ext.device.address << ")";
260 }
261 return ss.str();
262}
263
Glenn Kasten03490092014-05-27 12:30:54 -0700264static pthread_once_t sFastTrackMultiplierOnce = PTHREAD_ONCE_INIT;
265
266static void sFastTrackMultiplierInit()
267{
268 char value[PROPERTY_VALUE_MAX];
269 if (property_get("af.fast_track_multiplier", value, NULL) > 0) {
270 char *endptr;
271 unsigned long ul = strtoul(value, &endptr, 0);
272 if (*endptr == '\0' && kFastTrackMultiplierMin <= ul && ul <= kFastTrackMultiplierMax) {
273 sFastTrackMultiplier = (int) ul;
274 }
275 }
276}
277
278// ----------------------------------------------------------------------------
279
Eric Laurent81784c32012-11-19 14:55:58 -0800280#ifdef ADD_BATTERY_DATA
281// To collect the amplifier usage
282static void addBatteryData(uint32_t params) {
283 sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService();
284 if (service == NULL) {
285 // it already logged
286 return;
287 }
288
289 service->addBatteryData(params);
290}
291#endif
292
Andy Hung3f0c9022016-01-15 17:49:46 -0800293// Track the CLOCK_BOOTTIME versus CLOCK_MONOTONIC timebase offset
294struct {
295 // call when you acquire a partial wakelock
296 void acquire(const sp<IBinder> &wakeLockToken) {
297 pthread_mutex_lock(&mLock);
298 if (wakeLockToken.get() == nullptr) {
299 adjustTimebaseOffset(&mBoottimeOffset, ExtendedTimestamp::TIMEBASE_BOOTTIME);
300 } else {
301 if (mCount == 0) {
302 adjustTimebaseOffset(&mBoottimeOffset, ExtendedTimestamp::TIMEBASE_BOOTTIME);
303 }
304 ++mCount;
305 }
306 pthread_mutex_unlock(&mLock);
307 }
308
309 // call when you release a partial wakelock.
310 void release(const sp<IBinder> &wakeLockToken) {
311 if (wakeLockToken.get() == nullptr) {
312 return;
313 }
314 pthread_mutex_lock(&mLock);
315 if (--mCount < 0) {
316 ALOGE("negative wakelock count");
317 mCount = 0;
318 }
319 pthread_mutex_unlock(&mLock);
320 }
321
322 // retrieves the boottime timebase offset from monotonic.
323 int64_t getBoottimeOffset() {
324 pthread_mutex_lock(&mLock);
325 int64_t boottimeOffset = mBoottimeOffset;
326 pthread_mutex_unlock(&mLock);
327 return boottimeOffset;
328 }
329
330 // Adjusts the timebase offset between TIMEBASE_MONOTONIC
331 // and the selected timebase.
332 // Currently only TIMEBASE_BOOTTIME is allowed.
333 //
334 // This only needs to be called upon acquiring the first partial wakelock
335 // after all other partial wakelocks are released.
336 //
337 // We do an empirical measurement of the offset rather than parsing
338 // /proc/timer_list since the latter is not a formal kernel ABI.
339 static void adjustTimebaseOffset(int64_t *offset, ExtendedTimestamp::Timebase timebase) {
340 int clockbase;
341 switch (timebase) {
342 case ExtendedTimestamp::TIMEBASE_BOOTTIME:
343 clockbase = SYSTEM_TIME_BOOTTIME;
344 break;
345 default:
346 LOG_ALWAYS_FATAL("invalid timebase %d", timebase);
347 break;
348 }
349 // try three times to get the clock offset, choose the one
350 // with the minimum gap in measurements.
351 const int tries = 3;
352 nsecs_t bestGap, measured;
353 for (int i = 0; i < tries; ++i) {
354 const nsecs_t tmono = systemTime(SYSTEM_TIME_MONOTONIC);
355 const nsecs_t tbase = systemTime(clockbase);
356 const nsecs_t tmono2 = systemTime(SYSTEM_TIME_MONOTONIC);
357 const nsecs_t gap = tmono2 - tmono;
358 if (i == 0 || gap < bestGap) {
359 bestGap = gap;
360 measured = tbase - ((tmono + tmono2) >> 1);
361 }
362 }
363
364 // to avoid micro-adjusting, we don't change the timebase
365 // unless it is significantly different.
366 //
367 // Assumption: It probably takes more than toleranceNs to
368 // suspend and resume the device.
369 static int64_t toleranceNs = 10000; // 10 us
370 if (llabs(*offset - measured) > toleranceNs) {
371 ALOGV("Adjusting timebase offset old: %lld new: %lld",
372 (long long)*offset, (long long)measured);
373 *offset = measured;
374 }
375 }
376
377 pthread_mutex_t mLock;
378 int32_t mCount;
379 int64_t mBoottimeOffset;
380} gBoottime = { PTHREAD_MUTEX_INITIALIZER, 0, 0 }; // static, so use POD initialization
Eric Laurent81784c32012-11-19 14:55:58 -0800381
382// ----------------------------------------------------------------------------
383// CPU Stats
384// ----------------------------------------------------------------------------
385
386class CpuStats {
387public:
388 CpuStats();
389 void sample(const String8 &title);
390#ifdef DEBUG_CPU_USAGE
391private:
392 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns
Andy Hung16698b82018-08-01 10:48:38 -0700393 audio_utils::Statistics<double> mWcStats; // statistics on thread CPU usage in wall clock ns
Eric Laurent81784c32012-11-19 14:55:58 -0800394
Andy Hung16698b82018-08-01 10:48:38 -0700395 audio_utils::Statistics<double> mHzStats; // statistics on thread CPU usage in cycles
Eric Laurent81784c32012-11-19 14:55:58 -0800396
397 int mCpuNum; // thread's current CPU number
398 int mCpukHz; // frequency of thread's current CPU in kHz
399#endif
400};
401
402CpuStats::CpuStats()
403#ifdef DEBUG_CPU_USAGE
404 : mCpuNum(-1), mCpukHz(-1)
405#endif
406{
407}
408
Glenn Kasten0f11b512014-01-31 16:18:54 -0800409void CpuStats::sample(const String8 &title
410#ifndef DEBUG_CPU_USAGE
411 __unused
412#endif
413 ) {
Eric Laurent81784c32012-11-19 14:55:58 -0800414#ifdef DEBUG_CPU_USAGE
415 // get current thread's delta CPU time in wall clock ns
416 double wcNs;
417 bool valid = mCpuUsage.sampleAndEnable(wcNs);
418
419 // record sample for wall clock statistics
420 if (valid) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700421 mWcStats.add(wcNs);
Eric Laurent81784c32012-11-19 14:55:58 -0800422 }
423
424 // get the current CPU number
425 int cpuNum = sched_getcpu();
426
427 // get the current CPU frequency in kHz
428 int cpukHz = mCpuUsage.getCpukHz(cpuNum);
429
430 // check if either CPU number or frequency changed
431 if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
432 mCpuNum = cpuNum;
433 mCpukHz = cpukHz;
434 // ignore sample for purposes of cycles
435 valid = false;
436 }
437
438 // if no change in CPU number or frequency, then record sample for cycle statistics
439 if (valid && mCpukHz > 0) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700440 const double cycles = wcNs * cpukHz * 0.000001;
441 mHzStats.add(cycles);
Eric Laurent81784c32012-11-19 14:55:58 -0800442 }
443
Eric Tan5b13ff82018-07-27 11:20:17 -0700444 const unsigned n = mWcStats.getN();
Eric Laurent81784c32012-11-19 14:55:58 -0800445 // mCpuUsage.elapsed() is expensive, so don't call it every loop
446 if ((n & 127) == 1) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700447 const long long elapsed = mCpuUsage.elapsed();
Eric Laurent81784c32012-11-19 14:55:58 -0800448 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700449 const double perLoop = elapsed / (double) n;
450 const double perLoop100 = perLoop * 0.01;
451 const double perLoop1k = perLoop * 0.001;
452 const double mean = mWcStats.getMean();
453 const double stddev = mWcStats.getStdDev();
454 const double minimum = mWcStats.getMin();
455 const double maximum = mWcStats.getMax();
456 const double meanCycles = mHzStats.getMean();
457 const double stddevCycles = mHzStats.getStdDev();
458 const double minCycles = mHzStats.getMin();
459 const double maxCycles = mHzStats.getMax();
Eric Laurent81784c32012-11-19 14:55:58 -0800460 mCpuUsage.resetElapsed();
461 mWcStats.reset();
462 mHzStats.reset();
463 ALOGD("CPU usage for %s over past %.1f secs\n"
464 " (%u mixer loops at %.1f mean ms per loop):\n"
465 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
466 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
467 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
468 title.string(),
469 elapsed * .000000001, n, perLoop * .000001,
470 mean * .001,
471 stddev * .001,
472 minimum * .001,
473 maximum * .001,
474 mean / perLoop100,
475 stddev / perLoop100,
476 minimum / perLoop100,
477 maximum / perLoop100,
478 meanCycles / perLoop1k,
479 stddevCycles / perLoop1k,
480 minCycles / perLoop1k,
481 maxCycles / perLoop1k);
482
483 }
484 }
485#endif
486};
487
488// ----------------------------------------------------------------------------
489// ThreadBase
490// ----------------------------------------------------------------------------
491
Glenn Kasten97b7b752014-09-28 13:04:24 -0700492// static
493const char *AudioFlinger::ThreadBase::threadTypeToString(AudioFlinger::ThreadBase::type_t type)
494{
495 switch (type) {
496 case MIXER:
497 return "MIXER";
498 case DIRECT:
499 return "DIRECT";
500 case DUPLICATING:
501 return "DUPLICATING";
502 case RECORD:
503 return "RECORD";
504 case OFFLOAD:
505 return "OFFLOAD";
Andy Hungea840382020-05-05 21:50:17 -0700506 case MMAP_PLAYBACK:
507 return "MMAP_PLAYBACK";
508 case MMAP_CAPTURE:
509 return "MMAP_CAPTURE";
Glenn Kasten97b7b752014-09-28 13:04:24 -0700510 default:
511 return "unknown";
512 }
513}
514
Eric Laurent81784c32012-11-19 14:55:58 -0800515AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
Andy Hungcf10d742020-04-28 15:38:24 -0700516 type_t type, bool systemReady, bool isOut)
Eric Laurent81784c32012-11-19 14:55:58 -0800517 : Thread(false /*canCallJava*/),
518 mType(type),
Glenn Kasten9b58f632013-07-16 11:37:48 -0700519 mAudioFlinger(audioFlinger),
Andy Hungcf10d742020-04-28 15:38:24 -0700520 mThreadMetrics(std::string(AMEDIAMETRICS_KEY_PREFIX_AUDIO_THREAD) + std::to_string(id),
521 isOut),
522 mIsOut(isOut),
Glenn Kasten70949c42013-08-06 07:40:12 -0700523 // mSampleRate, mFrameCount, mChannelMask, mChannelCount, mFrameSize, mFormat, mBufferSize
Glenn Kastendeca2ae2014-02-07 10:25:56 -0800524 // are set by PlaybackThread::readOutputParameters_l() or
525 // RecordThread::readInputParameters_l()
Eric Laurentfd477972013-10-25 18:10:40 -0700526 //FIXME: mStandby should be true here. Is this some kind of hack?
jiabinc52b1ff2019-10-31 17:20:42 -0700527 mStandby(false),
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700528 mAudioSource(AUDIO_SOURCE_DEFAULT), mId(id),
Eric Laurent81784c32012-11-19 14:55:58 -0800529 // mName will be set by concrete (non-virtual) subclass
Eric Laurent72e3f392015-05-20 14:43:50 -0700530 mDeathRecipient(new PMDeathRecipient(this)),
Eric Laurent6acd1d42017-01-04 14:23:29 -0800531 mSystemReady(systemReady),
532 mSignalPending(false)
Eric Laurent81784c32012-11-19 14:55:58 -0800533{
Andy Hungcf10d742020-04-28 15:38:24 -0700534 mThreadMetrics.logConstructor(getpid(), threadTypeToString(type), id);
Eric Laurent296fb132015-05-01 11:38:42 -0700535 memset(&mPatch, 0, sizeof(struct audio_patch));
Eric Laurent81784c32012-11-19 14:55:58 -0800536}
537
538AudioFlinger::ThreadBase::~ThreadBase()
539{
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700540 // mConfigEvents should be empty, but just in case it isn't, free the memory it owns
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700541 mConfigEvents.clear();
542
Eric Laurent81784c32012-11-19 14:55:58 -0800543 // do not lock the mutex in destructor
544 releaseWakeLock_l();
545 if (mPowerManager != 0) {
Marco Nelissen06b46062014-11-14 07:58:25 -0800546 sp<IBinder> binder = IInterface::asBinder(mPowerManager);
Eric Laurent81784c32012-11-19 14:55:58 -0800547 binder->unlinkToDeath(mDeathRecipient);
548 }
Andy Hungd0979812019-02-21 15:51:44 -0800549
550 sendStatistics(true /* force */);
Eric Laurent81784c32012-11-19 14:55:58 -0800551}
552
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700553status_t AudioFlinger::ThreadBase::readyToRun()
554{
555 status_t status = initCheck();
556 if (status == NO_ERROR) {
Glenn Kasten1bfe09a2017-02-21 13:05:56 -0800557 ALOGI("AudioFlinger's thread %p tid=%d ready to run", this, getTid());
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700558 } else {
559 ALOGE("No working audio driver found.");
560 }
561 return status;
562}
563
Eric Laurent81784c32012-11-19 14:55:58 -0800564void AudioFlinger::ThreadBase::exit()
565{
566 ALOGV("ThreadBase::exit");
567 // do any cleanup required for exit to succeed
568 preExit();
569 {
570 // This lock prevents the following race in thread (uniprocessor for illustration):
571 // if (!exitPending()) {
572 // // context switch from here to exit()
573 // // exit() calls requestExit(), what exitPending() observes
574 // // exit() calls signal(), which is dropped since no waiters
575 // // context switch back from exit() to here
576 // mWaitWorkCV.wait(...);
577 // // now thread is hung
578 // }
579 AutoMutex lock(mLock);
580 requestExit();
581 mWaitWorkCV.broadcast();
582 }
583 // When Thread::requestExitAndWait is made virtual and this method is renamed to
584 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
585 requestExitAndWait();
586}
587
588status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
589{
Eric Laurent81784c32012-11-19 14:55:58 -0800590 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
591 Mutex::Autolock _l(mLock);
592
Eric Laurent10351942014-05-08 18:49:52 -0700593 return sendSetParameterConfigEvent_l(keyValuePairs);
594}
595
596// sendConfigEvent_l() must be called with ThreadBase::mLock held
597// Can temporarily release the lock if waiting for a reply from processConfigEvents_l().
598status_t AudioFlinger::ThreadBase::sendConfigEvent_l(sp<ConfigEvent>& event)
599{
600 status_t status = NO_ERROR;
601
Eric Laurent72e3f392015-05-20 14:43:50 -0700602 if (event->mRequiresSystemReady && !mSystemReady) {
603 event->mWaitStatus = false;
604 mPendingConfigEvents.add(event);
605 return status;
606 }
Eric Laurent10351942014-05-08 18:49:52 -0700607 mConfigEvents.add(event);
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700608 ALOGV("sendConfigEvent_l() num events %zu event %d", mConfigEvents.size(), event->mType);
Eric Laurent81784c32012-11-19 14:55:58 -0800609 mWaitWorkCV.signal();
Eric Laurent10351942014-05-08 18:49:52 -0700610 mLock.unlock();
611 {
612 Mutex::Autolock _l(event->mLock);
613 while (event->mWaitStatus) {
614 if (event->mCond.waitRelative(event->mLock, kConfigEventTimeoutNs) != NO_ERROR) {
615 event->mStatus = TIMED_OUT;
616 event->mWaitStatus = false;
617 }
618 }
619 status = event->mStatus;
Eric Laurent81784c32012-11-19 14:55:58 -0800620 }
Eric Laurent10351942014-05-08 18:49:52 -0700621 mLock.lock();
Eric Laurent81784c32012-11-19 14:55:58 -0800622 return status;
623}
624
Eric Laurent09f1ed22019-04-24 17:45:17 -0700625void AudioFlinger::ThreadBase::sendIoConfigEvent(audio_io_config_event event, pid_t pid,
626 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -0800627{
628 Mutex::Autolock _l(mLock);
Eric Laurent09f1ed22019-04-24 17:45:17 -0700629 sendIoConfigEvent_l(event, pid, portId);
Eric Laurent81784c32012-11-19 14:55:58 -0800630}
631
632// sendIoConfigEvent_l() must be called with ThreadBase::mLock held
Eric Laurent09f1ed22019-04-24 17:45:17 -0700633void AudioFlinger::ThreadBase::sendIoConfigEvent_l(audio_io_config_event event, pid_t pid,
634 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -0800635{
Andy Hungd0979812019-02-21 15:51:44 -0800636 // The audio statistics history is exponentially weighted to forget events
637 // about five or more seconds in the past. In order to have
638 // crisper statistics for mediametrics, we reset the statistics on
639 // an IoConfigEvent, to reflect different properties for a new device.
640 mIoJitterMs.reset();
641 mLatencyMs.reset();
642 mProcessTimeMs.reset();
Dean Wheatley12473e92021-03-18 23:00:55 +1100643 mTimestampVerifier.discontinuity(mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS);
Andy Hungd0979812019-02-21 15:51:44 -0800644
Eric Laurent09f1ed22019-04-24 17:45:17 -0700645 sp<ConfigEvent> configEvent = (ConfigEvent *)new IoConfigEvent(event, pid, portId);
Eric Laurent10351942014-05-08 18:49:52 -0700646 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800647}
648
Mikhail Naganov83f04272017-02-07 10:45:09 -0800649void AudioFlinger::ThreadBase::sendPrioConfigEvent(pid_t pid, pid_t tid, int32_t prio, bool forApp)
Eric Laurent72e3f392015-05-20 14:43:50 -0700650{
651 Mutex::Autolock _l(mLock);
Mikhail Naganov83f04272017-02-07 10:45:09 -0800652 sendPrioConfigEvent_l(pid, tid, prio, forApp);
Eric Laurent72e3f392015-05-20 14:43:50 -0700653}
654
Eric Laurent81784c32012-11-19 14:55:58 -0800655// sendPrioConfigEvent_l() must be called with ThreadBase::mLock held
Mikhail Naganov83f04272017-02-07 10:45:09 -0800656void AudioFlinger::ThreadBase::sendPrioConfigEvent_l(
657 pid_t pid, pid_t tid, int32_t prio, bool forApp)
Eric Laurent81784c32012-11-19 14:55:58 -0800658{
Mikhail Naganov83f04272017-02-07 10:45:09 -0800659 sp<ConfigEvent> configEvent = (ConfigEvent *)new PrioConfigEvent(pid, tid, prio, forApp);
Eric Laurent10351942014-05-08 18:49:52 -0700660 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800661}
662
Eric Laurent10351942014-05-08 18:49:52 -0700663// sendSetParameterConfigEvent_l() must be called with ThreadBase::mLock held
664status_t AudioFlinger::ThreadBase::sendSetParameterConfigEvent_l(const String8& keyValuePair)
Eric Laurent81784c32012-11-19 14:55:58 -0800665{
Andy Hung2ddee192015-12-18 17:34:44 -0800666 sp<ConfigEvent> configEvent;
667 AudioParameter param(keyValuePair);
668 int value;
Mikhail Naganov00260b52016-10-13 12:54:24 -0700669 if (param.getInt(String8(AudioParameter::keyMonoOutput), value) == NO_ERROR) {
Andy Hung2ddee192015-12-18 17:34:44 -0800670 setMasterMono_l(value != 0);
671 if (param.size() == 1) {
672 return NO_ERROR; // should be a solo parameter - we don't pass down
673 }
Mikhail Naganov00260b52016-10-13 12:54:24 -0700674 param.remove(String8(AudioParameter::keyMonoOutput));
Andy Hung2ddee192015-12-18 17:34:44 -0800675 configEvent = new SetParameterConfigEvent(param.toString());
676 } else {
677 configEvent = new SetParameterConfigEvent(keyValuePair);
678 }
Eric Laurent10351942014-05-08 18:49:52 -0700679 return sendConfigEvent_l(configEvent);
Glenn Kastenf7773312013-08-13 16:00:42 -0700680}
681
Eric Laurent1c333e22014-05-20 10:48:17 -0700682status_t AudioFlinger::ThreadBase::sendCreateAudioPatchConfigEvent(
683 const struct audio_patch *patch,
684 audio_patch_handle_t *handle)
685{
686 Mutex::Autolock _l(mLock);
687 sp<ConfigEvent> configEvent = (ConfigEvent *)new CreateAudioPatchConfigEvent(*patch, *handle);
688 status_t status = sendConfigEvent_l(configEvent);
689 if (status == NO_ERROR) {
690 CreateAudioPatchConfigEventData *data =
691 (CreateAudioPatchConfigEventData *)configEvent->mData.get();
692 *handle = data->mHandle;
693 }
694 return status;
695}
696
697status_t AudioFlinger::ThreadBase::sendReleaseAudioPatchConfigEvent(
698 const audio_patch_handle_t handle)
699{
700 Mutex::Autolock _l(mLock);
701 sp<ConfigEvent> configEvent = (ConfigEvent *)new ReleaseAudioPatchConfigEvent(handle);
702 return sendConfigEvent_l(configEvent);
703}
704
jiabinc52b1ff2019-10-31 17:20:42 -0700705status_t AudioFlinger::ThreadBase::sendUpdateOutDeviceConfigEvent(
706 const DeviceDescriptorBaseVector& outDevices)
707{
708 if (type() != RECORD) {
709 // The update out device operation is only for record thread.
710 return INVALID_OPERATION;
711 }
712 Mutex::Autolock _l(mLock);
713 sp<ConfigEvent> configEvent = (ConfigEvent *)new UpdateOutDevicesConfigEvent(outDevices);
714 return sendConfigEvent_l(configEvent);
715}
716
Eric Laurentec376dc2021-04-08 20:41:22 +0200717void AudioFlinger::ThreadBase::sendResizeBufferConfigEvent_l(int32_t maxSharedAudioHistoryMs)
718{
719 ALOG_ASSERT(type() == RECORD, "sendResizeBufferConfigEvent_l() called on non record thread");
720 sp<ConfigEvent> configEvent =
721 (ConfigEvent *)new ResizeBufferConfigEvent(maxSharedAudioHistoryMs);
722 sendConfigEvent_l(configEvent);
723}
Eric Laurent1c333e22014-05-20 10:48:17 -0700724
Glenn Kasten2cfbf882013-08-14 13:12:11 -0700725// post condition: mConfigEvents.isEmpty()
Eric Laurent021cf962014-05-13 10:18:14 -0700726void AudioFlinger::ThreadBase::processConfigEvents_l()
Glenn Kastenf7773312013-08-13 16:00:42 -0700727{
Eric Laurent10351942014-05-08 18:49:52 -0700728 bool configChanged = false;
729
Eric Laurent81784c32012-11-19 14:55:58 -0800730 while (!mConfigEvents.isEmpty()) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700731 ALOGV("processConfigEvents_l() remaining events %zu", mConfigEvents.size());
Eric Laurent10351942014-05-08 18:49:52 -0700732 sp<ConfigEvent> event = mConfigEvents[0];
Eric Laurent81784c32012-11-19 14:55:58 -0800733 mConfigEvents.removeAt(0);
Eric Laurent10351942014-05-08 18:49:52 -0700734 switch (event->mType) {
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700735 case CFG_EVENT_PRIO: {
Eric Laurent10351942014-05-08 18:49:52 -0700736 PrioConfigEventData *data = (PrioConfigEventData *)event->mData.get();
737 // FIXME Need to understand why this has to be done asynchronously
Mikhail Naganov83f04272017-02-07 10:45:09 -0800738 int err = requestPriority(data->mPid, data->mTid, data->mPrio, data->mForApp,
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700739 true /*asynchronous*/);
740 if (err != 0) {
741 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Eric Laurent10351942014-05-08 18:49:52 -0700742 data->mPrio, data->mPid, data->mTid, err);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700743 }
744 } break;
745 case CFG_EVENT_IO: {
Eric Laurent10351942014-05-08 18:49:52 -0700746 IoConfigEventData *data = (IoConfigEventData *)event->mData.get();
Eric Laurent09f1ed22019-04-24 17:45:17 -0700747 ioConfigChanged(data->mEvent, data->mPid, data->mPortId);
Eric Laurent10351942014-05-08 18:49:52 -0700748 } break;
749 case CFG_EVENT_SET_PARAMETER: {
750 SetParameterConfigEventData *data = (SetParameterConfigEventData *)event->mData.get();
751 if (checkForNewParameter_l(data->mKeyValuePairs, event->mStatus)) {
752 configChanged = true;
Andy Hung293558a2017-03-21 12:19:20 -0700753 mLocalLog.log("CFG_EVENT_SET_PARAMETER: (%s) configuration changed",
754 data->mKeyValuePairs.string());
Glenn Kastend5418eb2013-08-14 13:11:06 -0700755 }
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700756 } break;
Eric Laurent1c333e22014-05-20 10:48:17 -0700757 case CFG_EVENT_CREATE_AUDIO_PATCH: {
jiabinc52b1ff2019-10-31 17:20:42 -0700758 const DeviceTypeSet oldDevices = getDeviceTypes();
Eric Laurent1c333e22014-05-20 10:48:17 -0700759 CreateAudioPatchConfigEventData *data =
760 (CreateAudioPatchConfigEventData *)event->mData.get();
761 event->mStatus = createAudioPatch_l(&data->mPatch, &data->mHandle);
jiabinc52b1ff2019-10-31 17:20:42 -0700762 const DeviceTypeSet newDevices = getDeviceTypes();
763 mLocalLog.log("CFG_EVENT_CREATE_AUDIO_PATCH: old device %s (%s) new device %s (%s)",
764 dumpDeviceTypes(oldDevices).c_str(), toString(oldDevices).c_str(),
765 dumpDeviceTypes(newDevices).c_str(), toString(newDevices).c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -0700766 } break;
767 case CFG_EVENT_RELEASE_AUDIO_PATCH: {
jiabinc52b1ff2019-10-31 17:20:42 -0700768 const DeviceTypeSet oldDevices = getDeviceTypes();
Eric Laurent1c333e22014-05-20 10:48:17 -0700769 ReleaseAudioPatchConfigEventData *data =
770 (ReleaseAudioPatchConfigEventData *)event->mData.get();
771 event->mStatus = releaseAudioPatch_l(data->mHandle);
jiabinc52b1ff2019-10-31 17:20:42 -0700772 const DeviceTypeSet newDevices = getDeviceTypes();
773 mLocalLog.log("CFG_EVENT_RELEASE_AUDIO_PATCH: old device %s (%s) new device %s (%s)",
774 dumpDeviceTypes(oldDevices).c_str(), toString(oldDevices).c_str(),
775 dumpDeviceTypes(newDevices).c_str(), toString(newDevices).c_str());
776 } break;
777 case CFG_EVENT_UPDATE_OUT_DEVICE: {
778 UpdateOutDevicesConfigEventData *data =
779 (UpdateOutDevicesConfigEventData *)event->mData.get();
780 updateOutDevices(data->mOutDevices);
Eric Laurent1c333e22014-05-20 10:48:17 -0700781 } break;
Eric Laurentec376dc2021-04-08 20:41:22 +0200782 case CFG_EVENT_RESIZE_BUFFER: {
783 ResizeBufferConfigEventData *data =
784 (ResizeBufferConfigEventData *)event->mData.get();
785 resizeInputBuffer_l(data->mMaxSharedAudioHistoryMs);
786 } break;
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700787 default:
Eric Laurent10351942014-05-08 18:49:52 -0700788 ALOG_ASSERT(false, "processConfigEvents_l() unknown event type %d", event->mType);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700789 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800790 }
Eric Laurent10351942014-05-08 18:49:52 -0700791 {
792 Mutex::Autolock _l(event->mLock);
793 if (event->mWaitStatus) {
794 event->mWaitStatus = false;
795 event->mCond.signal();
796 }
797 }
798 ALOGV_IF(mConfigEvents.isEmpty(), "processConfigEvents_l() DONE thread %p", this);
799 }
800
801 if (configChanged) {
802 cacheParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800803 }
Eric Laurent81784c32012-11-19 14:55:58 -0800804}
805
Marco Nelissenb2208842014-02-07 14:00:50 -0800806String8 channelMaskToString(audio_channel_mask_t mask, bool output) {
807 String8 s;
Glenn Kastene1635ec2015-06-08 15:46:49 -0700808 const audio_channel_representation_t representation =
809 audio_channel_mask_get_representation(mask);
Andy Hungf98ec8d2015-05-19 12:53:24 -0700810
811 switch (representation) {
jiabin245cdd92018-12-07 17:55:15 -0800812 // Travel all single bit channel mask to convert channel mask to string.
Andy Hungf98ec8d2015-05-19 12:53:24 -0700813 case AUDIO_CHANNEL_REPRESENTATION_POSITION: {
814 if (output) {
815 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT) s.append("front-left, ");
816 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT) s.append("front-right, ");
817 if (mask & AUDIO_CHANNEL_OUT_FRONT_CENTER) s.append("front-center, ");
Andy Hungfba71252021-05-07 11:58:32 -0700818 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY) s.append("low-frequency, ");
Andy Hungf98ec8d2015-05-19 12:53:24 -0700819 if (mask & AUDIO_CHANNEL_OUT_BACK_LEFT) s.append("back-left, ");
820 if (mask & AUDIO_CHANNEL_OUT_BACK_RIGHT) s.append("back-right, ");
821 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT_OF_CENTER) s.append("front-left-of-center, ");
822 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT_OF_CENTER) s.append("front-right-of-center, ");
823 if (mask & AUDIO_CHANNEL_OUT_BACK_CENTER) s.append("back-center, ");
824 if (mask & AUDIO_CHANNEL_OUT_SIDE_LEFT) s.append("side-left, ");
825 if (mask & AUDIO_CHANNEL_OUT_SIDE_RIGHT) s.append("side-right, ");
826 if (mask & AUDIO_CHANNEL_OUT_TOP_CENTER) s.append("top-center ,");
827 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_LEFT) s.append("top-front-left, ");
828 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_CENTER) s.append("top-front-center, ");
829 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_RIGHT) s.append("top-front-right, ");
830 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_LEFT) s.append("top-back-left, ");
Andy Hungae81b4c2021-05-07 08:54:28 -0700831 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_CENTER) s.append("top-back-center, ");
832 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_RIGHT) s.append("top-back-right, ");
833 if (mask & AUDIO_CHANNEL_OUT_TOP_SIDE_LEFT) s.append("top-side-left, ");
834 if (mask & AUDIO_CHANNEL_OUT_TOP_SIDE_RIGHT) s.append("top-side-right, ");
835 if (mask & AUDIO_CHANNEL_OUT_BOTTOM_FRONT_LEFT) s.append("bottom-front-left, ");
836 if (mask & AUDIO_CHANNEL_OUT_BOTTOM_FRONT_CENTER) s.append("bottom-front-center, ");
837 if (mask & AUDIO_CHANNEL_OUT_BOTTOM_FRONT_RIGHT) s.append("bottom-front-right, ");
Andy Hungfba71252021-05-07 11:58:32 -0700838 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY_2) s.append("low-frequency-2, ");
Andy Hungae81b4c2021-05-07 08:54:28 -0700839 if (mask & AUDIO_CHANNEL_OUT_HAPTIC_B) s.append("haptic-B, ");
840 if (mask & AUDIO_CHANNEL_OUT_HAPTIC_A) s.append("haptic-A, ");
Andy Hungf98ec8d2015-05-19 12:53:24 -0700841 if (mask & ~AUDIO_CHANNEL_OUT_ALL) s.append("unknown, ");
842 } else {
843 if (mask & AUDIO_CHANNEL_IN_LEFT) s.append("left, ");
844 if (mask & AUDIO_CHANNEL_IN_RIGHT) s.append("right, ");
845 if (mask & AUDIO_CHANNEL_IN_FRONT) s.append("front, ");
846 if (mask & AUDIO_CHANNEL_IN_BACK) s.append("back, ");
847 if (mask & AUDIO_CHANNEL_IN_LEFT_PROCESSED) s.append("left-processed, ");
848 if (mask & AUDIO_CHANNEL_IN_RIGHT_PROCESSED) s.append("right-processed, ");
849 if (mask & AUDIO_CHANNEL_IN_FRONT_PROCESSED) s.append("front-processed, ");
850 if (mask & AUDIO_CHANNEL_IN_BACK_PROCESSED) s.append("back-processed, ");
851 if (mask & AUDIO_CHANNEL_IN_PRESSURE) s.append("pressure, ");
852 if (mask & AUDIO_CHANNEL_IN_X_AXIS) s.append("X, ");
853 if (mask & AUDIO_CHANNEL_IN_Y_AXIS) s.append("Y, ");
854 if (mask & AUDIO_CHANNEL_IN_Z_AXIS) s.append("Z, ");
Mikhail Naganovc9948492018-05-10 17:25:28 -0700855 if (mask & AUDIO_CHANNEL_IN_BACK_LEFT) s.append("back-left, ");
856 if (mask & AUDIO_CHANNEL_IN_BACK_RIGHT) s.append("back-right, ");
857 if (mask & AUDIO_CHANNEL_IN_CENTER) s.append("center, ");
Andy Hungfba71252021-05-07 11:58:32 -0700858 if (mask & AUDIO_CHANNEL_IN_LOW_FREQUENCY) s.append("low-frequency, ");
Andy Hungae81b4c2021-05-07 08:54:28 -0700859 if (mask & AUDIO_CHANNEL_IN_TOP_LEFT) s.append("top-left, ");
860 if (mask & AUDIO_CHANNEL_IN_TOP_RIGHT) s.append("top-right, ");
Andy Hungf98ec8d2015-05-19 12:53:24 -0700861 if (mask & AUDIO_CHANNEL_IN_VOICE_UPLINK) s.append("voice-uplink, ");
862 if (mask & AUDIO_CHANNEL_IN_VOICE_DNLINK) s.append("voice-dnlink, ");
863 if (mask & ~AUDIO_CHANNEL_IN_ALL) s.append("unknown, ");
864 }
865 const int len = s.length();
866 if (len > 2) {
Glenn Kasten57c4e6f2016-03-18 14:54:07 -0700867 (void) s.lockBuffer(len); // needed?
Andy Hungf98ec8d2015-05-19 12:53:24 -0700868 s.unlockBuffer(len - 2); // remove trailing ", "
869 }
870 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -0800871 }
Andy Hungf98ec8d2015-05-19 12:53:24 -0700872 case AUDIO_CHANNEL_REPRESENTATION_INDEX:
873 s.appendFormat("index mask, bits:%#x", audio_channel_mask_get_bits(mask));
874 return s;
875 default:
876 s.appendFormat("unknown mask, representation:%d bits:%#x",
877 representation, audio_channel_mask_get_bits(mask));
878 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -0800879 }
Marco Nelissenb2208842014-02-07 14:00:50 -0800880}
881
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -0700882void AudioFlinger::ThreadBase::dump(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -0800883{
Glenn Kasten1bfe09a2017-02-21 13:05:56 -0800884 dprintf(fd, "\n%s thread %p, name %s, tid %d, type %d (%s):\n", isOutput() ? "Output" : "Input",
885 this, mThreadName, getTid(), type(), threadTypeToString(type()));
886
Eric Laurent81784c32012-11-19 14:55:58 -0800887 bool locked = AudioFlinger::dumpTryLock(mLock);
888 if (!locked) {
Glenn Kasten1bfe09a2017-02-21 13:05:56 -0800889 dprintf(fd, " Thread may be deadlocked\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800890 }
891
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -0700892 dumpBase_l(fd, args);
893 dumpInternals_l(fd, args);
894 dumpTracks_l(fd, args);
895 dumpEffectChains_l(fd, args);
896
897 if (locked) {
898 mLock.unlock();
899 }
900
901 dprintf(fd, " Local log:\n");
902 mLocalLog.dump(fd, " " /* prefix */, 40 /* lines */);
903}
904
905void AudioFlinger::ThreadBase::dumpBase_l(int fd, const Vector<String16>& args __unused)
906{
Elliott Hughes87cebad2014-05-22 10:14:43 -0700907 dprintf(fd, " I/O handle: %d\n", mId);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700908 dprintf(fd, " Standby: %s\n", mStandby ? "yes" : "no");
Glenn Kasten97b7b752014-09-28 13:04:24 -0700909 dprintf(fd, " Sample rate: %u Hz\n", mSampleRate);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700910 dprintf(fd, " HAL frame count: %zu\n", mFrameCount);
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700911 dprintf(fd, " HAL format: 0x%x (%s)\n", mHALFormat, formatToString(mHALFormat).c_str());
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700912 dprintf(fd, " HAL buffer size: %zu bytes\n", mBufferSize);
Glenn Kasten97b7b752014-09-28 13:04:24 -0700913 dprintf(fd, " Channel count: %u\n", mChannelCount);
914 dprintf(fd, " Channel mask: 0x%08x (%s)\n", mChannelMask,
Marco Nelissenb2208842014-02-07 14:00:50 -0800915 channelMaskToString(mChannelMask, mType != RECORD).string());
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700916 dprintf(fd, " Processing format: 0x%x (%s)\n", mFormat, formatToString(mFormat).c_str());
Glenn Kastenf87c2f52015-08-21 08:03:57 -0700917 dprintf(fd, " Processing frame size: %zu bytes\n", mFrameSize);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700918 dprintf(fd, " Pending config events:");
Marco Nelissenb2208842014-02-07 14:00:50 -0800919 size_t numConfig = mConfigEvents.size();
920 if (numConfig) {
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -0700921 const size_t SIZE = 256;
922 char buffer[SIZE];
Marco Nelissenb2208842014-02-07 14:00:50 -0800923 for (size_t i = 0; i < numConfig; i++) {
924 mConfigEvents[i]->dump(buffer, SIZE);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700925 dprintf(fd, "\n %s", buffer);
Marco Nelissenb2208842014-02-07 14:00:50 -0800926 }
Elliott Hughes87cebad2014-05-22 10:14:43 -0700927 dprintf(fd, "\n");
Marco Nelissenb2208842014-02-07 14:00:50 -0800928 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -0700929 dprintf(fd, " none\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800930 }
Andy Hung293558a2017-03-21 12:19:20 -0700931 // Note: output device may be used by capture threads for effects such as AEC.
jiabinc52b1ff2019-10-31 17:20:42 -0700932 dprintf(fd, " Output devices: %s (%s)\n",
933 dumpDeviceTypes(outDeviceTypes()).c_str(), toString(outDeviceTypes()).c_str());
934 dprintf(fd, " Input device: %#x (%s)\n",
935 inDeviceType(), toString(inDeviceType()).c_str());
Andy Hung9b181952019-02-25 14:53:36 -0800936 dprintf(fd, " Audio source: %d (%s)\n", mAudioSource, toString(mAudioSource).c_str());
Eric Laurent81784c32012-11-19 14:55:58 -0800937
Andy Hung2e2c0bb2018-06-11 19:13:11 -0700938 // Dump timestamp statistics for the Thread types that support it.
939 if (mType == RECORD
940 || mType == MIXER
941 || mType == DUPLICATING
Andy Hungf3234512018-07-03 14:51:47 -0700942 || mType == DIRECT
943 || mType == OFFLOAD) {
Andy Hung2e2c0bb2018-06-11 19:13:11 -0700944 dprintf(fd, " Timestamp stats: %s\n", mTimestampVerifier.toString().c_str());
Andy Hungc8fddf32018-08-08 18:32:37 -0700945 dprintf(fd, " Timestamp corrected: %s\n", isTimestampCorrectionEnabled() ? "yes" : "no");
Andy Hung2e2c0bb2018-06-11 19:13:11 -0700946 }
947
Andy Hung446f4df2019-02-21 12:26:41 -0800948 if (mLastIoBeginNs > 0) { // MMAP may not set this
949 dprintf(fd, " Last %s occurred (msecs): %lld\n",
950 isOutput() ? "write" : "read",
951 (long long) (systemTime() - mLastIoBeginNs) / NANOS_PER_MILLISECOND);
952 }
953
954 if (mProcessTimeMs.getN() > 0) {
955 dprintf(fd, " Process time ms stats: %s\n", mProcessTimeMs.toString().c_str());
956 }
957
958 if (mIoJitterMs.getN() > 0) {
959 dprintf(fd, " Hal %s jitter ms stats: %s\n",
960 isOutput() ? "write" : "read",
961 mIoJitterMs.toString().c_str());
962 }
963
Andy Hunge6c37112019-02-26 17:38:10 -0800964 if (mLatencyMs.getN() > 0) {
965 dprintf(fd, " Threadloop %s latency stats: %s\n",
966 isOutput() ? "write" : "read",
967 mLatencyMs.toString().c_str());
968 }
Eric Laurent81784c32012-11-19 14:55:58 -0800969}
970
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -0700971void AudioFlinger::ThreadBase::dumpEffectChains_l(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -0800972{
973 const size_t SIZE = 256;
974 char buffer[SIZE];
Eric Laurent81784c32012-11-19 14:55:58 -0800975
Marco Nelissenb2208842014-02-07 14:00:50 -0800976 size_t numEffectChains = mEffectChains.size();
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +0000977 snprintf(buffer, SIZE, " %zu Effect Chains\n", numEffectChains);
Eric Laurent81784c32012-11-19 14:55:58 -0800978 write(fd, buffer, strlen(buffer));
979
Marco Nelissenb2208842014-02-07 14:00:50 -0800980 for (size_t i = 0; i < numEffectChains; ++i) {
Eric Laurent81784c32012-11-19 14:55:58 -0800981 sp<EffectChain> chain = mEffectChains[i];
982 if (chain != 0) {
983 chain->dump(fd, args);
984 }
985 }
986}
987
Andy Hungdae27702016-10-31 14:01:16 -0700988void AudioFlinger::ThreadBase::acquireWakeLock()
Eric Laurent81784c32012-11-19 14:55:58 -0800989{
990 Mutex::Autolock _l(mLock);
Andy Hungdae27702016-10-31 14:01:16 -0700991 acquireWakeLock_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800992}
993
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100994String16 AudioFlinger::ThreadBase::getWakeLockTag()
995{
996 switch (mType) {
Glenn Kastenbcb14862015-03-05 17:11:21 -0800997 case MIXER:
998 return String16("AudioMix");
999 case DIRECT:
1000 return String16("AudioDirectOut");
1001 case DUPLICATING:
1002 return String16("AudioDup");
1003 case RECORD:
1004 return String16("AudioIn");
1005 case OFFLOAD:
1006 return String16("AudioOffload");
Andy Hungea840382020-05-05 21:50:17 -07001007 case MMAP_PLAYBACK:
1008 return String16("MmapPlayback");
1009 case MMAP_CAPTURE:
1010 return String16("MmapCapture");
Glenn Kastenbcb14862015-03-05 17:11:21 -08001011 default:
1012 ALOG_ASSERT(false);
1013 return String16("AudioUnknown");
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001014 }
1015}
1016
Andy Hungdae27702016-10-31 14:01:16 -07001017void AudioFlinger::ThreadBase::acquireWakeLock_l()
Eric Laurent81784c32012-11-19 14:55:58 -08001018{
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001019 getPowerManager_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001020 if (mPowerManager != 0) {
1021 sp<IBinder> binder = new BBinder();
Andy Hungdae27702016-10-31 14:01:16 -07001022 // Uses AID_AUDIOSERVER for wakelock. updateWakeLockUids_l() updates with client uids.
Chris Ye6597d732020-02-28 22:38:25 -08001023 binder::Status status = mPowerManager->acquireWakeLockAsync(binder,
1024 POWERMANAGER_PARTIAL_WAKE_LOCK,
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001025 getWakeLockTag(),
Marco Nelissendcb346b2015-09-09 10:47:29 -07001026 String16("audioserver"),
Chris Ye6597d732020-02-28 22:38:25 -08001027 {} /* workSource */,
1028 {} /* historyTag */);
1029 if (status.isOk()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001030 mWakeLockToken = binder;
1031 }
Chris Ye6597d732020-02-28 22:38:25 -08001032 ALOGV("acquireWakeLock_l() %s status %d", mThreadName, status.exceptionCode());
Eric Laurent81784c32012-11-19 14:55:58 -08001033 }
Wei Jia3f273d12015-11-24 09:06:49 -08001034
Andy Hung3f0c9022016-01-15 17:49:46 -08001035 gBoottime.acquire(mWakeLockToken);
Andy Hung818e7a32016-02-16 18:08:07 -08001036 mTimestamp.mTimebaseOffset[ExtendedTimestamp::TIMEBASE_BOOTTIME] =
1037 gBoottime.getBoottimeOffset();
Eric Laurent81784c32012-11-19 14:55:58 -08001038}
1039
1040void AudioFlinger::ThreadBase::releaseWakeLock()
1041{
1042 Mutex::Autolock _l(mLock);
1043 releaseWakeLock_l();
1044}
1045
1046void AudioFlinger::ThreadBase::releaseWakeLock_l()
1047{
Andy Hung3f0c9022016-01-15 17:49:46 -08001048 gBoottime.release(mWakeLockToken);
Eric Laurent81784c32012-11-19 14:55:58 -08001049 if (mWakeLockToken != 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -08001050 ALOGV("releaseWakeLock_l() %s", mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08001051 if (mPowerManager != 0) {
Chris Ye6597d732020-02-28 22:38:25 -08001052 mPowerManager->releaseWakeLockAsync(mWakeLockToken, 0);
Eric Laurent81784c32012-11-19 14:55:58 -08001053 }
1054 mWakeLockToken.clear();
1055 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001056}
1057
1058void AudioFlinger::ThreadBase::getPowerManager_l() {
Eric Laurent72e3f392015-05-20 14:43:50 -07001059 if (mSystemReady && mPowerManager == 0) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001060 // use checkService() to avoid blocking if power service is not up yet
1061 sp<IBinder> binder =
1062 defaultServiceManager()->checkService(String16("power"));
1063 if (binder == 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -08001064 ALOGW("Thread %s cannot connect to the power manager service", mThreadName);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001065 } else {
Chris Ye6597d732020-02-28 22:38:25 -08001066 mPowerManager = interface_cast<os::IPowerManager>(binder);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001067 binder->linkToDeath(mDeathRecipient);
1068 }
1069 }
1070}
1071
Andy Hungd01b0f12016-11-07 16:10:30 -08001072void AudioFlinger::ThreadBase::updateWakeLockUids_l(const SortedVector<uid_t> &uids) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001073 getPowerManager_l();
Andy Hungdae27702016-10-31 14:01:16 -07001074
1075#if !LOG_NDEBUG
1076 std::stringstream s;
Andy Hungd01b0f12016-11-07 16:10:30 -08001077 for (uid_t uid : uids) {
Andy Hungdae27702016-10-31 14:01:16 -07001078 s << uid << " ";
1079 }
1080 ALOGD("updateWakeLockUids_l %s uids:%s", mThreadName, s.str().c_str());
1081#endif
1082
Andy Hung438e7572015-12-14 15:51:17 -08001083 if (mWakeLockToken == NULL) { // token may be NULL if AudioFlinger::systemReady() not called.
1084 if (mSystemReady) {
1085 ALOGE("no wake lock to update, but system ready!");
1086 } else {
1087 ALOGW("no wake lock to update, system not ready yet");
1088 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001089 return;
1090 }
1091 if (mPowerManager != 0) {
Andy Hung1f12a8a2016-11-07 16:10:30 -08001092 std::vector<int> uidsAsInt(uids.begin(), uids.end()); // powermanager expects uids as ints
Chris Ye6597d732020-02-28 22:38:25 -08001093 binder::Status status = mPowerManager->updateWakeLockUidsAsync(
1094 mWakeLockToken, uidsAsInt);
1095 ALOGV("updateWakeLockUids_l() %s status %d", mThreadName, status.exceptionCode());
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001096 }
1097}
1098
Eric Laurent81784c32012-11-19 14:55:58 -08001099void AudioFlinger::ThreadBase::clearPowerManager()
1100{
1101 Mutex::Autolock _l(mLock);
1102 releaseWakeLock_l();
1103 mPowerManager.clear();
1104}
1105
jiabinc52b1ff2019-10-31 17:20:42 -07001106void AudioFlinger::ThreadBase::updateOutDevices(
1107 const DeviceDescriptorBaseVector& outDevices __unused)
1108{
1109 ALOGE("%s should only be called in RecordThread", __func__);
1110}
1111
Eric Laurentec376dc2021-04-08 20:41:22 +02001112void AudioFlinger::ThreadBase::resizeInputBuffer_l(int32_t maxSharedAudioHistoryMs __unused)
1113{
1114 ALOGE("%s should only be called in RecordThread", __func__);
1115}
1116
Glenn Kasten0f11b512014-01-31 16:18:54 -08001117void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001118{
1119 sp<ThreadBase> thread = mThread.promote();
1120 if (thread != 0) {
1121 thread->clearPowerManager();
1122 }
1123 ALOGW("power manager service died !!!");
1124}
1125
Eric Laurent81784c32012-11-19 14:55:58 -08001126void AudioFlinger::ThreadBase::setEffectSuspended_l(
Glenn Kastend848eb42016-03-08 13:42:11 -08001127 const effect_uuid_t *type, bool suspend, audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001128{
1129 sp<EffectChain> chain = getEffectChain_l(sessionId);
1130 if (chain != 0) {
1131 if (type != NULL) {
1132 chain->setEffectSuspended_l(type, suspend);
1133 } else {
1134 chain->setEffectSuspendedAll_l(suspend);
1135 }
1136 }
1137
1138 updateSuspendedSessions_l(type, suspend, sessionId);
1139}
1140
1141void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1142{
1143 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
1144 if (index < 0) {
1145 return;
1146 }
1147
1148 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
1149 mSuspendedSessions.valueAt(index);
1150
1151 for (size_t i = 0; i < sessionEffects.size(); i++) {
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07001152 const sp<SuspendedSessionDesc>& desc = sessionEffects.valueAt(i);
Eric Laurent81784c32012-11-19 14:55:58 -08001153 for (int j = 0; j < desc->mRefCount; j++) {
1154 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1155 chain->setEffectSuspendedAll_l(true);
1156 } else {
1157 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
1158 desc->mType.timeLow);
1159 chain->setEffectSuspended_l(&desc->mType, true);
1160 }
1161 }
1162 }
1163}
1164
1165void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1166 bool suspend,
Glenn Kastend848eb42016-03-08 13:42:11 -08001167 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001168{
1169 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
1170
1171 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1172
1173 if (suspend) {
1174 if (index >= 0) {
1175 sessionEffects = mSuspendedSessions.valueAt(index);
1176 } else {
1177 mSuspendedSessions.add(sessionId, sessionEffects);
1178 }
1179 } else {
1180 if (index < 0) {
1181 return;
1182 }
1183 sessionEffects = mSuspendedSessions.valueAt(index);
1184 }
1185
1186
1187 int key = EffectChain::kKeyForSuspendAll;
1188 if (type != NULL) {
1189 key = type->timeLow;
1190 }
1191 index = sessionEffects.indexOfKey(key);
1192
1193 sp<SuspendedSessionDesc> desc;
1194 if (suspend) {
1195 if (index >= 0) {
1196 desc = sessionEffects.valueAt(index);
1197 } else {
1198 desc = new SuspendedSessionDesc();
1199 if (type != NULL) {
1200 desc->mType = *type;
1201 }
1202 sessionEffects.add(key, desc);
1203 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
1204 }
1205 desc->mRefCount++;
1206 } else {
1207 if (index < 0) {
1208 return;
1209 }
1210 desc = sessionEffects.valueAt(index);
1211 if (--desc->mRefCount == 0) {
1212 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
1213 sessionEffects.removeItemsAt(index);
1214 if (sessionEffects.isEmpty()) {
1215 ALOGV("updateSuspendedSessions_l() restore removing session %d",
1216 sessionId);
1217 mSuspendedSessions.removeItem(sessionId);
1218 }
1219 }
1220 }
1221 if (!sessionEffects.isEmpty()) {
1222 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1223 }
1224}
1225
Eric Laurent6b446ce2019-12-13 10:56:31 -08001226void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(bool enabled,
1227 audio_session_t sessionId,
1228 bool threadLocked) {
1229 if (!threadLocked) {
1230 mLock.lock();
1231 }
Eric Laurent81784c32012-11-19 14:55:58 -08001232
Eric Laurent81784c32012-11-19 14:55:58 -08001233 if (mType != RECORD) {
1234 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1235 // another session. This gives the priority to well behaved effect control panels
1236 // and applications not using global effects.
1237 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
1238 // global effects
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001239 if (!audio_is_global_session(sessionId)) {
Eric Laurent81784c32012-11-19 14:55:58 -08001240 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1241 }
1242 }
1243
Eric Laurent6b446ce2019-12-13 10:56:31 -08001244 if (!threadLocked) {
1245 mLock.unlock();
Eric Laurent81784c32012-11-19 14:55:58 -08001246 }
1247}
1248
Eric Laurent4c415062016-06-17 16:14:16 -07001249// checkEffectCompatibility_l() must be called with ThreadBase::mLock held
1250status_t AudioFlinger::RecordThread::checkEffectCompatibility_l(
1251 const effect_descriptor_t *desc, audio_session_t sessionId)
1252{
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001253 // No global output effect sessions on record threads
1254 if (sessionId == AUDIO_SESSION_OUTPUT_MIX
1255 || sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Eric Laurent4c415062016-06-17 16:14:16 -07001256 ALOGW("checkEffectCompatibility_l(): global effect %s on record thread %s",
1257 desc->name, mThreadName);
1258 return BAD_VALUE;
1259 }
1260 // only pre processing effects on record thread
1261 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC) {
1262 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on record thread %s",
1263 desc->name, mThreadName);
1264 return BAD_VALUE;
1265 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001266
1267 // always allow effects without processing load or latency
1268 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1269 return NO_ERROR;
1270 }
1271
Eric Laurent4c415062016-06-17 16:14:16 -07001272 audio_input_flags_t flags = mInput->flags;
1273 if (hasFastCapture() || (flags & AUDIO_INPUT_FLAG_FAST)) {
1274 if (flags & AUDIO_INPUT_FLAG_RAW) {
1275 ALOGW("checkEffectCompatibility_l(): effect %s on record thread %s in raw mode",
1276 desc->name, mThreadName);
1277 return BAD_VALUE;
1278 }
1279 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1280 ALOGW("checkEffectCompatibility_l(): non HW effect %s on record thread %s in fast mode",
1281 desc->name, mThreadName);
1282 return BAD_VALUE;
1283 }
1284 }
jiabineb3bda02020-06-30 14:07:03 -07001285
1286 if (EffectModule::isHapticGenerator(&desc->type)) {
1287 ALOGE("%s(): HapticGenerator is not supported in RecordThread", __func__);
1288 return BAD_VALUE;
1289 }
Eric Laurent4c415062016-06-17 16:14:16 -07001290 return NO_ERROR;
1291}
1292
1293// checkEffectCompatibility_l() must be called with ThreadBase::mLock held
1294status_t AudioFlinger::PlaybackThread::checkEffectCompatibility_l(
1295 const effect_descriptor_t *desc, audio_session_t sessionId)
1296{
1297 // no preprocessing on playback threads
1298 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC) {
1299 ALOGW("checkEffectCompatibility_l(): pre processing effect %s created on playback"
1300 " thread %s", desc->name, mThreadName);
1301 return BAD_VALUE;
1302 }
1303
Eric Laurent3e4de772017-07-16 16:55:08 -07001304 // always allow effects without processing load or latency
1305 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1306 return NO_ERROR;
1307 }
1308
jiabineb3bda02020-06-30 14:07:03 -07001309 if (EffectModule::isHapticGenerator(&desc->type) && mHapticChannelCount == 0) {
1310 ALOGW("%s: thread doesn't support haptic playback while the effect is HapticGenerator",
1311 __func__);
1312 return BAD_VALUE;
1313 }
1314
Eric Laurent4c415062016-06-17 16:14:16 -07001315 switch (mType) {
1316 case MIXER: {
Andy Hung9aad48c2017-11-29 10:29:19 -08001317#ifndef MULTICHANNEL_EFFECT_CHAIN
Eric Laurent4c415062016-06-17 16:14:16 -07001318 // Reject any effect on mixer multichannel sinks.
1319 // TODO: fix both format and multichannel issues with effects.
1320 if (mChannelCount != FCC_2) {
1321 ALOGW("checkEffectCompatibility_l(): effect %s for multichannel(%d) on MIXER"
1322 " thread %s", desc->name, mChannelCount, mThreadName);
1323 return BAD_VALUE;
1324 }
Andy Hung9aad48c2017-11-29 10:29:19 -08001325#endif
Eric Laurent4c415062016-06-17 16:14:16 -07001326 audio_output_flags_t flags = mOutput->flags;
1327 if (hasFastMixer() || (flags & AUDIO_OUTPUT_FLAG_FAST)) {
1328 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1329 // global effects are applied only to non fast tracks if they are SW
1330 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1331 break;
1332 }
1333 } else if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1334 // only post processing on output stage session
1335 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
1336 ALOGW("checkEffectCompatibility_l(): non post processing effect %s not allowed"
1337 " on output stage session", desc->name);
1338 return BAD_VALUE;
1339 }
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001340 } else if (sessionId == AUDIO_SESSION_DEVICE) {
1341 // only post processing on output stage session
1342 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
1343 ALOGW("checkEffectCompatibility_l(): non post processing effect %s not allowed"
1344 " on device session", desc->name);
1345 return BAD_VALUE;
1346 }
Eric Laurent4c415062016-06-17 16:14:16 -07001347 } else {
1348 // no restriction on effects applied on non fast tracks
1349 if ((hasAudioSession_l(sessionId) & ThreadBase::FAST_SESSION) == 0) {
1350 break;
1351 }
1352 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001353
Eric Laurent4c415062016-06-17 16:14:16 -07001354 if (flags & AUDIO_OUTPUT_FLAG_RAW) {
1355 ALOGW("checkEffectCompatibility_l(): effect %s on playback thread in raw mode",
1356 desc->name);
1357 return BAD_VALUE;
1358 }
1359 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1360 ALOGW("checkEffectCompatibility_l(): non HW effect %s on playback thread"
1361 " in fast mode", desc->name);
1362 return BAD_VALUE;
1363 }
1364 }
1365 } break;
1366 case OFFLOAD:
Jean-Michel Trivi773ee952016-07-11 16:53:18 -07001367 // nothing actionable on offload threads, if the effect:
1368 // - is offloadable: the effect can be created
1369 // - is NOT offloadable: the effect should still be created, but EffectHandle::enable()
1370 // will take care of invalidating the tracks of the thread
Eric Laurent4c415062016-06-17 16:14:16 -07001371 break;
1372 case DIRECT:
1373 // Reject any effect on Direct output threads for now, since the format of
1374 // mSinkBuffer is not guaranteed to be compatible with effect processing (PCM 16 stereo).
1375 ALOGW("checkEffectCompatibility_l(): effect %s on DIRECT output thread %s",
1376 desc->name, mThreadName);
1377 return BAD_VALUE;
1378 case DUPLICATING:
Andy Hung9aad48c2017-11-29 10:29:19 -08001379#ifndef MULTICHANNEL_EFFECT_CHAIN
Eric Laurent4c415062016-06-17 16:14:16 -07001380 // Reject any effect on mixer multichannel sinks.
1381 // TODO: fix both format and multichannel issues with effects.
1382 if (mChannelCount != FCC_2) {
1383 ALOGW("checkEffectCompatibility_l(): effect %s for multichannel(%d)"
1384 " on DUPLICATING thread %s", desc->name, mChannelCount, mThreadName);
1385 return BAD_VALUE;
1386 }
Andy Hung9aad48c2017-11-29 10:29:19 -08001387#endif
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001388 if (audio_is_global_session(sessionId)) {
Eric Laurent4c415062016-06-17 16:14:16 -07001389 ALOGW("checkEffectCompatibility_l(): global effect %s on DUPLICATING"
1390 " thread %s", desc->name, mThreadName);
1391 return BAD_VALUE;
1392 }
1393 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
1394 ALOGW("checkEffectCompatibility_l(): post processing effect %s on"
1395 " DUPLICATING thread %s", desc->name, mThreadName);
1396 return BAD_VALUE;
1397 }
1398 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) != 0) {
1399 ALOGW("checkEffectCompatibility_l(): HW tunneled effect %s on"
1400 " DUPLICATING thread %s", desc->name, mThreadName);
1401 return BAD_VALUE;
1402 }
1403 break;
1404 default:
1405 LOG_ALWAYS_FATAL("checkEffectCompatibility_l(): wrong thread type %d", mType);
1406 }
1407
1408 return NO_ERROR;
1409}
1410
Eric Laurent81784c32012-11-19 14:55:58 -08001411// ThreadBase::createEffect_l() must be called with AudioFlinger::mLock held
1412sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
1413 const sp<AudioFlinger::Client>& client,
1414 const sp<IEffectClient>& effectClient,
1415 int32_t priority,
Glenn Kastend848eb42016-03-08 13:42:11 -08001416 audio_session_t sessionId,
Eric Laurent81784c32012-11-19 14:55:58 -08001417 effect_descriptor_t *desc,
1418 int *enabled,
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001419 status_t *status,
Eric Laurent2fe0acd2020-03-13 14:30:46 -07001420 bool pinned,
1421 bool probe)
Eric Laurent81784c32012-11-19 14:55:58 -08001422{
1423 sp<EffectModule> effect;
1424 sp<EffectHandle> handle;
1425 status_t lStatus;
1426 sp<EffectChain> chain;
1427 bool chainCreated = false;
1428 bool effectCreated = false;
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001429 audio_unique_id_t effectId = AUDIO_UNIQUE_ID_USE_UNSPECIFIED;
Eric Laurent81784c32012-11-19 14:55:58 -08001430
1431 lStatus = initCheck();
1432 if (lStatus != NO_ERROR) {
1433 ALOGW("createEffect_l() Audio driver not initialized.");
1434 goto Exit;
1435 }
1436
Eric Laurent81784c32012-11-19 14:55:58 -08001437 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
1438
1439 { // scope for mLock
1440 Mutex::Autolock _l(mLock);
1441
Eric Laurent4c415062016-06-17 16:14:16 -07001442 lStatus = checkEffectCompatibility_l(desc, sessionId);
Eric Laurent2fe0acd2020-03-13 14:30:46 -07001443 if (probe || lStatus != NO_ERROR) {
Eric Laurent4c415062016-06-17 16:14:16 -07001444 goto Exit;
1445 }
1446
Eric Laurent81784c32012-11-19 14:55:58 -08001447 // check for existing effect chain with the requested audio session
1448 chain = getEffectChain_l(sessionId);
1449 if (chain == 0) {
1450 // create a new chain for this session
1451 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
1452 chain = new EffectChain(this, sessionId);
1453 addEffectChain_l(chain);
1454 chain->setStrategy(getStrategyForSession_l(sessionId));
1455 chainCreated = true;
1456 } else {
1457 effect = chain->getEffectFromDesc_l(desc);
1458 }
1459
1460 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
1461
1462 if (effect == 0) {
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001463 effectId = mAudioFlinger->nextUniqueId(AUDIO_UNIQUE_ID_USE_EFFECT);
Eric Laurent81784c32012-11-19 14:55:58 -08001464 // create a new effect module if none present in the chain
Eric Laurent6b446ce2019-12-13 10:56:31 -08001465 lStatus = chain->createEffect_l(effect, desc, effectId, sessionId, pinned);
Eric Laurent81784c32012-11-19 14:55:58 -08001466 if (lStatus != NO_ERROR) {
1467 goto Exit;
1468 }
1469 effectCreated = true;
1470
jiabinc52b1ff2019-10-31 17:20:42 -07001471 // FIXME: use vector of device and address when effect interface is ready.
jiabin8f278ee2019-11-11 12:16:27 -08001472 effect->setDevices(outDeviceTypeAddrs());
1473 effect->setInputDevice(inDeviceTypeAddr());
Eric Laurent81784c32012-11-19 14:55:58 -08001474 effect->setMode(mAudioFlinger->getMode());
1475 effect->setAudioSource(mAudioSource);
1476 }
jiabin1319f5a2021-03-30 22:21:24 +00001477 if (effect->isHapticGenerator()) {
1478 // TODO(b/184194057): Use the vibrator information from the vibrator that will be used
1479 // for the HapticGenerator.
Lais Andradebc3f37a2021-07-02 00:13:19 +01001480 const std::optional<media::AudioVibratorInfo> defaultVibratorInfo =
1481 std::move(mAudioFlinger->getDefaultVibratorInfo_l());
1482 if (defaultVibratorInfo) {
jiabin1319f5a2021-03-30 22:21:24 +00001483 // Only set the vibrator info when it is a valid one.
Lais Andradebc3f37a2021-07-02 00:13:19 +01001484 effect->setVibratorInfo(*defaultVibratorInfo);
jiabin1319f5a2021-03-30 22:21:24 +00001485 }
1486 }
Eric Laurent81784c32012-11-19 14:55:58 -08001487 // create effect handle and connect it to effect module
1488 handle = new EffectHandle(effect, client, effectClient, priority);
Glenn Kastene75da402013-11-20 13:54:52 -08001489 lStatus = handle->initCheck();
1490 if (lStatus == OK) {
1491 lStatus = effect->addHandle(handle.get());
1492 }
Eric Laurent81784c32012-11-19 14:55:58 -08001493 if (enabled != NULL) {
1494 *enabled = (int)effect->isEnabled();
1495 }
1496 }
1497
1498Exit:
Eric Laurent2fe0acd2020-03-13 14:30:46 -07001499 if (!probe && lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurent81784c32012-11-19 14:55:58 -08001500 Mutex::Autolock _l(mLock);
1501 if (effectCreated) {
1502 chain->removeEffect_l(effect);
1503 }
Eric Laurent81784c32012-11-19 14:55:58 -08001504 if (chainCreated) {
1505 removeEffectChain_l(chain);
1506 }
haobo101735295ff7b0d2017-03-17 17:44:03 +08001507 // handle must be cleared by caller to avoid deadlock.
Eric Laurent81784c32012-11-19 14:55:58 -08001508 }
1509
Glenn Kasten9156ef32013-08-06 15:39:08 -07001510 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001511 return handle;
1512}
1513
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001514void AudioFlinger::ThreadBase::disconnectEffectHandle(EffectHandle *handle,
1515 bool unpinIfLast)
1516{
1517 bool remove = false;
1518 sp<EffectModule> effect;
1519 {
1520 Mutex::Autolock _l(mLock);
Eric Laurent41709552019-12-16 19:34:05 -08001521 sp<EffectBase> effectBase = handle->effect().promote();
1522 if (effectBase == nullptr) {
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001523 return;
1524 }
Eric Laurentb82e6b72019-11-22 17:25:04 -08001525 effect = effectBase->asEffectModule();
1526 if (effect == nullptr) {
1527 return;
1528 }
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001529 // restore suspended effects if the disconnected handle was enabled and the last one.
1530 remove = (effect->removeHandle(handle) == 0) && (!effect->isPinned() || unpinIfLast);
1531 if (remove) {
1532 removeEffect_l(effect, true);
1533 }
1534 }
1535 if (remove) {
1536 mAudioFlinger->updateOrphanEffectChains(effect);
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001537 if (handle->enabled()) {
Eric Laurent6b446ce2019-12-13 10:56:31 -08001538 effect->checkSuspendOnEffectEnabled(false, false /*threadLocked*/);
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001539 }
1540 }
1541}
1542
Eric Laurent6b446ce2019-12-13 10:56:31 -08001543void AudioFlinger::ThreadBase::onEffectEnable(const sp<EffectModule>& effect) {
Andy Hungea840382020-05-05 21:50:17 -07001544 if (isOffloadOrMmap()) {
Eric Laurent6b446ce2019-12-13 10:56:31 -08001545 Mutex::Autolock _l(mLock);
1546 broadcast_l();
1547 }
1548 if (!effect->isOffloadable()) {
1549 if (mType == ThreadBase::OFFLOAD) {
1550 PlaybackThread *t = (PlaybackThread *)this;
1551 t->invalidateTracks(AUDIO_STREAM_MUSIC);
1552 }
1553 if (effect->sessionId() == AUDIO_SESSION_OUTPUT_MIX) {
1554 mAudioFlinger->onNonOffloadableGlobalEffectEnable();
1555 }
1556 }
1557}
1558
1559void AudioFlinger::ThreadBase::onEffectDisable() {
Andy Hungea840382020-05-05 21:50:17 -07001560 if (isOffloadOrMmap()) {
Eric Laurent6b446ce2019-12-13 10:56:31 -08001561 Mutex::Autolock _l(mLock);
1562 broadcast_l();
1563 }
1564}
1565
Glenn Kastend848eb42016-03-08 13:42:11 -08001566sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(audio_session_t sessionId,
1567 int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08001568{
1569 Mutex::Autolock _l(mLock);
1570 return getEffect_l(sessionId, effectId);
1571}
1572
Glenn Kastend848eb42016-03-08 13:42:11 -08001573sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(audio_session_t sessionId,
1574 int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08001575{
1576 sp<EffectChain> chain = getEffectChain_l(sessionId);
1577 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
1578}
1579
Eric Laurent6c796322019-04-09 14:13:17 -07001580std::vector<int> AudioFlinger::ThreadBase::getEffectIds_l(audio_session_t sessionId)
1581{
1582 sp<EffectChain> chain = getEffectChain_l(sessionId);
1583 return chain != nullptr ? chain->getEffectIds() : std::vector<int>{};
1584}
1585
Eric Laurent81784c32012-11-19 14:55:58 -08001586// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
1587// PlaybackThread::mLock held
1588status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
1589{
1590 // check for existing effect chain with the requested audio session
Glenn Kastend848eb42016-03-08 13:42:11 -08001591 audio_session_t sessionId = effect->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08001592 sp<EffectChain> chain = getEffectChain_l(sessionId);
1593 bool chainCreated = false;
1594
Eric Laurent5baf2af2013-09-12 17:37:00 -07001595 ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(),
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001596 "addEffect_l() on offloaded thread %p: effect %s does not support offload flags %#x",
Eric Laurent5baf2af2013-09-12 17:37:00 -07001597 this, effect->desc().name, effect->desc().flags);
1598
Eric Laurent81784c32012-11-19 14:55:58 -08001599 if (chain == 0) {
1600 // create a new chain for this session
1601 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
1602 chain = new EffectChain(this, sessionId);
1603 addEffectChain_l(chain);
1604 chain->setStrategy(getStrategyForSession_l(sessionId));
1605 chainCreated = true;
1606 }
1607 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
1608
1609 if (chain->getEffectFromId_l(effect->id()) != 0) {
1610 ALOGW("addEffect_l() %p effect %s already present in chain %p",
1611 this, effect->desc().name, chain.get());
1612 return BAD_VALUE;
1613 }
1614
Eric Laurent5baf2af2013-09-12 17:37:00 -07001615 effect->setOffloaded(mType == OFFLOAD, mId);
1616
Eric Laurent81784c32012-11-19 14:55:58 -08001617 status_t status = chain->addEffect_l(effect);
1618 if (status != NO_ERROR) {
1619 if (chainCreated) {
1620 removeEffectChain_l(chain);
1621 }
1622 return status;
1623 }
1624
jiabin8f278ee2019-11-11 12:16:27 -08001625 effect->setDevices(outDeviceTypeAddrs());
1626 effect->setInputDevice(inDeviceTypeAddr());
Eric Laurent81784c32012-11-19 14:55:58 -08001627 effect->setMode(mAudioFlinger->getMode());
1628 effect->setAudioSource(mAudioSource);
Eric Laurentd8365c52017-07-16 15:27:05 -07001629
Eric Laurent81784c32012-11-19 14:55:58 -08001630 return NO_ERROR;
1631}
1632
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001633void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect, bool release) {
Eric Laurent81784c32012-11-19 14:55:58 -08001634
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001635 ALOGV("%s %p effect %p", __FUNCTION__, this, effect.get());
Eric Laurent81784c32012-11-19 14:55:58 -08001636 effect_descriptor_t desc = effect->desc();
1637 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
1638 detachAuxEffect_l(effect->id());
1639 }
1640
Andy Hungfda44002021-06-03 17:23:16 -07001641 sp<EffectChain> chain = effect->getCallback()->chain().promote();
Eric Laurent81784c32012-11-19 14:55:58 -08001642 if (chain != 0) {
1643 // remove effect chain if removing last effect
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001644 if (chain->removeEffect_l(effect, release) == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08001645 removeEffectChain_l(chain);
1646 }
1647 } else {
1648 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
1649 }
1650}
1651
1652void AudioFlinger::ThreadBase::lockEffectChains_l(
1653 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1654{
1655 effectChains = mEffectChains;
1656 for (size_t i = 0; i < mEffectChains.size(); i++) {
1657 mEffectChains[i]->lock();
1658 }
1659}
1660
1661void AudioFlinger::ThreadBase::unlockEffectChains(
1662 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1663{
1664 for (size_t i = 0; i < effectChains.size(); i++) {
1665 effectChains[i]->unlock();
1666 }
1667}
1668
Glenn Kastend848eb42016-03-08 13:42:11 -08001669sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001670{
1671 Mutex::Autolock _l(mLock);
1672 return getEffectChain_l(sessionId);
1673}
1674
Glenn Kastend848eb42016-03-08 13:42:11 -08001675sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(audio_session_t sessionId)
1676 const
Eric Laurent81784c32012-11-19 14:55:58 -08001677{
1678 size_t size = mEffectChains.size();
1679 for (size_t i = 0; i < size; i++) {
1680 if (mEffectChains[i]->sessionId() == sessionId) {
1681 return mEffectChains[i];
1682 }
1683 }
1684 return 0;
1685}
1686
1687void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
1688{
1689 Mutex::Autolock _l(mLock);
1690 size_t size = mEffectChains.size();
1691 for (size_t i = 0; i < size; i++) {
1692 mEffectChains[i]->setMode_l(mode);
1693 }
1694}
1695
Mikhail Naganovdc769682018-05-04 15:34:08 -07001696void AudioFlinger::ThreadBase::toAudioPortConfig(struct audio_port_config *config)
Eric Laurent83b88082014-06-20 18:31:16 -07001697{
1698 config->type = AUDIO_PORT_TYPE_MIX;
1699 config->ext.mix.handle = mId;
1700 config->sample_rate = mSampleRate;
1701 config->format = mFormat;
1702 config->channel_mask = mChannelMask;
1703 config->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
1704 AUDIO_PORT_CONFIG_FORMAT;
1705}
1706
Eric Laurent72e3f392015-05-20 14:43:50 -07001707void AudioFlinger::ThreadBase::systemReady()
1708{
1709 Mutex::Autolock _l(mLock);
1710 if (mSystemReady) {
1711 return;
1712 }
1713 mSystemReady = true;
1714
1715 for (size_t i = 0; i < mPendingConfigEvents.size(); i++) {
1716 sendConfigEvent_l(mPendingConfigEvents.editItemAt(i));
1717 }
1718 mPendingConfigEvents.clear();
1719}
1720
Andy Hungdae27702016-10-31 14:01:16 -07001721template <typename T>
1722ssize_t AudioFlinger::ThreadBase::ActiveTracks<T>::add(const sp<T> &track) {
1723 ssize_t index = mActiveTracks.indexOf(track);
1724 if (index >= 0) {
1725 ALOGW("ActiveTracks<T>::add track %p already there", track.get());
1726 return index;
1727 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001728 logTrack("add", track);
Andy Hungdae27702016-10-31 14:01:16 -07001729 mActiveTracksGeneration++;
1730 mLatestActiveTrack = track;
1731 ++mBatteryCounter[track->uid()].second;
Kevin Rocard069c2712018-03-29 19:09:14 -07001732 mHasChanged = true;
Andy Hungdae27702016-10-31 14:01:16 -07001733 return mActiveTracks.add(track);
1734}
1735
1736template <typename T>
1737ssize_t AudioFlinger::ThreadBase::ActiveTracks<T>::remove(const sp<T> &track) {
1738 ssize_t index = mActiveTracks.remove(track);
1739 if (index < 0) {
1740 ALOGW("ActiveTracks<T>::remove nonexistent track %p", track.get());
1741 return index;
1742 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001743 logTrack("remove", track);
Andy Hungdae27702016-10-31 14:01:16 -07001744 mActiveTracksGeneration++;
1745 --mBatteryCounter[track->uid()].second;
1746 // mLatestActiveTrack is not cleared even if is the same as track.
Kevin Rocard069c2712018-03-29 19:09:14 -07001747 mHasChanged = true;
Andy Hung8946a282018-04-19 20:04:56 -07001748#ifdef TEE_SINK
1749 track->dumpTee(-1 /* fd */, "_REMOVE");
1750#endif
Andy Hungc2b11cb2020-04-22 09:04:01 -07001751 track->logEndInterval(); // log to MediaMetrics
Andy Hungdae27702016-10-31 14:01:16 -07001752 return index;
1753}
1754
1755template <typename T>
1756void AudioFlinger::ThreadBase::ActiveTracks<T>::clear() {
1757 for (const sp<T> &track : mActiveTracks) {
1758 BatteryNotifier::getInstance().noteStopAudio(track->uid());
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001759 logTrack("clear", track);
Andy Hungdae27702016-10-31 14:01:16 -07001760 }
1761 mLastActiveTracksGeneration = mActiveTracksGeneration;
Kevin Rocard069c2712018-03-29 19:09:14 -07001762 if (!mActiveTracks.empty()) { mHasChanged = true; }
Andy Hungdae27702016-10-31 14:01:16 -07001763 mActiveTracks.clear();
1764 mLatestActiveTrack.clear();
1765 mBatteryCounter.clear();
1766}
1767
1768template <typename T>
1769void AudioFlinger::ThreadBase::ActiveTracks<T>::updatePowerState(
1770 sp<ThreadBase> thread, bool force) {
1771 // Updates ActiveTracks client uids to the thread wakelock.
1772 if (mActiveTracksGeneration != mLastActiveTracksGeneration || force) {
1773 thread->updateWakeLockUids_l(getWakeLockUids());
1774 mLastActiveTracksGeneration = mActiveTracksGeneration;
1775 }
1776
1777 // Updates BatteryNotifier uids
1778 for (auto it = mBatteryCounter.begin(); it != mBatteryCounter.end();) {
1779 const uid_t uid = it->first;
1780 ssize_t &previous = it->second.first;
1781 ssize_t &current = it->second.second;
1782 if (current > 0) {
1783 if (previous == 0) {
1784 BatteryNotifier::getInstance().noteStartAudio(uid);
1785 }
1786 previous = current;
1787 ++it;
1788 } else if (current == 0) {
1789 if (previous > 0) {
1790 BatteryNotifier::getInstance().noteStopAudio(uid);
1791 }
1792 it = mBatteryCounter.erase(it); // std::map<> is stable on iterator erase.
1793 } else /* (current < 0) */ {
1794 LOG_ALWAYS_FATAL("negative battery count %zd", current);
1795 }
1796 }
1797}
Eric Laurent83b88082014-06-20 18:31:16 -07001798
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001799template <typename T>
Kevin Rocard069c2712018-03-29 19:09:14 -07001800bool AudioFlinger::ThreadBase::ActiveTracks<T>::readAndClearHasChanged() {
Jasmine Chaeaa10e42021-05-11 10:11:14 +08001801 bool hasChanged = mHasChanged;
Kevin Rocard069c2712018-03-29 19:09:14 -07001802 mHasChanged = false;
Jasmine Chaeaa10e42021-05-11 10:11:14 +08001803
1804 for (const sp<T> &track : mActiveTracks) {
1805 // Do not short-circuit as all hasChanged states must be reset
1806 // as all the metadata are going to be sent
1807 hasChanged |= track->readAndClearHasChanged();
1808 }
Kevin Rocard069c2712018-03-29 19:09:14 -07001809 return hasChanged;
1810}
1811
1812template <typename T>
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001813void AudioFlinger::ThreadBase::ActiveTracks<T>::logTrack(
1814 const char *funcName, const sp<T> &track) const {
1815 if (mLocalLog != nullptr) {
1816 String8 result;
1817 track->appendDump(result, false /* active */);
1818 mLocalLog->log("AT::%-10s(%p) %s", funcName, track.get(), result.string());
1819 }
1820}
1821
Eric Laurent6acd1d42017-01-04 14:23:29 -08001822void AudioFlinger::ThreadBase::broadcast_l()
1823{
1824 // Thread could be blocked waiting for async
1825 // so signal it to handle state changes immediately
1826 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
1827 // be lost so we also flag to prevent it blocking on mWaitWorkCV
1828 mSignalPending = true;
1829 mWaitWorkCV.broadcast();
1830}
1831
Andy Hungd0979812019-02-21 15:51:44 -08001832// Call only from threadLoop() or when it is idle.
1833// Do not call from high performance code as this may do binder rpc to the MediaMetrics service.
1834void AudioFlinger::ThreadBase::sendStatistics(bool force)
1835{
1836 // Do not log if we have no stats.
1837 // We choose the timestamp verifier because it is the most likely item to be present.
1838 const int64_t nstats = mTimestampVerifier.getN() - mLastRecordedTimestampVerifierN;
1839 if (nstats == 0) {
1840 return;
1841 }
1842
1843 // Don't log more frequently than once per 12 hours.
1844 // We use BOOTTIME to include suspend time.
1845 const int64_t timeNs = systemTime(SYSTEM_TIME_BOOTTIME);
1846 const int64_t sinceNs = timeNs - mLastRecordedTimeNs; // ok if mLastRecordedTimeNs = 0
1847 if (!force && sinceNs <= 12 * NANOS_PER_HOUR) {
1848 return;
1849 }
1850
1851 mLastRecordedTimestampVerifierN = mTimestampVerifier.getN();
1852 mLastRecordedTimeNs = timeNs;
1853
Ray Essickf27e9872019-12-07 06:28:46 -08001854 std::unique_ptr<mediametrics::Item> item(mediametrics::Item::create("audiothread"));
Andy Hungd0979812019-02-21 15:51:44 -08001855
1856#define MM_PREFIX "android.media.audiothread." // avoid cut-n-paste errors.
1857
1858 // thread configuration
1859 item->setInt32(MM_PREFIX "id", (int32_t)mId); // IO handle
1860 // item->setInt32(MM_PREFIX "portId", (int32_t)mPortId);
1861 item->setCString(MM_PREFIX "type", threadTypeToString(mType));
1862 item->setInt32(MM_PREFIX "sampleRate", (int32_t)mSampleRate);
1863 item->setInt64(MM_PREFIX "channelMask", (int64_t)mChannelMask);
1864 item->setCString(MM_PREFIX "encoding", toString(mFormat).c_str());
1865 item->setInt32(MM_PREFIX "frameCount", (int32_t)mFrameCount);
jiabinc52b1ff2019-10-31 17:20:42 -07001866 item->setCString(MM_PREFIX "outDevice", toString(outDeviceTypes()).c_str());
1867 item->setCString(MM_PREFIX "inDevice", toString(inDeviceType()).c_str());
Andy Hungd0979812019-02-21 15:51:44 -08001868
1869 // thread statistics
1870 if (mIoJitterMs.getN() > 0) {
1871 item->setDouble(MM_PREFIX "ioJitterMs.mean", mIoJitterMs.getMean());
1872 item->setDouble(MM_PREFIX "ioJitterMs.std", mIoJitterMs.getStdDev());
1873 }
1874 if (mProcessTimeMs.getN() > 0) {
1875 item->setDouble(MM_PREFIX "processTimeMs.mean", mProcessTimeMs.getMean());
1876 item->setDouble(MM_PREFIX "processTimeMs.std", mProcessTimeMs.getStdDev());
1877 }
1878 const auto tsjitter = mTimestampVerifier.getJitterMs();
1879 if (tsjitter.getN() > 0) {
1880 item->setDouble(MM_PREFIX "timestampJitterMs.mean", tsjitter.getMean());
1881 item->setDouble(MM_PREFIX "timestampJitterMs.std", tsjitter.getStdDev());
1882 }
1883 if (mLatencyMs.getN() > 0) {
1884 item->setDouble(MM_PREFIX "latencyMs.mean", mLatencyMs.getMean());
1885 item->setDouble(MM_PREFIX "latencyMs.std", mLatencyMs.getStdDev());
1886 }
1887
1888 item->selfrecord();
1889}
1890
Eric Laurentd66d7a12021-07-13 13:35:32 +02001891product_strategy_t AudioFlinger::ThreadBase::getStrategyForStream(audio_stream_type_t stream) const
1892{
1893 if (!mAudioFlinger->isAudioPolicyReady()) {
1894 return PRODUCT_STRATEGY_NONE;
1895 }
1896 return AudioSystem::getStrategyForStream(stream);
1897}
1898
Eric Laurent81784c32012-11-19 14:55:58 -08001899// ----------------------------------------------------------------------------
1900// Playback
1901// ----------------------------------------------------------------------------
1902
1903AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1904 AudioStreamOut* output,
1905 audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -07001906 type_t type,
Eric Laurentf1f22e72021-07-13 14:04:14 +02001907 bool systemReady,
1908 audio_config_base_t *mixerConfig)
Andy Hungcf10d742020-04-28 15:38:24 -07001909 : ThreadBase(audioFlinger, id, type, systemReady, true /* isOut */),
Andy Hung2098f272014-02-27 14:00:06 -08001910 mNormalFrameCount(0), mSinkBuffer(NULL),
Andy Hung6146c082014-03-18 11:56:15 -07001911 mMixerBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung69aed5f2014-02-25 17:24:40 -08001912 mMixerBuffer(NULL),
1913 mMixerBufferSize(0),
1914 mMixerBufferFormat(AUDIO_FORMAT_INVALID),
1915 mMixerBufferValid(false),
Andy Hung6146c082014-03-18 11:56:15 -07001916 mEffectBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung98ef9782014-03-04 14:46:50 -08001917 mEffectBuffer(NULL),
1918 mEffectBufferSize(0),
1919 mEffectBufferFormat(AUDIO_FORMAT_INVALID),
1920 mEffectBufferValid(false),
Glenn Kastenc1fac192013-08-06 07:41:36 -07001921 mSuspended(0), mBytesWritten(0),
Andy Hungc54b1ff2016-02-23 14:07:07 -08001922 mFramesWritten(0),
Andy Hung238fa3d2016-07-28 10:53:22 -07001923 mSuspendedFrames(0),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001924 mActiveTracks(&this->mLocalLog),
Eric Laurent81784c32012-11-19 14:55:58 -08001925 // mStreamTypes[] initialized in constructor body
Andy Hung1bc088a2018-02-09 15:57:31 -08001926 mTracks(type == MIXER),
Eric Laurent81784c32012-11-19 14:55:58 -08001927 mOutput(output),
Andy Hung446f4df2019-02-21 12:26:41 -08001928 mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
Eric Laurent81784c32012-11-19 14:55:58 -08001929 mMixerStatus(MIXER_IDLE),
1930 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
Eric Laurentad9cb8b2015-05-26 16:38:19 -07001931 mStandbyDelayNs(AudioFlinger::mStandbyTimeInNsecs),
Eric Laurentbfb1b832013-01-07 09:53:42 -08001932 mBytesRemaining(0),
1933 mCurrentWriteLength(0),
1934 mUseAsyncWrite(false),
Eric Laurent3b4529e2013-09-05 18:09:19 -07001935 mWriteAckSequence(0),
1936 mDrainSequence(0),
Eric Laurent81784c32012-11-19 14:55:58 -08001937 mScreenState(AudioFlinger::mScreenState),
1938 // index 0 is reserved for normal mixer's submix
Glenn Kastendc2c50b2016-04-21 08:13:14 -07001939 mFastTrackAvailMask(((1 << FastMixerState::sMaxFastTracks) - 1) & ~1),
Eric Laurent7c29ec92017-09-20 17:54:22 -07001940 mHwSupportsPause(false), mHwPaused(false), mFlushPending(false),
Eric Laurent74c38dc2020-12-23 18:19:44 +01001941 mLeftVolFloat(-1.0), mRightVolFloat(-1.0),
1942 mDownStreamPatch{}
Eric Laurent81784c32012-11-19 14:55:58 -08001943{
Glenn Kastend7dca052015-03-05 16:05:54 -08001944 snprintf(mThreadName, kThreadNameLength, "AudioOut_%X", id);
1945 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08001946
1947 // Assumes constructor is called by AudioFlinger with it's mLock held, but
1948 // it would be safer to explicitly pass initial masterVolume/masterMute as
1949 // parameter.
1950 //
1951 // If the HAL we are using has support for master volume or master mute,
1952 // then do not attenuate or mute during mixing (just leave the volume at 1.0
1953 // and the mute set to false).
1954 mMasterVolume = audioFlinger->masterVolume_l();
1955 mMasterMute = audioFlinger->masterMute_l();
George Burgess IV5e4d86f2020-02-18 12:55:36 -08001956 if (mOutput->audioHwDev) {
Eric Laurent81784c32012-11-19 14:55:58 -08001957 if (mOutput->audioHwDev->canSetMasterVolume()) {
1958 mMasterVolume = 1.0;
1959 }
1960
1961 if (mOutput->audioHwDev->canSetMasterMute()) {
1962 mMasterMute = false;
1963 }
Andy Hungc8fddf32018-08-08 18:32:37 -07001964 mIsMsdDevice = strcmp(
1965 mOutput->audioHwDev->moduleName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0;
Eric Laurent81784c32012-11-19 14:55:58 -08001966 }
1967
Eric Laurentf1f22e72021-07-13 14:04:14 +02001968 if (mixerConfig != nullptr && mixerConfig->channel_mask != AUDIO_CHANNEL_NONE) {
1969 mMixerChannelMask = mixerConfig->channel_mask;
1970 }
1971
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001972 readOutputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001973
Andy Hungc8fddf32018-08-08 18:32:37 -07001974 // TODO: We may also match on address as well as device type for
1975 // AUDIO_DEVICE_OUT_BUS, AUDIO_DEVICE_OUT_ALL_A2DP, AUDIO_DEVICE_OUT_REMOTE_SUBMIX
Dean Wheatleyf8726f02019-12-02 14:12:01 +11001976 if (type == MIXER || type == DIRECT || type == OFFLOAD) {
jiabinc52b1ff2019-10-31 17:20:42 -07001977 // TODO: This property should be ensure that only contains one single device type.
1978 mTimestampCorrectedDevice = (audio_devices_t)property_get_int64(
1979 "audio.timestamp.corrected_output_device",
Andy Hungc8fddf32018-08-08 18:32:37 -07001980 (int64_t)(mIsMsdDevice ? AUDIO_DEVICE_OUT_BUS // turn on by default for MSD
1981 : AUDIO_DEVICE_NONE));
1982 }
1983
Mikhail Naganovf33115d2020-09-25 23:03:05 +00001984 for (int i = AUDIO_STREAM_MIN; i < AUDIO_STREAM_FOR_POLICY_CNT; ++i) {
1985 const audio_stream_type_t stream{static_cast<audio_stream_type_t>(i)};
Eric Laurent98e38192018-02-15 18:31:53 -08001986 mStreamTypes[stream].volume = 0.0f;
Eric Laurent81784c32012-11-19 14:55:58 -08001987 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
1988 }
Eric Laurent35f8c7c2020-02-08 11:42:35 -08001989 // Audio patch and call assistant volume are always max
Eric Laurent98e38192018-02-15 18:31:53 -08001990 mStreamTypes[AUDIO_STREAM_PATCH].volume = 1.0f;
1991 mStreamTypes[AUDIO_STREAM_PATCH].mute = false;
Eric Laurent35f8c7c2020-02-08 11:42:35 -08001992 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].volume = 1.0f;
1993 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].mute = false;
Eric Laurent81784c32012-11-19 14:55:58 -08001994}
1995
1996AudioFlinger::PlaybackThread::~PlaybackThread()
1997{
Glenn Kasten9e58b552013-01-18 15:09:48 -08001998 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung010a1a12014-03-13 13:57:33 -07001999 free(mSinkBuffer);
Andy Hung69aed5f2014-02-25 17:24:40 -08002000 free(mMixerBuffer);
Andy Hung98ef9782014-03-04 14:46:50 -08002001 free(mEffectBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08002002}
2003
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002004// Thread virtuals
2005
2006void AudioFlinger::PlaybackThread::onFirstRef()
Eric Laurent81784c32012-11-19 14:55:58 -08002007{
Jasmine Chaeaa10e42021-05-11 10:11:14 +08002008 if (!isStreamInitialized()) {
jiabinf6eb4c32020-02-25 14:06:25 -08002009 ALOGE("The stream is not open yet"); // This should not happen.
2010 } else {
2011 // setEventCallback will need a strong pointer as a parameter. Calling it
2012 // here instead of constructor of PlaybackThread so that the onFirstRef
2013 // callback would not be made on an incompletely constructed object.
2014 if (mOutput->stream->setEventCallback(this) != OK) {
jiabinf1a36052020-08-19 14:33:31 -07002015 ALOGD("Failed to add event callback");
jiabinf6eb4c32020-02-25 14:06:25 -08002016 }
2017 }
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002018 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08002019}
2020
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002021// ThreadBase virtuals
2022void AudioFlinger::PlaybackThread::preExit()
2023{
2024 ALOGV(" preExit()");
2025 // FIXME this is using hard-coded strings but in the future, this functionality will be
2026 // converted to use audio HAL extensions required to support tunneling
2027 status_t result = mOutput->stream->setParameters(String8("exiting=1"));
2028 ALOGE_IF(result != OK, "Error when setting parameters on exit: %d", result);
2029}
2030
2031void AudioFlinger::PlaybackThread::dumpTracks_l(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08002032{
Eric Laurent81784c32012-11-19 14:55:58 -08002033 String8 result;
2034
Marco Nelissenb2208842014-02-07 14:00:50 -08002035 result.appendFormat(" Stream volumes in dB: ");
Eric Laurent81784c32012-11-19 14:55:58 -08002036 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
2037 const stream_type_t *st = &mStreamTypes[i];
2038 if (i > 0) {
2039 result.appendFormat(", ");
2040 }
2041 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
2042 if (st->mute) {
2043 result.append("M");
2044 }
2045 }
2046 result.append("\n");
2047 write(fd, result.string(), result.length());
2048 result.clear();
2049
Eric Laurent81784c32012-11-19 14:55:58 -08002050 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
2051 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
Elliott Hughes87cebad2014-05-22 10:14:43 -07002052 dprintf(fd, " Normal mixer raw underrun counters: partial=%u empty=%u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08002053 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Marco Nelissenb2208842014-02-07 14:00:50 -08002054
2055 size_t numtracks = mTracks.size();
2056 size_t numactive = mActiveTracks.size();
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002057 dprintf(fd, " %zu Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08002058 size_t numactiveseen = 0;
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002059 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08002060 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002061 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002062 result.append(prefix);
Andy Hungf6ab58d2018-05-25 12:50:39 -07002063 mTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08002064 for (size_t i = 0; i < numtracks; ++i) {
2065 sp<Track> track = mTracks[i];
2066 if (track != 0) {
2067 bool active = mActiveTracks.indexOf(track) >= 0;
2068 if (active) {
2069 numactiveseen++;
2070 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002071 result.append(prefix);
2072 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08002073 }
2074 }
2075 } else {
2076 result.append("\n");
2077 }
2078 if (numactiveseen != numactive) {
2079 // some tracks in the active list were not in the tracks list
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002080 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08002081 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002082 result.append(prefix);
Andy Hungf6ab58d2018-05-25 12:50:39 -07002083 mActiveTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08002084 for (size_t i = 0; i < numactive; ++i) {
Andy Hungdae27702016-10-31 14:01:16 -07002085 sp<Track> track = mActiveTracks[i];
2086 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002087 result.append(prefix);
2088 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08002089 }
2090 }
2091 }
2092
2093 write(fd, result.string(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08002094}
2095
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002096void AudioFlinger::PlaybackThread::dumpInternals_l(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08002097{
Andy Hung04cb8f72020-03-20 13:44:33 -07002098 dprintf(fd, " Master volume: %f\n", mMasterVolume);
Mikhail Naganovdfb411f2018-09-11 13:39:56 -07002099 dprintf(fd, " Master mute: %s\n", mMasterMute ? "on" : "off");
Eric Laurentf1f22e72021-07-13 14:04:14 +02002100 dprintf(fd, " Mixer channel Mask: %#x (%s)\n",
2101 mMixerChannelMask, channelMaskToString(mMixerChannelMask, true /* output */).c_str());
jiabin245cdd92018-12-07 17:55:15 -08002102 if (mHapticChannelMask != AUDIO_CHANNEL_NONE) {
2103 dprintf(fd, " Haptic channel mask: %#x (%s)\n", mHapticChannelMask,
2104 channelMaskToString(mHapticChannelMask, true /* output */).c_str());
2105 }
Elliott Hughes87cebad2014-05-22 10:14:43 -07002106 dprintf(fd, " Normal frame count: %zu\n", mNormalFrameCount);
Elliott Hughes87cebad2014-05-22 10:14:43 -07002107 dprintf(fd, " Total writes: %d\n", mNumWrites);
2108 dprintf(fd, " Delayed writes: %d\n", mNumDelayedWrites);
2109 dprintf(fd, " Blocked in write: %s\n", mInWrite ? "yes" : "no");
2110 dprintf(fd, " Suspend count: %d\n", mSuspended);
2111 dprintf(fd, " Sink buffer : %p\n", mSinkBuffer);
2112 dprintf(fd, " Mixer buffer: %p\n", mMixerBuffer);
2113 dprintf(fd, " Effect buffer: %p\n", mEffectBuffer);
2114 dprintf(fd, " Fast track availMask=%#x\n", mFastTrackAvailMask);
Eric Laurent42537be2016-01-08 17:16:42 -08002115 dprintf(fd, " Standby delay ns=%lld\n", (long long)mStandbyDelayNs);
Glenn Kasten97b7b752014-09-28 13:04:24 -07002116 AudioStreamOut *output = mOutput;
2117 audio_output_flags_t flags = output != NULL ? output->flags : AUDIO_OUTPUT_FLAG_NONE;
Mikhail Naganov913d06c2016-11-01 12:49:22 -07002118 dprintf(fd, " AudioStreamOut: %p flags %#x (%s)\n",
Andy Hung9b181952019-02-25 14:53:36 -08002119 output, flags, toString(flags).c_str());
Andy Hungb54c8542016-09-21 12:55:15 -07002120 dprintf(fd, " Frames written: %lld\n", (long long)mFramesWritten);
2121 dprintf(fd, " Suspended frames: %lld\n", (long long)mSuspendedFrames);
2122 if (mPipeSink.get() != nullptr) {
2123 dprintf(fd, " PipeSink frames written: %lld\n", (long long)mPipeSink->framesWritten());
2124 }
2125 if (output != nullptr) {
2126 dprintf(fd, " Hal stream dump:\n");
2127 (void)output->stream->dump(fd);
2128 }
Eric Laurent81784c32012-11-19 14:55:58 -08002129}
2130
Eric Laurent81784c32012-11-19 14:55:58 -08002131// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
2132sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
2133 const sp<AudioFlinger::Client>& client,
2134 audio_stream_type_t streamType,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07002135 const audio_attributes_t& attr,
Eric Laurent21da6472017-11-09 16:29:26 -08002136 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08002137 audio_format_t format,
2138 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08002139 size_t *pFrameCount,
Eric Laurent21da6472017-11-09 16:29:26 -08002140 size_t *pNotificationFrameCount,
2141 uint32_t notificationsPerBuffer,
2142 float speed,
Eric Laurent81784c32012-11-19 14:55:58 -08002143 const sp<IMemory>& sharedBuffer,
Glenn Kastend848eb42016-03-08 13:42:11 -08002144 audio_session_t sessionId,
Eric Laurent05067782016-06-01 18:27:28 -07002145 audio_output_flags_t *flags,
Eric Laurent09f1ed22019-04-24 17:45:17 -07002146 pid_t creatorPid,
Svet Ganov33761132021-05-13 22:51:08 +00002147 const AttributionSourceState& attributionSource,
Eric Laurent81784c32012-11-19 14:55:58 -08002148 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002149 status_t *status,
jiabinf6eb4c32020-02-25 14:06:25 -08002150 audio_port_handle_t portId,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07002151 const sp<media::IAudioTrackCallback>& callback)
Eric Laurent81784c32012-11-19 14:55:58 -08002152{
Glenn Kasten74935e42013-12-19 08:56:45 -08002153 size_t frameCount = *pFrameCount;
Eric Laurent21da6472017-11-09 16:29:26 -08002154 size_t notificationFrameCount = *pNotificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08002155 sp<Track> track;
2156 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07002157 audio_output_flags_t outputFlags = mOutput->flags;
Eric Laurent21da6472017-11-09 16:29:26 -08002158 audio_output_flags_t requestedFlags = *flags;
Eric Laurent9b11c022018-06-06 19:19:22 -07002159 uint32_t sampleRate;
2160
2161 if (sharedBuffer != 0 && checkIMemory(sharedBuffer) != NO_ERROR) {
2162 lStatus = BAD_VALUE;
2163 goto Exit;
2164 }
Eric Laurent21da6472017-11-09 16:29:26 -08002165
2166 if (*pSampleRate == 0) {
2167 *pSampleRate = mSampleRate;
2168 }
Eric Laurent9b11c022018-06-06 19:19:22 -07002169 sampleRate = *pSampleRate;
Eric Laurent05067782016-06-01 18:27:28 -07002170
2171 // special case for FAST flag considered OK if fast mixer is present
2172 if (hasFastMixer()) {
2173 outputFlags = (audio_output_flags_t)(outputFlags | AUDIO_OUTPUT_FLAG_FAST);
2174 }
2175
2176 // Check if requested flags are compatible with output stream flags
2177 if ((*flags & outputFlags) != *flags) {
2178 ALOGW("createTrack_l(): mismatch between requested flags (%08x) and output flags (%08x)",
2179 *flags, outputFlags);
2180 *flags = (audio_output_flags_t)(*flags & outputFlags);
2181 }
Eric Laurent81784c32012-11-19 14:55:58 -08002182
Eric Laurent81784c32012-11-19 14:55:58 -08002183 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07002184 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
Eric Laurent81784c32012-11-19 14:55:58 -08002185 if (
Eric Laurent81784c32012-11-19 14:55:58 -08002186 // PCM data
2187 audio_is_linear_pcm(format) &&
Andy Hung1f439e12015-05-19 12:57:41 -07002188 // TODO: extract as a data library function that checks that a computationally
2189 // expensive downmixer is not required: isFastOutputChannelConversion()
jiabin245cdd92018-12-07 17:55:15 -08002190 (channelMask == (mChannelMask | mHapticChannelMask) ||
Andy Hung1f439e12015-05-19 12:57:41 -07002191 mChannelMask != AUDIO_CHANNEL_OUT_STEREO ||
2192 (channelMask == AUDIO_CHANNEL_OUT_MONO
2193 /* && mChannelMask == AUDIO_CHANNEL_OUT_STEREO */)) &&
Eric Laurent81784c32012-11-19 14:55:58 -08002194 // hardware sample rate
2195 (sampleRate == mSampleRate) &&
Eric Laurent81784c32012-11-19 14:55:58 -08002196 // normal mixer has an associated fast mixer
2197 hasFastMixer() &&
2198 // there are sufficient fast track slots available
2199 (mFastTrackAvailMask != 0)
2200 // FIXME test that MixerThread for this fast track has a capable output HAL
2201 // FIXME add a permission test also?
2202 ) {
Andy Hunge0a269a2016-03-23 15:13:42 -07002203 // static tracks can have any nonzero framecount, streaming tracks check against minimum.
2204 if (sharedBuffer == 0) {
Glenn Kasten03490092014-05-27 12:30:54 -07002205 // read the fast track multiplier property the first time it is needed
2206 int ok = pthread_once(&sFastTrackMultiplierOnce, sFastTrackMultiplierInit);
2207 if (ok != 0) {
2208 ALOGE("%s pthread_once failed: %d", __func__, ok);
2209 }
Andy Hunge0a269a2016-03-23 15:13:42 -07002210 frameCount = max(frameCount, mFrameCount * sFastTrackMultiplier); // incl framecount 0
Eric Laurent81784c32012-11-19 14:55:58 -08002211 }
Eric Laurent4c415062016-06-17 16:14:16 -07002212
2213 // check compatibility with audio effects.
2214 { // scope for mLock
2215 Mutex::Autolock _l(mLock);
Andy Hungd3bb0ad2016-10-11 17:16:43 -07002216 for (audio_session_t session : {
Eric Laurent3f75a5b2019-11-12 15:55:51 -08002217 AUDIO_SESSION_DEVICE,
Andy Hungd3bb0ad2016-10-11 17:16:43 -07002218 AUDIO_SESSION_OUTPUT_STAGE,
2219 AUDIO_SESSION_OUTPUT_MIX,
2220 sessionId,
2221 }) {
2222 sp<EffectChain> chain = getEffectChain_l(session);
2223 if (chain.get() != nullptr) {
2224 audio_output_flags_t old = *flags;
2225 chain->checkOutputFlagCompatibility(flags);
2226 if (old != *flags) {
2227 ALOGV("AUDIO_OUTPUT_FLAGS denied by effect, session=%d old=%#x new=%#x",
2228 (int)session, (int)old, (int)*flags);
2229 }
Eric Laurent4c415062016-06-17 16:14:16 -07002230 }
2231 }
2232 }
Eric Laurent122f7e72016-06-29 11:53:29 -07002233 ALOGV_IF((*flags & AUDIO_OUTPUT_FLAG_FAST) != 0,
Eric Laurent4c415062016-06-17 16:14:16 -07002234 "AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
2235 frameCount, mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08002236 } else {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002237 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: sharedBuffer=%p frameCount=%zu "
2238 "mFrameCount=%zu format=%#x mFormat=%#x isLinear=%d channelMask=%#x "
Andy Hung6146c082014-03-18 11:56:15 -07002239 "sampleRate=%u mSampleRate=%u "
Eric Laurent81784c32012-11-19 14:55:58 -08002240 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
Glenn Kastend79072e2016-01-06 08:41:20 -08002241 sharedBuffer.get(), frameCount, mFrameCount, format, mFormat,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07002242 audio_is_linear_pcm(format), channelMask, sampleRate,
2243 mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
Eric Laurent4c415062016-06-17 16:14:16 -07002244 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_FAST);
Andy Hung0e48d252015-01-26 11:43:15 -08002245 }
2246 }
Eric Laurent21da6472017-11-09 16:29:26 -08002247
2248 if (!audio_has_proportional_frames(format)) {
2249 if (sharedBuffer != 0) {
2250 // Same comment as below about ignoring frameCount parameter for set()
2251 frameCount = sharedBuffer->size();
2252 } else if (frameCount == 0) {
2253 frameCount = mNormalFrameCount;
2254 }
2255 if (notificationFrameCount != frameCount) {
2256 notificationFrameCount = frameCount;
2257 }
2258 } else if (sharedBuffer != 0) {
2259 // FIXME: Ensure client side memory buffers need
2260 // not have additional alignment beyond sample
2261 // (e.g. 16 bit stereo accessed as 32 bit frame).
2262 size_t alignment = audio_bytes_per_sample(format);
2263 if (alignment & 1) {
2264 // for AUDIO_FORMAT_PCM_24_BIT_PACKED (not exposed through Java).
2265 alignment = 1;
2266 }
2267 uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
2268 size_t frameSize = channelCount * audio_bytes_per_sample(format);
2269 if (channelCount > 1) {
2270 // More than 2 channels does not require stronger alignment than stereo
2271 alignment <<= 1;
2272 }
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07002273 if (((uintptr_t)sharedBuffer->unsecurePointer() & (alignment - 1)) != 0) {
Eric Laurent21da6472017-11-09 16:29:26 -08002274 ALOGE("Invalid buffer alignment: address %p, channel count %u",
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07002275 sharedBuffer->unsecurePointer(), channelCount);
Eric Laurent21da6472017-11-09 16:29:26 -08002276 lStatus = BAD_VALUE;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002277 goto Exit;
2278 }
Eric Laurent21da6472017-11-09 16:29:26 -08002279
2280 // When initializing a shared buffer AudioTrack via constructors,
2281 // there's no frameCount parameter.
2282 // But when initializing a shared buffer AudioTrack via set(),
2283 // there _is_ a frameCount parameter. We silently ignore it.
2284 frameCount = sharedBuffer->size() / frameSize;
2285 } else {
2286 size_t minFrameCount = 0;
2287 // For fast tracks we try to respect the application's request for notifications per buffer.
2288 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
2289 if (notificationsPerBuffer > 0) {
2290 // Avoid possible arithmetic overflow during multiplication.
2291 if (notificationsPerBuffer > SIZE_MAX / mFrameCount) {
2292 ALOGE("Requested notificationPerBuffer=%u ignored for HAL frameCount=%zu",
2293 notificationsPerBuffer, mFrameCount);
2294 } else {
2295 minFrameCount = mFrameCount * notificationsPerBuffer;
2296 }
2297 }
2298 } else {
2299 // For normal PCM streaming tracks, update minimum frame count.
2300 // Buffer depth is forced to be at least 2 x the normal mixer frame count and
2301 // cover audio hardware latency.
2302 // This is probably too conservative, but legacy application code may depend on it.
2303 // If you change this calculation, also review the start threshold which is related.
2304 uint32_t latencyMs = latency_l();
2305 if (latencyMs == 0) {
2306 ALOGE("Error when retrieving output stream latency");
2307 lStatus = UNKNOWN_ERROR;
2308 goto Exit;
2309 }
2310
2311 minFrameCount = AudioSystem::calculateMinFrameCount(latencyMs, mNormalFrameCount,
2312 mSampleRate, sampleRate, speed /*, 0 mNotificationsPerBufferReq*/);
2313
Eric Laurent81784c32012-11-19 14:55:58 -08002314 }
Eric Laurent21da6472017-11-09 16:29:26 -08002315 if (frameCount < minFrameCount) {
Eric Laurent81784c32012-11-19 14:55:58 -08002316 frameCount = minFrameCount;
2317 }
Eric Laurent81784c32012-11-19 14:55:58 -08002318 }
Eric Laurent21da6472017-11-09 16:29:26 -08002319
2320 // Make sure that application is notified with sufficient margin before underrun.
2321 // The client can divide the AudioTrack buffer into sub-buffers,
2322 // and expresses its desire to server as the notification frame count.
2323 if (sharedBuffer == 0 && audio_is_linear_pcm(format)) {
2324 size_t maxNotificationFrames;
2325 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
2326 // notify every HAL buffer, regardless of the size of the track buffer
2327 maxNotificationFrames = mFrameCount;
2328 } else {
Andy Hungfa117802019-04-12 13:50:39 -07002329 // Triple buffer the notification period for a triple buffered mixer period;
2330 // otherwise, double buffering for the notification period is fine.
2331 //
2332 // TODO: This should be moved to AudioTrack to modify the notification period
2333 // on AudioTrack::setBufferSizeInFrames() changes.
2334 const int nBuffering =
2335 (uint64_t{frameCount} * mSampleRate)
2336 / (uint64_t{mNormalFrameCount} * sampleRate) == 3 ? 3 : 2;
2337
Eric Laurent21da6472017-11-09 16:29:26 -08002338 maxNotificationFrames = frameCount / nBuffering;
2339 // If client requested a fast track but this was denied, then use the smaller maximum.
2340 if (requestedFlags & AUDIO_OUTPUT_FLAG_FAST) {
2341 size_t maxNotificationFramesFastDenied = FMS_20 * sampleRate / 1000;
2342 if (maxNotificationFrames > maxNotificationFramesFastDenied) {
2343 maxNotificationFrames = maxNotificationFramesFastDenied;
2344 }
2345 }
2346 }
2347 if (notificationFrameCount == 0 || notificationFrameCount > maxNotificationFrames) {
2348 if (notificationFrameCount == 0) {
2349 ALOGD("Client defaulted notificationFrames to %zu for frameCount %zu",
2350 maxNotificationFrames, frameCount);
2351 } else {
2352 ALOGW("Client adjusted notificationFrames from %zu to %zu for frameCount %zu",
2353 notificationFrameCount, maxNotificationFrames, frameCount);
2354 }
2355 notificationFrameCount = maxNotificationFrames;
2356 }
2357 }
2358
Glenn Kasten74935e42013-12-19 08:56:45 -08002359 *pFrameCount = frameCount;
Eric Laurent21da6472017-11-09 16:29:26 -08002360 *pNotificationFrameCount = notificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08002361
Glenn Kastenc3df8382014-03-13 15:05:25 -07002362 switch (mType) {
2363
2364 case DIRECT:
Phil Burkfdb3c072016-02-09 10:47:02 -08002365 if (audio_is_linear_pcm(format)) { // TODO maybe use audio_has_proportional_frames()?
Eric Laurent81784c32012-11-19 14:55:58 -08002366 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002367 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
2368 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08002369 sampleRate, format, channelMask, mOutput, mFormat);
2370 lStatus = BAD_VALUE;
2371 goto Exit;
2372 }
2373 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002374 break;
2375
2376 case OFFLOAD:
Eric Laurentbfb1b832013-01-07 09:53:42 -08002377 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002378 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
2379 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002380 sampleRate, format, channelMask, mOutput, mFormat);
2381 lStatus = BAD_VALUE;
2382 goto Exit;
2383 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002384 break;
2385
2386 default:
Glenn Kasten993fa062014-05-02 11:14:34 -07002387 if (!audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002388 ALOGE("createTrack_l() Bad parameter: format %#x \""
2389 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002390 format, mOutput, mFormat);
2391 lStatus = BAD_VALUE;
2392 goto Exit;
2393 }
Andy Hungcd044842014-08-07 11:04:34 -07002394 if (sampleRate > mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Eric Laurent81784c32012-11-19 14:55:58 -08002395 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
2396 lStatus = BAD_VALUE;
2397 goto Exit;
2398 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002399 break;
2400
Eric Laurent81784c32012-11-19 14:55:58 -08002401 }
2402
2403 lStatus = initCheck();
2404 if (lStatus != NO_ERROR) {
Glenn Kasten15e57982013-09-24 11:52:37 -07002405 ALOGE("createTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08002406 goto Exit;
2407 }
2408
2409 { // scope for mLock
2410 Mutex::Autolock _l(mLock);
2411
2412 // all tracks in same audio session must share the same routing strategy otherwise
2413 // conflicts will happen when tracks are moved from one output to another by audio policy
2414 // manager
Eric Laurentd66d7a12021-07-13 13:35:32 +02002415 product_strategy_t strategy = getStrategyForStream(streamType);
Eric Laurent81784c32012-11-19 14:55:58 -08002416 for (size_t i = 0; i < mTracks.size(); ++i) {
2417 sp<Track> t = mTracks[i];
Eric Laurent83b88082014-06-20 18:31:16 -07002418 if (t != 0 && t->isExternalTrack()) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02002419 product_strategy_t actual = getStrategyForStream(t->streamType());
Eric Laurent81784c32012-11-19 14:55:58 -08002420 if (sessionId == t->sessionId() && strategy != actual) {
2421 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
2422 strategy, actual);
2423 lStatus = BAD_VALUE;
2424 goto Exit;
2425 }
2426 }
2427 }
2428
yucliuc9c49cd2020-07-13 16:25:21 -07002429 // Set DIRECT flag if current thread is DirectOutputThread. This can
2430 // happen when the playback is rerouted to direct output thread by
2431 // dynamic audio policy.
2432 // Do NOT report the flag changes back to client, since the client
2433 // doesn't explicitly request a direct flag.
2434 audio_output_flags_t trackFlags = *flags;
2435 if (mType == DIRECT) {
2436 trackFlags = static_cast<audio_output_flags_t>(trackFlags | AUDIO_OUTPUT_FLAG_DIRECT);
2437 }
2438
Kevin Rocard1f564ac2018-03-29 13:53:10 -07002439 track = new Track(this, client, streamType, attr, sampleRate, format,
Andy Hung8fe68032017-06-05 16:17:51 -07002440 channelMask, frameCount,
2441 nullptr /* buffer */, (size_t)0 /* bufferSize */, sharedBuffer,
Svet Ganov33761132021-05-13 22:51:08 +00002442 sessionId, creatorPid, attributionSource, trackFlags,
2443 TrackBase::TYPE_DEFAULT, portId, SIZE_MAX /*frameCountToBeReady*/, speed);
Glenn Kasten03003332013-08-06 15:40:54 -07002444
Glenn Kasten03003332013-08-06 15:40:54 -07002445 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
2446 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08002447 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08002448 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08002449 goto Exit;
2450 }
2451 mTracks.add(track);
jiabinf6eb4c32020-02-25 14:06:25 -08002452 {
2453 Mutex::Autolock _atCbL(mAudioTrackCbLock);
2454 if (callback.get() != nullptr) {
jiabin18a4b1c2020-09-17 11:40:42 -07002455 mAudioTrackCallbacks.emplace(track, callback);
jiabinf6eb4c32020-02-25 14:06:25 -08002456 }
2457 }
Eric Laurent81784c32012-11-19 14:55:58 -08002458
2459 sp<EffectChain> chain = getEffectChain_l(sessionId);
2460 if (chain != 0) {
2461 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
2462 track->setMainBuffer(chain->inBuffer());
Eric Laurentd66d7a12021-07-13 13:35:32 +02002463 chain->setStrategy(getStrategyForStream(track->streamType()));
Eric Laurent81784c32012-11-19 14:55:58 -08002464 chain->incTrackCnt();
2465 }
2466
Eric Laurent05067782016-06-01 18:27:28 -07002467 if ((*flags & AUDIO_OUTPUT_FLAG_FAST) && (tid != -1)) {
Eric Laurent81784c32012-11-19 14:55:58 -08002468 pid_t callingPid = IPCThreadState::self()->getCallingPid();
2469 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
2470 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07002471 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08002472 }
2473 }
2474
2475 lStatus = NO_ERROR;
2476
2477Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07002478 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08002479 return track;
2480}
2481
Andy Hung1bc088a2018-02-09 15:57:31 -08002482template<typename T>
Andy Hung1bc088a2018-02-09 15:57:31 -08002483ssize_t AudioFlinger::PlaybackThread::Tracks<T>::remove(const sp<T> &track)
2484{
Andy Hungc0691382018-09-12 18:01:57 -07002485 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08002486 const ssize_t index = mTracks.remove(track);
2487 if (index >= 0) {
Andy Hungc0691382018-09-12 18:01:57 -07002488 if (mSaveDeletedTrackIds) {
Andy Hung1bc088a2018-02-09 15:57:31 -08002489 // We can't directly access mAudioMixer since the caller may be outside of threadLoop.
Andy Hungc0691382018-09-12 18:01:57 -07002490 // Instead, we add to mDeletedTrackIds which is solely used for mAudioMixer update,
Andy Hung1bc088a2018-02-09 15:57:31 -08002491 // to be handled when MixerThread::prepareTracks_l() next changes mAudioMixer.
Andy Hungc0691382018-09-12 18:01:57 -07002492 mDeletedTrackIds.emplace(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08002493 }
Andy Hung1bc088a2018-02-09 15:57:31 -08002494 }
2495 return index;
2496}
2497
Eric Laurent81784c32012-11-19 14:55:58 -08002498uint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const
2499{
2500 return latency;
2501}
2502
2503uint32_t AudioFlinger::PlaybackThread::latency() const
2504{
2505 Mutex::Autolock _l(mLock);
2506 return latency_l();
2507}
2508uint32_t AudioFlinger::PlaybackThread::latency_l() const
2509{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002510 uint32_t latency;
2511 if (initCheck() == NO_ERROR && mOutput->stream->getLatency(&latency) == OK) {
2512 return correctLatency_l(latency);
Eric Laurent81784c32012-11-19 14:55:58 -08002513 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002514 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002515}
2516
2517void AudioFlinger::PlaybackThread::setMasterVolume(float value)
2518{
2519 Mutex::Autolock _l(mLock);
2520 // Don't apply master volume in SW if our HAL can do it for us.
2521 if (mOutput && mOutput->audioHwDev &&
2522 mOutput->audioHwDev->canSetMasterVolume()) {
2523 mMasterVolume = 1.0;
2524 } else {
2525 mMasterVolume = value;
2526 }
2527}
2528
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01002529void AudioFlinger::PlaybackThread::setMasterBalance(float balance)
2530{
2531 mMasterBalance.store(balance);
2532}
2533
Eric Laurent81784c32012-11-19 14:55:58 -08002534void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
2535{
Eric Laurent6acd1d42017-01-04 14:23:29 -08002536 if (isDuplicating()) {
2537 return;
2538 }
Eric Laurent81784c32012-11-19 14:55:58 -08002539 Mutex::Autolock _l(mLock);
2540 // Don't apply master mute in SW if our HAL can do it for us.
2541 if (mOutput && mOutput->audioHwDev &&
2542 mOutput->audioHwDev->canSetMasterMute()) {
2543 mMasterMute = false;
2544 } else {
2545 mMasterMute = muted;
2546 }
2547}
2548
2549void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
2550{
2551 Mutex::Autolock _l(mLock);
2552 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002553 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002554}
2555
2556void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
2557{
2558 Mutex::Autolock _l(mLock);
2559 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002560 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002561}
2562
2563float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
2564{
2565 Mutex::Autolock _l(mLock);
2566 return mStreamTypes[stream].volume;
2567}
2568
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09002569void AudioFlinger::PlaybackThread::setVolumeForOutput_l(float left, float right) const
2570{
2571 mOutput->stream->setVolume(left, right);
2572}
2573
Eric Laurent81784c32012-11-19 14:55:58 -08002574// addTrack_l() must be called with ThreadBase::mLock held
2575status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
2576{
2577 status_t status = ALREADY_EXISTS;
2578
Eric Laurent81784c32012-11-19 14:55:58 -08002579 if (mActiveTracks.indexOf(track) < 0) {
2580 // the track is newly added, make sure it fills up all its
2581 // buffers before playing. This is to ensure the client will
2582 // effectively get the latency it requested.
Eric Laurent83b88082014-06-20 18:31:16 -07002583 if (track->isExternalTrack()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002584 TrackBase::track_state state = track->mState;
2585 mLock.unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002586 status = AudioSystem::startOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002587 mLock.lock();
2588 // abort track was stopped/paused while we released the lock
2589 if (state != track->mState) {
2590 if (status == NO_ERROR) {
2591 mLock.unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002592 AudioSystem::stopOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002593 mLock.lock();
2594 }
2595 return INVALID_OPERATION;
2596 }
2597 // abort if start is rejected by audio policy manager
2598 if (status != NO_ERROR) {
2599 return PERMISSION_DENIED;
2600 }
2601#ifdef ADD_BATTERY_DATA
2602 // to track the speaker usage
2603 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
2604#endif
Eric Laurent09f1ed22019-04-24 17:45:17 -07002605 sendIoConfigEvent_l(AUDIO_CLIENT_STARTED, track->creatorPid(), track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002606 }
2607
Eric Laurent51716182016-02-29 18:00:56 -08002608 // set retry count for buffer fill
2609 if (track->isOffloaded()) {
Eric Laurente93cc032016-05-05 10:15:10 -07002610 if (track->isStopping_1()) {
2611 track->mRetryCount = kMaxTrackStopRetriesOffload;
2612 } else {
2613 track->mRetryCount = kMaxTrackStartupRetriesOffload;
2614 }
2615 track->mFillingUpStatus = mStandby ? Track::FS_FILLING : Track::FS_FILLED;
Eric Laurent51716182016-02-29 18:00:56 -08002616 } else {
2617 track->mRetryCount = kMaxTrackStartupRetries;
Eric Laurente93cc032016-05-05 10:15:10 -07002618 track->mFillingUpStatus =
2619 track->sharedBuffer() != 0 ? Track::FS_FILLED : Track::FS_FILLING;
Eric Laurent51716182016-02-29 18:00:56 -08002620 }
2621
jiabineb3bda02020-06-30 14:07:03 -07002622 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2623 if (mHapticChannelMask != AUDIO_CHANNEL_NONE
2624 && ((track->channelMask() & AUDIO_CHANNEL_HAPTIC_ALL) != AUDIO_CHANNEL_NONE
2625 || (chain != nullptr && chain->containsHapticGeneratingEffect_l()))) {
jiabin57303cc2018-12-18 15:45:57 -08002626 // Unlock due to VibratorService will lock for this call and will
2627 // call Tracks.mute/unmute which also require thread's lock.
2628 mLock.unlock();
2629 const int intensity = AudioFlinger::onExternalVibrationStart(
2630 track->getExternalVibration());
Lais Andradebc3f37a2021-07-02 00:13:19 +01002631 std::optional<media::AudioVibratorInfo> vibratorInfo;
2632 {
2633 // TODO(b/184194780): Use the vibrator information from the vibrator that will be
2634 // used to play this track.
2635 Mutex::Autolock _l(mAudioFlinger->mLock);
2636 vibratorInfo = std::move(mAudioFlinger->getDefaultVibratorInfo_l());
2637 }
jiabin57303cc2018-12-18 15:45:57 -08002638 mLock.lock();
jiabine70bc7f2020-06-30 22:07:55 -07002639 track->setHapticIntensity(static_cast<os::HapticScale>(intensity));
Lais Andradebc3f37a2021-07-02 00:13:19 +01002640 if (vibratorInfo) {
2641 track->setHapticMaxAmplitude(vibratorInfo->maxAmplitude);
2642 }
2643
jiabin57303cc2018-12-18 15:45:57 -08002644 // Haptic playback should be enabled by vibrator service.
2645 if (track->getHapticPlaybackEnabled()) {
2646 // Disable haptic playback of all active track to ensure only
2647 // one track playing haptic if current track should play haptic.
2648 for (const auto &t : mActiveTracks) {
2649 t->setHapticPlaybackEnabled(false);
2650 }
jiabin245cdd92018-12-07 17:55:15 -08002651 }
jiabine70bc7f2020-06-30 22:07:55 -07002652
2653 // Set haptic intensity for effect
2654 if (chain != nullptr) {
2655 chain->setHapticIntensity_l(track->id(), intensity);
2656 }
jiabin245cdd92018-12-07 17:55:15 -08002657 }
2658
Eric Laurent81784c32012-11-19 14:55:58 -08002659 track->mResetDone = false;
Andy Hung59de4262021-06-14 10:53:54 -07002660 track->resetPresentationComplete();
Eric Laurent81784c32012-11-19 14:55:58 -08002661 mActiveTracks.add(track);
Eric Laurentd0107bc2013-06-11 14:38:48 -07002662 if (chain != 0) {
2663 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
2664 track->sessionId());
2665 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08002666 }
2667
Andy Hungc2b11cb2020-04-22 09:04:01 -07002668 track->logBeginInterval(patchSinksToString(&mPatch)); // log to MediaMetrics
Eric Laurent81784c32012-11-19 14:55:58 -08002669 status = NO_ERROR;
2670 }
2671
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08002672 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002673 return status;
2674}
2675
Eric Laurentbfb1b832013-01-07 09:53:42 -08002676bool AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002677{
Eric Laurentbfb1b832013-01-07 09:53:42 -08002678 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08002679 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002680 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
2681 track->mState = TrackBase::STOPPED;
2682 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08002683 removeTrack_l(track);
Eric Laurentab5cdba2014-06-09 17:22:27 -07002684 } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002685 track->mState = TrackBase::STOPPING_1;
Eric Laurent81784c32012-11-19 14:55:58 -08002686 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002687
2688 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08002689}
2690
2691void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
2692{
2693 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Andy Hung2148bf02016-11-28 19:01:02 -08002694
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002695 String8 result;
2696 track->appendDump(result, false /* active */);
2697 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.string());
Andy Hung2148bf02016-11-28 19:01:02 -08002698
Eric Laurent81784c32012-11-19 14:55:58 -08002699 mTracks.remove(track);
jiabin18a4b1c2020-09-17 11:40:42 -07002700 {
2701 Mutex::Autolock _atCbL(mAudioTrackCbLock);
2702 mAudioTrackCallbacks.erase(track);
2703 }
Eric Laurent81784c32012-11-19 14:55:58 -08002704 if (track->isFastTrack()) {
2705 int index = track->mFastIndex;
Glenn Kastendc2c50b2016-04-21 08:13:14 -07002706 ALOG_ASSERT(0 < index && index < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08002707 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
2708 mFastTrackAvailMask |= 1 << index;
2709 // redundant as track is about to be destroyed, for dumpsys only
2710 track->mFastIndex = -1;
2711 }
2712 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2713 if (chain != 0) {
2714 chain->decTrackCnt();
2715 }
2716}
2717
2718String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
2719{
Eric Laurent81784c32012-11-19 14:55:58 -08002720 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002721 String8 out_s8;
2722 if (initCheck() == NO_ERROR && mOutput->stream->getParameters(keys, &out_s8) == OK) {
2723 return out_s8;
Eric Laurent81784c32012-11-19 14:55:58 -08002724 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002725 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08002726}
2727
Mikhail Naganovac917ac2018-11-28 14:03:52 -08002728status_t AudioFlinger::DirectOutputThread::selectPresentation(int presentationId, int programId) {
2729 Mutex::Autolock _l(mLock);
Jasmine Chaeaa10e42021-05-11 10:11:14 +08002730 if (!isStreamInitialized()) {
Mikhail Naganovac917ac2018-11-28 14:03:52 -08002731 return NO_INIT;
2732 }
2733 return mOutput->stream->selectPresentation(presentationId, programId);
2734}
2735
Eric Laurent09f1ed22019-04-24 17:45:17 -07002736void AudioFlinger::PlaybackThread::ioConfigChanged(audio_io_config_event event, pid_t pid,
2737 audio_port_handle_t portId) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002738 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
2739 ALOGV("PlaybackThread::ioConfigChanged, thread %p, event %d", this, event);
Eric Laurent81784c32012-11-19 14:55:58 -08002740
Eric Laurent73e26b62015-04-27 16:55:58 -07002741 desc->mIoHandle = mId;
Eric Laurent74c38dc2020-12-23 18:19:44 +01002742 struct audio_patch patch = mPatch;
2743 if (isMsdDevice()) {
2744 patch = mDownStreamPatch;
2745 }
Eric Laurent81784c32012-11-19 14:55:58 -08002746
2747 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002748 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07002749 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07002750 case AUDIO_OUTPUT_CONFIG_CHANGED:
Eric Laurent74c38dc2020-12-23 18:19:44 +01002751 desc->mPatch = patch;
Eric Laurent73e26b62015-04-27 16:55:58 -07002752 desc->mChannelMask = mChannelMask;
2753 desc->mSamplingRate = mSampleRate;
2754 desc->mFormat = mFormat;
2755 desc->mFrameCount = mNormalFrameCount; // FIXME see
Eric Laurent81784c32012-11-19 14:55:58 -08002756 // AudioFlinger::frameCount(audio_io_handle_t)
Glenn Kasten4a8308b2016-04-18 14:10:01 -07002757 desc->mFrameCountHAL = mFrameCount;
Eric Laurent73e26b62015-04-27 16:55:58 -07002758 desc->mLatency = latency_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002759 break;
Eric Laurent09f1ed22019-04-24 17:45:17 -07002760 case AUDIO_CLIENT_STARTED:
Eric Laurent74c38dc2020-12-23 18:19:44 +01002761 desc->mPatch = patch;
Eric Laurent09f1ed22019-04-24 17:45:17 -07002762 desc->mPortId = portId;
2763 break;
Eric Laurent73e26b62015-04-27 16:55:58 -07002764 case AUDIO_OUTPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08002765 default:
2766 break;
2767 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002768 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08002769}
2770
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002771void AudioFlinger::PlaybackThread::onWriteReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002772{
Eric Laurent3b4529e2013-09-05 18:09:19 -07002773 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002774}
2775
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002776void AudioFlinger::PlaybackThread::onDrainReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002777{
Eric Laurent3b4529e2013-09-05 18:09:19 -07002778 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002779}
2780
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002781void AudioFlinger::PlaybackThread::onError()
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002782{
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002783 mCallbackThread->setAsyncError();
2784}
2785
jiabinf6eb4c32020-02-25 14:06:25 -08002786void AudioFlinger::PlaybackThread::onCodecFormatChanged(
2787 const std::basic_string<uint8_t>& metadataBs)
2788{
2789 std::thread([this, metadataBs]() {
2790 audio_utils::metadata::Data metadata =
2791 audio_utils::metadata::dataFromByteString(metadataBs);
2792 if (metadata.empty()) {
2793 ALOGW("Can not transform the buffer to audio metadata, %s, %d",
2794 reinterpret_cast<char*>(const_cast<uint8_t*>(metadataBs.data())),
2795 (int)metadataBs.size());
2796 return;
2797 }
2798
2799 audio_utils::metadata::ByteString metaDataStr =
2800 audio_utils::metadata::byteStringFromData(metadata);
2801 std::vector metadataVec(metaDataStr.begin(), metaDataStr.end());
2802 Mutex::Autolock _l(mAudioTrackCbLock);
jiabin18a4b1c2020-09-17 11:40:42 -07002803 for (const auto& callbackPair : mAudioTrackCallbacks) {
2804 callbackPair.second->onCodecFormatChanged(metadataVec);
jiabinf6eb4c32020-02-25 14:06:25 -08002805 }
2806 }).detach();
2807}
2808
Eric Laurent3b4529e2013-09-05 18:09:19 -07002809void AudioFlinger::PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002810{
2811 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002812 // reject out of sequence requests
2813 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
2814 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002815 mWaitWorkCV.signal();
2816 }
2817}
2818
Eric Laurent3b4529e2013-09-05 18:09:19 -07002819void AudioFlinger::PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002820{
2821 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002822 // reject out of sequence requests
2823 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
Andy Hungf3234512018-07-03 14:51:47 -07002824 // Register discontinuity when HW drain is completed because that can cause
2825 // the timestamp frame position to reset to 0 for direct and offload threads.
2826 // (Out of sequence requests are ignored, since the discontinuity would be handled
2827 // elsewhere, e.g. in flush).
Dean Wheatley12473e92021-03-18 23:00:55 +11002828 mTimestampVerifier.discontinuity(mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002829 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002830 mWaitWorkCV.signal();
2831 }
2832}
2833
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002834void AudioFlinger::PlaybackThread::readOutputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08002835{
Glenn Kastenadad3d72014-02-21 14:51:43 -08002836 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Mikhail Naganov560637e2021-03-31 22:40:13 +00002837 const audio_config_base_t audioConfig = mOutput->getAudioProperties();
2838 mSampleRate = audioConfig.sample_rate;
2839 mChannelMask = audioConfig.channel_mask;
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002840 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002841 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002842 }
Andy Hung9a592762014-07-21 21:56:01 -07002843 if ((mType == MIXER || mType == DUPLICATING)
2844 && !isValidPcmSinkChannelMask(mChannelMask)) {
2845 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output",
2846 mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002847 }
Eric Laurentf1f22e72021-07-13 14:04:14 +02002848
2849 if (mMixerChannelMask == AUDIO_CHANNEL_NONE) {
2850 mMixerChannelMask = mChannelMask;
2851 }
2852
Andy Hunge5412692014-05-16 11:25:07 -07002853 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01002854 mBalance.setChannelMask(mChannelMask);
Phil Burkca5e6142015-07-14 09:42:29 -07002855
Eric Laurentf1f22e72021-07-13 14:04:14 +02002856 uint32_t mixerChannelCount = audio_channel_count_from_out_mask(mMixerChannelMask);
2857
Phil Burkca5e6142015-07-14 09:42:29 -07002858 // Get actual HAL format.
Mikhail Naganov560637e2021-03-31 22:40:13 +00002859 status_t result = mOutput->stream->getAudioProperties(nullptr, nullptr, &mHALFormat);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002860 LOG_ALWAYS_FATAL_IF(result != OK, "Error when retrieving output stream format: %d", result);
Phil Burkca5e6142015-07-14 09:42:29 -07002861 // Get format from the shim, which will be different than the HAL format
2862 // if playing compressed audio over HDMI passthrough.
Mikhail Naganov560637e2021-03-31 22:40:13 +00002863 mFormat = audioConfig.format;
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002864 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002865 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002866 }
Andy Hung6146c082014-03-18 11:56:15 -07002867 if ((mType == MIXER || mType == DUPLICATING)
2868 && !isValidPcmSinkFormat(mFormat)) {
2869 LOG_FATAL("HAL format %#x not supported for mixed output",
2870 mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002871 }
Phil Burk062e67a2015-02-11 13:40:50 -08002872 mFrameSize = mOutput->getFrameSize();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002873 result = mOutput->stream->getBufferSize(&mBufferSize);
2874 LOG_ALWAYS_FATAL_IF(result != OK,
2875 "Error when retrieving output stream buffer size: %d", result);
Glenn Kasten70949c42013-08-06 07:40:12 -07002876 mFrameCount = mBufferSize / mFrameSize;
Dean Wheatley77cbebd2019-04-23 14:18:44 +10002877 if ((mType == MIXER || mType == DUPLICATING) && (mFrameCount & 15)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002878 ALOGW("HAL output buffer size is %zu frames but AudioMixer requires multiples of 16 frames",
Eric Laurent81784c32012-11-19 14:55:58 -08002879 mFrameCount);
2880 }
2881
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002882 if (mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING) {
2883 if (mOutput->stream->setCallback(this) == OK) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002884 mUseAsyncWrite = true;
Eric Laurent4de95592013-09-26 15:28:21 -07002885 mCallbackThread = new AudioFlinger::AsyncCallbackThread(this);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002886 }
2887 }
2888
Eric Laurentd1f69b02014-12-15 14:33:13 -08002889 mHwSupportsPause = false;
2890 if (mOutput->flags & AUDIO_OUTPUT_FLAG_DIRECT) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002891 bool supportsPause = false, supportsResume = false;
2892 if (mOutput->stream->supportsPauseAndResume(&supportsPause, &supportsResume) == OK) {
2893 if (supportsPause && supportsResume) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08002894 mHwSupportsPause = true;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002895 } else if (supportsPause) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08002896 ALOGW("direct output implements pause but not resume");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002897 } else if (supportsResume) {
2898 ALOGW("direct output implements resume but not pause");
Eric Laurentd1f69b02014-12-15 14:33:13 -08002899 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002900 }
2901 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07002902 if (!mHwSupportsPause && mOutput->flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) {
2903 LOG_ALWAYS_FATAL("HW_AV_SYNC requested but HAL does not implement pause and resume");
2904 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002905
Andy Hungfbfc3952015-01-15 13:33:51 -08002906 if (mType == DUPLICATING && mMixerBufferEnabled && mEffectBufferEnabled) {
2907 // For best precision, we use float instead of the associated output
2908 // device format (typically PCM 16 bit).
2909
2910 mFormat = AUDIO_FORMAT_PCM_FLOAT;
2911 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
2912 mBufferSize = mFrameSize * mFrameCount;
2913
2914 // TODO: We currently use the associated output device channel mask and sample rate.
2915 // (1) Perhaps use the ORed channel mask of all downstream MixerThreads
2916 // (if a valid mask) to avoid premature downmix.
2917 // (2) Perhaps use the maximum sample rate of all downstream MixerThreads
2918 // instead of the output device sample rate to avoid loss of high frequency information.
2919 // This may need to be updated as MixerThread/OutputTracks are added and not here.
2920 }
2921
Andy Hung09a50072014-02-27 14:30:47 -08002922 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08002923 double multiplier = 1.0;
2924 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
2925 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08002926 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
2927 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Haynes Mathew George227a14b2016-05-09 12:45:48 -07002928
Eric Laurent81784c32012-11-19 14:55:58 -08002929 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
2930 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
2931 maxNormalFrameCount = maxNormalFrameCount & ~15;
2932 if (maxNormalFrameCount < minNormalFrameCount) {
2933 maxNormalFrameCount = minNormalFrameCount;
2934 }
2935 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
2936 if (multiplier <= 1.0) {
2937 multiplier = 1.0;
2938 } else if (multiplier <= 2.0) {
2939 if (2 * mFrameCount <= maxNormalFrameCount) {
2940 multiplier = 2.0;
2941 } else {
2942 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
2943 }
2944 } else {
Haynes Mathew George227a14b2016-05-09 12:45:48 -07002945 multiplier = floor(multiplier);
Eric Laurent81784c32012-11-19 14:55:58 -08002946 }
2947 }
2948 mNormalFrameCount = multiplier * mFrameCount;
2949 // round up to nearest 16 frames to satisfy AudioMixer
Eric Laurentab5cdba2014-06-09 17:22:27 -07002950 if (mType == MIXER || mType == DUPLICATING) {
2951 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
2952 }
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002953 ALOGI("HAL output buffer size %zu frames, normal sink buffer size %zu frames", mFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08002954 mNormalFrameCount);
2955
Andy Hung08fb1742015-05-31 23:22:10 -07002956 // Check if we want to throttle the processing to no more than 2x normal rate
2957 mThreadThrottle = property_get_bool("af.thread.throttle", true /* default_value */);
Andy Hung40eb1a12015-06-18 13:42:02 -07002958 mThreadThrottleTimeMs = 0;
2959 mThreadThrottleEndMs = 0;
Andy Hung08fb1742015-05-31 23:22:10 -07002960 mHalfBufferMs = mNormalFrameCount * 1000 / (2 * mSampleRate);
2961
Andy Hung010a1a12014-03-13 13:57:33 -07002962 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
2963 // Originally this was int16_t[] array, need to remove legacy implications.
2964 free(mSinkBuffer);
2965 mSinkBuffer = NULL;
Andy Hung5b10a202014-03-13 13:59:29 -07002966 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
2967 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
2968 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07002969 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08002970
Andy Hung69aed5f2014-02-25 17:24:40 -08002971 // We resize the mMixerBuffer according to the requirements of the sink buffer which
2972 // drives the output.
2973 free(mMixerBuffer);
2974 mMixerBuffer = NULL;
2975 if (mMixerBufferEnabled) {
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01002976 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // no longer valid: AUDIO_FORMAT_PCM_16_BIT.
Eric Laurentf1f22e72021-07-13 14:04:14 +02002977 mMixerBufferSize = mNormalFrameCount * mixerChannelCount
Andy Hung69aed5f2014-02-25 17:24:40 -08002978 * audio_bytes_per_sample(mMixerBufferFormat);
2979 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
2980 }
Andy Hung98ef9782014-03-04 14:46:50 -08002981 free(mEffectBuffer);
2982 mEffectBuffer = NULL;
2983 if (mEffectBufferEnabled) {
rago94a1ee82017-07-21 15:11:02 -07002984 mEffectBufferFormat = EFFECT_BUFFER_FORMAT;
Eric Laurentf1f22e72021-07-13 14:04:14 +02002985 mEffectBufferSize = mNormalFrameCount * mixerChannelCount
Andy Hung98ef9782014-03-04 14:46:50 -08002986 * audio_bytes_per_sample(mEffectBufferFormat);
2987 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
2988 }
Andy Hung69aed5f2014-02-25 17:24:40 -08002989
Mikhail Naganov55773032020-10-01 15:08:13 -07002990 mHapticChannelMask = static_cast<audio_channel_mask_t>(mChannelMask & AUDIO_CHANNEL_HAPTIC_ALL);
2991 mChannelMask = static_cast<audio_channel_mask_t>(mChannelMask & ~mHapticChannelMask);
jiabin245cdd92018-12-07 17:55:15 -08002992 mHapticChannelCount = audio_channel_count_from_out_mask(mHapticChannelMask);
2993 mChannelCount -= mHapticChannelCount;
Eric Laurentf1f22e72021-07-13 14:04:14 +02002994 mMixerChannelMask = static_cast<audio_channel_mask_t>(mMixerChannelMask & ~mHapticChannelMask);
jiabin245cdd92018-12-07 17:55:15 -08002995
Eric Laurent81784c32012-11-19 14:55:58 -08002996 // force reconfiguration of effect chains and engines to take new buffer size and audio
2997 // parameters into account
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002998 // Note that mLock is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08002999 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
3000 // matter.
3001 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
3002 Vector< sp<EffectChain> > effectChains = mEffectChains;
3003 for (size_t i = 0; i < effectChains.size(); i ++) {
Eric Laurent6c796322019-04-09 14:13:17 -07003004 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(),
3005 this/* srcThread */, this/* dstThread */);
Eric Laurent81784c32012-11-19 14:55:58 -08003006 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08003007
George Burgess IV5e4d86f2020-02-18 12:55:36 -08003008 audio_output_flags_t flags = mOutput->flags;
Andy Hungcf10d742020-04-28 15:38:24 -07003009 mediametrics::LogItem item(mThreadMetrics.getMetricsId()); // TODO: method in ThreadMetrics?
Andy Hungb68f5eb2019-12-03 16:49:17 -08003010 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
3011 .set(AMEDIAMETRICS_PROP_ENCODING, formatToString(mFormat).c_str())
3012 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
3013 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
3014 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
3015 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mNormalFrameCount)
3016 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
3017 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELMASK,
3018 (int32_t)mHapticChannelMask)
3019 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELCOUNT,
3020 (int32_t)mHapticChannelCount)
3021 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_ENCODING,
3022 formatToString(mHALFormat).c_str())
3023 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_FRAMECOUNT,
3024 (int32_t)mFrameCount) // sic - added HAL
3025 ;
3026 uint32_t latencyMs;
3027 if (mOutput->stream->getLatency(&latencyMs) == NO_ERROR) {
3028 item.set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_LATENCYMS, (double)latencyMs);
3029 }
3030 item.record();
Eric Laurent81784c32012-11-19 14:55:58 -08003031}
3032
Kevin Rocard069c2712018-03-29 19:09:14 -07003033void AudioFlinger::PlaybackThread::updateMetadata_l()
3034{
Jasmine Chaeaa10e42021-05-11 10:11:14 +08003035 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
Kevin Rocard12381092018-04-11 09:19:59 -07003036 return; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -07003037 }
3038 StreamOutHalInterface::SourceMetadata metadata;
Kevin Rocard12381092018-04-11 09:19:59 -07003039 auto backInserter = std::back_inserter(metadata.tracks);
Kevin Rocard069c2712018-03-29 19:09:14 -07003040 for (const sp<Track> &track : mActiveTracks) {
3041 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurentb9cc0ab2021-01-29 11:46:52 +01003042 // Do not forward metadata for PatchTrack with unspecified stream type
3043 if (track->streamType() != AUDIO_STREAM_PATCH) {
3044 track->copyMetadataTo(backInserter);
3045 }
Kevin Rocard069c2712018-03-29 19:09:14 -07003046 }
Kevin Rocard12381092018-04-11 09:19:59 -07003047 sendMetadataToBackend_l(metadata);
Kevin Rocard80ee2722018-04-11 15:53:48 +00003048}
Kevin Rocardc86a7f72018-04-03 09:00:09 -07003049
Kevin Rocard12381092018-04-11 09:19:59 -07003050void AudioFlinger::PlaybackThread::sendMetadataToBackend_l(
3051 const StreamOutHalInterface::SourceMetadata& metadata)
3052{
3053 mOutput->stream->updateSourceMetadata(metadata);
3054};
3055
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003056status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
Eric Laurent81784c32012-11-19 14:55:58 -08003057{
3058 if (halFrames == NULL || dspFrames == NULL) {
3059 return BAD_VALUE;
3060 }
3061 Mutex::Autolock _l(mLock);
3062 if (initCheck() != NO_ERROR) {
3063 return INVALID_OPERATION;
3064 }
Andy Hung818e7a32016-02-16 18:08:07 -08003065 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08003066 *halFrames = framesWritten;
3067
3068 if (isSuspended()) {
3069 // return an estimation of rendered frames when the output is suspended
3070 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08003071 *dspFrames = (uint32_t)
3072 (framesWritten >= (int64_t)latencyFrames ? framesWritten - latencyFrames : 0);
Eric Laurent81784c32012-11-19 14:55:58 -08003073 return NO_ERROR;
3074 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003075 status_t status;
3076 uint32_t frames;
Phil Burk062e67a2015-02-11 13:40:50 -08003077 status = mOutput->getRenderPosition(&frames);
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003078 *dspFrames = (size_t)frames;
3079 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08003080 }
3081}
3082
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08003083product_strategy_t AudioFlinger::PlaybackThread::getStrategyForSession_l(audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08003084{
3085 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
3086 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
3087 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02003088 return getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurent81784c32012-11-19 14:55:58 -08003089 }
3090 for (size_t i = 0; i < mTracks.size(); i++) {
3091 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08003092 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02003093 return getStrategyForStream(track->streamType());
Eric Laurent81784c32012-11-19 14:55:58 -08003094 }
3095 }
Eric Laurentd66d7a12021-07-13 13:35:32 +02003096 return getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurent81784c32012-11-19 14:55:58 -08003097}
3098
3099
Phil Burk062e67a2015-02-11 13:40:50 -08003100AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurent81784c32012-11-19 14:55:58 -08003101{
3102 Mutex::Autolock _l(mLock);
3103 return mOutput;
3104}
3105
Phil Burk062e67a2015-02-11 13:40:50 -08003106AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
Eric Laurent81784c32012-11-19 14:55:58 -08003107{
3108 Mutex::Autolock _l(mLock);
3109 AudioStreamOut *output = mOutput;
3110 mOutput = NULL;
3111 // FIXME FastMixer might also have a raw ptr to mOutputSink;
3112 // must push a NULL and wait for ack
3113 mOutputSink.clear();
3114 mPipeSink.clear();
3115 mNormalSink.clear();
3116 return output;
3117}
3118
3119// this method must always be called either with ThreadBase mLock held or inside the thread loop
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003120sp<StreamHalInterface> AudioFlinger::PlaybackThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08003121{
3122 if (mOutput == NULL) {
3123 return NULL;
3124 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003125 return mOutput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08003126}
3127
3128uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
3129{
3130 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
3131}
3132
3133status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
3134{
3135 if (!isValidSyncEvent(event)) {
3136 return BAD_VALUE;
3137 }
3138
3139 Mutex::Autolock _l(mLock);
3140
3141 for (size_t i = 0; i < mTracks.size(); ++i) {
3142 sp<Track> track = mTracks[i];
3143 if (event->triggerSession() == track->sessionId()) {
3144 (void) track->setSyncEvent(event);
3145 return NO_ERROR;
3146 }
3147 }
3148
3149 return NAME_NOT_FOUND;
3150}
3151
3152bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
3153{
3154 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
3155}
3156
3157void AudioFlinger::PlaybackThread::threadLoop_removeTracks(
3158 const Vector< sp<Track> >& tracksToRemove)
3159{
Andy Hungfe726a62018-09-27 15:17:25 -07003160 // Miscellaneous track cleanup when removed from the active list,
3161 // called without Thread lock but synchronized with threadLoop processing.
Eric Laurentbfb1b832013-01-07 09:53:42 -08003162#ifdef ADD_BATTERY_DATA
Andy Hungfe726a62018-09-27 15:17:25 -07003163 for (const auto& track : tracksToRemove) {
3164 if (track->isExternalTrack()) {
3165 // to track the speaker usage
3166 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Eric Laurent81784c32012-11-19 14:55:58 -08003167 }
3168 }
Andy Hungfe726a62018-09-27 15:17:25 -07003169#else
3170 (void)tracksToRemove; // suppress unused warning
3171#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003172}
3173
3174void AudioFlinger::PlaybackThread::checkSilentMode_l()
3175{
3176 if (!mMasterMute) {
3177 char value[PROPERTY_VALUE_MAX];
jiabin0a957d32020-04-29 10:56:20 -07003178 if (mOutDeviceTypeAddrs.empty()) {
3179 ALOGD("ro.audio.silent is ignored since no output device is set");
3180 return;
3181 }
jiabinc52b1ff2019-10-31 17:20:42 -07003182 if (isSingleDeviceType(outDeviceTypes(), AUDIO_DEVICE_OUT_REMOTE_SUBMIX)) {
Jean-Michel Trivi32f37c22016-03-31 16:00:32 -07003183 ALOGD("ro.audio.silent will be ignored for threads on AUDIO_DEVICE_OUT_REMOTE_SUBMIX");
3184 return;
3185 }
Eric Laurent81784c32012-11-19 14:55:58 -08003186 if (property_get("ro.audio.silent", value, "0") > 0) {
3187 char *endptr;
3188 unsigned long ul = strtoul(value, &endptr, 0);
3189 if (*endptr == '\0' && ul != 0) {
3190 ALOGD("Silence is golden");
3191 // The setprop command will not allow a property to be changed after
3192 // the first time it is set, so we don't have to worry about un-muting.
3193 setMasterMute_l(true);
3194 }
3195 }
3196 }
3197}
3198
3199// shared by MIXER and DIRECT, overridden by DUPLICATING
Eric Laurentbfb1b832013-01-07 09:53:42 -08003200ssize_t AudioFlinger::PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08003201{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07003202 LOG_HIST_TS();
Eric Laurent81784c32012-11-19 14:55:58 -08003203 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003204 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07003205 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08003206
3207 // If an NBAIO sink is present, use it to write the normal mixer's submix
3208 if (mNormalSink != 0) {
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003209
Andy Hung010a1a12014-03-13 13:57:33 -07003210 const size_t count = mBytesRemaining / mFrameSize;
3211
Simon Wilson2d590962012-11-29 15:18:50 -08003212 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08003213 // update the setpoint when AudioFlinger::mScreenState changes
3214 uint32_t screenState = AudioFlinger::mScreenState;
3215 if (screenState != mScreenState) {
3216 mScreenState = screenState;
3217 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
3218 if (pipe != NULL) {
3219 pipe->setAvgFrames((mScreenState & 1) ?
3220 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
3221 }
3222 }
Andy Hung010a1a12014-03-13 13:57:33 -07003223 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08003224 ATRACE_END();
Eric Laurent81784c32012-11-19 14:55:58 -08003225 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07003226 bytesWritten = framesWritten * mFrameSize;
Andy Hung8946a282018-04-19 20:04:56 -07003227#ifdef TEE_SINK
3228 mTee.write((char *)mSinkBuffer + offset, framesWritten);
3229#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003230 } else {
3231 bytesWritten = framesWritten;
3232 }
3233 // otherwise use the HAL / AudioStreamOut directly
3234 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003235 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07003236
Eric Laurentbfb1b832013-01-07 09:53:42 -08003237 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003238 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
3239 mWriteAckSequence += 2;
3240 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003241 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003242 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003243 }
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07003244 ATRACE_BEGIN("write");
Glenn Kasten767094d2013-08-23 13:51:43 -07003245 // FIXME We should have an implementation of timestamps for direct output threads.
3246 // They are used e.g for multichannel PCM playback over HDMI.
Phil Burk062e67a2015-02-11 13:40:50 -08003247 bytesWritten = mOutput->write((char *)mSinkBuffer + offset, mBytesRemaining);
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07003248 ATRACE_END();
Eric Laurent51716182016-02-29 18:00:56 -08003249
Eric Laurentbfb1b832013-01-07 09:53:42 -08003250 if (mUseAsyncWrite &&
3251 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
3252 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07003253 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003254 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003255 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003256 }
Eric Laurent81784c32012-11-19 14:55:58 -08003257 }
3258
Eric Laurent81784c32012-11-19 14:55:58 -08003259 mNumWrites++;
3260 mInWrite = false;
Andy Hungcf10d742020-04-28 15:38:24 -07003261 if (mStandby) {
3262 mThreadMetrics.logBeginInterval();
3263 mStandby = false;
3264 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003265 return bytesWritten;
3266}
3267
3268void AudioFlinger::PlaybackThread::threadLoop_drain()
3269{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003270 bool supportsDrain = false;
3271 if (mOutput->stream->supportsDrain(&supportsDrain) == OK && supportsDrain) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003272 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
3273 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003274 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
3275 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003276 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003277 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003278 }
Mikhail Naganovcbc8f612016-10-11 18:05:13 -07003279 status_t result = mOutput->stream->drain(mMixerStatus == MIXER_DRAIN_TRACK);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003280 ALOGE_IF(result != OK, "Error when draining stream: %d", result);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003281 }
3282}
3283
3284void AudioFlinger::PlaybackThread::threadLoop_exit()
3285{
Eric Laurent275e8e92014-11-30 15:14:47 -08003286 {
3287 Mutex::Autolock _l(mLock);
3288 for (size_t i = 0; i < mTracks.size(); i++) {
3289 sp<Track> track = mTracks[i];
3290 track->invalidate();
3291 }
Andy Hungdae27702016-10-31 14:01:16 -07003292 // Clear ActiveTracks to update BatteryNotifier in case active tracks remain.
3293 // After we exit there are no more track changes sent to BatteryNotifier
3294 // because that requires an active threadLoop.
3295 // TODO: should we decActiveTrackCnt() of the cleared track effect chain?
3296 mActiveTracks.clear();
Eric Laurent275e8e92014-11-30 15:14:47 -08003297 }
Eric Laurent81784c32012-11-19 14:55:58 -08003298}
3299
3300/*
3301The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08003302 - mSinkBufferSize from frame count * frame size
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003303 - mActiveSleepTimeUs from activeSleepTimeUs()
3304 - mIdleSleepTimeUs from idleSleepTimeUs()
Eric Laurent42537be2016-01-08 17:16:42 -08003305 - mStandbyDelayNs from mActiveSleepTimeUs (DIRECT only) or forced to at least
3306 kDefaultStandbyTimeInNsecs when connected to an A2DP device.
Eric Laurent81784c32012-11-19 14:55:58 -08003307 - maxPeriod from frame count and sample rate (MIXER only)
3308
3309The parameters that affect these derived values are:
3310 - frame count
3311 - frame size
3312 - sample rate
3313 - device type: A2DP or not
3314 - device latency
3315 - format: PCM or not
3316 - active sleep time
3317 - idle sleep time
3318*/
3319
3320void AudioFlinger::PlaybackThread::cacheParameters_l()
3321{
Andy Hung25c2dac2014-02-27 14:56:00 -08003322 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003323 mActiveSleepTimeUs = activeSleepTimeUs();
3324 mIdleSleepTimeUs = idleSleepTimeUs();
Eric Laurent42537be2016-01-08 17:16:42 -08003325
3326 // make sure standby delay is not too short when connected to an A2DP sink to avoid
3327 // truncating audio when going to standby.
3328 mStandbyDelayNs = AudioFlinger::mStandbyTimeInNsecs;
jiabinc52b1ff2019-10-31 17:20:42 -07003329 if (!Intersection(outDeviceTypes(), getAudioDeviceOutAllA2dpSet()).empty()) {
Eric Laurent42537be2016-01-08 17:16:42 -08003330 if (mStandbyDelayNs < kDefaultStandbyTimeInNsecs) {
3331 mStandbyDelayNs = kDefaultStandbyTimeInNsecs;
3332 }
3333 }
Eric Laurent81784c32012-11-19 14:55:58 -08003334}
3335
Eric Laurent13084622016-05-17 10:51:49 -07003336bool AudioFlinger::PlaybackThread::invalidateTracks_l(audio_stream_type_t streamType)
Eric Laurent81784c32012-11-19 14:55:58 -08003337{
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003338 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %zu",
Eric Laurent81784c32012-11-19 14:55:58 -08003339 this, streamType, mTracks.size());
Eric Laurent13084622016-05-17 10:51:49 -07003340 bool trackMatch = false;
Eric Laurent81784c32012-11-19 14:55:58 -08003341 size_t size = mTracks.size();
3342 for (size_t i = 0; i < size; i++) {
3343 sp<Track> t = mTracks[i];
Eric Laurentd60560a2015-04-10 11:31:20 -07003344 if (t->streamType() == streamType && t->isExternalTrack()) {
Glenn Kasten5736c352012-12-04 12:12:34 -08003345 t->invalidate();
Eric Laurent13084622016-05-17 10:51:49 -07003346 trackMatch = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003347 }
3348 }
Eric Laurent13084622016-05-17 10:51:49 -07003349 return trackMatch;
Eric Laurent81784c32012-11-19 14:55:58 -08003350}
3351
Haynes Mathew George05317d22016-05-03 16:34:26 -07003352void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
3353{
3354 Mutex::Autolock _l(mLock);
3355 invalidateTracks_l(streamType);
3356}
3357
jiabinf042b9b2021-05-07 23:46:28 +00003358// getTrackById_l must be called with holding thread lock
3359AudioFlinger::PlaybackThread::Track* AudioFlinger::PlaybackThread::getTrackById_l(
3360 audio_port_handle_t trackPortId) {
3361 for (size_t i = 0; i < mTracks.size(); i++) {
3362 if (mTracks[i]->portId() == trackPortId) {
3363 return mTracks[i].get();
3364 }
3365 }
3366 return nullptr;
3367}
3368
Eric Laurent81784c32012-11-19 14:55:58 -08003369status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
3370{
Glenn Kastend848eb42016-03-08 13:42:11 -08003371 audio_session_t session = chain->sessionId();
Mikhail Naganov022b9952017-01-04 16:36:51 -08003372 sp<EffectBufferHalInterface> halInBuffer, halOutBuffer;
Kevin Rocard7588ff42018-01-08 11:11:30 -08003373 status_t result = mAudioFlinger->mEffectsFactoryHal->mirrorBuffer(
Mikhail Naganov022b9952017-01-04 16:36:51 -08003374 mEffectBufferEnabled ? mEffectBuffer : mSinkBuffer,
3375 mEffectBufferEnabled ? mEffectBufferSize : mSinkBufferSize,
3376 &halInBuffer);
3377 if (result != OK) return result;
3378 halOutBuffer = halInBuffer;
rago94a1ee82017-07-21 15:11:02 -07003379 effect_buffer_t *buffer = reinterpret_cast<effect_buffer_t*>(halInBuffer->externalData());
Eric Laurent81784c32012-11-19 14:55:58 -08003380 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Eric Laurent3f75a5b2019-11-12 15:55:51 -08003381 if (!audio_is_global_session(session)) {
Eric Laurent81784c32012-11-19 14:55:58 -08003382 // Only one effect chain can be present in direct output thread and it uses
Andy Hung2098f272014-02-27 14:00:06 -08003383 // the sink buffer as input
Eric Laurent81784c32012-11-19 14:55:58 -08003384 if (mType != DIRECT) {
Eric Laurentf1f22e72021-07-13 14:04:14 +02003385 size_t numSamples = mNormalFrameCount
3386 * (audio_channel_count_from_out_mask(mMixerChannelMask) + mHapticChannelCount);
Kevin Rocard7588ff42018-01-08 11:11:30 -08003387 status_t result = mAudioFlinger->mEffectsFactoryHal->allocateBuffer(
rago94a1ee82017-07-21 15:11:02 -07003388 numSamples * sizeof(effect_buffer_t),
Mikhail Naganov022b9952017-01-04 16:36:51 -08003389 &halInBuffer);
3390 if (result != OK) return result;
rago94a1ee82017-07-21 15:11:02 -07003391#ifdef FLOAT_EFFECT_CHAIN
3392 buffer = halInBuffer->audioBuffer()->f32;
3393#else
Mikhail Naganov022b9952017-01-04 16:36:51 -08003394 buffer = halInBuffer->audioBuffer()->s16;
rago94a1ee82017-07-21 15:11:02 -07003395#endif
Mikhail Naganov022b9952017-01-04 16:36:51 -08003396 ALOGV("addEffectChain_l() creating new input buffer %p session %d",
3397 buffer, session);
Eric Laurent81784c32012-11-19 14:55:58 -08003398 }
3399
3400 // Attach all tracks with same session ID to this chain.
3401 for (size_t i = 0; i < mTracks.size(); ++i) {
3402 sp<Track> track = mTracks[i];
3403 if (session == track->sessionId()) {
3404 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(),
3405 buffer);
3406 track->setMainBuffer(buffer);
3407 chain->incTrackCnt();
3408 }
3409 }
3410
3411 // indicate all active tracks in the chain
Andy Hungdae27702016-10-31 14:01:16 -07003412 for (const sp<Track> &track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08003413 if (session == track->sessionId()) {
3414 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
3415 chain->incActiveTrackCnt();
3416 }
3417 }
3418 }
Eric Laurentaaa44472014-09-12 17:41:50 -07003419 chain->setThread(this);
Mikhail Naganov022b9952017-01-04 16:36:51 -08003420 chain->setInBuffer(halInBuffer);
3421 chain->setOutBuffer(halOutBuffer);
Eric Laurent3f75a5b2019-11-12 15:55:51 -08003422 // Effect chain for session AUDIO_SESSION_DEVICE is inserted at end of effect
3423 // chains list in order to be processed last as it contains output device effects.
3424 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted just before to apply post
3425 // processing effects specific to an output stream before effects applied to all streams
3426 // routed to a given device.
Eric Laurent81784c32012-11-19 14:55:58 -08003427 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
3428 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Glenn Kastend848eb42016-03-08 13:42:11 -08003429 // after track specific effects and before output stage.
Eric Laurent81784c32012-11-19 14:55:58 -08003430 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
Glenn Kastend848eb42016-03-08 13:42:11 -08003431 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX.
Eric Laurent81784c32012-11-19 14:55:58 -08003432 // Effect chain for other sessions are inserted at beginning of effect
3433 // chains list to be processed before output mix effects. Relative order between other
Glenn Kastend848eb42016-03-08 13:42:11 -08003434 // sessions is not important.
3435 static_assert(AUDIO_SESSION_OUTPUT_MIX == 0 &&
Eric Laurent3f75a5b2019-11-12 15:55:51 -08003436 AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX &&
3437 AUDIO_SESSION_DEVICE < AUDIO_SESSION_OUTPUT_STAGE,
Glenn Kastend848eb42016-03-08 13:42:11 -08003438 "audio_session_t constants misdefined");
Eric Laurent81784c32012-11-19 14:55:58 -08003439 size_t size = mEffectChains.size();
3440 size_t i = 0;
3441 for (i = 0; i < size; i++) {
3442 if (mEffectChains[i]->sessionId() < session) {
3443 break;
3444 }
3445 }
3446 mEffectChains.insertAt(chain, i);
3447 checkSuspendOnAddEffectChain_l(chain);
3448
3449 return NO_ERROR;
3450}
3451
3452size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
3453{
Glenn Kastend848eb42016-03-08 13:42:11 -08003454 audio_session_t session = chain->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08003455
3456 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
3457
3458 for (size_t i = 0; i < mEffectChains.size(); i++) {
3459 if (chain == mEffectChains[i]) {
3460 mEffectChains.removeAt(i);
3461 // detach all active tracks from the chain
Andy Hungdae27702016-10-31 14:01:16 -07003462 for (const sp<Track> &track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08003463 if (session == track->sessionId()) {
3464 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
3465 chain.get(), session);
3466 chain->decActiveTrackCnt();
3467 }
3468 }
3469
3470 // detach all tracks with same session ID from this chain
3471 for (size_t i = 0; i < mTracks.size(); ++i) {
3472 sp<Track> track = mTracks[i];
3473 if (session == track->sessionId()) {
rago94a1ee82017-07-21 15:11:02 -07003474 track->setMainBuffer(reinterpret_cast<effect_buffer_t*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08003475 chain->decTrackCnt();
3476 }
3477 }
3478 break;
3479 }
3480 }
3481 return mEffectChains.size();
3482}
3483
3484status_t AudioFlinger::PlaybackThread::attachAuxEffect(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003485 const sp<AudioFlinger::PlaybackThread::Track>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003486{
3487 Mutex::Autolock _l(mLock);
3488 return attachAuxEffect_l(track, EffectId);
3489}
3490
3491status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003492 const sp<AudioFlinger::PlaybackThread::Track>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003493{
3494 status_t status = NO_ERROR;
3495
3496 if (EffectId == 0) {
3497 track->setAuxBuffer(0, NULL);
3498 } else {
3499 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
3500 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
3501 if (effect != 0) {
3502 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
3503 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
3504 } else {
3505 status = INVALID_OPERATION;
3506 }
3507 } else {
3508 status = BAD_VALUE;
3509 }
3510 }
3511 return status;
3512}
3513
3514void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
3515{
3516 for (size_t i = 0; i < mTracks.size(); ++i) {
3517 sp<Track> track = mTracks[i];
3518 if (track->auxEffectId() == effectId) {
3519 attachAuxEffect_l(track, 0);
3520 }
3521 }
3522}
3523
3524bool AudioFlinger::PlaybackThread::threadLoop()
3525{
Glenn Kasten388d5712017-04-07 14:38:41 -07003526 tlNBLogWriter = mNBLogWriter.get();
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003527
Eric Laurent81784c32012-11-19 14:55:58 -08003528 Vector< sp<Track> > tracksToRemove;
3529
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003530 mStandbyTimeNs = systemTime();
Andy Hung446f4df2019-02-21 12:26:41 -08003531 int64_t lastLoopCountWritten = -2; // never matches "previous" loop, when loopCount = 0.
Eric Laurent81784c32012-11-19 14:55:58 -08003532
3533 // MIXER
3534 nsecs_t lastWarning = 0;
3535
3536 // DUPLICATING
3537 // FIXME could this be made local to while loop?
3538 writeFrames = 0;
3539
3540 cacheParameters_l();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003541 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003542
3543 if (mType == MIXER) {
3544 sleepTimeShift = 0;
3545 }
3546
3547 CpuStats cpuStats;
3548 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
3549
3550 acquireWakeLock();
3551
Glenn Kasteneef598c2017-04-03 14:41:13 -07003552 // mNBLogWriter logging APIs can only be called by a single thread, typically the
3553 // thread associated with this PlaybackThread.
3554 // If you want to share the mNBLogWriter with other threads (for example, binder threads)
3555 // then all such threads must agree to hold a common mutex before logging.
Glenn Kasten9e58b552013-01-18 15:09:48 -08003556 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
3557 // and then that string will be logged at the next convenient opportunity.
Glenn Kasteneef598c2017-04-03 14:41:13 -07003558 // See reference to logString below.
Glenn Kasten9e58b552013-01-18 15:09:48 -08003559 const char *logString = NULL;
3560
rago1bb90822017-05-02 18:31:48 -07003561 // Estimated time for next buffer to be written to hal. This is used only on
3562 // suspended mode (for now) to help schedule the wait time until next iteration.
3563 nsecs_t timeLoopNextNs = 0;
3564
Eric Laurent664539d2013-09-23 18:24:31 -07003565 checkSilentMode_l();
Glenn Kasteneef598c2017-04-03 14:41:13 -07003566
Andy Hung2dbffc22018-08-08 18:50:41 -07003567 audio_patch_handle_t lastDownstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Andy Hungf3234512018-07-03 14:51:47 -07003568
Andy Hung446f4df2019-02-21 12:26:41 -08003569 // loopCount is used for statistics and diagnostics.
3570 for (int64_t loopCount = 0; !exitPending(); ++loopCount)
Eric Laurent81784c32012-11-19 14:55:58 -08003571 {
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08003572 // Log merge requests are performed during AudioFlinger binder transactions, but
3573 // that does not cover audio playback. It's requested here for that reason.
3574 mAudioFlinger->requestLogMerge();
3575
Eric Laurent81784c32012-11-19 14:55:58 -08003576 cpuStats.sample(myName);
3577
3578 Vector< sp<EffectChain> > effectChains;
Andy Hung6e6a2e62019-04-30 16:38:41 -07003579 audio_session_t activeHapticSessionId = AUDIO_SESSION_NONE;
Andy Hungc1646382019-04-30 16:12:10 -07003580 std::vector<sp<Track>> activeTracks;
Eric Laurent81784c32012-11-19 14:55:58 -08003581
Andy Hung2dbffc22018-08-08 18:50:41 -07003582 // If the device is AUDIO_DEVICE_OUT_BUS, check for downstream latency.
3583 //
jiabinc52b1ff2019-10-31 17:20:42 -07003584 // Note: we access outDeviceTypes() outside of mLock.
3585 if (isMsdDevice() && outDeviceTypes().count(AUDIO_DEVICE_OUT_BUS) != 0) {
Andy Hung2dbffc22018-08-08 18:50:41 -07003586 // Here, we try for the AF lock, but do not block on it as the latency
3587 // is more informational.
3588 if (mAudioFlinger->mLock.tryLock() == NO_ERROR) {
3589 std::vector<PatchPanel::SoftwarePatch> swPatches;
3590 double latencyMs;
3591 status_t status = INVALID_OPERATION;
3592 audio_patch_handle_t downstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
3593 if (mAudioFlinger->mPatchPanel.getDownstreamSoftwarePatches(id(), &swPatches) == OK
3594 && swPatches.size() > 0) {
3595 status = swPatches[0].getLatencyMs_l(&latencyMs);
3596 downstreamPatchHandle = swPatches[0].getPatchHandle();
3597 }
3598 if (downstreamPatchHandle != lastDownstreamPatchHandle) {
Dean Wheatley30d28422018-11-06 10:27:40 +11003599 mDownstreamLatencyStatMs.reset();
Andy Hung2dbffc22018-08-08 18:50:41 -07003600 lastDownstreamPatchHandle = downstreamPatchHandle;
3601 }
3602 if (status == OK) {
3603 // verify downstream latency (we assume a max reasonable
Mikhail Naganov6aa0a312018-11-09 11:00:01 -08003604 // latency of 5 seconds).
3605 const double minLatency = 0., maxLatency = 5000.;
3606 if (latencyMs >= minLatency && latencyMs <= maxLatency) {
Dean Wheatley56a583e2020-05-08 15:12:17 +10003607 ALOGVV("new downstream latency %lf ms", latencyMs);
Andy Hung2dbffc22018-08-08 18:50:41 -07003608 } else {
3609 ALOGD("out of range downstream latency %lf ms", latencyMs);
Mikhail Naganov6aa0a312018-11-09 11:00:01 -08003610 if (latencyMs < minLatency) latencyMs = minLatency;
3611 else if (latencyMs > maxLatency) latencyMs = maxLatency;
Andy Hung2dbffc22018-08-08 18:50:41 -07003612 }
Dean Wheatley30d28422018-11-06 10:27:40 +11003613 mDownstreamLatencyStatMs.add(latencyMs);
Andy Hung2dbffc22018-08-08 18:50:41 -07003614 }
3615 mAudioFlinger->mLock.unlock();
3616 }
3617 } else {
3618 if (lastDownstreamPatchHandle != AUDIO_PATCH_HANDLE_NONE) {
3619 // our device is no longer AUDIO_DEVICE_OUT_BUS, reset patch handle and stats.
Dean Wheatley30d28422018-11-06 10:27:40 +11003620 mDownstreamLatencyStatMs.reset();
Andy Hung2dbffc22018-08-08 18:50:41 -07003621 lastDownstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
3622 }
3623 }
3624
Eric Laurent81784c32012-11-19 14:55:58 -08003625 { // scope for mLock
3626
3627 Mutex::Autolock _l(mLock);
3628
Eric Laurent021cf962014-05-13 10:18:14 -07003629 processConfigEvents_l();
Eric Laurent10351942014-05-08 18:49:52 -07003630
Glenn Kasteneef598c2017-04-03 14:41:13 -07003631 // See comment at declaration of logString for why this is done under mLock
Glenn Kasten9e58b552013-01-18 15:09:48 -08003632 if (logString != NULL) {
3633 mNBLogWriter->logTimestamp();
3634 mNBLogWriter->log(logString);
3635 logString = NULL;
3636 }
3637
Dean Wheatley12473e92021-03-18 23:00:55 +11003638 collectTimestamps_l();
Andy Hungc8fddf32018-08-08 18:32:37 -07003639
Eric Laurent81784c32012-11-19 14:55:58 -08003640 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003641 if (mSignalPending) {
3642 // A signal was raised while we were unlocked
3643 mSignalPending = false;
3644 } else if (waitingAsyncCallback_l()) {
3645 if (exitPending()) {
3646 break;
3647 }
Marco Nelissen078538c2015-05-12 09:17:57 -07003648 bool released = false;
Eric Laurent64667972016-03-30 18:19:46 -07003649 if (!keepWakeLock()) {
Marco Nelissen078538c2015-05-12 09:17:57 -07003650 releaseWakeLock_l();
3651 released = true;
3652 }
Andy Hung10cbff12017-02-21 17:30:14 -08003653
3654 const int64_t waitNs = computeWaitTimeNs_l();
3655 ALOGV("wait async completion (wait time: %lld)", (long long)waitNs);
3656 status_t status = mWaitWorkCV.waitRelative(mLock, waitNs);
3657 if (status == TIMED_OUT) {
3658 mSignalPending = true; // if timeout recheck everything
3659 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003660 ALOGV("async completion/wake");
Marco Nelissen078538c2015-05-12 09:17:57 -07003661 if (released) {
3662 acquireWakeLock_l();
3663 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003664 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3665 mSleepTimeUs = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07003666
3667 continue;
3668 }
Eric Tan39ec8d62018-07-24 09:49:29 -07003669 if ((mActiveTracks.isEmpty() && systemTime() > mStandbyTimeNs) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08003670 isSuspended()) {
3671 // put audio hardware into standby after short delay
3672 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003673
3674 threadLoop_standby();
3675
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07003676 // This is where we go into standby
3677 if (!mStandby) {
3678 LOG_AUDIO_STATE();
Andy Hungcf10d742020-04-28 15:38:24 -07003679 mThreadMetrics.logEndInterval();
3680 mStandby = true;
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07003681 }
Andy Hungd0979812019-02-21 15:51:44 -08003682 sendStatistics(false /* force */);
Eric Laurent81784c32012-11-19 14:55:58 -08003683 }
3684
Eric Tan39ec8d62018-07-24 09:49:29 -07003685 if (mActiveTracks.isEmpty() && mConfigEvents.isEmpty()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003686 // we're about to wait, flush the binder command buffer
3687 IPCThreadState::self()->flushCommands();
3688
3689 clearOutputTracks();
3690
3691 if (exitPending()) {
3692 break;
3693 }
3694
3695 releaseWakeLock_l();
3696 // wait until we have something to do...
3697 ALOGV("%s going to sleep", myName.string());
3698 mWaitWorkCV.wait(mLock);
3699 ALOGV("%s waking up", myName.string());
3700 acquireWakeLock_l();
3701
3702 mMixerStatus = MIXER_IDLE;
3703 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
3704 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003705 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003706 checkSilentMode_l();
3707
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003708 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3709 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003710 if (mType == MIXER) {
3711 sleepTimeShift = 0;
3712 }
3713
3714 continue;
3715 }
3716 }
Eric Laurent81784c32012-11-19 14:55:58 -08003717 // mMixerStatusIgnoringFastTracks is also updated internally
3718 mMixerStatus = prepareTracks_l(&tracksToRemove);
3719
Andy Hungdae27702016-10-31 14:01:16 -07003720 mActiveTracks.updatePowerState(this);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003721
Kevin Rocard069c2712018-03-29 19:09:14 -07003722 updateMetadata_l();
3723
Eric Laurent81784c32012-11-19 14:55:58 -08003724 // prevent any changes in effect chain list and in each effect chain
3725 // during mixing and effect process as the audio buffers could be deleted
3726 // or modified if an effect is created or deleted
3727 lockEffectChains_l(effectChains);
Andy Hung6e6a2e62019-04-30 16:38:41 -07003728
3729 // Determine which session to pick up haptic data.
3730 // This must be done under the same lock as prepareTracks_l().
jiabineb3bda02020-06-30 14:07:03 -07003731 // The haptic data from the effect is at a higher priority than the one from track.
Andy Hung6e6a2e62019-04-30 16:38:41 -07003732 // TODO: Write haptic data directly to sink buffer when mixing.
3733 if (mHapticChannelCount > 0 && effectChains.size() > 0) {
3734 for (const auto& track : mActiveTracks) {
jiabineb3bda02020-06-30 14:07:03 -07003735 sp<EffectChain> effectChain = getEffectChain_l(track->sessionId());
3736 if (effectChain != nullptr && effectChain->containsHapticGeneratingEffect_l()) {
3737 activeHapticSessionId = track->sessionId();
3738 break;
3739 }
Andy Hung6e6a2e62019-04-30 16:38:41 -07003740 if (track->getHapticPlaybackEnabled()) {
3741 activeHapticSessionId = track->sessionId();
3742 break;
3743 }
3744 }
3745 }
3746
Andy Hungc1646382019-04-30 16:12:10 -07003747 // Acquire a local copy of active tracks with lock (release w/o lock).
3748 //
3749 // Control methods on the track acquire the ThreadBase lock (e.g. start()
3750 // stop(), pause(), etc.), but the threadLoop is entitled to call audio
3751 // data / buffer methods on tracks from activeTracks without the ThreadBase lock.
3752 activeTracks.insert(activeTracks.end(), mActiveTracks.begin(), mActiveTracks.end());
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003753 } // mLock scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08003754
Eric Laurentbfb1b832013-01-07 09:53:42 -08003755 if (mBytesRemaining == 0) {
3756 mCurrentWriteLength = 0;
3757 if (mMixerStatus == MIXER_TRACKS_READY) {
3758 // threadLoop_mix() sets mCurrentWriteLength
3759 threadLoop_mix();
3760 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
3761 && (mMixerStatus != MIXER_DRAIN_ALL)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003762 // threadLoop_sleepTime sets mSleepTimeUs to 0 if data
Eric Laurentbfb1b832013-01-07 09:53:42 -08003763 // must be written to HAL
3764 threadLoop_sleepTime();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003765 if (mSleepTimeUs == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08003766 mCurrentWriteLength = mSinkBufferSize;
Andy Hungc1646382019-04-30 16:12:10 -07003767
3768 // Tally underrun frames as we are inserting 0s here.
3769 for (const auto& track : activeTracks) {
Andy Hunge2e830f2019-12-03 12:54:46 -08003770 if (track->mFillingUpStatus == Track::FS_ACTIVE
3771 && !track->isStopped()
3772 && !track->isPaused()
3773 && !track->isTerminated()) {
3774 ALOGV("%s: track(%d) %s underrun due to thread sleep of %zu frames",
3775 __func__, track->id(), track->getTrackStateAsString(),
3776 mNormalFrameCount);
Andy Hungc1646382019-04-30 16:12:10 -07003777 track->mAudioTrackServerProxy->tallyUnderrunFrames(mNormalFrameCount);
3778 }
3779 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003780 }
3781 }
Andy Hung98ef9782014-03-04 14:46:50 -08003782 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003783 // mMixerBuffer with data if mMixerBufferValid is true and mSleepTimeUs == 0.
Andy Hung98ef9782014-03-04 14:46:50 -08003784 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
3785 // or mSinkBuffer (if there are no effects).
3786 //
3787 // This is done pre-effects computation; if effects change to
3788 // support higher precision, this needs to move.
3789 //
3790 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003791 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08003792 if (mMixerBufferValid) {
3793 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
3794 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
Eric Laurentf1f22e72021-07-13 14:04:14 +02003795 uint32_t channelCount = mEffectBufferValid ?
3796 audio_channel_count_from_out_mask(mMixerChannelMask) : mChannelCount;
Andy Hung98ef9782014-03-04 14:46:50 -08003797
Andy Hung2ddee192015-12-18 17:34:44 -08003798 // mono blend occurs for mixer threads only (not direct or offloaded)
3799 // and is handled here if we're going directly to the sink.
3800 if (requireMonoBlend() && !mEffectBufferValid) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003801 mono_blend(mMixerBuffer, mMixerBufferFormat, mChannelCount, mNormalFrameCount,
3802 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003803 }
3804
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01003805 if (!hasFastMixer()) {
3806 // Balance must take effect after mono conversion.
3807 // We do it here if there is no FastMixer.
3808 // mBalance detects zero balance within the class for speed (not needed here).
3809 mBalance.setBalance(mMasterBalance.load());
3810 mBalance.process((float *)mMixerBuffer, mNormalFrameCount);
3811 }
3812
Andy Hung98ef9782014-03-04 14:46:50 -08003813 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
Eric Laurentf1f22e72021-07-13 14:04:14 +02003814 mNormalFrameCount * (channelCount + mHapticChannelCount));
jiabin245cdd92018-12-07 17:55:15 -08003815
3816 // If we're going directly to the sink and there are haptic channels,
3817 // we should adjust channels as the sample data is partially interleaved
3818 // in this case.
3819 if (!mEffectBufferValid && mHapticChannelCount > 0) {
3820 adjust_channels_non_destructive(buffer, mChannelCount, buffer,
3821 mChannelCount + mHapticChannelCount,
3822 audio_bytes_per_sample(format),
3823 audio_bytes_per_frame(mChannelCount, format) * mNormalFrameCount);
3824 }
Andy Hung98ef9782014-03-04 14:46:50 -08003825 }
3826
Eric Laurentbfb1b832013-01-07 09:53:42 -08003827 mBytesRemaining = mCurrentWriteLength;
3828 if (isSuspended()) {
Andy Hung238fa3d2016-07-28 10:53:22 -07003829 // Simulate write to HAL when suspended (e.g. BT SCO phone call).
3830 mSleepTimeUs = suspendSleepTimeUs(); // assumes full buffer.
3831 const size_t framesRemaining = mBytesRemaining / mFrameSize;
3832 mBytesWritten += mBytesRemaining;
3833 mFramesWritten += framesRemaining;
3834 mSuspendedFrames += framesRemaining; // to adjust kernel HAL position
Eric Laurentbfb1b832013-01-07 09:53:42 -08003835 mBytesRemaining = 0;
3836 }
Eric Laurent81784c32012-11-19 14:55:58 -08003837
Eric Laurentbfb1b832013-01-07 09:53:42 -08003838 // only process effects if we're going to write
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003839 if (mSleepTimeUs == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003840 for (size_t i = 0; i < effectChains.size(); i ++) {
3841 effectChains[i]->process_l();
jiabin47affe52019-04-04 18:02:07 -07003842 // TODO: Write haptic data directly to sink buffer when mixing.
Andy Hung6e6a2e62019-04-30 16:38:41 -07003843 if (activeHapticSessionId != AUDIO_SESSION_NONE
3844 && activeHapticSessionId == effectChains[i]->sessionId()) {
jiabin47affe52019-04-04 18:02:07 -07003845 // Haptic data is active in this case, copy it directly from
3846 // in buffer to out buffer.
3847 const size_t audioBufferSize = mNormalFrameCount
3848 * audio_bytes_per_frame(mChannelCount, EFFECT_BUFFER_FORMAT);
3849 memcpy_by_audio_format(
3850 (uint8_t*)effectChains[i]->outBuffer() + audioBufferSize,
3851 EFFECT_BUFFER_FORMAT,
3852 (const uint8_t*)effectChains[i]->inBuffer() + audioBufferSize,
3853 EFFECT_BUFFER_FORMAT, mNormalFrameCount * mHapticChannelCount);
3854 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003855 }
Eric Laurent81784c32012-11-19 14:55:58 -08003856 }
3857 }
Eric Laurent59fe0102013-09-27 18:48:26 -07003858 // Process effect chains for offloaded thread even if no audio
3859 // was read from audio track: process only updates effect state
3860 // and thus does have to be synchronized with audio writes but may have
3861 // to be called while waiting for async write callback
3862 if (mType == OFFLOAD) {
3863 for (size_t i = 0; i < effectChains.size(); i ++) {
3864 effectChains[i]->process_l();
3865 }
3866 }
Eric Laurent81784c32012-11-19 14:55:58 -08003867
Andy Hung98ef9782014-03-04 14:46:50 -08003868 // Only if the Effects buffer is enabled and there is data in the
3869 // Effects buffer (buffer valid), we need to
3870 // copy into the sink buffer.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003871 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08003872 if (mEffectBufferValid) {
3873 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
Andy Hung2ddee192015-12-18 17:34:44 -08003874
3875 if (requireMonoBlend()) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003876 mono_blend(mEffectBuffer, mEffectBufferFormat, mChannelCount, mNormalFrameCount,
3877 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003878 }
3879
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01003880 if (!hasFastMixer()) {
3881 // Balance must take effect after mono conversion.
3882 // We do it here if there is no FastMixer.
3883 // mBalance detects zero balance within the class for speed (not needed here).
3884 mBalance.setBalance(mMasterBalance.load());
3885 mBalance.process((float *)mEffectBuffer, mNormalFrameCount);
3886 }
3887
Andy Hung98ef9782014-03-04 14:46:50 -08003888 memcpy_by_audio_format(mSinkBuffer, mFormat, mEffectBuffer, mEffectBufferFormat,
jiabin245cdd92018-12-07 17:55:15 -08003889 mNormalFrameCount * (mChannelCount + mHapticChannelCount));
3890 // The sample data is partially interleaved when haptic channels exist,
3891 // we need to adjust channels here.
3892 if (mHapticChannelCount > 0) {
3893 adjust_channels_non_destructive(mSinkBuffer, mChannelCount, mSinkBuffer,
3894 mChannelCount + mHapticChannelCount,
3895 audio_bytes_per_sample(mFormat),
3896 audio_bytes_per_frame(mChannelCount, mFormat) * mNormalFrameCount);
3897 }
Andy Hung98ef9782014-03-04 14:46:50 -08003898 }
3899
Eric Laurent81784c32012-11-19 14:55:58 -08003900 // enable changes in effect chain
3901 unlockEffectChains(effectChains);
3902
Eric Laurentbfb1b832013-01-07 09:53:42 -08003903 if (!waitingAsyncCallback()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003904 // mSleepTimeUs == 0 means we must write to audio hardware
3905 if (mSleepTimeUs == 0) {
Andy Hung08fb1742015-05-31 23:22:10 -07003906 ssize_t ret = 0;
Andy Hung446f4df2019-02-21 12:26:41 -08003907 // writePeriodNs is updated >= 0 when ret > 0.
3908 int64_t writePeriodNs = -1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003909 if (mBytesRemaining) {
Andy Hung69488c42016-05-16 18:43:33 -07003910 // FIXME rewrite to reduce number of system calls
Andy Hung446f4df2019-02-21 12:26:41 -08003911 const int64_t lastIoBeginNs = systemTime();
Andy Hung08fb1742015-05-31 23:22:10 -07003912 ret = threadLoop_write();
Andy Hung446f4df2019-02-21 12:26:41 -08003913 const int64_t lastIoEndNs = systemTime();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003914 if (ret < 0) {
3915 mBytesRemaining = 0;
Andy Hung446f4df2019-02-21 12:26:41 -08003916 } else if (ret > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003917 mBytesWritten += ret;
3918 mBytesRemaining -= ret;
Andy Hung446f4df2019-02-21 12:26:41 -08003919 const int64_t frames = ret / mFrameSize;
3920 mFramesWritten += frames;
3921
3922 writePeriodNs = lastIoEndNs - mLastIoEndNs;
3923 // process information relating to write time.
3924 if (audio_has_proportional_frames(mFormat)) {
3925 // we are in a continuous mixing cycle
3926 if (mMixerStatus == MIXER_TRACKS_READY &&
3927 loopCount == lastLoopCountWritten + 1) {
3928
3929 const double jitterMs =
3930 TimestampVerifier<int64_t, int64_t>::computeJitterMs(
3931 {frames, writePeriodNs},
3932 {0, 0} /* lastTimestamp */, mSampleRate);
3933 const double processMs =
3934 (lastIoBeginNs - mLastIoEndNs) * 1e-6;
3935
3936 Mutex::Autolock _l(mLock);
3937 mIoJitterMs.add(jitterMs);
3938 mProcessTimeMs.add(processMs);
3939 }
3940
3941 // write blocked detection
3942 const int64_t deltaWriteNs = lastIoEndNs - lastIoBeginNs;
3943 if (mType == MIXER && deltaWriteNs > maxPeriod) {
3944 mNumDelayedWrites++;
3945 if ((lastIoEndNs - lastWarning) > kWarningThrottleNs) {
3946 ATRACE_NAME("underrun");
3947 ALOGW("write blocked for %lld msecs, "
3948 "%d delayed writes, thread %d",
3949 (long long)deltaWriteNs / NANOS_PER_MILLISECOND,
3950 mNumDelayedWrites, mId);
3951 lastWarning = lastIoEndNs;
3952 }
3953 }
3954 }
3955 // update timing info.
3956 mLastIoBeginNs = lastIoBeginNs;
3957 mLastIoEndNs = lastIoEndNs;
3958 lastLoopCountWritten = loopCount;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003959 }
3960 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
3961 (mMixerStatus == MIXER_DRAIN_ALL)) {
3962 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08003963 }
Andy Hung08fb1742015-05-31 23:22:10 -07003964 if (mType == MIXER && !mStandby) {
Andy Hung08fb1742015-05-31 23:22:10 -07003965
3966 if (mThreadThrottle
3967 && mMixerStatus == MIXER_TRACKS_READY // we are mixing (active tracks)
Andy Hung446f4df2019-02-21 12:26:41 -08003968 && writePeriodNs > 0) { // we have write period info
Andy Hung08fb1742015-05-31 23:22:10 -07003969 // Limit MixerThread data processing to no more than twice the
3970 // expected processing rate.
3971 //
3972 // This helps prevent underruns with NuPlayer and other applications
3973 // which may set up buffers that are close to the minimum size, or use
3974 // deep buffers, and rely on a double-buffering sleep strategy to fill.
3975 //
3976 // The throttle smooths out sudden large data drains from the device,
3977 // e.g. when it comes out of standby, which often causes problems with
3978 // (1) mixer threads without a fast mixer (which has its own warm-up)
3979 // (2) minimum buffer sized tracks (even if the track is full,
3980 // the app won't fill fast enough to handle the sudden draw).
Haynes Mathew Georgef92b2172016-05-09 11:34:15 -07003981 //
3982 // Total time spent in last processing cycle equals time spent in
3983 // 1. threadLoop_write, as well as time spent in
3984 // 2. threadLoop_mix (significant for heavy mixing, especially
3985 // on low tier processors)
Andy Hung08fb1742015-05-31 23:22:10 -07003986
Andy Hung446f4df2019-02-21 12:26:41 -08003987 // it's OK if deltaMs is an overestimate.
3988
3989 const int32_t deltaMs = writePeriodNs / NANOS_PER_MILLISECOND;
Ivan Lozanoe02bc542017-10-26 09:51:54 -07003990
Ivan Lozanoea04d392017-11-07 14:37:07 -08003991 const int32_t throttleMs = (int32_t)mHalfBufferMs - deltaMs;
Andy Hung08fb1742015-05-31 23:22:10 -07003992 if ((signed)mHalfBufferMs >= throttleMs && throttleMs > 0) {
Andy Hungcf10d742020-04-28 15:38:24 -07003993 mThreadMetrics.logThrottleMs((double)throttleMs);
Andy Hungb68f5eb2019-12-03 16:49:17 -08003994
Andy Hung08fb1742015-05-31 23:22:10 -07003995 usleep(throttleMs * 1000);
Andy Hung40eb1a12015-06-18 13:42:02 -07003996 // notify of throttle start on verbose log
3997 ALOGV_IF(mThreadThrottleEndMs == mThreadThrottleTimeMs,
3998 "mixer(%p) throttle begin:"
3999 " ret(%zd) deltaMs(%d) requires sleep %d ms",
Andy Hung08fb1742015-05-31 23:22:10 -07004000 this, ret, deltaMs, throttleMs);
Andy Hung40eb1a12015-06-18 13:42:02 -07004001 mThreadThrottleTimeMs += throttleMs;
Andy Hung0a31ddd2016-07-06 19:10:29 -07004002 // Throttle must be attributed to the previous mixer loop's write time
4003 // to allow back-to-back throttling.
Andy Hung446f4df2019-02-21 12:26:41 -08004004 // This also ensures proper timing statistics.
4005 mLastIoEndNs = systemTime(); // we fetch the write end time again.
Andy Hung40eb1a12015-06-18 13:42:02 -07004006 } else {
4007 uint32_t diff = mThreadThrottleTimeMs - mThreadThrottleEndMs;
4008 if (diff > 0) {
4009 // notify of throttle end on debug log
Andy Hung3ea004d2016-05-05 16:48:37 -07004010 // but prevent spamming for bluetooth
jiabinc52b1ff2019-10-31 17:20:42 -07004011 ALOGD_IF(!isSingleDeviceType(
4012 outDeviceTypes(), audio_is_a2dp_out_device) &&
4013 !isSingleDeviceType(
4014 outDeviceTypes(), audio_is_hearing_aid_out_device),
Andy Hung3ea004d2016-05-05 16:48:37 -07004015 "mixer(%p) throttle end: throttle time(%u)", this, diff);
Andy Hung40eb1a12015-06-18 13:42:02 -07004016 mThreadThrottleEndMs = mThreadThrottleTimeMs;
4017 }
Andy Hung08fb1742015-05-31 23:22:10 -07004018 }
4019 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004020 }
Eric Laurent81784c32012-11-19 14:55:58 -08004021
Eric Laurentbfb1b832013-01-07 09:53:42 -08004022 } else {
Glenn Kastene7754022014-10-31 12:11:26 -07004023 ATRACE_BEGIN("sleep");
Eric Laurente93cc032016-05-05 10:15:10 -07004024 Mutex::Autolock _l(mLock);
rago1bb90822017-05-02 18:31:48 -07004025 // suspended requires accurate metering of sleep time.
4026 if (isSuspended()) {
4027 // advance by expected sleepTime
4028 timeLoopNextNs += microseconds((nsecs_t)mSleepTimeUs);
4029 const nsecs_t nowNs = systemTime();
4030
4031 // compute expected next time vs current time.
4032 // (negative deltas are treated as delays).
4033 nsecs_t deltaNs = timeLoopNextNs - nowNs;
4034 if (deltaNs < -kMaxNextBufferDelayNs) {
4035 // Delays longer than the max allowed trigger a reset.
4036 ALOGV("DelayNs: %lld, resetting timeLoopNextNs", (long long) deltaNs);
4037 deltaNs = microseconds((nsecs_t)mSleepTimeUs);
4038 timeLoopNextNs = nowNs + deltaNs;
4039 } else if (deltaNs < 0) {
4040 // Delays within the max delay allowed: zero the delta/sleepTime
4041 // to help the system catch up in the next iteration(s)
4042 ALOGV("DelayNs: %lld, catching-up", (long long) deltaNs);
4043 deltaNs = 0;
4044 }
4045 // update sleep time (which is >= 0)
4046 mSleepTimeUs = deltaNs / 1000;
4047 }
Eric Laurente93cc032016-05-05 10:15:10 -07004048 if (!mSignalPending && mConfigEvents.isEmpty() && !exitPending()) {
4049 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)mSleepTimeUs));
Eric Laurent51716182016-02-29 18:00:56 -08004050 }
Glenn Kastene7754022014-10-31 12:11:26 -07004051 ATRACE_END();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004052 }
Eric Laurent81784c32012-11-19 14:55:58 -08004053 }
4054
4055 // Finally let go of removed track(s), without the lock held
4056 // since we can't guarantee the destructors won't acquire that
4057 // same lock. This will also mutate and push a new fast mixer state.
4058 threadLoop_removeTracks(tracksToRemove);
4059 tracksToRemove.clear();
4060
4061 // FIXME I don't understand the need for this here;
4062 // it was in the original code but maybe the
4063 // assignment in saveOutputTracks() makes this unnecessary?
4064 clearOutputTracks();
4065
4066 // Effect chains will be actually deleted here if they were removed from
4067 // mEffectChains list during mixing or effects processing
4068 effectChains.clear();
4069
4070 // FIXME Note that the above .clear() is no longer necessary since effectChains
4071 // is now local to this block, but will keep it for now (at least until merge done).
4072 }
4073
Eric Laurentbfb1b832013-01-07 09:53:42 -08004074 threadLoop_exit();
4075
Eric Laurentcf817a22014-08-04 20:36:31 -07004076 if (!mStandby) {
4077 threadLoop_standby();
4078 mStandby = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004079 }
4080
4081 releaseWakeLock();
4082
4083 ALOGV("Thread %p type %d exiting", this, mType);
4084 return false;
4085}
4086
Dean Wheatley12473e92021-03-18 23:00:55 +11004087void AudioFlinger::PlaybackThread::collectTimestamps_l()
4088{
4089 // Collect timestamp statistics for the Playback Thread types that support it.
4090 if (mType != MIXER
4091 && mType != DUPLICATING
4092 && mType != DIRECT
4093 && mType != OFFLOAD) {
4094 return;
4095 }
4096 if (mStandby) {
4097 mTimestampVerifier.discontinuity(discontinuityForStandbyOrFlush());
4098 return;
4099 } else if (mHwPaused) {
4100 mTimestampVerifier.discontinuity(mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS);
4101 return;
4102 }
4103
4104 // Gather the framesReleased counters for all active tracks,
4105 // and associate with the sink frames written out. We need
4106 // this to convert the sink timestamp to the track timestamp.
4107 bool kernelLocationUpdate = false;
4108 ExtendedTimestamp timestamp; // use private copy to fetch
4109
4110 // Always query HAL timestamp and update timestamp verifier. In standby or pause,
4111 // HAL may be draining some small duration buffered data for fade out.
4112 if (threadloop_getHalTimestamp_l(&timestamp) == OK) {
4113 mTimestampVerifier.add(timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL],
4114 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4115 mSampleRate);
4116
4117 if (isTimestampCorrectionEnabled()) {
4118 ALOGVV("TS_BEFORE: %d %lld %lld", id(),
4119 (long long)timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4120 (long long)timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]);
4121 auto correctedTimestamp = mTimestampVerifier.getLastCorrectedTimestamp();
4122 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4123 = correctedTimestamp.mFrames;
4124 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]
4125 = correctedTimestamp.mTimeNs;
4126 ALOGVV("TS_AFTER: %d %lld %lld", id(),
4127 (long long)timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4128 (long long)timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]);
4129
4130 // Note: Downstream latency only added if timestamp correction enabled.
4131 if (mDownstreamLatencyStatMs.getN() > 0) { // we have latency info.
4132 const int64_t newPosition =
4133 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4134 - int64_t(mDownstreamLatencyStatMs.getMean() * mSampleRate * 1e-3);
4135 // prevent retrograde
4136 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = max(
4137 newPosition,
4138 (mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4139 - mSuspendedFrames));
4140 }
4141 }
4142
4143 // We always fetch the timestamp here because often the downstream
4144 // sink will block while writing.
4145
4146 // We keep track of the last valid kernel position in case we are in underrun
4147 // and the normal mixer period is the same as the fast mixer period, or there
4148 // is some error from the HAL.
4149 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
4150 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
4151 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
4152 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
4153 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4154
4155 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
4156 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER];
4157 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
4158 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER];
4159 }
4160
4161 if (timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
4162 kernelLocationUpdate = true;
4163 } else {
4164 ALOGVV("getTimestamp error - no valid kernel position");
4165 }
4166
4167 // copy over kernel info
4168 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] =
4169 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4170 + mSuspendedFrames; // add frames discarded when suspended
4171 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] =
4172 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4173 } else {
4174 mTimestampVerifier.error();
4175 }
4176
4177 // mFramesWritten for non-offloaded tracks are contiguous
4178 // even after standby() is called. This is useful for the track frame
4179 // to sink frame mapping.
4180 bool serverLocationUpdate = false;
4181 if (mFramesWritten != mLastFramesWritten) {
4182 serverLocationUpdate = true;
4183 mLastFramesWritten = mFramesWritten;
4184 }
4185 // Only update timestamps if there is a meaningful change.
4186 // Either the kernel timestamp must be valid or we have written something.
4187 if (kernelLocationUpdate || serverLocationUpdate) {
4188 if (serverLocationUpdate) {
4189 // use the time before we called the HAL write - it is a bit more accurate
4190 // to when the server last read data than the current time here.
4191 //
4192 // If we haven't written anything, mLastIoBeginNs will be -1
4193 // and we use systemTime().
4194 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] = mFramesWritten;
4195 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = mLastIoBeginNs == -1
4196 ? systemTime() : mLastIoBeginNs;
4197 }
4198
4199 for (const sp<Track> &t : mActiveTracks) {
4200 if (!t->isFastTrack()) {
4201 t->updateTrackFrameInfo(
4202 t->mAudioTrackServerProxy->framesReleased(),
4203 mFramesWritten,
4204 mSampleRate,
4205 mTimestamp);
4206 }
4207 }
4208 }
4209
4210 if (audio_has_proportional_frames(mFormat)) {
4211 const double latencyMs = mTimestamp.getOutputServerLatencyMs(mSampleRate);
4212 if (latencyMs != 0.) { // note 0. means timestamp is empty.
4213 mLatencyMs.add(latencyMs);
4214 }
4215 }
4216#if 0
4217 // logFormat example
4218 if (z % 100 == 0) {
4219 timespec ts;
4220 clock_gettime(CLOCK_MONOTONIC, &ts);
4221 LOGT("This is an integer %d, this is a float %f, this is my "
4222 "pid %p %% %s %t", 42, 3.14, "and this is a timestamp", ts);
4223 LOGT("A deceptive null-terminated string %\0");
4224 }
4225 ++z;
4226#endif
4227}
4228
Eric Laurentbfb1b832013-01-07 09:53:42 -08004229// removeTracks_l() must be called with ThreadBase::mLock held
4230void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
4231{
Andy Hungfe726a62018-09-27 15:17:25 -07004232 for (const auto& track : tracksToRemove) {
4233 mActiveTracks.remove(track);
4234 ALOGV("%s(%d): removing track on session %d", __func__, track->id(), track->sessionId());
4235 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
4236 if (chain != 0) {
4237 ALOGV("%s(%d): stopping track on chain %p for session Id: %d",
4238 __func__, track->id(), chain.get(), track->sessionId());
4239 chain->decActiveTrackCnt();
4240 }
4241 // If an external client track, inform APM we're no longer active, and remove if needed.
4242 // We do this under lock so that the state is consistent if the Track is destroyed.
4243 if (track->isExternalTrack()) {
4244 AudioSystem::stopOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08004245 if (track->isTerminated()) {
Andy Hungfe726a62018-09-27 15:17:25 -07004246 AudioSystem::releaseOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08004247 }
4248 }
Andy Hungfe726a62018-09-27 15:17:25 -07004249 if (track->isTerminated()) {
4250 // remove from our tracks vector
4251 removeTrack_l(track);
4252 }
jiabineb3bda02020-06-30 14:07:03 -07004253 if (mHapticChannelCount > 0 &&
4254 ((track->channelMask() & AUDIO_CHANNEL_HAPTIC_ALL) != AUDIO_CHANNEL_NONE
4255 || (chain != nullptr && chain->containsHapticGeneratingEffect_l()))) {
jiabin57303cc2018-12-18 15:45:57 -08004256 mLock.unlock();
4257 // Unlock due to VibratorService will lock for this call and will
4258 // call Tracks.mute/unmute which also require thread's lock.
4259 AudioFlinger::onExternalVibrationStop(track->getExternalVibration());
4260 mLock.lock();
jiabine70bc7f2020-06-30 22:07:55 -07004261
4262 // When the track is stop, set the haptic intensity as MUTE
4263 // for the HapticGenerator effect.
4264 if (chain != nullptr) {
4265 chain->setHapticIntensity_l(track->id(), static_cast<int>(os::HapticScale::MUTE));
4266 }
jiabin245cdd92018-12-07 17:55:15 -08004267 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004268 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004269}
Eric Laurent81784c32012-11-19 14:55:58 -08004270
Eric Laurentaccc1472013-09-20 09:36:34 -07004271status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
4272{
4273 if (mNormalSink != 0) {
Andy Hung818e7a32016-02-16 18:08:07 -08004274 ExtendedTimestamp ets;
4275 status_t status = mNormalSink->getTimestamp(ets);
4276 if (status == NO_ERROR) {
4277 status = ets.getBestTimestamp(&timestamp);
4278 }
4279 return status;
Eric Laurentaccc1472013-09-20 09:36:34 -07004280 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004281 if ((mType == OFFLOAD || mType == DIRECT) && mOutput != NULL) {
Dean Wheatley12473e92021-03-18 23:00:55 +11004282 collectTimestamps_l();
4283 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] <= 0) {
4284 return INVALID_OPERATION;
Eric Laurentaccc1472013-09-20 09:36:34 -07004285 }
Dean Wheatley12473e92021-03-18 23:00:55 +11004286 timestamp.mPosition = mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
4287 const int64_t timeNs = mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4288 timestamp.mTime.tv_sec = timeNs / NANOS_PER_SECOND;
4289 timestamp.mTime.tv_nsec = timeNs - (timestamp.mTime.tv_sec * NANOS_PER_SECOND);
4290 return NO_ERROR;
Eric Laurentaccc1472013-09-20 09:36:34 -07004291 }
4292 return INVALID_OPERATION;
4293}
Eric Laurent1c333e22014-05-20 10:48:17 -07004294
Eric Laurenteab90452019-06-24 15:17:46 -07004295// For dedicated VoIP outputs, let the HAL apply the stream volume. Track volume is
4296// still applied by the mixer.
4297// All tracks attached to a mixer with flag VOIP_RX are tied to the same
4298// stream type STREAM_VOICE_CALL so this will only change the HAL volume once even
4299// if more than one track are active
4300status_t AudioFlinger::PlaybackThread::handleVoipVolume_l(float *volume)
4301{
4302 status_t result = NO_ERROR;
4303 if ((mOutput->flags & AUDIO_OUTPUT_FLAG_VOIP_RX) != 0) {
4304 if (*volume != mLeftVolFloat) {
4305 result = mOutput->stream->setVolume(*volume, *volume);
4306 ALOGE_IF(result != OK,
4307 "Error when setting output stream volume: %d", result);
4308 if (result == NO_ERROR) {
4309 mLeftVolFloat = *volume;
4310 }
4311 }
4312 // if stream volume was successfully sent to the HAL, mLeftVolFloat == v here and we
4313 // remove stream volume contribution from software volume.
4314 if (mLeftVolFloat == *volume) {
4315 *volume = 1.0f;
4316 }
4317 }
4318 return result;
4319}
4320
Eric Laurent054d9d32015-04-24 08:48:48 -07004321status_t AudioFlinger::MixerThread::createAudioPatch_l(const struct audio_patch *patch,
4322 audio_patch_handle_t *handle)
4323{
Andy Hungf60abce2016-08-26 11:37:54 -07004324 status_t status;
4325 if (property_get_bool("af.patch_park", false /* default_value */)) {
4326 // Park FastMixer to avoid potential DOS issues with writing to the HAL
4327 // or if HAL does not properly lock against access.
4328 AutoPark<FastMixer> park(mFastMixer);
4329 status = PlaybackThread::createAudioPatch_l(patch, handle);
4330 } else {
4331 status = PlaybackThread::createAudioPatch_l(patch, handle);
4332 }
Eric Laurent054d9d32015-04-24 08:48:48 -07004333 return status;
4334}
4335
Eric Laurent1c333e22014-05-20 10:48:17 -07004336status_t AudioFlinger::PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
4337 audio_patch_handle_t *handle)
4338{
4339 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07004340
4341 // store new device and send to effects
4342 audio_devices_t type = AUDIO_DEVICE_NONE;
jiabinc52b1ff2019-10-31 17:20:42 -07004343 AudioDeviceTypeAddrVector deviceTypeAddrs;
Eric Laurent054d9d32015-04-24 08:48:48 -07004344 for (unsigned int i = 0; i < patch->num_sinks; i++) {
jiabinc52b1ff2019-10-31 17:20:42 -07004345 LOG_ALWAYS_FATAL_IF(popcount(patch->sinks[i].ext.device.type) > 1
4346 && !mOutput->audioHwDev->supportsAudioPatches(),
4347 "Enumerated device type(%#x) must not be used "
4348 "as it does not support audio patches",
4349 patch->sinks[i].ext.device.type);
Mikhail Naganov55773032020-10-01 15:08:13 -07004350 type = static_cast<audio_devices_t>(type | patch->sinks[i].ext.device.type);
jiabinc52b1ff2019-10-31 17:20:42 -07004351 deviceTypeAddrs.push_back(AudioDeviceTypeAddr(patch->sinks[i].ext.device.type,
4352 patch->sinks[i].ext.device.address));
Eric Laurent054d9d32015-04-24 08:48:48 -07004353 }
4354
François Gaffie0c280aa2018-07-25 10:02:15 +02004355 audio_port_handle_t sinkPortId = patch->sinks[0].id;
Eric Laurent054d9d32015-04-24 08:48:48 -07004356#ifdef ADD_BATTERY_DATA
4357 // when changing the audio output device, call addBatteryData to notify
4358 // the change
jiabinc52b1ff2019-10-31 17:20:42 -07004359 if (outDeviceTypes() != deviceTypes) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004360 uint32_t params = 0;
4361 // check whether speaker is on
jiabinc52b1ff2019-10-31 17:20:42 -07004362 if (deviceTypes.count(AUDIO_DEVICE_OUT_SPEAKER) > 0) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004363 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent1c333e22014-05-20 10:48:17 -07004364 }
4365
Eric Laurent054d9d32015-04-24 08:48:48 -07004366 // check if any other device (except speaker) is on
jiabinc52b1ff2019-10-31 17:20:42 -07004367 if (!isSingleDeviceType(deviceTypes, AUDIO_DEVICE_OUT_SPEAKER)) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004368 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
4369 }
4370
4371 if (params != 0) {
4372 addBatteryData(params);
4373 }
4374 }
4375#endif
4376
4377 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08004378 mEffectChains[i]->setDevices_l(deviceTypeAddrs);
Eric Laurent054d9d32015-04-24 08:48:48 -07004379 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07004380
jiabinc52b1ff2019-10-31 17:20:42 -07004381 // mPatch.num_sinks is not set when the thread is created so that
4382 // the first patch creation triggers an ioConfigChanged callback
4383 bool configChanged = (mPatch.num_sinks == 0) ||
4384 (mPatch.sinks[0].id != sinkPortId);
Eric Laurent296fb132015-05-01 11:38:42 -07004385 mPatch = *patch;
jiabinc52b1ff2019-10-31 17:20:42 -07004386 mOutDeviceTypeAddrs = deviceTypeAddrs;
jiabin0a957d32020-04-29 10:56:20 -07004387 checkSilentMode_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07004388
Mikhail Naganov9ee05402016-10-13 15:58:17 -07004389 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07004390 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
4391 status = hwDevice->createAudioPatch(patch->num_sources,
4392 patch->sources,
4393 patch->num_sinks,
4394 patch->sinks,
4395 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07004396 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07004397 char *address;
4398 if (strcmp(patch->sinks[0].ext.device.address, "") != 0) {
4399 //FIXME: we only support address on first sink with HAL version < 3.0
4400 address = audio_device_address_to_parameter(
4401 patch->sinks[0].ext.device.type,
4402 patch->sinks[0].ext.device.address);
4403 } else {
4404 address = (char *)calloc(1, 1);
4405 }
4406 AudioParameter param = AudioParameter(String8(address));
4407 free(address);
Mikhail Naganov00260b52016-10-13 12:54:24 -07004408 param.addInt(String8(AudioParameter::keyRouting), (int)type);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004409 status = mOutput->stream->setParameters(param.toString());
Eric Laurent054d9d32015-04-24 08:48:48 -07004410 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07004411 }
Andy Hungc2b11cb2020-04-22 09:04:01 -07004412 const std::string patchSinksAsString = patchSinksToString(patch);
Andy Hungcf10d742020-04-28 15:38:24 -07004413
4414 mThreadMetrics.logEndInterval();
Andy Hungea840382020-05-05 21:50:17 -07004415 mThreadMetrics.logCreatePatch(/* inDevices */ {}, patchSinksAsString);
Andy Hungcf10d742020-04-28 15:38:24 -07004416 mThreadMetrics.logBeginInterval();
Andy Hungc2b11cb2020-04-22 09:04:01 -07004417 // also dispatch to active AudioTracks for MediaMetrics
4418 for (const auto &track : mActiveTracks) {
4419 track->logEndInterval();
4420 track->logBeginInterval(patchSinksAsString);
4421 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08004422
Eric Laurente8726fe2015-06-26 09:39:24 -07004423 if (configChanged) {
4424 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
4425 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004426 return status;
4427}
4428
Eric Laurent054d9d32015-04-24 08:48:48 -07004429status_t AudioFlinger::MixerThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
4430{
Andy Hungf60abce2016-08-26 11:37:54 -07004431 status_t status;
4432 if (property_get_bool("af.patch_park", false /* default_value */)) {
4433 // Park FastMixer to avoid potential DOS issues with writing to the HAL
4434 // or if HAL does not properly lock against access.
4435 AutoPark<FastMixer> park(mFastMixer);
4436 status = PlaybackThread::releaseAudioPatch_l(handle);
4437 } else {
4438 status = PlaybackThread::releaseAudioPatch_l(handle);
4439 }
Eric Laurent054d9d32015-04-24 08:48:48 -07004440 return status;
4441}
4442
Eric Laurent1c333e22014-05-20 10:48:17 -07004443status_t AudioFlinger::PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
4444{
4445 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07004446
jiabinc52b1ff2019-10-31 17:20:42 -07004447 mPatch = audio_patch{};
4448 mOutDeviceTypeAddrs.clear();
Eric Laurent054d9d32015-04-24 08:48:48 -07004449
Mikhail Naganov9ee05402016-10-13 15:58:17 -07004450 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07004451 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
4452 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07004453 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07004454 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07004455 param.addInt(String8(AudioParameter::keyRouting), 0);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004456 status = mOutput->stream->setParameters(param.toString());
Eric Laurent1c333e22014-05-20 10:48:17 -07004457 }
4458 return status;
4459}
4460
Eric Laurent83b88082014-06-20 18:31:16 -07004461void AudioFlinger::PlaybackThread::addPatchTrack(const sp<PatchTrack>& track)
4462{
4463 Mutex::Autolock _l(mLock);
4464 mTracks.add(track);
4465}
4466
4467void AudioFlinger::PlaybackThread::deletePatchTrack(const sp<PatchTrack>& track)
4468{
4469 Mutex::Autolock _l(mLock);
4470 destroyTrack_l(track);
4471}
4472
Mikhail Naganovdc769682018-05-04 15:34:08 -07004473void AudioFlinger::PlaybackThread::toAudioPortConfig(struct audio_port_config *config)
Eric Laurent83b88082014-06-20 18:31:16 -07004474{
Mikhail Naganovdc769682018-05-04 15:34:08 -07004475 ThreadBase::toAudioPortConfig(config);
Eric Laurent83b88082014-06-20 18:31:16 -07004476 config->role = AUDIO_PORT_ROLE_SOURCE;
4477 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
4478 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07004479 if (mOutput && mOutput->flags != AUDIO_OUTPUT_FLAG_NONE) {
4480 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
4481 config->flags.output = mOutput->flags;
4482 }
Eric Laurent83b88082014-06-20 18:31:16 -07004483}
4484
Eric Laurent81784c32012-11-19 14:55:58 -08004485// ----------------------------------------------------------------------------
4486
4487AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Eric Laurentf1f22e72021-07-13 14:04:14 +02004488 audio_io_handle_t id, bool systemReady, type_t type, audio_config_base_t *mixerConfig)
4489 : PlaybackThread(audioFlinger, output, id, type, systemReady, mixerConfig),
Eric Laurent81784c32012-11-19 14:55:58 -08004490 // mAudioMixer below
4491 // mFastMixer below
Andy Hung2ddee192015-12-18 17:34:44 -08004492 mFastMixerFutex(0),
4493 mMasterMono(false)
Eric Laurent81784c32012-11-19 14:55:58 -08004494 // mOutputSink below
4495 // mPipeSink below
4496 // mNormalSink below
4497{
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01004498 setMasterBalance(audioFlinger->getMasterBalance_l());
jiabinc52b1ff2019-10-31 17:20:42 -07004499 ALOGV("MixerThread() id=%d type=%d", id, type);
Glenn Kasten49f36ba2017-12-06 13:02:02 -08004500 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%#x, mFrameSize=%zu, "
Glenn Kastenc42e9b42016-03-21 11:35:03 -07004501 "mFrameCount=%zu, mNormalFrameCount=%zu",
Eric Laurent81784c32012-11-19 14:55:58 -08004502 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
4503 mNormalFrameCount);
4504 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
4505
Andy Hungfbfc3952015-01-15 13:33:51 -08004506 if (type == DUPLICATING) {
4507 // The Duplicating thread uses the AudioMixer and delivers data to OutputTracks
4508 // (downstream MixerThreads) in DuplicatingThread::threadLoop_write().
4509 // Do not create or use mFastMixer, mOutputSink, mPipeSink, or mNormalSink.
4510 return;
4511 }
Eric Laurent81784c32012-11-19 14:55:58 -08004512 // create an NBAIO sink for the HAL output stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07004513 mOutputSink = new AudioStreamOutSink(output->stream);
Eric Laurent81784c32012-11-19 14:55:58 -08004514 size_t numCounterOffers = 0;
jiabin245cdd92018-12-07 17:55:15 -08004515 const NBAIO_Format offers[1] = {Format_from_SR_C(
4516 mSampleRate, mChannelCount + mHapticChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07004517#if !LOG_NDEBUG
4518 ssize_t index =
4519#else
4520 (void)
4521#endif
4522 mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08004523 ALOG_ASSERT(index == 0);
4524
4525 // initialize fast mixer depending on configuration
4526 bool initFastMixer;
4527 switch (kUseFastMixer) {
4528 case FastMixer_Never:
4529 initFastMixer = false;
4530 break;
4531 case FastMixer_Always:
4532 initFastMixer = true;
4533 break;
4534 case FastMixer_Static:
4535 case FastMixer_Dynamic:
Andy Hungfda69402017-02-15 14:33:12 -08004536 // FastMixer was designed to operate with a HAL that pulls at a regular rate,
4537 // where the period is less than an experimentally determined threshold that can be
4538 // scheduled reliably with CFS. However, the BT A2DP HAL is
4539 // bursty (does not pull at a regular rate) and so cannot operate with FastMixer.
4540 initFastMixer = mFrameCount < mNormalFrameCount
jiabinc52b1ff2019-10-31 17:20:42 -07004541 && Intersection(outDeviceTypes(), getAudioDeviceOutAllA2dpSet()).empty();
Eric Laurent81784c32012-11-19 14:55:58 -08004542 break;
4543 }
Andy Hungfda69402017-02-15 14:33:12 -08004544 ALOGW_IF(initFastMixer == false && mFrameCount < mNormalFrameCount,
4545 "FastMixer is preferred for this sink as frameCount %zu is less than threshold %zu",
4546 mFrameCount, mNormalFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08004547 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07004548 audio_format_t fastMixerFormat;
4549 if (mMixerBufferEnabled && mEffectBufferEnabled) {
4550 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
4551 } else {
4552 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
4553 }
4554 if (mFormat != fastMixerFormat) {
4555 // change our Sink format to accept our intermediate precision
4556 mFormat = fastMixerFormat;
4557 free(mSinkBuffer);
jiabin245cdd92018-12-07 17:55:15 -08004558 mFrameSize = audio_bytes_per_frame(mChannelCount + mHapticChannelCount, mFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07004559 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
4560 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
4561 }
Eric Laurent81784c32012-11-19 14:55:58 -08004562
4563 // create a MonoPipe to connect our submix to FastMixer
4564 NBAIO_Format format = mOutputSink->format();
Andy Hung8946a282018-04-19 20:04:56 -07004565
Andy Hung1258c1a2014-05-23 21:22:17 -07004566 // adjust format to match that of the Fast Mixer
Glenn Kasten49f36ba2017-12-06 13:02:02 -08004567 ALOGV("format changed from %#x to %#x", format.mFormat, fastMixerFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07004568 format.mFormat = fastMixerFormat;
4569 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
4570
Eric Laurent81784c32012-11-19 14:55:58 -08004571 // This pipe depth compensates for scheduling latency of the normal mixer thread.
4572 // When it wakes up after a maximum latency, it runs a few cycles quickly before
4573 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
4574 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
4575 const NBAIO_Format offers[1] = {format};
4576 size_t numCounterOffers = 0;
Andy Hung8946a282018-04-19 20:04:56 -07004577#if !LOG_NDEBUG
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07004578 ssize_t index =
4579#else
4580 (void)
4581#endif
4582 monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08004583 ALOG_ASSERT(index == 0);
4584 monoPipe->setAvgFrames((mScreenState & 1) ?
4585 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
4586 mPipeSink = monoPipe;
4587
Eric Laurent81784c32012-11-19 14:55:58 -08004588 // create fast mixer and configure it initially with just one fast track for our submix
Andy Hung8946a282018-04-19 20:04:56 -07004589 mFastMixer = new FastMixer(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08004590 FastMixerStateQueue *sq = mFastMixer->sq();
4591#ifdef STATE_QUEUE_DUMP
4592 sq->setObserverDump(&mStateQueueObserverDump);
4593 sq->setMutatorDump(&mStateQueueMutatorDump);
4594#endif
4595 FastMixerState *state = sq->begin();
4596 FastTrack *fastTrack = &state->mFastTracks[0];
4597 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
4598 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
4599 fastTrack->mVolumeProvider = NULL;
Mikhail Naganov55773032020-10-01 15:08:13 -07004600 fastTrack->mChannelMask = static_cast<audio_channel_mask_t>(
4601 mChannelMask | mHapticChannelMask); // mPipeSink channel mask for
4602 // audio to FastMixer
Andy Hunge8a1ced2014-05-09 15:02:21 -07004603 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
jiabin245cdd92018-12-07 17:55:15 -08004604 fastTrack->mHapticPlaybackEnabled = mHapticChannelMask != AUDIO_CHANNEL_NONE;
jiabine70bc7f2020-06-30 22:07:55 -07004605 fastTrack->mHapticIntensity = os::HapticScale::NONE;
Lais Andradebc3f37a2021-07-02 00:13:19 +01004606 fastTrack->mHapticMaxAmplitude = NAN;
Eric Laurent81784c32012-11-19 14:55:58 -08004607 fastTrack->mGeneration++;
4608 state->mFastTracksGen++;
4609 state->mTrackMask = 1;
4610 // fast mixer will use the HAL output sink
4611 state->mOutputSink = mOutputSink.get();
4612 state->mOutputSinkGen++;
4613 state->mFrameCount = mFrameCount;
jiabin245cdd92018-12-07 17:55:15 -08004614 // specify sink channel mask when haptic channel mask present as it can not
4615 // be calculated directly from channel count
4616 state->mSinkChannelMask = mHapticChannelMask == AUDIO_CHANNEL_NONE
Mikhail Naganov55773032020-10-01 15:08:13 -07004617 ? AUDIO_CHANNEL_NONE
4618 : static_cast<audio_channel_mask_t>(mChannelMask | mHapticChannelMask);
Eric Laurent81784c32012-11-19 14:55:58 -08004619 state->mCommand = FastMixerState::COLD_IDLE;
4620 // already done in constructor initialization list
4621 //mFastMixerFutex = 0;
4622 state->mColdFutexAddr = &mFastMixerFutex;
4623 state->mColdGen++;
4624 state->mDumpState = &mFastMixerDumpState;
Glenn Kasten9e58b552013-01-18 15:09:48 -08004625 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
4626 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08004627 sq->end();
4628 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
4629
Eric Tan0513b5d2018-09-17 10:32:48 -07004630 NBLog::thread_info_t info;
4631 info.id = mId;
4632 info.type = NBLog::FASTMIXER;
4633 mFastMixerNBLogWriter->log<NBLog::EVENT_THREAD_INFO>(info);
4634
Eric Laurent81784c32012-11-19 14:55:58 -08004635 // start the fast mixer
4636 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
4637 pid_t tid = mFastMixer->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07004638 sendPrioConfigEvent(getpid(), tid, kPriorityFastMixer, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08004639 stream()->setHalThreadPriority(kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08004640
4641#ifdef AUDIO_WATCHDOG
4642 // create and start the watchdog
4643 mAudioWatchdog = new AudioWatchdog();
4644 mAudioWatchdog->setDump(&mAudioWatchdogDump);
4645 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
4646 tid = mAudioWatchdog->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07004647 sendPrioConfigEvent(getpid(), tid, kPriorityFastMixer, false /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08004648#endif
Andy Hung8946a282018-04-19 20:04:56 -07004649 } else {
4650#ifdef TEE_SINK
4651 // Only use the MixerThread tee if there is no FastMixer.
4652 mTee.set(mOutputSink->format(), NBAIO_Tee::TEE_FLAG_OUTPUT_THREAD);
4653 mTee.setId(std::string("_") + std::to_string(mId) + "_M");
4654#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004655 }
4656
4657 switch (kUseFastMixer) {
4658 case FastMixer_Never:
4659 case FastMixer_Dynamic:
4660 mNormalSink = mOutputSink;
4661 break;
4662 case FastMixer_Always:
4663 mNormalSink = mPipeSink;
4664 break;
4665 case FastMixer_Static:
4666 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
4667 break;
4668 }
4669}
4670
4671AudioFlinger::MixerThread::~MixerThread()
4672{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004673 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004674 FastMixerStateQueue *sq = mFastMixer->sq();
4675 FastMixerState *state = sq->begin();
4676 if (state->mCommand == FastMixerState::COLD_IDLE) {
4677 int32_t old = android_atomic_inc(&mFastMixerFutex);
4678 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07004679 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08004680 }
4681 }
4682 state->mCommand = FastMixerState::EXIT;
4683 sq->end();
4684 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
4685 mFastMixer->join();
4686 // Though the fast mixer thread has exited, it's state queue is still valid.
4687 // We'll use that extract the final state which contains one remaining fast track
4688 // corresponding to our sub-mix.
4689 state = sq->begin();
4690 ALOG_ASSERT(state->mTrackMask == 1);
4691 FastTrack *fastTrack = &state->mFastTracks[0];
4692 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
4693 delete fastTrack->mBufferProvider;
4694 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004695 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08004696#ifdef AUDIO_WATCHDOG
4697 if (mAudioWatchdog != 0) {
4698 mAudioWatchdog->requestExit();
4699 mAudioWatchdog->requestExitAndWait();
4700 mAudioWatchdog.clear();
4701 }
4702#endif
4703 }
Glenn Kasten9e58b552013-01-18 15:09:48 -08004704 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08004705 delete mAudioMixer;
4706}
4707
4708
4709uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
4710{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004711 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004712 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
4713 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
4714 }
4715 return latency;
4716}
4717
Eric Laurentbfb1b832013-01-07 09:53:42 -08004718ssize_t AudioFlinger::MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08004719{
4720 // FIXME we should only do one push per cycle; confirm this is true
4721 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004722 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004723 FastMixerStateQueue *sq = mFastMixer->sq();
4724 FastMixerState *state = sq->begin();
4725 if (state->mCommand != FastMixerState::MIX_WRITE &&
4726 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
4727 if (state->mCommand == FastMixerState::COLD_IDLE) {
Eric Laurenta2ab4502015-09-09 12:25:51 -07004728
4729 // FIXME workaround for first HAL write being CPU bound on some devices
4730 ATRACE_BEGIN("write");
4731 mOutput->write((char *)mSinkBuffer, 0);
4732 ATRACE_END();
4733
Eric Laurent81784c32012-11-19 14:55:58 -08004734 int32_t old = android_atomic_inc(&mFastMixerFutex);
4735 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07004736 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08004737 }
4738#ifdef AUDIO_WATCHDOG
4739 if (mAudioWatchdog != 0) {
4740 mAudioWatchdog->resume();
4741 }
4742#endif
4743 }
4744 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kastend797a9d2015-03-02 14:19:25 -08004745#ifdef FAST_THREAD_STATISTICS
Glenn Kasten4182c4e2013-07-15 14:45:07 -07004746 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08004747 FastThreadDumpState::kSamplingNforLowRamDevice : FastThreadDumpState::kSamplingN);
Glenn Kastend797a9d2015-03-02 14:19:25 -08004748#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004749 sq->end();
4750 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
4751 if (kUseFastMixer == FastMixer_Dynamic) {
4752 mNormalSink = mPipeSink;
4753 }
4754 } else {
4755 sq->end(false /*didModify*/);
4756 }
4757 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004758 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08004759}
4760
4761void AudioFlinger::MixerThread::threadLoop_standby()
4762{
4763 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004764 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004765 FastMixerStateQueue *sq = mFastMixer->sq();
4766 FastMixerState *state = sq->begin();
4767 if (!(state->mCommand & FastMixerState::IDLE)) {
Andy Hung2148bf02016-11-28 19:01:02 -08004768 // Report any frames trapped in the Monopipe
4769 MonoPipe *monoPipe = (MonoPipe *)mPipeSink.get();
4770 const long long pipeFrames = monoPipe->maxFrames() - monoPipe->availableToWrite();
4771 mLocalLog.log("threadLoop_standby: framesWritten:%lld suspendedFrames:%lld "
4772 "monoPipeWritten:%lld monoPipeLeft:%lld",
4773 (long long)mFramesWritten, (long long)mSuspendedFrames,
4774 (long long)mPipeSink->framesWritten(), pipeFrames);
4775 mLocalLog.log("threadLoop_standby: %s", mTimestamp.toString().c_str());
4776
Eric Laurent81784c32012-11-19 14:55:58 -08004777 state->mCommand = FastMixerState::COLD_IDLE;
4778 state->mColdFutexAddr = &mFastMixerFutex;
4779 state->mColdGen++;
4780 mFastMixerFutex = 0;
4781 sq->end();
4782 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
4783 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
4784 if (kUseFastMixer == FastMixer_Dynamic) {
4785 mNormalSink = mOutputSink;
4786 }
4787#ifdef AUDIO_WATCHDOG
4788 if (mAudioWatchdog != 0) {
4789 mAudioWatchdog->pause();
4790 }
4791#endif
4792 } else {
4793 sq->end(false /*didModify*/);
4794 }
4795 }
4796 PlaybackThread::threadLoop_standby();
4797}
4798
Eric Laurentbfb1b832013-01-07 09:53:42 -08004799bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
4800{
4801 return false;
4802}
4803
4804bool AudioFlinger::PlaybackThread::shouldStandby_l()
4805{
4806 return !mStandby;
4807}
4808
4809bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
4810{
4811 Mutex::Autolock _l(mLock);
4812 return waitingAsyncCallback_l();
4813}
4814
Eric Laurent81784c32012-11-19 14:55:58 -08004815// shared by MIXER and DIRECT, overridden by DUPLICATING
4816void AudioFlinger::PlaybackThread::threadLoop_standby()
4817{
4818 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
Phil Burk062e67a2015-02-11 13:40:50 -08004819 mOutput->standby();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004820 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004821 // discard any pending drain or write ack by incrementing sequence
4822 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
4823 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004824 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004825 mCallbackThread->setWriteBlocked(mWriteAckSequence);
4826 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004827 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08004828 mHwPaused = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004829}
4830
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08004831void AudioFlinger::PlaybackThread::onAddNewTrack_l()
4832{
4833 ALOGV("signal playback thread");
4834 broadcast_l();
4835}
4836
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07004837void AudioFlinger::PlaybackThread::onAsyncError()
4838{
4839 for (int i = AUDIO_STREAM_SYSTEM; i < (int)AUDIO_STREAM_CNT; i++) {
4840 invalidateTracks((audio_stream_type_t)i);
4841 }
4842}
4843
Eric Laurent81784c32012-11-19 14:55:58 -08004844void AudioFlinger::MixerThread::threadLoop_mix()
4845{
Eric Laurent81784c32012-11-19 14:55:58 -08004846 // mix buffers...
Glenn Kastend79072e2016-01-06 08:41:20 -08004847 mAudioMixer->process();
Andy Hung25c2dac2014-02-27 14:56:00 -08004848 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004849 // increase sleep time progressively when application underrun condition clears.
4850 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
4851 // that a steady state of alternating ready/not ready conditions keeps the sleep time
4852 // such that we would underrun the audio HAL.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004853 if ((mSleepTimeUs == 0) && (sleepTimeShift > 0)) {
Eric Laurent81784c32012-11-19 14:55:58 -08004854 sleepTimeShift--;
4855 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004856 mSleepTimeUs = 0;
4857 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08004858 //TODO: delay standby when effects have a tail
Glenn Kasten4c053ea2014-09-28 14:41:07 -07004859
Eric Laurent81784c32012-11-19 14:55:58 -08004860}
4861
4862void AudioFlinger::MixerThread::threadLoop_sleepTime()
4863{
4864 // If no tracks are ready, sleep once for the duration of an output
4865 // buffer size, then write 0s to the output
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004866 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004867 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Andy Hung06d13222018-05-03 20:13:31 -07004868 if (mPipeSink.get() != nullptr && mPipeSink == mNormalSink) {
4869 // Using the Monopipe availableToWrite, we estimate the
4870 // sleep time to retry for more data (before we underrun).
4871 MonoPipe *monoPipe = static_cast<MonoPipe *>(mPipeSink.get());
4872 const ssize_t availableToWrite = mPipeSink->availableToWrite();
4873 const size_t pipeFrames = monoPipe->maxFrames();
4874 const size_t framesLeft = pipeFrames - max(availableToWrite, 0);
4875 // HAL_framecount <= framesDelay ~ framesLeft / 2 <= Normal_Mixer_framecount
4876 const size_t framesDelay = std::min(
4877 mNormalFrameCount, max(framesLeft / 2, mFrameCount));
4878 ALOGV("pipeFrames:%zu framesLeft:%zu framesDelay:%zu",
4879 pipeFrames, framesLeft, framesDelay);
4880 mSleepTimeUs = framesDelay * MICROS_PER_SECOND / mSampleRate;
4881 } else {
4882 mSleepTimeUs = mActiveSleepTimeUs >> sleepTimeShift;
4883 if (mSleepTimeUs < kMinThreadSleepTimeUs) {
4884 mSleepTimeUs = kMinThreadSleepTimeUs;
4885 }
4886 // reduce sleep time in case of consecutive application underruns to avoid
4887 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
4888 // duration we would end up writing less data than needed by the audio HAL if
4889 // the condition persists.
4890 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
4891 sleepTimeShift++;
4892 }
Eric Laurent81784c32012-11-19 14:55:58 -08004893 }
4894 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004895 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08004896 }
4897 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08004898 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
4899 // before effects processing or output.
4900 if (mMixerBufferValid) {
4901 memset(mMixerBuffer, 0, mMixerBufferSize);
4902 } else {
4903 memset(mSinkBuffer, 0, mSinkBufferSize);
4904 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004905 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08004906 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
4907 "anticipated start");
4908 }
4909 // TODO add standby time extension fct of effect tail
4910}
4911
4912// prepareTracks_l() must be called with ThreadBase::mLock held
4913AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
4914 Vector< sp<Track> > *tracksToRemove)
4915{
Andy Hungc0691382018-09-12 18:01:57 -07004916 // clean up deleted track ids in AudioMixer before allocating new tracks
4917 (void)mTracks.processDeletedTrackIds([this](int trackId) {
4918 // for each trackId, destroy it in the AudioMixer
4919 if (mAudioMixer->exists(trackId)) {
4920 mAudioMixer->destroy(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08004921 }
4922 });
Andy Hungc0691382018-09-12 18:01:57 -07004923 mTracks.clearDeletedTrackIds();
Eric Laurent81784c32012-11-19 14:55:58 -08004924
4925 mixer_state mixerStatus = MIXER_IDLE;
4926 // find out which tracks need to be processed
4927 size_t count = mActiveTracks.size();
4928 size_t mixedTracks = 0;
4929 size_t tracksWithEffect = 0;
4930 // counts only _active_ fast tracks
4931 size_t fastTracks = 0;
4932 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
4933
4934 float masterVolume = mMasterVolume;
4935 bool masterMute = mMasterMute;
4936
4937 if (masterMute) {
4938 masterVolume = 0;
4939 }
4940 // Delegate master volume control to effect in output mix effect chain if needed
4941 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
4942 if (chain != 0) {
4943 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
4944 chain->setVolume_l(&v, &v);
4945 masterVolume = (float)((v + (1 << 23)) >> 24);
4946 chain.clear();
4947 }
4948
4949 // prepare a new state to push
4950 FastMixerStateQueue *sq = NULL;
4951 FastMixerState *state = NULL;
4952 bool didModify = false;
4953 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Andy Hungf2285312017-02-14 18:31:59 -08004954 bool coldIdle = false;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004955 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004956 sq = mFastMixer->sq();
4957 state = sq->begin();
Andy Hungf2285312017-02-14 18:31:59 -08004958 coldIdle = state->mCommand == FastMixerState::COLD_IDLE;
Eric Laurent81784c32012-11-19 14:55:58 -08004959 }
4960
Andy Hung69aed5f2014-02-25 17:24:40 -08004961 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08004962 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08004963
Andy Hungbd3b2b02018-05-21 10:53:11 -07004964 // DeferredOperations handles statistics after setting mixerStatus.
4965 class DeferredOperations {
4966 public:
Andy Hungea840382020-05-05 21:50:17 -07004967 DeferredOperations(mixer_state *mixerStatus, ThreadMetrics *threadMetrics)
4968 : mMixerStatus(mixerStatus)
4969 , mThreadMetrics(threadMetrics) {}
Andy Hungbd3b2b02018-05-21 10:53:11 -07004970
4971 // when leaving scope, tally frames properly.
4972 ~DeferredOperations() {
4973 // Tally underrun frames only if we are actually mixing (MIXER_TRACKS_READY)
4974 // because that is when the underrun occurs.
4975 // We do not distinguish between FastTracks and NormalTracks here.
Andy Hungea840382020-05-05 21:50:17 -07004976 size_t maxUnderrunFrames = 0;
Andy Hungb68f5eb2019-12-03 16:49:17 -08004977 if (*mMixerStatus == MIXER_TRACKS_READY && mUnderrunFrames.size() > 0) {
Andy Hungbd3b2b02018-05-21 10:53:11 -07004978 for (const auto &underrun : mUnderrunFrames) {
Andy Hungc2b11cb2020-04-22 09:04:01 -07004979 underrun.first->tallyUnderrunFrames(underrun.second);
Andy Hungea840382020-05-05 21:50:17 -07004980 maxUnderrunFrames = max(underrun.second, maxUnderrunFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07004981 }
4982 }
Andy Hungea840382020-05-05 21:50:17 -07004983 // send the max underrun frames for this mixer period
4984 mThreadMetrics->logUnderrunFrames(maxUnderrunFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07004985 }
4986
4987 // tallyUnderrunFrames() is called to update the track counters
4988 // with the number of underrun frames for a particular mixer period.
4989 // We defer tallying until we know the final mixer status.
4990 void tallyUnderrunFrames(sp<Track> track, size_t underrunFrames) {
4991 mUnderrunFrames.emplace_back(track, underrunFrames);
4992 }
4993
4994 private:
4995 const mixer_state * const mMixerStatus;
Andy Hungea840382020-05-05 21:50:17 -07004996 ThreadMetrics * const mThreadMetrics;
Andy Hungbd3b2b02018-05-21 10:53:11 -07004997 std::vector<std::pair<sp<Track>, size_t>> mUnderrunFrames;
Andy Hungea840382020-05-05 21:50:17 -07004998 } deferredOperations(&mixerStatus, &mThreadMetrics);
Andy Hungb68f5eb2019-12-03 16:49:17 -08004999 // implicit nested scope for variable capture
Andy Hungbd3b2b02018-05-21 10:53:11 -07005000
jiabin245cdd92018-12-07 17:55:15 -08005001 bool noFastHapticTrack = true;
Eric Laurent81784c32012-11-19 14:55:58 -08005002 for (size_t i=0 ; i<count ; i++) {
Andy Hungdae27702016-10-31 14:01:16 -07005003 const sp<Track> t = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08005004
5005 // this const just means the local variable doesn't change
5006 Track* const track = t.get();
5007
5008 // process fast tracks
5009 if (track->isFastTrack()) {
Andy Hungae22b482019-05-09 15:38:55 -07005010 LOG_ALWAYS_FATAL_IF(mFastMixer.get() == nullptr,
5011 "%s(%d): FastTrack(%d) present without FastMixer",
5012 __func__, id(), track->id());
5013
jiabin245cdd92018-12-07 17:55:15 -08005014 if (track->getHapticPlaybackEnabled()) {
5015 noFastHapticTrack = false;
5016 }
Eric Laurent81784c32012-11-19 14:55:58 -08005017
5018 // It's theoretically possible (though unlikely) for a fast track to be created
5019 // and then removed within the same normal mix cycle. This is not a problem, as
5020 // the track never becomes active so it's fast mixer slot is never touched.
5021 // The converse, of removing an (active) track and then creating a new track
5022 // at the identical fast mixer slot within the same normal mix cycle,
5023 // is impossible because the slot isn't marked available until the end of each cycle.
5024 int j = track->mFastIndex;
Glenn Kastendc2c50b2016-04-21 08:13:14 -07005025 ALOG_ASSERT(0 < j && j < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08005026 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
5027 FastTrack *fastTrack = &state->mFastTracks[j];
5028
5029 // Determine whether the track is currently in underrun condition,
5030 // and whether it had a recent underrun.
5031 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
5032 FastTrackUnderruns underruns = ftDump->mUnderruns;
5033 uint32_t recentFull = (underruns.mBitFields.mFull -
5034 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
5035 uint32_t recentPartial = (underruns.mBitFields.mPartial -
5036 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
5037 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
5038 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
5039 uint32_t recentUnderruns = recentPartial + recentEmpty;
5040 track->mObservedUnderruns = underruns;
5041 // don't count underruns that occur while stopping or pausing
5042 // or stopped which can occur when flush() is called while active
Andy Hungbd3b2b02018-05-21 10:53:11 -07005043 size_t underrunFrames = 0;
Glenn Kasten82aaf942013-07-17 16:05:07 -07005044 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
5045 recentUnderruns > 0) {
5046 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
Andy Hungbd3b2b02018-05-21 10:53:11 -07005047 underrunFrames = recentUnderruns * mFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08005048 }
Andy Hungbd3b2b02018-05-21 10:53:11 -07005049 // Immediately account for FastTrack underruns.
5050 track->mAudioTrackServerProxy->tallyUnderrunFrames(underrunFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08005051
5052 // This is similar to the state machine for normal tracks,
5053 // with a few modifications for fast tracks.
5054 bool isActive = true;
5055 switch (track->mState) {
5056 case TrackBase::STOPPING_1:
5057 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08005058 if (recentUnderruns > 0 || track->isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -08005059 track->mState = TrackBase::STOPPING_2;
5060 }
5061 break;
5062 case TrackBase::PAUSING:
5063 // ramp down is not yet implemented
5064 track->setPaused();
5065 break;
5066 case TrackBase::RESUMING:
5067 // ramp up is not yet implemented
5068 track->mState = TrackBase::ACTIVE;
5069 break;
5070 case TrackBase::ACTIVE:
5071 if (recentFull > 0 || recentPartial > 0) {
5072 // track has provided at least some frames recently: reset retry count
5073 track->mRetryCount = kMaxTrackRetries;
5074 }
5075 if (recentUnderruns == 0) {
5076 // no recent underruns: stay active
5077 break;
5078 }
5079 // there has recently been an underrun of some kind
5080 if (track->sharedBuffer() == 0) {
5081 // were any of the recent underruns "empty" (no frames available)?
5082 if (recentEmpty == 0) {
5083 // no, then ignore the partial underruns as they are allowed indefinitely
5084 break;
5085 }
5086 // there has recently been an "empty" underrun: decrement the retry counter
5087 if (--(track->mRetryCount) > 0) {
5088 break;
5089 }
5090 // indicate to client process that the track was disabled because of underrun;
5091 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08005092 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08005093 // remove from active list, but state remains ACTIVE [confusing but true]
5094 isActive = false;
5095 break;
5096 }
Chih-Hung Hsieh2b487032018-09-13 14:16:02 -07005097 FALLTHROUGH_INTENDED;
Eric Laurent81784c32012-11-19 14:55:58 -08005098 case TrackBase::STOPPING_2:
5099 case TrackBase::PAUSED:
Eric Laurent81784c32012-11-19 14:55:58 -08005100 case TrackBase::STOPPED:
5101 case TrackBase::FLUSHED: // flush() while active
5102 // Check for presentation complete if track is inactive
5103 // We have consumed all the buffers of this track.
5104 // This would be incomplete if we auto-paused on underrun
5105 {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005106 uint32_t latency = 0;
5107 status_t result = mOutput->stream->getLatency(&latency);
5108 ALOGE_IF(result != OK,
5109 "Error when retrieving output stream latency: %d", result);
5110 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08005111 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005112 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
5113 // track stays in active list until presentation is complete
5114 break;
5115 }
5116 }
5117 if (track->isStopping_2()) {
5118 track->mState = TrackBase::STOPPED;
5119 }
5120 if (track->isStopped()) {
5121 // Can't reset directly, as fast mixer is still polling this track
5122 // track->reset();
5123 // So instead mark this track as needing to be reset after push with ack
5124 resetMask |= 1 << i;
5125 }
5126 isActive = false;
5127 break;
5128 case TrackBase::IDLE:
5129 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08005130 LOG_ALWAYS_FATAL("unexpected track state %d", track->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08005131 }
5132
5133 if (isActive) {
5134 // was it previously inactive?
5135 if (!(state->mTrackMask & (1 << j))) {
5136 ExtendedAudioBufferProvider *eabp = track;
5137 VolumeProvider *vp = track;
5138 fastTrack->mBufferProvider = eabp;
5139 fastTrack->mVolumeProvider = vp;
Eric Laurent81784c32012-11-19 14:55:58 -08005140 fastTrack->mChannelMask = track->mChannelMask;
Andy Hunge8a1ced2014-05-09 15:02:21 -07005141 fastTrack->mFormat = track->mFormat;
jiabin245cdd92018-12-07 17:55:15 -08005142 fastTrack->mHapticPlaybackEnabled = track->getHapticPlaybackEnabled();
jiabin77270b82018-12-18 15:41:29 -08005143 fastTrack->mHapticIntensity = track->getHapticIntensity();
Lais Andradebc3f37a2021-07-02 00:13:19 +01005144 fastTrack->mHapticMaxAmplitude = track->getHapticMaxAmplitude();
Eric Laurent81784c32012-11-19 14:55:58 -08005145 fastTrack->mGeneration++;
5146 state->mTrackMask |= 1 << j;
5147 didModify = true;
5148 // no acknowledgement required for newly active tracks
5149 }
Kevin Rocard12381092018-04-11 09:19:59 -07005150 sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
Eric Laurenteab90452019-06-24 15:17:46 -07005151 float volume;
5152 if (track->isPlaybackRestricted() || mStreamTypes[track->streamType()].mute) {
5153 volume = 0.f;
5154 } else {
5155 volume = masterVolume * mStreamTypes[track->streamType()].volume;
5156 }
5157
5158 handleVoipVolume_l(&volume);
5159
Eric Laurent81784c32012-11-19 14:55:58 -08005160 // cache the combined master volume and stream type volume for fast mixer; this
5161 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005162 const float vh = track->getVolumeHandler()->getVolume(
Eric Laurenteab90452019-06-24 15:17:46 -07005163 proxy->framesReleased()).first;
5164 volume *= vh;
Kevin Rocardb0eeaf122018-04-11 08:30:16 -07005165 track->mCachedVolume = volume;
Kevin Rocard12381092018-04-11 09:19:59 -07005166 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
5167 float vlf = volume * float_from_gain(gain_minifloat_unpack_left(vlr));
5168 float vrf = volume * float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurenteab90452019-06-24 15:17:46 -07005169
Kevin Rocard12381092018-04-11 09:19:59 -07005170 track->setFinalVolume((vlf + vrf) / 2.f);
Eric Laurent81784c32012-11-19 14:55:58 -08005171 ++fastTracks;
5172 } else {
5173 // was it previously active?
5174 if (state->mTrackMask & (1 << j)) {
5175 fastTrack->mBufferProvider = NULL;
5176 fastTrack->mGeneration++;
5177 state->mTrackMask &= ~(1 << j);
5178 didModify = true;
5179 // If any fast tracks were removed, we must wait for acknowledgement
5180 // because we're about to decrement the last sp<> on those tracks.
5181 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
5182 } else {
Glenn Kastenbf848af2017-12-22 11:55:01 -08005183 // ALOGW rather than LOG_ALWAYS_FATAL because it seems there are cases where an
5184 // AudioTrack may start (which may not be with a start() but with a write()
5185 // after underrun) and immediately paused or released. In that case the
5186 // FastTrack state hasn't had time to update.
5187 // TODO Remove the ALOGW when this theory is confirmed.
5188 ALOGW("fast track %d should have been active; "
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08005189 "mState=%d, mTrackMask=%#x, recentUnderruns=%u, isShared=%d",
5190 j, track->mState, state->mTrackMask, recentUnderruns,
5191 track->sharedBuffer() != 0);
Glenn Kastenbf848af2017-12-22 11:55:01 -08005192 // Since the FastMixer state already has the track inactive, do nothing here.
Eric Laurent81784c32012-11-19 14:55:58 -08005193 }
5194 tracksToRemove->add(track);
5195 // Avoids a misleading display in dumpsys
5196 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
5197 }
jiabin245cdd92018-12-07 17:55:15 -08005198 if (fastTrack->mHapticPlaybackEnabled != track->getHapticPlaybackEnabled()) {
5199 fastTrack->mHapticPlaybackEnabled = track->getHapticPlaybackEnabled();
5200 didModify = true;
5201 }
Eric Laurent81784c32012-11-19 14:55:58 -08005202 continue;
5203 }
5204
5205 { // local variable scope to avoid goto warning
5206
5207 audio_track_cblk_t* cblk = track->cblk();
5208
5209 // The first time a track is added we wait
5210 // for all its buffers to be filled before processing it
Andy Hungc0691382018-09-12 18:01:57 -07005211 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08005212
5213 // if an active track doesn't exist in the AudioMixer, create it.
Andy Hungc0691382018-09-12 18:01:57 -07005214 // use the trackId as the AudioMixer name.
5215 if (!mAudioMixer->exists(trackId)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08005216 status_t status = mAudioMixer->create(
Andy Hungc0691382018-09-12 18:01:57 -07005217 trackId,
Andy Hung1bc088a2018-02-09 15:57:31 -08005218 track->mChannelMask,
5219 track->mFormat,
5220 track->mSessionId);
5221 if (status != OK) {
Andy Hungc0691382018-09-12 18:01:57 -07005222 ALOGW("%s(): AudioMixer cannot create track(%d)"
5223 " mask %#x, format %#x, sessionId %d",
5224 __func__, trackId,
5225 track->mChannelMask, track->mFormat, track->mSessionId);
Andy Hung1bc088a2018-02-09 15:57:31 -08005226 tracksToRemove->add(track);
5227 track->invalidate(); // consider it dead.
5228 continue;
5229 }
5230 }
5231
Eric Laurent81784c32012-11-19 14:55:58 -08005232 // make sure that we have enough frames to mix one full buffer.
5233 // enforce this condition only once to enable draining the buffer in case the client
5234 // app does not call stop() and relies on underrun to stop:
5235 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
5236 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005237 size_t desiredFrames;
Andy Hung8edb8dc2015-03-26 19:13:55 -07005238 const uint32_t sampleRate = track->mAudioTrackServerProxy->getSampleRate();
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07005239 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07005240
5241 desiredFrames = sourceFramesNeededWithTimestretch(
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07005242 sampleRate, mNormalFrameCount, mSampleRate, playbackRate.mSpeed);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005243 // TODO: ONLY USED FOR LEGACY RESAMPLERS, remove when they are removed.
5244 // add frames already consumed but not yet released by the resampler
5245 // because mAudioTrackServerProxy->framesReady() will include these frames
Andy Hungc0691382018-09-12 18:01:57 -07005246 desiredFrames += mAudioMixer->getUnreleasedFrames(trackId);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005247
Eric Laurent81784c32012-11-19 14:55:58 -08005248 uint32_t minFrames = 1;
5249 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
5250 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005251 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08005252 }
Eric Laurent13e4c962013-12-20 17:36:01 -08005253
5254 size_t framesReady = track->framesReady();
Glenn Kastene7754022014-10-31 12:11:26 -07005255 if (ATRACE_ENABLED()) {
5256 // I wish we had formatted trace names
Andy Hung1bc088a2018-02-09 15:57:31 -08005257 std::string traceName("nRdy");
Andy Hungc0691382018-09-12 18:01:57 -07005258 traceName += std::to_string(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08005259 ATRACE_INT(traceName.c_str(), framesReady);
Glenn Kastene7754022014-10-31 12:11:26 -07005260 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005261 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08005262 !track->isPaused() && !track->isTerminated())
5263 {
Andy Hungc0691382018-09-12 18:01:57 -07005264 ALOGVV("track(%d) s=%08x [OK] on thread %p", trackId, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08005265
5266 mixedTracks++;
5267
Andy Hung69aed5f2014-02-25 17:24:40 -08005268 // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
5269 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08005270 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08005271 if (track->mainBuffer() != mSinkBuffer &&
5272 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08005273 if (mEffectBufferEnabled) {
5274 mEffectBufferValid = true; // Later can set directly.
5275 }
Eric Laurent81784c32012-11-19 14:55:58 -08005276 chain = getEffectChain_l(track->sessionId());
5277 // Delegate volume control to effect in track effect chain if needed
5278 if (chain != 0) {
5279 tracksWithEffect++;
5280 } else {
Andy Hungc0691382018-09-12 18:01:57 -07005281 ALOGW("prepareTracks_l(): track(%d) attached to effect but no chain found on "
Eric Laurent81784c32012-11-19 14:55:58 -08005282 "session %d",
Andy Hungc0691382018-09-12 18:01:57 -07005283 trackId, track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08005284 }
5285 }
5286
5287
5288 int param = AudioMixer::VOLUME;
5289 if (track->mFillingUpStatus == Track::FS_FILLED) {
5290 // no ramp for the first volume setting
5291 track->mFillingUpStatus = Track::FS_ACTIVE;
5292 if (track->mState == TrackBase::RESUMING) {
5293 track->mState = TrackBase::ACTIVE;
Revathi Uddaraju453bcb52017-08-14 14:19:40 +08005294 // If a new track is paused immediately after start, do not ramp on resume.
5295 if (cblk->mServer != 0) {
5296 param = AudioMixer::RAMP_VOLUME;
5297 }
Eric Laurent81784c32012-11-19 14:55:58 -08005298 }
Andy Hungc0691382018-09-12 18:01:57 -07005299 mAudioMixer->setParameter(trackId, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Eric Laurent7c29ec92017-09-20 17:54:22 -07005300 mLeftVolFloat = -1.0;
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005301 // FIXME should not make a decision based on mServer
5302 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005303 // If the track is stopped before the first frame was mixed,
5304 // do not apply ramp
5305 param = AudioMixer::RAMP_VOLUME;
5306 }
5307
5308 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07005309 uint32_t vl, vr; // in U8.24 integer format
5310 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Eric Laurent7c29ec92017-09-20 17:54:22 -07005311 // read original volumes with volume control
Eric Laurenteab90452019-06-24 15:17:46 -07005312 float v = masterVolume * mStreamTypes[track->streamType()].volume;
Andy Hung333ab962019-05-28 20:23:35 -07005313 // Always fetch volumeshaper volume to ensure state is updated.
5314 const sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
5315 const float vh = track->getVolumeHandler()->getVolume(
5316 track->mAudioTrackServerProxy->framesReleased()).first;
Eric Laurent7c29ec92017-09-20 17:54:22 -07005317
Eric Laurenteab90452019-06-24 15:17:46 -07005318 if (mStreamTypes[track->streamType()].mute || track->isPlaybackRestricted()) {
5319 v = 0;
5320 }
5321
5322 handleVoipVolume_l(&v);
5323
5324 if (track->isPausing()) {
Andy Hung6be49402014-05-30 10:42:03 -07005325 vl = vr = 0;
5326 vlf = vrf = vaf = 0.;
Eric Laurenteab90452019-06-24 15:17:46 -07005327 track->setPaused();
Eric Laurent81784c32012-11-19 14:55:58 -08005328 } else {
Glenn Kastenc56f3422014-03-21 17:53:17 -07005329 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07005330 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
5331 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08005332 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07005333 if (vlf > GAIN_FLOAT_UNITY) {
5334 ALOGV("Track left volume out of range: %.3g", vlf);
5335 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08005336 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07005337 if (vrf > GAIN_FLOAT_UNITY) {
5338 ALOGV("Track right volume out of range: %.3g", vrf);
5339 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08005340 }
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005341 // now apply the master volume and stream type volume and shaper volume
5342 vlf *= v * vh;
5343 vrf *= v * vh;
Eric Laurent81784c32012-11-19 14:55:58 -08005344 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07005345 // then derive vl and vr as U8.24 versions for the effect chain
5346 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
5347 vl = (uint32_t) (scaleto8_24 * vlf);
5348 vr = (uint32_t) (scaleto8_24 * vrf);
5349 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08005350 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08005351 // send level comes from shared memory and so may be corrupt
5352 if (sendLevel > MAX_GAIN_INT) {
5353 ALOGV("Track send level out of range: %04X", sendLevel);
5354 sendLevel = MAX_GAIN_INT;
5355 }
Andy Hung6be49402014-05-30 10:42:03 -07005356 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
5357 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08005358 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005359
Kevin Rocard12381092018-04-11 09:19:59 -07005360 track->setFinalVolume((vrf + vlf) / 2.f);
5361
Eric Laurent81784c32012-11-19 14:55:58 -08005362 // Delegate volume control to effect in track effect chain if needed
5363 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
5364 // Do not ramp volume if volume is controlled by effect
5365 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08005366 // Update remaining floating point volume levels
5367 vlf = (float)vl / (1 << 24);
5368 vrf = (float)vr / (1 << 24);
Eric Laurent81784c32012-11-19 14:55:58 -08005369 track->mHasVolumeController = true;
5370 } else {
5371 // force no volume ramp when volume controller was just disabled or removed
5372 // from effect chain to avoid volume spike
5373 if (track->mHasVolumeController) {
5374 param = AudioMixer::VOLUME;
5375 }
5376 track->mHasVolumeController = false;
5377 }
5378
Eric Laurent81784c32012-11-19 14:55:58 -08005379 // XXX: these things DON'T need to be done each time
Andy Hungc0691382018-09-12 18:01:57 -07005380 mAudioMixer->setBufferProvider(trackId, track);
5381 mAudioMixer->enable(trackId);
Eric Laurent81784c32012-11-19 14:55:58 -08005382
Andy Hungc0691382018-09-12 18:01:57 -07005383 mAudioMixer->setParameter(trackId, param, AudioMixer::VOLUME0, &vlf);
5384 mAudioMixer->setParameter(trackId, param, AudioMixer::VOLUME1, &vrf);
5385 mAudioMixer->setParameter(trackId, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08005386 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005387 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005388 AudioMixer::TRACK,
5389 AudioMixer::FORMAT, (void *)track->format());
5390 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005391 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005392 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00005393 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Andy Hung9a592762014-07-21 21:56:01 -07005394 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005395 trackId,
Andy Hung9a592762014-07-21 21:56:01 -07005396 AudioMixer::TRACK,
jiabin245cdd92018-12-07 17:55:15 -08005397 AudioMixer::MIXER_CHANNEL_MASK,
Eric Laurentf1f22e72021-07-13 14:04:14 +02005398 (void *)(uintptr_t)(mMixerChannelMask | mHapticChannelMask));
Glenn Kastene3aa6592012-12-04 12:22:46 -08005399 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07005400 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Andy Hung333ab962019-05-28 20:23:35 -07005401 uint32_t reqSampleRate = proxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08005402 if (reqSampleRate == 0) {
5403 reqSampleRate = mSampleRate;
5404 } else if (reqSampleRate > maxSampleRate) {
5405 reqSampleRate = maxSampleRate;
5406 }
Eric Laurent81784c32012-11-19 14:55:58 -08005407 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005408 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005409 AudioMixer::RESAMPLE,
5410 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00005411 (void *)(uintptr_t)reqSampleRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005412
Andy Hung333ab962019-05-28 20:23:35 -07005413 AudioPlaybackRate playbackRate = proxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07005414 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005415 trackId,
Andy Hung8edb8dc2015-03-26 19:13:55 -07005416 AudioMixer::TIMESTRETCH,
5417 AudioMixer::PLAYBACK_RATE,
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07005418 &playbackRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005419
Andy Hung69aed5f2014-02-25 17:24:40 -08005420 /*
5421 * Select the appropriate output buffer for the track.
5422 *
Andy Hung98ef9782014-03-04 14:46:50 -08005423 * Tracks with effects go into their own effects chain buffer
5424 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08005425 *
5426 * Other tracks can use mMixerBuffer for higher precision
5427 * channel accumulation. If this buffer is enabled
5428 * (mMixerBufferEnabled true), then selected tracks will accumulate
5429 * into it.
5430 *
5431 */
5432 if (mMixerBufferEnabled
5433 && (track->mainBuffer() == mSinkBuffer
5434 || track->mainBuffer() == mMixerBuffer)) {
5435 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005436 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08005437 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08005438 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
Andy Hung69aed5f2014-02-25 17:24:40 -08005439 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005440 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08005441 AudioMixer::TRACK,
5442 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
5443 // TODO: override track->mainBuffer()?
5444 mMixerBufferValid = true;
5445 } else {
5446 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005447 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08005448 AudioMixer::TRACK,
rago94a1ee82017-07-21 15:11:02 -07005449 AudioMixer::MIXER_FORMAT, (void *)EFFECT_BUFFER_FORMAT);
Andy Hung69aed5f2014-02-25 17:24:40 -08005450 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005451 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08005452 AudioMixer::TRACK,
5453 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
5454 }
Eric Laurent81784c32012-11-19 14:55:58 -08005455 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005456 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005457 AudioMixer::TRACK,
5458 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
jiabin245cdd92018-12-07 17:55:15 -08005459 mAudioMixer->setParameter(
5460 trackId,
5461 AudioMixer::TRACK,
5462 AudioMixer::HAPTIC_ENABLED, (void *)(uintptr_t)track->getHapticPlaybackEnabled());
jiabin77270b82018-12-18 15:41:29 -08005463 mAudioMixer->setParameter(
5464 trackId,
5465 AudioMixer::TRACK,
5466 AudioMixer::HAPTIC_INTENSITY, (void *)(uintptr_t)track->getHapticIntensity());
Lais Andradebc3f37a2021-07-02 00:13:19 +01005467 mAudioMixer->setParameter(
5468 trackId,
5469 AudioMixer::TRACK,
5470 AudioMixer::HAPTIC_MAX_AMPLITUDE, (void *)(&(track->mHapticMaxAmplitude)));
Eric Laurent81784c32012-11-19 14:55:58 -08005471
5472 // reset retry count
5473 track->mRetryCount = kMaxTrackRetries;
5474
5475 // If one track is ready, set the mixer ready if:
5476 // - the mixer was not ready during previous round OR
5477 // - no other track is not ready
5478 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
5479 mixerStatus != MIXER_TRACKS_ENABLED) {
5480 mixerStatus = MIXER_TRACKS_READY;
5481 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08005482
5483 // Enable the next few lines to instrument a test for underrun log handling.
5484 // TODO: Remove when we have a better way of testing the underrun log.
5485#if 0
5486 static int i;
5487 if ((++i & 0xf) == 0) {
5488 deferredOperations.tallyUnderrunFrames(track, 10 /* underrunFrames */);
5489 }
5490#endif
Eric Laurent81784c32012-11-19 14:55:58 -08005491 } else {
Andy Hungbd3b2b02018-05-21 10:53:11 -07005492 size_t underrunFrames = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005493 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Andy Hungb68f5eb2019-12-03 16:49:17 -08005494 ALOGV("track(%d) underrun, track state %s framesReady(%zu) < framesDesired(%zd)",
5495 trackId, track->getTrackStateAsString(), framesReady, desiredFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07005496 underrunFrames = desiredFrames;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005497 }
Andy Hungbd3b2b02018-05-21 10:53:11 -07005498 deferredOperations.tallyUnderrunFrames(track, underrunFrames);
Phil Burk2812d9e2016-01-04 10:34:30 -08005499
Eric Laurent81784c32012-11-19 14:55:58 -08005500 // clear effect chain input buffer if an active track underruns to avoid sending
5501 // previous audio buffer again to effects
5502 chain = getEffectChain_l(track->sessionId());
5503 if (chain != 0) {
5504 chain->clearInputBuffer();
5505 }
5506
Andy Hungc0691382018-09-12 18:01:57 -07005507 ALOGVV("track(%d) s=%08x [NOT READY] on thread %p", trackId, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08005508 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
5509 track->isStopped() || track->isPaused()) {
5510 // We have consumed all the buffers of this track.
5511 // Remove it from the list of active tracks.
5512 // TODO: use actual buffer filling status instead of latency when available from
5513 // audio HAL
5514 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08005515 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005516 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
5517 if (track->isStopped()) {
5518 track->reset();
5519 }
5520 tracksToRemove->add(track);
5521 }
5522 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08005523 // No buffers for this track. Give it a few chances to
5524 // fill a buffer, then remove it from active list.
5525 if (--(track->mRetryCount) <= 0) {
Andy Hungc0691382018-09-12 18:01:57 -07005526 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p",
5527 trackId, this);
Eric Laurent81784c32012-11-19 14:55:58 -08005528 tracksToRemove->add(track);
5529 // indicate to client process that the track was disabled because of underrun;
5530 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08005531 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08005532 // If one track is not ready, mark the mixer also not ready if:
5533 // - the mixer was ready during previous round OR
5534 // - no other track is ready
5535 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
5536 mixerStatus != MIXER_TRACKS_READY) {
5537 mixerStatus = MIXER_TRACKS_ENABLED;
5538 }
5539 }
Andy Hungc0691382018-09-12 18:01:57 -07005540 mAudioMixer->disable(trackId);
Eric Laurent81784c32012-11-19 14:55:58 -08005541 }
5542
5543 } // local variable scope to avoid goto warning
Eric Laurent81784c32012-11-19 14:55:58 -08005544
5545 }
5546
jiabin245cdd92018-12-07 17:55:15 -08005547 if (mHapticChannelMask != AUDIO_CHANNEL_NONE && sq != NULL) {
5548 // When there is no fast track playing haptic and FastMixer exists,
5549 // enabling the first FastTrack, which provides mixed data from normal
5550 // tracks, to play haptic data.
5551 FastTrack *fastTrack = &state->mFastTracks[0];
5552 if (fastTrack->mHapticPlaybackEnabled != noFastHapticTrack) {
5553 fastTrack->mHapticPlaybackEnabled = noFastHapticTrack;
5554 didModify = true;
5555 }
5556 }
5557
Eric Laurent81784c32012-11-19 14:55:58 -08005558 // Push the new FastMixer state if necessary
5559 bool pauseAudioWatchdog = false;
5560 if (didModify) {
5561 state->mFastTracksGen++;
5562 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
5563 if (kUseFastMixer == FastMixer_Dynamic &&
5564 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
5565 state->mCommand = FastMixerState::COLD_IDLE;
5566 state->mColdFutexAddr = &mFastMixerFutex;
5567 state->mColdGen++;
5568 mFastMixerFutex = 0;
5569 if (kUseFastMixer == FastMixer_Dynamic) {
5570 mNormalSink = mOutputSink;
5571 }
5572 // If we go into cold idle, need to wait for acknowledgement
5573 // so that fast mixer stops doing I/O.
5574 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
5575 pauseAudioWatchdog = true;
5576 }
Eric Laurent81784c32012-11-19 14:55:58 -08005577 }
5578 if (sq != NULL) {
5579 sq->end(didModify);
Andy Hungf2285312017-02-14 18:31:59 -08005580 // No need to block if the FastMixer is in COLD_IDLE as the FastThread
5581 // is not active. (We BLOCK_UNTIL_ACKED when entering COLD_IDLE
5582 // when bringing the output sink into standby.)
5583 //
5584 // We will get the latest FastMixer state when we come out of COLD_IDLE.
5585 //
5586 // This occurs with BT suspend when we idle the FastMixer with
5587 // active tracks, which may be added or removed.
5588 sq->push(coldIdle ? FastMixerStateQueue::BLOCK_NEVER : block);
Eric Laurent81784c32012-11-19 14:55:58 -08005589 }
5590#ifdef AUDIO_WATCHDOG
5591 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
5592 mAudioWatchdog->pause();
5593 }
5594#endif
5595
5596 // Now perform the deferred reset on fast tracks that have stopped
5597 while (resetMask != 0) {
5598 size_t i = __builtin_ctz(resetMask);
5599 ALOG_ASSERT(i < count);
5600 resetMask &= ~(1 << i);
Andy Hungdae27702016-10-31 14:01:16 -07005601 sp<Track> track = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08005602 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
5603 track->reset();
5604 }
5605
Andy Hung80d03d22018-04-10 10:32:11 -07005606 // Track destruction may occur outside of threadLoop once it is removed from active tracks.
5607 // Ensure the AudioMixer doesn't have a raw "buffer provider" pointer to the track if
5608 // it ceases to be active, to allow safe removal from the AudioMixer at the start
5609 // of prepareTracks_l(); this releases any outstanding buffer back to the track.
5610 // See also the implementation of destroyTrack_l().
5611 for (const auto &track : *tracksToRemove) {
Andy Hungc0691382018-09-12 18:01:57 -07005612 const int trackId = track->id();
5613 if (mAudioMixer->exists(trackId)) { // Normal tracks here, fast tracks in FastMixer.
5614 mAudioMixer->setBufferProvider(trackId, nullptr /* bufferProvider */);
Andy Hung80d03d22018-04-10 10:32:11 -07005615 }
5616 }
5617
Eric Laurent81784c32012-11-19 14:55:58 -08005618 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08005619 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08005620
Eric Laurent97d547d2014-09-02 14:45:53 -07005621 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0) {
5622 mEffectBufferValid = true;
Marco Nelissenac302142014-10-20 13:15:38 -07005623 }
5624
5625 if (mEffectBufferValid) {
Marco Nelissen57088b52014-10-17 16:39:39 -07005626 // as long as there are effects we should clear the effects buffer, to avoid
5627 // passing a non-clean buffer to the effect chain
5628 memset(mEffectBuffer, 0, mEffectBufferSize);
Eric Laurent97d547d2014-09-02 14:45:53 -07005629 }
Andy Hung69aed5f2014-02-25 17:24:40 -08005630 // sink or mix buffer must be cleared if all tracks are connected to an
5631 // effect chain as in this case the mixer will not write to the sink or mix buffer
5632 // and track effects will accumulate into it
Eric Laurentbfb1b832013-01-07 09:53:42 -08005633 if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
5634 (mixedTracks == 0 && fastTracks > 0))) {
Eric Laurent81784c32012-11-19 14:55:58 -08005635 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08005636 if (mMixerBufferValid) {
5637 memset(mMixerBuffer, 0, mMixerBufferSize);
5638 // TODO: In testing, mSinkBuffer below need not be cleared because
5639 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
5640 // after mixing.
5641 //
5642 // To enforce this guarantee:
5643 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
5644 // (mixedTracks == 0 && fastTracks > 0))
5645 // must imply MIXER_TRACKS_READY.
5646 // Later, we may clear buffers regardless, and skip much of this logic.
5647 }
Andy Hung98ef9782014-03-04 14:46:50 -08005648 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07005649 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08005650 }
5651
5652 // if any fast tracks, then status is ready
5653 mMixerStatusIgnoringFastTracks = mixerStatus;
5654 if (fastTracks > 0) {
5655 mixerStatus = MIXER_TRACKS_READY;
5656 }
5657 return mixerStatus;
5658}
5659
Eric Laurentad7dd962016-09-22 12:38:37 -07005660// trackCountForUid_l() must be called with ThreadBase::mLock held
Andy Hung1bc088a2018-02-09 15:57:31 -08005661uint32_t AudioFlinger::PlaybackThread::trackCountForUid_l(uid_t uid) const
Eric Laurentad7dd962016-09-22 12:38:37 -07005662{
5663 uint32_t trackCount = 0;
5664 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hung1f12a8a2016-11-07 16:10:30 -08005665 if (mTracks[i]->uid() == uid) {
Eric Laurentad7dd962016-09-22 12:38:37 -07005666 trackCount++;
5667 }
5668 }
5669 return trackCount;
5670}
5671
Andy Hung1bc088a2018-02-09 15:57:31 -08005672// isTrackAllowed_l() must be called with ThreadBase::mLock held
5673bool AudioFlinger::MixerThread::isTrackAllowed_l(
5674 audio_channel_mask_t channelMask, audio_format_t format,
5675 audio_session_t sessionId, uid_t uid) const
Eric Laurent81784c32012-11-19 14:55:58 -08005676{
Andy Hung1bc088a2018-02-09 15:57:31 -08005677 if (!PlaybackThread::isTrackAllowed_l(channelMask, format, sessionId, uid)) {
5678 return false;
Eric Laurentad7dd962016-09-22 12:38:37 -07005679 }
Andy Hung1bc088a2018-02-09 15:57:31 -08005680 // Check validity as we don't call AudioMixer::create() here.
Mikhail Naganov7ad7a252019-07-30 14:42:32 -07005681 if (!mAudioMixer->isValidFormat(format)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08005682 ALOGW("%s: invalid format: %#x", __func__, format);
5683 return false;
5684 }
Mikhail Naganov7ad7a252019-07-30 14:42:32 -07005685 if (!mAudioMixer->isValidChannelMask(channelMask)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08005686 ALOGW("%s: invalid channelMask: %#x", __func__, channelMask);
5687 return false;
5688 }
5689 return true;
Eric Laurent81784c32012-11-19 14:55:58 -08005690}
5691
Eric Laurent10351942014-05-08 18:49:52 -07005692// checkForNewParameter_l() must be called with ThreadBase::mLock held
5693bool AudioFlinger::MixerThread::checkForNewParameter_l(const String8& keyValuePair,
5694 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08005695{
Eric Laurent81784c32012-11-19 14:55:58 -08005696 bool reconfig = false;
Eric Laurent10351942014-05-08 18:49:52 -07005697 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08005698
Glenn Kastenc05b8d72016-03-24 09:48:17 -07005699 AutoPark<FastMixer> park(mFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08005700
Eric Laurent10351942014-05-08 18:49:52 -07005701 AudioParameter param = AudioParameter(keyValuePair);
5702 int value;
5703 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
5704 reconfig = true;
5705 }
5706 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07005707 if (!isValidPcmSinkFormat((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07005708 status = BAD_VALUE;
5709 } else {
5710 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08005711 reconfig = true;
5712 }
Eric Laurent10351942014-05-08 18:49:52 -07005713 }
5714 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07005715 if (!isValidPcmSinkChannelMask((audio_channel_mask_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07005716 status = BAD_VALUE;
5717 } else {
5718 // no need to save value, since it's constant
5719 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08005720 }
Eric Laurent10351942014-05-08 18:49:52 -07005721 }
5722 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
5723 // do not accept frame count changes if tracks are open as the track buffer
5724 // size depends on frame count and correct behavior would not be guaranteed
5725 // if frame count is changed after track creation
5726 if (!mTracks.isEmpty()) {
5727 status = INVALID_OPERATION;
5728 } else {
5729 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08005730 }
Eric Laurent10351942014-05-08 18:49:52 -07005731 }
5732 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07005733 LOG_FATAL("Should not set routing device in MixerThread");
Eric Laurent10351942014-05-08 18:49:52 -07005734 }
Eric Laurent81784c32012-11-19 14:55:58 -08005735
Eric Laurent10351942014-05-08 18:49:52 -07005736 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005737 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07005738 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08005739 mOutput->standby();
Andy Hungcf10d742020-04-28 15:38:24 -07005740 if (!mStandby) {
5741 mThreadMetrics.logEndInterval();
5742 mStandby = true;
5743 }
Eric Laurent10351942014-05-08 18:49:52 -07005744 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005745 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent81784c32012-11-19 14:55:58 -08005746 }
Eric Laurent10351942014-05-08 18:49:52 -07005747 if (status == NO_ERROR && reconfig) {
5748 readOutputParameters_l();
5749 delete mAudioMixer;
5750 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
Andy Hung1bc088a2018-02-09 15:57:31 -08005751 for (const auto &track : mTracks) {
Andy Hungc0691382018-09-12 18:01:57 -07005752 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08005753 status_t status = mAudioMixer->create(
Andy Hungc0691382018-09-12 18:01:57 -07005754 trackId,
Andy Hung1bc088a2018-02-09 15:57:31 -08005755 track->mChannelMask,
5756 track->mFormat,
5757 track->mSessionId);
5758 ALOGW_IF(status != NO_ERROR,
Andy Hungc0691382018-09-12 18:01:57 -07005759 "%s(): AudioMixer cannot create track(%d)"
5760 " mask %#x, format %#x, sessionId %d",
Andy Hung1bc088a2018-02-09 15:57:31 -08005761 __func__,
Andy Hungc0691382018-09-12 18:01:57 -07005762 trackId, track->mChannelMask, track->mFormat, track->mSessionId);
Eric Laurent10351942014-05-08 18:49:52 -07005763 }
Eric Laurent73e26b62015-04-27 16:55:58 -07005764 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07005765 }
Eric Laurent81784c32012-11-19 14:55:58 -08005766 }
5767
Dean Wheatley68918102021-03-19 22:09:19 +11005768 return reconfig;
Eric Laurent81784c32012-11-19 14:55:58 -08005769}
5770
5771
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07005772void AudioFlinger::MixerThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -08005773{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07005774 PlaybackThread::dumpInternals_l(fd, args);
Andy Hung40eb1a12015-06-18 13:42:02 -07005775 dprintf(fd, " Thread throttle time (msecs): %u\n", mThreadThrottleTimeMs);
Andy Hung8ed196a2018-01-05 13:21:11 -08005776 dprintf(fd, " AudioMixer tracks: %s\n", mAudioMixer->trackNames().c_str());
Andy Hung2ddee192015-12-18 17:34:44 -08005777 dprintf(fd, " Master mono: %s\n", mMasterMono ? "on" : "off");
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01005778 dprintf(fd, " Master balance: %f (%s)\n", mMasterBalance.load(),
5779 (hasFastMixer() ? std::to_string(mFastMixer->getMasterBalance())
5780 : mBalance.toString()).c_str());
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08005781 if (hasFastMixer()) {
5782 dprintf(fd, " FastMixer thread %p tid=%d", mFastMixer.get(), mFastMixer->getTid());
5783
5784 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
5785 // while we are dumping it. It may be inconsistent, but it won't mutate!
5786 // This is a large object so we place it on the heap.
5787 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
Eric Tan2942a4e2018-09-12 17:41:27 -07005788 const std::unique_ptr<FastMixerDumpState> copy =
5789 std::make_unique<FastMixerDumpState>(mFastMixerDumpState);
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08005790 copy->dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08005791
5792#ifdef STATE_QUEUE_DUMP
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08005793 // Similar for state queue
5794 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
5795 observerCopy.dump(fd);
5796 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
5797 mutatorCopy.dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08005798#endif
5799
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08005800#ifdef AUDIO_WATCHDOG
5801 if (mAudioWatchdog != 0) {
5802 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
5803 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
5804 wdCopy.dump(fd);
5805 }
5806#endif
5807
5808 } else {
5809 dprintf(fd, " No FastMixer\n");
5810 }
Eric Laurent81784c32012-11-19 14:55:58 -08005811}
5812
5813uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
5814{
5815 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
5816}
5817
5818uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
5819{
5820 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
5821}
5822
5823void AudioFlinger::MixerThread::cacheParameters_l()
5824{
5825 PlaybackThread::cacheParameters_l();
5826
5827 // FIXME: Relaxed timing because of a certain device that can't meet latency
5828 // Should be reduced to 2x after the vendor fixes the driver issue
5829 // increase threshold again due to low power audio mode. The way this warning
5830 // threshold is calculated and its usefulness should be reconsidered anyway.
5831 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
5832}
5833
5834// ----------------------------------------------------------------------------
5835
5836AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
jiabinc52b1ff2019-10-31 17:20:42 -07005837 AudioStreamOut* output, audio_io_handle_t id, ThreadBase::type_t type, bool systemReady)
5838 : PlaybackThread(audioFlinger, output, id, type, systemReady)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005839{
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01005840 setMasterBalance(audioFlinger->getMasterBalance_l());
Eric Laurentbfb1b832013-01-07 09:53:42 -08005841}
5842
Eric Laurent81784c32012-11-19 14:55:58 -08005843AudioFlinger::DirectOutputThread::~DirectOutputThread()
5844{
5845}
5846
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07005847void AudioFlinger::DirectOutputThread::dumpInternals_l(int fd, const Vector<String16>& args)
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01005848{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07005849 PlaybackThread::dumpInternals_l(fd, args);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01005850 dprintf(fd, " Master balance: %f Left: %f Right: %f\n",
5851 mMasterBalance.load(), mMasterBalanceLeft, mMasterBalanceRight);
5852}
5853
5854void AudioFlinger::DirectOutputThread::setMasterBalance(float balance)
5855{
5856 Mutex::Autolock _l(mLock);
5857 if (mMasterBalance != balance) {
5858 mMasterBalance.store(balance);
5859 mBalance.computeStereoBalance(balance, &mMasterBalanceLeft, &mMasterBalanceRight);
5860 broadcast_l();
5861 }
5862}
5863
Eric Laurent5850c4c2016-11-10 13:04:31 -08005864void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005865{
Eric Laurentbfb1b832013-01-07 09:53:42 -08005866 float left, right;
5867
Andy Hung333ab962019-05-28 20:23:35 -07005868 // Ensure volumeshaper state always advances even when muted.
5869 const sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
5870 const auto [shaperVolume, shaperActive] = track->getVolumeHandler()->getVolume(
5871 proxy->framesReleased());
5872 mVolumeShaperActive = shaperActive;
5873
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08005874 if (mMasterMute || mStreamTypes[track->streamType()].mute || track->isPlaybackRestricted()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08005875 left = right = 0;
5876 } else {
5877 float typeVolume = mStreamTypes[track->streamType()].volume;
Andy Hung333ab962019-05-28 20:23:35 -07005878 const float v = mMasterVolume * typeVolume * shaperVolume;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005879
Glenn Kastenc56f3422014-03-21 17:53:17 -07005880 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
5881 left = float_from_gain(gain_minifloat_unpack_left(vlr));
5882 if (left > GAIN_FLOAT_UNITY) {
5883 left = GAIN_FLOAT_UNITY;
5884 }
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01005885 left *= v * mMasterBalanceLeft; // DirectOutputThread balance applied as track volume
Glenn Kastenc56f3422014-03-21 17:53:17 -07005886 right = float_from_gain(gain_minifloat_unpack_right(vlr));
5887 if (right > GAIN_FLOAT_UNITY) {
5888 right = GAIN_FLOAT_UNITY;
5889 }
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01005890 right *= v * mMasterBalanceRight;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005891 }
5892
5893 if (lastTrack) {
Kevin Rocard12381092018-04-11 09:19:59 -07005894 track->setFinalVolume((left + right) / 2.f);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005895 if (left != mLeftVolFloat || right != mRightVolFloat) {
5896 mLeftVolFloat = left;
5897 mRightVolFloat = right;
5898
Eric Laurentbfb1b832013-01-07 09:53:42 -08005899 // Delegate volume control to effect in track effect chain if needed
5900 // only one effect chain can be present on DirectOutputThread, so if
5901 // there is one, the track is connected to it
5902 if (!mEffectChains.isEmpty()) {
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09005903 // if effect chain exists, volume is handled by it.
5904 // Convert volumes from float to 8.24
5905 uint32_t vl = (uint32_t)(left * (1 << 24));
5906 uint32_t vr = (uint32_t)(right * (1 << 24));
5907 // Direct/Offload effect chains set output volume in setVolume_l().
5908 (void)mEffectChains[0]->setVolume_l(&vl, &vr);
5909 } else {
5910 // otherwise we directly set the volume.
5911 setVolumeForOutput_l(left, right);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005912 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005913 }
5914 }
5915}
5916
Phil Burk43b4dcc2015-06-09 16:53:44 -07005917void AudioFlinger::DirectOutputThread::onAddNewTrack_l()
5918{
5919 sp<Track> previousTrack = mPreviousTrack.promote();
Andy Hungdae27702016-10-31 14:01:16 -07005920 sp<Track> latestTrack = mActiveTracks.getLatest();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005921
Eric Laurent0f0631e2015-07-06 18:01:25 -07005922 if (previousTrack != 0 && latestTrack != 0) {
5923 if (mType == DIRECT) {
5924 if (previousTrack.get() != latestTrack.get()) {
5925 mFlushPending = true;
5926 }
5927 } else /* mType == OFFLOAD */ {
5928 if (previousTrack->sessionId() != latestTrack->sessionId()) {
5929 mFlushPending = true;
5930 }
5931 }
Revathi Uddaraju20413a92016-10-13 17:16:14 +08005932 } else if (previousTrack == 0) {
5933 // there could be an old track added back during track transition for direct
5934 // output, so always issues flush to flush data of the previous track if it
5935 // was already destroyed with HAL paused, then flush can resume the playback
5936 mFlushPending = true;
Phil Burk43b4dcc2015-06-09 16:53:44 -07005937 }
5938 PlaybackThread::onAddNewTrack_l();
5939}
Eric Laurentbfb1b832013-01-07 09:53:42 -08005940
Eric Laurent81784c32012-11-19 14:55:58 -08005941AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
5942 Vector< sp<Track> > *tracksToRemove
5943)
5944{
Eric Laurentd595b7c2013-04-03 17:27:56 -07005945 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08005946 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005947 bool doHwPause = false;
5948 bool doHwResume = false;
Eric Laurent81784c32012-11-19 14:55:58 -08005949
5950 // find out which tracks need to be processed
Andy Hungdae27702016-10-31 14:01:16 -07005951 for (const sp<Track> &t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08005952 if (t->isInvalid()) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07005953 ALOGW("An invalidated track shouldn't be in active list");
Eric Laurent5850c4c2016-11-10 13:04:31 -08005954 tracksToRemove->add(t);
Phil Burk43b4dcc2015-06-09 16:53:44 -07005955 continue;
5956 }
5957
Eric Laurent5850c4c2016-11-10 13:04:31 -08005958 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005959#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurent81784c32012-11-19 14:55:58 -08005960 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005961#endif
Eric Laurentfd477972013-10-25 18:10:40 -07005962 // Only consider last track started for volume and mixer state control.
5963 // In theory an older track could underrun and restart after the new one starts
5964 // but as we only care about the transition phase between two tracks on a
5965 // direct output, it is not a problem to ignore the underrun case.
Andy Hungdae27702016-10-31 14:01:16 -07005966 sp<Track> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08005967 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08005968
Kuowei Li23666472021-01-20 10:23:25 +08005969 if (track->isPausePending()) {
5970 track->pauseAck();
5971 // It is possible a track might have been flushed or stopped.
5972 // Other operations such as flush pending might occur on the next prepare.
5973 if (track->isPausing()) {
5974 track->setPaused();
5975 }
5976 // Always perform pause, as an immediate flush will change
5977 // the pause state to be no longer isPausing().
Phil Burk6fc2a7c2015-04-30 16:08:10 -07005978 if (mHwSupportsPause && last && !mHwPaused) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005979 doHwPause = true;
5980 mHwPaused = true;
5981 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08005982 } else if (track->isFlushPending()) {
5983 track->flushAck();
5984 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07005985 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005986 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07005987 } else if (track->isResumePending()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005988 track->resumeAck();
Eric Laurent3df841a2016-07-15 15:15:40 -07005989 if (last) {
5990 mLeftVolFloat = mRightVolFloat = -1.0;
5991 if (mHwPaused) {
5992 doHwResume = true;
5993 mHwPaused = false;
5994 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08005995 }
5996 }
5997
Eric Laurent81784c32012-11-19 14:55:58 -08005998 // The first time a track is added we wait
Phil Burk99adee32014-12-10 16:46:30 -08005999 // for all its buffers to be filled before processing it.
6000 // Allow draining the buffer in case the client
6001 // app does not call stop() and relies on underrun to stop:
6002 // hence the test on (track->mRetryCount > 1).
Andy Hung455982f2021-04-27 17:46:12 -07006003 // If track->mRetryCount <= 1 then track is about to be disabled, paused, removed,
6004 // so we accept any nonzero amount of data delivered by the AudioTrack (which will
6005 // reset the retry counter).
Phil Burkca5e6142015-07-14 09:42:29 -07006006 // Do not use a high threshold for compressed audio.
Andy Hung455982f2021-04-27 17:46:12 -07006007
6008 // target retry count that we will use is based on the time we wait for retries.
6009 const int32_t targetRetryCount = kMaxTrackRetriesDirectMs * 1000 / mActiveSleepTimeUs;
6010 // the retry threshold is when we accept any size for PCM data. This is slightly
6011 // smaller than the retry count so we can push small bits of data without a glitch.
6012 const int32_t retryThreshold = targetRetryCount > 2 ? targetRetryCount - 1 : 1;
Eric Laurent81784c32012-11-19 14:55:58 -08006013 uint32_t minFrames;
Phil Burk99adee32014-12-10 16:46:30 -08006014 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
Andy Hung455982f2021-04-27 17:46:12 -07006015 && (track->mRetryCount > retryThreshold) && audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006016 minFrames = mNormalFrameCount;
6017 } else {
6018 minFrames = 1;
6019 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006020
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07006021 const size_t framesReady = track->framesReady();
6022 const int trackId = track->id();
6023 if (ATRACE_ENABLED()) {
6024 std::string traceName("nRdy");
6025 traceName += std::to_string(trackId);
6026 ATRACE_INT(traceName.c_str(), framesReady);
6027 }
6028 if ((framesReady >= minFrames) && track->isReady() && !track->isPaused() &&
Eric Laurentab5cdba2014-06-09 17:22:27 -07006029 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08006030 {
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07006031 ALOGVV("track(%d) s=%08x [OK]", trackId, cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08006032
6033 if (track->mFillingUpStatus == Track::FS_FILLED) {
6034 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07006035 if (last) {
6036 // make sure processVolume_l() will apply new volume even if 0
6037 mLeftVolFloat = mRightVolFloat = -1.0;
6038 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08006039 if (!mHwSupportsPause) {
6040 track->resumeAck();
Eric Laurent81784c32012-11-19 14:55:58 -08006041 }
6042 }
6043
6044 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08006045 processVolume_l(track, last);
6046 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07006047 sp<Track> previousTrack = mPreviousTrack.promote();
6048 if (previousTrack != 0) {
6049 if (track != previousTrack.get()) {
6050 // Flush any data still being written from last track
6051 mBytesRemaining = 0;
Eric Laurent0f0631e2015-07-06 18:01:25 -07006052 // Invalidate previous track to force a seek when resuming.
6053 previousTrack->invalidate();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006054 }
6055 }
6056 mPreviousTrack = track;
6057
Eric Laurentd595b7c2013-04-03 17:27:56 -07006058 // reset retry count
Andy Hung455982f2021-04-27 17:46:12 -07006059 track->mRetryCount = targetRetryCount;
Eric Laurent5850c4c2016-11-10 13:04:31 -08006060 mActiveTrack = t;
Eric Laurentd595b7c2013-04-03 17:27:56 -07006061 mixerStatus = MIXER_TRACKS_READY;
Eric Laurent5cff4032015-05-26 13:49:58 -07006062 if (mHwPaused) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08006063 doHwResume = true;
6064 mHwPaused = false;
6065 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07006066 }
Eric Laurent81784c32012-11-19 14:55:58 -08006067 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07006068 // clear effect chain input buffer if the last active track started underruns
6069 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07006070 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08006071 mEffectChains[0]->clearInputBuffer();
6072 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07006073 if (track->isStopping_1()) {
6074 track->mState = TrackBase::STOPPING_2;
Eric Laurentb369caf2015-03-30 20:51:47 -07006075 if (last && mHwPaused) {
6076 doHwResume = true;
6077 mHwPaused = false;
6078 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07006079 }
6080 if ((track->sharedBuffer() != 0) || track->isStopped() ||
6081 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08006082 // We have consumed all the buffers of this track.
6083 // Remove it from the list of active tracks.
Eric Laurentfd477972013-10-25 18:10:40 -07006084 if (mStandby || !last ||
Andy Hung59de4262021-06-14 10:53:54 -07006085 track->presentationComplete(latency_l()) ||
Jindong32dc26e2019-11-11 18:10:01 +08006086 track->isPaused() || mHwPaused) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07006087 if (track->isStopping_2()) {
6088 track->mState = TrackBase::STOPPED;
6089 }
Eric Laurent81784c32012-11-19 14:55:58 -08006090 if (track->isStopped()) {
6091 track->reset();
6092 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07006093 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08006094 }
6095 } else {
6096 // No buffers for this track. Give it a few chances to
6097 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07006098 // Only consider last track started for mixer state control
Eric Laurent81784c32012-11-19 14:55:58 -08006099 if (--(track->mRetryCount) <= 0) {
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07006100 ALOGV("BUFFER TIMEOUT: remove track(%d) from active list", trackId);
Eric Laurentd595b7c2013-04-03 17:27:56 -07006101 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08006102 // indicate to client process that the track was disabled because of underrun;
6103 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08006104 track->disable();
Haynes Mathew George5c6daae2017-01-24 20:06:05 -08006105 // only do hw pause when track is going to be removed due to BUFFER TIMEOUT.
6106 // unlike mixerthread, HAL can be paused for direct output
Phil Burkca5e6142015-07-14 09:42:29 -07006107 ALOGW("pause because of UNDERRUN, framesReady = %zu,"
6108 "minFrames = %u, mFormat = %#x",
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07006109 framesReady, minFrames, mFormat);
Haynes Mathew George5c6daae2017-01-24 20:06:05 -08006110 if (last && mHwSupportsPause && !mHwPaused && !mStandby) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08006111 doHwPause = true;
6112 mHwPaused = true;
6113 }
Haynes Mathew George5c6daae2017-01-24 20:06:05 -08006114 } else if (last) {
6115 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurent81784c32012-11-19 14:55:58 -08006116 }
6117 }
6118 }
6119 }
6120
Eric Laurentd1f69b02014-12-15 14:33:13 -08006121 // if an active track did not command a flush, check for pending flush on stopped tracks
Phil Burk43b4dcc2015-06-09 16:53:44 -07006122 if (!mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006123 for (size_t i = 0; i < mTracks.size(); i++) {
6124 if (mTracks[i]->isFlushPending()) {
6125 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006126 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006127 }
6128 }
6129 }
6130
6131 // make sure the pause/flush/resume sequence is executed in the right order.
6132 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
6133 // before flush and then resume HW. This can happen in case of pause/flush/resume
6134 // if resume is received before pause is executed.
6135 if (mHwSupportsPause && !mStandby &&
Phil Burk43b4dcc2015-06-09 16:53:44 -07006136 (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006137 status_t result = mOutput->stream->pause();
6138 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08006139 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07006140 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006141 flushHw_l();
6142 }
6143 if (mHwSupportsPause && !mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006144 status_t result = mOutput->stream->resume();
6145 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08006146 }
Eric Laurent81784c32012-11-19 14:55:58 -08006147 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08006148 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08006149
6150 return mixerStatus;
6151}
6152
6153void AudioFlinger::DirectOutputThread::threadLoop_mix()
6154{
Eric Laurent81784c32012-11-19 14:55:58 -08006155 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08006156 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08006157 // output audio to hardware
6158 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07006159 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08006160 buffer.frameCount = frameCount;
Phil Burk062e67a2015-02-11 13:40:50 -08006161 status_t status = mActiveTrack->getNextBuffer(&buffer);
6162 if (status != NO_ERROR || buffer.raw == NULL) {
Eric Laurent51716182016-02-29 18:00:56 -08006163 // no need to pad with 0 for compressed audio
6164 if (audio_has_proportional_frames(mFormat)) {
6165 memset(curBuf, 0, frameCount * mFrameSize);
6166 }
Eric Laurent81784c32012-11-19 14:55:58 -08006167 break;
6168 }
6169 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
6170 frameCount -= buffer.frameCount;
6171 curBuf += buffer.frameCount * mFrameSize;
6172 mActiveTrack->releaseBuffer(&buffer);
6173 }
Andy Hung2098f272014-02-27 14:00:06 -08006174 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006175 mSleepTimeUs = 0;
6176 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08006177 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08006178}
6179
6180void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
6181{
Eric Laurentd1f69b02014-12-15 14:33:13 -08006182 // do not write to HAL when paused
Eric Laurent0f7b5f22014-12-19 10:43:21 -08006183 if (mHwPaused || (usesHwAvSync() && mStandby)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006184 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006185 return;
6186 }
Andy Hung85ba3332021-04-27 17:40:26 -07006187 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
6188 mSleepTimeUs = mActiveSleepTimeUs;
6189 } else {
6190 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006191 }
Andy Hung85ba3332021-04-27 17:40:26 -07006192 // Note: In S or later, we do not write zeroes for
6193 // linear or proportional PCM direct tracks in underrun.
Eric Laurent81784c32012-11-19 14:55:58 -08006194}
6195
Eric Laurentd1f69b02014-12-15 14:33:13 -08006196void AudioFlinger::DirectOutputThread::threadLoop_exit()
6197{
6198 {
6199 Mutex::Autolock _l(mLock);
Eric Laurentd1f69b02014-12-15 14:33:13 -08006200 for (size_t i = 0; i < mTracks.size(); i++) {
6201 if (mTracks[i]->isFlushPending()) {
6202 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006203 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006204 }
6205 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07006206 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006207 flushHw_l();
6208 }
6209 }
6210 PlaybackThread::threadLoop_exit();
6211}
6212
6213// must be called with thread mutex locked
6214bool AudioFlinger::DirectOutputThread::shouldStandby_l()
6215{
6216 bool trackPaused = false;
Eric Laurentb369caf2015-03-30 20:51:47 -07006217 bool trackStopped = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006218
6219 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
6220 // after a timeout and we will enter standby then.
6221 if (mTracks.size() > 0) {
6222 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
Eric Laurentb369caf2015-03-30 20:51:47 -07006223 trackStopped = mTracks[mTracks.size() - 1]->isStopped() ||
6224 mTracks[mTracks.size() - 1]->mState == TrackBase::IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006225 }
6226
Eric Laurent5cff4032015-05-26 13:49:58 -07006227 return !mStandby && !(trackPaused || (mHwPaused && !trackStopped));
Eric Laurentd1f69b02014-12-15 14:33:13 -08006228}
6229
Eric Laurent10351942014-05-08 18:49:52 -07006230// checkForNewParameter_l() must be called with ThreadBase::mLock held
6231bool AudioFlinger::DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
6232 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08006233{
6234 bool reconfig = false;
Eric Laurent10351942014-05-08 18:49:52 -07006235 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006236
Eric Laurent10351942014-05-08 18:49:52 -07006237 AudioParameter param = AudioParameter(keyValuePair);
6238 int value;
6239 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07006240 LOG_FATAL("Should not set routing device in DirectOutputThread");
Eric Laurent81784c32012-11-19 14:55:58 -08006241 }
Eric Laurent10351942014-05-08 18:49:52 -07006242 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6243 // do not accept frame count changes if tracks are open as the track buffer
6244 // size depends on frame count and correct behavior would not be garantied
6245 // if frame count is changed after track creation
6246 if (!mTracks.isEmpty()) {
6247 status = INVALID_OPERATION;
6248 } else {
6249 reconfig = true;
6250 }
6251 }
6252 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006253 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07006254 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08006255 mOutput->standby();
Andy Hungcf10d742020-04-28 15:38:24 -07006256 if (!mStandby) {
6257 mThreadMetrics.logEndInterval();
6258 mStandby = true;
6259 }
Eric Laurent10351942014-05-08 18:49:52 -07006260 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006261 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07006262 }
6263 if (status == NO_ERROR && reconfig) {
6264 readOutputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07006265 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07006266 }
6267 }
6268
Dean Wheatley68918102021-03-19 22:09:19 +11006269 return reconfig;
Eric Laurent81784c32012-11-19 14:55:58 -08006270}
6271
6272uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
6273{
6274 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08006275 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006276 time = PlaybackThread::activeSleepTimeUs();
6277 } else {
Eric Laurent51716182016-02-29 18:00:56 -08006278 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006279 }
6280 return time;
6281}
6282
6283uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
6284{
6285 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08006286 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006287 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
6288 } else {
Eric Laurent51716182016-02-29 18:00:56 -08006289 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006290 }
6291 return time;
6292}
6293
6294uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
6295{
6296 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08006297 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006298 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
6299 } else {
Eric Laurent51716182016-02-29 18:00:56 -08006300 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006301 }
6302 return time;
6303}
6304
6305void AudioFlinger::DirectOutputThread::cacheParameters_l()
6306{
6307 PlaybackThread::cacheParameters_l();
6308
6309 // use shorter standby delay as on normal output to release
6310 // hardware resources as soon as possible
Eric Laurentb369caf2015-03-30 20:51:47 -07006311 // no delay on outputs with HW A/V sync
6312 if (usesHwAvSync()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006313 mStandbyDelayNs = 0;
Phil Burkfdb3c072016-02-09 10:47:02 -08006314 } else if ((mType == OFFLOAD) && !audio_has_proportional_frames(mFormat)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006315 mStandbyDelayNs = kOffloadStandbyDelayNs;
Eric Laurent5cff4032015-05-26 13:49:58 -07006316 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006317 mStandbyDelayNs = microseconds(mActiveSleepTimeUs*2);
Eric Laurent972a1732013-09-04 09:42:59 -07006318 }
Eric Laurent81784c32012-11-19 14:55:58 -08006319}
6320
Eric Laurente659ef42014-09-29 13:06:46 -07006321void AudioFlinger::DirectOutputThread::flushHw_l()
6322{
Phil Burk062e67a2015-02-11 13:40:50 -08006323 mOutput->flush();
Eric Laurentd1f69b02014-12-15 14:33:13 -08006324 mHwPaused = false;
Phil Burk43b4dcc2015-06-09 16:53:44 -07006325 mFlushPending = false;
Dean Wheatley12473e92021-03-18 23:00:55 +11006326 mTimestampVerifier.discontinuity(discontinuityForStandbyOrFlush());
Sampath Shetty999f0e82020-01-15 10:19:06 +11006327 mTimestamp.clear();
Eric Laurente659ef42014-09-29 13:06:46 -07006328}
6329
Andy Hung10cbff12017-02-21 17:30:14 -08006330int64_t AudioFlinger::DirectOutputThread::computeWaitTimeNs_l() const {
6331 // If a VolumeShaper is active, we must wake up periodically to update volume.
6332 const int64_t NS_PER_MS = 1000000;
6333 return mVolumeShaperActive ?
6334 kMinNormalSinkBufferSizeMs * NS_PER_MS : PlaybackThread::computeWaitTimeNs_l();
6335}
6336
Eric Laurent81784c32012-11-19 14:55:58 -08006337// ----------------------------------------------------------------------------
6338
Eric Laurentbfb1b832013-01-07 09:53:42 -08006339AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
Eric Laurent4de95592013-09-26 15:28:21 -07006340 const wp<AudioFlinger::PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006341 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07006342 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07006343 mWriteAckSequence(0),
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006344 mDrainSequence(0),
6345 mAsyncError(false)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006346{
6347}
6348
6349AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
6350{
6351}
6352
6353void AudioFlinger::AsyncCallbackThread::onFirstRef()
6354{
6355 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
6356}
6357
6358bool AudioFlinger::AsyncCallbackThread::threadLoop()
6359{
6360 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07006361 uint32_t writeAckSequence;
6362 uint32_t drainSequence;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006363 bool asyncError;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006364
6365 {
6366 Mutex::Autolock _l(mLock);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08006367 while (!((mWriteAckSequence & 1) ||
6368 (mDrainSequence & 1) ||
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006369 mAsyncError ||
Haynes Mathew George24a325d2013-12-03 21:26:02 -08006370 exitPending())) {
6371 mWaitWorkCV.wait(mLock);
6372 }
6373
Eric Laurentbfb1b832013-01-07 09:53:42 -08006374 if (exitPending()) {
6375 break;
6376 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07006377 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
6378 mWriteAckSequence, mDrainSequence);
6379 writeAckSequence = mWriteAckSequence;
6380 mWriteAckSequence &= ~1;
6381 drainSequence = mDrainSequence;
6382 mDrainSequence &= ~1;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006383 asyncError = mAsyncError;
6384 mAsyncError = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006385 }
6386 {
Eric Laurent4de95592013-09-26 15:28:21 -07006387 sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
6388 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07006389 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07006390 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006391 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07006392 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07006393 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006394 }
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006395 if (asyncError) {
6396 playbackThread->onAsyncError();
6397 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006398 }
6399 }
6400 }
6401 return false;
6402}
6403
6404void AudioFlinger::AsyncCallbackThread::exit()
6405{
6406 ALOGV("AsyncCallbackThread::exit");
6407 Mutex::Autolock _l(mLock);
6408 requestExit();
6409 mWaitWorkCV.broadcast();
6410}
6411
Eric Laurent3b4529e2013-09-05 18:09:19 -07006412void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006413{
6414 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07006415 // bit 0 is cleared
6416 mWriteAckSequence = sequence << 1;
6417}
6418
6419void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
6420{
6421 Mutex::Autolock _l(mLock);
6422 // ignore unexpected callbacks
6423 if (mWriteAckSequence & 2) {
6424 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006425 mWaitWorkCV.signal();
6426 }
6427}
6428
Eric Laurent3b4529e2013-09-05 18:09:19 -07006429void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006430{
6431 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07006432 // bit 0 is cleared
6433 mDrainSequence = sequence << 1;
6434}
6435
6436void AudioFlinger::AsyncCallbackThread::resetDraining()
6437{
6438 Mutex::Autolock _l(mLock);
6439 // ignore unexpected callbacks
6440 if (mDrainSequence & 2) {
6441 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006442 mWaitWorkCV.signal();
6443 }
6444}
6445
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006446void AudioFlinger::AsyncCallbackThread::setAsyncError()
6447{
6448 Mutex::Autolock _l(mLock);
6449 mAsyncError = true;
6450 mWaitWorkCV.signal();
6451}
6452
Eric Laurentbfb1b832013-01-07 09:53:42 -08006453
6454// ----------------------------------------------------------------------------
6455AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
jiabinc52b1ff2019-10-31 17:20:42 -07006456 AudioStreamOut* output, audio_io_handle_t id, bool systemReady)
6457 : DirectOutputThread(audioFlinger, output, id, OFFLOAD, systemReady),
Andy Hungf8044752016-07-27 14:58:11 -07006458 mPausedWriteLength(0), mPausedBytesRemaining(0), mKeepWakeLock(true),
6459 mOffloadUnderrunPosition(~0LL)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006460{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07006461 //FIXME: mStandby should be set to true by ThreadBase constructo
Eric Laurentfd477972013-10-25 18:10:40 -07006462 mStandby = true;
Eric Laurent64667972016-03-30 18:19:46 -07006463 mKeepWakeLock = property_get_bool("ro.audio.offload_wakelock", true /* default_value */);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006464}
6465
Eric Laurentbfb1b832013-01-07 09:53:42 -08006466void AudioFlinger::OffloadThread::threadLoop_exit()
6467{
6468 if (mFlushPending || mHwPaused) {
6469 // If a flush is pending or track was paused, just discard buffered data
6470 flushHw_l();
6471 } else {
6472 mMixerStatus = MIXER_DRAIN_ALL;
6473 threadLoop_drain();
6474 }
Uday Gupta56604aa2014-05-13 11:19:17 -07006475 if (mUseAsyncWrite) {
6476 ALOG_ASSERT(mCallbackThread != 0);
6477 mCallbackThread->exit();
6478 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006479 PlaybackThread::threadLoop_exit();
6480}
6481
6482AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
6483 Vector< sp<Track> > *tracksToRemove
6484)
6485{
Eric Laurentbfb1b832013-01-07 09:53:42 -08006486 size_t count = mActiveTracks.size();
6487
6488 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07006489 bool doHwPause = false;
6490 bool doHwResume = false;
6491
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006492 ALOGV("OffloadThread::prepareTracks_l active tracks %zu", count);
Eric Laurentede6c3b2013-09-19 14:37:46 -07006493
Eric Laurentbfb1b832013-01-07 09:53:42 -08006494 // find out which tracks need to be processed
Andy Hungdae27702016-10-31 14:01:16 -07006495 for (const sp<Track> &t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08006496 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006497#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurentbfb1b832013-01-07 09:53:42 -08006498 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006499#endif
Eric Laurentfd477972013-10-25 18:10:40 -07006500 // Only consider last track started for volume and mixer state control.
6501 // In theory an older track could underrun and restart after the new one starts
6502 // but as we only care about the transition phase between two tracks on a
6503 // direct output, it is not a problem to ignore the underrun case.
Andy Hungdae27702016-10-31 14:01:16 -07006504 sp<Track> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08006505 bool last = l.get() == track;
Eric Laurentfd477972013-10-25 18:10:40 -07006506
Haynes Mathew George7844f672014-01-15 12:32:55 -08006507 if (track->isInvalid()) {
6508 ALOGW("An invalidated track shouldn't be in active list");
6509 tracksToRemove->add(track);
6510 continue;
6511 }
6512
6513 if (track->mState == TrackBase::IDLE) {
6514 ALOGW("An idle track shouldn't be in active list");
6515 continue;
6516 }
6517
Kuowei Li23666472021-01-20 10:23:25 +08006518 if (track->isPausePending()) {
6519 track->pauseAck();
6520 // It is possible a track might have been flushed or stopped.
6521 // Other operations such as flush pending might occur on the next prepare.
6522 if (track->isPausing()) {
6523 track->setPaused();
6524 }
6525 // Always perform pause if last, as an immediate flush will change
6526 // the pause state to be no longer isPausing().
Eric Laurentbfb1b832013-01-07 09:53:42 -08006527 if (last) {
Eric Laurent5cff4032015-05-26 13:49:58 -07006528 if (mHwSupportsPause && !mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07006529 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006530 mHwPaused = true;
6531 }
6532 // If we were part way through writing the mixbuffer to
6533 // the HAL we must save this until we resume
6534 // BUG - this will be wrong if a different track is made active,
6535 // in that case we want to discard the pending data in the
6536 // mixbuffer and tell the client to present it again when the
6537 // track is resumed
6538 mPausedWriteLength = mCurrentWriteLength;
6539 mPausedBytesRemaining = mBytesRemaining;
6540 mBytesRemaining = 0; // stop writing
6541 }
6542 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08006543 } else if (track->isFlushPending()) {
Eric Laurente93cc032016-05-05 10:15:10 -07006544 if (track->isStopping_1()) {
6545 track->mRetryCount = kMaxTrackStopRetriesOffload;
6546 } else {
6547 track->mRetryCount = kMaxTrackRetriesOffload;
6548 }
Haynes Mathew George7844f672014-01-15 12:32:55 -08006549 track->flushAck();
6550 if (last) {
6551 mFlushPending = true;
6552 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08006553 } else if (track->isResumePending()){
6554 track->resumeAck();
6555 if (last) {
6556 if (mPausedBytesRemaining) {
6557 // Need to continue write that was interrupted
6558 mCurrentWriteLength = mPausedWriteLength;
6559 mBytesRemaining = mPausedBytesRemaining;
6560 mPausedBytesRemaining = 0;
6561 }
6562 if (mHwPaused) {
6563 doHwResume = true;
6564 mHwPaused = false;
6565 // threadLoop_mix() will handle the case that we need to
6566 // resume an interrupted write
6567 }
6568 // enable write to audio HAL
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006569 mSleepTimeUs = 0;
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08006570
Eric Laurent3df841a2016-07-15 15:15:40 -07006571 mLeftVolFloat = mRightVolFloat = -1.0;
6572
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08006573 // Do not handle new data in this iteration even if track->framesReady()
6574 mixerStatus = MIXER_TRACKS_ENABLED;
6575 }
6576 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07006577 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Andy Hungc0691382018-09-12 18:01:57 -07006578 ALOGVV("OffloadThread: track(%d) s=%08x [OK]", track->id(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006579 if (track->mFillingUpStatus == Track::FS_FILLED) {
6580 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07006581 if (last) {
6582 // make sure processVolume_l() will apply new volume even if 0
6583 mLeftVolFloat = mRightVolFloat = -1.0;
6584 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006585 }
6586
6587 if (last) {
Eric Laurentd7e59222013-11-15 12:02:28 -08006588 sp<Track> previousTrack = mPreviousTrack.promote();
6589 if (previousTrack != 0) {
6590 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08006591 // Flush any data still being written from last track
6592 mBytesRemaining = 0;
6593 if (mPausedBytesRemaining) {
6594 // Last track was paused so we also need to flush saved
6595 // mixbuffer state and invalidate track so that it will
6596 // re-submit that unwritten data when it is next resumed
6597 mPausedBytesRemaining = 0;
6598 // Invalidate is a bit drastic - would be more efficient
6599 // to have a flag to tell client that some of the
6600 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08006601 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08006602 }
6603 // flush data already sent to the DSP if changing audio session as audio
6604 // comes from a different source. Also invalidate previous track to force a
6605 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08006606 if (previousTrack->sessionId() != track->sessionId()) {
6607 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08006608 }
6609 }
6610 }
6611 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006612 // reset retry count
Eric Laurente93cc032016-05-05 10:15:10 -07006613 if (track->isStopping_1()) {
6614 track->mRetryCount = kMaxTrackStopRetriesOffload;
6615 } else {
6616 track->mRetryCount = kMaxTrackRetriesOffload;
6617 }
Eric Laurent5850c4c2016-11-10 13:04:31 -08006618 mActiveTrack = t;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006619 mixerStatus = MIXER_TRACKS_READY;
6620 }
6621 } else {
Andy Hungc0691382018-09-12 18:01:57 -07006622 ALOGVV("OffloadThread: track(%d) s=%08x [NOT READY]", track->id(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006623 if (track->isStopping_1()) {
Eric Laurente93cc032016-05-05 10:15:10 -07006624 if (--(track->mRetryCount) <= 0) {
6625 // Hardware buffer can hold a large amount of audio so we must
6626 // wait for all current track's data to drain before we say
6627 // that the track is stopped.
6628 if (mBytesRemaining == 0) {
6629 // Only start draining when all data in mixbuffer
6630 // has been written
6631 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
6632 track->mState = TrackBase::STOPPING_2; // so presentation completes after
6633 // drain do not drain if no data was ever sent to HAL (mStandby == true)
6634 if (last && !mStandby) {
6635 // do not modify drain sequence if we are already draining. This happens
6636 // when resuming from pause after drain.
6637 if ((mDrainSequence & 1) == 0) {
6638 mSleepTimeUs = 0;
6639 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
6640 mixerStatus = MIXER_DRAIN_TRACK;
6641 mDrainSequence += 2;
6642 }
6643 if (mHwPaused) {
6644 // It is possible to move from PAUSED to STOPPING_1 without
6645 // a resume so we must ensure hardware is running
6646 doHwResume = true;
6647 mHwPaused = false;
6648 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006649 }
6650 }
Eric Laurente93cc032016-05-05 10:15:10 -07006651 } else if (last) {
6652 ALOGV("stopping1 underrun retries left %d", track->mRetryCount);
6653 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006654 }
6655 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07006656 // Drain has completed or we are in standby, signal presentation complete
6657 if (!(mDrainSequence & 1) || !last || mStandby) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08006658 track->mState = TrackBase::STOPPED;
Andy Hung59de4262021-06-14 10:53:54 -07006659 track->presentationComplete(latency_l());
Eric Laurentbfb1b832013-01-07 09:53:42 -08006660 track->reset();
6661 tracksToRemove->add(track);
Dean Wheatley12473e92021-03-18 23:00:55 +11006662 // OFFLOADED stop resets frame counts.
Andy Hungf3234512018-07-03 14:51:47 -07006663 if (!mUseAsyncWrite) {
6664 // If we don't get explicit drain notification we must
6665 // register discontinuity regardless of whether this is
6666 // the previous (!last) or the upcoming (last) track
6667 // to avoid skipping the discontinuity.
Dean Wheatley12473e92021-03-18 23:00:55 +11006668 mTimestampVerifier.discontinuity(
6669 mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Andy Hungf3234512018-07-03 14:51:47 -07006670 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006671 }
6672 } else {
6673 // No buffers for this track. Give it a few chances to
6674 // fill a buffer, then remove it from active list.
6675 if (--(track->mRetryCount) <= 0) {
Andy Hungf8044752016-07-27 14:58:11 -07006676 bool running = false;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006677 uint64_t position = 0;
6678 struct timespec unused;
6679 // The running check restarts the retry counter at least once.
6680 status_t ret = mOutput->stream->getPresentationPosition(&position, &unused);
6681 if (ret == NO_ERROR && position != mOffloadUnderrunPosition) {
6682 running = true;
6683 mOffloadUnderrunPosition = position;
6684 }
6685 if (ret == NO_ERROR) {
Andy Hungf8044752016-07-27 14:58:11 -07006686 ALOGVV("underrun counter, running(%d): %lld vs %lld", running,
6687 (long long)position, (long long)mOffloadUnderrunPosition);
6688 }
6689 if (running) { // still running, give us more time.
6690 track->mRetryCount = kMaxTrackRetriesOffload;
6691 } else {
Andy Hungc0691382018-09-12 18:01:57 -07006692 ALOGV("OffloadThread: BUFFER TIMEOUT: remove track(%d) from active list",
6693 track->id());
Andy Hungf8044752016-07-27 14:58:11 -07006694 tracksToRemove->add(track);
Glenn Kastend3bb6452016-12-05 18:14:37 -08006695 // tell client process that the track was disabled because of underrun;
Andy Hungf8044752016-07-27 14:58:11 -07006696 // it will then automatically call start() when data is available
6697 track->disable();
6698 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006699 } else if (last){
6700 mixerStatus = MIXER_TRACKS_ENABLED;
6701 }
6702 }
6703 }
6704 // compute volume for this track
Wenfeng Sun79458332019-05-29 20:12:43 +08006705 if (track->isReady()) { // check ready to prevent premature start.
6706 processVolume_l(track, last);
6707 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006708 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07006709
Eric Laurentea0fade2013-10-04 16:23:48 -07006710 // make sure the pause/flush/resume sequence is executed in the right order.
6711 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
6712 // before flush and then resume HW. This can happen in case of pause/flush/resume
6713 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07006714 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006715 status_t result = mOutput->stream->pause();
6716 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07006717 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07006718 if (mFlushPending) {
6719 flushHw_l();
Eric Laurent6bf9ae22013-08-30 15:12:37 -07006720 }
Eric Laurentfd477972013-10-25 18:10:40 -07006721 if (!mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006722 status_t result = mOutput->stream->resume();
6723 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07006724 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07006725
Eric Laurentbfb1b832013-01-07 09:53:42 -08006726 // remove all the tracks that need to be...
6727 removeTracks_l(*tracksToRemove);
6728
6729 return mixerStatus;
6730}
6731
Eric Laurentbfb1b832013-01-07 09:53:42 -08006732// must be called with thread mutex locked
6733bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
6734{
Eric Laurent3b4529e2013-09-05 18:09:19 -07006735 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
6736 mWriteAckSequence, mDrainSequence);
6737 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08006738 return true;
6739 }
6740 return false;
6741}
6742
Eric Laurentbfb1b832013-01-07 09:53:42 -08006743bool AudioFlinger::OffloadThread::waitingAsyncCallback()
6744{
6745 Mutex::Autolock _l(mLock);
6746 return waitingAsyncCallback_l();
6747}
6748
6749void AudioFlinger::OffloadThread::flushHw_l()
6750{
Eric Laurente659ef42014-09-29 13:06:46 -07006751 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08006752 // Flush anything still waiting in the mixbuffer
6753 mCurrentWriteLength = 0;
6754 mBytesRemaining = 0;
6755 mPausedWriteLength = 0;
6756 mPausedBytesRemaining = 0;
Eric Laurent3eaf66b2016-04-01 14:44:17 -07006757 // reset bytes written count to reflect that DSP buffers are empty after flush.
6758 mBytesWritten = 0;
Andy Hungf8044752016-07-27 14:58:11 -07006759 mOffloadUnderrunPosition = ~0LL;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08006760
Eric Laurentbfb1b832013-01-07 09:53:42 -08006761 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07006762 // discard any pending drain or write ack by incrementing sequence
6763 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
6764 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006765 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07006766 mCallbackThread->setWriteBlocked(mWriteAckSequence);
6767 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006768 }
6769}
6770
Haynes Mathew George05317d22016-05-03 16:34:26 -07006771void AudioFlinger::OffloadThread::invalidateTracks(audio_stream_type_t streamType)
6772{
6773 Mutex::Autolock _l(mLock);
Eric Laurent13084622016-05-17 10:51:49 -07006774 if (PlaybackThread::invalidateTracks_l(streamType)) {
6775 mFlushPending = true;
6776 }
Haynes Mathew George05317d22016-05-03 16:34:26 -07006777}
6778
Eric Laurentbfb1b832013-01-07 09:53:42 -08006779// ----------------------------------------------------------------------------
6780
Eric Laurent81784c32012-11-19 14:55:58 -08006781AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurent72e3f392015-05-20 14:43:50 -07006782 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id, bool systemReady)
jiabinc52b1ff2019-10-31 17:20:42 -07006783 : MixerThread(audioFlinger, mainThread->getOutput(), id,
Eric Laurent72e3f392015-05-20 14:43:50 -07006784 systemReady, DUPLICATING),
Eric Laurent81784c32012-11-19 14:55:58 -08006785 mWaitTimeMs(UINT_MAX)
6786{
6787 addOutputTrack(mainThread);
6788}
6789
6790AudioFlinger::DuplicatingThread::~DuplicatingThread()
6791{
6792 for (size_t i = 0; i < mOutputTracks.size(); i++) {
6793 mOutputTracks[i]->destroy();
6794 }
6795}
6796
6797void AudioFlinger::DuplicatingThread::threadLoop_mix()
6798{
6799 // mix buffers...
6800 if (outputsReady(outputTracks)) {
Glenn Kastend79072e2016-01-06 08:41:20 -08006801 mAudioMixer->process();
Eric Laurent81784c32012-11-19 14:55:58 -08006802 } else {
Eric Laurent02b57082014-11-07 17:28:28 -08006803 if (mMixerBufferValid) {
6804 memset(mMixerBuffer, 0, mMixerBufferSize);
6805 } else {
6806 memset(mSinkBuffer, 0, mSinkBufferSize);
6807 }
Eric Laurent81784c32012-11-19 14:55:58 -08006808 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006809 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08006810 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08006811 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006812 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08006813}
6814
6815void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
6816{
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006817 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006818 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006819 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006820 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006821 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006822 }
6823 } else if (mBytesWritten != 0) {
6824 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
6825 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08006826 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08006827 } else {
6828 // flush remaining overflow buffers in output tracks
6829 writeFrames = 0;
6830 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006831 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08006832 }
6833}
6834
Eric Laurentbfb1b832013-01-07 09:53:42 -08006835ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08006836{
6837 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hung1c86ebe2018-05-29 20:29:08 -07006838 const ssize_t actualWritten = outputTracks[i]->write(mSinkBuffer, writeFrames);
6839
6840 // Consider the first OutputTrack for timestamp and frame counting.
6841
6842 // The threadLoop() generally assumes writing a full sink buffer size at a time.
6843 // Here, we correct for writeFrames of 0 (a stop) or underruns because
6844 // we always claim success.
6845 if (i == 0) {
6846 const ssize_t correction = mSinkBufferSize / mFrameSize - actualWritten;
6847 ALOGD_IF(correction != 0 && writeFrames != 0,
6848 "%s: writeFrames:%u actualWritten:%zd correction:%zd mFramesWritten:%lld",
6849 __func__, writeFrames, actualWritten, correction, (long long)mFramesWritten);
6850 mFramesWritten -= correction;
6851 }
6852
6853 // TODO: Report correction for the other output tracks and show in the dump.
Eric Laurent81784c32012-11-19 14:55:58 -08006854 }
Andy Hungcf10d742020-04-28 15:38:24 -07006855 if (mStandby) {
6856 mThreadMetrics.logBeginInterval();
6857 mStandby = false;
6858 }
Andy Hung25c2dac2014-02-27 14:56:00 -08006859 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08006860}
6861
6862void AudioFlinger::DuplicatingThread::threadLoop_standby()
6863{
6864 // DuplicatingThread implements standby by stopping all tracks
6865 for (size_t i = 0; i < outputTracks.size(); i++) {
6866 outputTracks[i]->stop();
6867 }
6868}
6869
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07006870void AudioFlinger::DuplicatingThread::dumpInternals_l(int fd, const Vector<String16>& args __unused)
Andy Hung1bc088a2018-02-09 15:57:31 -08006871{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07006872 MixerThread::dumpInternals_l(fd, args);
Andy Hung1bc088a2018-02-09 15:57:31 -08006873
6874 std::stringstream ss;
6875 const size_t numTracks = mOutputTracks.size();
6876 ss << " " << numTracks << " OutputTracks";
6877 if (numTracks > 0) {
6878 ss << ":";
6879 for (const auto &track : mOutputTracks) {
6880 const sp<ThreadBase> thread = track->thread().promote();
Andy Hungc0691382018-09-12 18:01:57 -07006881 ss << " (" << track->id() << " : ";
Andy Hung1bc088a2018-02-09 15:57:31 -08006882 if (thread.get() != nullptr) {
6883 ss << thread.get() << ", " << thread->id();
6884 } else {
6885 ss << "null";
6886 }
6887 ss << ")";
6888 }
6889 }
6890 ss << "\n";
6891 std::string result = ss.str();
6892 write(fd, result.c_str(), result.size());
6893}
6894
Eric Laurent81784c32012-11-19 14:55:58 -08006895void AudioFlinger::DuplicatingThread::saveOutputTracks()
6896{
6897 outputTracks = mOutputTracks;
6898}
6899
6900void AudioFlinger::DuplicatingThread::clearOutputTracks()
6901{
6902 outputTracks.clear();
6903}
6904
6905void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
6906{
6907 Mutex::Autolock _l(mLock);
Andy Hungc25b84a2015-01-14 19:04:10 -08006908 // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
6909 // Adjust for thread->sampleRate() to determine minimum buffer frame count.
6910 // Then triple buffer because Threads do not run synchronously and may not be clock locked.
6911 const size_t frameCount =
6912 3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
6913 // TODO: Consider asynchronous sample rate conversion to handle clock disparity
6914 // from different OutputTracks and their associated MixerThreads (e.g. one may
6915 // nearly empty and the other may be dropping data).
6916
Svet Ganov33761132021-05-13 22:51:08 +00006917 // TODO b/182392769: use attribution source util, move to server edge
6918 AttributionSourceState attributionSource = AttributionSourceState();
6919 attributionSource.uid = VALUE_OR_FATAL(legacy2aidl_uid_t_int32_t(
Philip P. Moltmannbda45752020-07-17 16:41:18 -07006920 IPCThreadState::self()->getCallingUid()));
Svet Ganov33761132021-05-13 22:51:08 +00006921 attributionSource.pid = VALUE_OR_FATAL(legacy2aidl_pid_t_int32_t(
Philip P. Moltmannbda45752020-07-17 16:41:18 -07006922 IPCThreadState::self()->getCallingPid()));
Svet Ganov33761132021-05-13 22:51:08 +00006923 attributionSource.token = sp<BBinder>::make();
Andy Hungc25b84a2015-01-14 19:04:10 -08006924 sp<OutputTrack> outputTrack = new OutputTrack(thread,
Eric Laurent81784c32012-11-19 14:55:58 -08006925 this,
6926 mSampleRate,
Andy Hungc25b84a2015-01-14 19:04:10 -08006927 mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08006928 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08006929 frameCount,
Svet Ganov33761132021-05-13 22:51:08 +00006930 attributionSource);
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07006931 status_t status = outputTrack != 0 ? outputTrack->initCheck() : (status_t) NO_MEMORY;
6932 if (status != NO_ERROR) {
6933 ALOGE("addOutputTrack() initCheck failed %d", status);
6934 return;
Eric Laurent81784c32012-11-19 14:55:58 -08006935 }
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07006936 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
6937 mOutputTracks.add(outputTrack);
6938 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
6939 updateWaitTime_l();
Eric Laurent81784c32012-11-19 14:55:58 -08006940}
6941
6942void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
6943{
6944 Mutex::Autolock _l(mLock);
6945 for (size_t i = 0; i < mOutputTracks.size(); i++) {
6946 if (mOutputTracks[i]->thread() == thread) {
6947 mOutputTracks[i]->destroy();
6948 mOutputTracks.removeAt(i);
6949 updateWaitTime_l();
Eric Laurentf6870ae2015-05-08 10:50:03 -07006950 if (thread->getOutput() == mOutput) {
6951 mOutput = NULL;
6952 }
Eric Laurent81784c32012-11-19 14:55:58 -08006953 return;
6954 }
6955 }
Eric Laurentf6870ae2015-05-08 10:50:03 -07006956 ALOGV("removeOutputTrack(): unknown thread: %p", thread);
Eric Laurent81784c32012-11-19 14:55:58 -08006957}
6958
6959// caller must hold mLock
6960void AudioFlinger::DuplicatingThread::updateWaitTime_l()
6961{
6962 mWaitTimeMs = UINT_MAX;
6963 for (size_t i = 0; i < mOutputTracks.size(); i++) {
6964 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
6965 if (strong != 0) {
6966 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
6967 if (waitTimeMs < mWaitTimeMs) {
6968 mWaitTimeMs = waitTimeMs;
6969 }
6970 }
6971 }
6972}
6973
6974
6975bool AudioFlinger::DuplicatingThread::outputsReady(
6976 const SortedVector< sp<OutputTrack> > &outputTracks)
6977{
6978 for (size_t i = 0; i < outputTracks.size(); i++) {
6979 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
6980 if (thread == 0) {
6981 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
6982 outputTracks[i].get());
6983 return false;
6984 }
6985 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
6986 // see note at standby() declaration
6987 if (playbackThread->standby() && !playbackThread->isSuspended()) {
6988 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
6989 thread.get());
6990 return false;
6991 }
6992 }
6993 return true;
6994}
6995
Kevin Rocard12381092018-04-11 09:19:59 -07006996void AudioFlinger::DuplicatingThread::sendMetadataToBackend_l(
6997 const StreamOutHalInterface::SourceMetadata& metadata)
Kevin Rocard069c2712018-03-29 19:09:14 -07006998{
Kevin Rocard12381092018-04-11 09:19:59 -07006999 for (auto& outputTrack : outputTracks) { // not mOutputTracks
7000 outputTrack->setMetadatas(metadata.tracks);
7001 }
Kevin Rocard069c2712018-03-29 19:09:14 -07007002}
7003
Eric Laurent81784c32012-11-19 14:55:58 -08007004uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
7005{
7006 return (mWaitTimeMs * 1000) / 2;
7007}
7008
7009void AudioFlinger::DuplicatingThread::cacheParameters_l()
7010{
7011 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
7012 updateWaitTime_l();
7013
7014 MixerThread::cacheParameters_l();
7015}
7016
Eric Laurent6acd1d42017-01-04 14:23:29 -08007017
Eric Laurent81784c32012-11-19 14:55:58 -08007018// ----------------------------------------------------------------------------
7019// Record
7020// ----------------------------------------------------------------------------
7021
7022AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
7023 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08007024 audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -07007025 bool systemReady
Glenn Kasten46909e72013-02-26 09:20:22 -08007026 ) :
Andy Hungcf10d742020-04-28 15:38:24 -07007027 ThreadBase(audioFlinger, id, RECORD, systemReady, false /* isOut */),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007028 mInput(input),
Mikhail Naganov2534b382019-09-25 13:05:02 -07007029 mSource(mInput),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007030 mActiveTracks(&this->mLocalLog),
7031 mRsmpInBuffer(NULL),
Glenn Kasten1b291842016-07-18 14:55:21 -07007032 // mRsmpInFrames, mRsmpInFramesP2, and mRsmpInFramesOA are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007033 mRsmpInRear(0)
Glenn Kastenb880f5e2014-05-07 08:43:45 -07007034 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
7035 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007036 // mFastCapture below
7037 , mFastCaptureFutex(0)
7038 // mInputSource
7039 // mPipeSink
7040 // mPipeSource
7041 , mPipeFramesP2(0)
7042 // mPipeMemory
7043 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07007044 , mFastTrackAvail(false)
Eric Laurentd8365c52017-07-16 15:27:05 -07007045 , mBtNrecSuspended(false)
Eric Laurent81784c32012-11-19 14:55:58 -08007046{
Glenn Kastend7dca052015-03-05 16:05:54 -08007047 snprintf(mThreadName, kThreadNameLength, "AudioIn_%X", id);
7048 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08007049
George Burgess IVa8f90c12020-05-14 11:27:19 -07007050 if (mInput->audioHwDev != nullptr) {
Andy Hungc8fddf32018-08-08 18:32:37 -07007051 mIsMsdDevice = strcmp(
7052 mInput->audioHwDev->moduleName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0;
7053 }
7054
Glenn Kastendeca2ae2014-02-07 10:25:56 -08007055 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007056
Andy Hungc8fddf32018-08-08 18:32:37 -07007057 // TODO: We may also match on address as well as device type for
7058 // AUDIO_DEVICE_IN_BUS, AUDIO_DEVICE_IN_BLUETOOTH_A2DP, AUDIO_DEVICE_IN_REMOTE_SUBMIX
jiabinc52b1ff2019-10-31 17:20:42 -07007059 // TODO: This property should be ensure that only contains one single device type.
7060 mTimestampCorrectedDevice = (audio_devices_t)property_get_int64(
7061 "audio.timestamp.corrected_input_device",
Andy Hungc8fddf32018-08-08 18:32:37 -07007062 (int64_t)(mIsMsdDevice ? AUDIO_DEVICE_IN_BUS // turn on by default for MSD
7063 : AUDIO_DEVICE_NONE));
7064
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007065 // create an NBAIO source for the HAL input stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07007066 mInputSource = new AudioStreamInSource(input->stream);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007067 size_t numCounterOffers = 0;
7068 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07007069#if !LOG_NDEBUG
7070 ssize_t index =
7071#else
7072 (void)
7073#endif
7074 mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007075 ALOG_ASSERT(index == 0);
7076
7077 // initialize fast capture depending on configuration
7078 bool initFastCapture;
7079 switch (kUseFastCapture) {
7080 case FastCapture_Never:
7081 initFastCapture = false;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007082 ALOGV("%p kUseFastCapture = Never, initFastCapture = false", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007083 break;
7084 case FastCapture_Always:
7085 initFastCapture = true;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007086 ALOGV("%p kUseFastCapture = Always, initFastCapture = true", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007087 break;
7088 case FastCapture_Static:
Glenn Kasteneb9487e2015-07-22 09:15:17 -07007089 initFastCapture = (mFrameCount * 1000) / mSampleRate < kMinNormalCaptureBufferSizeMs;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007090 ALOGV("%p kUseFastCapture = Static, (%lld * 1000) / %u vs %u, initFastCapture = %d",
7091 this, (long long)mFrameCount, mSampleRate, kMinNormalCaptureBufferSizeMs,
7092 initFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007093 break;
7094 // case FastCapture_Dynamic:
7095 }
7096
7097 if (initFastCapture) {
Glenn Kastend198b852015-03-16 14:55:53 -07007098 // create a Pipe for FastCapture to write to, and for us and fast tracks to read from
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007099 NBAIO_Format format = mInputSource->format();
Glenn Kasten1b291842016-07-18 14:55:21 -07007100 // quadruple-buffering of 20 ms each; this ensures we can sleep for 20ms in RecordThread
7101 size_t pipeFramesP2 = roundup(4 * FMS_20 * mSampleRate / 1000);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007102 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007103 void *pipeBuffer = nullptr;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007104 const sp<MemoryDealer> roHeap(readOnlyHeap());
7105 sp<IMemory> pipeMemory;
7106 if ((roHeap == 0) ||
7107 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07007108 (pipeBuffer = pipeMemory->unsecurePointer()) == nullptr) {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007109 ALOGE("not enough memory for pipe buffer size=%zu; "
7110 "roHeap=%p, pipeMemory=%p, pipeBuffer=%p; roHeapSize: %lld",
7111 pipeSize, roHeap.get(), pipeMemory.get(), pipeBuffer,
7112 (long long)kRecordThreadReadOnlyHeapSize);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007113 goto failed;
7114 }
7115 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
7116 memset(pipeBuffer, 0, pipeSize);
7117 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
7118 const NBAIO_Format offers[1] = {format};
7119 size_t numCounterOffers = 0;
7120 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
7121 ALOG_ASSERT(index == 0);
7122 mPipeSink = pipe;
7123 PipeReader *pipeReader = new PipeReader(*pipe);
7124 numCounterOffers = 0;
7125 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
7126 ALOG_ASSERT(index == 0);
7127 mPipeSource = pipeReader;
7128 mPipeFramesP2 = pipeFramesP2;
7129 mPipeMemory = pipeMemory;
7130
7131 // create fast capture
7132 mFastCapture = new FastCapture();
7133 FastCaptureStateQueue *sq = mFastCapture->sq();
7134#ifdef STATE_QUEUE_DUMP
7135 // FIXME
7136#endif
7137 FastCaptureState *state = sq->begin();
7138 state->mCblk = NULL;
7139 state->mInputSource = mInputSource.get();
7140 state->mInputSourceGen++;
7141 state->mPipeSink = pipe;
7142 state->mPipeSinkGen++;
7143 state->mFrameCount = mFrameCount;
7144 state->mCommand = FastCaptureState::COLD_IDLE;
7145 // already done in constructor initialization list
7146 //mFastCaptureFutex = 0;
7147 state->mColdFutexAddr = &mFastCaptureFutex;
7148 state->mColdGen++;
7149 state->mDumpState = &mFastCaptureDumpState;
7150#ifdef TEE_SINK
7151 // FIXME
7152#endif
7153 mFastCaptureNBLogWriter = audioFlinger->newWriter_l(kFastCaptureLogSize, "FastCapture");
7154 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
7155 sq->end();
7156 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
7157
7158 // start the fast capture
7159 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
7160 pid_t tid = mFastCapture->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07007161 sendPrioConfigEvent(getpid(), tid, kPriorityFastCapture, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08007162 stream()->setHalThreadPriority(kPriorityFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007163#ifdef AUDIO_WATCHDOG
7164 // FIXME
7165#endif
7166
Glenn Kasten6e6704c2014-07-03 10:20:00 -07007167 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007168 }
Andy Hung8946a282018-04-19 20:04:56 -07007169#ifdef TEE_SINK
7170 mTee.set(mInputSource->format(), NBAIO_Tee::TEE_FLAG_INPUT_THREAD);
7171 mTee.setId(std::string("_") + std::to_string(mId) + "_C");
7172#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007173failed: ;
7174
7175 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08007176}
7177
Eric Laurent81784c32012-11-19 14:55:58 -08007178AudioFlinger::RecordThread::~RecordThread()
7179{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007180 if (mFastCapture != 0) {
7181 FastCaptureStateQueue *sq = mFastCapture->sq();
7182 FastCaptureState *state = sq->begin();
7183 if (state->mCommand == FastCaptureState::COLD_IDLE) {
7184 int32_t old = android_atomic_inc(&mFastCaptureFutex);
7185 if (old == -1) {
7186 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
7187 }
7188 }
7189 state->mCommand = FastCaptureState::EXIT;
7190 sq->end();
7191 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
7192 mFastCapture->join();
7193 mFastCapture.clear();
7194 }
7195 mAudioFlinger->unregisterWriter(mFastCaptureNBLogWriter);
Glenn Kasten481fb672013-09-30 14:39:28 -07007196 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung57446612015-04-19 23:56:46 -07007197 free(mRsmpInBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08007198}
7199
7200void AudioFlinger::RecordThread::onFirstRef()
7201{
Glenn Kastend7dca052015-03-05 16:05:54 -08007202 run(mThreadName, PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08007203}
7204
Eric Laurent555530a2017-02-07 18:17:24 -08007205void AudioFlinger::RecordThread::preExit()
7206{
7207 ALOGV(" preExit()");
7208 Mutex::Autolock _l(mLock);
7209 for (size_t i = 0; i < mTracks.size(); i++) {
7210 sp<RecordTrack> track = mTracks[i];
7211 track->invalidate();
7212 }
7213 mActiveTracks.clear();
7214 mStartStopCond.broadcast();
7215}
7216
Eric Laurent81784c32012-11-19 14:55:58 -08007217bool AudioFlinger::RecordThread::threadLoop()
7218{
Eric Laurent81784c32012-11-19 14:55:58 -08007219 nsecs_t lastWarning = 0;
7220
7221 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08007222
Glenn Kastenf10ffec2013-11-20 16:40:08 -08007223reacquire_wakelock:
7224 sp<RecordTrack> activeTrack;
7225 {
7226 Mutex::Autolock _l(mLock);
Andy Hungdae27702016-10-31 14:01:16 -07007227 acquireWakeLock_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08007228 }
7229
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007230 // used to request a deferred sleep, to be executed later while mutex is unlocked
7231 uint32_t sleepUs = 0;
7232
Andy Hung446f4df2019-02-21 12:26:41 -08007233 int64_t lastLoopCountRead = -2; // never matches "previous" loop, when loopCount = 0.
7234
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007235 // loop while there is work to do
Andy Hung446f4df2019-02-21 12:26:41 -08007236 for (int64_t loopCount = 0;; ++loopCount) { // loopCount used for statistics tracking
Glenn Kastenc527a7c2013-08-13 15:43:49 -07007237 Vector< sp<EffectChain> > effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07007238
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007239 // activeTracks accumulates a copy of a subset of mActiveTracks
7240 Vector< sp<RecordTrack> > activeTracks;
7241
Glenn Kasten735f45f2014-08-18 15:51:59 -07007242 // reference to the (first and only) active fast track
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007243 sp<RecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07007244
Glenn Kasten735f45f2014-08-18 15:51:59 -07007245 // reference to a fast track which is about to be removed
7246 sp<RecordTrack> fastTrackToRemove;
7247
Eric Laurent33403f02020-05-29 18:35:06 -07007248 bool silenceFastCapture = false;
7249
Eric Laurent81784c32012-11-19 14:55:58 -08007250 { // scope for mLock
7251 Mutex::Autolock _l(mLock);
Eric Laurent000a4192014-01-29 15:17:32 -08007252
Eric Laurent021cf962014-05-13 10:18:14 -07007253 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08007254
Eric Laurent000a4192014-01-29 15:17:32 -08007255 // check exitPending here because checkForNewParameters_l() and
7256 // checkForNewParameters_l() can temporarily release mLock
7257 if (exitPending()) {
7258 break;
7259 }
7260
Eric Laurent5c25d562016-07-13 17:17:45 -07007261 // sleep with mutex unlocked
7262 if (sleepUs > 0) {
Glenn Kastenf9715e42016-07-13 14:02:03 -07007263 ATRACE_BEGIN("sleepC");
Eric Laurent5c25d562016-07-13 17:17:45 -07007264 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)sleepUs));
7265 ATRACE_END();
7266 sleepUs = 0;
7267 continue;
7268 }
7269
Glenn Kasten2b806402013-11-20 16:37:38 -08007270 // if no active track(s), then standby and release wakelock
7271 size_t size = mActiveTracks.size();
7272 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07007273 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07007274 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08007275 releaseWakeLock_l();
7276 ALOGV("RecordThread: loop stopping");
7277 // go to sleep
7278 mWaitWorkCV.wait(mLock);
7279 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08007280 goto reacquire_wakelock;
7281 }
7282
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007283 bool doBroadcast = false;
Eric Laurent5c25d562016-07-13 17:17:45 -07007284 bool allStopped = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007285 for (size_t i = 0; i < size; ) {
Glenn Kasten9e982352013-08-14 14:39:50 -07007286
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007287 activeTrack = mActiveTracks[i];
7288 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07007289 if (activeTrack->isFastTrack()) {
7290 ALOG_ASSERT(fastTrackToRemove == 0);
7291 fastTrackToRemove = activeTrack;
7292 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007293 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08007294 mActiveTracks.remove(activeTrack);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007295 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07007296 continue;
7297 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007298
7299 TrackBase::track_state activeTrackState = activeTrack->mState;
7300 switch (activeTrackState) {
7301
7302 case TrackBase::PAUSING:
7303 mActiveTracks.remove(activeTrack);
Andy Hungce685402018-10-05 17:23:27 -07007304 activeTrack->mState = TrackBase::PAUSED;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007305 doBroadcast = true;
7306 size--;
7307 continue;
7308
7309 case TrackBase::STARTING_1:
7310 sleepUs = 10000;
7311 i++;
Eric Laurent5c25d562016-07-13 17:17:45 -07007312 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007313 continue;
7314
7315 case TrackBase::STARTING_2:
7316 doBroadcast = true;
Andy Hungcf10d742020-04-28 15:38:24 -07007317 if (mStandby) {
7318 mThreadMetrics.logBeginInterval();
7319 mStandby = false;
7320 }
Glenn Kasten9e982352013-08-14 14:39:50 -07007321 activeTrack->mState = TrackBase::ACTIVE;
Eric Laurent5c25d562016-07-13 17:17:45 -07007322 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007323 break;
7324
7325 case TrackBase::ACTIVE:
Eric Laurent5c25d562016-07-13 17:17:45 -07007326 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007327 break;
7328
Andy Hungce685402018-10-05 17:23:27 -07007329 case TrackBase::IDLE: // cannot be on ActiveTracks if idle
7330 case TrackBase::PAUSED: // cannot be on ActiveTracks if paused
7331 case TrackBase::STOPPED: // cannot be on ActiveTracks if destroyed/terminated
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007332 default:
Andy Hungce685402018-10-05 17:23:27 -07007333 LOG_ALWAYS_FATAL("%s: Unexpected active track state:%d, id:%d, tracks:%zu",
7334 __func__, activeTrackState, activeTrack->id(), size);
Glenn Kasten9e982352013-08-14 14:39:50 -07007335 }
Glenn Kasten9e982352013-08-14 14:39:50 -07007336
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007337 if (activeTrack->isFastTrack()) {
7338 ALOG_ASSERT(!mFastTrackAvail);
7339 ALOG_ASSERT(fastTrack == 0);
Eric Laurent33403f02020-05-29 18:35:06 -07007340 // if the active fast track is silenced either:
7341 // 1) silence the whole capture from fast capture buffer if this is
7342 // the only active track
7343 // 2) invalidate this track: this will cause the client to reconnect and possibly
7344 // be invalidated again until unsilenced
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02007345 bool invalidate = false;
Eric Laurent33403f02020-05-29 18:35:06 -07007346 if (activeTrack->isSilenced()) {
7347 if (size > 1) {
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02007348 invalidate = true;
Eric Laurent33403f02020-05-29 18:35:06 -07007349 } else {
7350 silenceFastCapture = true;
7351 }
7352 }
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02007353 // Invalidate fast tracks if access to audio history is required as this is not
7354 // possible with fast tracks. Once the fast track has been invalidated, no new
7355 // fast track will be created until mMaxSharedAudioHistoryMs is cleared.
7356 if (mMaxSharedAudioHistoryMs != 0) {
7357 invalidate = true;
7358 }
7359 if (invalidate) {
7360 activeTrack->invalidate();
7361 ALOG_ASSERT(fastTrackToRemove == 0);
7362 fastTrackToRemove = activeTrack;
7363 removeTrack_l(activeTrack);
7364 mActiveTracks.remove(activeTrack);
7365 size--;
7366 continue;
7367 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007368 fastTrack = activeTrack;
7369 }
Eric Laurent33403f02020-05-29 18:35:06 -07007370
7371 activeTracks.add(activeTrack);
7372 i++;
7373
Glenn Kasten9e982352013-08-14 14:39:50 -07007374 }
Eric Laurent5c25d562016-07-13 17:17:45 -07007375
Andy Hungdae27702016-10-31 14:01:16 -07007376 mActiveTracks.updatePowerState(this);
7377
Kevin Rocard069c2712018-03-29 19:09:14 -07007378 updateMetadata_l();
7379
Eric Laurent5c25d562016-07-13 17:17:45 -07007380 if (allStopped) {
7381 standbyIfNotAlreadyInStandby();
7382 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007383 if (doBroadcast) {
7384 mStartStopCond.broadcast();
7385 }
7386
7387 // sleep if there are no active tracks to process
Eric Tan39ec8d62018-07-24 09:49:29 -07007388 if (activeTracks.isEmpty()) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007389 if (sleepUs == 0) {
7390 sleepUs = kRecordThreadSleepUs;
7391 }
7392 continue;
7393 }
7394 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07007395
Eric Laurent81784c32012-11-19 14:55:58 -08007396 lockEffectChains_l(effectChains);
7397 }
7398
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007399 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07007400
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007401 size_t size = effectChains.size();
7402 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07007403 // thread mutex is not locked, but effect chain is locked
7404 effectChains[i]->process_l();
7405 }
7406
Glenn Kasten735f45f2014-08-18 15:51:59 -07007407 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007408 if (mFastCapture != 0) {
7409 FastCaptureStateQueue *sq = mFastCapture->sq();
7410 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07007411 bool didModify = false;
7412 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007413 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
7414 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
7415 if (state->mCommand == FastCaptureState::COLD_IDLE) {
7416 int32_t old = android_atomic_inc(&mFastCaptureFutex);
7417 if (old == -1) {
7418 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
7419 }
7420 }
7421 state->mCommand = FastCaptureState::READ_WRITE;
7422#if 0 // FIXME
7423 mFastCaptureDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08007424 FastThreadDumpState::kSamplingNforLowRamDevice :
7425 FastThreadDumpState::kSamplingN);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007426#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07007427 didModify = true;
7428 }
7429 audio_track_cblk_t *cblkOld = state->mCblk;
7430 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
7431 if (cblkNew != cblkOld) {
7432 state->mCblk = cblkNew;
7433 // block until acked if removing a fast track
7434 if (cblkOld != NULL) {
7435 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
7436 }
7437 didModify = true;
7438 }
jiabin01c8f562018-07-19 17:47:28 -07007439 AudioBufferProvider* abp = (fastTrack != 0 && fastTrack->isPatchTrack()) ?
7440 reinterpret_cast<AudioBufferProvider*>(fastTrack.get()) : nullptr;
7441 if (state->mFastPatchRecordBufferProvider != abp) {
7442 state->mFastPatchRecordBufferProvider = abp;
7443 state->mFastPatchRecordFormat = fastTrack == 0 ?
7444 AUDIO_FORMAT_INVALID : fastTrack->format();
7445 didModify = true;
7446 }
Eric Laurent33403f02020-05-29 18:35:06 -07007447 if (state->mSilenceCapture != silenceFastCapture) {
7448 state->mSilenceCapture = silenceFastCapture;
7449 didModify = true;
7450 }
Glenn Kasten735f45f2014-08-18 15:51:59 -07007451 sq->end(didModify);
7452 if (didModify) {
7453 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007454#if 0
7455 if (kUseFastCapture == FastCapture_Dynamic) {
7456 mNormalSource = mPipeSource;
7457 }
7458#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007459 }
7460 }
7461
Glenn Kasten735f45f2014-08-18 15:51:59 -07007462 // now run the fast track destructor with thread mutex unlocked
7463 fastTrackToRemove.clear();
7464
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007465 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
7466 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
7467 // slow, then this RecordThread will overrun by not calling HAL read often enough.
7468 // If destination is non-contiguous, first read past the nominal end of buffer, then
7469 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07007470
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007471 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007472 ssize_t framesRead;
Andy Hung446f4df2019-02-21 12:26:41 -08007473 const int64_t lastIoBeginNs = systemTime(); // start IO timing
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007474
7475 // If an NBAIO source is present, use it to read the normal capture's data
7476 if (mPipeSource != 0) {
Andy Hung156317a2018-08-02 11:49:29 -07007477 size_t framesToRead = min(mRsmpInFramesOA - rear, mRsmpInFramesP2 / 2);
Andy Hungd5b638f2018-04-30 13:56:10 -07007478
7479 // The audio fifo read() returns OVERRUN on overflow, and advances the read pointer
7480 // to the full buffer point (clearing the overflow condition). Upon OVERRUN error,
7481 // we immediately retry the read() to get data and prevent another overflow.
7482 for (int retries = 0; retries <= 2; ++retries) {
7483 ALOGW_IF(retries > 0, "overrun on read from pipe, retry #%d", retries);
7484 framesRead = mPipeSource->read((uint8_t*)mRsmpInBuffer + rear * mFrameSize,
7485 framesToRead);
7486 if (framesRead != OVERRUN) break;
7487 }
7488
Andy Hung7a3dc6b2018-05-01 16:39:51 -07007489 const ssize_t availableToRead = mPipeSource->availableToRead();
7490 if (availableToRead >= 0) {
Glenn Kastena2f59b32020-08-03 16:37:24 -07007491 // PipeSource is the primary clock. It is up to the AudioRecord client to keep up.
Andy Hung7a3dc6b2018-05-01 16:39:51 -07007492 LOG_ALWAYS_FATAL_IF((size_t)availableToRead > mPipeFramesP2,
7493 "more frames to read than fifo size, %zd > %zu",
7494 availableToRead, mPipeFramesP2);
7495 const size_t pipeFramesFree = mPipeFramesP2 - availableToRead;
7496 const size_t sleepFrames = min(pipeFramesFree, mRsmpInFramesP2) / 2;
7497 ALOGVV("mPipeFramesP2:%zu mRsmpInFramesP2:%zu sleepFrames:%zu availableToRead:%zd",
7498 mPipeFramesP2, mRsmpInFramesP2, sleepFrames, availableToRead);
Glenn Kasten1b291842016-07-18 14:55:21 -07007499 sleepUs = (sleepFrames * 1000000LL) / mSampleRate;
7500 }
7501 if (framesRead < 0) {
7502 status_t status = (status_t) framesRead;
7503 switch (status) {
7504 case OVERRUN:
7505 ALOGW("overrun on read from pipe");
7506 framesRead = 0;
7507 break;
7508 case NEGOTIATE:
7509 ALOGE("re-negotiation is needed");
7510 framesRead = -1; // Will cause an attempt to recover.
7511 break;
7512 default:
7513 ALOGE("unknown error %d on read from pipe", status);
7514 break;
7515 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007516 }
7517 // otherwise use the HAL / AudioStreamIn directly
7518 } else {
Glenn Kastenec6a7032016-03-14 07:40:23 -07007519 ATRACE_BEGIN("read");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007520 size_t bytesRead;
Mikhail Naganov2534b382019-09-25 13:05:02 -07007521 status_t result = mSource->read(
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007522 (uint8_t*)mRsmpInBuffer + rear * mFrameSize, mBufferSize, &bytesRead);
Glenn Kastenec6a7032016-03-14 07:40:23 -07007523 ATRACE_END();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007524 if (result < 0) {
7525 framesRead = result;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007526 } else {
7527 framesRead = bytesRead / mFrameSize;
7528 }
7529 }
7530
Andy Hung446f4df2019-02-21 12:26:41 -08007531 const int64_t lastIoEndNs = systemTime(); // end IO timing
7532
Andy Hung3f0c9022016-01-15 17:49:46 -08007533 // Update server timestamp with server stats
7534 // systemTime() is optional if the hardware supports timestamps.
Andy Hung743f6402020-06-03 13:17:04 -07007535 if (framesRead >= 0) {
7536 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += framesRead;
7537 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = lastIoEndNs;
7538 }
Andy Hung3f0c9022016-01-15 17:49:46 -08007539
7540 // Update server timestamp with kernel stats
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007541 if (mPipeSource.get() == nullptr /* don't obtain for FastCapture, could block */) {
Andy Hung3f0c9022016-01-15 17:49:46 -08007542 int64_t position, time;
Andy Hung2e2c0bb2018-06-11 19:13:11 -07007543 if (mStandby) {
Dean Wheatley12473e92021-03-18 23:00:55 +11007544 mTimestampVerifier.discontinuity(audio_is_linear_pcm(mFormat) ?
7545 mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS :
7546 mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Mikhail Naganov2534b382019-09-25 13:05:02 -07007547 } else if (mSource->getCapturePosition(&position, &time) == NO_ERROR
Andy Hungc8fddf32018-08-08 18:32:37 -07007548 && time > mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]) {
7549
7550 mTimestampVerifier.add(position, time, mSampleRate);
7551
7552 // Correct timestamps
7553 if (isTimestampCorrectionEnabled()) {
Dean Wheatley56a583e2020-05-08 15:12:17 +10007554 ALOGVV("TS_BEFORE: %d %lld %lld",
Andy Hungc8fddf32018-08-08 18:32:37 -07007555 id(), (long long)time, (long long)position);
7556 auto correctedTimestamp = mTimestampVerifier.getLastCorrectedTimestamp();
7557 position = correctedTimestamp.mFrames;
7558 time = correctedTimestamp.mTimeNs;
Dean Wheatley56a583e2020-05-08 15:12:17 +10007559 ALOGVV("TS_AFTER: %d %lld %lld",
Andy Hungc8fddf32018-08-08 18:32:37 -07007560 id(), (long long)time, (long long)position);
7561 }
7562
Andy Hung3f0c9022016-01-15 17:49:46 -08007563 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = position;
7564 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] = time;
7565 // Note: In general record buffers should tend to be empty in
7566 // a properly running pipeline.
7567 //
7568 // Also, it is not advantageous to call get_presentation_position during the read
7569 // as the read obtains a lock, preventing the timestamp call from executing.
Andy Hung2e2c0bb2018-06-11 19:13:11 -07007570 } else {
7571 mTimestampVerifier.error();
Andy Hung3f0c9022016-01-15 17:49:46 -08007572 }
7573 }
Andy Hunge6c37112019-02-26 17:38:10 -08007574
7575 // From the timestamp, input read latency is negative output write latency.
7576 const audio_input_flags_t flags = mInput != NULL ? mInput->flags : AUDIO_INPUT_FLAG_NONE;
7577 const double latencyMs = RecordTrack::checkServerLatencySupported(mFormat, flags)
7578 ? - mTimestamp.getOutputServerLatencyMs(mSampleRate) : 0.;
7579 if (latencyMs != 0.) { // note 0. means timestamp is empty.
7580 mLatencyMs.add(latencyMs);
7581 }
7582
Andy Hung3f0c9022016-01-15 17:49:46 -08007583 // Use this to track timestamp information
7584 // ALOGD("%s", mTimestamp.toString().c_str());
7585
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007586 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07007587 ALOGE("read failed: framesRead=%zd", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007588 // Force input into standby so that it tries to recover at next read attempt
7589 inputStandBy();
7590 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007591 }
7592 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07007593 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07007594 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007595 ALOG_ASSERT(framesRead > 0);
Andy Hung6427e442018-08-09 12:51:02 -07007596 mFramesRead += framesRead;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007597
Andy Hung8946a282018-04-19 20:04:56 -07007598#ifdef TEE_SINK
7599 (void)mTee.write((uint8_t*)mRsmpInBuffer + rear * mFrameSize, framesRead);
7600#endif
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007601 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07007602 {
7603 size_t part1 = mRsmpInFramesP2 - rear;
7604 if ((size_t) framesRead > part1) {
Andy Hung57446612015-04-19 23:56:46 -07007605 memcpy(mRsmpInBuffer, (uint8_t*)mRsmpInBuffer + mRsmpInFramesP2 * mFrameSize,
Glenn Kasten3d61bc12014-06-16 10:25:20 -07007606 (framesRead - part1) * mFrameSize);
7607 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007608 }
Dean Wheatleyfd56e812020-11-06 22:32:21 +11007609 mRsmpInRear = audio_utils::safe_add_overflow(mRsmpInRear, (int32_t)framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007610
7611 size = activeTracks.size();
Svet Ganovf4ddfef2018-01-16 07:37:58 -08007612
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007613 // loop over each active track
7614 for (size_t i = 0; i < size; i++) {
7615 activeTrack = activeTracks[i];
7616
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007617 // skip fast tracks, as those are handled directly by FastCapture
7618 if (activeTrack->isFastTrack()) {
7619 continue;
7620 }
7621
Andy Hung73c02e42015-03-29 01:13:58 -07007622 // TODO: This code probably should be moved to RecordTrack.
Andy Hung97a893e2015-03-29 01:03:07 -07007623 // TODO: Update the activeTrack buffer converter in case of reconfigure.
7624
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007625 enum {
7626 OVERRUN_UNKNOWN,
7627 OVERRUN_TRUE,
7628 OVERRUN_FALSE
7629 } overrun = OVERRUN_UNKNOWN;
7630
7631 // loop over getNextBuffer to handle circular sink
7632 for (;;) {
7633
7634 activeTrack->mSink.frameCount = ~0;
7635 status_t status = activeTrack->getNextBuffer(&activeTrack->mSink);
7636 size_t framesOut = activeTrack->mSink.frameCount;
7637 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
7638
Andy Hung73c02e42015-03-29 01:13:58 -07007639 // check available frames and handle overrun conditions
7640 // if the record track isn't draining fast enough.
7641 bool hasOverrun;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007642 size_t framesIn;
Andy Hung73c02e42015-03-29 01:13:58 -07007643 activeTrack->mResamplerBufferProvider->sync(&framesIn, &hasOverrun);
7644 if (hasOverrun) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007645 overrun = OVERRUN_TRUE;
7646 }
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007647 if (framesOut == 0 || framesIn == 0) {
7648 break;
7649 }
7650
Andy Hung6770c6f2015-04-07 13:43:36 -07007651 // Don't allow framesOut to be larger than what is possible with resampling
7652 // from framesIn.
7653 // This isn't strictly necessary but helps limit buffer resizing in
7654 // RecordBufferConverter. TODO: remove when no longer needed.
7655 framesOut = min(framesOut,
7656 destinationFramesPossible(
7657 framesIn, mSampleRate, activeTrack->mSampleRate));
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07007658
7659 if (activeTrack->isDirect()) {
Daniel Van Veen9e2376e2018-09-27 14:37:58 +10007660 // No RecordBufferConverter used for direct streams. Pass
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07007661 // straight from RecordThread buffer to RecordTrack buffer.
7662 AudioBufferProvider::Buffer buffer;
7663 buffer.frameCount = framesOut;
7664 status_t status = activeTrack->mResamplerBufferProvider->getNextBuffer(&buffer);
7665 if (status == OK && buffer.frameCount != 0) {
7666 ALOGV_IF(buffer.frameCount != framesOut,
7667 "%s() read less than expected (%zu vs %zu)",
7668 __func__, buffer.frameCount, framesOut);
7669 framesOut = buffer.frameCount;
Daniel Van Veen9e2376e2018-09-27 14:37:58 +10007670 memcpy(activeTrack->mSink.raw, buffer.raw, buffer.frameCount * mFrameSize);
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07007671 activeTrack->mResamplerBufferProvider->releaseBuffer(&buffer);
7672 } else {
7673 framesOut = 0;
7674 ALOGE("%s() cannot fill request, status: %d, frameCount: %zu",
7675 __func__, status, buffer.frameCount);
7676 }
7677 } else {
7678 // process frames from the RecordThread buffer provider to the RecordTrack
7679 // buffer
7680 framesOut = activeTrack->mRecordBufferConverter->convert(
7681 activeTrack->mSink.raw,
7682 activeTrack->mResamplerBufferProvider,
7683 framesOut);
7684 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007685
7686 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
7687 overrun = OVERRUN_FALSE;
7688 }
7689
7690 if (activeTrack->mFramesToDrop == 0) {
7691 if (framesOut > 0) {
7692 activeTrack->mSink.frameCount = framesOut;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08007693 // Sanitize before releasing if the track has no access to the source data
7694 // An idle UID receives silence from non virtual devices until active
7695 if (activeTrack->isSilenced()) {
Jean-Michel Trividdf87ef2019-08-20 15:42:04 -07007696 memset(activeTrack->mSink.raw, 0, framesOut * activeTrack->frameSize());
Svet Ganovf4ddfef2018-01-16 07:37:58 -08007697 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007698 activeTrack->releaseBuffer(&activeTrack->mSink);
7699 }
7700 } else {
7701 // FIXME could do a partial drop of framesOut
7702 if (activeTrack->mFramesToDrop > 0) {
Mikhail Naganov6d91ba52019-03-26 14:35:28 -07007703 activeTrack->mFramesToDrop -= (ssize_t)framesOut;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007704 if (activeTrack->mFramesToDrop <= 0) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08007705 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007706 }
7707 } else {
7708 activeTrack->mFramesToDrop += framesOut;
7709 if (activeTrack->mFramesToDrop >= 0 || activeTrack->mSyncStartEvent == 0 ||
7710 activeTrack->mSyncStartEvent->isCancelled()) {
7711 ALOGW("Synced record %s, session %d, trigger session %d",
7712 (activeTrack->mFramesToDrop >= 0) ? "timed out" : "cancelled",
7713 activeTrack->sessionId(),
7714 (activeTrack->mSyncStartEvent != 0) ?
Glenn Kastend848eb42016-03-08 13:42:11 -08007715 activeTrack->mSyncStartEvent->triggerSession() :
7716 AUDIO_SESSION_NONE);
Glenn Kasten25f4aa82014-02-07 10:50:43 -08007717 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007718 }
7719 }
7720 }
7721
7722 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007723 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07007724 }
7725 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007726
7727 switch (overrun) {
7728 case OVERRUN_TRUE:
7729 // client isn't retrieving buffers fast enough
7730 if (!activeTrack->setOverflow()) {
7731 nsecs_t now = systemTime();
7732 // FIXME should lastWarning per track?
7733 if ((now - lastWarning) > kWarningThrottleNs) {
7734 ALOGW("RecordThread: buffer overflow");
7735 lastWarning = now;
7736 }
7737 }
7738 break;
7739 case OVERRUN_FALSE:
7740 activeTrack->clearOverflow();
7741 break;
7742 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007743 break;
7744 }
7745
Andy Hung3f0c9022016-01-15 17:49:46 -08007746 // update frame information and push timestamp out
7747 activeTrack->updateTrackFrameInfo(
Andy Hung6ae58432016-02-16 18:32:24 -08007748 activeTrack->mServerProxy->framesReleased(),
Andy Hung3f0c9022016-01-15 17:49:46 -08007749 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER],
7750 mSampleRate, mTimestamp);
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07007751 }
7752
Glenn Kasten3d61bc12014-06-16 10:25:20 -07007753unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08007754 // enable changes in effect chain
7755 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07007756 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurentcccbc762019-04-05 14:20:05 -07007757 if (audio_has_proportional_frames(mFormat)
7758 && loopCount == lastLoopCountRead + 1) {
7759 const int64_t readPeriodNs = lastIoEndNs - mLastIoEndNs;
7760 const double jitterMs =
7761 TimestampVerifier<int64_t, int64_t>::computeJitterMs(
7762 {framesRead, readPeriodNs},
7763 {0, 0} /* lastTimestamp */, mSampleRate);
7764 const double processMs = (lastIoBeginNs - mLastIoEndNs) * 1e-6;
7765
7766 Mutex::Autolock _l(mLock);
7767 mIoJitterMs.add(jitterMs);
7768 mProcessTimeMs.add(processMs);
7769 }
7770 // update timing info.
7771 mLastIoBeginNs = lastIoBeginNs;
7772 mLastIoEndNs = lastIoEndNs;
7773 lastLoopCountRead = loopCount;
Eric Laurent81784c32012-11-19 14:55:58 -08007774 }
7775
Glenn Kasten93e471f2013-08-19 08:40:07 -07007776 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08007777
7778 {
7779 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07007780 for (size_t i = 0; i < mTracks.size(); i++) {
7781 sp<RecordTrack> track = mTracks[i];
7782 track->invalidate();
7783 }
Glenn Kasten2b806402013-11-20 16:37:38 -08007784 mActiveTracks.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08007785 mStartStopCond.broadcast();
7786 }
7787
7788 releaseWakeLock();
7789
7790 ALOGV("RecordThread %p exiting", this);
7791 return false;
7792}
7793
Glenn Kasten93e471f2013-08-19 08:40:07 -07007794void AudioFlinger::RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08007795{
7796 if (!mStandby) {
7797 inputStandBy();
Andy Hungcf10d742020-04-28 15:38:24 -07007798 mThreadMetrics.logEndInterval();
Eric Laurent81784c32012-11-19 14:55:58 -08007799 mStandby = true;
7800 }
7801}
7802
7803void AudioFlinger::RecordThread::inputStandBy()
7804{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007805 // Idle the fast capture if it's currently running
7806 if (mFastCapture != 0) {
7807 FastCaptureStateQueue *sq = mFastCapture->sq();
7808 FastCaptureState *state = sq->begin();
7809 if (!(state->mCommand & FastCaptureState::IDLE)) {
7810 state->mCommand = FastCaptureState::COLD_IDLE;
7811 state->mColdFutexAddr = &mFastCaptureFutex;
7812 state->mColdGen++;
7813 mFastCaptureFutex = 0;
7814 sq->end();
7815 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
7816 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
7817#if 0
7818 if (kUseFastCapture == FastCapture_Dynamic) {
7819 // FIXME
7820 }
7821#endif
7822#ifdef AUDIO_WATCHDOG
7823 // FIXME
7824#endif
7825 } else {
7826 sq->end(false /*didModify*/);
7827 }
7828 }
Mikhail Naganov2534b382019-09-25 13:05:02 -07007829 status_t result = mSource->standby();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007830 ALOGE_IF(result != OK, "Error when putting input stream into standby: %d", result);
Andy Hungad6d52d2016-07-18 13:42:03 -07007831
7832 // If going into standby, flush the pipe source.
7833 if (mPipeSource.get() != nullptr) {
7834 const ssize_t flushed = mPipeSource->flush();
7835 if (flushed > 0) {
7836 ALOGV("Input standby flushed PipeSource %zd frames", flushed);
7837 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += flushed;
7838 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
7839 }
7840 }
Eric Laurent81784c32012-11-19 14:55:58 -08007841}
7842
Glenn Kasten05997e22014-03-13 15:08:33 -07007843// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastene198c362013-08-13 09:13:36 -07007844sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
Eric Laurent81784c32012-11-19 14:55:58 -08007845 const sp<AudioFlinger::Client>& client,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07007846 const audio_attributes_t& attr,
Eric Laurentf14db3c2017-12-08 14:20:36 -08007847 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08007848 audio_format_t format,
7849 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08007850 size_t *pFrameCount,
Glenn Kastend848eb42016-03-08 13:42:11 -08007851 audio_session_t sessionId,
Eric Laurentf14db3c2017-12-08 14:20:36 -08007852 size_t *pNotificationFrameCount,
Eric Laurent09f1ed22019-04-24 17:45:17 -07007853 pid_t creatorPid,
Svet Ganov33761132021-05-13 22:51:08 +00007854 const AttributionSourceState& attributionSource,
Eric Laurent05067782016-06-01 18:27:28 -07007855 audio_input_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08007856 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08007857 status_t *status,
Eric Laurentec376dc2021-04-08 20:41:22 +02007858 audio_port_handle_t portId,
7859 int32_t maxSharedAudioHistoryMs)
Eric Laurent81784c32012-11-19 14:55:58 -08007860{
Glenn Kasten74935e42013-12-19 08:56:45 -08007861 size_t frameCount = *pFrameCount;
Eric Laurentf14db3c2017-12-08 14:20:36 -08007862 size_t notificationFrameCount = *pNotificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08007863 sp<RecordTrack> track;
7864 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07007865 audio_input_flags_t inputFlags = mInput->flags;
Eric Laurentf14db3c2017-12-08 14:20:36 -08007866 audio_input_flags_t requestedFlags = *flags;
7867 uint32_t sampleRate;
Svet Ganov33761132021-05-13 22:51:08 +00007868 AttributionSourceState checkedAttributionSource = AudioFlinger::checkAttributionSourcePackage(
7869 attributionSource);
Eric Laurentf14db3c2017-12-08 14:20:36 -08007870
7871 lStatus = initCheck();
7872 if (lStatus != NO_ERROR) {
7873 ALOGE("createRecordTrack_l() audio driver not initialized");
7874 goto Exit;
7875 }
7876
Mikhail Naganovce9f2652018-07-16 11:09:24 -07007877 if (!audio_is_linear_pcm(mFormat) && (*flags & AUDIO_INPUT_FLAG_DIRECT) == 0) {
7878 ALOGE("createRecordTrack_l() on an encoded stream requires AUDIO_INPUT_FLAG_DIRECT");
7879 lStatus = BAD_VALUE;
7880 goto Exit;
7881 }
7882
Eric Laurentec376dc2021-04-08 20:41:22 +02007883 if (maxSharedAudioHistoryMs != 0) {
Svet Ganov33761132021-05-13 22:51:08 +00007884 if (!captureHotwordAllowed(checkedAttributionSource)) {
Eric Laurentec376dc2021-04-08 20:41:22 +02007885 lStatus = PERMISSION_DENIED;
7886 goto Exit;
7887 }
Eric Laurentec376dc2021-04-08 20:41:22 +02007888 if (maxSharedAudioHistoryMs < 0
7889 || maxSharedAudioHistoryMs > AudioFlinger::kMaxSharedAudioHistoryMs) {
7890 lStatus = BAD_VALUE;
7891 goto Exit;
7892 }
7893 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08007894 if (*pSampleRate == 0) {
7895 *pSampleRate = mSampleRate;
7896 }
7897 sampleRate = *pSampleRate;
Eric Laurent05067782016-06-01 18:27:28 -07007898
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02007899 // special case for FAST flag considered OK if fast capture is present and access to
7900 // audio history is not required
7901 if (hasFastCapture() && mMaxSharedAudioHistoryMs == 0) {
Eric Laurent05067782016-06-01 18:27:28 -07007902 inputFlags = (audio_input_flags_t)(inputFlags | AUDIO_INPUT_FLAG_FAST);
7903 }
7904
Eric Laurentf14db3c2017-12-08 14:20:36 -08007905 // Check if requested flags are compatible with input stream flags
Eric Laurent05067782016-06-01 18:27:28 -07007906 if ((*flags & inputFlags) != *flags) {
7907 ALOGW("createRecordTrack_l(): mismatch between requested flags (%08x) and"
7908 " input flags (%08x)",
7909 *flags, inputFlags);
7910 *flags = (audio_input_flags_t)(*flags & inputFlags);
7911 }
Eric Laurent81784c32012-11-19 14:55:58 -08007912
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02007913 // client expresses a preference for FAST and no access to audio history,
7914 // but we get the final say
7915 if (*flags & AUDIO_INPUT_FLAG_FAST && maxSharedAudioHistoryMs == 0) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07007916 if (
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07007917 // we formerly checked for a callback handler (non-0 tid),
7918 // but that is no longer required for TRANSFER_OBTAIN mode
7919 //
Phil Burk7ed66a12019-04-18 13:20:30 -07007920 // Frame count is not specified (0), or is less than or equal the pipe depth.
7921 // It is OK to provide a higher capacity than requested.
7922 // We will force it to mPipeFramesP2 below.
7923 (frameCount <= mPipeFramesP2) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07007924 // PCM data
7925 audio_is_linear_pcm(format) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08007926 // hardware format
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007927 (format == mFormat) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08007928 // hardware channel mask
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007929 (channelMask == mChannelMask) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08007930 // hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07007931 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07007932 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007933 hasFastCapture() &&
7934 // there are sufficient fast track slots available
7935 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07007936 ) {
Eric Laurent4c415062016-06-17 16:14:16 -07007937 // check compatibility with audio effects.
7938 Mutex::Autolock _l(mLock);
7939 // Do not accept FAST flag if the session has software effects
7940 sp<EffectChain> chain = getEffectChain_l(sessionId);
7941 if (chain != 0) {
Andy Hungd3bb0ad2016-10-11 17:16:43 -07007942 audio_input_flags_t old = *flags;
7943 chain->checkInputFlagCompatibility(flags);
7944 if (old != *flags) {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007945 ALOGV("%p AUDIO_INPUT_FLAGS denied by effect old=%#x new=%#x",
7946 this, (int)old, (int)*flags);
Eric Laurent4c415062016-06-17 16:14:16 -07007947 }
7948 }
Eric Laurent122f7e72016-06-29 11:53:29 -07007949 ALOGV_IF((*flags & AUDIO_INPUT_FLAG_FAST) != 0,
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007950 "%p AUDIO_INPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
7951 this, frameCount, mFrameCount);
Glenn Kasten90e58b12013-07-31 16:16:02 -07007952 } else {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007953 ALOGV("%p AUDIO_INPUT_FLAG_FAST denied: frameCount=%zu mFrameCount=%zu mPipeFramesP2=%zu "
7954 "format=%#x isLinear=%d mFormat=%#x channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007955 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007956 this, frameCount, mFrameCount, mPipeFramesP2,
7957 format, audio_is_linear_pcm(format), mFormat, channelMask, sampleRate, mSampleRate,
Glenn Kasten74105912014-07-03 12:28:53 -07007958 hasFastCapture(), tid, mFastTrackAvail);
Eric Laurent05067782016-06-01 18:27:28 -07007959 *flags = (audio_input_flags_t)(*flags & ~AUDIO_INPUT_FLAG_FAST);
Glenn Kasten74105912014-07-03 12:28:53 -07007960 }
7961 }
7962
Eric Laurentf14db3c2017-12-08 14:20:36 -08007963 // If FAST or RAW flags were corrected, ask caller to request new input from audio policy
7964 if ((*flags & AUDIO_INPUT_FLAG_FAST) !=
7965 (requestedFlags & AUDIO_INPUT_FLAG_FAST)) {
7966 *flags = (audio_input_flags_t) (*flags & ~(AUDIO_INPUT_FLAG_FAST | AUDIO_INPUT_FLAG_RAW));
7967 lStatus = BAD_TYPE;
7968 goto Exit;
7969 }
7970
Glenn Kasten74105912014-07-03 12:28:53 -07007971 // compute track buffer size in frames, and suggest the notification frame count
Eric Laurent05067782016-06-01 18:27:28 -07007972 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten74105912014-07-03 12:28:53 -07007973 // fast track: frame count is exactly the pipe depth
7974 frameCount = mPipeFramesP2;
7975 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
Eric Laurentf14db3c2017-12-08 14:20:36 -08007976 notificationFrameCount = mFrameCount;
Glenn Kasten74105912014-07-03 12:28:53 -07007977 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07007978 // not fast track: max notification period is resampled equivalent of one HAL buffer time
7979 // or 20 ms if there is a fast capture
7980 // TODO This could be a roundupRatio inline, and const
7981 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
7982 * sampleRate + mSampleRate - 1) / mSampleRate;
7983 // minimum number of notification periods is at least kMinNotifications,
7984 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
7985 static const size_t kMinNotifications = 3;
7986 static const uint32_t kMinMs = 30;
7987 // TODO This could be a roundupRatio inline
7988 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
7989 // TODO This could be a roundupRatio inline
7990 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
7991 maxNotificationFrames;
7992 const size_t minFrameCount = maxNotificationFrames *
7993 max(kMinNotifications, minNotificationsByMs);
7994 frameCount = max(frameCount, minFrameCount);
Eric Laurentf14db3c2017-12-08 14:20:36 -08007995 if (notificationFrameCount == 0 || notificationFrameCount > maxNotificationFrames) {
7996 notificationFrameCount = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07007997 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07007998 }
Glenn Kasten74935e42013-12-19 08:56:45 -08007999 *pFrameCount = frameCount;
Eric Laurentf14db3c2017-12-08 14:20:36 -08008000 *pNotificationFrameCount = notificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08008001
8002 { // scope for mLock
8003 Mutex::Autolock _l(mLock);
Eric Laurent2407ce32021-04-26 14:56:03 +02008004 int32_t startFrames = -1;
Eric Laurentec376dc2021-04-08 20:41:22 +02008005 if (!mSharedAudioPackageName.empty()
Svet Ganov33761132021-05-13 22:51:08 +00008006 && mSharedAudioPackageName == checkedAttributionSource.packageName
Eric Laurentec376dc2021-04-08 20:41:22 +02008007 && mSharedAudioSessionId == sessionId
Svet Ganov33761132021-05-13 22:51:08 +00008008 && captureHotwordAllowed(checkedAttributionSource)) {
Eric Laurent2407ce32021-04-26 14:56:03 +02008009 startFrames = mSharedAudioStartFrames;
Eric Laurentec376dc2021-04-08 20:41:22 +02008010 }
Eric Laurent81784c32012-11-19 14:55:58 -08008011
Kevin Rocard1f564ac2018-03-29 13:53:10 -07008012 track = new RecordTrack(this, client, attr, sampleRate,
Andy Hung8fe68032017-06-05 16:17:51 -07008013 format, channelMask, frameCount,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07008014 nullptr /* buffer */, (size_t)0 /* bufferSize */, sessionId, creatorPid,
Svet Ganov33761132021-05-13 22:51:08 +00008015 checkedAttributionSource, *flags, TrackBase::TYPE_DEFAULT, portId,
8016 startFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08008017
Glenn Kasten03003332013-08-06 15:40:54 -07008018 lStatus = track->initCheck();
8019 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07008020 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08008021 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08008022 goto Exit;
8023 }
8024 mTracks.add(track);
8025
Eric Laurent05067782016-06-01 18:27:28 -07008026 if ((*flags & AUDIO_INPUT_FLAG_FAST) && (tid != -1)) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07008027 pid_t callingPid = IPCThreadState::self()->getCallingPid();
8028 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
8029 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07008030 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Glenn Kasten90e58b12013-07-31 16:16:02 -07008031 }
Eric Laurentec376dc2021-04-08 20:41:22 +02008032
8033 if (maxSharedAudioHistoryMs != 0) {
8034 sendResizeBufferConfigEvent_l(maxSharedAudioHistoryMs);
8035 }
Eric Laurent81784c32012-11-19 14:55:58 -08008036 }
Glenn Kasten05997e22014-03-13 15:08:33 -07008037
Eric Laurent81784c32012-11-19 14:55:58 -08008038 lStatus = NO_ERROR;
8039
8040Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07008041 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08008042 return track;
8043}
8044
8045status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
8046 AudioSystem::sync_event_t event,
Glenn Kastend848eb42016-03-08 13:42:11 -08008047 audio_session_t triggerSession)
Eric Laurent81784c32012-11-19 14:55:58 -08008048{
8049 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
8050 sp<ThreadBase> strongMe = this;
8051 status_t status = NO_ERROR;
8052
8053 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08008054 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08008055 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008056 recordTrack->mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
Eric Laurent81784c32012-11-19 14:55:58 -08008057 triggerSession,
8058 recordTrack->sessionId(),
8059 syncStartEventCallback,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008060 recordTrack);
Eric Laurent81784c32012-11-19 14:55:58 -08008061 // Sync event can be cancelled by the trigger session if the track is not in a
8062 // compatible state in which case we start record immediately
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008063 if (recordTrack->mSyncStartEvent->isCancelled()) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08008064 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08008065 } else {
8066 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
Ivan Lozano1b35dd62017-12-06 16:55:10 -08008067 recordTrack->mFramesToDrop = -(ssize_t)
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08008068 ((AudioSystem::kSyncRecordStartTimeOutMs * recordTrack->mSampleRate) / 1000);
Eric Laurent81784c32012-11-19 14:55:58 -08008069 }
8070 }
8071
8072 {
Glenn Kasten47c20702013-08-13 15:37:35 -07008073 // This section is a rendezvous between binder thread executing start() and RecordThread
Eric Laurent81784c32012-11-19 14:55:58 -08008074 AutoMutex lock(mLock);
Andy Hungce685402018-10-05 17:23:27 -07008075 if (recordTrack->isInvalid()) {
8076 recordTrack->clearSyncStartEvent();
Eric Laurentd52a28c2020-08-21 17:10:39 -07008077 ALOGW("%s track %d: invalidated before startInput", __func__, recordTrack->portId());
8078 return DEAD_OBJECT;
Andy Hungce685402018-10-05 17:23:27 -07008079 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008080 if (mActiveTracks.indexOf(recordTrack) >= 0) {
8081 if (recordTrack->mState == TrackBase::PAUSING) {
Andy Hungce685402018-10-05 17:23:27 -07008082 // We haven't stopped yet (moved to PAUSED and not in mActiveTracks)
8083 // so no need to startInput().
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008084 ALOGV("active record track PAUSING -> ACTIVE");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008085 recordTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008086 } else {
8087 ALOGV("active record track state %d", recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08008088 }
8089 return status;
8090 }
8091
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08008092 // TODO consider other ways of handling this, such as changing the state to :STARTING and
8093 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
8094 // or using a separate command thread
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008095 recordTrack->mState = TrackBase::STARTING_1;
Glenn Kasten2b806402013-11-20 16:37:38 -08008096 mActiveTracks.add(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07008097 status_t status = NO_ERROR;
8098 if (recordTrack->isExternalTrack()) {
8099 mLock.unlock();
Eric Laurent4eb58f12018-12-07 16:41:02 -08008100 status = AudioSystem::startInput(recordTrack->portId());
Eric Laurent83b88082014-06-20 18:31:16 -07008101 mLock.lock();
Andy Hungce685402018-10-05 17:23:27 -07008102 if (recordTrack->isInvalid()) {
8103 recordTrack->clearSyncStartEvent();
8104 if (status == NO_ERROR && recordTrack->mState == TrackBase::STARTING_1) {
8105 recordTrack->mState = TrackBase::STARTING_2;
8106 // STARTING_2 forces destroy to call stopInput.
8107 }
Eric Laurentd52a28c2020-08-21 17:10:39 -07008108 ALOGW("%s track %d: invalidated after startInput", __func__, recordTrack->portId());
8109 return DEAD_OBJECT;
Andy Hungce685402018-10-05 17:23:27 -07008110 }
8111 if (recordTrack->mState != TrackBase::STARTING_1) {
8112 ALOGW("%s(%d): unsynchronized mState:%d change",
8113 __func__, recordTrack->id(), recordTrack->mState);
8114 // Someone else has changed state, let them take over,
8115 // leave mState in the new state.
8116 recordTrack->clearSyncStartEvent();
8117 return INVALID_OPERATION;
8118 }
8119 // we're ok, but perhaps startInput has failed
Eric Laurent83b88082014-06-20 18:31:16 -07008120 if (status != NO_ERROR) {
Andy Hungce685402018-10-05 17:23:27 -07008121 ALOGW("%s(%d): startInput failed, status %d",
8122 __func__, recordTrack->id(), status);
8123 // We are in ActiveTracks if STARTING_1 and valid, so remove from ActiveTracks,
8124 // leave in STARTING_1, so destroy() will not call stopInput.
Eric Laurent83b88082014-06-20 18:31:16 -07008125 mActiveTracks.remove(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07008126 recordTrack->clearSyncStartEvent();
Eric Laurent83b88082014-06-20 18:31:16 -07008127 return status;
8128 }
Eric Laurent09f1ed22019-04-24 17:45:17 -07008129 sendIoConfigEvent_l(
8130 AUDIO_CLIENT_STARTED, recordTrack->creatorPid(), recordTrack->portId());
Eric Laurent81784c32012-11-19 14:55:58 -08008131 }
Andy Hungc2b11cb2020-04-22 09:04:01 -07008132
8133 recordTrack->logBeginInterval(patchSourcesToString(&mPatch)); // log to MediaMetrics
8134
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008135 // Catch up with current buffer indices if thread is already running.
8136 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
8137 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
8138 // see previously buffered data before it called start(), but with greater risk of overrun.
8139
Andy Hung73c02e42015-03-29 01:13:58 -07008140 recordTrack->mResamplerBufferProvider->reset();
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008141 if (!recordTrack->isDirect()) {
8142 // clear any converter state as new data will be discontinuous
8143 recordTrack->mRecordBufferConverter->reset();
8144 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008145 recordTrack->mState = TrackBase::STARTING_2;
Eric Laurent81784c32012-11-19 14:55:58 -08008146 // signal thread to start
Eric Laurent81784c32012-11-19 14:55:58 -08008147 mWaitWorkCV.broadcast();
Eric Laurent81784c32012-11-19 14:55:58 -08008148 return status;
8149 }
Eric Laurent81784c32012-11-19 14:55:58 -08008150}
8151
Eric Laurent81784c32012-11-19 14:55:58 -08008152void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
8153{
8154 sp<SyncEvent> strongEvent = event.promote();
8155
8156 if (strongEvent != 0) {
Eric Laurent8ea16e42014-02-20 16:26:11 -08008157 sp<RefBase> ptr = strongEvent->cookie().promote();
8158 if (ptr != 0) {
8159 RecordTrack *recordTrack = (RecordTrack *)ptr.get();
8160 recordTrack->handleSyncStartEvent(strongEvent);
8161 }
Eric Laurent81784c32012-11-19 14:55:58 -08008162 }
8163}
8164
Glenn Kastena8356f62013-07-25 14:37:52 -07008165bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08008166 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07008167 AutoMutex _l(mLock);
Andy Hungce685402018-10-05 17:23:27 -07008168 // if we're invalid, we can't be on the ActiveTracks.
Jean-Michel Trivi38f86712017-04-11 14:10:17 -07008169 if (mActiveTracks.indexOf(recordTrack) < 0 || recordTrack->mState == TrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08008170 return false;
8171 }
Glenn Kasten47c20702013-08-13 15:37:35 -07008172 // note that threadLoop may still be processing the track at this point [without lock]
Eric Laurent81784c32012-11-19 14:55:58 -08008173 recordTrack->mState = TrackBase::PAUSING;
Andy Hungce685402018-10-05 17:23:27 -07008174
Andy Hungabfab202019-03-07 19:45:54 -08008175 // NOTE: Waiting here is important to keep stop synchronous.
8176 // This is needed for proper patchRecord peer release.
Andy Hungce685402018-10-05 17:23:27 -07008177 while (recordTrack->mState == TrackBase::PAUSING && !recordTrack->isInvalid()) {
8178 mWaitWorkCV.broadcast(); // signal thread to stop
8179 mStartStopCond.wait(mLock);
Eric Laurent81784c32012-11-19 14:55:58 -08008180 }
Andy Hungce685402018-10-05 17:23:27 -07008181
8182 if (recordTrack->mState == TrackBase::PAUSED) { // successful stop
Eric Laurent81784c32012-11-19 14:55:58 -08008183 ALOGV("Record stopped OK");
8184 return true;
8185 }
Andy Hungce685402018-10-05 17:23:27 -07008186
8187 // don't handle anything - we've been invalidated or restarted and in a different state
8188 ALOGW_IF("%s(%d): unsynchronized stop, state: %d",
8189 __func__, recordTrack->id(), recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08008190 return false;
8191}
8192
Glenn Kasten0f11b512014-01-31 16:18:54 -08008193bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
Eric Laurent81784c32012-11-19 14:55:58 -08008194{
8195 return false;
8196}
8197
Glenn Kasten0f11b512014-01-31 16:18:54 -08008198status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08008199{
8200#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
8201 if (!isValidSyncEvent(event)) {
8202 return BAD_VALUE;
8203 }
8204
Glenn Kastend848eb42016-03-08 13:42:11 -08008205 audio_session_t eventSession = event->triggerSession();
Eric Laurent81784c32012-11-19 14:55:58 -08008206 status_t ret = NAME_NOT_FOUND;
8207
8208 Mutex::Autolock _l(mLock);
8209
8210 for (size_t i = 0; i < mTracks.size(); i++) {
8211 sp<RecordTrack> track = mTracks[i];
8212 if (eventSession == track->sessionId()) {
8213 (void) track->setSyncEvent(event);
8214 ret = NO_ERROR;
8215 }
8216 }
8217 return ret;
8218#else
8219 return BAD_VALUE;
8220#endif
8221}
8222
jiabin653cc0a2018-01-17 17:54:10 -08008223status_t AudioFlinger::RecordThread::getActiveMicrophones(
8224 std::vector<media::MicrophoneInfo>* activeMicrophones)
8225{
8226 ALOGV("RecordThread::getActiveMicrophones");
8227 AutoMutex _l(mLock);
Jasmine Chaeaa10e42021-05-11 10:11:14 +08008228 if (!isStreamInitialized()) {
Paul McLean8a661a32021-04-12 10:21:42 -06008229 return NO_INIT;
8230 }
jiabin9ff780e2018-03-19 18:19:52 -07008231 status_t status = mInput->stream->getActiveMicrophones(activeMicrophones);
8232 return status;
jiabin653cc0a2018-01-17 17:54:10 -08008233}
8234
Paul McLean12340082019-03-19 09:35:05 -06008235status_t AudioFlinger::RecordThread::setPreferredMicrophoneDirection(
8236 audio_microphone_direction_t direction)
Paul McLean03a6e6a2018-12-04 10:54:13 -07008237{
Paul McLean12340082019-03-19 09:35:05 -06008238 ALOGV("setPreferredMicrophoneDirection(%d)", direction);
Paul McLean03a6e6a2018-12-04 10:54:13 -07008239 AutoMutex _l(mLock);
Jasmine Chaeaa10e42021-05-11 10:11:14 +08008240 if (!isStreamInitialized()) {
Paul McLean8a661a32021-04-12 10:21:42 -06008241 return NO_INIT;
8242 }
Paul McLean12340082019-03-19 09:35:05 -06008243 return mInput->stream->setPreferredMicrophoneDirection(direction);
Paul McLean03a6e6a2018-12-04 10:54:13 -07008244}
8245
Paul McLean12340082019-03-19 09:35:05 -06008246status_t AudioFlinger::RecordThread::setPreferredMicrophoneFieldDimension(float zoom)
Paul McLean03a6e6a2018-12-04 10:54:13 -07008247{
Paul McLean12340082019-03-19 09:35:05 -06008248 ALOGV("setPreferredMicrophoneFieldDimension(%f)", zoom);
Paul McLean03a6e6a2018-12-04 10:54:13 -07008249 AutoMutex _l(mLock);
Jasmine Chaeaa10e42021-05-11 10:11:14 +08008250 if (!isStreamInitialized()) {
Paul McLean8a661a32021-04-12 10:21:42 -06008251 return NO_INIT;
8252 }
Paul McLean12340082019-03-19 09:35:05 -06008253 return mInput->stream->setPreferredMicrophoneFieldDimension(zoom);
Paul McLean03a6e6a2018-12-04 10:54:13 -07008254}
8255
Eric Laurentec376dc2021-04-08 20:41:22 +02008256status_t AudioFlinger::RecordThread::shareAudioHistory(
8257 const std::string& sharedAudioPackageName, audio_session_t sharedSessionId,
8258 int64_t sharedAudioStartMs) {
8259 AutoMutex _l(mLock);
8260 return shareAudioHistory_l(sharedAudioPackageName, sharedSessionId, sharedAudioStartMs);
8261}
8262
8263status_t AudioFlinger::RecordThread::shareAudioHistory_l(
8264 const std::string& sharedAudioPackageName, audio_session_t sharedSessionId,
8265 int64_t sharedAudioStartMs) {
Eric Laurent92d0a322021-07-16 15:32:33 +02008266
Eric Laurentec376dc2021-04-08 20:41:22 +02008267 if ((hasAudioSession_l(sharedSessionId) & ThreadBase::TRACK_SESSION) == 0) {
8268 return BAD_VALUE;
8269 }
Eric Laurent2407ce32021-04-26 14:56:03 +02008270
8271 if (sharedAudioStartMs < 0
8272 || sharedAudioStartMs > INT64_MAX / mSampleRate) {
Eric Laurentec376dc2021-04-08 20:41:22 +02008273 return BAD_VALUE;
8274 }
8275
Eric Laurent2407ce32021-04-26 14:56:03 +02008276 // Current implementation of the input resampling buffer wraps around indexes at 32 bit.
8277 // As we cannot detect more than one wraparound, only accept values up current write position
8278 // after one wraparound
8279 // We assume recent wraparounds on mRsmpInRear only given it is unlikely that the requesting
8280 // app waits several hours after the start time was computed.
Eric Laurent92d0a322021-07-16 15:32:33 +02008281 int64_t sharedAudioStartFrames = sharedAudioStartMs * mSampleRate / 1000;
Eric Laurent2407ce32021-04-26 14:56:03 +02008282 const int32_t sharedOffset = audio_utils::safe_sub_overflow(mRsmpInRear,
8283 (int32_t)sharedAudioStartFrames);
Eric Laurent92d0a322021-07-16 15:32:33 +02008284 // Bring the start frame position within the input buffer to match the documented
8285 // "best effort" behavior of the API.
8286 if (sharedOffset < 0) {
8287 sharedAudioStartFrames = mRsmpInRear;
8288 } else if (sharedOffset > mRsmpInFrames) {
8289 sharedAudioStartFrames =
8290 audio_utils::safe_sub_overflow(mRsmpInRear, (int32_t)mRsmpInFrames);
Eric Laurent2407ce32021-04-26 14:56:03 +02008291 }
8292
Eric Laurentec376dc2021-04-08 20:41:22 +02008293 mSharedAudioPackageName = sharedAudioPackageName;
8294 if (mSharedAudioPackageName.empty()) {
Eric Laurent92d0a322021-07-16 15:32:33 +02008295 resetAudioHistory_l();
Eric Laurentec376dc2021-04-08 20:41:22 +02008296 } else {
8297 mSharedAudioSessionId = sharedSessionId;
Eric Laurent2407ce32021-04-26 14:56:03 +02008298 mSharedAudioStartFrames = (int32_t)sharedAudioStartFrames;
Eric Laurentec376dc2021-04-08 20:41:22 +02008299 }
8300 return NO_ERROR;
8301}
8302
Eric Laurent92d0a322021-07-16 15:32:33 +02008303void AudioFlinger::RecordThread::resetAudioHistory_l() {
8304 mSharedAudioSessionId = AUDIO_SESSION_NONE;
8305 mSharedAudioStartFrames = -1;
8306 mSharedAudioPackageName = "";
8307}
8308
Kevin Rocard069c2712018-03-29 19:09:14 -07008309void AudioFlinger::RecordThread::updateMetadata_l()
8310{
Jasmine Chaeaa10e42021-05-11 10:11:14 +08008311 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
8312 return; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -07008313 }
8314 StreamInHalInterface::SinkMetadata metadata;
8315 for (const sp<RecordTrack> &track : mActiveTracks) {
Eric Laurentb9cc0ab2021-01-29 11:46:52 +01008316 // Do not forward PatchRecord metadata to audio HAL
8317 if (track->isPatchTrack()) {
8318 continue;
8319 }
Kevin Rocard069c2712018-03-29 19:09:14 -07008320 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurent94579172020-11-20 18:41:04 +01008321 record_track_metadata_v7_t trackMetadata;
8322 trackMetadata.base = {
Kevin Rocard069c2712018-03-29 19:09:14 -07008323 .source = track->attributes().source,
8324 .gain = 1, // capture tracks do not have volumes
Eric Laurent94579172020-11-20 18:41:04 +01008325 };
8326 trackMetadata.channel_mask = track->channelMask(),
8327 strncpy(trackMetadata.tags, track->attributes().tags, AUDIO_ATTRIBUTES_TAGS_MAX_SIZE);
8328
8329 metadata.tracks.push_back(trackMetadata);
Kevin Rocard069c2712018-03-29 19:09:14 -07008330 }
8331 mInput->stream->updateSinkMetadata(metadata);
8332}
8333
Eric Laurent81784c32012-11-19 14:55:58 -08008334// destroyTrack_l() must be called with ThreadBase::mLock held
8335void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
8336{
Eric Laurentbfb1b832013-01-07 09:53:42 -08008337 track->terminate();
8338 track->mState = TrackBase::STOPPED;
Eric Laurentec376dc2021-04-08 20:41:22 +02008339
Eric Laurent81784c32012-11-19 14:55:58 -08008340 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08008341 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08008342 removeTrack_l(track);
8343 }
8344}
8345
8346void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
8347{
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008348 String8 result;
8349 track->appendDump(result, false /* active */);
8350 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.string());
8351
Eric Laurent81784c32012-11-19 14:55:58 -08008352 mTracks.remove(track);
8353 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008354 if (track->isFastTrack()) {
8355 ALOG_ASSERT(!mFastTrackAvail);
8356 mFastTrackAvail = true;
8357 }
Eric Laurent81784c32012-11-19 14:55:58 -08008358}
8359
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07008360void AudioFlinger::RecordThread::dumpInternals_l(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08008361{
Mikhail Naganov913d06c2016-11-01 12:49:22 -07008362 AudioStreamIn *input = mInput;
8363 audio_input_flags_t flags = input != NULL ? input->flags : AUDIO_INPUT_FLAG_NONE;
8364 dprintf(fd, " AudioStreamIn: %p flags %#x (%s)\n",
Andy Hung9b181952019-02-25 14:53:36 -08008365 input, flags, toString(flags).c_str());
Andy Hung6427e442018-08-09 12:51:02 -07008366 dprintf(fd, " Frames read: %lld\n", (long long)mFramesRead);
Eric Tan39ec8d62018-07-24 09:49:29 -07008367 if (mActiveTracks.isEmpty()) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07008368 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08008369 }
Andy Hungbfa64962017-06-12 14:43:19 -07008370
8371 if (input != nullptr) {
8372 dprintf(fd, " Hal stream dump:\n");
8373 (void)input->stream->dump(fd);
8374 }
8375
Glenn Kasten6e6704c2014-07-03 10:20:00 -07008376 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008377 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Glenn Kasten17c9c992015-03-02 15:53:01 -08008378
Glenn Kasten2f90c512015-12-02 11:40:09 -08008379 // Make a non-atomic copy of fast capture dump state so it won't change underneath us
8380 // while we are dumping it. It may be inconsistent, but it won't mutate!
8381 // This is a large object so we place it on the heap.
8382 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
Eric Tan2942a4e2018-09-12 17:41:27 -07008383 const std::unique_ptr<FastCaptureDumpState> copy =
8384 std::make_unique<FastCaptureDumpState>(mFastCaptureDumpState);
Glenn Kasten2f90c512015-12-02 11:40:09 -08008385 copy->dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08008386}
8387
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07008388void AudioFlinger::RecordThread::dumpTracks_l(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08008389{
Eric Laurent81784c32012-11-19 14:55:58 -08008390 String8 result;
Marco Nelissenb2208842014-02-07 14:00:50 -08008391 size_t numtracks = mTracks.size();
8392 size_t numactive = mActiveTracks.size();
8393 size_t numactiveseen = 0;
Glenn Kastenc42e9b42016-03-21 11:35:03 -07008394 dprintf(fd, " %zu Tracks", numtracks);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008395 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08008396 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07008397 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008398 result.append(prefix);
Andy Hung000adb52018-06-01 15:43:26 -07008399 mTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08008400 for (size_t i = 0; i < numtracks ; ++i) {
8401 sp<RecordTrack> track = mTracks[i];
8402 if (track != 0) {
8403 bool active = mActiveTracks.indexOf(track) >= 0;
8404 if (active) {
8405 numactiveseen++;
8406 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008407 result.append(prefix);
8408 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08008409 }
Eric Laurent81784c32012-11-19 14:55:58 -08008410 }
Marco Nelissenb2208842014-02-07 14:00:50 -08008411 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07008412 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08008413 }
8414
Marco Nelissenb2208842014-02-07 14:00:50 -08008415 if (numactiveseen != numactive) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008416 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08008417 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008418 result.append(prefix);
Andy Hung000adb52018-06-01 15:43:26 -07008419 mActiveTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08008420 for (size_t i = 0; i < numactive; ++i) {
Glenn Kasten2b806402013-11-20 16:37:38 -08008421 sp<RecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08008422 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008423 result.append(prefix);
8424 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08008425 }
Glenn Kasten2b806402013-11-20 16:37:38 -08008426 }
Eric Laurent81784c32012-11-19 14:55:58 -08008427
8428 }
8429 write(fd, result.string(), result.size());
8430}
8431
Eric Laurent5ada82e2019-08-29 17:53:54 -07008432void AudioFlinger::RecordThread::setRecordSilenced(audio_port_handle_t portId, bool silenced)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008433{
8434 Mutex::Autolock _l(mLock);
8435 for (size_t i = 0; i < mTracks.size() ; i++) {
8436 sp<RecordTrack> track = mTracks[i];
Eric Laurent5ada82e2019-08-29 17:53:54 -07008437 if (track != 0 && track->portId() == portId) {
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008438 track->setSilenced(silenced);
8439 }
8440 }
8441}
Andy Hung73c02e42015-03-29 01:13:58 -07008442
8443void AudioFlinger::RecordThread::ResamplerBufferProvider::reset()
8444{
8445 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
8446 RecordThread *recordThread = (RecordThread *) threadBase.get();
Andy Hung73c02e42015-03-29 01:13:58 -07008447 mRsmpInUnrel = 0;
Eric Laurentec376dc2021-04-08 20:41:22 +02008448 const int32_t rear = recordThread->mRsmpInRear;
8449 ssize_t deltaFrames = 0;
Eric Laurent2407ce32021-04-26 14:56:03 +02008450 if (mRecordTrack->startFrames() >= 0) {
8451 int32_t startFrames = mRecordTrack->startFrames();
8452 // Accept a recent wraparound of mRsmpInRear
8453 if (startFrames <= rear) {
8454 deltaFrames = rear - startFrames;
8455 } else {
8456 deltaFrames = (int32_t)((int64_t)rear + UINT32_MAX + 1 - startFrames);
Eric Laurentec376dc2021-04-08 20:41:22 +02008457 }
Eric Laurentec376dc2021-04-08 20:41:22 +02008458 // start frame cannot be further in the past than start of resampling buffer
8459 if ((size_t) deltaFrames > recordThread->mRsmpInFrames) {
8460 deltaFrames = recordThread->mRsmpInFrames;
8461 }
8462 }
8463 mRsmpInFront = audio_utils::safe_sub_overflow(rear, static_cast<int32_t>(deltaFrames));
Andy Hung73c02e42015-03-29 01:13:58 -07008464}
8465
8466void AudioFlinger::RecordThread::ResamplerBufferProvider::sync(
8467 size_t *framesAvailable, bool *hasOverrun)
8468{
8469 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
8470 RecordThread *recordThread = (RecordThread *) threadBase.get();
8471 const int32_t rear = recordThread->mRsmpInRear;
8472 const int32_t front = mRsmpInFront;
Hongwei Wang95e37682019-04-12 11:13:36 -07008473 const ssize_t filled = audio_utils::safe_sub_overflow(rear, front);
Andy Hung73c02e42015-03-29 01:13:58 -07008474
8475 size_t framesIn;
8476 bool overrun = false;
8477 if (filled < 0) {
8478 // should not happen, but treat like a massive overrun and re-sync
8479 framesIn = 0;
8480 mRsmpInFront = rear;
8481 overrun = true;
8482 } else if ((size_t) filled <= recordThread->mRsmpInFrames) {
8483 framesIn = (size_t) filled;
8484 } else {
8485 // client is not keeping up with server, but give it latest data
8486 framesIn = recordThread->mRsmpInFrames;
Hongwei Wang95e37682019-04-12 11:13:36 -07008487 mRsmpInFront = /* front = */ audio_utils::safe_sub_overflow(
8488 rear, static_cast<int32_t>(framesIn));
Andy Hung73c02e42015-03-29 01:13:58 -07008489 overrun = true;
8490 }
8491 if (framesAvailable != NULL) {
8492 *framesAvailable = framesIn;
8493 }
8494 if (hasOverrun != NULL) {
8495 *hasOverrun = overrun;
8496 }
8497}
8498
Eric Laurent81784c32012-11-19 14:55:58 -08008499// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008500status_t AudioFlinger::RecordThread::ResamplerBufferProvider::getNextBuffer(
Glenn Kastend79072e2016-01-06 08:41:20 -08008501 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08008502{
Andy Hung73c02e42015-03-29 01:13:58 -07008503 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008504 if (threadBase == 0) {
8505 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08008506 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008507 return NOT_ENOUGH_DATA;
8508 }
8509 RecordThread *recordThread = (RecordThread *) threadBase.get();
8510 int32_t rear = recordThread->mRsmpInRear;
Andy Hung73c02e42015-03-29 01:13:58 -07008511 int32_t front = mRsmpInFront;
Hongwei Wang95e37682019-04-12 11:13:36 -07008512 ssize_t filled = audio_utils::safe_sub_overflow(rear, front);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008513 // FIXME should not be P2 (don't want to increase latency)
8514 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08008515 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07008516 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008517
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008518 front &= recordThread->mRsmpInFramesP2 - 1;
8519 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07008520 if (part1 > (size_t) filled) {
8521 part1 = filled;
8522 }
8523 size_t ask = buffer->frameCount;
8524 ALOG_ASSERT(ask > 0);
8525 if (part1 > ask) {
8526 part1 = ask;
8527 }
8528 if (part1 == 0) {
Andy Hung73c02e42015-03-29 01:13:58 -07008529 // out of data is fine since the resampler will return a short-count.
Glenn Kasten85948432013-08-19 12:09:05 -07008530 buffer->raw = NULL;
8531 buffer->frameCount = 0;
Andy Hung73c02e42015-03-29 01:13:58 -07008532 mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07008533 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08008534 }
8535
Andy Hung57446612015-04-19 23:56:46 -07008536 buffer->raw = (uint8_t*)recordThread->mRsmpInBuffer + front * recordThread->mFrameSize;
Glenn Kasten85948432013-08-19 12:09:05 -07008537 buffer->frameCount = part1;
Andy Hung73c02e42015-03-29 01:13:58 -07008538 mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08008539 return NO_ERROR;
8540}
8541
8542// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008543void AudioFlinger::RecordThread::ResamplerBufferProvider::releaseBuffer(
8544 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08008545{
Hongwei Wang95e37682019-04-12 11:13:36 -07008546 int32_t stepCount = static_cast<int32_t>(buffer->frameCount);
Glenn Kasten85948432013-08-19 12:09:05 -07008547 if (stepCount == 0) {
8548 return;
8549 }
Andy Hung73c02e42015-03-29 01:13:58 -07008550 ALOG_ASSERT(stepCount <= mRsmpInUnrel);
8551 mRsmpInUnrel -= stepCount;
Hongwei Wang95e37682019-04-12 11:13:36 -07008552 mRsmpInFront = audio_utils::safe_add_overflow(mRsmpInFront, stepCount);
Glenn Kasten85948432013-08-19 12:09:05 -07008553 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08008554 buffer->frameCount = 0;
8555}
8556
Eric Laurentd8365c52017-07-16 15:27:05 -07008557void AudioFlinger::RecordThread::checkBtNrec()
8558{
8559 Mutex::Autolock _l(mLock);
8560 checkBtNrec_l();
8561}
8562
8563void AudioFlinger::RecordThread::checkBtNrec_l()
8564{
8565 // disable AEC and NS if the device is a BT SCO headset supporting those
8566 // pre processings
jiabinc52b1ff2019-10-31 17:20:42 -07008567 bool suspend = audio_is_bluetooth_sco_device(inDeviceType()) &&
Eric Laurentd8365c52017-07-16 15:27:05 -07008568 mAudioFlinger->btNrecIsOff();
8569 if (mBtNrecSuspended.exchange(suspend) != suspend) {
8570 for (size_t i = 0; i < mEffectChains.size(); i++) {
8571 setEffectSuspended_l(FX_IID_AEC, suspend, mEffectChains[i]->sessionId());
8572 setEffectSuspended_l(FX_IID_NS, suspend, mEffectChains[i]->sessionId());
8573 }
8574 }
8575}
8576
Andy Hung97a893e2015-03-29 01:03:07 -07008577
Eric Laurent10351942014-05-08 18:49:52 -07008578bool AudioFlinger::RecordThread::checkForNewParameter_l(const String8& keyValuePair,
8579 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08008580{
8581 bool reconfig = false;
8582
Eric Laurent10351942014-05-08 18:49:52 -07008583 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08008584
Eric Laurent10351942014-05-08 18:49:52 -07008585 audio_format_t reqFormat = mFormat;
8586 uint32_t samplingRate = mSampleRate;
Glenn Kastene1635ec2015-06-08 15:46:49 -07008587 // 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 -07008588 audio_channel_mask_t channelMask = audio_channel_in_mask_from_count(mChannelCount);
8589
8590 AudioParameter param = AudioParameter(keyValuePair);
8591 int value;
Haynes Mathew George9ce67b52015-09-30 11:40:47 -07008592
8593 // scope for AutoPark extends to end of method
8594 AutoPark<FastCapture> park(mFastCapture);
8595
Eric Laurent10351942014-05-08 18:49:52 -07008596 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
8597 // channel count change can be requested. Do we mandate the first client defines the
8598 // HAL sampling rate and channel count or do we allow changes on the fly?
8599 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
8600 samplingRate = value;
8601 reconfig = true;
8602 }
8603 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung97a893e2015-03-29 01:03:07 -07008604 if (!audio_is_linear_pcm((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07008605 status = BAD_VALUE;
8606 } else {
8607 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08008608 reconfig = true;
8609 }
Eric Laurent10351942014-05-08 18:49:52 -07008610 }
8611 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
8612 audio_channel_mask_t mask = (audio_channel_mask_t) value;
Andy Hungd330ee42015-04-20 13:23:41 -07008613 if (!audio_is_input_channel(mask) ||
Andy Hung936845a2021-06-08 00:09:06 -07008614 audio_channel_count_from_in_mask(mask) > FCC_LIMIT) {
Eric Laurent10351942014-05-08 18:49:52 -07008615 status = BAD_VALUE;
8616 } else {
8617 channelMask = mask;
8618 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08008619 }
Eric Laurent10351942014-05-08 18:49:52 -07008620 }
8621 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
8622 // do not accept frame count changes if tracks are open as the track buffer
8623 // size depends on frame count and correct behavior would not be guaranteed
8624 // if frame count is changed after track creation
8625 if (mActiveTracks.size() > 0) {
8626 status = INVALID_OPERATION;
8627 } else {
8628 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08008629 }
Eric Laurent10351942014-05-08 18:49:52 -07008630 }
8631 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07008632 LOG_FATAL("Should not set routing device in RecordThread");
Eric Laurent10351942014-05-08 18:49:52 -07008633 }
8634 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
8635 mAudioSource != (audio_source_t)value) {
jiabinc52b1ff2019-10-31 17:20:42 -07008636 LOG_FATAL("Should not set audio source in RecordThread");
Eric Laurent10351942014-05-08 18:49:52 -07008637 }
Glenn Kastene198c362013-08-13 09:13:36 -07008638
Eric Laurent10351942014-05-08 18:49:52 -07008639 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008640 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07008641 if (status == INVALID_OPERATION) {
8642 inputStandBy();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008643 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07008644 }
8645 if (reconfig) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008646 if (status == BAD_VALUE) {
Mikhail Naganov560637e2021-03-31 22:40:13 +00008647 audio_config_base_t config = AUDIO_CONFIG_BASE_INITIALIZER;
8648 if (mInput->stream->getAudioProperties(&config) == OK &&
8649 audio_is_linear_pcm(config.format) && audio_is_linear_pcm(reqFormat) &&
8650 config.sample_rate <= (AUDIO_RESAMPLER_DOWN_RATIO_MAX * samplingRate) &&
Andy Hung936845a2021-06-08 00:09:06 -07008651 audio_channel_count_from_in_mask(config.channel_mask) <= FCC_LIMIT) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008652 status = NO_ERROR;
8653 }
Eric Laurent81784c32012-11-19 14:55:58 -08008654 }
Eric Laurent10351942014-05-08 18:49:52 -07008655 if (status == NO_ERROR) {
8656 readInputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07008657 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08008658 }
8659 }
Eric Laurent81784c32012-11-19 14:55:58 -08008660 }
Eric Laurent10351942014-05-08 18:49:52 -07008661
Eric Laurent81784c32012-11-19 14:55:58 -08008662 return reconfig;
8663}
8664
8665String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
8666{
Eric Laurent81784c32012-11-19 14:55:58 -08008667 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008668 if (initCheck() == NO_ERROR) {
8669 String8 out_s8;
8670 if (mInput->stream->getParameters(keys, &out_s8) == OK) {
8671 return out_s8;
8672 }
Eric Laurent81784c32012-11-19 14:55:58 -08008673 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008674 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08008675}
8676
Eric Laurent09f1ed22019-04-24 17:45:17 -07008677void AudioFlinger::RecordThread::ioConfigChanged(audio_io_config_event event, pid_t pid,
8678 audio_port_handle_t portId) {
Eric Laurent73e26b62015-04-27 16:55:58 -07008679 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
8680
8681 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08008682
8683 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07008684 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07008685 case AUDIO_INPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07008686 case AUDIO_INPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07008687 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07008688 desc->mChannelMask = mChannelMask;
8689 desc->mSamplingRate = mSampleRate;
8690 desc->mFormat = mFormat;
8691 desc->mFrameCount = mFrameCount;
Glenn Kasten4a8308b2016-04-18 14:10:01 -07008692 desc->mFrameCountHAL = mFrameCount;
Eric Laurent73e26b62015-04-27 16:55:58 -07008693 desc->mLatency = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08008694 break;
Eric Laurent09f1ed22019-04-24 17:45:17 -07008695 case AUDIO_CLIENT_STARTED:
8696 desc->mPatch = mPatch;
8697 desc->mPortId = portId;
8698 break;
Eric Laurent73e26b62015-04-27 16:55:58 -07008699 case AUDIO_INPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08008700 default:
8701 break;
8702 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07008703 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08008704}
8705
Glenn Kastendeca2ae2014-02-07 10:25:56 -08008706void AudioFlinger::RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08008707{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008708 status_t result = mInput->stream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
8709 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
Andy Hung463be252014-07-10 16:56:07 -07008710 mFormat = mHALFormat;
Mikhail Naganovce9f2652018-07-16 11:09:24 -07008711 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
8712 if (audio_is_linear_pcm(mFormat)) {
Andy Hung936845a2021-06-08 00:09:06 -07008713 LOG_ALWAYS_FATAL_IF(mChannelCount > FCC_LIMIT, "HAL channel count %d > %d",
8714 mChannelCount, FCC_LIMIT);
Mikhail Naganovce9f2652018-07-16 11:09:24 -07008715 } else {
Andy Hung936845a2021-06-08 00:09:06 -07008716 // Can have more that FCC_LIMIT channels in encoded streams.
Mikhail Naganovce9f2652018-07-16 11:09:24 -07008717 ALOGI("HAL format %#x is not linear pcm", mFormat);
8718 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008719 result = mInput->stream->getFrameSize(&mFrameSize);
8720 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
Hayden Gomes1a89ab32020-06-12 11:05:47 -07008721 LOG_ALWAYS_FATAL_IF(mFrameSize <= 0, "Error frame size was %zu but must be greater than zero",
8722 mFrameSize);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008723 result = mInput->stream->getBufferSize(&mBufferSize);
8724 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
Glenn Kasten548efc92012-11-29 08:48:51 -08008725 mFrameCount = mBufferSize / mFrameSize;
Hayden Gomes1a89ab32020-06-12 11:05:47 -07008726 ALOGV("%p RecordThread params: mChannelCount=%u, mFormat=%#x, mFrameSize=%zu, "
8727 "mBufferSize=%zu, mFrameCount=%zu",
8728 this, mChannelCount, mFormat, mFrameSize, mBufferSize, mFrameCount);
Glenn Kasten49d00ad2014-07-21 11:22:03 -07008729
Eric Laurentec376dc2021-04-08 20:41:22 +02008730 // mRsmpInFrames must be 0 before calling resizeInputBuffer_l for the first time
8731 mRsmpInFrames = 0;
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008732 resizeInputBuffer_l(0 /*maxSharedAudioHistoryMs*/);
Eric Laurent81784c32012-11-19 14:55:58 -08008733
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08008734 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
8735 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Andy Hungea840382020-05-05 21:50:17 -07008736
8737 audio_input_flags_t flags = mInput->flags;
8738 mediametrics::LogItem item(mThreadMetrics.getMetricsId());
8739 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
8740 .set(AMEDIAMETRICS_PROP_ENCODING, formatToString(mFormat).c_str())
8741 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
8742 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
8743 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
8744 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
8745 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mFrameCount)
8746 .record();
Eric Laurent81784c32012-11-19 14:55:58 -08008747}
8748
Glenn Kasten5f972c02014-01-13 09:59:31 -08008749uint32_t AudioFlinger::RecordThread::getInputFramesLost()
Eric Laurent81784c32012-11-19 14:55:58 -08008750{
8751 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008752 uint32_t result;
8753 if (initCheck() == NO_ERROR && mInput->stream->getInputFramesLost(&result) == OK) {
8754 return result;
Eric Laurent81784c32012-11-19 14:55:58 -08008755 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008756 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08008757}
8758
Glenn Kastend848eb42016-03-08 13:42:11 -08008759KeyedVector<audio_session_t, bool> AudioFlinger::RecordThread::sessionIds() const
Eric Laurent81784c32012-11-19 14:55:58 -08008760{
Glenn Kastend848eb42016-03-08 13:42:11 -08008761 KeyedVector<audio_session_t, bool> ids;
Eric Laurent81784c32012-11-19 14:55:58 -08008762 Mutex::Autolock _l(mLock);
8763 for (size_t j = 0; j < mTracks.size(); ++j) {
8764 sp<RecordThread::RecordTrack> track = mTracks[j];
Glenn Kastend848eb42016-03-08 13:42:11 -08008765 audio_session_t sessionId = track->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08008766 if (ids.indexOfKey(sessionId) < 0) {
8767 ids.add(sessionId, true);
8768 }
8769 }
8770 return ids;
8771}
8772
8773AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
8774{
8775 Mutex::Autolock _l(mLock);
8776 AudioStreamIn *input = mInput;
8777 mInput = NULL;
8778 return input;
8779}
8780
8781// this method must always be called either with ThreadBase mLock held or inside the thread loop
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008782sp<StreamHalInterface> AudioFlinger::RecordThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08008783{
8784 if (mInput == NULL) {
8785 return NULL;
8786 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008787 return mInput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08008788}
8789
8790status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
8791{
Eric Laurent81784c32012-11-19 14:55:58 -08008792 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurentaaa44472014-09-12 17:41:50 -07008793 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08008794 chain->setInBuffer(NULL);
8795 chain->setOutBuffer(NULL);
8796
8797 checkSuspendOnAddEffectChain_l(chain);
8798
Eric Laurent1b928682014-10-02 19:41:47 -07008799 // make sure enabled pre processing effects state is communicated to the HAL as we
8800 // just moved them to a new input stream.
8801 chain->syncHalEffectsState();
8802
Eric Laurent81784c32012-11-19 14:55:58 -08008803 mEffectChains.add(chain);
8804
8805 return NO_ERROR;
8806}
8807
8808size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
8809{
8810 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
Eric Laurentb20cf7d2019-04-05 19:37:34 -07008811
8812 for (size_t i = 0; i < mEffectChains.size(); i++) {
8813 if (chain == mEffectChains[i]) {
8814 mEffectChains.removeAt(i);
8815 break;
8816 }
Eric Laurent81784c32012-11-19 14:55:58 -08008817 }
Eric Laurentb20cf7d2019-04-05 19:37:34 -07008818 return mEffectChains.size();
Eric Laurent81784c32012-11-19 14:55:58 -08008819}
8820
Eric Laurent1c333e22014-05-20 10:48:17 -07008821status_t AudioFlinger::RecordThread::createAudioPatch_l(const struct audio_patch *patch,
8822 audio_patch_handle_t *handle)
8823{
8824 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07008825
8826 // store new device and send to effects
jiabinc52b1ff2019-10-31 17:20:42 -07008827 mInDeviceTypeAddr.mType = patch->sources[0].ext.device.type;
jiabin0a488932020-08-07 17:32:40 -07008828 mInDeviceTypeAddr.setAddress(patch->sources[0].ext.device.address);
François Gaffie0c280aa2018-07-25 10:02:15 +02008829 audio_port_handle_t deviceId = patch->sources[0].id;
Eric Laurent054d9d32015-04-24 08:48:48 -07008830 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08008831 mEffectChains[i]->setInputDevice_l(inDeviceTypeAddr());
Eric Laurent054d9d32015-04-24 08:48:48 -07008832 }
8833
Eric Laurentd8365c52017-07-16 15:27:05 -07008834 checkBtNrec_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07008835
8836 // store new source and send to effects
8837 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
8838 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent1c333e22014-05-20 10:48:17 -07008839 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent054d9d32015-04-24 08:48:48 -07008840 mEffectChains[i]->setAudioSource_l(mAudioSource);
Eric Laurent1c333e22014-05-20 10:48:17 -07008841 }
Eric Laurent054d9d32015-04-24 08:48:48 -07008842 }
Eric Laurent1c333e22014-05-20 10:48:17 -07008843
Mikhail Naganov9ee05402016-10-13 15:58:17 -07008844 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07008845 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
8846 status = hwDevice->createAudioPatch(patch->num_sources,
8847 patch->sources,
8848 patch->num_sinks,
8849 patch->sinks,
8850 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07008851 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07008852 char *address;
8853 if (strcmp(patch->sources[0].ext.device.address, "") != 0) {
8854 address = audio_device_address_to_parameter(
8855 patch->sources[0].ext.device.type,
8856 patch->sources[0].ext.device.address);
8857 } else {
8858 address = (char *)calloc(1, 1);
8859 }
8860 AudioParameter param = AudioParameter(String8(address));
8861 free(address);
Mikhail Naganov00260b52016-10-13 12:54:24 -07008862 param.addInt(String8(AudioParameter::keyRouting),
Eric Laurent054d9d32015-04-24 08:48:48 -07008863 (int)patch->sources[0].ext.device.type);
Mikhail Naganov00260b52016-10-13 12:54:24 -07008864 param.addInt(String8(AudioParameter::keyInputSource),
Eric Laurent054d9d32015-04-24 08:48:48 -07008865 (int)patch->sinks[0].ext.mix.usecase.source);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008866 status = mInput->stream->setParameters(param.toString());
Eric Laurent054d9d32015-04-24 08:48:48 -07008867 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07008868 }
Eric Laurent054d9d32015-04-24 08:48:48 -07008869
jiabinc52b1ff2019-10-31 17:20:42 -07008870 if ((mPatch.num_sources == 0) || (mPatch.sources[0].id != deviceId)) {
Eric Laurente8726fe2015-06-26 09:39:24 -07008871 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
jiabinc52b1ff2019-10-31 17:20:42 -07008872 mPatch = *patch;
Eric Laurente8726fe2015-06-26 09:39:24 -07008873 }
Eric Laurent296fb132015-05-01 11:38:42 -07008874
Andy Hungc2b11cb2020-04-22 09:04:01 -07008875 const std::string pathSourcesAsString = patchSourcesToString(patch);
Andy Hungcf10d742020-04-28 15:38:24 -07008876 mThreadMetrics.logEndInterval();
Andy Hungea840382020-05-05 21:50:17 -07008877 mThreadMetrics.logCreatePatch(pathSourcesAsString, /* outDevices */ {});
Andy Hungcf10d742020-04-28 15:38:24 -07008878 mThreadMetrics.logBeginInterval();
Andy Hungc2b11cb2020-04-22 09:04:01 -07008879 // also dispatch to active AudioRecords
8880 for (const auto &track : mActiveTracks) {
8881 track->logEndInterval();
8882 track->logBeginInterval(pathSourcesAsString);
8883 }
Eric Laurent1c333e22014-05-20 10:48:17 -07008884 return status;
8885}
8886
8887status_t AudioFlinger::RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
8888{
8889 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07008890
jiabinc52b1ff2019-10-31 17:20:42 -07008891 mPatch = audio_patch{};
8892 mInDeviceTypeAddr.reset();
Eric Laurent054d9d32015-04-24 08:48:48 -07008893
Mikhail Naganov9ee05402016-10-13 15:58:17 -07008894 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07008895 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
8896 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07008897 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07008898 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07008899 param.addInt(String8(AudioParameter::keyRouting), 0);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008900 status = mInput->stream->setParameters(param.toString());
Eric Laurent1c333e22014-05-20 10:48:17 -07008901 }
8902 return status;
8903}
8904
jiabinc52b1ff2019-10-31 17:20:42 -07008905void AudioFlinger::RecordThread::updateOutDevices(const DeviceDescriptorBaseVector& outDevices)
8906{
wendy lin56aa82b2020-12-02 15:19:55 +08008907 Mutex::Autolock _l(mLock);
jiabinc52b1ff2019-10-31 17:20:42 -07008908 mOutDevices = outDevices;
8909 mOutDeviceTypeAddrs = deviceTypeAddrsFromDescriptors(mOutDevices);
8910 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08008911 mEffectChains[i]->setDevices_l(outDeviceTypeAddrs());
jiabinc52b1ff2019-10-31 17:20:42 -07008912 }
8913}
8914
Eric Laurentec376dc2021-04-08 20:41:22 +02008915int32_t AudioFlinger::RecordThread::getOldestFront_l()
8916{
8917 if (mTracks.size() == 0) {
Eric Laurent92d0a322021-07-16 15:32:33 +02008918 return mRsmpInRear;
Eric Laurentec376dc2021-04-08 20:41:22 +02008919 }
Eric Laurent2407ce32021-04-26 14:56:03 +02008920 int32_t oldestFront = mRsmpInRear;
8921 int32_t maxFilled = 0;
Eric Laurentec376dc2021-04-08 20:41:22 +02008922 for (size_t i = 0; i < mTracks.size(); i++) {
Eric Laurent2407ce32021-04-26 14:56:03 +02008923 int32_t front = mTracks[i]->mResamplerBufferProvider->getFront();
8924 int32_t filled;
Eric Laurent92d0a322021-07-16 15:32:33 +02008925 (void)__builtin_sub_overflow(mRsmpInRear, front, &filled);
Eric Laurent2407ce32021-04-26 14:56:03 +02008926 if (filled > maxFilled) {
8927 oldestFront = front;
8928 maxFilled = filled;
8929 }
Eric Laurentec376dc2021-04-08 20:41:22 +02008930 }
Eric Laurent92d0a322021-07-16 15:32:33 +02008931 if (maxFilled > mRsmpInFrames) {
8932 (void)__builtin_sub_overflow(mRsmpInRear, mRsmpInFrames, &oldestFront);
8933 }
Eric Laurent2407ce32021-04-26 14:56:03 +02008934 return oldestFront;
Eric Laurentec376dc2021-04-08 20:41:22 +02008935}
8936
8937void AudioFlinger::RecordThread::updateFronts_l(int32_t offset)
8938{
8939 if (offset == 0) {
8940 return;
8941 }
8942 for (size_t i = 0; i < mTracks.size(); i++) {
8943 int32_t front = mTracks[i]->mResamplerBufferProvider->getFront();
8944 front = audio_utils::safe_sub_overflow(front, offset);
8945 mTracks[i]->mResamplerBufferProvider->setFront(front);
8946 }
8947}
8948
8949void AudioFlinger::RecordThread::resizeInputBuffer_l(int32_t maxSharedAudioHistoryMs)
8950{
8951 // This is the formula for calculating the temporary buffer size.
8952 // With 7 HAL buffers, we can guarantee ability to down-sample the input by ratio of 6:1 to
8953 // 1 full output buffer, regardless of the alignment of the available input.
8954 // The value is somewhat arbitrary, and could probably be even larger.
8955 // A larger value should allow more old data to be read after a track calls start(),
8956 // without increasing latency.
8957 //
8958 // Note this is independent of the maximum downsampling ratio permitted for capture.
8959 size_t minRsmpInFrames = mFrameCount * 7;
8960
8961 // maxSharedAudioHistoryMs != 0 indicates a request to possibly make some part of the audio
8962 // capture history available to another client using the same session ID:
8963 // dimension the resampler input buffer accordingly.
8964
8965 // Get oldest client read position: getOldestFront_l() must be called before altering
8966 // mRsmpInRear, or mRsmpInFrames
8967 int32_t previousFront = getOldestFront_l();
8968 size_t previousRsmpInFramesP2 = mRsmpInFramesP2;
8969 int32_t previousRear = mRsmpInRear;
8970 mRsmpInRear = 0;
8971
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008972 ALOG_ASSERT(maxSharedAudioHistoryMs >= 0
8973 && maxSharedAudioHistoryMs <= AudioFlinger::kMaxSharedAudioHistoryMs,
8974 "resizeInputBuffer_l() called with invalid max shared history %d",
8975 maxSharedAudioHistoryMs);
Eric Laurentec376dc2021-04-08 20:41:22 +02008976 if (maxSharedAudioHistoryMs != 0) {
8977 // resizeInputBuffer_l should never be called with a non zero shared history if the
8978 // buffer was not already allocated
8979 ALOG_ASSERT(mRsmpInBuffer != nullptr && mRsmpInFrames != 0,
8980 "resizeInputBuffer_l() called with shared history and unallocated buffer");
8981 size_t rsmpInFrames = (size_t)maxSharedAudioHistoryMs * mSampleRate / 1000;
8982 // never reduce resampler input buffer size
Eric Laurent92d0a322021-07-16 15:32:33 +02008983 if (rsmpInFrames <= mRsmpInFrames) {
Eric Laurentec376dc2021-04-08 20:41:22 +02008984 return;
8985 }
8986 mRsmpInFrames = rsmpInFrames;
8987 }
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008988 mMaxSharedAudioHistoryMs = maxSharedAudioHistoryMs;
Eric Laurentec376dc2021-04-08 20:41:22 +02008989 // Note: mRsmpInFrames is 0 when called with maxSharedAudioHistoryMs equals to 0 so it is always
8990 // initialized
8991 if (mRsmpInFrames < minRsmpInFrames) {
8992 mRsmpInFrames = minRsmpInFrames;
8993 }
8994 mRsmpInFramesP2 = roundup(mRsmpInFrames);
8995
8996 // TODO optimize audio capture buffer sizes ...
8997 // Here we calculate the size of the sliding buffer used as a source
8998 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
8999 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
9000 // be better to have it derived from the pipe depth in the long term.
9001 // The current value is higher than necessary. However it should not add to latency.
9002
9003 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
9004 mRsmpInFramesOA = mRsmpInFramesP2 + mFrameCount - 1;
9005
9006 void *rsmpInBuffer;
9007 (void)posix_memalign(&rsmpInBuffer, 32, mRsmpInFramesOA * mFrameSize);
9008 // if posix_memalign fails, will segv here.
9009 memset(rsmpInBuffer, 0, mRsmpInFramesOA * mFrameSize);
9010
9011 // Copy audio history if any from old buffer before freeing it
9012 if (previousRear != 0) {
9013 ALOG_ASSERT(mRsmpInBuffer != nullptr,
9014 "resizeInputBuffer_l() called with null buffer but frames already read from HAL");
9015
9016 ssize_t unread = audio_utils::safe_sub_overflow(previousRear, previousFront);
9017 previousFront &= previousRsmpInFramesP2 - 1;
9018 size_t part1 = previousRsmpInFramesP2 - previousFront;
9019 if (part1 > (size_t) unread) {
9020 part1 = unread;
9021 }
9022 if (part1 != 0) {
9023 memcpy(rsmpInBuffer, (const uint8_t*)mRsmpInBuffer + previousFront * mFrameSize,
9024 part1 * mFrameSize);
9025 mRsmpInRear = part1;
9026 part1 = unread - part1;
9027 if (part1 != 0) {
9028 memcpy((uint8_t*)rsmpInBuffer + mRsmpInRear * mFrameSize,
9029 (const uint8_t*)mRsmpInBuffer, part1 * mFrameSize);
9030 mRsmpInRear += part1;
9031 }
9032 }
9033 // Update front for all clients according to new rear
9034 updateFronts_l(audio_utils::safe_sub_overflow(previousRear, mRsmpInRear));
9035 } else {
9036 mRsmpInRear = 0;
9037 }
9038 free(mRsmpInBuffer);
9039 mRsmpInBuffer = rsmpInBuffer;
9040}
9041
Mikhail Naganov444ecc32018-05-01 17:40:05 -07009042void AudioFlinger::RecordThread::addPatchTrack(const sp<PatchRecord>& record)
Eric Laurent83b88082014-06-20 18:31:16 -07009043{
9044 Mutex::Autolock _l(mLock);
9045 mTracks.add(record);
Mikhail Naganov2534b382019-09-25 13:05:02 -07009046 if (record->getSource()) {
9047 mSource = record->getSource();
9048 }
Eric Laurent83b88082014-06-20 18:31:16 -07009049}
9050
Mikhail Naganov444ecc32018-05-01 17:40:05 -07009051void AudioFlinger::RecordThread::deletePatchTrack(const sp<PatchRecord>& record)
Eric Laurent83b88082014-06-20 18:31:16 -07009052{
9053 Mutex::Autolock _l(mLock);
Mikhail Naganov2534b382019-09-25 13:05:02 -07009054 if (mSource == record->getSource()) {
9055 mSource = mInput;
9056 }
Eric Laurent83b88082014-06-20 18:31:16 -07009057 destroyTrack_l(record);
9058}
9059
Mikhail Naganovdc769682018-05-04 15:34:08 -07009060void AudioFlinger::RecordThread::toAudioPortConfig(struct audio_port_config *config)
Eric Laurent83b88082014-06-20 18:31:16 -07009061{
Mikhail Naganovdc769682018-05-04 15:34:08 -07009062 ThreadBase::toAudioPortConfig(config);
Eric Laurent83b88082014-06-20 18:31:16 -07009063 config->role = AUDIO_PORT_ROLE_SINK;
9064 config->ext.mix.hw_module = mInput->audioHwDev->handle();
9065 config->ext.mix.usecase.source = mAudioSource;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07009066 if (mInput && mInput->flags != AUDIO_INPUT_FLAG_NONE) {
9067 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
9068 config->flags.input = mInput->flags;
9069 }
Eric Laurent83b88082014-06-20 18:31:16 -07009070}
Eric Laurent1c333e22014-05-20 10:48:17 -07009071
Eric Laurent6acd1d42017-01-04 14:23:29 -08009072// ----------------------------------------------------------------------------
9073// Mmap
9074// ----------------------------------------------------------------------------
9075
9076AudioFlinger::MmapThreadHandle::MmapThreadHandle(const sp<MmapThread>& thread)
9077 : mThread(thread)
9078{
Phil Burk9fabbf82017-08-03 12:02:00 -07009079 assert(thread != 0); // thread must start non-null and stay non-null
Eric Laurent6acd1d42017-01-04 14:23:29 -08009080}
9081
9082AudioFlinger::MmapThreadHandle::~MmapThreadHandle()
9083{
Phil Burk9fabbf82017-08-03 12:02:00 -07009084 mThread->disconnect();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009085}
9086
9087status_t AudioFlinger::MmapThreadHandle::createMmapBuffer(int32_t minSizeFrames,
9088 struct audio_mmap_buffer_info *info)
9089{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009090 return mThread->createMmapBuffer(minSizeFrames, info);
9091}
9092
9093status_t AudioFlinger::MmapThreadHandle::getMmapPosition(struct audio_mmap_position *position)
9094{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009095 return mThread->getMmapPosition(position);
9096}
9097
jiabinb7d8c5a2020-08-26 17:24:52 -07009098status_t AudioFlinger::MmapThreadHandle::getExternalPosition(uint64_t *position,
9099 int64_t *timeNanos) {
9100 return mThread->getExternalPosition(position, timeNanos);
9101}
9102
Eric Laurenta54f1282017-07-01 19:39:32 -07009103status_t AudioFlinger::MmapThreadHandle::start(const AudioClient& client,
jiabind1f1cb62020-03-24 11:57:57 -07009104 const audio_attributes_t *attr, audio_port_handle_t *handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009105
9106{
jiabind1f1cb62020-03-24 11:57:57 -07009107 return mThread->start(client, attr, handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009108}
9109
9110status_t AudioFlinger::MmapThreadHandle::stop(audio_port_handle_t handle)
9111{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009112 return mThread->stop(handle);
9113}
9114
Eric Laurent18b57012017-02-13 16:23:52 -08009115status_t AudioFlinger::MmapThreadHandle::standby()
9116{
Eric Laurent18b57012017-02-13 16:23:52 -08009117 return mThread->standby();
9118}
9119
Eric Laurent6acd1d42017-01-04 14:23:29 -08009120
9121AudioFlinger::MmapThread::MmapThread(
9122 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
Andy Hungcf10d742020-04-28 15:38:24 -07009123 AudioHwDevice *hwDev, sp<StreamHalInterface> stream, bool systemReady, bool isOut)
Andy Hungea840382020-05-05 21:50:17 -07009124 : ThreadBase(audioFlinger, id, (isOut ? MMAP_PLAYBACK : MMAP_CAPTURE), systemReady, isOut),
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009125 mSessionId(AUDIO_SESSION_NONE),
François Gaffie0c280aa2018-07-25 10:02:15 +02009126 mPortId(AUDIO_PORT_HANDLE_NONE),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009127 mHalStream(stream), mHalDevice(hwDev->hwDevice()), mAudioHwDev(hwDev),
Eric Laurent67f97292018-04-20 18:05:41 -07009128 mActiveTracks(&this->mLocalLog),
9129 mHalVolFloat(-1.0f), // Initialize to illegal value so it always gets set properly later.
9130 mNoCallbackWarningCount(0)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009131{
Eric Laurent18b57012017-02-13 16:23:52 -08009132 mStandby = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009133 readHalParameters_l();
9134}
9135
9136AudioFlinger::MmapThread::~MmapThread()
9137{
9138}
9139
9140void AudioFlinger::MmapThread::onFirstRef()
9141{
9142 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
9143}
9144
9145void AudioFlinger::MmapThread::disconnect()
9146{
Eric Laurent331679c2018-04-16 17:03:16 -07009147 ActiveTracks<MmapTrack> activeTracks;
9148 {
9149 Mutex::Autolock _l(mLock);
9150 for (const sp<MmapTrack> &t : mActiveTracks) {
9151 activeTracks.add(t);
9152 }
9153 }
9154 for (const sp<MmapTrack> &t : activeTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08009155 stop(t->portId());
9156 }
Phil Burk9fabbf82017-08-03 12:02:00 -07009157 // This will decrement references and may cause the destruction of this thread.
Eric Laurent6acd1d42017-01-04 14:23:29 -08009158 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07009159 AudioSystem::releaseOutput(mPortId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009160 } else {
Eric Laurentfee19762018-01-29 18:44:13 -08009161 AudioSystem::releaseInput(mPortId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009162 }
9163}
9164
9165
9166void AudioFlinger::MmapThread::configure(const audio_attributes_t *attr,
9167 audio_stream_type_t streamType __unused,
9168 audio_session_t sessionId,
9169 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009170 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -08009171 audio_port_handle_t portId)
9172{
9173 mAttr = *attr;
9174 mSessionId = sessionId;
9175 mCallback = callback;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009176 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009177 mPortId = portId;
9178}
9179
9180status_t AudioFlinger::MmapThread::createMmapBuffer(int32_t minSizeFrames,
9181 struct audio_mmap_buffer_info *info)
9182{
9183 if (mHalStream == 0) {
9184 return NO_INIT;
9185 }
Eric Laurent18b57012017-02-13 16:23:52 -08009186 mStandby = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009187 return mHalStream->createMmapBuffer(minSizeFrames, info);
9188}
9189
9190status_t AudioFlinger::MmapThread::getMmapPosition(struct audio_mmap_position *position)
9191{
9192 if (mHalStream == 0) {
9193 return NO_INIT;
9194 }
9195 return mHalStream->getMmapPosition(position);
9196}
9197
Eric Laurent331679c2018-04-16 17:03:16 -07009198status_t AudioFlinger::MmapThread::exitStandby()
9199{
9200 status_t ret = mHalStream->start();
9201 if (ret != NO_ERROR) {
9202 ALOGE("%s: error mHalStream->start() = %d for first track", __FUNCTION__, ret);
9203 return ret;
9204 }
Andy Hungcf10d742020-04-28 15:38:24 -07009205 if (mStandby) {
9206 mThreadMetrics.logBeginInterval();
9207 mStandby = false;
9208 }
Eric Laurent331679c2018-04-16 17:03:16 -07009209 return NO_ERROR;
9210}
9211
Eric Laurenta54f1282017-07-01 19:39:32 -07009212status_t AudioFlinger::MmapThread::start(const AudioClient& client,
jiabind1f1cb62020-03-24 11:57:57 -07009213 const audio_attributes_t *attr,
Eric Laurent6acd1d42017-01-04 14:23:29 -08009214 audio_port_handle_t *handle)
9215{
Eric Laurenta54f1282017-07-01 19:39:32 -07009216 ALOGV("%s clientUid %d mStandby %d mPortId %d *handle %d", __FUNCTION__,
Svet Ganov33761132021-05-13 22:51:08 +00009217 client.attributionSource.uid, mStandby, mPortId, *handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009218 if (mHalStream == 0) {
9219 return NO_INIT;
9220 }
9221
9222 status_t ret;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009223
Eric Laurenta54f1282017-07-01 19:39:32 -07009224 if (*handle == mPortId) {
Phil Burk98ab4082020-09-25 21:46:34 +00009225 // For the first track, reuse portId and session allocated when the stream was opened.
9226 ret = exitStandby();
9227 if (ret == NO_ERROR) {
9228 acquireWakeLock();
9229 }
9230 return ret;
Eric Laurenta54f1282017-07-01 19:39:32 -07009231 }
9232
9233 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
9234
9235 audio_io_handle_t io = mId;
9236 if (isOutput()) {
9237 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
9238 config.sample_rate = mSampleRate;
9239 config.channel_mask = mChannelMask;
9240 config.format = mFormat;
9241 audio_stream_type_t stream = streamType();
9242 audio_output_flags_t flags =
9243 (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009244 audio_port_handle_t deviceId = mDeviceId;
Kevin Rocard153f92d2018-12-18 18:33:28 -08009245 std::vector<audio_io_handle_t> secondaryOutputs;
Eric Laurenta54f1282017-07-01 19:39:32 -07009246 ret = AudioSystem::getOutputForAttr(&mAttr, &io,
9247 mSessionId,
9248 &stream,
Svet Ganov33761132021-05-13 22:51:08 +00009249 client.attributionSource,
Eric Laurenta54f1282017-07-01 19:39:32 -07009250 &config,
9251 flags,
9252 &deviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -08009253 &portId,
9254 &secondaryOutputs);
9255 ALOGD_IF(!secondaryOutputs.empty(),
9256 "MmapThread::start does not support secondary outputs, ignoring them");
Eric Laurent6acd1d42017-01-04 14:23:29 -08009257 } else {
Eric Laurenta54f1282017-07-01 19:39:32 -07009258 audio_config_base_t config;
9259 config.sample_rate = mSampleRate;
9260 config.channel_mask = mChannelMask;
9261 config.format = mFormat;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009262 audio_port_handle_t deviceId = mDeviceId;
Eric Laurenta54f1282017-07-01 19:39:32 -07009263 ret = AudioSystem::getInputForAttr(&mAttr, &io,
Mikhail Naganov2996f672019-04-18 12:29:59 -07009264 RECORD_RIID_INVALID,
Eric Laurenta54f1282017-07-01 19:39:32 -07009265 mSessionId,
Svet Ganov33761132021-05-13 22:51:08 +00009266 client.attributionSource,
Eric Laurenta54f1282017-07-01 19:39:32 -07009267 &config,
9268 AUDIO_INPUT_FLAG_MMAP_NOIRQ,
9269 &deviceId,
9270 &portId);
9271 }
9272 // APM should not chose a different input or output stream for the same set of attributes
9273 // and audo configuration
9274 if (ret != NO_ERROR || io != mId) {
9275 ALOGE("%s: error getting output or input from APM (error %d, io %d expected io %d)",
9276 __FUNCTION__, ret, io, mId);
9277 return BAD_VALUE;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009278 }
9279
9280 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07009281 ret = AudioSystem::startOutput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009282 } else {
Eric Laurent4eb58f12018-12-07 16:41:02 -08009283 ret = AudioSystem::startInput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009284 }
9285
Eric Laurent331679c2018-04-16 17:03:16 -07009286 Mutex::Autolock _l(mLock);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009287 // abort if start is rejected by audio policy manager
9288 if (ret != NO_ERROR) {
Phil Burk7f6b40d2017-02-09 13:18:38 -08009289 ALOGE("%s: error start rejected by AudioPolicyManager = %d", __FUNCTION__, ret);
Eric Tan39ec8d62018-07-24 09:49:29 -07009290 if (!mActiveTracks.isEmpty()) {
Eric Laurent331679c2018-04-16 17:03:16 -07009291 mLock.unlock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009292 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07009293 AudioSystem::releaseOutput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009294 } else {
Eric Laurentfee19762018-01-29 18:44:13 -08009295 AudioSystem::releaseInput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009296 }
Eric Laurent331679c2018-04-16 17:03:16 -07009297 mLock.lock();
Eric Laurent18b57012017-02-13 16:23:52 -08009298 } else {
9299 mHalStream->stop();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009300 }
9301 return PERMISSION_DENIED;
9302 }
9303
Kevin Rocard1f564ac2018-03-29 13:53:10 -07009304 // Given that MmapThread::mAttr is mutable, should a MmapTrack have attributes ?
jiabind1f1cb62020-03-24 11:57:57 -07009305 sp<MmapTrack> track = new MmapTrack(this, attr == nullptr ? mAttr : *attr, mSampleRate, mFormat,
Svet Ganov33761132021-05-13 22:51:08 +00009306 mChannelMask, mSessionId, isOutput(),
9307 client.attributionSource,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07009308 IPCThreadState::self()->getCallingPid(), portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009309
Eric Laurent4eb58f12018-12-07 16:41:02 -08009310 if (isOutput()) {
9311 // force volume update when a new track is added
9312 mHalVolFloat = -1.0f;
9313 } else if (!track->isSilenced_l()) {
9314 for (const sp<MmapTrack> &t : mActiveTracks) {
Svet Ganov33761132021-05-13 22:51:08 +00009315 if (t->isSilenced_l() && t->uid() != client.attributionSource.uid)
Eric Laurent4eb58f12018-12-07 16:41:02 -08009316 t->invalidate();
9317 }
9318 }
9319
9320
Eric Laurent6acd1d42017-01-04 14:23:29 -08009321 mActiveTracks.add(track);
Eric Laurenta54f1282017-07-01 19:39:32 -07009322 sp<EffectChain> chain = getEffectChain_l(mSessionId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009323 if (chain != 0) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02009324 chain->setStrategy(getStrategyForStream(streamType()));
Eric Laurent6acd1d42017-01-04 14:23:29 -08009325 chain->incTrackCnt();
9326 chain->incActiveTrackCnt();
9327 }
9328
Andy Hungc2b11cb2020-04-22 09:04:01 -07009329 track->logBeginInterval(patchSinksToString(&mPatch)); // log to MediaMetrics
Eric Laurent6acd1d42017-01-04 14:23:29 -08009330 *handle = portId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009331 broadcast_l();
9332
Eric Laurenta54f1282017-07-01 19:39:32 -07009333 ALOGV("%s DONE handle %d stream %p", __FUNCTION__, *handle, mHalStream.get());
Eric Laurent6acd1d42017-01-04 14:23:29 -08009334
9335 return NO_ERROR;
9336}
9337
9338status_t AudioFlinger::MmapThread::stop(audio_port_handle_t handle)
9339{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009340 ALOGV("%s handle %d", __FUNCTION__, handle);
9341
9342 if (mHalStream == 0) {
9343 return NO_INIT;
9344 }
9345
Eric Laurenta54f1282017-07-01 19:39:32 -07009346 if (handle == mPortId) {
9347 mHalStream->stop();
Phil Burk98ab4082020-09-25 21:46:34 +00009348 releaseWakeLock();
Eric Laurenta54f1282017-07-01 19:39:32 -07009349 return NO_ERROR;
9350 }
9351
Eric Laurent331679c2018-04-16 17:03:16 -07009352 Mutex::Autolock _l(mLock);
9353
Eric Laurent6acd1d42017-01-04 14:23:29 -08009354 sp<MmapTrack> track;
9355 for (const sp<MmapTrack> &t : mActiveTracks) {
9356 if (handle == t->portId()) {
9357 track = t;
9358 break;
9359 }
9360 }
9361 if (track == 0) {
9362 return BAD_VALUE;
9363 }
9364
9365 mActiveTracks.remove(track);
9366
Eric Laurent331679c2018-04-16 17:03:16 -07009367 mLock.unlock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009368 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07009369 AudioSystem::stopOutput(track->portId());
9370 AudioSystem::releaseOutput(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -08009371 } else {
Eric Laurentfee19762018-01-29 18:44:13 -08009372 AudioSystem::stopInput(track->portId());
9373 AudioSystem::releaseInput(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -08009374 }
Eric Laurent331679c2018-04-16 17:03:16 -07009375 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009376
9377 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
9378 if (chain != 0) {
9379 chain->decActiveTrackCnt();
9380 chain->decTrackCnt();
9381 }
9382
9383 broadcast_l();
9384
Eric Laurent6acd1d42017-01-04 14:23:29 -08009385 return NO_ERROR;
9386}
9387
Eric Laurent18b57012017-02-13 16:23:52 -08009388status_t AudioFlinger::MmapThread::standby()
9389{
9390 ALOGV("%s", __FUNCTION__);
9391
9392 if (mHalStream == 0) {
9393 return NO_INIT;
9394 }
Eric Tan39ec8d62018-07-24 09:49:29 -07009395 if (!mActiveTracks.isEmpty()) {
Eric Laurent18b57012017-02-13 16:23:52 -08009396 return INVALID_OPERATION;
9397 }
9398 mHalStream->standby();
Andy Hungcf10d742020-04-28 15:38:24 -07009399 if (!mStandby) {
9400 mThreadMetrics.logEndInterval();
9401 mStandby = true;
9402 }
Eric Laurent18b57012017-02-13 16:23:52 -08009403 releaseWakeLock();
9404 return NO_ERROR;
9405}
9406
Eric Laurent6acd1d42017-01-04 14:23:29 -08009407
9408void AudioFlinger::MmapThread::readHalParameters_l()
9409{
9410 status_t result = mHalStream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
9411 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
9412 mFormat = mHALFormat;
9413 LOG_ALWAYS_FATAL_IF(!audio_is_linear_pcm(mFormat), "HAL format %#x is not linear pcm", mFormat);
9414 result = mHalStream->getFrameSize(&mFrameSize);
9415 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
Hayden Gomes1a89ab32020-06-12 11:05:47 -07009416 LOG_ALWAYS_FATAL_IF(mFrameSize <= 0, "Error frame size was %zu but must be greater than zero",
9417 mFrameSize);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009418 result = mHalStream->getBufferSize(&mBufferSize);
9419 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
9420 mFrameCount = mBufferSize / mFrameSize;
Andy Hungc2b11cb2020-04-22 09:04:01 -07009421
Andy Hungcf10d742020-04-28 15:38:24 -07009422 // TODO: make a readHalParameters call?
9423 mediametrics::LogItem item(mThreadMetrics.getMetricsId());
Andy Hungc2b11cb2020-04-22 09:04:01 -07009424 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
9425 .set(AMEDIAMETRICS_PROP_ENCODING, formatToString(mFormat).c_str())
9426 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
9427 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
9428 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
9429 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mFrameCount)
9430 /*
9431 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
9432 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELMASK,
9433 (int32_t)mHapticChannelMask)
9434 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELCOUNT,
9435 (int32_t)mHapticChannelCount)
9436 */
9437 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_ENCODING,
9438 formatToString(mHALFormat).c_str())
9439 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_FRAMECOUNT,
9440 (int32_t)mFrameCount) // sic - added HAL
9441 .record();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009442}
9443
9444bool AudioFlinger::MmapThread::threadLoop()
9445{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009446 checkSilentMode_l();
9447
9448 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
9449
9450 while (!exitPending())
9451 {
Eric Laurent6acd1d42017-01-04 14:23:29 -08009452 Vector< sp<EffectChain> > effectChains;
9453
Andy Hung13850be2019-03-14 11:33:09 -07009454 { // under Thread lock
9455 Mutex::Autolock _l(mLock);
9456
Eric Laurent6acd1d42017-01-04 14:23:29 -08009457 if (mSignalPending) {
9458 // A signal was raised while we were unlocked
9459 mSignalPending = false;
9460 } else {
9461 if (mConfigEvents.isEmpty()) {
9462 // we're about to wait, flush the binder command buffer
9463 IPCThreadState::self()->flushCommands();
9464
9465 if (exitPending()) {
9466 break;
9467 }
9468
Eric Laurent6acd1d42017-01-04 14:23:29 -08009469 // wait until we have something to do...
9470 ALOGV("%s going to sleep", myName.string());
9471 mWaitWorkCV.wait(mLock);
9472 ALOGV("%s waking up", myName.string());
Eric Laurent6acd1d42017-01-04 14:23:29 -08009473
9474 checkSilentMode_l();
9475
9476 continue;
9477 }
9478 }
9479
9480 processConfigEvents_l();
9481
9482 processVolume_l();
9483
9484 checkInvalidTracks_l();
9485
9486 mActiveTracks.updatePowerState(this);
9487
Kevin Rocard069c2712018-03-29 19:09:14 -07009488 updateMetadata_l();
9489
Eric Laurent6acd1d42017-01-04 14:23:29 -08009490 lockEffectChains_l(effectChains);
Andy Hung13850be2019-03-14 11:33:09 -07009491 } // release Thread lock
9492
Eric Laurent6acd1d42017-01-04 14:23:29 -08009493 for (size_t i = 0; i < effectChains.size(); i ++) {
Andy Hung13850be2019-03-14 11:33:09 -07009494 effectChains[i]->process_l(); // Thread is not locked, but effect chain is locked
Eric Laurent6acd1d42017-01-04 14:23:29 -08009495 }
Andy Hung13850be2019-03-14 11:33:09 -07009496
9497 // enable changes in effect chain, including moving to another thread.
Eric Laurent6acd1d42017-01-04 14:23:29 -08009498 unlockEffectChains(effectChains);
9499 // Effect chains will be actually deleted here if they were removed from
9500 // mEffectChains list during mixing or effects processing
9501 }
9502
9503 threadLoop_exit();
9504
9505 if (!mStandby) {
9506 threadLoop_standby();
9507 mStandby = true;
9508 }
9509
Eric Laurent6acd1d42017-01-04 14:23:29 -08009510 ALOGV("Thread %p type %d exiting", this, mType);
9511 return false;
9512}
9513
9514// checkForNewParameter_l() must be called with ThreadBase::mLock held
9515bool AudioFlinger::MmapThread::checkForNewParameter_l(const String8& keyValuePair,
9516 status_t& status)
9517{
9518 AudioParameter param = AudioParameter(keyValuePair);
9519 int value;
Eric Laurente6e9a482017-07-25 19:26:02 -07009520 bool sendToHal = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009521 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07009522 LOG_FATAL("Should not happen set routing device in MmapThread");
Eric Laurent6acd1d42017-01-04 14:23:29 -08009523 }
Eric Laurente6e9a482017-07-25 19:26:02 -07009524 if (sendToHal) {
9525 status = mHalStream->setParameters(keyValuePair);
9526 } else {
9527 status = NO_ERROR;
9528 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08009529
9530 return false;
9531}
9532
9533String8 AudioFlinger::MmapThread::getParameters(const String8& keys)
9534{
9535 Mutex::Autolock _l(mLock);
9536 String8 out_s8;
9537 if (initCheck() == NO_ERROR && mHalStream->getParameters(keys, &out_s8) == OK) {
9538 return out_s8;
9539 }
9540 return String8();
9541}
9542
Eric Laurent09f1ed22019-04-24 17:45:17 -07009543void AudioFlinger::MmapThread::ioConfigChanged(audio_io_config_event event, pid_t pid,
9544 audio_port_handle_t portId __unused) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08009545 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
9546
9547 desc->mIoHandle = mId;
9548
9549 switch (event) {
9550 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07009551 case AUDIO_INPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -08009552 case AUDIO_INPUT_CONFIG_CHANGED:
9553 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07009554 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -08009555 case AUDIO_OUTPUT_CONFIG_CHANGED:
9556 desc->mPatch = mPatch;
9557 desc->mChannelMask = mChannelMask;
9558 desc->mSamplingRate = mSampleRate;
9559 desc->mFormat = mFormat;
9560 desc->mFrameCount = mFrameCount;
9561 desc->mFrameCountHAL = mFrameCount;
9562 desc->mLatency = 0;
9563 break;
9564
9565 case AUDIO_INPUT_CLOSED:
9566 case AUDIO_OUTPUT_CLOSED:
9567 default:
9568 break;
9569 }
9570 mAudioFlinger->ioConfigChanged(event, desc, pid);
9571}
9572
9573status_t AudioFlinger::MmapThread::createAudioPatch_l(const struct audio_patch *patch,
9574 audio_patch_handle_t *handle)
9575{
9576 status_t status = NO_ERROR;
9577
9578 // store new device and send to effects
9579 audio_devices_t type = AUDIO_DEVICE_NONE;
9580 audio_port_handle_t deviceId;
jiabinc52b1ff2019-10-31 17:20:42 -07009581 AudioDeviceTypeAddrVector sinkDeviceTypeAddrs;
9582 AudioDeviceTypeAddr sourceDeviceTypeAddr;
9583 uint32_t numDevices = 0;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009584 if (isOutput()) {
9585 for (unsigned int i = 0; i < patch->num_sinks; i++) {
jiabinc52b1ff2019-10-31 17:20:42 -07009586 LOG_ALWAYS_FATAL_IF(popcount(patch->sinks[i].ext.device.type) > 1
9587 && !mAudioHwDev->supportsAudioPatches(),
9588 "Enumerated device type(%#x) must not be used "
9589 "as it does not support audio patches",
9590 patch->sinks[i].ext.device.type);
Mikhail Naganov55773032020-10-01 15:08:13 -07009591 type = static_cast<audio_devices_t>(type | patch->sinks[i].ext.device.type);
jiabinc52b1ff2019-10-31 17:20:42 -07009592 sinkDeviceTypeAddrs.push_back(AudioDeviceTypeAddr(patch->sinks[i].ext.device.type,
9593 patch->sinks[i].ext.device.address));
Eric Laurent6acd1d42017-01-04 14:23:29 -08009594 }
9595 deviceId = patch->sinks[0].id;
jiabinc52b1ff2019-10-31 17:20:42 -07009596 numDevices = mPatch.num_sinks;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009597 } else {
9598 type = patch->sources[0].ext.device.type;
9599 deviceId = patch->sources[0].id;
jiabinc52b1ff2019-10-31 17:20:42 -07009600 numDevices = mPatch.num_sources;
9601 sourceDeviceTypeAddr.mType = patch->sources[0].ext.device.type;
jiabin0a488932020-08-07 17:32:40 -07009602 sourceDeviceTypeAddr.setAddress(patch->sources[0].ext.device.address);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009603 }
9604
9605 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08009606 if (isOutput()) {
9607 mEffectChains[i]->setDevices_l(sinkDeviceTypeAddrs);
9608 } else {
9609 mEffectChains[i]->setInputDevice_l(sourceDeviceTypeAddr);
9610 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08009611 }
9612
jiabinc52b1ff2019-10-31 17:20:42 -07009613 if (!isOutput()) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08009614 // store new source and send to effects
9615 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
9616 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
9617 for (size_t i = 0; i < mEffectChains.size(); i++) {
9618 mEffectChains[i]->setAudioSource_l(mAudioSource);
9619 }
9620 }
9621 }
9622
9623 if (mAudioHwDev->supportsAudioPatches()) {
9624 status = mHalDevice->createAudioPatch(patch->num_sources,
9625 patch->sources,
9626 patch->num_sinks,
9627 patch->sinks,
9628 handle);
9629 } else {
9630 char *address;
9631 if (strcmp(patch->sinks[0].ext.device.address, "") != 0) {
9632 //FIXME: we only support address on first sink with HAL version < 3.0
9633 address = audio_device_address_to_parameter(
9634 patch->sinks[0].ext.device.type,
9635 patch->sinks[0].ext.device.address);
9636 } else {
9637 address = (char *)calloc(1, 1);
9638 }
9639 AudioParameter param = AudioParameter(String8(address));
9640 free(address);
9641 param.addInt(String8(AudioParameter::keyRouting), (int)type);
9642 if (!isOutput()) {
9643 param.addInt(String8(AudioParameter::keyInputSource),
9644 (int)patch->sinks[0].ext.mix.usecase.source);
9645 }
9646 status = mHalStream->setParameters(param.toString());
9647 *handle = AUDIO_PATCH_HANDLE_NONE;
9648 }
9649
jiabinc52b1ff2019-10-31 17:20:42 -07009650 if (numDevices == 0 || mDeviceId != deviceId) {
9651 if (isOutput()) {
9652 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
9653 mOutDeviceTypeAddrs = sinkDeviceTypeAddrs;
jiabin0a957d32020-04-29 10:56:20 -07009654 checkSilentMode_l();
jiabinc52b1ff2019-10-31 17:20:42 -07009655 } else {
9656 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
9657 mInDeviceTypeAddr = sourceDeviceTypeAddr;
9658 }
Phil Burk7f6b40d2017-02-09 13:18:38 -08009659 sp<MmapStreamCallback> callback = mCallback.promote();
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009660 if (mDeviceId != deviceId && callback != 0) {
Eric Laurent734046e2018-04-16 14:50:52 -07009661 mLock.unlock();
Phil Burk7f6b40d2017-02-09 13:18:38 -08009662 callback->onRoutingChanged(deviceId);
Eric Laurent734046e2018-04-16 14:50:52 -07009663 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009664 }
jiabinc52b1ff2019-10-31 17:20:42 -07009665 mPatch = *patch;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009666 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009667 }
9668 return status;
9669}
9670
9671status_t AudioFlinger::MmapThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
9672{
9673 status_t status = NO_ERROR;
9674
jiabinc52b1ff2019-10-31 17:20:42 -07009675 mPatch = audio_patch{};
9676 mOutDeviceTypeAddrs.clear();
9677 mInDeviceTypeAddr.reset();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009678
9679 bool supportsAudioPatches = mHalDevice->supportsAudioPatches(&supportsAudioPatches) == OK ?
9680 supportsAudioPatches : false;
9681
9682 if (supportsAudioPatches) {
9683 status = mHalDevice->releaseAudioPatch(handle);
9684 } else {
9685 AudioParameter param;
9686 param.addInt(String8(AudioParameter::keyRouting), 0);
9687 status = mHalStream->setParameters(param.toString());
9688 }
9689 return status;
9690}
9691
Mikhail Naganovdc769682018-05-04 15:34:08 -07009692void AudioFlinger::MmapThread::toAudioPortConfig(struct audio_port_config *config)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009693{
Mikhail Naganovdc769682018-05-04 15:34:08 -07009694 ThreadBase::toAudioPortConfig(config);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009695 if (isOutput()) {
9696 config->role = AUDIO_PORT_ROLE_SOURCE;
9697 config->ext.mix.hw_module = mAudioHwDev->handle();
9698 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
9699 } else {
9700 config->role = AUDIO_PORT_ROLE_SINK;
9701 config->ext.mix.hw_module = mAudioHwDev->handle();
9702 config->ext.mix.usecase.source = mAudioSource;
9703 }
9704}
9705
9706status_t AudioFlinger::MmapThread::addEffectChain_l(const sp<EffectChain>& chain)
9707{
9708 audio_session_t session = chain->sessionId();
9709
9710 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
9711 // Attach all tracks with same session ID to this chain.
9712 // indicate all active tracks in the chain
9713 for (const sp<MmapTrack> &track : mActiveTracks) {
9714 if (session == track->sessionId()) {
9715 chain->incTrackCnt();
9716 chain->incActiveTrackCnt();
9717 }
9718 }
9719
9720 chain->setThread(this);
9721 chain->setInBuffer(nullptr);
9722 chain->setOutBuffer(nullptr);
9723 chain->syncHalEffectsState();
9724
9725 mEffectChains.add(chain);
9726 checkSuspendOnAddEffectChain_l(chain);
9727 return NO_ERROR;
9728}
9729
9730size_t AudioFlinger::MmapThread::removeEffectChain_l(const sp<EffectChain>& chain)
9731{
9732 audio_session_t session = chain->sessionId();
9733
9734 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
9735
9736 for (size_t i = 0; i < mEffectChains.size(); i++) {
9737 if (chain == mEffectChains[i]) {
9738 mEffectChains.removeAt(i);
9739 // detach all active tracks from the chain
9740 // detach all tracks with same session ID from this chain
9741 for (const sp<MmapTrack> &track : mActiveTracks) {
9742 if (session == track->sessionId()) {
9743 chain->decActiveTrackCnt();
9744 chain->decTrackCnt();
9745 }
9746 }
9747 break;
9748 }
9749 }
9750 return mEffectChains.size();
9751}
9752
Eric Laurent6acd1d42017-01-04 14:23:29 -08009753void AudioFlinger::MmapThread::threadLoop_standby()
9754{
9755 mHalStream->standby();
9756}
9757
9758void AudioFlinger::MmapThread::threadLoop_exit()
9759{
Phil Burk7dce7282017-09-27 13:51:41 -07009760 // Do not call callback->onTearDown() because it is redundant for thread exit
9761 // and because it can cause a recursive mutex lock on stop().
Eric Laurent6acd1d42017-01-04 14:23:29 -08009762}
9763
9764status_t AudioFlinger::MmapThread::setSyncEvent(const sp<SyncEvent>& event __unused)
9765{
9766 return BAD_VALUE;
9767}
9768
9769bool AudioFlinger::MmapThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
9770{
9771 return false;
9772}
9773
9774status_t AudioFlinger::MmapThread::checkEffectCompatibility_l(
9775 const effect_descriptor_t *desc, audio_session_t sessionId)
9776{
9777 // No global effect sessions on mmap threads
Eric Laurent3f75a5b2019-11-12 15:55:51 -08009778 if (audio_is_global_session(sessionId)) {
9779 ALOGW("checkEffectCompatibility_l(): global effect %s on MMAP thread %s",
Eric Laurent6acd1d42017-01-04 14:23:29 -08009780 desc->name, mThreadName);
9781 return BAD_VALUE;
9782 }
9783
9784 if (!isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC)) {
9785 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on capture mmap thread",
9786 desc->name);
9787 return BAD_VALUE;
9788 }
9789 if (isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Glenn Kastend3bb6452016-12-05 18:14:37 -08009790 ALOGW("checkEffectCompatibility_l(): pre processing effect %s created on playback mmap "
9791 "thread", desc->name);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009792 return BAD_VALUE;
9793 }
9794
9795 // Only allow effects without processing load or latency
9796 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) != EFFECT_FLAG_NO_PROCESS) {
9797 return BAD_VALUE;
9798 }
9799
jiabineb3bda02020-06-30 14:07:03 -07009800 if (EffectModule::isHapticGenerator(&desc->type)) {
9801 ALOGE("%s(): HapticGenerator is not supported for MmapThread", __func__);
9802 return BAD_VALUE;
9803 }
9804
Eric Laurent6acd1d42017-01-04 14:23:29 -08009805 return NO_ERROR;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009806}
9807
9808void AudioFlinger::MmapThread::checkInvalidTracks_l()
9809{
9810 for (const sp<MmapTrack> &track : mActiveTracks) {
9811 if (track->isInvalid()) {
Phil Burk7f6b40d2017-02-09 13:18:38 -08009812 sp<MmapStreamCallback> callback = mCallback.promote();
9813 if (callback != 0) {
Eric Laurent734046e2018-04-16 14:50:52 -07009814 mLock.unlock();
Eric Laurent331679c2018-04-16 17:03:16 -07009815 callback->onTearDown(track->portId());
Eric Laurent734046e2018-04-16 14:50:52 -07009816 mLock.lock();
Eric Laurent331679c2018-04-16 17:03:16 -07009817 } else if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
9818 ALOGW("Could not notify MMAP stream tear down: no onTearDown callback!");
9819 mNoCallbackWarningCount++;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009820 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08009821 }
9822 }
9823}
9824
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07009825void AudioFlinger::MmapThread::dumpInternals_l(int fd, const Vector<String16>& args __unused)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009826{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009827 dprintf(fd, " Attributes: content type %d usage %d source %d\n",
9828 mAttr.content_type, mAttr.usage, mAttr.source);
9829 dprintf(fd, " Session: %d port Id: %d\n", mSessionId, mPortId);
Eric Tan39ec8d62018-07-24 09:49:29 -07009830 if (mActiveTracks.isEmpty()) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08009831 dprintf(fd, " No active clients\n");
9832 }
9833}
9834
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07009835void AudioFlinger::MmapThread::dumpTracks_l(int fd, const Vector<String16>& args __unused)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009836{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009837 String8 result;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009838 size_t numtracks = mActiveTracks.size();
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009839 dprintf(fd, " %zu Tracks\n", numtracks);
9840 const char *prefix = " ";
Eric Laurent6acd1d42017-01-04 14:23:29 -08009841 if (numtracks) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009842 result.append(prefix);
Kevin Rocard5f2136e2018-05-11 22:03:00 -07009843 mActiveTracks[0]->appendDumpHeader(result);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009844 for (size_t i = 0; i < numtracks ; ++i) {
9845 sp<MmapTrack> track = mActiveTracks[i];
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009846 result.append(prefix);
9847 track->appendDump(result, true /* active */);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009848 }
9849 } else {
9850 dprintf(fd, "\n");
9851 }
9852 write(fd, result.string(), result.size());
9853}
9854
9855AudioFlinger::MmapPlaybackThread::MmapPlaybackThread(
9856 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
jiabinc52b1ff2019-10-31 17:20:42 -07009857 AudioHwDevice *hwDev, AudioStreamOut *output, bool systemReady)
Andy Hungcf10d742020-04-28 15:38:24 -07009858 : MmapThread(audioFlinger, id, hwDev, output->stream, systemReady, true /* isOut */),
Eric Laurent6acd1d42017-01-04 14:23:29 -08009859 mStreamType(AUDIO_STREAM_MUSIC),
Phil Burk56ecf3e2018-03-12 15:38:17 -07009860 mStreamVolume(1.0),
9861 mStreamMute(false),
Phil Burk56ecf3e2018-03-12 15:38:17 -07009862 mOutput(output)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009863{
9864 snprintf(mThreadName, kThreadNameLength, "AudioMmapOut_%X", id);
9865 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
9866 mMasterVolume = audioFlinger->masterVolume_l();
9867 mMasterMute = audioFlinger->masterMute_l();
9868 if (mAudioHwDev) {
9869 if (mAudioHwDev->canSetMasterVolume()) {
9870 mMasterVolume = 1.0;
9871 }
9872
9873 if (mAudioHwDev->canSetMasterMute()) {
9874 mMasterMute = false;
9875 }
9876 }
9877}
9878
9879void AudioFlinger::MmapPlaybackThread::configure(const audio_attributes_t *attr,
9880 audio_stream_type_t streamType,
9881 audio_session_t sessionId,
9882 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009883 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -08009884 audio_port_handle_t portId)
9885{
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009886 MmapThread::configure(attr, streamType, sessionId, callback, deviceId, portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009887 mStreamType = streamType;
9888}
9889
9890AudioStreamOut* AudioFlinger::MmapPlaybackThread::clearOutput()
9891{
9892 Mutex::Autolock _l(mLock);
9893 AudioStreamOut *output = mOutput;
9894 mOutput = NULL;
9895 return output;
9896}
9897
9898void AudioFlinger::MmapPlaybackThread::setMasterVolume(float value)
9899{
9900 Mutex::Autolock _l(mLock);
9901 // Don't apply master volume in SW if our HAL can do it for us.
9902 if (mAudioHwDev &&
9903 mAudioHwDev->canSetMasterVolume()) {
9904 mMasterVolume = 1.0;
9905 } else {
9906 mMasterVolume = value;
9907 }
9908}
9909
9910void AudioFlinger::MmapPlaybackThread::setMasterMute(bool muted)
9911{
9912 Mutex::Autolock _l(mLock);
9913 // Don't apply master mute in SW if our HAL can do it for us.
9914 if (mAudioHwDev && mAudioHwDev->canSetMasterMute()) {
9915 mMasterMute = false;
9916 } else {
9917 mMasterMute = muted;
9918 }
9919}
9920
9921void AudioFlinger::MmapPlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
9922{
9923 Mutex::Autolock _l(mLock);
9924 if (stream == mStreamType) {
9925 mStreamVolume = value;
9926 broadcast_l();
9927 }
9928}
9929
9930float AudioFlinger::MmapPlaybackThread::streamVolume(audio_stream_type_t stream) const
9931{
9932 Mutex::Autolock _l(mLock);
9933 if (stream == mStreamType) {
9934 return mStreamVolume;
9935 }
9936 return 0.0f;
9937}
9938
9939void AudioFlinger::MmapPlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
9940{
9941 Mutex::Autolock _l(mLock);
9942 if (stream == mStreamType) {
9943 mStreamMute= muted;
9944 broadcast_l();
9945 }
9946}
9947
9948void AudioFlinger::MmapPlaybackThread::invalidateTracks(audio_stream_type_t streamType)
9949{
9950 Mutex::Autolock _l(mLock);
9951 if (streamType == mStreamType) {
9952 for (const sp<MmapTrack> &track : mActiveTracks) {
9953 track->invalidate();
9954 }
9955 broadcast_l();
9956 }
9957}
9958
9959void AudioFlinger::MmapPlaybackThread::processVolume_l()
9960{
9961 float volume;
9962
9963 if (mMasterMute || mStreamMute) {
9964 volume = 0;
9965 } else {
9966 volume = mMasterVolume * mStreamVolume;
9967 }
9968
9969 if (volume != mHalVolFloat) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08009970
9971 // Convert volumes from float to 8.24
9972 uint32_t vol = (uint32_t)(volume * (1 << 24));
9973
9974 // Delegate volume control to effect in track effect chain if needed
9975 // only one effect chain can be present on DirectOutputThread, so if
9976 // there is one, the track is connected to it
9977 if (!mEffectChains.isEmpty()) {
9978 mEffectChains[0]->setVolume_l(&vol, &vol);
9979 volume = (float)vol / (1 << 24);
9980 }
Eric Laurentdff774a2017-04-21 15:29:38 -07009981 // Try to use HW volume control and fall back to SW control if not implemented
Phil Burk56ecf3e2018-03-12 15:38:17 -07009982 if (mOutput->stream->setVolume(volume, volume) == NO_ERROR) {
9983 mHalVolFloat = volume; // HW volume control worked, so update value.
9984 mNoCallbackWarningCount = 0;
9985 } else {
Eric Laurentdff774a2017-04-21 15:29:38 -07009986 sp<MmapStreamCallback> callback = mCallback.promote();
9987 if (callback != 0) {
9988 int channelCount;
9989 if (isOutput()) {
9990 channelCount = audio_channel_count_from_out_mask(mChannelMask);
9991 } else {
9992 channelCount = audio_channel_count_from_in_mask(mChannelMask);
9993 }
9994 Vector<float> values;
9995 for (int i = 0; i < channelCount; i++) {
9996 values.add(volume);
9997 }
Phil Burk56ecf3e2018-03-12 15:38:17 -07009998 mHalVolFloat = volume; // SW volume control worked, so update value.
9999 mNoCallbackWarningCount = 0;
Eric Laurent734046e2018-04-16 14:50:52 -070010000 mLock.unlock();
10001 callback->onVolumeChanged(mChannelMask, values);
10002 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010003 } else {
Phil Burk56ecf3e2018-03-12 15:38:17 -070010004 if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
10005 ALOGW("Could not set MMAP stream volume: no volume callback!");
10006 mNoCallbackWarningCount++;
10007 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010008 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010009 }
Jasmine Chaeaa10e42021-05-11 10:11:14 +080010010 for (const sp<MmapTrack> &track : mActiveTracks) {
10011 track->setMetadataHasChanged();
10012 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010013 }
10014}
10015
Kevin Rocard069c2712018-03-29 19:09:14 -070010016void AudioFlinger::MmapPlaybackThread::updateMetadata_l()
10017{
Jasmine Chaeaa10e42021-05-11 10:11:14 +080010018 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
10019 return; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -070010020 }
10021 StreamOutHalInterface::SourceMetadata metadata;
10022 for (const sp<MmapTrack> &track : mActiveTracks) {
10023 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurent94579172020-11-20 18:41:04 +010010024 playback_track_metadata_v7_t trackMetadata;
10025 trackMetadata.base = {
Kevin Rocard069c2712018-03-29 19:09:14 -070010026 .usage = track->attributes().usage,
10027 .content_type = track->attributes().content_type,
10028 .gain = mHalVolFloat, // TODO: propagate from aaudio pre-mix volume
Eric Laurent94579172020-11-20 18:41:04 +010010029 };
10030 trackMetadata.channel_mask = track->channelMask(),
10031 strncpy(trackMetadata.tags, track->attributes().tags, AUDIO_ATTRIBUTES_TAGS_MAX_SIZE);
10032 metadata.tracks.push_back(trackMetadata);
Kevin Rocard069c2712018-03-29 19:09:14 -070010033 }
10034 mOutput->stream->updateSourceMetadata(metadata);
10035}
10036
Eric Laurent6acd1d42017-01-04 14:23:29 -080010037void AudioFlinger::MmapPlaybackThread::checkSilentMode_l()
10038{
10039 if (!mMasterMute) {
10040 char value[PROPERTY_VALUE_MAX];
10041 if (property_get("ro.audio.silent", value, "0") > 0) {
10042 char *endptr;
10043 unsigned long ul = strtoul(value, &endptr, 0);
10044 if (*endptr == '\0' && ul != 0) {
10045 ALOGD("Silence is golden");
10046 // The setprop command will not allow a property to be changed after
10047 // the first time it is set, so we don't have to worry about un-muting.
10048 setMasterMute_l(true);
10049 }
10050 }
10051 }
10052}
10053
Mikhail Naganov32abc2b2018-05-24 12:57:11 -070010054void AudioFlinger::MmapPlaybackThread::toAudioPortConfig(struct audio_port_config *config)
10055{
10056 MmapThread::toAudioPortConfig(config);
10057 if (mOutput && mOutput->flags != AUDIO_OUTPUT_FLAG_NONE) {
10058 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
10059 config->flags.output = mOutput->flags;
10060 }
10061}
10062
jiabinb7d8c5a2020-08-26 17:24:52 -070010063status_t AudioFlinger::MmapPlaybackThread::getExternalPosition(uint64_t *position,
10064 int64_t *timeNanos)
10065{
10066 if (mOutput == nullptr) {
10067 return NO_INIT;
10068 }
10069 struct timespec timestamp;
10070 status_t status = mOutput->getPresentationPosition(position, &timestamp);
10071 if (status == NO_ERROR) {
10072 *timeNanos = timestamp.tv_sec * NANOS_PER_SECOND + timestamp.tv_nsec;
10073 }
10074 return status;
10075}
10076
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -070010077void AudioFlinger::MmapPlaybackThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010078{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -070010079 MmapThread::dumpInternals_l(fd, args);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010080
Glenn Kastend3bb6452016-12-05 18:14:37 -080010081 dprintf(fd, " Stream type: %d Stream volume: %f HAL volume: %f Stream mute %d\n",
10082 mStreamType, mStreamVolume, mHalVolFloat, mStreamMute);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010083 dprintf(fd, " Master volume: %f Master mute %d\n", mMasterVolume, mMasterMute);
10084}
10085
10086AudioFlinger::MmapCaptureThread::MmapCaptureThread(
10087 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
jiabinc52b1ff2019-10-31 17:20:42 -070010088 AudioHwDevice *hwDev, AudioStreamIn *input, bool systemReady)
Andy Hungcf10d742020-04-28 15:38:24 -070010089 : MmapThread(audioFlinger, id, hwDev, input->stream, systemReady, false /* isOut */),
Eric Laurent6acd1d42017-01-04 14:23:29 -080010090 mInput(input)
10091{
10092 snprintf(mThreadName, kThreadNameLength, "AudioMmapIn_%X", id);
10093 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
10094}
10095
Eric Laurent331679c2018-04-16 17:03:16 -070010096status_t AudioFlinger::MmapCaptureThread::exitStandby()
10097{
Phil Burkf054fc32018-12-06 09:45:59 -080010098 {
10099 // mInput might have been cleared by clearInput()
10100 Mutex::Autolock _l(mLock);
10101 if (mInput != nullptr && mInput->stream != nullptr) {
10102 mInput->stream->setGain(1.0f);
10103 }
10104 }
Eric Laurent331679c2018-04-16 17:03:16 -070010105 return MmapThread::exitStandby();
10106}
10107
Eric Laurent6acd1d42017-01-04 14:23:29 -080010108AudioFlinger::AudioStreamIn* AudioFlinger::MmapCaptureThread::clearInput()
10109{
10110 Mutex::Autolock _l(mLock);
10111 AudioStreamIn *input = mInput;
10112 mInput = NULL;
10113 return input;
10114}
Kevin Rocard069c2712018-03-29 19:09:14 -070010115
Eric Laurent331679c2018-04-16 17:03:16 -070010116
10117void AudioFlinger::MmapCaptureThread::processVolume_l()
10118{
10119 bool changed = false;
10120 bool silenced = false;
10121
10122 sp<MmapStreamCallback> callback = mCallback.promote();
10123 if (callback == 0) {
10124 if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
10125 ALOGW("Could not set MMAP stream silenced: no onStreamSilenced callback!");
10126 mNoCallbackWarningCount++;
10127 }
10128 }
10129
10130 // After a change occurred in track silenced state, mute capture in audio DSP if at least one
10131 // track is silenced and unmute otherwise
10132 for (size_t i = 0; i < mActiveTracks.size() && !silenced; i++) {
10133 if (!mActiveTracks[i]->getAndSetSilencedNotified_l()) {
10134 changed = true;
10135 silenced = mActiveTracks[i]->isSilenced_l();
10136 }
10137 }
10138
10139 if (changed) {
10140 mInput->stream->setGain(silenced ? 0.0f: 1.0f);
10141 }
10142}
10143
Kevin Rocard069c2712018-03-29 19:09:14 -070010144void AudioFlinger::MmapCaptureThread::updateMetadata_l()
10145{
Jasmine Chaeaa10e42021-05-11 10:11:14 +080010146 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
10147 return; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -070010148 }
10149 StreamInHalInterface::SinkMetadata metadata;
10150 for (const sp<MmapTrack> &track : mActiveTracks) {
10151 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurent94579172020-11-20 18:41:04 +010010152 record_track_metadata_v7_t trackMetadata;
10153 trackMetadata.base = {
Kevin Rocard069c2712018-03-29 19:09:14 -070010154 .source = track->attributes().source,
10155 .gain = 1, // capture tracks do not have volumes
Eric Laurent94579172020-11-20 18:41:04 +010010156 };
10157 trackMetadata.channel_mask = track->channelMask(),
10158 strncpy(trackMetadata.tags, track->attributes().tags, AUDIO_ATTRIBUTES_TAGS_MAX_SIZE);
10159 metadata.tracks.push_back(trackMetadata);
Kevin Rocard069c2712018-03-29 19:09:14 -070010160 }
10161 mInput->stream->updateSinkMetadata(metadata);
10162}
10163
Eric Laurent5ada82e2019-08-29 17:53:54 -070010164void AudioFlinger::MmapCaptureThread::setRecordSilenced(audio_port_handle_t portId, bool silenced)
Eric Laurent331679c2018-04-16 17:03:16 -070010165{
10166 Mutex::Autolock _l(mLock);
10167 for (size_t i = 0; i < mActiveTracks.size() ; i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -070010168 if (mActiveTracks[i]->portId() == portId) {
Eric Laurent331679c2018-04-16 17:03:16 -070010169 mActiveTracks[i]->setSilenced_l(silenced);
10170 broadcast_l();
10171 }
10172 }
10173}
10174
Mikhail Naganov32abc2b2018-05-24 12:57:11 -070010175void AudioFlinger::MmapCaptureThread::toAudioPortConfig(struct audio_port_config *config)
10176{
10177 MmapThread::toAudioPortConfig(config);
10178 if (mInput && mInput->flags != AUDIO_INPUT_FLAG_NONE) {
10179 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
10180 config->flags.input = mInput->flags;
10181 }
10182}
10183
jiabinb7d8c5a2020-08-26 17:24:52 -070010184status_t AudioFlinger::MmapCaptureThread::getExternalPosition(
10185 uint64_t *position, int64_t *timeNanos)
10186{
10187 if (mInput == nullptr) {
10188 return NO_INIT;
10189 }
10190 return mInput->getCapturePosition((int64_t*)position, timeNanos);
10191}
10192
Glenn Kasten63238ef2015-03-02 15:50:29 -080010193} // namespace android