blob: 51f3032e0935b7d212cf132d824cb36be2119007 [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;
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700121using media::permission::Identity;
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, ");
818 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY) s.append("low freq, ");
819 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, ");
831 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, " );
Mikhail Naganovc9948492018-05-10 17:25:28 -0700833 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, " );
jiabin245cdd92018-12-07 17:55:15 -0800835 if (mask & AUDIO_CHANNEL_OUT_HAPTIC_B) s.append("haptic-B, " );
836 if (mask & AUDIO_CHANNEL_OUT_HAPTIC_A) s.append("haptic-A, " );
Andy Hungf98ec8d2015-05-19 12:53:24 -0700837 if (mask & ~AUDIO_CHANNEL_OUT_ALL) s.append("unknown, ");
838 } else {
839 if (mask & AUDIO_CHANNEL_IN_LEFT) s.append("left, ");
840 if (mask & AUDIO_CHANNEL_IN_RIGHT) s.append("right, ");
841 if (mask & AUDIO_CHANNEL_IN_FRONT) s.append("front, ");
842 if (mask & AUDIO_CHANNEL_IN_BACK) s.append("back, ");
843 if (mask & AUDIO_CHANNEL_IN_LEFT_PROCESSED) s.append("left-processed, ");
844 if (mask & AUDIO_CHANNEL_IN_RIGHT_PROCESSED) s.append("right-processed, ");
845 if (mask & AUDIO_CHANNEL_IN_FRONT_PROCESSED) s.append("front-processed, ");
846 if (mask & AUDIO_CHANNEL_IN_BACK_PROCESSED) s.append("back-processed, ");
847 if (mask & AUDIO_CHANNEL_IN_PRESSURE) s.append("pressure, ");
848 if (mask & AUDIO_CHANNEL_IN_X_AXIS) s.append("X, ");
849 if (mask & AUDIO_CHANNEL_IN_Y_AXIS) s.append("Y, ");
850 if (mask & AUDIO_CHANNEL_IN_Z_AXIS) s.append("Z, ");
Mikhail Naganovc9948492018-05-10 17:25:28 -0700851 if (mask & AUDIO_CHANNEL_IN_BACK_LEFT) s.append("back-left, ");
852 if (mask & AUDIO_CHANNEL_IN_BACK_RIGHT) s.append("back-right, ");
853 if (mask & AUDIO_CHANNEL_IN_CENTER) s.append("center, ");
854 if (mask & AUDIO_CHANNEL_IN_LOW_FREQUENCY) s.append("low freq, ");
855 if (mask & AUDIO_CHANNEL_IN_TOP_LEFT) s.append("top-left, " );
856 if (mask & AUDIO_CHANNEL_IN_TOP_RIGHT) s.append("top-right, " );
Andy Hungf98ec8d2015-05-19 12:53:24 -0700857 if (mask & AUDIO_CHANNEL_IN_VOICE_UPLINK) s.append("voice-uplink, ");
858 if (mask & AUDIO_CHANNEL_IN_VOICE_DNLINK) s.append("voice-dnlink, ");
859 if (mask & ~AUDIO_CHANNEL_IN_ALL) s.append("unknown, ");
860 }
861 const int len = s.length();
862 if (len > 2) {
Glenn Kasten57c4e6f2016-03-18 14:54:07 -0700863 (void) s.lockBuffer(len); // needed?
Andy Hungf98ec8d2015-05-19 12:53:24 -0700864 s.unlockBuffer(len - 2); // remove trailing ", "
865 }
866 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -0800867 }
Andy Hungf98ec8d2015-05-19 12:53:24 -0700868 case AUDIO_CHANNEL_REPRESENTATION_INDEX:
869 s.appendFormat("index mask, bits:%#x", audio_channel_mask_get_bits(mask));
870 return s;
871 default:
872 s.appendFormat("unknown mask, representation:%d bits:%#x",
873 representation, audio_channel_mask_get_bits(mask));
874 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -0800875 }
Marco Nelissenb2208842014-02-07 14:00:50 -0800876}
877
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -0700878void AudioFlinger::ThreadBase::dump(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -0800879{
Glenn Kasten1bfe09a2017-02-21 13:05:56 -0800880 dprintf(fd, "\n%s thread %p, name %s, tid %d, type %d (%s):\n", isOutput() ? "Output" : "Input",
881 this, mThreadName, getTid(), type(), threadTypeToString(type()));
882
Eric Laurent81784c32012-11-19 14:55:58 -0800883 bool locked = AudioFlinger::dumpTryLock(mLock);
884 if (!locked) {
Glenn Kasten1bfe09a2017-02-21 13:05:56 -0800885 dprintf(fd, " Thread may be deadlocked\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800886 }
887
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -0700888 dumpBase_l(fd, args);
889 dumpInternals_l(fd, args);
890 dumpTracks_l(fd, args);
891 dumpEffectChains_l(fd, args);
892
893 if (locked) {
894 mLock.unlock();
895 }
896
897 dprintf(fd, " Local log:\n");
898 mLocalLog.dump(fd, " " /* prefix */, 40 /* lines */);
899}
900
901void AudioFlinger::ThreadBase::dumpBase_l(int fd, const Vector<String16>& args __unused)
902{
Elliott Hughes87cebad2014-05-22 10:14:43 -0700903 dprintf(fd, " I/O handle: %d\n", mId);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700904 dprintf(fd, " Standby: %s\n", mStandby ? "yes" : "no");
Glenn Kasten97b7b752014-09-28 13:04:24 -0700905 dprintf(fd, " Sample rate: %u Hz\n", mSampleRate);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700906 dprintf(fd, " HAL frame count: %zu\n", mFrameCount);
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700907 dprintf(fd, " HAL format: 0x%x (%s)\n", mHALFormat, formatToString(mHALFormat).c_str());
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700908 dprintf(fd, " HAL buffer size: %zu bytes\n", mBufferSize);
Glenn Kasten97b7b752014-09-28 13:04:24 -0700909 dprintf(fd, " Channel count: %u\n", mChannelCount);
910 dprintf(fd, " Channel mask: 0x%08x (%s)\n", mChannelMask,
Marco Nelissenb2208842014-02-07 14:00:50 -0800911 channelMaskToString(mChannelMask, mType != RECORD).string());
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700912 dprintf(fd, " Processing format: 0x%x (%s)\n", mFormat, formatToString(mFormat).c_str());
Glenn Kastenf87c2f52015-08-21 08:03:57 -0700913 dprintf(fd, " Processing frame size: %zu bytes\n", mFrameSize);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700914 dprintf(fd, " Pending config events:");
Marco Nelissenb2208842014-02-07 14:00:50 -0800915 size_t numConfig = mConfigEvents.size();
916 if (numConfig) {
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -0700917 const size_t SIZE = 256;
918 char buffer[SIZE];
Marco Nelissenb2208842014-02-07 14:00:50 -0800919 for (size_t i = 0; i < numConfig; i++) {
920 mConfigEvents[i]->dump(buffer, SIZE);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700921 dprintf(fd, "\n %s", buffer);
Marco Nelissenb2208842014-02-07 14:00:50 -0800922 }
Elliott Hughes87cebad2014-05-22 10:14:43 -0700923 dprintf(fd, "\n");
Marco Nelissenb2208842014-02-07 14:00:50 -0800924 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -0700925 dprintf(fd, " none\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800926 }
Andy Hung293558a2017-03-21 12:19:20 -0700927 // Note: output device may be used by capture threads for effects such as AEC.
jiabinc52b1ff2019-10-31 17:20:42 -0700928 dprintf(fd, " Output devices: %s (%s)\n",
929 dumpDeviceTypes(outDeviceTypes()).c_str(), toString(outDeviceTypes()).c_str());
930 dprintf(fd, " Input device: %#x (%s)\n",
931 inDeviceType(), toString(inDeviceType()).c_str());
Andy Hung9b181952019-02-25 14:53:36 -0800932 dprintf(fd, " Audio source: %d (%s)\n", mAudioSource, toString(mAudioSource).c_str());
Eric Laurent81784c32012-11-19 14:55:58 -0800933
Andy Hung2e2c0bb2018-06-11 19:13:11 -0700934 // Dump timestamp statistics for the Thread types that support it.
935 if (mType == RECORD
936 || mType == MIXER
937 || mType == DUPLICATING
Andy Hungf3234512018-07-03 14:51:47 -0700938 || mType == DIRECT
939 || mType == OFFLOAD) {
Andy Hung2e2c0bb2018-06-11 19:13:11 -0700940 dprintf(fd, " Timestamp stats: %s\n", mTimestampVerifier.toString().c_str());
Andy Hungc8fddf32018-08-08 18:32:37 -0700941 dprintf(fd, " Timestamp corrected: %s\n", isTimestampCorrectionEnabled() ? "yes" : "no");
Andy Hung2e2c0bb2018-06-11 19:13:11 -0700942 }
943
Andy Hung446f4df2019-02-21 12:26:41 -0800944 if (mLastIoBeginNs > 0) { // MMAP may not set this
945 dprintf(fd, " Last %s occurred (msecs): %lld\n",
946 isOutput() ? "write" : "read",
947 (long long) (systemTime() - mLastIoBeginNs) / NANOS_PER_MILLISECOND);
948 }
949
950 if (mProcessTimeMs.getN() > 0) {
951 dprintf(fd, " Process time ms stats: %s\n", mProcessTimeMs.toString().c_str());
952 }
953
954 if (mIoJitterMs.getN() > 0) {
955 dprintf(fd, " Hal %s jitter ms stats: %s\n",
956 isOutput() ? "write" : "read",
957 mIoJitterMs.toString().c_str());
958 }
959
Andy Hunge6c37112019-02-26 17:38:10 -0800960 if (mLatencyMs.getN() > 0) {
961 dprintf(fd, " Threadloop %s latency stats: %s\n",
962 isOutput() ? "write" : "read",
963 mLatencyMs.toString().c_str());
964 }
Eric Laurent81784c32012-11-19 14:55:58 -0800965}
966
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -0700967void AudioFlinger::ThreadBase::dumpEffectChains_l(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -0800968{
969 const size_t SIZE = 256;
970 char buffer[SIZE];
Eric Laurent81784c32012-11-19 14:55:58 -0800971
Marco Nelissenb2208842014-02-07 14:00:50 -0800972 size_t numEffectChains = mEffectChains.size();
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +0000973 snprintf(buffer, SIZE, " %zu Effect Chains\n", numEffectChains);
Eric Laurent81784c32012-11-19 14:55:58 -0800974 write(fd, buffer, strlen(buffer));
975
Marco Nelissenb2208842014-02-07 14:00:50 -0800976 for (size_t i = 0; i < numEffectChains; ++i) {
Eric Laurent81784c32012-11-19 14:55:58 -0800977 sp<EffectChain> chain = mEffectChains[i];
978 if (chain != 0) {
979 chain->dump(fd, args);
980 }
981 }
982}
983
Andy Hungdae27702016-10-31 14:01:16 -0700984void AudioFlinger::ThreadBase::acquireWakeLock()
Eric Laurent81784c32012-11-19 14:55:58 -0800985{
986 Mutex::Autolock _l(mLock);
Andy Hungdae27702016-10-31 14:01:16 -0700987 acquireWakeLock_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800988}
989
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100990String16 AudioFlinger::ThreadBase::getWakeLockTag()
991{
992 switch (mType) {
Glenn Kastenbcb14862015-03-05 17:11:21 -0800993 case MIXER:
994 return String16("AudioMix");
995 case DIRECT:
996 return String16("AudioDirectOut");
997 case DUPLICATING:
998 return String16("AudioDup");
999 case RECORD:
1000 return String16("AudioIn");
1001 case OFFLOAD:
1002 return String16("AudioOffload");
Andy Hungea840382020-05-05 21:50:17 -07001003 case MMAP_PLAYBACK:
1004 return String16("MmapPlayback");
1005 case MMAP_CAPTURE:
1006 return String16("MmapCapture");
Glenn Kastenbcb14862015-03-05 17:11:21 -08001007 default:
1008 ALOG_ASSERT(false);
1009 return String16("AudioUnknown");
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001010 }
1011}
1012
Andy Hungdae27702016-10-31 14:01:16 -07001013void AudioFlinger::ThreadBase::acquireWakeLock_l()
Eric Laurent81784c32012-11-19 14:55:58 -08001014{
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001015 getPowerManager_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001016 if (mPowerManager != 0) {
1017 sp<IBinder> binder = new BBinder();
Andy Hungdae27702016-10-31 14:01:16 -07001018 // Uses AID_AUDIOSERVER for wakelock. updateWakeLockUids_l() updates with client uids.
Chris Ye6597d732020-02-28 22:38:25 -08001019 binder::Status status = mPowerManager->acquireWakeLockAsync(binder,
1020 POWERMANAGER_PARTIAL_WAKE_LOCK,
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001021 getWakeLockTag(),
Marco Nelissendcb346b2015-09-09 10:47:29 -07001022 String16("audioserver"),
Chris Ye6597d732020-02-28 22:38:25 -08001023 {} /* workSource */,
1024 {} /* historyTag */);
1025 if (status.isOk()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001026 mWakeLockToken = binder;
1027 }
Chris Ye6597d732020-02-28 22:38:25 -08001028 ALOGV("acquireWakeLock_l() %s status %d", mThreadName, status.exceptionCode());
Eric Laurent81784c32012-11-19 14:55:58 -08001029 }
Wei Jia3f273d12015-11-24 09:06:49 -08001030
Andy Hung3f0c9022016-01-15 17:49:46 -08001031 gBoottime.acquire(mWakeLockToken);
Andy Hung818e7a32016-02-16 18:08:07 -08001032 mTimestamp.mTimebaseOffset[ExtendedTimestamp::TIMEBASE_BOOTTIME] =
1033 gBoottime.getBoottimeOffset();
Eric Laurent81784c32012-11-19 14:55:58 -08001034}
1035
1036void AudioFlinger::ThreadBase::releaseWakeLock()
1037{
1038 Mutex::Autolock _l(mLock);
1039 releaseWakeLock_l();
1040}
1041
1042void AudioFlinger::ThreadBase::releaseWakeLock_l()
1043{
Andy Hung3f0c9022016-01-15 17:49:46 -08001044 gBoottime.release(mWakeLockToken);
Eric Laurent81784c32012-11-19 14:55:58 -08001045 if (mWakeLockToken != 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -08001046 ALOGV("releaseWakeLock_l() %s", mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08001047 if (mPowerManager != 0) {
Chris Ye6597d732020-02-28 22:38:25 -08001048 mPowerManager->releaseWakeLockAsync(mWakeLockToken, 0);
Eric Laurent81784c32012-11-19 14:55:58 -08001049 }
1050 mWakeLockToken.clear();
1051 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001052}
1053
1054void AudioFlinger::ThreadBase::getPowerManager_l() {
Eric Laurent72e3f392015-05-20 14:43:50 -07001055 if (mSystemReady && mPowerManager == 0) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001056 // use checkService() to avoid blocking if power service is not up yet
1057 sp<IBinder> binder =
1058 defaultServiceManager()->checkService(String16("power"));
1059 if (binder == 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -08001060 ALOGW("Thread %s cannot connect to the power manager service", mThreadName);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001061 } else {
Chris Ye6597d732020-02-28 22:38:25 -08001062 mPowerManager = interface_cast<os::IPowerManager>(binder);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001063 binder->linkToDeath(mDeathRecipient);
1064 }
1065 }
1066}
1067
Andy Hungd01b0f12016-11-07 16:10:30 -08001068void AudioFlinger::ThreadBase::updateWakeLockUids_l(const SortedVector<uid_t> &uids) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001069 getPowerManager_l();
Andy Hungdae27702016-10-31 14:01:16 -07001070
1071#if !LOG_NDEBUG
1072 std::stringstream s;
Andy Hungd01b0f12016-11-07 16:10:30 -08001073 for (uid_t uid : uids) {
Andy Hungdae27702016-10-31 14:01:16 -07001074 s << uid << " ";
1075 }
1076 ALOGD("updateWakeLockUids_l %s uids:%s", mThreadName, s.str().c_str());
1077#endif
1078
Andy Hung438e7572015-12-14 15:51:17 -08001079 if (mWakeLockToken == NULL) { // token may be NULL if AudioFlinger::systemReady() not called.
1080 if (mSystemReady) {
1081 ALOGE("no wake lock to update, but system ready!");
1082 } else {
1083 ALOGW("no wake lock to update, system not ready yet");
1084 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001085 return;
1086 }
1087 if (mPowerManager != 0) {
Andy Hung1f12a8a2016-11-07 16:10:30 -08001088 std::vector<int> uidsAsInt(uids.begin(), uids.end()); // powermanager expects uids as ints
Chris Ye6597d732020-02-28 22:38:25 -08001089 binder::Status status = mPowerManager->updateWakeLockUidsAsync(
1090 mWakeLockToken, uidsAsInt);
1091 ALOGV("updateWakeLockUids_l() %s status %d", mThreadName, status.exceptionCode());
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001092 }
1093}
1094
Eric Laurent81784c32012-11-19 14:55:58 -08001095void AudioFlinger::ThreadBase::clearPowerManager()
1096{
1097 Mutex::Autolock _l(mLock);
1098 releaseWakeLock_l();
1099 mPowerManager.clear();
1100}
1101
jiabinc52b1ff2019-10-31 17:20:42 -07001102void AudioFlinger::ThreadBase::updateOutDevices(
1103 const DeviceDescriptorBaseVector& outDevices __unused)
1104{
1105 ALOGE("%s should only be called in RecordThread", __func__);
1106}
1107
Eric Laurentec376dc2021-04-08 20:41:22 +02001108void AudioFlinger::ThreadBase::resizeInputBuffer_l(int32_t maxSharedAudioHistoryMs __unused)
1109{
1110 ALOGE("%s should only be called in RecordThread", __func__);
1111}
1112
Glenn Kasten0f11b512014-01-31 16:18:54 -08001113void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001114{
1115 sp<ThreadBase> thread = mThread.promote();
1116 if (thread != 0) {
1117 thread->clearPowerManager();
1118 }
1119 ALOGW("power manager service died !!!");
1120}
1121
Eric Laurent81784c32012-11-19 14:55:58 -08001122void AudioFlinger::ThreadBase::setEffectSuspended_l(
Glenn Kastend848eb42016-03-08 13:42:11 -08001123 const effect_uuid_t *type, bool suspend, audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001124{
1125 sp<EffectChain> chain = getEffectChain_l(sessionId);
1126 if (chain != 0) {
1127 if (type != NULL) {
1128 chain->setEffectSuspended_l(type, suspend);
1129 } else {
1130 chain->setEffectSuspendedAll_l(suspend);
1131 }
1132 }
1133
1134 updateSuspendedSessions_l(type, suspend, sessionId);
1135}
1136
1137void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1138{
1139 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
1140 if (index < 0) {
1141 return;
1142 }
1143
1144 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
1145 mSuspendedSessions.valueAt(index);
1146
1147 for (size_t i = 0; i < sessionEffects.size(); i++) {
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07001148 const sp<SuspendedSessionDesc>& desc = sessionEffects.valueAt(i);
Eric Laurent81784c32012-11-19 14:55:58 -08001149 for (int j = 0; j < desc->mRefCount; j++) {
1150 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1151 chain->setEffectSuspendedAll_l(true);
1152 } else {
1153 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
1154 desc->mType.timeLow);
1155 chain->setEffectSuspended_l(&desc->mType, true);
1156 }
1157 }
1158 }
1159}
1160
1161void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1162 bool suspend,
Glenn Kastend848eb42016-03-08 13:42:11 -08001163 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001164{
1165 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
1166
1167 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1168
1169 if (suspend) {
1170 if (index >= 0) {
1171 sessionEffects = mSuspendedSessions.valueAt(index);
1172 } else {
1173 mSuspendedSessions.add(sessionId, sessionEffects);
1174 }
1175 } else {
1176 if (index < 0) {
1177 return;
1178 }
1179 sessionEffects = mSuspendedSessions.valueAt(index);
1180 }
1181
1182
1183 int key = EffectChain::kKeyForSuspendAll;
1184 if (type != NULL) {
1185 key = type->timeLow;
1186 }
1187 index = sessionEffects.indexOfKey(key);
1188
1189 sp<SuspendedSessionDesc> desc;
1190 if (suspend) {
1191 if (index >= 0) {
1192 desc = sessionEffects.valueAt(index);
1193 } else {
1194 desc = new SuspendedSessionDesc();
1195 if (type != NULL) {
1196 desc->mType = *type;
1197 }
1198 sessionEffects.add(key, desc);
1199 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
1200 }
1201 desc->mRefCount++;
1202 } else {
1203 if (index < 0) {
1204 return;
1205 }
1206 desc = sessionEffects.valueAt(index);
1207 if (--desc->mRefCount == 0) {
1208 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
1209 sessionEffects.removeItemsAt(index);
1210 if (sessionEffects.isEmpty()) {
1211 ALOGV("updateSuspendedSessions_l() restore removing session %d",
1212 sessionId);
1213 mSuspendedSessions.removeItem(sessionId);
1214 }
1215 }
1216 }
1217 if (!sessionEffects.isEmpty()) {
1218 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1219 }
1220}
1221
Eric Laurent6b446ce2019-12-13 10:56:31 -08001222void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(bool enabled,
1223 audio_session_t sessionId,
1224 bool threadLocked) {
1225 if (!threadLocked) {
1226 mLock.lock();
1227 }
Eric Laurent81784c32012-11-19 14:55:58 -08001228
Eric Laurent81784c32012-11-19 14:55:58 -08001229 if (mType != RECORD) {
1230 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1231 // another session. This gives the priority to well behaved effect control panels
1232 // and applications not using global effects.
1233 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
1234 // global effects
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001235 if (!audio_is_global_session(sessionId)) {
Eric Laurent81784c32012-11-19 14:55:58 -08001236 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1237 }
1238 }
1239
Eric Laurent6b446ce2019-12-13 10:56:31 -08001240 if (!threadLocked) {
1241 mLock.unlock();
Eric Laurent81784c32012-11-19 14:55:58 -08001242 }
1243}
1244
Eric Laurent4c415062016-06-17 16:14:16 -07001245// checkEffectCompatibility_l() must be called with ThreadBase::mLock held
1246status_t AudioFlinger::RecordThread::checkEffectCompatibility_l(
1247 const effect_descriptor_t *desc, audio_session_t sessionId)
1248{
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001249 // No global output effect sessions on record threads
1250 if (sessionId == AUDIO_SESSION_OUTPUT_MIX
1251 || sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Eric Laurent4c415062016-06-17 16:14:16 -07001252 ALOGW("checkEffectCompatibility_l(): global effect %s on record thread %s",
1253 desc->name, mThreadName);
1254 return BAD_VALUE;
1255 }
1256 // only pre processing effects on record thread
1257 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC) {
1258 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on record thread %s",
1259 desc->name, mThreadName);
1260 return BAD_VALUE;
1261 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001262
1263 // always allow effects without processing load or latency
1264 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1265 return NO_ERROR;
1266 }
1267
Eric Laurent4c415062016-06-17 16:14:16 -07001268 audio_input_flags_t flags = mInput->flags;
1269 if (hasFastCapture() || (flags & AUDIO_INPUT_FLAG_FAST)) {
1270 if (flags & AUDIO_INPUT_FLAG_RAW) {
1271 ALOGW("checkEffectCompatibility_l(): effect %s on record thread %s in raw mode",
1272 desc->name, mThreadName);
1273 return BAD_VALUE;
1274 }
1275 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1276 ALOGW("checkEffectCompatibility_l(): non HW effect %s on record thread %s in fast mode",
1277 desc->name, mThreadName);
1278 return BAD_VALUE;
1279 }
1280 }
jiabineb3bda02020-06-30 14:07:03 -07001281
1282 if (EffectModule::isHapticGenerator(&desc->type)) {
1283 ALOGE("%s(): HapticGenerator is not supported in RecordThread", __func__);
1284 return BAD_VALUE;
1285 }
Eric Laurent4c415062016-06-17 16:14:16 -07001286 return NO_ERROR;
1287}
1288
1289// checkEffectCompatibility_l() must be called with ThreadBase::mLock held
1290status_t AudioFlinger::PlaybackThread::checkEffectCompatibility_l(
1291 const effect_descriptor_t *desc, audio_session_t sessionId)
1292{
1293 // no preprocessing on playback threads
1294 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC) {
1295 ALOGW("checkEffectCompatibility_l(): pre processing effect %s created on playback"
1296 " thread %s", desc->name, mThreadName);
1297 return BAD_VALUE;
1298 }
1299
Eric Laurent3e4de772017-07-16 16:55:08 -07001300 // always allow effects without processing load or latency
1301 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1302 return NO_ERROR;
1303 }
1304
jiabineb3bda02020-06-30 14:07:03 -07001305 if (EffectModule::isHapticGenerator(&desc->type) && mHapticChannelCount == 0) {
1306 ALOGW("%s: thread doesn't support haptic playback while the effect is HapticGenerator",
1307 __func__);
1308 return BAD_VALUE;
1309 }
1310
Eric Laurent4c415062016-06-17 16:14:16 -07001311 switch (mType) {
1312 case MIXER: {
Andy Hung9aad48c2017-11-29 10:29:19 -08001313#ifndef MULTICHANNEL_EFFECT_CHAIN
Eric Laurent4c415062016-06-17 16:14:16 -07001314 // Reject any effect on mixer multichannel sinks.
1315 // TODO: fix both format and multichannel issues with effects.
1316 if (mChannelCount != FCC_2) {
1317 ALOGW("checkEffectCompatibility_l(): effect %s for multichannel(%d) on MIXER"
1318 " thread %s", desc->name, mChannelCount, mThreadName);
1319 return BAD_VALUE;
1320 }
Andy Hung9aad48c2017-11-29 10:29:19 -08001321#endif
Eric Laurent4c415062016-06-17 16:14:16 -07001322 audio_output_flags_t flags = mOutput->flags;
1323 if (hasFastMixer() || (flags & AUDIO_OUTPUT_FLAG_FAST)) {
1324 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1325 // global effects are applied only to non fast tracks if they are SW
1326 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1327 break;
1328 }
1329 } else if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1330 // only post processing on output stage session
1331 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
1332 ALOGW("checkEffectCompatibility_l(): non post processing effect %s not allowed"
1333 " on output stage session", desc->name);
1334 return BAD_VALUE;
1335 }
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001336 } else if (sessionId == AUDIO_SESSION_DEVICE) {
1337 // only post processing on output stage session
1338 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
1339 ALOGW("checkEffectCompatibility_l(): non post processing effect %s not allowed"
1340 " on device session", desc->name);
1341 return BAD_VALUE;
1342 }
Eric Laurent4c415062016-06-17 16:14:16 -07001343 } else {
1344 // no restriction on effects applied on non fast tracks
1345 if ((hasAudioSession_l(sessionId) & ThreadBase::FAST_SESSION) == 0) {
1346 break;
1347 }
1348 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001349
Eric Laurent4c415062016-06-17 16:14:16 -07001350 if (flags & AUDIO_OUTPUT_FLAG_RAW) {
1351 ALOGW("checkEffectCompatibility_l(): effect %s on playback thread in raw mode",
1352 desc->name);
1353 return BAD_VALUE;
1354 }
1355 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1356 ALOGW("checkEffectCompatibility_l(): non HW effect %s on playback thread"
1357 " in fast mode", desc->name);
1358 return BAD_VALUE;
1359 }
1360 }
1361 } break;
1362 case OFFLOAD:
Jean-Michel Trivi773ee952016-07-11 16:53:18 -07001363 // nothing actionable on offload threads, if the effect:
1364 // - is offloadable: the effect can be created
1365 // - is NOT offloadable: the effect should still be created, but EffectHandle::enable()
1366 // will take care of invalidating the tracks of the thread
Eric Laurent4c415062016-06-17 16:14:16 -07001367 break;
1368 case DIRECT:
1369 // Reject any effect on Direct output threads for now, since the format of
1370 // mSinkBuffer is not guaranteed to be compatible with effect processing (PCM 16 stereo).
1371 ALOGW("checkEffectCompatibility_l(): effect %s on DIRECT output thread %s",
1372 desc->name, mThreadName);
1373 return BAD_VALUE;
1374 case DUPLICATING:
Andy Hung9aad48c2017-11-29 10:29:19 -08001375#ifndef MULTICHANNEL_EFFECT_CHAIN
Eric Laurent4c415062016-06-17 16:14:16 -07001376 // Reject any effect on mixer multichannel sinks.
1377 // TODO: fix both format and multichannel issues with effects.
1378 if (mChannelCount != FCC_2) {
1379 ALOGW("checkEffectCompatibility_l(): effect %s for multichannel(%d)"
1380 " on DUPLICATING thread %s", desc->name, mChannelCount, mThreadName);
1381 return BAD_VALUE;
1382 }
Andy Hung9aad48c2017-11-29 10:29:19 -08001383#endif
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001384 if (audio_is_global_session(sessionId)) {
Eric Laurent4c415062016-06-17 16:14:16 -07001385 ALOGW("checkEffectCompatibility_l(): global effect %s on DUPLICATING"
1386 " thread %s", desc->name, mThreadName);
1387 return BAD_VALUE;
1388 }
1389 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
1390 ALOGW("checkEffectCompatibility_l(): post processing effect %s on"
1391 " DUPLICATING thread %s", desc->name, mThreadName);
1392 return BAD_VALUE;
1393 }
1394 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) != 0) {
1395 ALOGW("checkEffectCompatibility_l(): HW tunneled effect %s on"
1396 " DUPLICATING thread %s", desc->name, mThreadName);
1397 return BAD_VALUE;
1398 }
1399 break;
1400 default:
1401 LOG_ALWAYS_FATAL("checkEffectCompatibility_l(): wrong thread type %d", mType);
1402 }
1403
1404 return NO_ERROR;
1405}
1406
Eric Laurent81784c32012-11-19 14:55:58 -08001407// ThreadBase::createEffect_l() must be called with AudioFlinger::mLock held
1408sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
1409 const sp<AudioFlinger::Client>& client,
1410 const sp<IEffectClient>& effectClient,
1411 int32_t priority,
Glenn Kastend848eb42016-03-08 13:42:11 -08001412 audio_session_t sessionId,
Eric Laurent81784c32012-11-19 14:55:58 -08001413 effect_descriptor_t *desc,
1414 int *enabled,
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001415 status_t *status,
Eric Laurent2fe0acd2020-03-13 14:30:46 -07001416 bool pinned,
1417 bool probe)
Eric Laurent81784c32012-11-19 14:55:58 -08001418{
1419 sp<EffectModule> effect;
1420 sp<EffectHandle> handle;
1421 status_t lStatus;
1422 sp<EffectChain> chain;
1423 bool chainCreated = false;
1424 bool effectCreated = false;
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001425 audio_unique_id_t effectId = AUDIO_UNIQUE_ID_USE_UNSPECIFIED;
Eric Laurent81784c32012-11-19 14:55:58 -08001426
1427 lStatus = initCheck();
1428 if (lStatus != NO_ERROR) {
1429 ALOGW("createEffect_l() Audio driver not initialized.");
1430 goto Exit;
1431 }
1432
Eric Laurent81784c32012-11-19 14:55:58 -08001433 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
1434
1435 { // scope for mLock
1436 Mutex::Autolock _l(mLock);
1437
Eric Laurent4c415062016-06-17 16:14:16 -07001438 lStatus = checkEffectCompatibility_l(desc, sessionId);
Eric Laurent2fe0acd2020-03-13 14:30:46 -07001439 if (probe || lStatus != NO_ERROR) {
Eric Laurent4c415062016-06-17 16:14:16 -07001440 goto Exit;
1441 }
1442
Eric Laurent81784c32012-11-19 14:55:58 -08001443 // check for existing effect chain with the requested audio session
1444 chain = getEffectChain_l(sessionId);
1445 if (chain == 0) {
1446 // create a new chain for this session
1447 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
1448 chain = new EffectChain(this, sessionId);
1449 addEffectChain_l(chain);
1450 chain->setStrategy(getStrategyForSession_l(sessionId));
1451 chainCreated = true;
1452 } else {
1453 effect = chain->getEffectFromDesc_l(desc);
1454 }
1455
1456 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
1457
1458 if (effect == 0) {
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001459 effectId = mAudioFlinger->nextUniqueId(AUDIO_UNIQUE_ID_USE_EFFECT);
Eric Laurent81784c32012-11-19 14:55:58 -08001460 // create a new effect module if none present in the chain
Eric Laurent6b446ce2019-12-13 10:56:31 -08001461 lStatus = chain->createEffect_l(effect, desc, effectId, sessionId, pinned);
Eric Laurent81784c32012-11-19 14:55:58 -08001462 if (lStatus != NO_ERROR) {
1463 goto Exit;
1464 }
1465 effectCreated = true;
1466
jiabinc52b1ff2019-10-31 17:20:42 -07001467 // FIXME: use vector of device and address when effect interface is ready.
jiabin8f278ee2019-11-11 12:16:27 -08001468 effect->setDevices(outDeviceTypeAddrs());
1469 effect->setInputDevice(inDeviceTypeAddr());
Eric Laurent81784c32012-11-19 14:55:58 -08001470 effect->setMode(mAudioFlinger->getMode());
1471 effect->setAudioSource(mAudioSource);
1472 }
jiabin1319f5a2021-03-30 22:21:24 +00001473 if (effect->isHapticGenerator()) {
1474 // TODO(b/184194057): Use the vibrator information from the vibrator that will be used
1475 // for the HapticGenerator.
1476 const media::AudioVibratorInfo* defaultVibratorInfo =
1477 mAudioFlinger->getDefaultVibratorInfo_l();
1478 if (defaultVibratorInfo != nullptr) {
1479 // Only set the vibrator info when it is a valid one.
1480 effect->setVibratorInfo(defaultVibratorInfo);
1481 }
1482 }
Eric Laurent81784c32012-11-19 14:55:58 -08001483 // create effect handle and connect it to effect module
1484 handle = new EffectHandle(effect, client, effectClient, priority);
Glenn Kastene75da402013-11-20 13:54:52 -08001485 lStatus = handle->initCheck();
1486 if (lStatus == OK) {
1487 lStatus = effect->addHandle(handle.get());
1488 }
Eric Laurent81784c32012-11-19 14:55:58 -08001489 if (enabled != NULL) {
1490 *enabled = (int)effect->isEnabled();
1491 }
1492 }
1493
1494Exit:
Eric Laurent2fe0acd2020-03-13 14:30:46 -07001495 if (!probe && lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurent81784c32012-11-19 14:55:58 -08001496 Mutex::Autolock _l(mLock);
1497 if (effectCreated) {
1498 chain->removeEffect_l(effect);
1499 }
Eric Laurent81784c32012-11-19 14:55:58 -08001500 if (chainCreated) {
1501 removeEffectChain_l(chain);
1502 }
haobo101735295ff7b0d2017-03-17 17:44:03 +08001503 // handle must be cleared by caller to avoid deadlock.
Eric Laurent81784c32012-11-19 14:55:58 -08001504 }
1505
Glenn Kasten9156ef32013-08-06 15:39:08 -07001506 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001507 return handle;
1508}
1509
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001510void AudioFlinger::ThreadBase::disconnectEffectHandle(EffectHandle *handle,
1511 bool unpinIfLast)
1512{
1513 bool remove = false;
1514 sp<EffectModule> effect;
1515 {
1516 Mutex::Autolock _l(mLock);
Eric Laurent41709552019-12-16 19:34:05 -08001517 sp<EffectBase> effectBase = handle->effect().promote();
1518 if (effectBase == nullptr) {
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001519 return;
1520 }
Eric Laurentb82e6b72019-11-22 17:25:04 -08001521 effect = effectBase->asEffectModule();
1522 if (effect == nullptr) {
1523 return;
1524 }
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001525 // restore suspended effects if the disconnected handle was enabled and the last one.
1526 remove = (effect->removeHandle(handle) == 0) && (!effect->isPinned() || unpinIfLast);
1527 if (remove) {
1528 removeEffect_l(effect, true);
1529 }
1530 }
1531 if (remove) {
1532 mAudioFlinger->updateOrphanEffectChains(effect);
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001533 if (handle->enabled()) {
Eric Laurent6b446ce2019-12-13 10:56:31 -08001534 effect->checkSuspendOnEffectEnabled(false, false /*threadLocked*/);
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001535 }
1536 }
1537}
1538
Eric Laurent6b446ce2019-12-13 10:56:31 -08001539void AudioFlinger::ThreadBase::onEffectEnable(const sp<EffectModule>& effect) {
Andy Hungea840382020-05-05 21:50:17 -07001540 if (isOffloadOrMmap()) {
Eric Laurent6b446ce2019-12-13 10:56:31 -08001541 Mutex::Autolock _l(mLock);
1542 broadcast_l();
1543 }
1544 if (!effect->isOffloadable()) {
1545 if (mType == ThreadBase::OFFLOAD) {
1546 PlaybackThread *t = (PlaybackThread *)this;
1547 t->invalidateTracks(AUDIO_STREAM_MUSIC);
1548 }
1549 if (effect->sessionId() == AUDIO_SESSION_OUTPUT_MIX) {
1550 mAudioFlinger->onNonOffloadableGlobalEffectEnable();
1551 }
1552 }
1553}
1554
1555void AudioFlinger::ThreadBase::onEffectDisable() {
Andy Hungea840382020-05-05 21:50:17 -07001556 if (isOffloadOrMmap()) {
Eric Laurent6b446ce2019-12-13 10:56:31 -08001557 Mutex::Autolock _l(mLock);
1558 broadcast_l();
1559 }
1560}
1561
Glenn Kastend848eb42016-03-08 13:42:11 -08001562sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(audio_session_t sessionId,
1563 int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08001564{
1565 Mutex::Autolock _l(mLock);
1566 return getEffect_l(sessionId, effectId);
1567}
1568
Glenn Kastend848eb42016-03-08 13:42:11 -08001569sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(audio_session_t sessionId,
1570 int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08001571{
1572 sp<EffectChain> chain = getEffectChain_l(sessionId);
1573 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
1574}
1575
Eric Laurent6c796322019-04-09 14:13:17 -07001576std::vector<int> AudioFlinger::ThreadBase::getEffectIds_l(audio_session_t sessionId)
1577{
1578 sp<EffectChain> chain = getEffectChain_l(sessionId);
1579 return chain != nullptr ? chain->getEffectIds() : std::vector<int>{};
1580}
1581
Eric Laurent81784c32012-11-19 14:55:58 -08001582// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
1583// PlaybackThread::mLock held
1584status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
1585{
1586 // check for existing effect chain with the requested audio session
Glenn Kastend848eb42016-03-08 13:42:11 -08001587 audio_session_t sessionId = effect->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08001588 sp<EffectChain> chain = getEffectChain_l(sessionId);
1589 bool chainCreated = false;
1590
Eric Laurent5baf2af2013-09-12 17:37:00 -07001591 ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(),
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001592 "addEffect_l() on offloaded thread %p: effect %s does not support offload flags %#x",
Eric Laurent5baf2af2013-09-12 17:37:00 -07001593 this, effect->desc().name, effect->desc().flags);
1594
Eric Laurent81784c32012-11-19 14:55:58 -08001595 if (chain == 0) {
1596 // create a new chain for this session
1597 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
1598 chain = new EffectChain(this, sessionId);
1599 addEffectChain_l(chain);
1600 chain->setStrategy(getStrategyForSession_l(sessionId));
1601 chainCreated = true;
1602 }
1603 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
1604
1605 if (chain->getEffectFromId_l(effect->id()) != 0) {
1606 ALOGW("addEffect_l() %p effect %s already present in chain %p",
1607 this, effect->desc().name, chain.get());
1608 return BAD_VALUE;
1609 }
1610
Eric Laurent5baf2af2013-09-12 17:37:00 -07001611 effect->setOffloaded(mType == OFFLOAD, mId);
1612
Eric Laurent81784c32012-11-19 14:55:58 -08001613 status_t status = chain->addEffect_l(effect);
1614 if (status != NO_ERROR) {
1615 if (chainCreated) {
1616 removeEffectChain_l(chain);
1617 }
1618 return status;
1619 }
1620
jiabin8f278ee2019-11-11 12:16:27 -08001621 effect->setDevices(outDeviceTypeAddrs());
1622 effect->setInputDevice(inDeviceTypeAddr());
Eric Laurent81784c32012-11-19 14:55:58 -08001623 effect->setMode(mAudioFlinger->getMode());
1624 effect->setAudioSource(mAudioSource);
Eric Laurentd8365c52017-07-16 15:27:05 -07001625
Eric Laurent81784c32012-11-19 14:55:58 -08001626 return NO_ERROR;
1627}
1628
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001629void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect, bool release) {
Eric Laurent81784c32012-11-19 14:55:58 -08001630
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001631 ALOGV("%s %p effect %p", __FUNCTION__, this, effect.get());
Eric Laurent81784c32012-11-19 14:55:58 -08001632 effect_descriptor_t desc = effect->desc();
1633 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
1634 detachAuxEffect_l(effect->id());
1635 }
1636
Eric Laurent6b446ce2019-12-13 10:56:31 -08001637 sp<EffectChain> chain = effect->callback()->chain().promote();
Eric Laurent81784c32012-11-19 14:55:58 -08001638 if (chain != 0) {
1639 // remove effect chain if removing last effect
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001640 if (chain->removeEffect_l(effect, release) == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08001641 removeEffectChain_l(chain);
1642 }
1643 } else {
1644 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
1645 }
1646}
1647
1648void AudioFlinger::ThreadBase::lockEffectChains_l(
1649 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1650{
1651 effectChains = mEffectChains;
1652 for (size_t i = 0; i < mEffectChains.size(); i++) {
1653 mEffectChains[i]->lock();
1654 }
1655}
1656
1657void AudioFlinger::ThreadBase::unlockEffectChains(
1658 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1659{
1660 for (size_t i = 0; i < effectChains.size(); i++) {
1661 effectChains[i]->unlock();
1662 }
1663}
1664
Glenn Kastend848eb42016-03-08 13:42:11 -08001665sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001666{
1667 Mutex::Autolock _l(mLock);
1668 return getEffectChain_l(sessionId);
1669}
1670
Glenn Kastend848eb42016-03-08 13:42:11 -08001671sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(audio_session_t sessionId)
1672 const
Eric Laurent81784c32012-11-19 14:55:58 -08001673{
1674 size_t size = mEffectChains.size();
1675 for (size_t i = 0; i < size; i++) {
1676 if (mEffectChains[i]->sessionId() == sessionId) {
1677 return mEffectChains[i];
1678 }
1679 }
1680 return 0;
1681}
1682
1683void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
1684{
1685 Mutex::Autolock _l(mLock);
1686 size_t size = mEffectChains.size();
1687 for (size_t i = 0; i < size; i++) {
1688 mEffectChains[i]->setMode_l(mode);
1689 }
1690}
1691
Mikhail Naganovdc769682018-05-04 15:34:08 -07001692void AudioFlinger::ThreadBase::toAudioPortConfig(struct audio_port_config *config)
Eric Laurent83b88082014-06-20 18:31:16 -07001693{
1694 config->type = AUDIO_PORT_TYPE_MIX;
1695 config->ext.mix.handle = mId;
1696 config->sample_rate = mSampleRate;
1697 config->format = mFormat;
1698 config->channel_mask = mChannelMask;
1699 config->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
1700 AUDIO_PORT_CONFIG_FORMAT;
1701}
1702
Eric Laurent72e3f392015-05-20 14:43:50 -07001703void AudioFlinger::ThreadBase::systemReady()
1704{
1705 Mutex::Autolock _l(mLock);
1706 if (mSystemReady) {
1707 return;
1708 }
1709 mSystemReady = true;
1710
1711 for (size_t i = 0; i < mPendingConfigEvents.size(); i++) {
1712 sendConfigEvent_l(mPendingConfigEvents.editItemAt(i));
1713 }
1714 mPendingConfigEvents.clear();
1715}
1716
Andy Hungdae27702016-10-31 14:01:16 -07001717template <typename T>
1718ssize_t AudioFlinger::ThreadBase::ActiveTracks<T>::add(const sp<T> &track) {
1719 ssize_t index = mActiveTracks.indexOf(track);
1720 if (index >= 0) {
1721 ALOGW("ActiveTracks<T>::add track %p already there", track.get());
1722 return index;
1723 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001724 logTrack("add", track);
Andy Hungdae27702016-10-31 14:01:16 -07001725 mActiveTracksGeneration++;
1726 mLatestActiveTrack = track;
1727 ++mBatteryCounter[track->uid()].second;
Kevin Rocard069c2712018-03-29 19:09:14 -07001728 mHasChanged = true;
Andy Hungdae27702016-10-31 14:01:16 -07001729 return mActiveTracks.add(track);
1730}
1731
1732template <typename T>
1733ssize_t AudioFlinger::ThreadBase::ActiveTracks<T>::remove(const sp<T> &track) {
1734 ssize_t index = mActiveTracks.remove(track);
1735 if (index < 0) {
1736 ALOGW("ActiveTracks<T>::remove nonexistent track %p", track.get());
1737 return index;
1738 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001739 logTrack("remove", track);
Andy Hungdae27702016-10-31 14:01:16 -07001740 mActiveTracksGeneration++;
1741 --mBatteryCounter[track->uid()].second;
1742 // mLatestActiveTrack is not cleared even if is the same as track.
Kevin Rocard069c2712018-03-29 19:09:14 -07001743 mHasChanged = true;
Andy Hung8946a282018-04-19 20:04:56 -07001744#ifdef TEE_SINK
1745 track->dumpTee(-1 /* fd */, "_REMOVE");
1746#endif
Andy Hungc2b11cb2020-04-22 09:04:01 -07001747 track->logEndInterval(); // log to MediaMetrics
Andy Hungdae27702016-10-31 14:01:16 -07001748 return index;
1749}
1750
1751template <typename T>
1752void AudioFlinger::ThreadBase::ActiveTracks<T>::clear() {
1753 for (const sp<T> &track : mActiveTracks) {
1754 BatteryNotifier::getInstance().noteStopAudio(track->uid());
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001755 logTrack("clear", track);
Andy Hungdae27702016-10-31 14:01:16 -07001756 }
1757 mLastActiveTracksGeneration = mActiveTracksGeneration;
Kevin Rocard069c2712018-03-29 19:09:14 -07001758 if (!mActiveTracks.empty()) { mHasChanged = true; }
Andy Hungdae27702016-10-31 14:01:16 -07001759 mActiveTracks.clear();
1760 mLatestActiveTrack.clear();
1761 mBatteryCounter.clear();
1762}
1763
1764template <typename T>
1765void AudioFlinger::ThreadBase::ActiveTracks<T>::updatePowerState(
1766 sp<ThreadBase> thread, bool force) {
1767 // Updates ActiveTracks client uids to the thread wakelock.
1768 if (mActiveTracksGeneration != mLastActiveTracksGeneration || force) {
1769 thread->updateWakeLockUids_l(getWakeLockUids());
1770 mLastActiveTracksGeneration = mActiveTracksGeneration;
1771 }
1772
1773 // Updates BatteryNotifier uids
1774 for (auto it = mBatteryCounter.begin(); it != mBatteryCounter.end();) {
1775 const uid_t uid = it->first;
1776 ssize_t &previous = it->second.first;
1777 ssize_t &current = it->second.second;
1778 if (current > 0) {
1779 if (previous == 0) {
1780 BatteryNotifier::getInstance().noteStartAudio(uid);
1781 }
1782 previous = current;
1783 ++it;
1784 } else if (current == 0) {
1785 if (previous > 0) {
1786 BatteryNotifier::getInstance().noteStopAudio(uid);
1787 }
1788 it = mBatteryCounter.erase(it); // std::map<> is stable on iterator erase.
1789 } else /* (current < 0) */ {
1790 LOG_ALWAYS_FATAL("negative battery count %zd", current);
1791 }
1792 }
1793}
Eric Laurent83b88082014-06-20 18:31:16 -07001794
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001795template <typename T>
Kevin Rocard069c2712018-03-29 19:09:14 -07001796bool AudioFlinger::ThreadBase::ActiveTracks<T>::readAndClearHasChanged() {
1797 const bool hasChanged = mHasChanged;
1798 mHasChanged = false;
1799 return hasChanged;
1800}
1801
1802template <typename T>
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001803void AudioFlinger::ThreadBase::ActiveTracks<T>::logTrack(
1804 const char *funcName, const sp<T> &track) const {
1805 if (mLocalLog != nullptr) {
1806 String8 result;
1807 track->appendDump(result, false /* active */);
1808 mLocalLog->log("AT::%-10s(%p) %s", funcName, track.get(), result.string());
1809 }
1810}
1811
Eric Laurent6acd1d42017-01-04 14:23:29 -08001812void AudioFlinger::ThreadBase::broadcast_l()
1813{
1814 // Thread could be blocked waiting for async
1815 // so signal it to handle state changes immediately
1816 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
1817 // be lost so we also flag to prevent it blocking on mWaitWorkCV
1818 mSignalPending = true;
1819 mWaitWorkCV.broadcast();
1820}
1821
Andy Hungd0979812019-02-21 15:51:44 -08001822// Call only from threadLoop() or when it is idle.
1823// Do not call from high performance code as this may do binder rpc to the MediaMetrics service.
1824void AudioFlinger::ThreadBase::sendStatistics(bool force)
1825{
1826 // Do not log if we have no stats.
1827 // We choose the timestamp verifier because it is the most likely item to be present.
1828 const int64_t nstats = mTimestampVerifier.getN() - mLastRecordedTimestampVerifierN;
1829 if (nstats == 0) {
1830 return;
1831 }
1832
1833 // Don't log more frequently than once per 12 hours.
1834 // We use BOOTTIME to include suspend time.
1835 const int64_t timeNs = systemTime(SYSTEM_TIME_BOOTTIME);
1836 const int64_t sinceNs = timeNs - mLastRecordedTimeNs; // ok if mLastRecordedTimeNs = 0
1837 if (!force && sinceNs <= 12 * NANOS_PER_HOUR) {
1838 return;
1839 }
1840
1841 mLastRecordedTimestampVerifierN = mTimestampVerifier.getN();
1842 mLastRecordedTimeNs = timeNs;
1843
Ray Essickf27e9872019-12-07 06:28:46 -08001844 std::unique_ptr<mediametrics::Item> item(mediametrics::Item::create("audiothread"));
Andy Hungd0979812019-02-21 15:51:44 -08001845
1846#define MM_PREFIX "android.media.audiothread." // avoid cut-n-paste errors.
1847
1848 // thread configuration
1849 item->setInt32(MM_PREFIX "id", (int32_t)mId); // IO handle
1850 // item->setInt32(MM_PREFIX "portId", (int32_t)mPortId);
1851 item->setCString(MM_PREFIX "type", threadTypeToString(mType));
1852 item->setInt32(MM_PREFIX "sampleRate", (int32_t)mSampleRate);
1853 item->setInt64(MM_PREFIX "channelMask", (int64_t)mChannelMask);
1854 item->setCString(MM_PREFIX "encoding", toString(mFormat).c_str());
1855 item->setInt32(MM_PREFIX "frameCount", (int32_t)mFrameCount);
jiabinc52b1ff2019-10-31 17:20:42 -07001856 item->setCString(MM_PREFIX "outDevice", toString(outDeviceTypes()).c_str());
1857 item->setCString(MM_PREFIX "inDevice", toString(inDeviceType()).c_str());
Andy Hungd0979812019-02-21 15:51:44 -08001858
1859 // thread statistics
1860 if (mIoJitterMs.getN() > 0) {
1861 item->setDouble(MM_PREFIX "ioJitterMs.mean", mIoJitterMs.getMean());
1862 item->setDouble(MM_PREFIX "ioJitterMs.std", mIoJitterMs.getStdDev());
1863 }
1864 if (mProcessTimeMs.getN() > 0) {
1865 item->setDouble(MM_PREFIX "processTimeMs.mean", mProcessTimeMs.getMean());
1866 item->setDouble(MM_PREFIX "processTimeMs.std", mProcessTimeMs.getStdDev());
1867 }
1868 const auto tsjitter = mTimestampVerifier.getJitterMs();
1869 if (tsjitter.getN() > 0) {
1870 item->setDouble(MM_PREFIX "timestampJitterMs.mean", tsjitter.getMean());
1871 item->setDouble(MM_PREFIX "timestampJitterMs.std", tsjitter.getStdDev());
1872 }
1873 if (mLatencyMs.getN() > 0) {
1874 item->setDouble(MM_PREFIX "latencyMs.mean", mLatencyMs.getMean());
1875 item->setDouble(MM_PREFIX "latencyMs.std", mLatencyMs.getStdDev());
1876 }
1877
1878 item->selfrecord();
1879}
1880
Eric Laurent81784c32012-11-19 14:55:58 -08001881// ----------------------------------------------------------------------------
1882// Playback
1883// ----------------------------------------------------------------------------
1884
1885AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1886 AudioStreamOut* output,
1887 audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -07001888 type_t type,
Eric Laurente93cc032016-05-05 10:15:10 -07001889 bool systemReady)
Andy Hungcf10d742020-04-28 15:38:24 -07001890 : ThreadBase(audioFlinger, id, type, systemReady, true /* isOut */),
Andy Hung2098f272014-02-27 14:00:06 -08001891 mNormalFrameCount(0), mSinkBuffer(NULL),
Andy Hung6146c082014-03-18 11:56:15 -07001892 mMixerBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung69aed5f2014-02-25 17:24:40 -08001893 mMixerBuffer(NULL),
1894 mMixerBufferSize(0),
1895 mMixerBufferFormat(AUDIO_FORMAT_INVALID),
1896 mMixerBufferValid(false),
Andy Hung6146c082014-03-18 11:56:15 -07001897 mEffectBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung98ef9782014-03-04 14:46:50 -08001898 mEffectBuffer(NULL),
1899 mEffectBufferSize(0),
1900 mEffectBufferFormat(AUDIO_FORMAT_INVALID),
1901 mEffectBufferValid(false),
Glenn Kastenc1fac192013-08-06 07:41:36 -07001902 mSuspended(0), mBytesWritten(0),
Andy Hungc54b1ff2016-02-23 14:07:07 -08001903 mFramesWritten(0),
Andy Hung238fa3d2016-07-28 10:53:22 -07001904 mSuspendedFrames(0),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001905 mActiveTracks(&this->mLocalLog),
Eric Laurent81784c32012-11-19 14:55:58 -08001906 // mStreamTypes[] initialized in constructor body
Andy Hung1bc088a2018-02-09 15:57:31 -08001907 mTracks(type == MIXER),
Eric Laurent81784c32012-11-19 14:55:58 -08001908 mOutput(output),
Andy Hung446f4df2019-02-21 12:26:41 -08001909 mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
Eric Laurent81784c32012-11-19 14:55:58 -08001910 mMixerStatus(MIXER_IDLE),
1911 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
Eric Laurentad9cb8b2015-05-26 16:38:19 -07001912 mStandbyDelayNs(AudioFlinger::mStandbyTimeInNsecs),
Eric Laurentbfb1b832013-01-07 09:53:42 -08001913 mBytesRemaining(0),
1914 mCurrentWriteLength(0),
1915 mUseAsyncWrite(false),
Eric Laurent3b4529e2013-09-05 18:09:19 -07001916 mWriteAckSequence(0),
1917 mDrainSequence(0),
Eric Laurent81784c32012-11-19 14:55:58 -08001918 mScreenState(AudioFlinger::mScreenState),
1919 // index 0 is reserved for normal mixer's submix
Glenn Kastendc2c50b2016-04-21 08:13:14 -07001920 mFastTrackAvailMask(((1 << FastMixerState::sMaxFastTracks) - 1) & ~1),
Eric Laurent7c29ec92017-09-20 17:54:22 -07001921 mHwSupportsPause(false), mHwPaused(false), mFlushPending(false),
Eric Laurent74c38dc2020-12-23 18:19:44 +01001922 mLeftVolFloat(-1.0), mRightVolFloat(-1.0),
1923 mDownStreamPatch{}
Eric Laurent81784c32012-11-19 14:55:58 -08001924{
Glenn Kastend7dca052015-03-05 16:05:54 -08001925 snprintf(mThreadName, kThreadNameLength, "AudioOut_%X", id);
1926 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08001927
1928 // Assumes constructor is called by AudioFlinger with it's mLock held, but
1929 // it would be safer to explicitly pass initial masterVolume/masterMute as
1930 // parameter.
1931 //
1932 // If the HAL we are using has support for master volume or master mute,
1933 // then do not attenuate or mute during mixing (just leave the volume at 1.0
1934 // and the mute set to false).
1935 mMasterVolume = audioFlinger->masterVolume_l();
1936 mMasterMute = audioFlinger->masterMute_l();
George Burgess IV5e4d86f2020-02-18 12:55:36 -08001937 if (mOutput->audioHwDev) {
Eric Laurent81784c32012-11-19 14:55:58 -08001938 if (mOutput->audioHwDev->canSetMasterVolume()) {
1939 mMasterVolume = 1.0;
1940 }
1941
1942 if (mOutput->audioHwDev->canSetMasterMute()) {
1943 mMasterMute = false;
1944 }
Andy Hungc8fddf32018-08-08 18:32:37 -07001945 mIsMsdDevice = strcmp(
1946 mOutput->audioHwDev->moduleName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0;
Eric Laurent81784c32012-11-19 14:55:58 -08001947 }
1948
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001949 readOutputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001950
Andy Hungc8fddf32018-08-08 18:32:37 -07001951 // TODO: We may also match on address as well as device type for
1952 // AUDIO_DEVICE_OUT_BUS, AUDIO_DEVICE_OUT_ALL_A2DP, AUDIO_DEVICE_OUT_REMOTE_SUBMIX
Dean Wheatleyf8726f02019-12-02 14:12:01 +11001953 if (type == MIXER || type == DIRECT || type == OFFLOAD) {
jiabinc52b1ff2019-10-31 17:20:42 -07001954 // TODO: This property should be ensure that only contains one single device type.
1955 mTimestampCorrectedDevice = (audio_devices_t)property_get_int64(
1956 "audio.timestamp.corrected_output_device",
Andy Hungc8fddf32018-08-08 18:32:37 -07001957 (int64_t)(mIsMsdDevice ? AUDIO_DEVICE_OUT_BUS // turn on by default for MSD
1958 : AUDIO_DEVICE_NONE));
1959 }
1960
Mikhail Naganovf33115d2020-09-25 23:03:05 +00001961 for (int i = AUDIO_STREAM_MIN; i < AUDIO_STREAM_FOR_POLICY_CNT; ++i) {
1962 const audio_stream_type_t stream{static_cast<audio_stream_type_t>(i)};
Eric Laurent98e38192018-02-15 18:31:53 -08001963 mStreamTypes[stream].volume = 0.0f;
Eric Laurent81784c32012-11-19 14:55:58 -08001964 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
1965 }
Eric Laurent35f8c7c2020-02-08 11:42:35 -08001966 // Audio patch and call assistant volume are always max
Eric Laurent98e38192018-02-15 18:31:53 -08001967 mStreamTypes[AUDIO_STREAM_PATCH].volume = 1.0f;
1968 mStreamTypes[AUDIO_STREAM_PATCH].mute = false;
Eric Laurent35f8c7c2020-02-08 11:42:35 -08001969 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].volume = 1.0f;
1970 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].mute = false;
Eric Laurent81784c32012-11-19 14:55:58 -08001971}
1972
1973AudioFlinger::PlaybackThread::~PlaybackThread()
1974{
Glenn Kasten9e58b552013-01-18 15:09:48 -08001975 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung010a1a12014-03-13 13:57:33 -07001976 free(mSinkBuffer);
Andy Hung69aed5f2014-02-25 17:24:40 -08001977 free(mMixerBuffer);
Andy Hung98ef9782014-03-04 14:46:50 -08001978 free(mEffectBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08001979}
1980
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001981// Thread virtuals
1982
1983void AudioFlinger::PlaybackThread::onFirstRef()
Eric Laurent81784c32012-11-19 14:55:58 -08001984{
jiabinf6eb4c32020-02-25 14:06:25 -08001985 if (mOutput == nullptr || mOutput->stream == nullptr) {
1986 ALOGE("The stream is not open yet"); // This should not happen.
1987 } else {
1988 // setEventCallback will need a strong pointer as a parameter. Calling it
1989 // here instead of constructor of PlaybackThread so that the onFirstRef
1990 // callback would not be made on an incompletely constructed object.
1991 if (mOutput->stream->setEventCallback(this) != OK) {
jiabinf1a36052020-08-19 14:33:31 -07001992 ALOGD("Failed to add event callback");
jiabinf6eb4c32020-02-25 14:06:25 -08001993 }
1994 }
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001995 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08001996}
1997
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001998// ThreadBase virtuals
1999void AudioFlinger::PlaybackThread::preExit()
2000{
2001 ALOGV(" preExit()");
2002 // FIXME this is using hard-coded strings but in the future, this functionality will be
2003 // converted to use audio HAL extensions required to support tunneling
2004 status_t result = mOutput->stream->setParameters(String8("exiting=1"));
2005 ALOGE_IF(result != OK, "Error when setting parameters on exit: %d", result);
2006}
2007
2008void AudioFlinger::PlaybackThread::dumpTracks_l(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08002009{
Eric Laurent81784c32012-11-19 14:55:58 -08002010 String8 result;
2011
Marco Nelissenb2208842014-02-07 14:00:50 -08002012 result.appendFormat(" Stream volumes in dB: ");
Eric Laurent81784c32012-11-19 14:55:58 -08002013 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
2014 const stream_type_t *st = &mStreamTypes[i];
2015 if (i > 0) {
2016 result.appendFormat(", ");
2017 }
2018 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
2019 if (st->mute) {
2020 result.append("M");
2021 }
2022 }
2023 result.append("\n");
2024 write(fd, result.string(), result.length());
2025 result.clear();
2026
Eric Laurent81784c32012-11-19 14:55:58 -08002027 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
2028 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
Elliott Hughes87cebad2014-05-22 10:14:43 -07002029 dprintf(fd, " Normal mixer raw underrun counters: partial=%u empty=%u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08002030 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Marco Nelissenb2208842014-02-07 14:00:50 -08002031
2032 size_t numtracks = mTracks.size();
2033 size_t numactive = mActiveTracks.size();
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002034 dprintf(fd, " %zu Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08002035 size_t numactiveseen = 0;
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002036 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08002037 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002038 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002039 result.append(prefix);
Andy Hungf6ab58d2018-05-25 12:50:39 -07002040 mTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08002041 for (size_t i = 0; i < numtracks; ++i) {
2042 sp<Track> track = mTracks[i];
2043 if (track != 0) {
2044 bool active = mActiveTracks.indexOf(track) >= 0;
2045 if (active) {
2046 numactiveseen++;
2047 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002048 result.append(prefix);
2049 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08002050 }
2051 }
2052 } else {
2053 result.append("\n");
2054 }
2055 if (numactiveseen != numactive) {
2056 // some tracks in the active list were not in the tracks list
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002057 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08002058 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002059 result.append(prefix);
Andy Hungf6ab58d2018-05-25 12:50:39 -07002060 mActiveTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08002061 for (size_t i = 0; i < numactive; ++i) {
Andy Hungdae27702016-10-31 14:01:16 -07002062 sp<Track> track = mActiveTracks[i];
2063 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002064 result.append(prefix);
2065 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08002066 }
2067 }
2068 }
2069
2070 write(fd, result.string(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08002071}
2072
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002073void AudioFlinger::PlaybackThread::dumpInternals_l(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08002074{
Andy Hung04cb8f72020-03-20 13:44:33 -07002075 dprintf(fd, " Master volume: %f\n", mMasterVolume);
Mikhail Naganovdfb411f2018-09-11 13:39:56 -07002076 dprintf(fd, " Master mute: %s\n", mMasterMute ? "on" : "off");
jiabin245cdd92018-12-07 17:55:15 -08002077 if (mHapticChannelMask != AUDIO_CHANNEL_NONE) {
2078 dprintf(fd, " Haptic channel mask: %#x (%s)\n", mHapticChannelMask,
2079 channelMaskToString(mHapticChannelMask, true /* output */).c_str());
2080 }
Elliott Hughes87cebad2014-05-22 10:14:43 -07002081 dprintf(fd, " Normal frame count: %zu\n", mNormalFrameCount);
Elliott Hughes87cebad2014-05-22 10:14:43 -07002082 dprintf(fd, " Total writes: %d\n", mNumWrites);
2083 dprintf(fd, " Delayed writes: %d\n", mNumDelayedWrites);
2084 dprintf(fd, " Blocked in write: %s\n", mInWrite ? "yes" : "no");
2085 dprintf(fd, " Suspend count: %d\n", mSuspended);
2086 dprintf(fd, " Sink buffer : %p\n", mSinkBuffer);
2087 dprintf(fd, " Mixer buffer: %p\n", mMixerBuffer);
2088 dprintf(fd, " Effect buffer: %p\n", mEffectBuffer);
2089 dprintf(fd, " Fast track availMask=%#x\n", mFastTrackAvailMask);
Eric Laurent42537be2016-01-08 17:16:42 -08002090 dprintf(fd, " Standby delay ns=%lld\n", (long long)mStandbyDelayNs);
Glenn Kasten97b7b752014-09-28 13:04:24 -07002091 AudioStreamOut *output = mOutput;
2092 audio_output_flags_t flags = output != NULL ? output->flags : AUDIO_OUTPUT_FLAG_NONE;
Mikhail Naganov913d06c2016-11-01 12:49:22 -07002093 dprintf(fd, " AudioStreamOut: %p flags %#x (%s)\n",
Andy Hung9b181952019-02-25 14:53:36 -08002094 output, flags, toString(flags).c_str());
Andy Hungb54c8542016-09-21 12:55:15 -07002095 dprintf(fd, " Frames written: %lld\n", (long long)mFramesWritten);
2096 dprintf(fd, " Suspended frames: %lld\n", (long long)mSuspendedFrames);
2097 if (mPipeSink.get() != nullptr) {
2098 dprintf(fd, " PipeSink frames written: %lld\n", (long long)mPipeSink->framesWritten());
2099 }
2100 if (output != nullptr) {
2101 dprintf(fd, " Hal stream dump:\n");
2102 (void)output->stream->dump(fd);
2103 }
Eric Laurent81784c32012-11-19 14:55:58 -08002104}
2105
Eric Laurent81784c32012-11-19 14:55:58 -08002106// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
2107sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
2108 const sp<AudioFlinger::Client>& client,
2109 audio_stream_type_t streamType,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07002110 const audio_attributes_t& attr,
Eric Laurent21da6472017-11-09 16:29:26 -08002111 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08002112 audio_format_t format,
2113 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08002114 size_t *pFrameCount,
Eric Laurent21da6472017-11-09 16:29:26 -08002115 size_t *pNotificationFrameCount,
2116 uint32_t notificationsPerBuffer,
2117 float speed,
Eric Laurent81784c32012-11-19 14:55:58 -08002118 const sp<IMemory>& sharedBuffer,
Glenn Kastend848eb42016-03-08 13:42:11 -08002119 audio_session_t sessionId,
Eric Laurent05067782016-06-01 18:27:28 -07002120 audio_output_flags_t *flags,
Eric Laurent09f1ed22019-04-24 17:45:17 -07002121 pid_t creatorPid,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07002122 const Identity& identity,
Eric Laurent81784c32012-11-19 14:55:58 -08002123 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002124 status_t *status,
jiabinf6eb4c32020-02-25 14:06:25 -08002125 audio_port_handle_t portId,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07002126 const sp<media::IAudioTrackCallback>& callback)
Eric Laurent81784c32012-11-19 14:55:58 -08002127{
Glenn Kasten74935e42013-12-19 08:56:45 -08002128 size_t frameCount = *pFrameCount;
Eric Laurent21da6472017-11-09 16:29:26 -08002129 size_t notificationFrameCount = *pNotificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08002130 sp<Track> track;
2131 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07002132 audio_output_flags_t outputFlags = mOutput->flags;
Eric Laurent21da6472017-11-09 16:29:26 -08002133 audio_output_flags_t requestedFlags = *flags;
Eric Laurent9b11c022018-06-06 19:19:22 -07002134 uint32_t sampleRate;
2135
2136 if (sharedBuffer != 0 && checkIMemory(sharedBuffer) != NO_ERROR) {
2137 lStatus = BAD_VALUE;
2138 goto Exit;
2139 }
Eric Laurent21da6472017-11-09 16:29:26 -08002140
2141 if (*pSampleRate == 0) {
2142 *pSampleRate = mSampleRate;
2143 }
Eric Laurent9b11c022018-06-06 19:19:22 -07002144 sampleRate = *pSampleRate;
Eric Laurent05067782016-06-01 18:27:28 -07002145
2146 // special case for FAST flag considered OK if fast mixer is present
2147 if (hasFastMixer()) {
2148 outputFlags = (audio_output_flags_t)(outputFlags | AUDIO_OUTPUT_FLAG_FAST);
2149 }
2150
2151 // Check if requested flags are compatible with output stream flags
2152 if ((*flags & outputFlags) != *flags) {
2153 ALOGW("createTrack_l(): mismatch between requested flags (%08x) and output flags (%08x)",
2154 *flags, outputFlags);
2155 *flags = (audio_output_flags_t)(*flags & outputFlags);
2156 }
Eric Laurent81784c32012-11-19 14:55:58 -08002157
Eric Laurent81784c32012-11-19 14:55:58 -08002158 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07002159 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
Eric Laurent81784c32012-11-19 14:55:58 -08002160 if (
Eric Laurent81784c32012-11-19 14:55:58 -08002161 // PCM data
2162 audio_is_linear_pcm(format) &&
Andy Hung1f439e12015-05-19 12:57:41 -07002163 // TODO: extract as a data library function that checks that a computationally
2164 // expensive downmixer is not required: isFastOutputChannelConversion()
jiabin245cdd92018-12-07 17:55:15 -08002165 (channelMask == (mChannelMask | mHapticChannelMask) ||
Andy Hung1f439e12015-05-19 12:57:41 -07002166 mChannelMask != AUDIO_CHANNEL_OUT_STEREO ||
2167 (channelMask == AUDIO_CHANNEL_OUT_MONO
2168 /* && mChannelMask == AUDIO_CHANNEL_OUT_STEREO */)) &&
Eric Laurent81784c32012-11-19 14:55:58 -08002169 // hardware sample rate
2170 (sampleRate == mSampleRate) &&
Eric Laurent81784c32012-11-19 14:55:58 -08002171 // normal mixer has an associated fast mixer
2172 hasFastMixer() &&
2173 // there are sufficient fast track slots available
2174 (mFastTrackAvailMask != 0)
2175 // FIXME test that MixerThread for this fast track has a capable output HAL
2176 // FIXME add a permission test also?
2177 ) {
Andy Hunge0a269a2016-03-23 15:13:42 -07002178 // static tracks can have any nonzero framecount, streaming tracks check against minimum.
2179 if (sharedBuffer == 0) {
Glenn Kasten03490092014-05-27 12:30:54 -07002180 // read the fast track multiplier property the first time it is needed
2181 int ok = pthread_once(&sFastTrackMultiplierOnce, sFastTrackMultiplierInit);
2182 if (ok != 0) {
2183 ALOGE("%s pthread_once failed: %d", __func__, ok);
2184 }
Andy Hunge0a269a2016-03-23 15:13:42 -07002185 frameCount = max(frameCount, mFrameCount * sFastTrackMultiplier); // incl framecount 0
Eric Laurent81784c32012-11-19 14:55:58 -08002186 }
Eric Laurent4c415062016-06-17 16:14:16 -07002187
2188 // check compatibility with audio effects.
2189 { // scope for mLock
2190 Mutex::Autolock _l(mLock);
Andy Hungd3bb0ad2016-10-11 17:16:43 -07002191 for (audio_session_t session : {
Eric Laurent3f75a5b2019-11-12 15:55:51 -08002192 AUDIO_SESSION_DEVICE,
Andy Hungd3bb0ad2016-10-11 17:16:43 -07002193 AUDIO_SESSION_OUTPUT_STAGE,
2194 AUDIO_SESSION_OUTPUT_MIX,
2195 sessionId,
2196 }) {
2197 sp<EffectChain> chain = getEffectChain_l(session);
2198 if (chain.get() != nullptr) {
2199 audio_output_flags_t old = *flags;
2200 chain->checkOutputFlagCompatibility(flags);
2201 if (old != *flags) {
2202 ALOGV("AUDIO_OUTPUT_FLAGS denied by effect, session=%d old=%#x new=%#x",
2203 (int)session, (int)old, (int)*flags);
2204 }
Eric Laurent4c415062016-06-17 16:14:16 -07002205 }
2206 }
2207 }
Eric Laurent122f7e72016-06-29 11:53:29 -07002208 ALOGV_IF((*flags & AUDIO_OUTPUT_FLAG_FAST) != 0,
Eric Laurent4c415062016-06-17 16:14:16 -07002209 "AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
2210 frameCount, mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08002211 } else {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002212 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: sharedBuffer=%p frameCount=%zu "
2213 "mFrameCount=%zu format=%#x mFormat=%#x isLinear=%d channelMask=%#x "
Andy Hung6146c082014-03-18 11:56:15 -07002214 "sampleRate=%u mSampleRate=%u "
Eric Laurent81784c32012-11-19 14:55:58 -08002215 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
Glenn Kastend79072e2016-01-06 08:41:20 -08002216 sharedBuffer.get(), frameCount, mFrameCount, format, mFormat,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07002217 audio_is_linear_pcm(format), channelMask, sampleRate,
2218 mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
Eric Laurent4c415062016-06-17 16:14:16 -07002219 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_FAST);
Andy Hung0e48d252015-01-26 11:43:15 -08002220 }
2221 }
Eric Laurent21da6472017-11-09 16:29:26 -08002222
2223 if (!audio_has_proportional_frames(format)) {
2224 if (sharedBuffer != 0) {
2225 // Same comment as below about ignoring frameCount parameter for set()
2226 frameCount = sharedBuffer->size();
2227 } else if (frameCount == 0) {
2228 frameCount = mNormalFrameCount;
2229 }
2230 if (notificationFrameCount != frameCount) {
2231 notificationFrameCount = frameCount;
2232 }
2233 } else if (sharedBuffer != 0) {
2234 // FIXME: Ensure client side memory buffers need
2235 // not have additional alignment beyond sample
2236 // (e.g. 16 bit stereo accessed as 32 bit frame).
2237 size_t alignment = audio_bytes_per_sample(format);
2238 if (alignment & 1) {
2239 // for AUDIO_FORMAT_PCM_24_BIT_PACKED (not exposed through Java).
2240 alignment = 1;
2241 }
2242 uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
2243 size_t frameSize = channelCount * audio_bytes_per_sample(format);
2244 if (channelCount > 1) {
2245 // More than 2 channels does not require stronger alignment than stereo
2246 alignment <<= 1;
2247 }
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07002248 if (((uintptr_t)sharedBuffer->unsecurePointer() & (alignment - 1)) != 0) {
Eric Laurent21da6472017-11-09 16:29:26 -08002249 ALOGE("Invalid buffer alignment: address %p, channel count %u",
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07002250 sharedBuffer->unsecurePointer(), channelCount);
Eric Laurent21da6472017-11-09 16:29:26 -08002251 lStatus = BAD_VALUE;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002252 goto Exit;
2253 }
Eric Laurent21da6472017-11-09 16:29:26 -08002254
2255 // When initializing a shared buffer AudioTrack via constructors,
2256 // there's no frameCount parameter.
2257 // But when initializing a shared buffer AudioTrack via set(),
2258 // there _is_ a frameCount parameter. We silently ignore it.
2259 frameCount = sharedBuffer->size() / frameSize;
2260 } else {
2261 size_t minFrameCount = 0;
2262 // For fast tracks we try to respect the application's request for notifications per buffer.
2263 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
2264 if (notificationsPerBuffer > 0) {
2265 // Avoid possible arithmetic overflow during multiplication.
2266 if (notificationsPerBuffer > SIZE_MAX / mFrameCount) {
2267 ALOGE("Requested notificationPerBuffer=%u ignored for HAL frameCount=%zu",
2268 notificationsPerBuffer, mFrameCount);
2269 } else {
2270 minFrameCount = mFrameCount * notificationsPerBuffer;
2271 }
2272 }
2273 } else {
2274 // For normal PCM streaming tracks, update minimum frame count.
2275 // Buffer depth is forced to be at least 2 x the normal mixer frame count and
2276 // cover audio hardware latency.
2277 // This is probably too conservative, but legacy application code may depend on it.
2278 // If you change this calculation, also review the start threshold which is related.
2279 uint32_t latencyMs = latency_l();
2280 if (latencyMs == 0) {
2281 ALOGE("Error when retrieving output stream latency");
2282 lStatus = UNKNOWN_ERROR;
2283 goto Exit;
2284 }
2285
2286 minFrameCount = AudioSystem::calculateMinFrameCount(latencyMs, mNormalFrameCount,
2287 mSampleRate, sampleRate, speed /*, 0 mNotificationsPerBufferReq*/);
2288
Eric Laurent81784c32012-11-19 14:55:58 -08002289 }
Eric Laurent21da6472017-11-09 16:29:26 -08002290 if (frameCount < minFrameCount) {
Eric Laurent81784c32012-11-19 14:55:58 -08002291 frameCount = minFrameCount;
2292 }
Eric Laurent81784c32012-11-19 14:55:58 -08002293 }
Eric Laurent21da6472017-11-09 16:29:26 -08002294
2295 // Make sure that application is notified with sufficient margin before underrun.
2296 // The client can divide the AudioTrack buffer into sub-buffers,
2297 // and expresses its desire to server as the notification frame count.
2298 if (sharedBuffer == 0 && audio_is_linear_pcm(format)) {
2299 size_t maxNotificationFrames;
2300 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
2301 // notify every HAL buffer, regardless of the size of the track buffer
2302 maxNotificationFrames = mFrameCount;
2303 } else {
Andy Hungfa117802019-04-12 13:50:39 -07002304 // Triple buffer the notification period for a triple buffered mixer period;
2305 // otherwise, double buffering for the notification period is fine.
2306 //
2307 // TODO: This should be moved to AudioTrack to modify the notification period
2308 // on AudioTrack::setBufferSizeInFrames() changes.
2309 const int nBuffering =
2310 (uint64_t{frameCount} * mSampleRate)
2311 / (uint64_t{mNormalFrameCount} * sampleRate) == 3 ? 3 : 2;
2312
Eric Laurent21da6472017-11-09 16:29:26 -08002313 maxNotificationFrames = frameCount / nBuffering;
2314 // If client requested a fast track but this was denied, then use the smaller maximum.
2315 if (requestedFlags & AUDIO_OUTPUT_FLAG_FAST) {
2316 size_t maxNotificationFramesFastDenied = FMS_20 * sampleRate / 1000;
2317 if (maxNotificationFrames > maxNotificationFramesFastDenied) {
2318 maxNotificationFrames = maxNotificationFramesFastDenied;
2319 }
2320 }
2321 }
2322 if (notificationFrameCount == 0 || notificationFrameCount > maxNotificationFrames) {
2323 if (notificationFrameCount == 0) {
2324 ALOGD("Client defaulted notificationFrames to %zu for frameCount %zu",
2325 maxNotificationFrames, frameCount);
2326 } else {
2327 ALOGW("Client adjusted notificationFrames from %zu to %zu for frameCount %zu",
2328 notificationFrameCount, maxNotificationFrames, frameCount);
2329 }
2330 notificationFrameCount = maxNotificationFrames;
2331 }
2332 }
2333
Glenn Kasten74935e42013-12-19 08:56:45 -08002334 *pFrameCount = frameCount;
Eric Laurent21da6472017-11-09 16:29:26 -08002335 *pNotificationFrameCount = notificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08002336
Glenn Kastenc3df8382014-03-13 15:05:25 -07002337 switch (mType) {
2338
2339 case DIRECT:
Phil Burkfdb3c072016-02-09 10:47:02 -08002340 if (audio_is_linear_pcm(format)) { // TODO maybe use audio_has_proportional_frames()?
Eric Laurent81784c32012-11-19 14:55:58 -08002341 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002342 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
2343 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08002344 sampleRate, format, channelMask, mOutput, mFormat);
2345 lStatus = BAD_VALUE;
2346 goto Exit;
2347 }
2348 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002349 break;
2350
2351 case OFFLOAD:
Eric Laurentbfb1b832013-01-07 09:53:42 -08002352 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002353 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
2354 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002355 sampleRate, format, channelMask, mOutput, mFormat);
2356 lStatus = BAD_VALUE;
2357 goto Exit;
2358 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002359 break;
2360
2361 default:
Glenn Kasten993fa062014-05-02 11:14:34 -07002362 if (!audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002363 ALOGE("createTrack_l() Bad parameter: format %#x \""
2364 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002365 format, mOutput, mFormat);
2366 lStatus = BAD_VALUE;
2367 goto Exit;
2368 }
Andy Hungcd044842014-08-07 11:04:34 -07002369 if (sampleRate > mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Eric Laurent81784c32012-11-19 14:55:58 -08002370 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
2371 lStatus = BAD_VALUE;
2372 goto Exit;
2373 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002374 break;
2375
Eric Laurent81784c32012-11-19 14:55:58 -08002376 }
2377
2378 lStatus = initCheck();
2379 if (lStatus != NO_ERROR) {
Glenn Kasten15e57982013-09-24 11:52:37 -07002380 ALOGE("createTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08002381 goto Exit;
2382 }
2383
2384 { // scope for mLock
2385 Mutex::Autolock _l(mLock);
2386
2387 // all tracks in same audio session must share the same routing strategy otherwise
2388 // conflicts will happen when tracks are moved from one output to another by audio policy
2389 // manager
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08002390 product_strategy_t strategy = AudioSystem::getStrategyForStream(streamType);
Eric Laurent81784c32012-11-19 14:55:58 -08002391 for (size_t i = 0; i < mTracks.size(); ++i) {
2392 sp<Track> t = mTracks[i];
Eric Laurent83b88082014-06-20 18:31:16 -07002393 if (t != 0 && t->isExternalTrack()) {
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08002394 product_strategy_t actual = AudioSystem::getStrategyForStream(t->streamType());
Eric Laurent81784c32012-11-19 14:55:58 -08002395 if (sessionId == t->sessionId() && strategy != actual) {
2396 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
2397 strategy, actual);
2398 lStatus = BAD_VALUE;
2399 goto Exit;
2400 }
2401 }
2402 }
2403
yucliuc9c49cd2020-07-13 16:25:21 -07002404 // Set DIRECT flag if current thread is DirectOutputThread. This can
2405 // happen when the playback is rerouted to direct output thread by
2406 // dynamic audio policy.
2407 // Do NOT report the flag changes back to client, since the client
2408 // doesn't explicitly request a direct flag.
2409 audio_output_flags_t trackFlags = *flags;
2410 if (mType == DIRECT) {
2411 trackFlags = static_cast<audio_output_flags_t>(trackFlags | AUDIO_OUTPUT_FLAG_DIRECT);
2412 }
2413
Kevin Rocard1f564ac2018-03-29 13:53:10 -07002414 track = new Track(this, client, streamType, attr, sampleRate, format,
Andy Hung8fe68032017-06-05 16:17:51 -07002415 channelMask, frameCount,
2416 nullptr /* buffer */, (size_t)0 /* bufferSize */, sharedBuffer,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07002417 sessionId, creatorPid, identity, trackFlags, TrackBase::TYPE_DEFAULT,
2418 portId, SIZE_MAX /*frameCountToBeReady*/);
Glenn Kasten03003332013-08-06 15:40:54 -07002419
Glenn Kasten03003332013-08-06 15:40:54 -07002420 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
2421 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08002422 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08002423 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08002424 goto Exit;
2425 }
2426 mTracks.add(track);
jiabinf6eb4c32020-02-25 14:06:25 -08002427 {
2428 Mutex::Autolock _atCbL(mAudioTrackCbLock);
2429 if (callback.get() != nullptr) {
jiabin18a4b1c2020-09-17 11:40:42 -07002430 mAudioTrackCallbacks.emplace(track, callback);
jiabinf6eb4c32020-02-25 14:06:25 -08002431 }
2432 }
Eric Laurent81784c32012-11-19 14:55:58 -08002433
2434 sp<EffectChain> chain = getEffectChain_l(sessionId);
2435 if (chain != 0) {
2436 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
2437 track->setMainBuffer(chain->inBuffer());
2438 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
2439 chain->incTrackCnt();
2440 }
2441
Eric Laurent05067782016-06-01 18:27:28 -07002442 if ((*flags & AUDIO_OUTPUT_FLAG_FAST) && (tid != -1)) {
Eric Laurent81784c32012-11-19 14:55:58 -08002443 pid_t callingPid = IPCThreadState::self()->getCallingPid();
2444 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
2445 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07002446 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08002447 }
2448 }
2449
2450 lStatus = NO_ERROR;
2451
2452Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07002453 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08002454 return track;
2455}
2456
Andy Hung1bc088a2018-02-09 15:57:31 -08002457template<typename T>
Andy Hung1bc088a2018-02-09 15:57:31 -08002458ssize_t AudioFlinger::PlaybackThread::Tracks<T>::remove(const sp<T> &track)
2459{
Andy Hungc0691382018-09-12 18:01:57 -07002460 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08002461 const ssize_t index = mTracks.remove(track);
2462 if (index >= 0) {
Andy Hungc0691382018-09-12 18:01:57 -07002463 if (mSaveDeletedTrackIds) {
Andy Hung1bc088a2018-02-09 15:57:31 -08002464 // We can't directly access mAudioMixer since the caller may be outside of threadLoop.
Andy Hungc0691382018-09-12 18:01:57 -07002465 // Instead, we add to mDeletedTrackIds which is solely used for mAudioMixer update,
Andy Hung1bc088a2018-02-09 15:57:31 -08002466 // to be handled when MixerThread::prepareTracks_l() next changes mAudioMixer.
Andy Hungc0691382018-09-12 18:01:57 -07002467 mDeletedTrackIds.emplace(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08002468 }
Andy Hung1bc088a2018-02-09 15:57:31 -08002469 }
2470 return index;
2471}
2472
Eric Laurent81784c32012-11-19 14:55:58 -08002473uint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const
2474{
2475 return latency;
2476}
2477
2478uint32_t AudioFlinger::PlaybackThread::latency() const
2479{
2480 Mutex::Autolock _l(mLock);
2481 return latency_l();
2482}
2483uint32_t AudioFlinger::PlaybackThread::latency_l() const
2484{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002485 uint32_t latency;
2486 if (initCheck() == NO_ERROR && mOutput->stream->getLatency(&latency) == OK) {
2487 return correctLatency_l(latency);
Eric Laurent81784c32012-11-19 14:55:58 -08002488 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002489 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002490}
2491
2492void AudioFlinger::PlaybackThread::setMasterVolume(float value)
2493{
2494 Mutex::Autolock _l(mLock);
2495 // Don't apply master volume in SW if our HAL can do it for us.
2496 if (mOutput && mOutput->audioHwDev &&
2497 mOutput->audioHwDev->canSetMasterVolume()) {
2498 mMasterVolume = 1.0;
2499 } else {
2500 mMasterVolume = value;
2501 }
2502}
2503
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01002504void AudioFlinger::PlaybackThread::setMasterBalance(float balance)
2505{
2506 mMasterBalance.store(balance);
2507}
2508
Eric Laurent81784c32012-11-19 14:55:58 -08002509void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
2510{
Eric Laurent6acd1d42017-01-04 14:23:29 -08002511 if (isDuplicating()) {
2512 return;
2513 }
Eric Laurent81784c32012-11-19 14:55:58 -08002514 Mutex::Autolock _l(mLock);
2515 // Don't apply master mute in SW if our HAL can do it for us.
2516 if (mOutput && mOutput->audioHwDev &&
2517 mOutput->audioHwDev->canSetMasterMute()) {
2518 mMasterMute = false;
2519 } else {
2520 mMasterMute = muted;
2521 }
2522}
2523
2524void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
2525{
2526 Mutex::Autolock _l(mLock);
2527 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002528 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002529}
2530
2531void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
2532{
2533 Mutex::Autolock _l(mLock);
2534 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002535 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002536}
2537
2538float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
2539{
2540 Mutex::Autolock _l(mLock);
2541 return mStreamTypes[stream].volume;
2542}
2543
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09002544void AudioFlinger::PlaybackThread::setVolumeForOutput_l(float left, float right) const
2545{
2546 mOutput->stream->setVolume(left, right);
2547}
2548
Eric Laurent81784c32012-11-19 14:55:58 -08002549// addTrack_l() must be called with ThreadBase::mLock held
2550status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
2551{
2552 status_t status = ALREADY_EXISTS;
2553
Eric Laurent81784c32012-11-19 14:55:58 -08002554 if (mActiveTracks.indexOf(track) < 0) {
2555 // the track is newly added, make sure it fills up all its
2556 // buffers before playing. This is to ensure the client will
2557 // effectively get the latency it requested.
Eric Laurent83b88082014-06-20 18:31:16 -07002558 if (track->isExternalTrack()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002559 TrackBase::track_state state = track->mState;
2560 mLock.unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002561 status = AudioSystem::startOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002562 mLock.lock();
2563 // abort track was stopped/paused while we released the lock
2564 if (state != track->mState) {
2565 if (status == NO_ERROR) {
2566 mLock.unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002567 AudioSystem::stopOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002568 mLock.lock();
2569 }
2570 return INVALID_OPERATION;
2571 }
2572 // abort if start is rejected by audio policy manager
2573 if (status != NO_ERROR) {
2574 return PERMISSION_DENIED;
2575 }
2576#ifdef ADD_BATTERY_DATA
2577 // to track the speaker usage
2578 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
2579#endif
Eric Laurent09f1ed22019-04-24 17:45:17 -07002580 sendIoConfigEvent_l(AUDIO_CLIENT_STARTED, track->creatorPid(), track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002581 }
2582
Eric Laurent51716182016-02-29 18:00:56 -08002583 // set retry count for buffer fill
2584 if (track->isOffloaded()) {
Eric Laurente93cc032016-05-05 10:15:10 -07002585 if (track->isStopping_1()) {
2586 track->mRetryCount = kMaxTrackStopRetriesOffload;
2587 } else {
2588 track->mRetryCount = kMaxTrackStartupRetriesOffload;
2589 }
2590 track->mFillingUpStatus = mStandby ? Track::FS_FILLING : Track::FS_FILLED;
Eric Laurent51716182016-02-29 18:00:56 -08002591 } else {
2592 track->mRetryCount = kMaxTrackStartupRetries;
Eric Laurente93cc032016-05-05 10:15:10 -07002593 track->mFillingUpStatus =
2594 track->sharedBuffer() != 0 ? Track::FS_FILLED : Track::FS_FILLING;
Eric Laurent51716182016-02-29 18:00:56 -08002595 }
2596
jiabineb3bda02020-06-30 14:07:03 -07002597 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2598 if (mHapticChannelMask != AUDIO_CHANNEL_NONE
2599 && ((track->channelMask() & AUDIO_CHANNEL_HAPTIC_ALL) != AUDIO_CHANNEL_NONE
2600 || (chain != nullptr && chain->containsHapticGeneratingEffect_l()))) {
jiabin57303cc2018-12-18 15:45:57 -08002601 // Unlock due to VibratorService will lock for this call and will
2602 // call Tracks.mute/unmute which also require thread's lock.
2603 mLock.unlock();
2604 const int intensity = AudioFlinger::onExternalVibrationStart(
2605 track->getExternalVibration());
2606 mLock.lock();
jiabine70bc7f2020-06-30 22:07:55 -07002607 track->setHapticIntensity(static_cast<os::HapticScale>(intensity));
jiabin57303cc2018-12-18 15:45:57 -08002608 // Haptic playback should be enabled by vibrator service.
2609 if (track->getHapticPlaybackEnabled()) {
2610 // Disable haptic playback of all active track to ensure only
2611 // one track playing haptic if current track should play haptic.
2612 for (const auto &t : mActiveTracks) {
2613 t->setHapticPlaybackEnabled(false);
2614 }
jiabin245cdd92018-12-07 17:55:15 -08002615 }
jiabine70bc7f2020-06-30 22:07:55 -07002616
2617 // Set haptic intensity for effect
2618 if (chain != nullptr) {
2619 chain->setHapticIntensity_l(track->id(), intensity);
2620 }
jiabin245cdd92018-12-07 17:55:15 -08002621 }
2622
Eric Laurent81784c32012-11-19 14:55:58 -08002623 track->mResetDone = false;
2624 track->mPresentationCompleteFrames = 0;
2625 mActiveTracks.add(track);
Eric Laurentd0107bc2013-06-11 14:38:48 -07002626 if (chain != 0) {
2627 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
2628 track->sessionId());
2629 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08002630 }
2631
Andy Hungc2b11cb2020-04-22 09:04:01 -07002632 track->logBeginInterval(patchSinksToString(&mPatch)); // log to MediaMetrics
Eric Laurent81784c32012-11-19 14:55:58 -08002633 status = NO_ERROR;
2634 }
2635
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08002636 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002637 return status;
2638}
2639
Eric Laurentbfb1b832013-01-07 09:53:42 -08002640bool AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002641{
Eric Laurentbfb1b832013-01-07 09:53:42 -08002642 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08002643 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002644 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
2645 track->mState = TrackBase::STOPPED;
2646 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08002647 removeTrack_l(track);
Eric Laurentab5cdba2014-06-09 17:22:27 -07002648 } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002649 track->mState = TrackBase::STOPPING_1;
Eric Laurent81784c32012-11-19 14:55:58 -08002650 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002651
2652 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08002653}
2654
2655void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
2656{
2657 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Andy Hung2148bf02016-11-28 19:01:02 -08002658
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002659 String8 result;
2660 track->appendDump(result, false /* active */);
2661 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.string());
Andy Hung2148bf02016-11-28 19:01:02 -08002662
Eric Laurent81784c32012-11-19 14:55:58 -08002663 mTracks.remove(track);
jiabin18a4b1c2020-09-17 11:40:42 -07002664 {
2665 Mutex::Autolock _atCbL(mAudioTrackCbLock);
2666 mAudioTrackCallbacks.erase(track);
2667 }
Eric Laurent81784c32012-11-19 14:55:58 -08002668 if (track->isFastTrack()) {
2669 int index = track->mFastIndex;
Glenn Kastendc2c50b2016-04-21 08:13:14 -07002670 ALOG_ASSERT(0 < index && index < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08002671 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
2672 mFastTrackAvailMask |= 1 << index;
2673 // redundant as track is about to be destroyed, for dumpsys only
2674 track->mFastIndex = -1;
2675 }
2676 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2677 if (chain != 0) {
2678 chain->decTrackCnt();
2679 }
2680}
2681
2682String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
2683{
Eric Laurent81784c32012-11-19 14:55:58 -08002684 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002685 String8 out_s8;
2686 if (initCheck() == NO_ERROR && mOutput->stream->getParameters(keys, &out_s8) == OK) {
2687 return out_s8;
Eric Laurent81784c32012-11-19 14:55:58 -08002688 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002689 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08002690}
2691
Mikhail Naganovac917ac2018-11-28 14:03:52 -08002692status_t AudioFlinger::DirectOutputThread::selectPresentation(int presentationId, int programId) {
2693 Mutex::Autolock _l(mLock);
2694 if (mOutput == nullptr || mOutput->stream == nullptr) {
2695 return NO_INIT;
2696 }
2697 return mOutput->stream->selectPresentation(presentationId, programId);
2698}
2699
Eric Laurent09f1ed22019-04-24 17:45:17 -07002700void AudioFlinger::PlaybackThread::ioConfigChanged(audio_io_config_event event, pid_t pid,
2701 audio_port_handle_t portId) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002702 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
2703 ALOGV("PlaybackThread::ioConfigChanged, thread %p, event %d", this, event);
Eric Laurent81784c32012-11-19 14:55:58 -08002704
Eric Laurent73e26b62015-04-27 16:55:58 -07002705 desc->mIoHandle = mId;
Eric Laurent74c38dc2020-12-23 18:19:44 +01002706 struct audio_patch patch = mPatch;
2707 if (isMsdDevice()) {
2708 patch = mDownStreamPatch;
2709 }
Eric Laurent81784c32012-11-19 14:55:58 -08002710
2711 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002712 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07002713 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07002714 case AUDIO_OUTPUT_CONFIG_CHANGED:
Eric Laurent74c38dc2020-12-23 18:19:44 +01002715 desc->mPatch = patch;
Eric Laurent73e26b62015-04-27 16:55:58 -07002716 desc->mChannelMask = mChannelMask;
2717 desc->mSamplingRate = mSampleRate;
2718 desc->mFormat = mFormat;
2719 desc->mFrameCount = mNormalFrameCount; // FIXME see
Eric Laurent81784c32012-11-19 14:55:58 -08002720 // AudioFlinger::frameCount(audio_io_handle_t)
Glenn Kasten4a8308b2016-04-18 14:10:01 -07002721 desc->mFrameCountHAL = mFrameCount;
Eric Laurent73e26b62015-04-27 16:55:58 -07002722 desc->mLatency = latency_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002723 break;
Eric Laurent09f1ed22019-04-24 17:45:17 -07002724 case AUDIO_CLIENT_STARTED:
Eric Laurent74c38dc2020-12-23 18:19:44 +01002725 desc->mPatch = patch;
Eric Laurent09f1ed22019-04-24 17:45:17 -07002726 desc->mPortId = portId;
2727 break;
Eric Laurent73e26b62015-04-27 16:55:58 -07002728 case AUDIO_OUTPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08002729 default:
2730 break;
2731 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002732 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08002733}
2734
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002735void AudioFlinger::PlaybackThread::onWriteReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002736{
Eric Laurent3b4529e2013-09-05 18:09:19 -07002737 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002738}
2739
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002740void AudioFlinger::PlaybackThread::onDrainReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002741{
Eric Laurent3b4529e2013-09-05 18:09:19 -07002742 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002743}
2744
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002745void AudioFlinger::PlaybackThread::onError()
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002746{
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002747 mCallbackThread->setAsyncError();
2748}
2749
jiabinf6eb4c32020-02-25 14:06:25 -08002750void AudioFlinger::PlaybackThread::onCodecFormatChanged(
2751 const std::basic_string<uint8_t>& metadataBs)
2752{
2753 std::thread([this, metadataBs]() {
2754 audio_utils::metadata::Data metadata =
2755 audio_utils::metadata::dataFromByteString(metadataBs);
2756 if (metadata.empty()) {
2757 ALOGW("Can not transform the buffer to audio metadata, %s, %d",
2758 reinterpret_cast<char*>(const_cast<uint8_t*>(metadataBs.data())),
2759 (int)metadataBs.size());
2760 return;
2761 }
2762
2763 audio_utils::metadata::ByteString metaDataStr =
2764 audio_utils::metadata::byteStringFromData(metadata);
2765 std::vector metadataVec(metaDataStr.begin(), metaDataStr.end());
2766 Mutex::Autolock _l(mAudioTrackCbLock);
jiabin18a4b1c2020-09-17 11:40:42 -07002767 for (const auto& callbackPair : mAudioTrackCallbacks) {
2768 callbackPair.second->onCodecFormatChanged(metadataVec);
jiabinf6eb4c32020-02-25 14:06:25 -08002769 }
2770 }).detach();
2771}
2772
Eric Laurent3b4529e2013-09-05 18:09:19 -07002773void AudioFlinger::PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002774{
2775 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002776 // reject out of sequence requests
2777 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
2778 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002779 mWaitWorkCV.signal();
2780 }
2781}
2782
Eric Laurent3b4529e2013-09-05 18:09:19 -07002783void AudioFlinger::PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002784{
2785 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002786 // reject out of sequence requests
2787 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
Andy Hungf3234512018-07-03 14:51:47 -07002788 // Register discontinuity when HW drain is completed because that can cause
2789 // the timestamp frame position to reset to 0 for direct and offload threads.
2790 // (Out of sequence requests are ignored, since the discontinuity would be handled
2791 // elsewhere, e.g. in flush).
Dean Wheatley12473e92021-03-18 23:00:55 +11002792 mTimestampVerifier.discontinuity(mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002793 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002794 mWaitWorkCV.signal();
2795 }
2796}
2797
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002798void AudioFlinger::PlaybackThread::readOutputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08002799{
Glenn Kastenadad3d72014-02-21 14:51:43 -08002800 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Mikhail Naganov560637e2021-03-31 22:40:13 +00002801 const audio_config_base_t audioConfig = mOutput->getAudioProperties();
2802 mSampleRate = audioConfig.sample_rate;
2803 mChannelMask = audioConfig.channel_mask;
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002804 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002805 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002806 }
Andy Hung9a592762014-07-21 21:56:01 -07002807 if ((mType == MIXER || mType == DUPLICATING)
2808 && !isValidPcmSinkChannelMask(mChannelMask)) {
2809 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output",
2810 mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002811 }
Andy Hunge5412692014-05-16 11:25:07 -07002812 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01002813 mBalance.setChannelMask(mChannelMask);
Phil Burkca5e6142015-07-14 09:42:29 -07002814
2815 // Get actual HAL format.
Mikhail Naganov560637e2021-03-31 22:40:13 +00002816 status_t result = mOutput->stream->getAudioProperties(nullptr, nullptr, &mHALFormat);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002817 LOG_ALWAYS_FATAL_IF(result != OK, "Error when retrieving output stream format: %d", result);
Phil Burkca5e6142015-07-14 09:42:29 -07002818 // Get format from the shim, which will be different than the HAL format
2819 // if playing compressed audio over HDMI passthrough.
Mikhail Naganov560637e2021-03-31 22:40:13 +00002820 mFormat = audioConfig.format;
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002821 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002822 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002823 }
Andy Hung6146c082014-03-18 11:56:15 -07002824 if ((mType == MIXER || mType == DUPLICATING)
2825 && !isValidPcmSinkFormat(mFormat)) {
2826 LOG_FATAL("HAL format %#x not supported for mixed output",
2827 mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002828 }
Phil Burk062e67a2015-02-11 13:40:50 -08002829 mFrameSize = mOutput->getFrameSize();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002830 result = mOutput->stream->getBufferSize(&mBufferSize);
2831 LOG_ALWAYS_FATAL_IF(result != OK,
2832 "Error when retrieving output stream buffer size: %d", result);
Glenn Kasten70949c42013-08-06 07:40:12 -07002833 mFrameCount = mBufferSize / mFrameSize;
Dean Wheatley77cbebd2019-04-23 14:18:44 +10002834 if ((mType == MIXER || mType == DUPLICATING) && (mFrameCount & 15)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002835 ALOGW("HAL output buffer size is %zu frames but AudioMixer requires multiples of 16 frames",
Eric Laurent81784c32012-11-19 14:55:58 -08002836 mFrameCount);
2837 }
2838
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002839 if (mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING) {
2840 if (mOutput->stream->setCallback(this) == OK) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002841 mUseAsyncWrite = true;
Eric Laurent4de95592013-09-26 15:28:21 -07002842 mCallbackThread = new AudioFlinger::AsyncCallbackThread(this);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002843 }
2844 }
2845
Eric Laurentd1f69b02014-12-15 14:33:13 -08002846 mHwSupportsPause = false;
2847 if (mOutput->flags & AUDIO_OUTPUT_FLAG_DIRECT) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002848 bool supportsPause = false, supportsResume = false;
2849 if (mOutput->stream->supportsPauseAndResume(&supportsPause, &supportsResume) == OK) {
2850 if (supportsPause && supportsResume) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08002851 mHwSupportsPause = true;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002852 } else if (supportsPause) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08002853 ALOGW("direct output implements pause but not resume");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002854 } else if (supportsResume) {
2855 ALOGW("direct output implements resume but not pause");
Eric Laurentd1f69b02014-12-15 14:33:13 -08002856 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002857 }
2858 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07002859 if (!mHwSupportsPause && mOutput->flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) {
2860 LOG_ALWAYS_FATAL("HW_AV_SYNC requested but HAL does not implement pause and resume");
2861 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002862
Andy Hungfbfc3952015-01-15 13:33:51 -08002863 if (mType == DUPLICATING && mMixerBufferEnabled && mEffectBufferEnabled) {
2864 // For best precision, we use float instead of the associated output
2865 // device format (typically PCM 16 bit).
2866
2867 mFormat = AUDIO_FORMAT_PCM_FLOAT;
2868 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
2869 mBufferSize = mFrameSize * mFrameCount;
2870
2871 // TODO: We currently use the associated output device channel mask and sample rate.
2872 // (1) Perhaps use the ORed channel mask of all downstream MixerThreads
2873 // (if a valid mask) to avoid premature downmix.
2874 // (2) Perhaps use the maximum sample rate of all downstream MixerThreads
2875 // instead of the output device sample rate to avoid loss of high frequency information.
2876 // This may need to be updated as MixerThread/OutputTracks are added and not here.
2877 }
2878
Andy Hung09a50072014-02-27 14:30:47 -08002879 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08002880 double multiplier = 1.0;
2881 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
2882 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08002883 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
2884 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Haynes Mathew George227a14b2016-05-09 12:45:48 -07002885
Eric Laurent81784c32012-11-19 14:55:58 -08002886 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
2887 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
2888 maxNormalFrameCount = maxNormalFrameCount & ~15;
2889 if (maxNormalFrameCount < minNormalFrameCount) {
2890 maxNormalFrameCount = minNormalFrameCount;
2891 }
2892 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
2893 if (multiplier <= 1.0) {
2894 multiplier = 1.0;
2895 } else if (multiplier <= 2.0) {
2896 if (2 * mFrameCount <= maxNormalFrameCount) {
2897 multiplier = 2.0;
2898 } else {
2899 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
2900 }
2901 } else {
Haynes Mathew George227a14b2016-05-09 12:45:48 -07002902 multiplier = floor(multiplier);
Eric Laurent81784c32012-11-19 14:55:58 -08002903 }
2904 }
2905 mNormalFrameCount = multiplier * mFrameCount;
2906 // round up to nearest 16 frames to satisfy AudioMixer
Eric Laurentab5cdba2014-06-09 17:22:27 -07002907 if (mType == MIXER || mType == DUPLICATING) {
2908 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
2909 }
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002910 ALOGI("HAL output buffer size %zu frames, normal sink buffer size %zu frames", mFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08002911 mNormalFrameCount);
2912
Andy Hung08fb1742015-05-31 23:22:10 -07002913 // Check if we want to throttle the processing to no more than 2x normal rate
2914 mThreadThrottle = property_get_bool("af.thread.throttle", true /* default_value */);
Andy Hung40eb1a12015-06-18 13:42:02 -07002915 mThreadThrottleTimeMs = 0;
2916 mThreadThrottleEndMs = 0;
Andy Hung08fb1742015-05-31 23:22:10 -07002917 mHalfBufferMs = mNormalFrameCount * 1000 / (2 * mSampleRate);
2918
Andy Hung010a1a12014-03-13 13:57:33 -07002919 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
2920 // Originally this was int16_t[] array, need to remove legacy implications.
2921 free(mSinkBuffer);
2922 mSinkBuffer = NULL;
Andy Hung5b10a202014-03-13 13:59:29 -07002923 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
2924 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
2925 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07002926 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08002927
Andy Hung69aed5f2014-02-25 17:24:40 -08002928 // We resize the mMixerBuffer according to the requirements of the sink buffer which
2929 // drives the output.
2930 free(mMixerBuffer);
2931 mMixerBuffer = NULL;
2932 if (mMixerBufferEnabled) {
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01002933 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // no longer valid: AUDIO_FORMAT_PCM_16_BIT.
Andy Hung69aed5f2014-02-25 17:24:40 -08002934 mMixerBufferSize = mNormalFrameCount * mChannelCount
2935 * audio_bytes_per_sample(mMixerBufferFormat);
2936 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
2937 }
Andy Hung98ef9782014-03-04 14:46:50 -08002938 free(mEffectBuffer);
2939 mEffectBuffer = NULL;
2940 if (mEffectBufferEnabled) {
rago94a1ee82017-07-21 15:11:02 -07002941 mEffectBufferFormat = EFFECT_BUFFER_FORMAT;
Andy Hung98ef9782014-03-04 14:46:50 -08002942 mEffectBufferSize = mNormalFrameCount * mChannelCount
2943 * audio_bytes_per_sample(mEffectBufferFormat);
2944 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
2945 }
Andy Hung69aed5f2014-02-25 17:24:40 -08002946
Mikhail Naganov55773032020-10-01 15:08:13 -07002947 mHapticChannelMask = static_cast<audio_channel_mask_t>(mChannelMask & AUDIO_CHANNEL_HAPTIC_ALL);
2948 mChannelMask = static_cast<audio_channel_mask_t>(mChannelMask & ~mHapticChannelMask);
jiabin245cdd92018-12-07 17:55:15 -08002949 mHapticChannelCount = audio_channel_count_from_out_mask(mHapticChannelMask);
2950 mChannelCount -= mHapticChannelCount;
2951
Eric Laurent81784c32012-11-19 14:55:58 -08002952 // force reconfiguration of effect chains and engines to take new buffer size and audio
2953 // parameters into account
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002954 // Note that mLock is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08002955 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
2956 // matter.
2957 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
2958 Vector< sp<EffectChain> > effectChains = mEffectChains;
2959 for (size_t i = 0; i < effectChains.size(); i ++) {
Eric Laurent6c796322019-04-09 14:13:17 -07002960 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(),
2961 this/* srcThread */, this/* dstThread */);
Eric Laurent81784c32012-11-19 14:55:58 -08002962 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08002963
George Burgess IV5e4d86f2020-02-18 12:55:36 -08002964 audio_output_flags_t flags = mOutput->flags;
Andy Hungcf10d742020-04-28 15:38:24 -07002965 mediametrics::LogItem item(mThreadMetrics.getMetricsId()); // TODO: method in ThreadMetrics?
Andy Hungb68f5eb2019-12-03 16:49:17 -08002966 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
2967 .set(AMEDIAMETRICS_PROP_ENCODING, formatToString(mFormat).c_str())
2968 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
2969 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
2970 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
2971 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mNormalFrameCount)
2972 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
2973 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELMASK,
2974 (int32_t)mHapticChannelMask)
2975 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELCOUNT,
2976 (int32_t)mHapticChannelCount)
2977 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_ENCODING,
2978 formatToString(mHALFormat).c_str())
2979 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_FRAMECOUNT,
2980 (int32_t)mFrameCount) // sic - added HAL
2981 ;
2982 uint32_t latencyMs;
2983 if (mOutput->stream->getLatency(&latencyMs) == NO_ERROR) {
2984 item.set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_LATENCYMS, (double)latencyMs);
2985 }
2986 item.record();
Eric Laurent81784c32012-11-19 14:55:58 -08002987}
2988
Kevin Rocard069c2712018-03-29 19:09:14 -07002989void AudioFlinger::PlaybackThread::updateMetadata_l()
2990{
Kevin Rocard12381092018-04-11 09:19:59 -07002991 if (mOutput == nullptr || mOutput->stream == nullptr ) {
2992 return; // That should not happen
2993 }
2994 bool hasChanged = mActiveTracks.readAndClearHasChanged();
2995 for (const sp<Track> &track : mActiveTracks) {
2996 // Do not short-circuit as all hasChanged states must be reset
2997 // as all the metadata are going to be sent
2998 hasChanged |= track->readAndClearHasChanged();
2999 }
3000 if (!hasChanged) {
3001 return; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -07003002 }
3003 StreamOutHalInterface::SourceMetadata metadata;
Kevin Rocard12381092018-04-11 09:19:59 -07003004 auto backInserter = std::back_inserter(metadata.tracks);
Kevin Rocard069c2712018-03-29 19:09:14 -07003005 for (const sp<Track> &track : mActiveTracks) {
3006 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurentb9cc0ab2021-01-29 11:46:52 +01003007 // Do not forward metadata for PatchTrack with unspecified stream type
3008 if (track->streamType() != AUDIO_STREAM_PATCH) {
3009 track->copyMetadataTo(backInserter);
3010 }
Kevin Rocard069c2712018-03-29 19:09:14 -07003011 }
Kevin Rocard12381092018-04-11 09:19:59 -07003012 sendMetadataToBackend_l(metadata);
Kevin Rocard80ee2722018-04-11 15:53:48 +00003013}
Kevin Rocardc86a7f72018-04-03 09:00:09 -07003014
Kevin Rocard12381092018-04-11 09:19:59 -07003015void AudioFlinger::PlaybackThread::sendMetadataToBackend_l(
3016 const StreamOutHalInterface::SourceMetadata& metadata)
3017{
3018 mOutput->stream->updateSourceMetadata(metadata);
3019};
3020
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003021status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
Eric Laurent81784c32012-11-19 14:55:58 -08003022{
3023 if (halFrames == NULL || dspFrames == NULL) {
3024 return BAD_VALUE;
3025 }
3026 Mutex::Autolock _l(mLock);
3027 if (initCheck() != NO_ERROR) {
3028 return INVALID_OPERATION;
3029 }
Andy Hung818e7a32016-02-16 18:08:07 -08003030 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08003031 *halFrames = framesWritten;
3032
3033 if (isSuspended()) {
3034 // return an estimation of rendered frames when the output is suspended
3035 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08003036 *dspFrames = (uint32_t)
3037 (framesWritten >= (int64_t)latencyFrames ? framesWritten - latencyFrames : 0);
Eric Laurent81784c32012-11-19 14:55:58 -08003038 return NO_ERROR;
3039 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003040 status_t status;
3041 uint32_t frames;
Phil Burk062e67a2015-02-11 13:40:50 -08003042 status = mOutput->getRenderPosition(&frames);
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003043 *dspFrames = (size_t)frames;
3044 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08003045 }
3046}
3047
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08003048product_strategy_t AudioFlinger::PlaybackThread::getStrategyForSession_l(audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08003049{
3050 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
3051 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
3052 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
3053 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
3054 }
3055 for (size_t i = 0; i < mTracks.size(); i++) {
3056 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08003057 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003058 return AudioSystem::getStrategyForStream(track->streamType());
3059 }
3060 }
3061 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
3062}
3063
3064
Phil Burk062e67a2015-02-11 13:40:50 -08003065AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurent81784c32012-11-19 14:55:58 -08003066{
3067 Mutex::Autolock _l(mLock);
3068 return mOutput;
3069}
3070
Phil Burk062e67a2015-02-11 13:40:50 -08003071AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
Eric Laurent81784c32012-11-19 14:55:58 -08003072{
3073 Mutex::Autolock _l(mLock);
3074 AudioStreamOut *output = mOutput;
3075 mOutput = NULL;
3076 // FIXME FastMixer might also have a raw ptr to mOutputSink;
3077 // must push a NULL and wait for ack
3078 mOutputSink.clear();
3079 mPipeSink.clear();
3080 mNormalSink.clear();
3081 return output;
3082}
3083
3084// this method must always be called either with ThreadBase mLock held or inside the thread loop
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003085sp<StreamHalInterface> AudioFlinger::PlaybackThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08003086{
3087 if (mOutput == NULL) {
3088 return NULL;
3089 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003090 return mOutput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08003091}
3092
3093uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
3094{
3095 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
3096}
3097
3098status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
3099{
3100 if (!isValidSyncEvent(event)) {
3101 return BAD_VALUE;
3102 }
3103
3104 Mutex::Autolock _l(mLock);
3105
3106 for (size_t i = 0; i < mTracks.size(); ++i) {
3107 sp<Track> track = mTracks[i];
3108 if (event->triggerSession() == track->sessionId()) {
3109 (void) track->setSyncEvent(event);
3110 return NO_ERROR;
3111 }
3112 }
3113
3114 return NAME_NOT_FOUND;
3115}
3116
3117bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
3118{
3119 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
3120}
3121
3122void AudioFlinger::PlaybackThread::threadLoop_removeTracks(
3123 const Vector< sp<Track> >& tracksToRemove)
3124{
Andy Hungfe726a62018-09-27 15:17:25 -07003125 // Miscellaneous track cleanup when removed from the active list,
3126 // called without Thread lock but synchronized with threadLoop processing.
Eric Laurentbfb1b832013-01-07 09:53:42 -08003127#ifdef ADD_BATTERY_DATA
Andy Hungfe726a62018-09-27 15:17:25 -07003128 for (const auto& track : tracksToRemove) {
3129 if (track->isExternalTrack()) {
3130 // to track the speaker usage
3131 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Eric Laurent81784c32012-11-19 14:55:58 -08003132 }
3133 }
Andy Hungfe726a62018-09-27 15:17:25 -07003134#else
3135 (void)tracksToRemove; // suppress unused warning
3136#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003137}
3138
3139void AudioFlinger::PlaybackThread::checkSilentMode_l()
3140{
3141 if (!mMasterMute) {
3142 char value[PROPERTY_VALUE_MAX];
jiabin0a957d32020-04-29 10:56:20 -07003143 if (mOutDeviceTypeAddrs.empty()) {
3144 ALOGD("ro.audio.silent is ignored since no output device is set");
3145 return;
3146 }
jiabinc52b1ff2019-10-31 17:20:42 -07003147 if (isSingleDeviceType(outDeviceTypes(), AUDIO_DEVICE_OUT_REMOTE_SUBMIX)) {
Jean-Michel Trivi32f37c22016-03-31 16:00:32 -07003148 ALOGD("ro.audio.silent will be ignored for threads on AUDIO_DEVICE_OUT_REMOTE_SUBMIX");
3149 return;
3150 }
Eric Laurent81784c32012-11-19 14:55:58 -08003151 if (property_get("ro.audio.silent", value, "0") > 0) {
3152 char *endptr;
3153 unsigned long ul = strtoul(value, &endptr, 0);
3154 if (*endptr == '\0' && ul != 0) {
3155 ALOGD("Silence is golden");
3156 // The setprop command will not allow a property to be changed after
3157 // the first time it is set, so we don't have to worry about un-muting.
3158 setMasterMute_l(true);
3159 }
3160 }
3161 }
3162}
3163
3164// shared by MIXER and DIRECT, overridden by DUPLICATING
Eric Laurentbfb1b832013-01-07 09:53:42 -08003165ssize_t AudioFlinger::PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08003166{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07003167 LOG_HIST_TS();
Eric Laurent81784c32012-11-19 14:55:58 -08003168 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003169 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07003170 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08003171
3172 // If an NBAIO sink is present, use it to write the normal mixer's submix
3173 if (mNormalSink != 0) {
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003174
Andy Hung010a1a12014-03-13 13:57:33 -07003175 const size_t count = mBytesRemaining / mFrameSize;
3176
Simon Wilson2d590962012-11-29 15:18:50 -08003177 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08003178 // update the setpoint when AudioFlinger::mScreenState changes
3179 uint32_t screenState = AudioFlinger::mScreenState;
3180 if (screenState != mScreenState) {
3181 mScreenState = screenState;
3182 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
3183 if (pipe != NULL) {
3184 pipe->setAvgFrames((mScreenState & 1) ?
3185 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
3186 }
3187 }
Andy Hung010a1a12014-03-13 13:57:33 -07003188 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08003189 ATRACE_END();
Eric Laurent81784c32012-11-19 14:55:58 -08003190 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07003191 bytesWritten = framesWritten * mFrameSize;
Andy Hung8946a282018-04-19 20:04:56 -07003192#ifdef TEE_SINK
3193 mTee.write((char *)mSinkBuffer + offset, framesWritten);
3194#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003195 } else {
3196 bytesWritten = framesWritten;
3197 }
3198 // otherwise use the HAL / AudioStreamOut directly
3199 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003200 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07003201
Eric Laurentbfb1b832013-01-07 09:53:42 -08003202 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003203 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
3204 mWriteAckSequence += 2;
3205 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003206 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003207 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003208 }
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07003209 ATRACE_BEGIN("write");
Glenn Kasten767094d2013-08-23 13:51:43 -07003210 // FIXME We should have an implementation of timestamps for direct output threads.
3211 // They are used e.g for multichannel PCM playback over HDMI.
Phil Burk062e67a2015-02-11 13:40:50 -08003212 bytesWritten = mOutput->write((char *)mSinkBuffer + offset, mBytesRemaining);
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07003213 ATRACE_END();
Eric Laurent51716182016-02-29 18:00:56 -08003214
Eric Laurentbfb1b832013-01-07 09:53:42 -08003215 if (mUseAsyncWrite &&
3216 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
3217 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07003218 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003219 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003220 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003221 }
Eric Laurent81784c32012-11-19 14:55:58 -08003222 }
3223
Eric Laurent81784c32012-11-19 14:55:58 -08003224 mNumWrites++;
3225 mInWrite = false;
Andy Hungcf10d742020-04-28 15:38:24 -07003226 if (mStandby) {
3227 mThreadMetrics.logBeginInterval();
3228 mStandby = false;
3229 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003230 return bytesWritten;
3231}
3232
3233void AudioFlinger::PlaybackThread::threadLoop_drain()
3234{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003235 bool supportsDrain = false;
3236 if (mOutput->stream->supportsDrain(&supportsDrain) == OK && supportsDrain) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003237 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
3238 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003239 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
3240 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003241 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003242 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003243 }
Mikhail Naganovcbc8f612016-10-11 18:05:13 -07003244 status_t result = mOutput->stream->drain(mMixerStatus == MIXER_DRAIN_TRACK);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003245 ALOGE_IF(result != OK, "Error when draining stream: %d", result);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003246 }
3247}
3248
3249void AudioFlinger::PlaybackThread::threadLoop_exit()
3250{
Eric Laurent275e8e92014-11-30 15:14:47 -08003251 {
3252 Mutex::Autolock _l(mLock);
3253 for (size_t i = 0; i < mTracks.size(); i++) {
3254 sp<Track> track = mTracks[i];
3255 track->invalidate();
3256 }
Andy Hungdae27702016-10-31 14:01:16 -07003257 // Clear ActiveTracks to update BatteryNotifier in case active tracks remain.
3258 // After we exit there are no more track changes sent to BatteryNotifier
3259 // because that requires an active threadLoop.
3260 // TODO: should we decActiveTrackCnt() of the cleared track effect chain?
3261 mActiveTracks.clear();
Eric Laurent275e8e92014-11-30 15:14:47 -08003262 }
Eric Laurent81784c32012-11-19 14:55:58 -08003263}
3264
3265/*
3266The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08003267 - mSinkBufferSize from frame count * frame size
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003268 - mActiveSleepTimeUs from activeSleepTimeUs()
3269 - mIdleSleepTimeUs from idleSleepTimeUs()
Eric Laurent42537be2016-01-08 17:16:42 -08003270 - mStandbyDelayNs from mActiveSleepTimeUs (DIRECT only) or forced to at least
3271 kDefaultStandbyTimeInNsecs when connected to an A2DP device.
Eric Laurent81784c32012-11-19 14:55:58 -08003272 - maxPeriod from frame count and sample rate (MIXER only)
3273
3274The parameters that affect these derived values are:
3275 - frame count
3276 - frame size
3277 - sample rate
3278 - device type: A2DP or not
3279 - device latency
3280 - format: PCM or not
3281 - active sleep time
3282 - idle sleep time
3283*/
3284
3285void AudioFlinger::PlaybackThread::cacheParameters_l()
3286{
Andy Hung25c2dac2014-02-27 14:56:00 -08003287 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003288 mActiveSleepTimeUs = activeSleepTimeUs();
3289 mIdleSleepTimeUs = idleSleepTimeUs();
Eric Laurent42537be2016-01-08 17:16:42 -08003290
3291 // make sure standby delay is not too short when connected to an A2DP sink to avoid
3292 // truncating audio when going to standby.
3293 mStandbyDelayNs = AudioFlinger::mStandbyTimeInNsecs;
jiabinc52b1ff2019-10-31 17:20:42 -07003294 if (!Intersection(outDeviceTypes(), getAudioDeviceOutAllA2dpSet()).empty()) {
Eric Laurent42537be2016-01-08 17:16:42 -08003295 if (mStandbyDelayNs < kDefaultStandbyTimeInNsecs) {
3296 mStandbyDelayNs = kDefaultStandbyTimeInNsecs;
3297 }
3298 }
Eric Laurent81784c32012-11-19 14:55:58 -08003299}
3300
Eric Laurent13084622016-05-17 10:51:49 -07003301bool AudioFlinger::PlaybackThread::invalidateTracks_l(audio_stream_type_t streamType)
Eric Laurent81784c32012-11-19 14:55:58 -08003302{
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003303 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %zu",
Eric Laurent81784c32012-11-19 14:55:58 -08003304 this, streamType, mTracks.size());
Eric Laurent13084622016-05-17 10:51:49 -07003305 bool trackMatch = false;
Eric Laurent81784c32012-11-19 14:55:58 -08003306 size_t size = mTracks.size();
3307 for (size_t i = 0; i < size; i++) {
3308 sp<Track> t = mTracks[i];
Eric Laurentd60560a2015-04-10 11:31:20 -07003309 if (t->streamType() == streamType && t->isExternalTrack()) {
Glenn Kasten5736c352012-12-04 12:12:34 -08003310 t->invalidate();
Eric Laurent13084622016-05-17 10:51:49 -07003311 trackMatch = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003312 }
3313 }
Eric Laurent13084622016-05-17 10:51:49 -07003314 return trackMatch;
Eric Laurent81784c32012-11-19 14:55:58 -08003315}
3316
Haynes Mathew George05317d22016-05-03 16:34:26 -07003317void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
3318{
3319 Mutex::Autolock _l(mLock);
3320 invalidateTracks_l(streamType);
3321}
3322
Eric Laurent81784c32012-11-19 14:55:58 -08003323status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
3324{
Glenn Kastend848eb42016-03-08 13:42:11 -08003325 audio_session_t session = chain->sessionId();
Mikhail Naganov022b9952017-01-04 16:36:51 -08003326 sp<EffectBufferHalInterface> halInBuffer, halOutBuffer;
Kevin Rocard7588ff42018-01-08 11:11:30 -08003327 status_t result = mAudioFlinger->mEffectsFactoryHal->mirrorBuffer(
Mikhail Naganov022b9952017-01-04 16:36:51 -08003328 mEffectBufferEnabled ? mEffectBuffer : mSinkBuffer,
3329 mEffectBufferEnabled ? mEffectBufferSize : mSinkBufferSize,
3330 &halInBuffer);
3331 if (result != OK) return result;
3332 halOutBuffer = halInBuffer;
rago94a1ee82017-07-21 15:11:02 -07003333 effect_buffer_t *buffer = reinterpret_cast<effect_buffer_t*>(halInBuffer->externalData());
Eric Laurent81784c32012-11-19 14:55:58 -08003334 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Eric Laurent3f75a5b2019-11-12 15:55:51 -08003335 if (!audio_is_global_session(session)) {
Eric Laurent81784c32012-11-19 14:55:58 -08003336 // Only one effect chain can be present in direct output thread and it uses
Andy Hung2098f272014-02-27 14:00:06 -08003337 // the sink buffer as input
Eric Laurent81784c32012-11-19 14:55:58 -08003338 if (mType != DIRECT) {
jiabin245cdd92018-12-07 17:55:15 -08003339 size_t numSamples = mNormalFrameCount * (mChannelCount + mHapticChannelCount);
Kevin Rocard7588ff42018-01-08 11:11:30 -08003340 status_t result = mAudioFlinger->mEffectsFactoryHal->allocateBuffer(
rago94a1ee82017-07-21 15:11:02 -07003341 numSamples * sizeof(effect_buffer_t),
Mikhail Naganov022b9952017-01-04 16:36:51 -08003342 &halInBuffer);
3343 if (result != OK) return result;
rago94a1ee82017-07-21 15:11:02 -07003344#ifdef FLOAT_EFFECT_CHAIN
3345 buffer = halInBuffer->audioBuffer()->f32;
3346#else
Mikhail Naganov022b9952017-01-04 16:36:51 -08003347 buffer = halInBuffer->audioBuffer()->s16;
rago94a1ee82017-07-21 15:11:02 -07003348#endif
Mikhail Naganov022b9952017-01-04 16:36:51 -08003349 ALOGV("addEffectChain_l() creating new input buffer %p session %d",
3350 buffer, session);
Eric Laurent81784c32012-11-19 14:55:58 -08003351 }
3352
3353 // Attach all tracks with same session ID to this chain.
3354 for (size_t i = 0; i < mTracks.size(); ++i) {
3355 sp<Track> track = mTracks[i];
3356 if (session == track->sessionId()) {
3357 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(),
3358 buffer);
3359 track->setMainBuffer(buffer);
3360 chain->incTrackCnt();
3361 }
3362 }
3363
3364 // indicate all active tracks in the chain
Andy Hungdae27702016-10-31 14:01:16 -07003365 for (const sp<Track> &track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08003366 if (session == track->sessionId()) {
3367 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
3368 chain->incActiveTrackCnt();
3369 }
3370 }
3371 }
Eric Laurentaaa44472014-09-12 17:41:50 -07003372 chain->setThread(this);
Mikhail Naganov022b9952017-01-04 16:36:51 -08003373 chain->setInBuffer(halInBuffer);
3374 chain->setOutBuffer(halOutBuffer);
Eric Laurent3f75a5b2019-11-12 15:55:51 -08003375 // Effect chain for session AUDIO_SESSION_DEVICE is inserted at end of effect
3376 // chains list in order to be processed last as it contains output device effects.
3377 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted just before to apply post
3378 // processing effects specific to an output stream before effects applied to all streams
3379 // routed to a given device.
Eric Laurent81784c32012-11-19 14:55:58 -08003380 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
3381 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Glenn Kastend848eb42016-03-08 13:42:11 -08003382 // after track specific effects and before output stage.
Eric Laurent81784c32012-11-19 14:55:58 -08003383 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
Glenn Kastend848eb42016-03-08 13:42:11 -08003384 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX.
Eric Laurent81784c32012-11-19 14:55:58 -08003385 // Effect chain for other sessions are inserted at beginning of effect
3386 // chains list to be processed before output mix effects. Relative order between other
Glenn Kastend848eb42016-03-08 13:42:11 -08003387 // sessions is not important.
3388 static_assert(AUDIO_SESSION_OUTPUT_MIX == 0 &&
Eric Laurent3f75a5b2019-11-12 15:55:51 -08003389 AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX &&
3390 AUDIO_SESSION_DEVICE < AUDIO_SESSION_OUTPUT_STAGE,
Glenn Kastend848eb42016-03-08 13:42:11 -08003391 "audio_session_t constants misdefined");
Eric Laurent81784c32012-11-19 14:55:58 -08003392 size_t size = mEffectChains.size();
3393 size_t i = 0;
3394 for (i = 0; i < size; i++) {
3395 if (mEffectChains[i]->sessionId() < session) {
3396 break;
3397 }
3398 }
3399 mEffectChains.insertAt(chain, i);
3400 checkSuspendOnAddEffectChain_l(chain);
3401
3402 return NO_ERROR;
3403}
3404
3405size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
3406{
Glenn Kastend848eb42016-03-08 13:42:11 -08003407 audio_session_t session = chain->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08003408
3409 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
3410
3411 for (size_t i = 0; i < mEffectChains.size(); i++) {
3412 if (chain == mEffectChains[i]) {
3413 mEffectChains.removeAt(i);
3414 // detach all active tracks from the chain
Andy Hungdae27702016-10-31 14:01:16 -07003415 for (const sp<Track> &track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08003416 if (session == track->sessionId()) {
3417 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
3418 chain.get(), session);
3419 chain->decActiveTrackCnt();
3420 }
3421 }
3422
3423 // detach all tracks with same session ID from this chain
3424 for (size_t i = 0; i < mTracks.size(); ++i) {
3425 sp<Track> track = mTracks[i];
3426 if (session == track->sessionId()) {
rago94a1ee82017-07-21 15:11:02 -07003427 track->setMainBuffer(reinterpret_cast<effect_buffer_t*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08003428 chain->decTrackCnt();
3429 }
3430 }
3431 break;
3432 }
3433 }
3434 return mEffectChains.size();
3435}
3436
3437status_t AudioFlinger::PlaybackThread::attachAuxEffect(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003438 const sp<AudioFlinger::PlaybackThread::Track>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003439{
3440 Mutex::Autolock _l(mLock);
3441 return attachAuxEffect_l(track, EffectId);
3442}
3443
3444status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003445 const sp<AudioFlinger::PlaybackThread::Track>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003446{
3447 status_t status = NO_ERROR;
3448
3449 if (EffectId == 0) {
3450 track->setAuxBuffer(0, NULL);
3451 } else {
3452 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
3453 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
3454 if (effect != 0) {
3455 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
3456 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
3457 } else {
3458 status = INVALID_OPERATION;
3459 }
3460 } else {
3461 status = BAD_VALUE;
3462 }
3463 }
3464 return status;
3465}
3466
3467void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
3468{
3469 for (size_t i = 0; i < mTracks.size(); ++i) {
3470 sp<Track> track = mTracks[i];
3471 if (track->auxEffectId() == effectId) {
3472 attachAuxEffect_l(track, 0);
3473 }
3474 }
3475}
3476
3477bool AudioFlinger::PlaybackThread::threadLoop()
3478{
Glenn Kasten388d5712017-04-07 14:38:41 -07003479 tlNBLogWriter = mNBLogWriter.get();
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003480
Eric Laurent81784c32012-11-19 14:55:58 -08003481 Vector< sp<Track> > tracksToRemove;
3482
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003483 mStandbyTimeNs = systemTime();
Andy Hung446f4df2019-02-21 12:26:41 -08003484 int64_t lastLoopCountWritten = -2; // never matches "previous" loop, when loopCount = 0.
Eric Laurent81784c32012-11-19 14:55:58 -08003485
3486 // MIXER
3487 nsecs_t lastWarning = 0;
3488
3489 // DUPLICATING
3490 // FIXME could this be made local to while loop?
3491 writeFrames = 0;
3492
3493 cacheParameters_l();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003494 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003495
3496 if (mType == MIXER) {
3497 sleepTimeShift = 0;
3498 }
3499
3500 CpuStats cpuStats;
3501 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
3502
3503 acquireWakeLock();
3504
Glenn Kasteneef598c2017-04-03 14:41:13 -07003505 // mNBLogWriter logging APIs can only be called by a single thread, typically the
3506 // thread associated with this PlaybackThread.
3507 // If you want to share the mNBLogWriter with other threads (for example, binder threads)
3508 // then all such threads must agree to hold a common mutex before logging.
Glenn Kasten9e58b552013-01-18 15:09:48 -08003509 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
3510 // and then that string will be logged at the next convenient opportunity.
Glenn Kasteneef598c2017-04-03 14:41:13 -07003511 // See reference to logString below.
Glenn Kasten9e58b552013-01-18 15:09:48 -08003512 const char *logString = NULL;
3513
rago1bb90822017-05-02 18:31:48 -07003514 // Estimated time for next buffer to be written to hal. This is used only on
3515 // suspended mode (for now) to help schedule the wait time until next iteration.
3516 nsecs_t timeLoopNextNs = 0;
3517
Eric Laurent664539d2013-09-23 18:24:31 -07003518 checkSilentMode_l();
Glenn Kasteneef598c2017-04-03 14:41:13 -07003519
Andy Hung2dbffc22018-08-08 18:50:41 -07003520 audio_patch_handle_t lastDownstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Andy Hungf3234512018-07-03 14:51:47 -07003521
Andy Hung446f4df2019-02-21 12:26:41 -08003522 // loopCount is used for statistics and diagnostics.
3523 for (int64_t loopCount = 0; !exitPending(); ++loopCount)
Eric Laurent81784c32012-11-19 14:55:58 -08003524 {
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08003525 // Log merge requests are performed during AudioFlinger binder transactions, but
3526 // that does not cover audio playback. It's requested here for that reason.
3527 mAudioFlinger->requestLogMerge();
3528
Eric Laurent81784c32012-11-19 14:55:58 -08003529 cpuStats.sample(myName);
3530
3531 Vector< sp<EffectChain> > effectChains;
Andy Hung6e6a2e62019-04-30 16:38:41 -07003532 audio_session_t activeHapticSessionId = AUDIO_SESSION_NONE;
Andy Hungc1646382019-04-30 16:12:10 -07003533 std::vector<sp<Track>> activeTracks;
Eric Laurent81784c32012-11-19 14:55:58 -08003534
Andy Hung2dbffc22018-08-08 18:50:41 -07003535 // If the device is AUDIO_DEVICE_OUT_BUS, check for downstream latency.
3536 //
jiabinc52b1ff2019-10-31 17:20:42 -07003537 // Note: we access outDeviceTypes() outside of mLock.
3538 if (isMsdDevice() && outDeviceTypes().count(AUDIO_DEVICE_OUT_BUS) != 0) {
Andy Hung2dbffc22018-08-08 18:50:41 -07003539 // Here, we try for the AF lock, but do not block on it as the latency
3540 // is more informational.
3541 if (mAudioFlinger->mLock.tryLock() == NO_ERROR) {
3542 std::vector<PatchPanel::SoftwarePatch> swPatches;
3543 double latencyMs;
3544 status_t status = INVALID_OPERATION;
3545 audio_patch_handle_t downstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
3546 if (mAudioFlinger->mPatchPanel.getDownstreamSoftwarePatches(id(), &swPatches) == OK
3547 && swPatches.size() > 0) {
3548 status = swPatches[0].getLatencyMs_l(&latencyMs);
3549 downstreamPatchHandle = swPatches[0].getPatchHandle();
3550 }
3551 if (downstreamPatchHandle != lastDownstreamPatchHandle) {
Dean Wheatley30d28422018-11-06 10:27:40 +11003552 mDownstreamLatencyStatMs.reset();
Andy Hung2dbffc22018-08-08 18:50:41 -07003553 lastDownstreamPatchHandle = downstreamPatchHandle;
3554 }
3555 if (status == OK) {
3556 // verify downstream latency (we assume a max reasonable
Mikhail Naganov6aa0a312018-11-09 11:00:01 -08003557 // latency of 5 seconds).
3558 const double minLatency = 0., maxLatency = 5000.;
3559 if (latencyMs >= minLatency && latencyMs <= maxLatency) {
Dean Wheatley56a583e2020-05-08 15:12:17 +10003560 ALOGVV("new downstream latency %lf ms", latencyMs);
Andy Hung2dbffc22018-08-08 18:50:41 -07003561 } else {
3562 ALOGD("out of range downstream latency %lf ms", latencyMs);
Mikhail Naganov6aa0a312018-11-09 11:00:01 -08003563 if (latencyMs < minLatency) latencyMs = minLatency;
3564 else if (latencyMs > maxLatency) latencyMs = maxLatency;
Andy Hung2dbffc22018-08-08 18:50:41 -07003565 }
Dean Wheatley30d28422018-11-06 10:27:40 +11003566 mDownstreamLatencyStatMs.add(latencyMs);
Andy Hung2dbffc22018-08-08 18:50:41 -07003567 }
3568 mAudioFlinger->mLock.unlock();
3569 }
3570 } else {
3571 if (lastDownstreamPatchHandle != AUDIO_PATCH_HANDLE_NONE) {
3572 // our device is no longer AUDIO_DEVICE_OUT_BUS, reset patch handle and stats.
Dean Wheatley30d28422018-11-06 10:27:40 +11003573 mDownstreamLatencyStatMs.reset();
Andy Hung2dbffc22018-08-08 18:50:41 -07003574 lastDownstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
3575 }
3576 }
3577
Eric Laurent81784c32012-11-19 14:55:58 -08003578 { // scope for mLock
3579
3580 Mutex::Autolock _l(mLock);
3581
Eric Laurent021cf962014-05-13 10:18:14 -07003582 processConfigEvents_l();
Eric Laurent10351942014-05-08 18:49:52 -07003583
Glenn Kasteneef598c2017-04-03 14:41:13 -07003584 // See comment at declaration of logString for why this is done under mLock
Glenn Kasten9e58b552013-01-18 15:09:48 -08003585 if (logString != NULL) {
3586 mNBLogWriter->logTimestamp();
3587 mNBLogWriter->log(logString);
3588 logString = NULL;
3589 }
3590
Dean Wheatley12473e92021-03-18 23:00:55 +11003591 collectTimestamps_l();
Andy Hungc8fddf32018-08-08 18:32:37 -07003592
Eric Laurent81784c32012-11-19 14:55:58 -08003593 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003594 if (mSignalPending) {
3595 // A signal was raised while we were unlocked
3596 mSignalPending = false;
3597 } else if (waitingAsyncCallback_l()) {
3598 if (exitPending()) {
3599 break;
3600 }
Marco Nelissen078538c2015-05-12 09:17:57 -07003601 bool released = false;
Eric Laurent64667972016-03-30 18:19:46 -07003602 if (!keepWakeLock()) {
Marco Nelissen078538c2015-05-12 09:17:57 -07003603 releaseWakeLock_l();
3604 released = true;
3605 }
Andy Hung10cbff12017-02-21 17:30:14 -08003606
3607 const int64_t waitNs = computeWaitTimeNs_l();
3608 ALOGV("wait async completion (wait time: %lld)", (long long)waitNs);
3609 status_t status = mWaitWorkCV.waitRelative(mLock, waitNs);
3610 if (status == TIMED_OUT) {
3611 mSignalPending = true; // if timeout recheck everything
3612 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003613 ALOGV("async completion/wake");
Marco Nelissen078538c2015-05-12 09:17:57 -07003614 if (released) {
3615 acquireWakeLock_l();
3616 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003617 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3618 mSleepTimeUs = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07003619
3620 continue;
3621 }
Eric Tan39ec8d62018-07-24 09:49:29 -07003622 if ((mActiveTracks.isEmpty() && systemTime() > mStandbyTimeNs) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08003623 isSuspended()) {
3624 // put audio hardware into standby after short delay
3625 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003626
3627 threadLoop_standby();
3628
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07003629 // This is where we go into standby
3630 if (!mStandby) {
3631 LOG_AUDIO_STATE();
Andy Hungcf10d742020-04-28 15:38:24 -07003632 mThreadMetrics.logEndInterval();
3633 mStandby = true;
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07003634 }
Andy Hungd0979812019-02-21 15:51:44 -08003635 sendStatistics(false /* force */);
Eric Laurent81784c32012-11-19 14:55:58 -08003636 }
3637
Eric Tan39ec8d62018-07-24 09:49:29 -07003638 if (mActiveTracks.isEmpty() && mConfigEvents.isEmpty()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003639 // we're about to wait, flush the binder command buffer
3640 IPCThreadState::self()->flushCommands();
3641
3642 clearOutputTracks();
3643
3644 if (exitPending()) {
3645 break;
3646 }
3647
3648 releaseWakeLock_l();
3649 // wait until we have something to do...
3650 ALOGV("%s going to sleep", myName.string());
3651 mWaitWorkCV.wait(mLock);
3652 ALOGV("%s waking up", myName.string());
3653 acquireWakeLock_l();
3654
3655 mMixerStatus = MIXER_IDLE;
3656 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
3657 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003658 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003659 checkSilentMode_l();
3660
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003661 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3662 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003663 if (mType == MIXER) {
3664 sleepTimeShift = 0;
3665 }
3666
3667 continue;
3668 }
3669 }
Eric Laurent81784c32012-11-19 14:55:58 -08003670 // mMixerStatusIgnoringFastTracks is also updated internally
3671 mMixerStatus = prepareTracks_l(&tracksToRemove);
3672
Andy Hungdae27702016-10-31 14:01:16 -07003673 mActiveTracks.updatePowerState(this);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003674
Kevin Rocard069c2712018-03-29 19:09:14 -07003675 updateMetadata_l();
3676
Eric Laurent81784c32012-11-19 14:55:58 -08003677 // prevent any changes in effect chain list and in each effect chain
3678 // during mixing and effect process as the audio buffers could be deleted
3679 // or modified if an effect is created or deleted
3680 lockEffectChains_l(effectChains);
Andy Hung6e6a2e62019-04-30 16:38:41 -07003681
3682 // Determine which session to pick up haptic data.
3683 // This must be done under the same lock as prepareTracks_l().
jiabineb3bda02020-06-30 14:07:03 -07003684 // The haptic data from the effect is at a higher priority than the one from track.
Andy Hung6e6a2e62019-04-30 16:38:41 -07003685 // TODO: Write haptic data directly to sink buffer when mixing.
3686 if (mHapticChannelCount > 0 && effectChains.size() > 0) {
3687 for (const auto& track : mActiveTracks) {
jiabineb3bda02020-06-30 14:07:03 -07003688 sp<EffectChain> effectChain = getEffectChain_l(track->sessionId());
3689 if (effectChain != nullptr && effectChain->containsHapticGeneratingEffect_l()) {
3690 activeHapticSessionId = track->sessionId();
3691 break;
3692 }
Andy Hung6e6a2e62019-04-30 16:38:41 -07003693 if (track->getHapticPlaybackEnabled()) {
3694 activeHapticSessionId = track->sessionId();
3695 break;
3696 }
3697 }
3698 }
3699
Andy Hungc1646382019-04-30 16:12:10 -07003700 // Acquire a local copy of active tracks with lock (release w/o lock).
3701 //
3702 // Control methods on the track acquire the ThreadBase lock (e.g. start()
3703 // stop(), pause(), etc.), but the threadLoop is entitled to call audio
3704 // data / buffer methods on tracks from activeTracks without the ThreadBase lock.
3705 activeTracks.insert(activeTracks.end(), mActiveTracks.begin(), mActiveTracks.end());
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003706 } // mLock scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08003707
Eric Laurentbfb1b832013-01-07 09:53:42 -08003708 if (mBytesRemaining == 0) {
3709 mCurrentWriteLength = 0;
3710 if (mMixerStatus == MIXER_TRACKS_READY) {
3711 // threadLoop_mix() sets mCurrentWriteLength
3712 threadLoop_mix();
3713 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
3714 && (mMixerStatus != MIXER_DRAIN_ALL)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003715 // threadLoop_sleepTime sets mSleepTimeUs to 0 if data
Eric Laurentbfb1b832013-01-07 09:53:42 -08003716 // must be written to HAL
3717 threadLoop_sleepTime();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003718 if (mSleepTimeUs == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08003719 mCurrentWriteLength = mSinkBufferSize;
Andy Hungc1646382019-04-30 16:12:10 -07003720
3721 // Tally underrun frames as we are inserting 0s here.
3722 for (const auto& track : activeTracks) {
Andy Hunge2e830f2019-12-03 12:54:46 -08003723 if (track->mFillingUpStatus == Track::FS_ACTIVE
3724 && !track->isStopped()
3725 && !track->isPaused()
3726 && !track->isTerminated()) {
3727 ALOGV("%s: track(%d) %s underrun due to thread sleep of %zu frames",
3728 __func__, track->id(), track->getTrackStateAsString(),
3729 mNormalFrameCount);
Andy Hungc1646382019-04-30 16:12:10 -07003730 track->mAudioTrackServerProxy->tallyUnderrunFrames(mNormalFrameCount);
3731 }
3732 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003733 }
3734 }
Andy Hung98ef9782014-03-04 14:46:50 -08003735 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003736 // mMixerBuffer with data if mMixerBufferValid is true and mSleepTimeUs == 0.
Andy Hung98ef9782014-03-04 14:46:50 -08003737 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
3738 // or mSinkBuffer (if there are no effects).
3739 //
3740 // This is done pre-effects computation; if effects change to
3741 // support higher precision, this needs to move.
3742 //
3743 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003744 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08003745 if (mMixerBufferValid) {
3746 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
3747 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
3748
Andy Hung2ddee192015-12-18 17:34:44 -08003749 // mono blend occurs for mixer threads only (not direct or offloaded)
3750 // and is handled here if we're going directly to the sink.
3751 if (requireMonoBlend() && !mEffectBufferValid) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003752 mono_blend(mMixerBuffer, mMixerBufferFormat, mChannelCount, mNormalFrameCount,
3753 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003754 }
3755
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01003756 if (!hasFastMixer()) {
3757 // Balance must take effect after mono conversion.
3758 // We do it here if there is no FastMixer.
3759 // mBalance detects zero balance within the class for speed (not needed here).
3760 mBalance.setBalance(mMasterBalance.load());
3761 mBalance.process((float *)mMixerBuffer, mNormalFrameCount);
3762 }
3763
Andy Hung98ef9782014-03-04 14:46:50 -08003764 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
jiabin245cdd92018-12-07 17:55:15 -08003765 mNormalFrameCount * (mChannelCount + mHapticChannelCount));
3766
3767 // If we're going directly to the sink and there are haptic channels,
3768 // we should adjust channels as the sample data is partially interleaved
3769 // in this case.
3770 if (!mEffectBufferValid && mHapticChannelCount > 0) {
3771 adjust_channels_non_destructive(buffer, mChannelCount, buffer,
3772 mChannelCount + mHapticChannelCount,
3773 audio_bytes_per_sample(format),
3774 audio_bytes_per_frame(mChannelCount, format) * mNormalFrameCount);
3775 }
Andy Hung98ef9782014-03-04 14:46:50 -08003776 }
3777
Eric Laurentbfb1b832013-01-07 09:53:42 -08003778 mBytesRemaining = mCurrentWriteLength;
3779 if (isSuspended()) {
Andy Hung238fa3d2016-07-28 10:53:22 -07003780 // Simulate write to HAL when suspended (e.g. BT SCO phone call).
3781 mSleepTimeUs = suspendSleepTimeUs(); // assumes full buffer.
3782 const size_t framesRemaining = mBytesRemaining / mFrameSize;
3783 mBytesWritten += mBytesRemaining;
3784 mFramesWritten += framesRemaining;
3785 mSuspendedFrames += framesRemaining; // to adjust kernel HAL position
Eric Laurentbfb1b832013-01-07 09:53:42 -08003786 mBytesRemaining = 0;
3787 }
Eric Laurent81784c32012-11-19 14:55:58 -08003788
Eric Laurentbfb1b832013-01-07 09:53:42 -08003789 // only process effects if we're going to write
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003790 if (mSleepTimeUs == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003791 for (size_t i = 0; i < effectChains.size(); i ++) {
3792 effectChains[i]->process_l();
jiabin47affe52019-04-04 18:02:07 -07003793 // TODO: Write haptic data directly to sink buffer when mixing.
Andy Hung6e6a2e62019-04-30 16:38:41 -07003794 if (activeHapticSessionId != AUDIO_SESSION_NONE
3795 && activeHapticSessionId == effectChains[i]->sessionId()) {
jiabin47affe52019-04-04 18:02:07 -07003796 // Haptic data is active in this case, copy it directly from
3797 // in buffer to out buffer.
3798 const size_t audioBufferSize = mNormalFrameCount
3799 * audio_bytes_per_frame(mChannelCount, EFFECT_BUFFER_FORMAT);
3800 memcpy_by_audio_format(
3801 (uint8_t*)effectChains[i]->outBuffer() + audioBufferSize,
3802 EFFECT_BUFFER_FORMAT,
3803 (const uint8_t*)effectChains[i]->inBuffer() + audioBufferSize,
3804 EFFECT_BUFFER_FORMAT, mNormalFrameCount * mHapticChannelCount);
3805 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003806 }
Eric Laurent81784c32012-11-19 14:55:58 -08003807 }
3808 }
Eric Laurent59fe0102013-09-27 18:48:26 -07003809 // Process effect chains for offloaded thread even if no audio
3810 // was read from audio track: process only updates effect state
3811 // and thus does have to be synchronized with audio writes but may have
3812 // to be called while waiting for async write callback
3813 if (mType == OFFLOAD) {
3814 for (size_t i = 0; i < effectChains.size(); i ++) {
3815 effectChains[i]->process_l();
3816 }
3817 }
Eric Laurent81784c32012-11-19 14:55:58 -08003818
Andy Hung98ef9782014-03-04 14:46:50 -08003819 // Only if the Effects buffer is enabled and there is data in the
3820 // Effects buffer (buffer valid), we need to
3821 // copy into the sink buffer.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003822 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08003823 if (mEffectBufferValid) {
3824 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
Andy Hung2ddee192015-12-18 17:34:44 -08003825
3826 if (requireMonoBlend()) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003827 mono_blend(mEffectBuffer, mEffectBufferFormat, mChannelCount, mNormalFrameCount,
3828 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003829 }
3830
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01003831 if (!hasFastMixer()) {
3832 // Balance must take effect after mono conversion.
3833 // We do it here if there is no FastMixer.
3834 // mBalance detects zero balance within the class for speed (not needed here).
3835 mBalance.setBalance(mMasterBalance.load());
3836 mBalance.process((float *)mEffectBuffer, mNormalFrameCount);
3837 }
3838
Andy Hung98ef9782014-03-04 14:46:50 -08003839 memcpy_by_audio_format(mSinkBuffer, mFormat, mEffectBuffer, mEffectBufferFormat,
jiabin245cdd92018-12-07 17:55:15 -08003840 mNormalFrameCount * (mChannelCount + mHapticChannelCount));
3841 // The sample data is partially interleaved when haptic channels exist,
3842 // we need to adjust channels here.
3843 if (mHapticChannelCount > 0) {
3844 adjust_channels_non_destructive(mSinkBuffer, mChannelCount, mSinkBuffer,
3845 mChannelCount + mHapticChannelCount,
3846 audio_bytes_per_sample(mFormat),
3847 audio_bytes_per_frame(mChannelCount, mFormat) * mNormalFrameCount);
3848 }
Andy Hung98ef9782014-03-04 14:46:50 -08003849 }
3850
Eric Laurent81784c32012-11-19 14:55:58 -08003851 // enable changes in effect chain
3852 unlockEffectChains(effectChains);
3853
Eric Laurentbfb1b832013-01-07 09:53:42 -08003854 if (!waitingAsyncCallback()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003855 // mSleepTimeUs == 0 means we must write to audio hardware
3856 if (mSleepTimeUs == 0) {
Andy Hung08fb1742015-05-31 23:22:10 -07003857 ssize_t ret = 0;
Andy Hung446f4df2019-02-21 12:26:41 -08003858 // writePeriodNs is updated >= 0 when ret > 0.
3859 int64_t writePeriodNs = -1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003860 if (mBytesRemaining) {
Andy Hung69488c42016-05-16 18:43:33 -07003861 // FIXME rewrite to reduce number of system calls
Andy Hung446f4df2019-02-21 12:26:41 -08003862 const int64_t lastIoBeginNs = systemTime();
Andy Hung08fb1742015-05-31 23:22:10 -07003863 ret = threadLoop_write();
Andy Hung446f4df2019-02-21 12:26:41 -08003864 const int64_t lastIoEndNs = systemTime();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003865 if (ret < 0) {
3866 mBytesRemaining = 0;
Andy Hung446f4df2019-02-21 12:26:41 -08003867 } else if (ret > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003868 mBytesWritten += ret;
3869 mBytesRemaining -= ret;
Andy Hung446f4df2019-02-21 12:26:41 -08003870 const int64_t frames = ret / mFrameSize;
3871 mFramesWritten += frames;
3872
3873 writePeriodNs = lastIoEndNs - mLastIoEndNs;
3874 // process information relating to write time.
3875 if (audio_has_proportional_frames(mFormat)) {
3876 // we are in a continuous mixing cycle
3877 if (mMixerStatus == MIXER_TRACKS_READY &&
3878 loopCount == lastLoopCountWritten + 1) {
3879
3880 const double jitterMs =
3881 TimestampVerifier<int64_t, int64_t>::computeJitterMs(
3882 {frames, writePeriodNs},
3883 {0, 0} /* lastTimestamp */, mSampleRate);
3884 const double processMs =
3885 (lastIoBeginNs - mLastIoEndNs) * 1e-6;
3886
3887 Mutex::Autolock _l(mLock);
3888 mIoJitterMs.add(jitterMs);
3889 mProcessTimeMs.add(processMs);
3890 }
3891
3892 // write blocked detection
3893 const int64_t deltaWriteNs = lastIoEndNs - lastIoBeginNs;
3894 if (mType == MIXER && deltaWriteNs > maxPeriod) {
3895 mNumDelayedWrites++;
3896 if ((lastIoEndNs - lastWarning) > kWarningThrottleNs) {
3897 ATRACE_NAME("underrun");
3898 ALOGW("write blocked for %lld msecs, "
3899 "%d delayed writes, thread %d",
3900 (long long)deltaWriteNs / NANOS_PER_MILLISECOND,
3901 mNumDelayedWrites, mId);
3902 lastWarning = lastIoEndNs;
3903 }
3904 }
3905 }
3906 // update timing info.
3907 mLastIoBeginNs = lastIoBeginNs;
3908 mLastIoEndNs = lastIoEndNs;
3909 lastLoopCountWritten = loopCount;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003910 }
3911 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
3912 (mMixerStatus == MIXER_DRAIN_ALL)) {
3913 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08003914 }
Andy Hung08fb1742015-05-31 23:22:10 -07003915 if (mType == MIXER && !mStandby) {
Andy Hung08fb1742015-05-31 23:22:10 -07003916
3917 if (mThreadThrottle
3918 && mMixerStatus == MIXER_TRACKS_READY // we are mixing (active tracks)
Andy Hung446f4df2019-02-21 12:26:41 -08003919 && writePeriodNs > 0) { // we have write period info
Andy Hung08fb1742015-05-31 23:22:10 -07003920 // Limit MixerThread data processing to no more than twice the
3921 // expected processing rate.
3922 //
3923 // This helps prevent underruns with NuPlayer and other applications
3924 // which may set up buffers that are close to the minimum size, or use
3925 // deep buffers, and rely on a double-buffering sleep strategy to fill.
3926 //
3927 // The throttle smooths out sudden large data drains from the device,
3928 // e.g. when it comes out of standby, which often causes problems with
3929 // (1) mixer threads without a fast mixer (which has its own warm-up)
3930 // (2) minimum buffer sized tracks (even if the track is full,
3931 // the app won't fill fast enough to handle the sudden draw).
Haynes Mathew Georgef92b2172016-05-09 11:34:15 -07003932 //
3933 // Total time spent in last processing cycle equals time spent in
3934 // 1. threadLoop_write, as well as time spent in
3935 // 2. threadLoop_mix (significant for heavy mixing, especially
3936 // on low tier processors)
Andy Hung08fb1742015-05-31 23:22:10 -07003937
Andy Hung446f4df2019-02-21 12:26:41 -08003938 // it's OK if deltaMs is an overestimate.
3939
3940 const int32_t deltaMs = writePeriodNs / NANOS_PER_MILLISECOND;
Ivan Lozanoe02bc542017-10-26 09:51:54 -07003941
Ivan Lozanoea04d392017-11-07 14:37:07 -08003942 const int32_t throttleMs = (int32_t)mHalfBufferMs - deltaMs;
Andy Hung08fb1742015-05-31 23:22:10 -07003943 if ((signed)mHalfBufferMs >= throttleMs && throttleMs > 0) {
Andy Hungcf10d742020-04-28 15:38:24 -07003944 mThreadMetrics.logThrottleMs((double)throttleMs);
Andy Hungb68f5eb2019-12-03 16:49:17 -08003945
Andy Hung08fb1742015-05-31 23:22:10 -07003946 usleep(throttleMs * 1000);
Andy Hung40eb1a12015-06-18 13:42:02 -07003947 // notify of throttle start on verbose log
3948 ALOGV_IF(mThreadThrottleEndMs == mThreadThrottleTimeMs,
3949 "mixer(%p) throttle begin:"
3950 " ret(%zd) deltaMs(%d) requires sleep %d ms",
Andy Hung08fb1742015-05-31 23:22:10 -07003951 this, ret, deltaMs, throttleMs);
Andy Hung40eb1a12015-06-18 13:42:02 -07003952 mThreadThrottleTimeMs += throttleMs;
Andy Hung0a31ddd2016-07-06 19:10:29 -07003953 // Throttle must be attributed to the previous mixer loop's write time
3954 // to allow back-to-back throttling.
Andy Hung446f4df2019-02-21 12:26:41 -08003955 // This also ensures proper timing statistics.
3956 mLastIoEndNs = systemTime(); // we fetch the write end time again.
Andy Hung40eb1a12015-06-18 13:42:02 -07003957 } else {
3958 uint32_t diff = mThreadThrottleTimeMs - mThreadThrottleEndMs;
3959 if (diff > 0) {
3960 // notify of throttle end on debug log
Andy Hung3ea004d2016-05-05 16:48:37 -07003961 // but prevent spamming for bluetooth
jiabinc52b1ff2019-10-31 17:20:42 -07003962 ALOGD_IF(!isSingleDeviceType(
3963 outDeviceTypes(), audio_is_a2dp_out_device) &&
3964 !isSingleDeviceType(
3965 outDeviceTypes(), audio_is_hearing_aid_out_device),
Andy Hung3ea004d2016-05-05 16:48:37 -07003966 "mixer(%p) throttle end: throttle time(%u)", this, diff);
Andy Hung40eb1a12015-06-18 13:42:02 -07003967 mThreadThrottleEndMs = mThreadThrottleTimeMs;
3968 }
Andy Hung08fb1742015-05-31 23:22:10 -07003969 }
3970 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003971 }
Eric Laurent81784c32012-11-19 14:55:58 -08003972
Eric Laurentbfb1b832013-01-07 09:53:42 -08003973 } else {
Glenn Kastene7754022014-10-31 12:11:26 -07003974 ATRACE_BEGIN("sleep");
Eric Laurente93cc032016-05-05 10:15:10 -07003975 Mutex::Autolock _l(mLock);
rago1bb90822017-05-02 18:31:48 -07003976 // suspended requires accurate metering of sleep time.
3977 if (isSuspended()) {
3978 // advance by expected sleepTime
3979 timeLoopNextNs += microseconds((nsecs_t)mSleepTimeUs);
3980 const nsecs_t nowNs = systemTime();
3981
3982 // compute expected next time vs current time.
3983 // (negative deltas are treated as delays).
3984 nsecs_t deltaNs = timeLoopNextNs - nowNs;
3985 if (deltaNs < -kMaxNextBufferDelayNs) {
3986 // Delays longer than the max allowed trigger a reset.
3987 ALOGV("DelayNs: %lld, resetting timeLoopNextNs", (long long) deltaNs);
3988 deltaNs = microseconds((nsecs_t)mSleepTimeUs);
3989 timeLoopNextNs = nowNs + deltaNs;
3990 } else if (deltaNs < 0) {
3991 // Delays within the max delay allowed: zero the delta/sleepTime
3992 // to help the system catch up in the next iteration(s)
3993 ALOGV("DelayNs: %lld, catching-up", (long long) deltaNs);
3994 deltaNs = 0;
3995 }
3996 // update sleep time (which is >= 0)
3997 mSleepTimeUs = deltaNs / 1000;
3998 }
Eric Laurente93cc032016-05-05 10:15:10 -07003999 if (!mSignalPending && mConfigEvents.isEmpty() && !exitPending()) {
4000 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)mSleepTimeUs));
Eric Laurent51716182016-02-29 18:00:56 -08004001 }
Glenn Kastene7754022014-10-31 12:11:26 -07004002 ATRACE_END();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004003 }
Eric Laurent81784c32012-11-19 14:55:58 -08004004 }
4005
4006 // Finally let go of removed track(s), without the lock held
4007 // since we can't guarantee the destructors won't acquire that
4008 // same lock. This will also mutate and push a new fast mixer state.
4009 threadLoop_removeTracks(tracksToRemove);
4010 tracksToRemove.clear();
4011
4012 // FIXME I don't understand the need for this here;
4013 // it was in the original code but maybe the
4014 // assignment in saveOutputTracks() makes this unnecessary?
4015 clearOutputTracks();
4016
4017 // Effect chains will be actually deleted here if they were removed from
4018 // mEffectChains list during mixing or effects processing
4019 effectChains.clear();
4020
4021 // FIXME Note that the above .clear() is no longer necessary since effectChains
4022 // is now local to this block, but will keep it for now (at least until merge done).
4023 }
4024
Eric Laurentbfb1b832013-01-07 09:53:42 -08004025 threadLoop_exit();
4026
Eric Laurentcf817a22014-08-04 20:36:31 -07004027 if (!mStandby) {
4028 threadLoop_standby();
4029 mStandby = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004030 }
4031
4032 releaseWakeLock();
4033
4034 ALOGV("Thread %p type %d exiting", this, mType);
4035 return false;
4036}
4037
Dean Wheatley12473e92021-03-18 23:00:55 +11004038void AudioFlinger::PlaybackThread::collectTimestamps_l()
4039{
4040 // Collect timestamp statistics for the Playback Thread types that support it.
4041 if (mType != MIXER
4042 && mType != DUPLICATING
4043 && mType != DIRECT
4044 && mType != OFFLOAD) {
4045 return;
4046 }
4047 if (mStandby) {
4048 mTimestampVerifier.discontinuity(discontinuityForStandbyOrFlush());
4049 return;
4050 } else if (mHwPaused) {
4051 mTimestampVerifier.discontinuity(mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS);
4052 return;
4053 }
4054
4055 // Gather the framesReleased counters for all active tracks,
4056 // and associate with the sink frames written out. We need
4057 // this to convert the sink timestamp to the track timestamp.
4058 bool kernelLocationUpdate = false;
4059 ExtendedTimestamp timestamp; // use private copy to fetch
4060
4061 // Always query HAL timestamp and update timestamp verifier. In standby or pause,
4062 // HAL may be draining some small duration buffered data for fade out.
4063 if (threadloop_getHalTimestamp_l(&timestamp) == OK) {
4064 mTimestampVerifier.add(timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL],
4065 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4066 mSampleRate);
4067
4068 if (isTimestampCorrectionEnabled()) {
4069 ALOGVV("TS_BEFORE: %d %lld %lld", id(),
4070 (long long)timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4071 (long long)timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]);
4072 auto correctedTimestamp = mTimestampVerifier.getLastCorrectedTimestamp();
4073 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4074 = correctedTimestamp.mFrames;
4075 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]
4076 = correctedTimestamp.mTimeNs;
4077 ALOGVV("TS_AFTER: %d %lld %lld", id(),
4078 (long long)timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4079 (long long)timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]);
4080
4081 // Note: Downstream latency only added if timestamp correction enabled.
4082 if (mDownstreamLatencyStatMs.getN() > 0) { // we have latency info.
4083 const int64_t newPosition =
4084 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4085 - int64_t(mDownstreamLatencyStatMs.getMean() * mSampleRate * 1e-3);
4086 // prevent retrograde
4087 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = max(
4088 newPosition,
4089 (mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4090 - mSuspendedFrames));
4091 }
4092 }
4093
4094 // We always fetch the timestamp here because often the downstream
4095 // sink will block while writing.
4096
4097 // We keep track of the last valid kernel position in case we are in underrun
4098 // and the normal mixer period is the same as the fast mixer period, or there
4099 // is some error from the HAL.
4100 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
4101 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
4102 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
4103 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
4104 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4105
4106 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
4107 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER];
4108 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
4109 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER];
4110 }
4111
4112 if (timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
4113 kernelLocationUpdate = true;
4114 } else {
4115 ALOGVV("getTimestamp error - no valid kernel position");
4116 }
4117
4118 // copy over kernel info
4119 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] =
4120 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4121 + mSuspendedFrames; // add frames discarded when suspended
4122 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] =
4123 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4124 } else {
4125 mTimestampVerifier.error();
4126 }
4127
4128 // mFramesWritten for non-offloaded tracks are contiguous
4129 // even after standby() is called. This is useful for the track frame
4130 // to sink frame mapping.
4131 bool serverLocationUpdate = false;
4132 if (mFramesWritten != mLastFramesWritten) {
4133 serverLocationUpdate = true;
4134 mLastFramesWritten = mFramesWritten;
4135 }
4136 // Only update timestamps if there is a meaningful change.
4137 // Either the kernel timestamp must be valid or we have written something.
4138 if (kernelLocationUpdate || serverLocationUpdate) {
4139 if (serverLocationUpdate) {
4140 // use the time before we called the HAL write - it is a bit more accurate
4141 // to when the server last read data than the current time here.
4142 //
4143 // If we haven't written anything, mLastIoBeginNs will be -1
4144 // and we use systemTime().
4145 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] = mFramesWritten;
4146 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = mLastIoBeginNs == -1
4147 ? systemTime() : mLastIoBeginNs;
4148 }
4149
4150 for (const sp<Track> &t : mActiveTracks) {
4151 if (!t->isFastTrack()) {
4152 t->updateTrackFrameInfo(
4153 t->mAudioTrackServerProxy->framesReleased(),
4154 mFramesWritten,
4155 mSampleRate,
4156 mTimestamp);
4157 }
4158 }
4159 }
4160
4161 if (audio_has_proportional_frames(mFormat)) {
4162 const double latencyMs = mTimestamp.getOutputServerLatencyMs(mSampleRate);
4163 if (latencyMs != 0.) { // note 0. means timestamp is empty.
4164 mLatencyMs.add(latencyMs);
4165 }
4166 }
4167#if 0
4168 // logFormat example
4169 if (z % 100 == 0) {
4170 timespec ts;
4171 clock_gettime(CLOCK_MONOTONIC, &ts);
4172 LOGT("This is an integer %d, this is a float %f, this is my "
4173 "pid %p %% %s %t", 42, 3.14, "and this is a timestamp", ts);
4174 LOGT("A deceptive null-terminated string %\0");
4175 }
4176 ++z;
4177#endif
4178}
4179
Eric Laurentbfb1b832013-01-07 09:53:42 -08004180// removeTracks_l() must be called with ThreadBase::mLock held
4181void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
4182{
Andy Hungfe726a62018-09-27 15:17:25 -07004183 for (const auto& track : tracksToRemove) {
4184 mActiveTracks.remove(track);
4185 ALOGV("%s(%d): removing track on session %d", __func__, track->id(), track->sessionId());
4186 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
4187 if (chain != 0) {
4188 ALOGV("%s(%d): stopping track on chain %p for session Id: %d",
4189 __func__, track->id(), chain.get(), track->sessionId());
4190 chain->decActiveTrackCnt();
4191 }
4192 // If an external client track, inform APM we're no longer active, and remove if needed.
4193 // We do this under lock so that the state is consistent if the Track is destroyed.
4194 if (track->isExternalTrack()) {
4195 AudioSystem::stopOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08004196 if (track->isTerminated()) {
Andy Hungfe726a62018-09-27 15:17:25 -07004197 AudioSystem::releaseOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08004198 }
4199 }
Andy Hungfe726a62018-09-27 15:17:25 -07004200 if (track->isTerminated()) {
4201 // remove from our tracks vector
4202 removeTrack_l(track);
4203 }
jiabineb3bda02020-06-30 14:07:03 -07004204 if (mHapticChannelCount > 0 &&
4205 ((track->channelMask() & AUDIO_CHANNEL_HAPTIC_ALL) != AUDIO_CHANNEL_NONE
4206 || (chain != nullptr && chain->containsHapticGeneratingEffect_l()))) {
jiabin57303cc2018-12-18 15:45:57 -08004207 mLock.unlock();
4208 // Unlock due to VibratorService will lock for this call and will
4209 // call Tracks.mute/unmute which also require thread's lock.
4210 AudioFlinger::onExternalVibrationStop(track->getExternalVibration());
4211 mLock.lock();
jiabine70bc7f2020-06-30 22:07:55 -07004212
4213 // When the track is stop, set the haptic intensity as MUTE
4214 // for the HapticGenerator effect.
4215 if (chain != nullptr) {
4216 chain->setHapticIntensity_l(track->id(), static_cast<int>(os::HapticScale::MUTE));
4217 }
jiabin245cdd92018-12-07 17:55:15 -08004218 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004219 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004220}
Eric Laurent81784c32012-11-19 14:55:58 -08004221
Eric Laurentaccc1472013-09-20 09:36:34 -07004222status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
4223{
4224 if (mNormalSink != 0) {
Andy Hung818e7a32016-02-16 18:08:07 -08004225 ExtendedTimestamp ets;
4226 status_t status = mNormalSink->getTimestamp(ets);
4227 if (status == NO_ERROR) {
4228 status = ets.getBestTimestamp(&timestamp);
4229 }
4230 return status;
Eric Laurentaccc1472013-09-20 09:36:34 -07004231 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004232 if ((mType == OFFLOAD || mType == DIRECT) && mOutput != NULL) {
Dean Wheatley12473e92021-03-18 23:00:55 +11004233 collectTimestamps_l();
4234 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] <= 0) {
4235 return INVALID_OPERATION;
Eric Laurentaccc1472013-09-20 09:36:34 -07004236 }
Dean Wheatley12473e92021-03-18 23:00:55 +11004237 timestamp.mPosition = mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
4238 const int64_t timeNs = mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4239 timestamp.mTime.tv_sec = timeNs / NANOS_PER_SECOND;
4240 timestamp.mTime.tv_nsec = timeNs - (timestamp.mTime.tv_sec * NANOS_PER_SECOND);
4241 return NO_ERROR;
Eric Laurentaccc1472013-09-20 09:36:34 -07004242 }
4243 return INVALID_OPERATION;
4244}
Eric Laurent1c333e22014-05-20 10:48:17 -07004245
Eric Laurenteab90452019-06-24 15:17:46 -07004246// For dedicated VoIP outputs, let the HAL apply the stream volume. Track volume is
4247// still applied by the mixer.
4248// All tracks attached to a mixer with flag VOIP_RX are tied to the same
4249// stream type STREAM_VOICE_CALL so this will only change the HAL volume once even
4250// if more than one track are active
4251status_t AudioFlinger::PlaybackThread::handleVoipVolume_l(float *volume)
4252{
4253 status_t result = NO_ERROR;
4254 if ((mOutput->flags & AUDIO_OUTPUT_FLAG_VOIP_RX) != 0) {
4255 if (*volume != mLeftVolFloat) {
4256 result = mOutput->stream->setVolume(*volume, *volume);
4257 ALOGE_IF(result != OK,
4258 "Error when setting output stream volume: %d", result);
4259 if (result == NO_ERROR) {
4260 mLeftVolFloat = *volume;
4261 }
4262 }
4263 // if stream volume was successfully sent to the HAL, mLeftVolFloat == v here and we
4264 // remove stream volume contribution from software volume.
4265 if (mLeftVolFloat == *volume) {
4266 *volume = 1.0f;
4267 }
4268 }
4269 return result;
4270}
4271
Eric Laurent054d9d32015-04-24 08:48:48 -07004272status_t AudioFlinger::MixerThread::createAudioPatch_l(const struct audio_patch *patch,
4273 audio_patch_handle_t *handle)
4274{
Andy Hungf60abce2016-08-26 11:37:54 -07004275 status_t status;
4276 if (property_get_bool("af.patch_park", false /* default_value */)) {
4277 // Park FastMixer to avoid potential DOS issues with writing to the HAL
4278 // or if HAL does not properly lock against access.
4279 AutoPark<FastMixer> park(mFastMixer);
4280 status = PlaybackThread::createAudioPatch_l(patch, handle);
4281 } else {
4282 status = PlaybackThread::createAudioPatch_l(patch, handle);
4283 }
Eric Laurent054d9d32015-04-24 08:48:48 -07004284 return status;
4285}
4286
Eric Laurent1c333e22014-05-20 10:48:17 -07004287status_t AudioFlinger::PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
4288 audio_patch_handle_t *handle)
4289{
4290 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07004291
4292 // store new device and send to effects
4293 audio_devices_t type = AUDIO_DEVICE_NONE;
jiabinc52b1ff2019-10-31 17:20:42 -07004294 AudioDeviceTypeAddrVector deviceTypeAddrs;
Eric Laurent054d9d32015-04-24 08:48:48 -07004295 for (unsigned int i = 0; i < patch->num_sinks; i++) {
jiabinc52b1ff2019-10-31 17:20:42 -07004296 LOG_ALWAYS_FATAL_IF(popcount(patch->sinks[i].ext.device.type) > 1
4297 && !mOutput->audioHwDev->supportsAudioPatches(),
4298 "Enumerated device type(%#x) must not be used "
4299 "as it does not support audio patches",
4300 patch->sinks[i].ext.device.type);
Mikhail Naganov55773032020-10-01 15:08:13 -07004301 type = static_cast<audio_devices_t>(type | patch->sinks[i].ext.device.type);
jiabinc52b1ff2019-10-31 17:20:42 -07004302 deviceTypeAddrs.push_back(AudioDeviceTypeAddr(patch->sinks[i].ext.device.type,
4303 patch->sinks[i].ext.device.address));
Eric Laurent054d9d32015-04-24 08:48:48 -07004304 }
4305
François Gaffie0c280aa2018-07-25 10:02:15 +02004306 audio_port_handle_t sinkPortId = patch->sinks[0].id;
Eric Laurent054d9d32015-04-24 08:48:48 -07004307#ifdef ADD_BATTERY_DATA
4308 // when changing the audio output device, call addBatteryData to notify
4309 // the change
jiabinc52b1ff2019-10-31 17:20:42 -07004310 if (outDeviceTypes() != deviceTypes) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004311 uint32_t params = 0;
4312 // check whether speaker is on
jiabinc52b1ff2019-10-31 17:20:42 -07004313 if (deviceTypes.count(AUDIO_DEVICE_OUT_SPEAKER) > 0) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004314 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent1c333e22014-05-20 10:48:17 -07004315 }
4316
Eric Laurent054d9d32015-04-24 08:48:48 -07004317 // check if any other device (except speaker) is on
jiabinc52b1ff2019-10-31 17:20:42 -07004318 if (!isSingleDeviceType(deviceTypes, AUDIO_DEVICE_OUT_SPEAKER)) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004319 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
4320 }
4321
4322 if (params != 0) {
4323 addBatteryData(params);
4324 }
4325 }
4326#endif
4327
4328 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08004329 mEffectChains[i]->setDevices_l(deviceTypeAddrs);
Eric Laurent054d9d32015-04-24 08:48:48 -07004330 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07004331
jiabinc52b1ff2019-10-31 17:20:42 -07004332 // mPatch.num_sinks is not set when the thread is created so that
4333 // the first patch creation triggers an ioConfigChanged callback
4334 bool configChanged = (mPatch.num_sinks == 0) ||
4335 (mPatch.sinks[0].id != sinkPortId);
Eric Laurent296fb132015-05-01 11:38:42 -07004336 mPatch = *patch;
jiabinc52b1ff2019-10-31 17:20:42 -07004337 mOutDeviceTypeAddrs = deviceTypeAddrs;
jiabin0a957d32020-04-29 10:56:20 -07004338 checkSilentMode_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07004339
Mikhail Naganov9ee05402016-10-13 15:58:17 -07004340 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07004341 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
4342 status = hwDevice->createAudioPatch(patch->num_sources,
4343 patch->sources,
4344 patch->num_sinks,
4345 patch->sinks,
4346 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07004347 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07004348 char *address;
4349 if (strcmp(patch->sinks[0].ext.device.address, "") != 0) {
4350 //FIXME: we only support address on first sink with HAL version < 3.0
4351 address = audio_device_address_to_parameter(
4352 patch->sinks[0].ext.device.type,
4353 patch->sinks[0].ext.device.address);
4354 } else {
4355 address = (char *)calloc(1, 1);
4356 }
4357 AudioParameter param = AudioParameter(String8(address));
4358 free(address);
Mikhail Naganov00260b52016-10-13 12:54:24 -07004359 param.addInt(String8(AudioParameter::keyRouting), (int)type);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004360 status = mOutput->stream->setParameters(param.toString());
Eric Laurent054d9d32015-04-24 08:48:48 -07004361 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07004362 }
Andy Hungc2b11cb2020-04-22 09:04:01 -07004363 const std::string patchSinksAsString = patchSinksToString(patch);
Andy Hungcf10d742020-04-28 15:38:24 -07004364
4365 mThreadMetrics.logEndInterval();
Andy Hungea840382020-05-05 21:50:17 -07004366 mThreadMetrics.logCreatePatch(/* inDevices */ {}, patchSinksAsString);
Andy Hungcf10d742020-04-28 15:38:24 -07004367 mThreadMetrics.logBeginInterval();
Andy Hungc2b11cb2020-04-22 09:04:01 -07004368 // also dispatch to active AudioTracks for MediaMetrics
4369 for (const auto &track : mActiveTracks) {
4370 track->logEndInterval();
4371 track->logBeginInterval(patchSinksAsString);
4372 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08004373
Eric Laurente8726fe2015-06-26 09:39:24 -07004374 if (configChanged) {
4375 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
4376 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004377 return status;
4378}
4379
Eric Laurent054d9d32015-04-24 08:48:48 -07004380status_t AudioFlinger::MixerThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
4381{
Andy Hungf60abce2016-08-26 11:37:54 -07004382 status_t status;
4383 if (property_get_bool("af.patch_park", false /* default_value */)) {
4384 // Park FastMixer to avoid potential DOS issues with writing to the HAL
4385 // or if HAL does not properly lock against access.
4386 AutoPark<FastMixer> park(mFastMixer);
4387 status = PlaybackThread::releaseAudioPatch_l(handle);
4388 } else {
4389 status = PlaybackThread::releaseAudioPatch_l(handle);
4390 }
Eric Laurent054d9d32015-04-24 08:48:48 -07004391 return status;
4392}
4393
Eric Laurent1c333e22014-05-20 10:48:17 -07004394status_t AudioFlinger::PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
4395{
4396 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07004397
jiabinc52b1ff2019-10-31 17:20:42 -07004398 mPatch = audio_patch{};
4399 mOutDeviceTypeAddrs.clear();
Eric Laurent054d9d32015-04-24 08:48:48 -07004400
Mikhail Naganov9ee05402016-10-13 15:58:17 -07004401 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07004402 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
4403 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07004404 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07004405 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07004406 param.addInt(String8(AudioParameter::keyRouting), 0);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004407 status = mOutput->stream->setParameters(param.toString());
Eric Laurent1c333e22014-05-20 10:48:17 -07004408 }
4409 return status;
4410}
4411
Eric Laurent83b88082014-06-20 18:31:16 -07004412void AudioFlinger::PlaybackThread::addPatchTrack(const sp<PatchTrack>& track)
4413{
4414 Mutex::Autolock _l(mLock);
4415 mTracks.add(track);
4416}
4417
4418void AudioFlinger::PlaybackThread::deletePatchTrack(const sp<PatchTrack>& track)
4419{
4420 Mutex::Autolock _l(mLock);
4421 destroyTrack_l(track);
4422}
4423
Mikhail Naganovdc769682018-05-04 15:34:08 -07004424void AudioFlinger::PlaybackThread::toAudioPortConfig(struct audio_port_config *config)
Eric Laurent83b88082014-06-20 18:31:16 -07004425{
Mikhail Naganovdc769682018-05-04 15:34:08 -07004426 ThreadBase::toAudioPortConfig(config);
Eric Laurent83b88082014-06-20 18:31:16 -07004427 config->role = AUDIO_PORT_ROLE_SOURCE;
4428 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
4429 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07004430 if (mOutput && mOutput->flags != AUDIO_OUTPUT_FLAG_NONE) {
4431 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
4432 config->flags.output = mOutput->flags;
4433 }
Eric Laurent83b88082014-06-20 18:31:16 -07004434}
4435
Eric Laurent81784c32012-11-19 14:55:58 -08004436// ----------------------------------------------------------------------------
4437
4438AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
jiabinc52b1ff2019-10-31 17:20:42 -07004439 audio_io_handle_t id, bool systemReady, type_t type)
4440 : PlaybackThread(audioFlinger, output, id, type, systemReady),
Eric Laurent81784c32012-11-19 14:55:58 -08004441 // mAudioMixer below
4442 // mFastMixer below
Andy Hung2ddee192015-12-18 17:34:44 -08004443 mFastMixerFutex(0),
4444 mMasterMono(false)
Eric Laurent81784c32012-11-19 14:55:58 -08004445 // mOutputSink below
4446 // mPipeSink below
4447 // mNormalSink below
4448{
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01004449 setMasterBalance(audioFlinger->getMasterBalance_l());
jiabinc52b1ff2019-10-31 17:20:42 -07004450 ALOGV("MixerThread() id=%d type=%d", id, type);
Glenn Kasten49f36ba2017-12-06 13:02:02 -08004451 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%#x, mFrameSize=%zu, "
Glenn Kastenc42e9b42016-03-21 11:35:03 -07004452 "mFrameCount=%zu, mNormalFrameCount=%zu",
Eric Laurent81784c32012-11-19 14:55:58 -08004453 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
4454 mNormalFrameCount);
4455 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
4456
Andy Hungfbfc3952015-01-15 13:33:51 -08004457 if (type == DUPLICATING) {
4458 // The Duplicating thread uses the AudioMixer and delivers data to OutputTracks
4459 // (downstream MixerThreads) in DuplicatingThread::threadLoop_write().
4460 // Do not create or use mFastMixer, mOutputSink, mPipeSink, or mNormalSink.
4461 return;
4462 }
Eric Laurent81784c32012-11-19 14:55:58 -08004463 // create an NBAIO sink for the HAL output stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07004464 mOutputSink = new AudioStreamOutSink(output->stream);
Eric Laurent81784c32012-11-19 14:55:58 -08004465 size_t numCounterOffers = 0;
jiabin245cdd92018-12-07 17:55:15 -08004466 const NBAIO_Format offers[1] = {Format_from_SR_C(
4467 mSampleRate, mChannelCount + mHapticChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07004468#if !LOG_NDEBUG
4469 ssize_t index =
4470#else
4471 (void)
4472#endif
4473 mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08004474 ALOG_ASSERT(index == 0);
4475
4476 // initialize fast mixer depending on configuration
4477 bool initFastMixer;
4478 switch (kUseFastMixer) {
4479 case FastMixer_Never:
4480 initFastMixer = false;
4481 break;
4482 case FastMixer_Always:
4483 initFastMixer = true;
4484 break;
4485 case FastMixer_Static:
4486 case FastMixer_Dynamic:
Andy Hungfda69402017-02-15 14:33:12 -08004487 // FastMixer was designed to operate with a HAL that pulls at a regular rate,
4488 // where the period is less than an experimentally determined threshold that can be
4489 // scheduled reliably with CFS. However, the BT A2DP HAL is
4490 // bursty (does not pull at a regular rate) and so cannot operate with FastMixer.
4491 initFastMixer = mFrameCount < mNormalFrameCount
jiabinc52b1ff2019-10-31 17:20:42 -07004492 && Intersection(outDeviceTypes(), getAudioDeviceOutAllA2dpSet()).empty();
Eric Laurent81784c32012-11-19 14:55:58 -08004493 break;
4494 }
Andy Hungfda69402017-02-15 14:33:12 -08004495 ALOGW_IF(initFastMixer == false && mFrameCount < mNormalFrameCount,
4496 "FastMixer is preferred for this sink as frameCount %zu is less than threshold %zu",
4497 mFrameCount, mNormalFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08004498 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07004499 audio_format_t fastMixerFormat;
4500 if (mMixerBufferEnabled && mEffectBufferEnabled) {
4501 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
4502 } else {
4503 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
4504 }
4505 if (mFormat != fastMixerFormat) {
4506 // change our Sink format to accept our intermediate precision
4507 mFormat = fastMixerFormat;
4508 free(mSinkBuffer);
jiabin245cdd92018-12-07 17:55:15 -08004509 mFrameSize = audio_bytes_per_frame(mChannelCount + mHapticChannelCount, mFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07004510 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
4511 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
4512 }
Eric Laurent81784c32012-11-19 14:55:58 -08004513
4514 // create a MonoPipe to connect our submix to FastMixer
4515 NBAIO_Format format = mOutputSink->format();
Andy Hung8946a282018-04-19 20:04:56 -07004516
Andy Hung1258c1a2014-05-23 21:22:17 -07004517 // adjust format to match that of the Fast Mixer
Glenn Kasten49f36ba2017-12-06 13:02:02 -08004518 ALOGV("format changed from %#x to %#x", format.mFormat, fastMixerFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07004519 format.mFormat = fastMixerFormat;
4520 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
4521
Eric Laurent81784c32012-11-19 14:55:58 -08004522 // This pipe depth compensates for scheduling latency of the normal mixer thread.
4523 // When it wakes up after a maximum latency, it runs a few cycles quickly before
4524 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
4525 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
4526 const NBAIO_Format offers[1] = {format};
4527 size_t numCounterOffers = 0;
Andy Hung8946a282018-04-19 20:04:56 -07004528#if !LOG_NDEBUG
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07004529 ssize_t index =
4530#else
4531 (void)
4532#endif
4533 monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08004534 ALOG_ASSERT(index == 0);
4535 monoPipe->setAvgFrames((mScreenState & 1) ?
4536 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
4537 mPipeSink = monoPipe;
4538
Eric Laurent81784c32012-11-19 14:55:58 -08004539 // create fast mixer and configure it initially with just one fast track for our submix
Andy Hung8946a282018-04-19 20:04:56 -07004540 mFastMixer = new FastMixer(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08004541 FastMixerStateQueue *sq = mFastMixer->sq();
4542#ifdef STATE_QUEUE_DUMP
4543 sq->setObserverDump(&mStateQueueObserverDump);
4544 sq->setMutatorDump(&mStateQueueMutatorDump);
4545#endif
4546 FastMixerState *state = sq->begin();
4547 FastTrack *fastTrack = &state->mFastTracks[0];
4548 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
4549 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
4550 fastTrack->mVolumeProvider = NULL;
Mikhail Naganov55773032020-10-01 15:08:13 -07004551 fastTrack->mChannelMask = static_cast<audio_channel_mask_t>(
4552 mChannelMask | mHapticChannelMask); // mPipeSink channel mask for
4553 // audio to FastMixer
Andy Hunge8a1ced2014-05-09 15:02:21 -07004554 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
jiabin245cdd92018-12-07 17:55:15 -08004555 fastTrack->mHapticPlaybackEnabled = mHapticChannelMask != AUDIO_CHANNEL_NONE;
jiabine70bc7f2020-06-30 22:07:55 -07004556 fastTrack->mHapticIntensity = os::HapticScale::NONE;
Eric Laurent81784c32012-11-19 14:55:58 -08004557 fastTrack->mGeneration++;
4558 state->mFastTracksGen++;
4559 state->mTrackMask = 1;
4560 // fast mixer will use the HAL output sink
4561 state->mOutputSink = mOutputSink.get();
4562 state->mOutputSinkGen++;
4563 state->mFrameCount = mFrameCount;
jiabin245cdd92018-12-07 17:55:15 -08004564 // specify sink channel mask when haptic channel mask present as it can not
4565 // be calculated directly from channel count
4566 state->mSinkChannelMask = mHapticChannelMask == AUDIO_CHANNEL_NONE
Mikhail Naganov55773032020-10-01 15:08:13 -07004567 ? AUDIO_CHANNEL_NONE
4568 : static_cast<audio_channel_mask_t>(mChannelMask | mHapticChannelMask);
Eric Laurent81784c32012-11-19 14:55:58 -08004569 state->mCommand = FastMixerState::COLD_IDLE;
4570 // already done in constructor initialization list
4571 //mFastMixerFutex = 0;
4572 state->mColdFutexAddr = &mFastMixerFutex;
4573 state->mColdGen++;
4574 state->mDumpState = &mFastMixerDumpState;
Glenn Kasten9e58b552013-01-18 15:09:48 -08004575 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
4576 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08004577 sq->end();
4578 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
4579
Eric Tan0513b5d2018-09-17 10:32:48 -07004580 NBLog::thread_info_t info;
4581 info.id = mId;
4582 info.type = NBLog::FASTMIXER;
4583 mFastMixerNBLogWriter->log<NBLog::EVENT_THREAD_INFO>(info);
4584
Eric Laurent81784c32012-11-19 14:55:58 -08004585 // start the fast mixer
4586 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
4587 pid_t tid = mFastMixer->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07004588 sendPrioConfigEvent(getpid(), tid, kPriorityFastMixer, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08004589 stream()->setHalThreadPriority(kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08004590
4591#ifdef AUDIO_WATCHDOG
4592 // create and start the watchdog
4593 mAudioWatchdog = new AudioWatchdog();
4594 mAudioWatchdog->setDump(&mAudioWatchdogDump);
4595 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
4596 tid = mAudioWatchdog->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07004597 sendPrioConfigEvent(getpid(), tid, kPriorityFastMixer, false /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08004598#endif
Andy Hung8946a282018-04-19 20:04:56 -07004599 } else {
4600#ifdef TEE_SINK
4601 // Only use the MixerThread tee if there is no FastMixer.
4602 mTee.set(mOutputSink->format(), NBAIO_Tee::TEE_FLAG_OUTPUT_THREAD);
4603 mTee.setId(std::string("_") + std::to_string(mId) + "_M");
4604#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004605 }
4606
4607 switch (kUseFastMixer) {
4608 case FastMixer_Never:
4609 case FastMixer_Dynamic:
4610 mNormalSink = mOutputSink;
4611 break;
4612 case FastMixer_Always:
4613 mNormalSink = mPipeSink;
4614 break;
4615 case FastMixer_Static:
4616 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
4617 break;
4618 }
4619}
4620
4621AudioFlinger::MixerThread::~MixerThread()
4622{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004623 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004624 FastMixerStateQueue *sq = mFastMixer->sq();
4625 FastMixerState *state = sq->begin();
4626 if (state->mCommand == FastMixerState::COLD_IDLE) {
4627 int32_t old = android_atomic_inc(&mFastMixerFutex);
4628 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07004629 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08004630 }
4631 }
4632 state->mCommand = FastMixerState::EXIT;
4633 sq->end();
4634 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
4635 mFastMixer->join();
4636 // Though the fast mixer thread has exited, it's state queue is still valid.
4637 // We'll use that extract the final state which contains one remaining fast track
4638 // corresponding to our sub-mix.
4639 state = sq->begin();
4640 ALOG_ASSERT(state->mTrackMask == 1);
4641 FastTrack *fastTrack = &state->mFastTracks[0];
4642 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
4643 delete fastTrack->mBufferProvider;
4644 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004645 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08004646#ifdef AUDIO_WATCHDOG
4647 if (mAudioWatchdog != 0) {
4648 mAudioWatchdog->requestExit();
4649 mAudioWatchdog->requestExitAndWait();
4650 mAudioWatchdog.clear();
4651 }
4652#endif
4653 }
Glenn Kasten9e58b552013-01-18 15:09:48 -08004654 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08004655 delete mAudioMixer;
4656}
4657
4658
4659uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
4660{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004661 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004662 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
4663 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
4664 }
4665 return latency;
4666}
4667
Eric Laurentbfb1b832013-01-07 09:53:42 -08004668ssize_t AudioFlinger::MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08004669{
4670 // FIXME we should only do one push per cycle; confirm this is true
4671 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004672 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004673 FastMixerStateQueue *sq = mFastMixer->sq();
4674 FastMixerState *state = sq->begin();
4675 if (state->mCommand != FastMixerState::MIX_WRITE &&
4676 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
4677 if (state->mCommand == FastMixerState::COLD_IDLE) {
Eric Laurenta2ab4502015-09-09 12:25:51 -07004678
4679 // FIXME workaround for first HAL write being CPU bound on some devices
4680 ATRACE_BEGIN("write");
4681 mOutput->write((char *)mSinkBuffer, 0);
4682 ATRACE_END();
4683
Eric Laurent81784c32012-11-19 14:55:58 -08004684 int32_t old = android_atomic_inc(&mFastMixerFutex);
4685 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07004686 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08004687 }
4688#ifdef AUDIO_WATCHDOG
4689 if (mAudioWatchdog != 0) {
4690 mAudioWatchdog->resume();
4691 }
4692#endif
4693 }
4694 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kastend797a9d2015-03-02 14:19:25 -08004695#ifdef FAST_THREAD_STATISTICS
Glenn Kasten4182c4e2013-07-15 14:45:07 -07004696 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08004697 FastThreadDumpState::kSamplingNforLowRamDevice : FastThreadDumpState::kSamplingN);
Glenn Kastend797a9d2015-03-02 14:19:25 -08004698#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004699 sq->end();
4700 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
4701 if (kUseFastMixer == FastMixer_Dynamic) {
4702 mNormalSink = mPipeSink;
4703 }
4704 } else {
4705 sq->end(false /*didModify*/);
4706 }
4707 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004708 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08004709}
4710
4711void AudioFlinger::MixerThread::threadLoop_standby()
4712{
4713 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004714 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004715 FastMixerStateQueue *sq = mFastMixer->sq();
4716 FastMixerState *state = sq->begin();
4717 if (!(state->mCommand & FastMixerState::IDLE)) {
Andy Hung2148bf02016-11-28 19:01:02 -08004718 // Report any frames trapped in the Monopipe
4719 MonoPipe *monoPipe = (MonoPipe *)mPipeSink.get();
4720 const long long pipeFrames = monoPipe->maxFrames() - monoPipe->availableToWrite();
4721 mLocalLog.log("threadLoop_standby: framesWritten:%lld suspendedFrames:%lld "
4722 "monoPipeWritten:%lld monoPipeLeft:%lld",
4723 (long long)mFramesWritten, (long long)mSuspendedFrames,
4724 (long long)mPipeSink->framesWritten(), pipeFrames);
4725 mLocalLog.log("threadLoop_standby: %s", mTimestamp.toString().c_str());
4726
Eric Laurent81784c32012-11-19 14:55:58 -08004727 state->mCommand = FastMixerState::COLD_IDLE;
4728 state->mColdFutexAddr = &mFastMixerFutex;
4729 state->mColdGen++;
4730 mFastMixerFutex = 0;
4731 sq->end();
4732 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
4733 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
4734 if (kUseFastMixer == FastMixer_Dynamic) {
4735 mNormalSink = mOutputSink;
4736 }
4737#ifdef AUDIO_WATCHDOG
4738 if (mAudioWatchdog != 0) {
4739 mAudioWatchdog->pause();
4740 }
4741#endif
4742 } else {
4743 sq->end(false /*didModify*/);
4744 }
4745 }
4746 PlaybackThread::threadLoop_standby();
4747}
4748
Eric Laurentbfb1b832013-01-07 09:53:42 -08004749bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
4750{
4751 return false;
4752}
4753
4754bool AudioFlinger::PlaybackThread::shouldStandby_l()
4755{
4756 return !mStandby;
4757}
4758
4759bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
4760{
4761 Mutex::Autolock _l(mLock);
4762 return waitingAsyncCallback_l();
4763}
4764
Eric Laurent81784c32012-11-19 14:55:58 -08004765// shared by MIXER and DIRECT, overridden by DUPLICATING
4766void AudioFlinger::PlaybackThread::threadLoop_standby()
4767{
4768 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
Phil Burk062e67a2015-02-11 13:40:50 -08004769 mOutput->standby();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004770 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004771 // discard any pending drain or write ack by incrementing sequence
4772 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
4773 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004774 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004775 mCallbackThread->setWriteBlocked(mWriteAckSequence);
4776 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004777 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08004778 mHwPaused = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004779}
4780
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08004781void AudioFlinger::PlaybackThread::onAddNewTrack_l()
4782{
4783 ALOGV("signal playback thread");
4784 broadcast_l();
4785}
4786
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07004787void AudioFlinger::PlaybackThread::onAsyncError()
4788{
4789 for (int i = AUDIO_STREAM_SYSTEM; i < (int)AUDIO_STREAM_CNT; i++) {
4790 invalidateTracks((audio_stream_type_t)i);
4791 }
4792}
4793
Eric Laurent81784c32012-11-19 14:55:58 -08004794void AudioFlinger::MixerThread::threadLoop_mix()
4795{
Eric Laurent81784c32012-11-19 14:55:58 -08004796 // mix buffers...
Glenn Kastend79072e2016-01-06 08:41:20 -08004797 mAudioMixer->process();
Andy Hung25c2dac2014-02-27 14:56:00 -08004798 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004799 // increase sleep time progressively when application underrun condition clears.
4800 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
4801 // that a steady state of alternating ready/not ready conditions keeps the sleep time
4802 // such that we would underrun the audio HAL.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004803 if ((mSleepTimeUs == 0) && (sleepTimeShift > 0)) {
Eric Laurent81784c32012-11-19 14:55:58 -08004804 sleepTimeShift--;
4805 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004806 mSleepTimeUs = 0;
4807 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08004808 //TODO: delay standby when effects have a tail
Glenn Kasten4c053ea2014-09-28 14:41:07 -07004809
Eric Laurent81784c32012-11-19 14:55:58 -08004810}
4811
4812void AudioFlinger::MixerThread::threadLoop_sleepTime()
4813{
4814 // If no tracks are ready, sleep once for the duration of an output
4815 // buffer size, then write 0s to the output
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004816 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004817 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Andy Hung06d13222018-05-03 20:13:31 -07004818 if (mPipeSink.get() != nullptr && mPipeSink == mNormalSink) {
4819 // Using the Monopipe availableToWrite, we estimate the
4820 // sleep time to retry for more data (before we underrun).
4821 MonoPipe *monoPipe = static_cast<MonoPipe *>(mPipeSink.get());
4822 const ssize_t availableToWrite = mPipeSink->availableToWrite();
4823 const size_t pipeFrames = monoPipe->maxFrames();
4824 const size_t framesLeft = pipeFrames - max(availableToWrite, 0);
4825 // HAL_framecount <= framesDelay ~ framesLeft / 2 <= Normal_Mixer_framecount
4826 const size_t framesDelay = std::min(
4827 mNormalFrameCount, max(framesLeft / 2, mFrameCount));
4828 ALOGV("pipeFrames:%zu framesLeft:%zu framesDelay:%zu",
4829 pipeFrames, framesLeft, framesDelay);
4830 mSleepTimeUs = framesDelay * MICROS_PER_SECOND / mSampleRate;
4831 } else {
4832 mSleepTimeUs = mActiveSleepTimeUs >> sleepTimeShift;
4833 if (mSleepTimeUs < kMinThreadSleepTimeUs) {
4834 mSleepTimeUs = kMinThreadSleepTimeUs;
4835 }
4836 // reduce sleep time in case of consecutive application underruns to avoid
4837 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
4838 // duration we would end up writing less data than needed by the audio HAL if
4839 // the condition persists.
4840 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
4841 sleepTimeShift++;
4842 }
Eric Laurent81784c32012-11-19 14:55:58 -08004843 }
4844 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004845 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08004846 }
4847 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08004848 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
4849 // before effects processing or output.
4850 if (mMixerBufferValid) {
4851 memset(mMixerBuffer, 0, mMixerBufferSize);
4852 } else {
4853 memset(mSinkBuffer, 0, mSinkBufferSize);
4854 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004855 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08004856 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
4857 "anticipated start");
4858 }
4859 // TODO add standby time extension fct of effect tail
4860}
4861
4862// prepareTracks_l() must be called with ThreadBase::mLock held
4863AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
4864 Vector< sp<Track> > *tracksToRemove)
4865{
Andy Hungc0691382018-09-12 18:01:57 -07004866 // clean up deleted track ids in AudioMixer before allocating new tracks
4867 (void)mTracks.processDeletedTrackIds([this](int trackId) {
4868 // for each trackId, destroy it in the AudioMixer
4869 if (mAudioMixer->exists(trackId)) {
4870 mAudioMixer->destroy(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08004871 }
4872 });
Andy Hungc0691382018-09-12 18:01:57 -07004873 mTracks.clearDeletedTrackIds();
Eric Laurent81784c32012-11-19 14:55:58 -08004874
4875 mixer_state mixerStatus = MIXER_IDLE;
4876 // find out which tracks need to be processed
4877 size_t count = mActiveTracks.size();
4878 size_t mixedTracks = 0;
4879 size_t tracksWithEffect = 0;
4880 // counts only _active_ fast tracks
4881 size_t fastTracks = 0;
4882 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
4883
4884 float masterVolume = mMasterVolume;
4885 bool masterMute = mMasterMute;
4886
4887 if (masterMute) {
4888 masterVolume = 0;
4889 }
4890 // Delegate master volume control to effect in output mix effect chain if needed
4891 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
4892 if (chain != 0) {
4893 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
4894 chain->setVolume_l(&v, &v);
4895 masterVolume = (float)((v + (1 << 23)) >> 24);
4896 chain.clear();
4897 }
4898
4899 // prepare a new state to push
4900 FastMixerStateQueue *sq = NULL;
4901 FastMixerState *state = NULL;
4902 bool didModify = false;
4903 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Andy Hungf2285312017-02-14 18:31:59 -08004904 bool coldIdle = false;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004905 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004906 sq = mFastMixer->sq();
4907 state = sq->begin();
Andy Hungf2285312017-02-14 18:31:59 -08004908 coldIdle = state->mCommand == FastMixerState::COLD_IDLE;
Eric Laurent81784c32012-11-19 14:55:58 -08004909 }
4910
Andy Hung69aed5f2014-02-25 17:24:40 -08004911 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08004912 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08004913
Andy Hungbd3b2b02018-05-21 10:53:11 -07004914 // DeferredOperations handles statistics after setting mixerStatus.
4915 class DeferredOperations {
4916 public:
Andy Hungea840382020-05-05 21:50:17 -07004917 DeferredOperations(mixer_state *mixerStatus, ThreadMetrics *threadMetrics)
4918 : mMixerStatus(mixerStatus)
4919 , mThreadMetrics(threadMetrics) {}
Andy Hungbd3b2b02018-05-21 10:53:11 -07004920
4921 // when leaving scope, tally frames properly.
4922 ~DeferredOperations() {
4923 // Tally underrun frames only if we are actually mixing (MIXER_TRACKS_READY)
4924 // because that is when the underrun occurs.
4925 // We do not distinguish between FastTracks and NormalTracks here.
Andy Hungea840382020-05-05 21:50:17 -07004926 size_t maxUnderrunFrames = 0;
Andy Hungb68f5eb2019-12-03 16:49:17 -08004927 if (*mMixerStatus == MIXER_TRACKS_READY && mUnderrunFrames.size() > 0) {
Andy Hungbd3b2b02018-05-21 10:53:11 -07004928 for (const auto &underrun : mUnderrunFrames) {
Andy Hungc2b11cb2020-04-22 09:04:01 -07004929 underrun.first->tallyUnderrunFrames(underrun.second);
Andy Hungea840382020-05-05 21:50:17 -07004930 maxUnderrunFrames = max(underrun.second, maxUnderrunFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07004931 }
4932 }
Andy Hungea840382020-05-05 21:50:17 -07004933 // send the max underrun frames for this mixer period
4934 mThreadMetrics->logUnderrunFrames(maxUnderrunFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07004935 }
4936
4937 // tallyUnderrunFrames() is called to update the track counters
4938 // with the number of underrun frames for a particular mixer period.
4939 // We defer tallying until we know the final mixer status.
4940 void tallyUnderrunFrames(sp<Track> track, size_t underrunFrames) {
4941 mUnderrunFrames.emplace_back(track, underrunFrames);
4942 }
4943
4944 private:
4945 const mixer_state * const mMixerStatus;
Andy Hungea840382020-05-05 21:50:17 -07004946 ThreadMetrics * const mThreadMetrics;
Andy Hungbd3b2b02018-05-21 10:53:11 -07004947 std::vector<std::pair<sp<Track>, size_t>> mUnderrunFrames;
Andy Hungea840382020-05-05 21:50:17 -07004948 } deferredOperations(&mixerStatus, &mThreadMetrics);
Andy Hungb68f5eb2019-12-03 16:49:17 -08004949 // implicit nested scope for variable capture
Andy Hungbd3b2b02018-05-21 10:53:11 -07004950
jiabin245cdd92018-12-07 17:55:15 -08004951 bool noFastHapticTrack = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004952 for (size_t i=0 ; i<count ; i++) {
Andy Hungdae27702016-10-31 14:01:16 -07004953 const sp<Track> t = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08004954
4955 // this const just means the local variable doesn't change
4956 Track* const track = t.get();
4957
4958 // process fast tracks
4959 if (track->isFastTrack()) {
Andy Hungae22b482019-05-09 15:38:55 -07004960 LOG_ALWAYS_FATAL_IF(mFastMixer.get() == nullptr,
4961 "%s(%d): FastTrack(%d) present without FastMixer",
4962 __func__, id(), track->id());
4963
jiabin245cdd92018-12-07 17:55:15 -08004964 if (track->getHapticPlaybackEnabled()) {
4965 noFastHapticTrack = false;
4966 }
Eric Laurent81784c32012-11-19 14:55:58 -08004967
4968 // It's theoretically possible (though unlikely) for a fast track to be created
4969 // and then removed within the same normal mix cycle. This is not a problem, as
4970 // the track never becomes active so it's fast mixer slot is never touched.
4971 // The converse, of removing an (active) track and then creating a new track
4972 // at the identical fast mixer slot within the same normal mix cycle,
4973 // is impossible because the slot isn't marked available until the end of each cycle.
4974 int j = track->mFastIndex;
Glenn Kastendc2c50b2016-04-21 08:13:14 -07004975 ALOG_ASSERT(0 < j && j < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08004976 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
4977 FastTrack *fastTrack = &state->mFastTracks[j];
4978
4979 // Determine whether the track is currently in underrun condition,
4980 // and whether it had a recent underrun.
4981 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
4982 FastTrackUnderruns underruns = ftDump->mUnderruns;
4983 uint32_t recentFull = (underruns.mBitFields.mFull -
4984 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
4985 uint32_t recentPartial = (underruns.mBitFields.mPartial -
4986 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
4987 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
4988 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
4989 uint32_t recentUnderruns = recentPartial + recentEmpty;
4990 track->mObservedUnderruns = underruns;
4991 // don't count underruns that occur while stopping or pausing
4992 // or stopped which can occur when flush() is called while active
Andy Hungbd3b2b02018-05-21 10:53:11 -07004993 size_t underrunFrames = 0;
Glenn Kasten82aaf942013-07-17 16:05:07 -07004994 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
4995 recentUnderruns > 0) {
4996 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
Andy Hungbd3b2b02018-05-21 10:53:11 -07004997 underrunFrames = recentUnderruns * mFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08004998 }
Andy Hungbd3b2b02018-05-21 10:53:11 -07004999 // Immediately account for FastTrack underruns.
5000 track->mAudioTrackServerProxy->tallyUnderrunFrames(underrunFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08005001
5002 // This is similar to the state machine for normal tracks,
5003 // with a few modifications for fast tracks.
5004 bool isActive = true;
5005 switch (track->mState) {
5006 case TrackBase::STOPPING_1:
5007 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08005008 if (recentUnderruns > 0 || track->isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -08005009 track->mState = TrackBase::STOPPING_2;
5010 }
5011 break;
5012 case TrackBase::PAUSING:
5013 // ramp down is not yet implemented
5014 track->setPaused();
5015 break;
5016 case TrackBase::RESUMING:
5017 // ramp up is not yet implemented
5018 track->mState = TrackBase::ACTIVE;
5019 break;
5020 case TrackBase::ACTIVE:
5021 if (recentFull > 0 || recentPartial > 0) {
5022 // track has provided at least some frames recently: reset retry count
5023 track->mRetryCount = kMaxTrackRetries;
5024 }
5025 if (recentUnderruns == 0) {
5026 // no recent underruns: stay active
5027 break;
5028 }
5029 // there has recently been an underrun of some kind
5030 if (track->sharedBuffer() == 0) {
5031 // were any of the recent underruns "empty" (no frames available)?
5032 if (recentEmpty == 0) {
5033 // no, then ignore the partial underruns as they are allowed indefinitely
5034 break;
5035 }
5036 // there has recently been an "empty" underrun: decrement the retry counter
5037 if (--(track->mRetryCount) > 0) {
5038 break;
5039 }
5040 // indicate to client process that the track was disabled because of underrun;
5041 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08005042 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08005043 // remove from active list, but state remains ACTIVE [confusing but true]
5044 isActive = false;
5045 break;
5046 }
Chih-Hung Hsieh2b487032018-09-13 14:16:02 -07005047 FALLTHROUGH_INTENDED;
Eric Laurent81784c32012-11-19 14:55:58 -08005048 case TrackBase::STOPPING_2:
5049 case TrackBase::PAUSED:
Eric Laurent81784c32012-11-19 14:55:58 -08005050 case TrackBase::STOPPED:
5051 case TrackBase::FLUSHED: // flush() while active
5052 // Check for presentation complete if track is inactive
5053 // We have consumed all the buffers of this track.
5054 // This would be incomplete if we auto-paused on underrun
5055 {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005056 uint32_t latency = 0;
5057 status_t result = mOutput->stream->getLatency(&latency);
5058 ALOGE_IF(result != OK,
5059 "Error when retrieving output stream latency: %d", result);
5060 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08005061 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005062 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
5063 // track stays in active list until presentation is complete
5064 break;
5065 }
5066 }
5067 if (track->isStopping_2()) {
5068 track->mState = TrackBase::STOPPED;
5069 }
5070 if (track->isStopped()) {
5071 // Can't reset directly, as fast mixer is still polling this track
5072 // track->reset();
5073 // So instead mark this track as needing to be reset after push with ack
5074 resetMask |= 1 << i;
5075 }
5076 isActive = false;
5077 break;
5078 case TrackBase::IDLE:
5079 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08005080 LOG_ALWAYS_FATAL("unexpected track state %d", track->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08005081 }
5082
5083 if (isActive) {
5084 // was it previously inactive?
5085 if (!(state->mTrackMask & (1 << j))) {
5086 ExtendedAudioBufferProvider *eabp = track;
5087 VolumeProvider *vp = track;
5088 fastTrack->mBufferProvider = eabp;
5089 fastTrack->mVolumeProvider = vp;
Eric Laurent81784c32012-11-19 14:55:58 -08005090 fastTrack->mChannelMask = track->mChannelMask;
Andy Hunge8a1ced2014-05-09 15:02:21 -07005091 fastTrack->mFormat = track->mFormat;
jiabin245cdd92018-12-07 17:55:15 -08005092 fastTrack->mHapticPlaybackEnabled = track->getHapticPlaybackEnabled();
jiabin77270b82018-12-18 15:41:29 -08005093 fastTrack->mHapticIntensity = track->getHapticIntensity();
Eric Laurent81784c32012-11-19 14:55:58 -08005094 fastTrack->mGeneration++;
5095 state->mTrackMask |= 1 << j;
5096 didModify = true;
5097 // no acknowledgement required for newly active tracks
5098 }
Kevin Rocard12381092018-04-11 09:19:59 -07005099 sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
Eric Laurenteab90452019-06-24 15:17:46 -07005100 float volume;
5101 if (track->isPlaybackRestricted() || mStreamTypes[track->streamType()].mute) {
5102 volume = 0.f;
5103 } else {
5104 volume = masterVolume * mStreamTypes[track->streamType()].volume;
5105 }
5106
5107 handleVoipVolume_l(&volume);
5108
Eric Laurent81784c32012-11-19 14:55:58 -08005109 // cache the combined master volume and stream type volume for fast mixer; this
5110 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005111 const float vh = track->getVolumeHandler()->getVolume(
Eric Laurenteab90452019-06-24 15:17:46 -07005112 proxy->framesReleased()).first;
5113 volume *= vh;
Kevin Rocardb0eeaf122018-04-11 08:30:16 -07005114 track->mCachedVolume = volume;
Kevin Rocard12381092018-04-11 09:19:59 -07005115 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
5116 float vlf = volume * float_from_gain(gain_minifloat_unpack_left(vlr));
5117 float vrf = volume * float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurenteab90452019-06-24 15:17:46 -07005118
Kevin Rocard12381092018-04-11 09:19:59 -07005119 track->setFinalVolume((vlf + vrf) / 2.f);
Eric Laurent81784c32012-11-19 14:55:58 -08005120 ++fastTracks;
5121 } else {
5122 // was it previously active?
5123 if (state->mTrackMask & (1 << j)) {
5124 fastTrack->mBufferProvider = NULL;
5125 fastTrack->mGeneration++;
5126 state->mTrackMask &= ~(1 << j);
5127 didModify = true;
5128 // If any fast tracks were removed, we must wait for acknowledgement
5129 // because we're about to decrement the last sp<> on those tracks.
5130 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
5131 } else {
Glenn Kastenbf848af2017-12-22 11:55:01 -08005132 // ALOGW rather than LOG_ALWAYS_FATAL because it seems there are cases where an
5133 // AudioTrack may start (which may not be with a start() but with a write()
5134 // after underrun) and immediately paused or released. In that case the
5135 // FastTrack state hasn't had time to update.
5136 // TODO Remove the ALOGW when this theory is confirmed.
5137 ALOGW("fast track %d should have been active; "
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08005138 "mState=%d, mTrackMask=%#x, recentUnderruns=%u, isShared=%d",
5139 j, track->mState, state->mTrackMask, recentUnderruns,
5140 track->sharedBuffer() != 0);
Glenn Kastenbf848af2017-12-22 11:55:01 -08005141 // Since the FastMixer state already has the track inactive, do nothing here.
Eric Laurent81784c32012-11-19 14:55:58 -08005142 }
5143 tracksToRemove->add(track);
5144 // Avoids a misleading display in dumpsys
5145 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
5146 }
jiabin245cdd92018-12-07 17:55:15 -08005147 if (fastTrack->mHapticPlaybackEnabled != track->getHapticPlaybackEnabled()) {
5148 fastTrack->mHapticPlaybackEnabled = track->getHapticPlaybackEnabled();
5149 didModify = true;
5150 }
Eric Laurent81784c32012-11-19 14:55:58 -08005151 continue;
5152 }
5153
5154 { // local variable scope to avoid goto warning
5155
5156 audio_track_cblk_t* cblk = track->cblk();
5157
5158 // The first time a track is added we wait
5159 // for all its buffers to be filled before processing it
Andy Hungc0691382018-09-12 18:01:57 -07005160 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08005161
5162 // if an active track doesn't exist in the AudioMixer, create it.
Andy Hungc0691382018-09-12 18:01:57 -07005163 // use the trackId as the AudioMixer name.
5164 if (!mAudioMixer->exists(trackId)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08005165 status_t status = mAudioMixer->create(
Andy Hungc0691382018-09-12 18:01:57 -07005166 trackId,
Andy Hung1bc088a2018-02-09 15:57:31 -08005167 track->mChannelMask,
5168 track->mFormat,
5169 track->mSessionId);
5170 if (status != OK) {
Andy Hungc0691382018-09-12 18:01:57 -07005171 ALOGW("%s(): AudioMixer cannot create track(%d)"
5172 " mask %#x, format %#x, sessionId %d",
5173 __func__, trackId,
5174 track->mChannelMask, track->mFormat, track->mSessionId);
Andy Hung1bc088a2018-02-09 15:57:31 -08005175 tracksToRemove->add(track);
5176 track->invalidate(); // consider it dead.
5177 continue;
5178 }
5179 }
5180
Eric Laurent81784c32012-11-19 14:55:58 -08005181 // make sure that we have enough frames to mix one full buffer.
5182 // enforce this condition only once to enable draining the buffer in case the client
5183 // app does not call stop() and relies on underrun to stop:
5184 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
5185 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005186 size_t desiredFrames;
Andy Hung8edb8dc2015-03-26 19:13:55 -07005187 const uint32_t sampleRate = track->mAudioTrackServerProxy->getSampleRate();
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07005188 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07005189
5190 desiredFrames = sourceFramesNeededWithTimestretch(
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07005191 sampleRate, mNormalFrameCount, mSampleRate, playbackRate.mSpeed);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005192 // TODO: ONLY USED FOR LEGACY RESAMPLERS, remove when they are removed.
5193 // add frames already consumed but not yet released by the resampler
5194 // because mAudioTrackServerProxy->framesReady() will include these frames
Andy Hungc0691382018-09-12 18:01:57 -07005195 desiredFrames += mAudioMixer->getUnreleasedFrames(trackId);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005196
Eric Laurent81784c32012-11-19 14:55:58 -08005197 uint32_t minFrames = 1;
5198 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
5199 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005200 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08005201 }
Eric Laurent13e4c962013-12-20 17:36:01 -08005202
5203 size_t framesReady = track->framesReady();
Glenn Kastene7754022014-10-31 12:11:26 -07005204 if (ATRACE_ENABLED()) {
5205 // I wish we had formatted trace names
Andy Hung1bc088a2018-02-09 15:57:31 -08005206 std::string traceName("nRdy");
Andy Hungc0691382018-09-12 18:01:57 -07005207 traceName += std::to_string(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08005208 ATRACE_INT(traceName.c_str(), framesReady);
Glenn Kastene7754022014-10-31 12:11:26 -07005209 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005210 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08005211 !track->isPaused() && !track->isTerminated())
5212 {
Andy Hungc0691382018-09-12 18:01:57 -07005213 ALOGVV("track(%d) s=%08x [OK] on thread %p", trackId, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08005214
5215 mixedTracks++;
5216
Andy Hung69aed5f2014-02-25 17:24:40 -08005217 // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
5218 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08005219 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08005220 if (track->mainBuffer() != mSinkBuffer &&
5221 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08005222 if (mEffectBufferEnabled) {
5223 mEffectBufferValid = true; // Later can set directly.
5224 }
Eric Laurent81784c32012-11-19 14:55:58 -08005225 chain = getEffectChain_l(track->sessionId());
5226 // Delegate volume control to effect in track effect chain if needed
5227 if (chain != 0) {
5228 tracksWithEffect++;
5229 } else {
Andy Hungc0691382018-09-12 18:01:57 -07005230 ALOGW("prepareTracks_l(): track(%d) attached to effect but no chain found on "
Eric Laurent81784c32012-11-19 14:55:58 -08005231 "session %d",
Andy Hungc0691382018-09-12 18:01:57 -07005232 trackId, track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08005233 }
5234 }
5235
5236
5237 int param = AudioMixer::VOLUME;
5238 if (track->mFillingUpStatus == Track::FS_FILLED) {
5239 // no ramp for the first volume setting
5240 track->mFillingUpStatus = Track::FS_ACTIVE;
5241 if (track->mState == TrackBase::RESUMING) {
5242 track->mState = TrackBase::ACTIVE;
Revathi Uddaraju453bcb52017-08-14 14:19:40 +08005243 // If a new track is paused immediately after start, do not ramp on resume.
5244 if (cblk->mServer != 0) {
5245 param = AudioMixer::RAMP_VOLUME;
5246 }
Eric Laurent81784c32012-11-19 14:55:58 -08005247 }
Andy Hungc0691382018-09-12 18:01:57 -07005248 mAudioMixer->setParameter(trackId, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Eric Laurent7c29ec92017-09-20 17:54:22 -07005249 mLeftVolFloat = -1.0;
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005250 // FIXME should not make a decision based on mServer
5251 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005252 // If the track is stopped before the first frame was mixed,
5253 // do not apply ramp
5254 param = AudioMixer::RAMP_VOLUME;
5255 }
5256
5257 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07005258 uint32_t vl, vr; // in U8.24 integer format
5259 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Eric Laurent7c29ec92017-09-20 17:54:22 -07005260 // read original volumes with volume control
Eric Laurenteab90452019-06-24 15:17:46 -07005261 float v = masterVolume * mStreamTypes[track->streamType()].volume;
Andy Hung333ab962019-05-28 20:23:35 -07005262 // Always fetch volumeshaper volume to ensure state is updated.
5263 const sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
5264 const float vh = track->getVolumeHandler()->getVolume(
5265 track->mAudioTrackServerProxy->framesReleased()).first;
Eric Laurent7c29ec92017-09-20 17:54:22 -07005266
Eric Laurenteab90452019-06-24 15:17:46 -07005267 if (mStreamTypes[track->streamType()].mute || track->isPlaybackRestricted()) {
5268 v = 0;
5269 }
5270
5271 handleVoipVolume_l(&v);
5272
5273 if (track->isPausing()) {
Andy Hung6be49402014-05-30 10:42:03 -07005274 vl = vr = 0;
5275 vlf = vrf = vaf = 0.;
Eric Laurenteab90452019-06-24 15:17:46 -07005276 track->setPaused();
Eric Laurent81784c32012-11-19 14:55:58 -08005277 } else {
Glenn Kastenc56f3422014-03-21 17:53:17 -07005278 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07005279 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
5280 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08005281 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07005282 if (vlf > GAIN_FLOAT_UNITY) {
5283 ALOGV("Track left volume out of range: %.3g", vlf);
5284 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08005285 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07005286 if (vrf > GAIN_FLOAT_UNITY) {
5287 ALOGV("Track right volume out of range: %.3g", vrf);
5288 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08005289 }
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005290 // now apply the master volume and stream type volume and shaper volume
5291 vlf *= v * vh;
5292 vrf *= v * vh;
Eric Laurent81784c32012-11-19 14:55:58 -08005293 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07005294 // then derive vl and vr as U8.24 versions for the effect chain
5295 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
5296 vl = (uint32_t) (scaleto8_24 * vlf);
5297 vr = (uint32_t) (scaleto8_24 * vrf);
5298 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08005299 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08005300 // send level comes from shared memory and so may be corrupt
5301 if (sendLevel > MAX_GAIN_INT) {
5302 ALOGV("Track send level out of range: %04X", sendLevel);
5303 sendLevel = MAX_GAIN_INT;
5304 }
Andy Hung6be49402014-05-30 10:42:03 -07005305 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
5306 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08005307 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005308
Kevin Rocard12381092018-04-11 09:19:59 -07005309 track->setFinalVolume((vrf + vlf) / 2.f);
5310
Eric Laurent81784c32012-11-19 14:55:58 -08005311 // Delegate volume control to effect in track effect chain if needed
5312 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
5313 // Do not ramp volume if volume is controlled by effect
5314 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08005315 // Update remaining floating point volume levels
5316 vlf = (float)vl / (1 << 24);
5317 vrf = (float)vr / (1 << 24);
Eric Laurent81784c32012-11-19 14:55:58 -08005318 track->mHasVolumeController = true;
5319 } else {
5320 // force no volume ramp when volume controller was just disabled or removed
5321 // from effect chain to avoid volume spike
5322 if (track->mHasVolumeController) {
5323 param = AudioMixer::VOLUME;
5324 }
5325 track->mHasVolumeController = false;
5326 }
5327
Eric Laurent81784c32012-11-19 14:55:58 -08005328 // XXX: these things DON'T need to be done each time
Andy Hungc0691382018-09-12 18:01:57 -07005329 mAudioMixer->setBufferProvider(trackId, track);
5330 mAudioMixer->enable(trackId);
Eric Laurent81784c32012-11-19 14:55:58 -08005331
Andy Hungc0691382018-09-12 18:01:57 -07005332 mAudioMixer->setParameter(trackId, param, AudioMixer::VOLUME0, &vlf);
5333 mAudioMixer->setParameter(trackId, param, AudioMixer::VOLUME1, &vrf);
5334 mAudioMixer->setParameter(trackId, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08005335 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005336 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005337 AudioMixer::TRACK,
5338 AudioMixer::FORMAT, (void *)track->format());
5339 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005340 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005341 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00005342 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Andy Hung9a592762014-07-21 21:56:01 -07005343 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005344 trackId,
Andy Hung9a592762014-07-21 21:56:01 -07005345 AudioMixer::TRACK,
jiabin245cdd92018-12-07 17:55:15 -08005346 AudioMixer::MIXER_CHANNEL_MASK,
5347 (void *)(uintptr_t)(mChannelMask | mHapticChannelMask));
Glenn Kastene3aa6592012-12-04 12:22:46 -08005348 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07005349 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Andy Hung333ab962019-05-28 20:23:35 -07005350 uint32_t reqSampleRate = proxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08005351 if (reqSampleRate == 0) {
5352 reqSampleRate = mSampleRate;
5353 } else if (reqSampleRate > maxSampleRate) {
5354 reqSampleRate = maxSampleRate;
5355 }
Eric Laurent81784c32012-11-19 14:55:58 -08005356 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005357 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005358 AudioMixer::RESAMPLE,
5359 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00005360 (void *)(uintptr_t)reqSampleRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005361
Andy Hung333ab962019-05-28 20:23:35 -07005362 AudioPlaybackRate playbackRate = proxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07005363 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005364 trackId,
Andy Hung8edb8dc2015-03-26 19:13:55 -07005365 AudioMixer::TIMESTRETCH,
5366 AudioMixer::PLAYBACK_RATE,
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07005367 &playbackRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005368
Andy Hung69aed5f2014-02-25 17:24:40 -08005369 /*
5370 * Select the appropriate output buffer for the track.
5371 *
Andy Hung98ef9782014-03-04 14:46:50 -08005372 * Tracks with effects go into their own effects chain buffer
5373 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08005374 *
5375 * Other tracks can use mMixerBuffer for higher precision
5376 * channel accumulation. If this buffer is enabled
5377 * (mMixerBufferEnabled true), then selected tracks will accumulate
5378 * into it.
5379 *
5380 */
5381 if (mMixerBufferEnabled
5382 && (track->mainBuffer() == mSinkBuffer
5383 || track->mainBuffer() == mMixerBuffer)) {
5384 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005385 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08005386 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08005387 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
Andy Hung69aed5f2014-02-25 17:24:40 -08005388 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005389 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08005390 AudioMixer::TRACK,
5391 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
5392 // TODO: override track->mainBuffer()?
5393 mMixerBufferValid = true;
5394 } else {
5395 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005396 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08005397 AudioMixer::TRACK,
rago94a1ee82017-07-21 15:11:02 -07005398 AudioMixer::MIXER_FORMAT, (void *)EFFECT_BUFFER_FORMAT);
Andy Hung69aed5f2014-02-25 17:24:40 -08005399 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005400 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08005401 AudioMixer::TRACK,
5402 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
5403 }
Eric Laurent81784c32012-11-19 14:55:58 -08005404 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005405 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005406 AudioMixer::TRACK,
5407 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
jiabin245cdd92018-12-07 17:55:15 -08005408 mAudioMixer->setParameter(
5409 trackId,
5410 AudioMixer::TRACK,
5411 AudioMixer::HAPTIC_ENABLED, (void *)(uintptr_t)track->getHapticPlaybackEnabled());
jiabin77270b82018-12-18 15:41:29 -08005412 mAudioMixer->setParameter(
5413 trackId,
5414 AudioMixer::TRACK,
5415 AudioMixer::HAPTIC_INTENSITY, (void *)(uintptr_t)track->getHapticIntensity());
Eric Laurent81784c32012-11-19 14:55:58 -08005416
5417 // reset retry count
5418 track->mRetryCount = kMaxTrackRetries;
5419
5420 // If one track is ready, set the mixer ready if:
5421 // - the mixer was not ready during previous round OR
5422 // - no other track is not ready
5423 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
5424 mixerStatus != MIXER_TRACKS_ENABLED) {
5425 mixerStatus = MIXER_TRACKS_READY;
5426 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08005427
5428 // Enable the next few lines to instrument a test for underrun log handling.
5429 // TODO: Remove when we have a better way of testing the underrun log.
5430#if 0
5431 static int i;
5432 if ((++i & 0xf) == 0) {
5433 deferredOperations.tallyUnderrunFrames(track, 10 /* underrunFrames */);
5434 }
5435#endif
Eric Laurent81784c32012-11-19 14:55:58 -08005436 } else {
Andy Hungbd3b2b02018-05-21 10:53:11 -07005437 size_t underrunFrames = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005438 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Andy Hungb68f5eb2019-12-03 16:49:17 -08005439 ALOGV("track(%d) underrun, track state %s framesReady(%zu) < framesDesired(%zd)",
5440 trackId, track->getTrackStateAsString(), framesReady, desiredFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07005441 underrunFrames = desiredFrames;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005442 }
Andy Hungbd3b2b02018-05-21 10:53:11 -07005443 deferredOperations.tallyUnderrunFrames(track, underrunFrames);
Phil Burk2812d9e2016-01-04 10:34:30 -08005444
Eric Laurent81784c32012-11-19 14:55:58 -08005445 // clear effect chain input buffer if an active track underruns to avoid sending
5446 // previous audio buffer again to effects
5447 chain = getEffectChain_l(track->sessionId());
5448 if (chain != 0) {
5449 chain->clearInputBuffer();
5450 }
5451
Andy Hungc0691382018-09-12 18:01:57 -07005452 ALOGVV("track(%d) s=%08x [NOT READY] on thread %p", trackId, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08005453 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
5454 track->isStopped() || track->isPaused()) {
5455 // We have consumed all the buffers of this track.
5456 // Remove it from the list of active tracks.
5457 // TODO: use actual buffer filling status instead of latency when available from
5458 // audio HAL
5459 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08005460 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005461 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
5462 if (track->isStopped()) {
5463 track->reset();
5464 }
5465 tracksToRemove->add(track);
5466 }
5467 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08005468 // No buffers for this track. Give it a few chances to
5469 // fill a buffer, then remove it from active list.
5470 if (--(track->mRetryCount) <= 0) {
Andy Hungc0691382018-09-12 18:01:57 -07005471 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p",
5472 trackId, this);
Eric Laurent81784c32012-11-19 14:55:58 -08005473 tracksToRemove->add(track);
5474 // indicate to client process that the track was disabled because of underrun;
5475 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08005476 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08005477 // If one track is not ready, mark the mixer also not ready if:
5478 // - the mixer was ready during previous round OR
5479 // - no other track is ready
5480 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
5481 mixerStatus != MIXER_TRACKS_READY) {
5482 mixerStatus = MIXER_TRACKS_ENABLED;
5483 }
5484 }
Andy Hungc0691382018-09-12 18:01:57 -07005485 mAudioMixer->disable(trackId);
Eric Laurent81784c32012-11-19 14:55:58 -08005486 }
5487
5488 } // local variable scope to avoid goto warning
Eric Laurent81784c32012-11-19 14:55:58 -08005489
5490 }
5491
jiabin245cdd92018-12-07 17:55:15 -08005492 if (mHapticChannelMask != AUDIO_CHANNEL_NONE && sq != NULL) {
5493 // When there is no fast track playing haptic and FastMixer exists,
5494 // enabling the first FastTrack, which provides mixed data from normal
5495 // tracks, to play haptic data.
5496 FastTrack *fastTrack = &state->mFastTracks[0];
5497 if (fastTrack->mHapticPlaybackEnabled != noFastHapticTrack) {
5498 fastTrack->mHapticPlaybackEnabled = noFastHapticTrack;
5499 didModify = true;
5500 }
5501 }
5502
Eric Laurent81784c32012-11-19 14:55:58 -08005503 // Push the new FastMixer state if necessary
5504 bool pauseAudioWatchdog = false;
5505 if (didModify) {
5506 state->mFastTracksGen++;
5507 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
5508 if (kUseFastMixer == FastMixer_Dynamic &&
5509 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
5510 state->mCommand = FastMixerState::COLD_IDLE;
5511 state->mColdFutexAddr = &mFastMixerFutex;
5512 state->mColdGen++;
5513 mFastMixerFutex = 0;
5514 if (kUseFastMixer == FastMixer_Dynamic) {
5515 mNormalSink = mOutputSink;
5516 }
5517 // If we go into cold idle, need to wait for acknowledgement
5518 // so that fast mixer stops doing I/O.
5519 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
5520 pauseAudioWatchdog = true;
5521 }
Eric Laurent81784c32012-11-19 14:55:58 -08005522 }
5523 if (sq != NULL) {
5524 sq->end(didModify);
Andy Hungf2285312017-02-14 18:31:59 -08005525 // No need to block if the FastMixer is in COLD_IDLE as the FastThread
5526 // is not active. (We BLOCK_UNTIL_ACKED when entering COLD_IDLE
5527 // when bringing the output sink into standby.)
5528 //
5529 // We will get the latest FastMixer state when we come out of COLD_IDLE.
5530 //
5531 // This occurs with BT suspend when we idle the FastMixer with
5532 // active tracks, which may be added or removed.
5533 sq->push(coldIdle ? FastMixerStateQueue::BLOCK_NEVER : block);
Eric Laurent81784c32012-11-19 14:55:58 -08005534 }
5535#ifdef AUDIO_WATCHDOG
5536 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
5537 mAudioWatchdog->pause();
5538 }
5539#endif
5540
5541 // Now perform the deferred reset on fast tracks that have stopped
5542 while (resetMask != 0) {
5543 size_t i = __builtin_ctz(resetMask);
5544 ALOG_ASSERT(i < count);
5545 resetMask &= ~(1 << i);
Andy Hungdae27702016-10-31 14:01:16 -07005546 sp<Track> track = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08005547 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
5548 track->reset();
5549 }
5550
Andy Hung80d03d22018-04-10 10:32:11 -07005551 // Track destruction may occur outside of threadLoop once it is removed from active tracks.
5552 // Ensure the AudioMixer doesn't have a raw "buffer provider" pointer to the track if
5553 // it ceases to be active, to allow safe removal from the AudioMixer at the start
5554 // of prepareTracks_l(); this releases any outstanding buffer back to the track.
5555 // See also the implementation of destroyTrack_l().
5556 for (const auto &track : *tracksToRemove) {
Andy Hungc0691382018-09-12 18:01:57 -07005557 const int trackId = track->id();
5558 if (mAudioMixer->exists(trackId)) { // Normal tracks here, fast tracks in FastMixer.
5559 mAudioMixer->setBufferProvider(trackId, nullptr /* bufferProvider */);
Andy Hung80d03d22018-04-10 10:32:11 -07005560 }
5561 }
5562
Eric Laurent81784c32012-11-19 14:55:58 -08005563 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08005564 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08005565
Eric Laurent97d547d2014-09-02 14:45:53 -07005566 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0) {
5567 mEffectBufferValid = true;
Marco Nelissenac302142014-10-20 13:15:38 -07005568 }
5569
5570 if (mEffectBufferValid) {
Marco Nelissen57088b52014-10-17 16:39:39 -07005571 // as long as there are effects we should clear the effects buffer, to avoid
5572 // passing a non-clean buffer to the effect chain
5573 memset(mEffectBuffer, 0, mEffectBufferSize);
Eric Laurent97d547d2014-09-02 14:45:53 -07005574 }
Andy Hung69aed5f2014-02-25 17:24:40 -08005575 // sink or mix buffer must be cleared if all tracks are connected to an
5576 // effect chain as in this case the mixer will not write to the sink or mix buffer
5577 // and track effects will accumulate into it
Eric Laurentbfb1b832013-01-07 09:53:42 -08005578 if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
5579 (mixedTracks == 0 && fastTracks > 0))) {
Eric Laurent81784c32012-11-19 14:55:58 -08005580 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08005581 if (mMixerBufferValid) {
5582 memset(mMixerBuffer, 0, mMixerBufferSize);
5583 // TODO: In testing, mSinkBuffer below need not be cleared because
5584 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
5585 // after mixing.
5586 //
5587 // To enforce this guarantee:
5588 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
5589 // (mixedTracks == 0 && fastTracks > 0))
5590 // must imply MIXER_TRACKS_READY.
5591 // Later, we may clear buffers regardless, and skip much of this logic.
5592 }
Andy Hung98ef9782014-03-04 14:46:50 -08005593 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07005594 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08005595 }
5596
5597 // if any fast tracks, then status is ready
5598 mMixerStatusIgnoringFastTracks = mixerStatus;
5599 if (fastTracks > 0) {
5600 mixerStatus = MIXER_TRACKS_READY;
5601 }
5602 return mixerStatus;
5603}
5604
Eric Laurentad7dd962016-09-22 12:38:37 -07005605// trackCountForUid_l() must be called with ThreadBase::mLock held
Andy Hung1bc088a2018-02-09 15:57:31 -08005606uint32_t AudioFlinger::PlaybackThread::trackCountForUid_l(uid_t uid) const
Eric Laurentad7dd962016-09-22 12:38:37 -07005607{
5608 uint32_t trackCount = 0;
5609 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hung1f12a8a2016-11-07 16:10:30 -08005610 if (mTracks[i]->uid() == uid) {
Eric Laurentad7dd962016-09-22 12:38:37 -07005611 trackCount++;
5612 }
5613 }
5614 return trackCount;
5615}
5616
Andy Hung1bc088a2018-02-09 15:57:31 -08005617// isTrackAllowed_l() must be called with ThreadBase::mLock held
5618bool AudioFlinger::MixerThread::isTrackAllowed_l(
5619 audio_channel_mask_t channelMask, audio_format_t format,
5620 audio_session_t sessionId, uid_t uid) const
Eric Laurent81784c32012-11-19 14:55:58 -08005621{
Andy Hung1bc088a2018-02-09 15:57:31 -08005622 if (!PlaybackThread::isTrackAllowed_l(channelMask, format, sessionId, uid)) {
5623 return false;
Eric Laurentad7dd962016-09-22 12:38:37 -07005624 }
Andy Hung1bc088a2018-02-09 15:57:31 -08005625 // Check validity as we don't call AudioMixer::create() here.
Mikhail Naganov7ad7a252019-07-30 14:42:32 -07005626 if (!mAudioMixer->isValidFormat(format)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08005627 ALOGW("%s: invalid format: %#x", __func__, format);
5628 return false;
5629 }
Mikhail Naganov7ad7a252019-07-30 14:42:32 -07005630 if (!mAudioMixer->isValidChannelMask(channelMask)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08005631 ALOGW("%s: invalid channelMask: %#x", __func__, channelMask);
5632 return false;
5633 }
5634 return true;
Eric Laurent81784c32012-11-19 14:55:58 -08005635}
5636
Eric Laurent10351942014-05-08 18:49:52 -07005637// checkForNewParameter_l() must be called with ThreadBase::mLock held
5638bool AudioFlinger::MixerThread::checkForNewParameter_l(const String8& keyValuePair,
5639 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08005640{
Eric Laurent81784c32012-11-19 14:55:58 -08005641 bool reconfig = false;
Eric Laurent10351942014-05-08 18:49:52 -07005642 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08005643
Glenn Kastenc05b8d72016-03-24 09:48:17 -07005644 AutoPark<FastMixer> park(mFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08005645
Eric Laurent10351942014-05-08 18:49:52 -07005646 AudioParameter param = AudioParameter(keyValuePair);
5647 int value;
5648 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
5649 reconfig = true;
5650 }
5651 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07005652 if (!isValidPcmSinkFormat((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07005653 status = BAD_VALUE;
5654 } else {
5655 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08005656 reconfig = true;
5657 }
Eric Laurent10351942014-05-08 18:49:52 -07005658 }
5659 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07005660 if (!isValidPcmSinkChannelMask((audio_channel_mask_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07005661 status = BAD_VALUE;
5662 } else {
5663 // no need to save value, since it's constant
5664 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08005665 }
Eric Laurent10351942014-05-08 18:49:52 -07005666 }
5667 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
5668 // do not accept frame count changes if tracks are open as the track buffer
5669 // size depends on frame count and correct behavior would not be guaranteed
5670 // if frame count is changed after track creation
5671 if (!mTracks.isEmpty()) {
5672 status = INVALID_OPERATION;
5673 } else {
5674 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08005675 }
Eric Laurent10351942014-05-08 18:49:52 -07005676 }
5677 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07005678 LOG_FATAL("Should not set routing device in MixerThread");
Eric Laurent10351942014-05-08 18:49:52 -07005679 }
Eric Laurent81784c32012-11-19 14:55:58 -08005680
Eric Laurent10351942014-05-08 18:49:52 -07005681 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005682 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07005683 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08005684 mOutput->standby();
Andy Hungcf10d742020-04-28 15:38:24 -07005685 if (!mStandby) {
5686 mThreadMetrics.logEndInterval();
5687 mStandby = true;
5688 }
Eric Laurent10351942014-05-08 18:49:52 -07005689 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005690 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent81784c32012-11-19 14:55:58 -08005691 }
Eric Laurent10351942014-05-08 18:49:52 -07005692 if (status == NO_ERROR && reconfig) {
5693 readOutputParameters_l();
5694 delete mAudioMixer;
5695 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
Andy Hung1bc088a2018-02-09 15:57:31 -08005696 for (const auto &track : mTracks) {
Andy Hungc0691382018-09-12 18:01:57 -07005697 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08005698 status_t status = mAudioMixer->create(
Andy Hungc0691382018-09-12 18:01:57 -07005699 trackId,
Andy Hung1bc088a2018-02-09 15:57:31 -08005700 track->mChannelMask,
5701 track->mFormat,
5702 track->mSessionId);
5703 ALOGW_IF(status != NO_ERROR,
Andy Hungc0691382018-09-12 18:01:57 -07005704 "%s(): AudioMixer cannot create track(%d)"
5705 " mask %#x, format %#x, sessionId %d",
Andy Hung1bc088a2018-02-09 15:57:31 -08005706 __func__,
Andy Hungc0691382018-09-12 18:01:57 -07005707 trackId, track->mChannelMask, track->mFormat, track->mSessionId);
Eric Laurent10351942014-05-08 18:49:52 -07005708 }
Eric Laurent73e26b62015-04-27 16:55:58 -07005709 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07005710 }
Eric Laurent81784c32012-11-19 14:55:58 -08005711 }
5712
Dean Wheatley68918102021-03-19 22:09:19 +11005713 return reconfig;
Eric Laurent81784c32012-11-19 14:55:58 -08005714}
5715
5716
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07005717void AudioFlinger::MixerThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -08005718{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07005719 PlaybackThread::dumpInternals_l(fd, args);
Andy Hung40eb1a12015-06-18 13:42:02 -07005720 dprintf(fd, " Thread throttle time (msecs): %u\n", mThreadThrottleTimeMs);
Andy Hung8ed196a2018-01-05 13:21:11 -08005721 dprintf(fd, " AudioMixer tracks: %s\n", mAudioMixer->trackNames().c_str());
Andy Hung2ddee192015-12-18 17:34:44 -08005722 dprintf(fd, " Master mono: %s\n", mMasterMono ? "on" : "off");
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01005723 dprintf(fd, " Master balance: %f (%s)\n", mMasterBalance.load(),
5724 (hasFastMixer() ? std::to_string(mFastMixer->getMasterBalance())
5725 : mBalance.toString()).c_str());
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08005726 if (hasFastMixer()) {
5727 dprintf(fd, " FastMixer thread %p tid=%d", mFastMixer.get(), mFastMixer->getTid());
5728
5729 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
5730 // while we are dumping it. It may be inconsistent, but it won't mutate!
5731 // This is a large object so we place it on the heap.
5732 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
Eric Tan2942a4e2018-09-12 17:41:27 -07005733 const std::unique_ptr<FastMixerDumpState> copy =
5734 std::make_unique<FastMixerDumpState>(mFastMixerDumpState);
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08005735 copy->dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08005736
5737#ifdef STATE_QUEUE_DUMP
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08005738 // Similar for state queue
5739 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
5740 observerCopy.dump(fd);
5741 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
5742 mutatorCopy.dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08005743#endif
5744
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08005745#ifdef AUDIO_WATCHDOG
5746 if (mAudioWatchdog != 0) {
5747 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
5748 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
5749 wdCopy.dump(fd);
5750 }
5751#endif
5752
5753 } else {
5754 dprintf(fd, " No FastMixer\n");
5755 }
Eric Laurent81784c32012-11-19 14:55:58 -08005756}
5757
5758uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
5759{
5760 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
5761}
5762
5763uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
5764{
5765 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
5766}
5767
5768void AudioFlinger::MixerThread::cacheParameters_l()
5769{
5770 PlaybackThread::cacheParameters_l();
5771
5772 // FIXME: Relaxed timing because of a certain device that can't meet latency
5773 // Should be reduced to 2x after the vendor fixes the driver issue
5774 // increase threshold again due to low power audio mode. The way this warning
5775 // threshold is calculated and its usefulness should be reconsidered anyway.
5776 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
5777}
5778
5779// ----------------------------------------------------------------------------
5780
5781AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
jiabinc52b1ff2019-10-31 17:20:42 -07005782 AudioStreamOut* output, audio_io_handle_t id, ThreadBase::type_t type, bool systemReady)
5783 : PlaybackThread(audioFlinger, output, id, type, systemReady)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005784{
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01005785 setMasterBalance(audioFlinger->getMasterBalance_l());
Eric Laurentbfb1b832013-01-07 09:53:42 -08005786}
5787
Eric Laurent81784c32012-11-19 14:55:58 -08005788AudioFlinger::DirectOutputThread::~DirectOutputThread()
5789{
5790}
5791
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07005792void AudioFlinger::DirectOutputThread::dumpInternals_l(int fd, const Vector<String16>& args)
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01005793{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07005794 PlaybackThread::dumpInternals_l(fd, args);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01005795 dprintf(fd, " Master balance: %f Left: %f Right: %f\n",
5796 mMasterBalance.load(), mMasterBalanceLeft, mMasterBalanceRight);
5797}
5798
5799void AudioFlinger::DirectOutputThread::setMasterBalance(float balance)
5800{
5801 Mutex::Autolock _l(mLock);
5802 if (mMasterBalance != balance) {
5803 mMasterBalance.store(balance);
5804 mBalance.computeStereoBalance(balance, &mMasterBalanceLeft, &mMasterBalanceRight);
5805 broadcast_l();
5806 }
5807}
5808
Eric Laurent5850c4c2016-11-10 13:04:31 -08005809void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005810{
Eric Laurentbfb1b832013-01-07 09:53:42 -08005811 float left, right;
5812
Andy Hung333ab962019-05-28 20:23:35 -07005813 // Ensure volumeshaper state always advances even when muted.
5814 const sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
5815 const auto [shaperVolume, shaperActive] = track->getVolumeHandler()->getVolume(
5816 proxy->framesReleased());
5817 mVolumeShaperActive = shaperActive;
5818
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08005819 if (mMasterMute || mStreamTypes[track->streamType()].mute || track->isPlaybackRestricted()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08005820 left = right = 0;
5821 } else {
5822 float typeVolume = mStreamTypes[track->streamType()].volume;
Andy Hung333ab962019-05-28 20:23:35 -07005823 const float v = mMasterVolume * typeVolume * shaperVolume;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005824
Glenn Kastenc56f3422014-03-21 17:53:17 -07005825 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
5826 left = float_from_gain(gain_minifloat_unpack_left(vlr));
5827 if (left > GAIN_FLOAT_UNITY) {
5828 left = GAIN_FLOAT_UNITY;
5829 }
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01005830 left *= v * mMasterBalanceLeft; // DirectOutputThread balance applied as track volume
Glenn Kastenc56f3422014-03-21 17:53:17 -07005831 right = float_from_gain(gain_minifloat_unpack_right(vlr));
5832 if (right > GAIN_FLOAT_UNITY) {
5833 right = GAIN_FLOAT_UNITY;
5834 }
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01005835 right *= v * mMasterBalanceRight;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005836 }
5837
5838 if (lastTrack) {
Kevin Rocard12381092018-04-11 09:19:59 -07005839 track->setFinalVolume((left + right) / 2.f);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005840 if (left != mLeftVolFloat || right != mRightVolFloat) {
5841 mLeftVolFloat = left;
5842 mRightVolFloat = right;
5843
Eric Laurentbfb1b832013-01-07 09:53:42 -08005844 // Delegate volume control to effect in track effect chain if needed
5845 // only one effect chain can be present on DirectOutputThread, so if
5846 // there is one, the track is connected to it
5847 if (!mEffectChains.isEmpty()) {
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09005848 // if effect chain exists, volume is handled by it.
5849 // Convert volumes from float to 8.24
5850 uint32_t vl = (uint32_t)(left * (1 << 24));
5851 uint32_t vr = (uint32_t)(right * (1 << 24));
5852 // Direct/Offload effect chains set output volume in setVolume_l().
5853 (void)mEffectChains[0]->setVolume_l(&vl, &vr);
5854 } else {
5855 // otherwise we directly set the volume.
5856 setVolumeForOutput_l(left, right);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005857 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005858 }
5859 }
5860}
5861
Phil Burk43b4dcc2015-06-09 16:53:44 -07005862void AudioFlinger::DirectOutputThread::onAddNewTrack_l()
5863{
5864 sp<Track> previousTrack = mPreviousTrack.promote();
Andy Hungdae27702016-10-31 14:01:16 -07005865 sp<Track> latestTrack = mActiveTracks.getLatest();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005866
Eric Laurent0f0631e2015-07-06 18:01:25 -07005867 if (previousTrack != 0 && latestTrack != 0) {
5868 if (mType == DIRECT) {
5869 if (previousTrack.get() != latestTrack.get()) {
5870 mFlushPending = true;
5871 }
5872 } else /* mType == OFFLOAD */ {
5873 if (previousTrack->sessionId() != latestTrack->sessionId()) {
5874 mFlushPending = true;
5875 }
5876 }
Revathi Uddaraju20413a92016-10-13 17:16:14 +08005877 } else if (previousTrack == 0) {
5878 // there could be an old track added back during track transition for direct
5879 // output, so always issues flush to flush data of the previous track if it
5880 // was already destroyed with HAL paused, then flush can resume the playback
5881 mFlushPending = true;
Phil Burk43b4dcc2015-06-09 16:53:44 -07005882 }
5883 PlaybackThread::onAddNewTrack_l();
5884}
Eric Laurentbfb1b832013-01-07 09:53:42 -08005885
Eric Laurent81784c32012-11-19 14:55:58 -08005886AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
5887 Vector< sp<Track> > *tracksToRemove
5888)
5889{
Eric Laurentd595b7c2013-04-03 17:27:56 -07005890 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08005891 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005892 bool doHwPause = false;
5893 bool doHwResume = false;
Eric Laurent81784c32012-11-19 14:55:58 -08005894
5895 // find out which tracks need to be processed
Andy Hungdae27702016-10-31 14:01:16 -07005896 for (const sp<Track> &t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08005897 if (t->isInvalid()) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07005898 ALOGW("An invalidated track shouldn't be in active list");
Eric Laurent5850c4c2016-11-10 13:04:31 -08005899 tracksToRemove->add(t);
Phil Burk43b4dcc2015-06-09 16:53:44 -07005900 continue;
5901 }
5902
Eric Laurent5850c4c2016-11-10 13:04:31 -08005903 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005904#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurent81784c32012-11-19 14:55:58 -08005905 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005906#endif
Eric Laurentfd477972013-10-25 18:10:40 -07005907 // Only consider last track started for volume and mixer state control.
5908 // In theory an older track could underrun and restart after the new one starts
5909 // but as we only care about the transition phase between two tracks on a
5910 // direct output, it is not a problem to ignore the underrun case.
Andy Hungdae27702016-10-31 14:01:16 -07005911 sp<Track> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08005912 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08005913
Kuowei Li23666472021-01-20 10:23:25 +08005914 if (track->isPausePending()) {
5915 track->pauseAck();
5916 // It is possible a track might have been flushed or stopped.
5917 // Other operations such as flush pending might occur on the next prepare.
5918 if (track->isPausing()) {
5919 track->setPaused();
5920 }
5921 // Always perform pause, as an immediate flush will change
5922 // the pause state to be no longer isPausing().
Phil Burk6fc2a7c2015-04-30 16:08:10 -07005923 if (mHwSupportsPause && last && !mHwPaused) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005924 doHwPause = true;
5925 mHwPaused = true;
5926 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08005927 } else if (track->isFlushPending()) {
5928 track->flushAck();
5929 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07005930 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005931 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07005932 } else if (track->isResumePending()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005933 track->resumeAck();
Eric Laurent3df841a2016-07-15 15:15:40 -07005934 if (last) {
5935 mLeftVolFloat = mRightVolFloat = -1.0;
5936 if (mHwPaused) {
5937 doHwResume = true;
5938 mHwPaused = false;
5939 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08005940 }
5941 }
5942
Eric Laurent81784c32012-11-19 14:55:58 -08005943 // The first time a track is added we wait
Phil Burk99adee32014-12-10 16:46:30 -08005944 // for all its buffers to be filled before processing it.
5945 // Allow draining the buffer in case the client
5946 // app does not call stop() and relies on underrun to stop:
5947 // hence the test on (track->mRetryCount > 1).
Andy Hung455982f2021-04-27 17:46:12 -07005948 // If track->mRetryCount <= 1 then track is about to be disabled, paused, removed,
5949 // so we accept any nonzero amount of data delivered by the AudioTrack (which will
5950 // reset the retry counter).
Phil Burkca5e6142015-07-14 09:42:29 -07005951 // Do not use a high threshold for compressed audio.
Andy Hung455982f2021-04-27 17:46:12 -07005952
5953 // target retry count that we will use is based on the time we wait for retries.
5954 const int32_t targetRetryCount = kMaxTrackRetriesDirectMs * 1000 / mActiveSleepTimeUs;
5955 // the retry threshold is when we accept any size for PCM data. This is slightly
5956 // smaller than the retry count so we can push small bits of data without a glitch.
5957 const int32_t retryThreshold = targetRetryCount > 2 ? targetRetryCount - 1 : 1;
Eric Laurent81784c32012-11-19 14:55:58 -08005958 uint32_t minFrames;
Phil Burk99adee32014-12-10 16:46:30 -08005959 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
Andy Hung455982f2021-04-27 17:46:12 -07005960 && (track->mRetryCount > retryThreshold) && audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005961 minFrames = mNormalFrameCount;
5962 } else {
5963 minFrames = 1;
5964 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005965
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07005966 const size_t framesReady = track->framesReady();
5967 const int trackId = track->id();
5968 if (ATRACE_ENABLED()) {
5969 std::string traceName("nRdy");
5970 traceName += std::to_string(trackId);
5971 ATRACE_INT(traceName.c_str(), framesReady);
5972 }
5973 if ((framesReady >= minFrames) && track->isReady() && !track->isPaused() &&
Eric Laurentab5cdba2014-06-09 17:22:27 -07005974 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08005975 {
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07005976 ALOGVV("track(%d) s=%08x [OK]", trackId, cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08005977
5978 if (track->mFillingUpStatus == Track::FS_FILLED) {
5979 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07005980 if (last) {
5981 // make sure processVolume_l() will apply new volume even if 0
5982 mLeftVolFloat = mRightVolFloat = -1.0;
5983 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08005984 if (!mHwSupportsPause) {
5985 track->resumeAck();
Eric Laurent81784c32012-11-19 14:55:58 -08005986 }
5987 }
5988
5989 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08005990 processVolume_l(track, last);
5991 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07005992 sp<Track> previousTrack = mPreviousTrack.promote();
5993 if (previousTrack != 0) {
5994 if (track != previousTrack.get()) {
5995 // Flush any data still being written from last track
5996 mBytesRemaining = 0;
Eric Laurent0f0631e2015-07-06 18:01:25 -07005997 // Invalidate previous track to force a seek when resuming.
5998 previousTrack->invalidate();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005999 }
6000 }
6001 mPreviousTrack = track;
6002
Eric Laurentd595b7c2013-04-03 17:27:56 -07006003 // reset retry count
Andy Hung455982f2021-04-27 17:46:12 -07006004 track->mRetryCount = targetRetryCount;
Eric Laurent5850c4c2016-11-10 13:04:31 -08006005 mActiveTrack = t;
Eric Laurentd595b7c2013-04-03 17:27:56 -07006006 mixerStatus = MIXER_TRACKS_READY;
Eric Laurent5cff4032015-05-26 13:49:58 -07006007 if (mHwPaused) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08006008 doHwResume = true;
6009 mHwPaused = false;
6010 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07006011 }
Eric Laurent81784c32012-11-19 14:55:58 -08006012 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07006013 // clear effect chain input buffer if the last active track started underruns
6014 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07006015 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08006016 mEffectChains[0]->clearInputBuffer();
6017 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07006018 if (track->isStopping_1()) {
6019 track->mState = TrackBase::STOPPING_2;
Eric Laurentb369caf2015-03-30 20:51:47 -07006020 if (last && mHwPaused) {
6021 doHwResume = true;
6022 mHwPaused = false;
6023 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07006024 }
6025 if ((track->sharedBuffer() != 0) || track->isStopped() ||
6026 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08006027 // We have consumed all the buffers of this track.
6028 // Remove it from the list of active tracks.
Eric Laurentab5cdba2014-06-09 17:22:27 -07006029 size_t audioHALFrames;
Phil Burkfdb3c072016-02-09 10:47:02 -08006030 if (audio_has_proportional_frames(mFormat)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07006031 audioHALFrames = (latency_l() * mSampleRate) / 1000;
6032 } else {
6033 audioHALFrames = 0;
6034 }
6035
Andy Hung818e7a32016-02-16 18:08:07 -08006036 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurentfd477972013-10-25 18:10:40 -07006037 if (mStandby || !last ||
Aniket Kumar Lata179a0742019-01-30 14:16:16 -08006038 track->presentationComplete(framesWritten, audioHALFrames) ||
Jindong32dc26e2019-11-11 18:10:01 +08006039 track->isPaused() || mHwPaused) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07006040 if (track->isStopping_2()) {
6041 track->mState = TrackBase::STOPPED;
6042 }
Eric Laurent81784c32012-11-19 14:55:58 -08006043 if (track->isStopped()) {
6044 track->reset();
6045 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07006046 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08006047 }
6048 } else {
6049 // No buffers for this track. Give it a few chances to
6050 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07006051 // Only consider last track started for mixer state control
Eric Laurent81784c32012-11-19 14:55:58 -08006052 if (--(track->mRetryCount) <= 0) {
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07006053 ALOGV("BUFFER TIMEOUT: remove track(%d) from active list", trackId);
Eric Laurentd595b7c2013-04-03 17:27:56 -07006054 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08006055 // indicate to client process that the track was disabled because of underrun;
6056 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08006057 track->disable();
Haynes Mathew George5c6daae2017-01-24 20:06:05 -08006058 // only do hw pause when track is going to be removed due to BUFFER TIMEOUT.
6059 // unlike mixerthread, HAL can be paused for direct output
Phil Burkca5e6142015-07-14 09:42:29 -07006060 ALOGW("pause because of UNDERRUN, framesReady = %zu,"
6061 "minFrames = %u, mFormat = %#x",
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07006062 framesReady, minFrames, mFormat);
Haynes Mathew George5c6daae2017-01-24 20:06:05 -08006063 if (last && mHwSupportsPause && !mHwPaused && !mStandby) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08006064 doHwPause = true;
6065 mHwPaused = true;
6066 }
Haynes Mathew George5c6daae2017-01-24 20:06:05 -08006067 } else if (last) {
6068 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurent81784c32012-11-19 14:55:58 -08006069 }
6070 }
6071 }
6072 }
6073
Eric Laurentd1f69b02014-12-15 14:33:13 -08006074 // if an active track did not command a flush, check for pending flush on stopped tracks
Phil Burk43b4dcc2015-06-09 16:53:44 -07006075 if (!mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006076 for (size_t i = 0; i < mTracks.size(); i++) {
6077 if (mTracks[i]->isFlushPending()) {
6078 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006079 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006080 }
6081 }
6082 }
6083
6084 // make sure the pause/flush/resume sequence is executed in the right order.
6085 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
6086 // before flush and then resume HW. This can happen in case of pause/flush/resume
6087 // if resume is received before pause is executed.
6088 if (mHwSupportsPause && !mStandby &&
Phil Burk43b4dcc2015-06-09 16:53:44 -07006089 (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006090 status_t result = mOutput->stream->pause();
6091 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08006092 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07006093 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006094 flushHw_l();
6095 }
6096 if (mHwSupportsPause && !mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006097 status_t result = mOutput->stream->resume();
6098 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08006099 }
Eric Laurent81784c32012-11-19 14:55:58 -08006100 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08006101 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08006102
6103 return mixerStatus;
6104}
6105
6106void AudioFlinger::DirectOutputThread::threadLoop_mix()
6107{
Eric Laurent81784c32012-11-19 14:55:58 -08006108 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08006109 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08006110 // output audio to hardware
6111 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07006112 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08006113 buffer.frameCount = frameCount;
Phil Burk062e67a2015-02-11 13:40:50 -08006114 status_t status = mActiveTrack->getNextBuffer(&buffer);
6115 if (status != NO_ERROR || buffer.raw == NULL) {
Eric Laurent51716182016-02-29 18:00:56 -08006116 // no need to pad with 0 for compressed audio
6117 if (audio_has_proportional_frames(mFormat)) {
6118 memset(curBuf, 0, frameCount * mFrameSize);
6119 }
Eric Laurent81784c32012-11-19 14:55:58 -08006120 break;
6121 }
6122 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
6123 frameCount -= buffer.frameCount;
6124 curBuf += buffer.frameCount * mFrameSize;
6125 mActiveTrack->releaseBuffer(&buffer);
6126 }
Andy Hung2098f272014-02-27 14:00:06 -08006127 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006128 mSleepTimeUs = 0;
6129 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08006130 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08006131}
6132
6133void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
6134{
Eric Laurentd1f69b02014-12-15 14:33:13 -08006135 // do not write to HAL when paused
Eric Laurent0f7b5f22014-12-19 10:43:21 -08006136 if (mHwPaused || (usesHwAvSync() && mStandby)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006137 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006138 return;
6139 }
Andy Hung85ba3332021-04-27 17:40:26 -07006140 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
6141 mSleepTimeUs = mActiveSleepTimeUs;
6142 } else {
6143 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006144 }
Andy Hung85ba3332021-04-27 17:40:26 -07006145 // Note: In S or later, we do not write zeroes for
6146 // linear or proportional PCM direct tracks in underrun.
Eric Laurent81784c32012-11-19 14:55:58 -08006147}
6148
Eric Laurentd1f69b02014-12-15 14:33:13 -08006149void AudioFlinger::DirectOutputThread::threadLoop_exit()
6150{
6151 {
6152 Mutex::Autolock _l(mLock);
Eric Laurentd1f69b02014-12-15 14:33:13 -08006153 for (size_t i = 0; i < mTracks.size(); i++) {
6154 if (mTracks[i]->isFlushPending()) {
6155 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006156 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006157 }
6158 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07006159 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006160 flushHw_l();
6161 }
6162 }
6163 PlaybackThread::threadLoop_exit();
6164}
6165
6166// must be called with thread mutex locked
6167bool AudioFlinger::DirectOutputThread::shouldStandby_l()
6168{
6169 bool trackPaused = false;
Eric Laurentb369caf2015-03-30 20:51:47 -07006170 bool trackStopped = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006171
6172 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
6173 // after a timeout and we will enter standby then.
6174 if (mTracks.size() > 0) {
6175 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
Eric Laurentb369caf2015-03-30 20:51:47 -07006176 trackStopped = mTracks[mTracks.size() - 1]->isStopped() ||
6177 mTracks[mTracks.size() - 1]->mState == TrackBase::IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006178 }
6179
Eric Laurent5cff4032015-05-26 13:49:58 -07006180 return !mStandby && !(trackPaused || (mHwPaused && !trackStopped));
Eric Laurentd1f69b02014-12-15 14:33:13 -08006181}
6182
Eric Laurent10351942014-05-08 18:49:52 -07006183// checkForNewParameter_l() must be called with ThreadBase::mLock held
6184bool AudioFlinger::DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
6185 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08006186{
6187 bool reconfig = false;
Eric Laurent10351942014-05-08 18:49:52 -07006188 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006189
Eric Laurent10351942014-05-08 18:49:52 -07006190 AudioParameter param = AudioParameter(keyValuePair);
6191 int value;
6192 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07006193 LOG_FATAL("Should not set routing device in DirectOutputThread");
Eric Laurent81784c32012-11-19 14:55:58 -08006194 }
Eric Laurent10351942014-05-08 18:49:52 -07006195 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6196 // do not accept frame count changes if tracks are open as the track buffer
6197 // size depends on frame count and correct behavior would not be garantied
6198 // if frame count is changed after track creation
6199 if (!mTracks.isEmpty()) {
6200 status = INVALID_OPERATION;
6201 } else {
6202 reconfig = true;
6203 }
6204 }
6205 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006206 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07006207 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08006208 mOutput->standby();
Andy Hungcf10d742020-04-28 15:38:24 -07006209 if (!mStandby) {
6210 mThreadMetrics.logEndInterval();
6211 mStandby = true;
6212 }
Eric Laurent10351942014-05-08 18:49:52 -07006213 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006214 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07006215 }
6216 if (status == NO_ERROR && reconfig) {
6217 readOutputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07006218 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07006219 }
6220 }
6221
Dean Wheatley68918102021-03-19 22:09:19 +11006222 return reconfig;
Eric Laurent81784c32012-11-19 14:55:58 -08006223}
6224
6225uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
6226{
6227 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08006228 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006229 time = PlaybackThread::activeSleepTimeUs();
6230 } else {
Eric Laurent51716182016-02-29 18:00:56 -08006231 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006232 }
6233 return time;
6234}
6235
6236uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
6237{
6238 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08006239 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006240 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
6241 } else {
Eric Laurent51716182016-02-29 18:00:56 -08006242 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006243 }
6244 return time;
6245}
6246
6247uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
6248{
6249 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08006250 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006251 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
6252 } else {
Eric Laurent51716182016-02-29 18:00:56 -08006253 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006254 }
6255 return time;
6256}
6257
6258void AudioFlinger::DirectOutputThread::cacheParameters_l()
6259{
6260 PlaybackThread::cacheParameters_l();
6261
6262 // use shorter standby delay as on normal output to release
6263 // hardware resources as soon as possible
Eric Laurentb369caf2015-03-30 20:51:47 -07006264 // no delay on outputs with HW A/V sync
6265 if (usesHwAvSync()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006266 mStandbyDelayNs = 0;
Phil Burkfdb3c072016-02-09 10:47:02 -08006267 } else if ((mType == OFFLOAD) && !audio_has_proportional_frames(mFormat)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006268 mStandbyDelayNs = kOffloadStandbyDelayNs;
Eric Laurent5cff4032015-05-26 13:49:58 -07006269 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006270 mStandbyDelayNs = microseconds(mActiveSleepTimeUs*2);
Eric Laurent972a1732013-09-04 09:42:59 -07006271 }
Eric Laurent81784c32012-11-19 14:55:58 -08006272}
6273
Eric Laurente659ef42014-09-29 13:06:46 -07006274void AudioFlinger::DirectOutputThread::flushHw_l()
6275{
Phil Burk062e67a2015-02-11 13:40:50 -08006276 mOutput->flush();
Eric Laurentd1f69b02014-12-15 14:33:13 -08006277 mHwPaused = false;
Phil Burk43b4dcc2015-06-09 16:53:44 -07006278 mFlushPending = false;
Dean Wheatley12473e92021-03-18 23:00:55 +11006279 mTimestampVerifier.discontinuity(discontinuityForStandbyOrFlush());
Sampath Shetty999f0e82020-01-15 10:19:06 +11006280 mTimestamp.clear();
Eric Laurente659ef42014-09-29 13:06:46 -07006281}
6282
Andy Hung10cbff12017-02-21 17:30:14 -08006283int64_t AudioFlinger::DirectOutputThread::computeWaitTimeNs_l() const {
6284 // If a VolumeShaper is active, we must wake up periodically to update volume.
6285 const int64_t NS_PER_MS = 1000000;
6286 return mVolumeShaperActive ?
6287 kMinNormalSinkBufferSizeMs * NS_PER_MS : PlaybackThread::computeWaitTimeNs_l();
6288}
6289
Eric Laurent81784c32012-11-19 14:55:58 -08006290// ----------------------------------------------------------------------------
6291
Eric Laurentbfb1b832013-01-07 09:53:42 -08006292AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
Eric Laurent4de95592013-09-26 15:28:21 -07006293 const wp<AudioFlinger::PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006294 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07006295 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07006296 mWriteAckSequence(0),
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006297 mDrainSequence(0),
6298 mAsyncError(false)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006299{
6300}
6301
6302AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
6303{
6304}
6305
6306void AudioFlinger::AsyncCallbackThread::onFirstRef()
6307{
6308 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
6309}
6310
6311bool AudioFlinger::AsyncCallbackThread::threadLoop()
6312{
6313 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07006314 uint32_t writeAckSequence;
6315 uint32_t drainSequence;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006316 bool asyncError;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006317
6318 {
6319 Mutex::Autolock _l(mLock);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08006320 while (!((mWriteAckSequence & 1) ||
6321 (mDrainSequence & 1) ||
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006322 mAsyncError ||
Haynes Mathew George24a325d2013-12-03 21:26:02 -08006323 exitPending())) {
6324 mWaitWorkCV.wait(mLock);
6325 }
6326
Eric Laurentbfb1b832013-01-07 09:53:42 -08006327 if (exitPending()) {
6328 break;
6329 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07006330 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
6331 mWriteAckSequence, mDrainSequence);
6332 writeAckSequence = mWriteAckSequence;
6333 mWriteAckSequence &= ~1;
6334 drainSequence = mDrainSequence;
6335 mDrainSequence &= ~1;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006336 asyncError = mAsyncError;
6337 mAsyncError = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006338 }
6339 {
Eric Laurent4de95592013-09-26 15:28:21 -07006340 sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
6341 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07006342 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07006343 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006344 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07006345 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07006346 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006347 }
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006348 if (asyncError) {
6349 playbackThread->onAsyncError();
6350 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006351 }
6352 }
6353 }
6354 return false;
6355}
6356
6357void AudioFlinger::AsyncCallbackThread::exit()
6358{
6359 ALOGV("AsyncCallbackThread::exit");
6360 Mutex::Autolock _l(mLock);
6361 requestExit();
6362 mWaitWorkCV.broadcast();
6363}
6364
Eric Laurent3b4529e2013-09-05 18:09:19 -07006365void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006366{
6367 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07006368 // bit 0 is cleared
6369 mWriteAckSequence = sequence << 1;
6370}
6371
6372void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
6373{
6374 Mutex::Autolock _l(mLock);
6375 // ignore unexpected callbacks
6376 if (mWriteAckSequence & 2) {
6377 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006378 mWaitWorkCV.signal();
6379 }
6380}
6381
Eric Laurent3b4529e2013-09-05 18:09:19 -07006382void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006383{
6384 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07006385 // bit 0 is cleared
6386 mDrainSequence = sequence << 1;
6387}
6388
6389void AudioFlinger::AsyncCallbackThread::resetDraining()
6390{
6391 Mutex::Autolock _l(mLock);
6392 // ignore unexpected callbacks
6393 if (mDrainSequence & 2) {
6394 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006395 mWaitWorkCV.signal();
6396 }
6397}
6398
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006399void AudioFlinger::AsyncCallbackThread::setAsyncError()
6400{
6401 Mutex::Autolock _l(mLock);
6402 mAsyncError = true;
6403 mWaitWorkCV.signal();
6404}
6405
Eric Laurentbfb1b832013-01-07 09:53:42 -08006406
6407// ----------------------------------------------------------------------------
6408AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
jiabinc52b1ff2019-10-31 17:20:42 -07006409 AudioStreamOut* output, audio_io_handle_t id, bool systemReady)
6410 : DirectOutputThread(audioFlinger, output, id, OFFLOAD, systemReady),
Andy Hungf8044752016-07-27 14:58:11 -07006411 mPausedWriteLength(0), mPausedBytesRemaining(0), mKeepWakeLock(true),
6412 mOffloadUnderrunPosition(~0LL)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006413{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07006414 //FIXME: mStandby should be set to true by ThreadBase constructo
Eric Laurentfd477972013-10-25 18:10:40 -07006415 mStandby = true;
Eric Laurent64667972016-03-30 18:19:46 -07006416 mKeepWakeLock = property_get_bool("ro.audio.offload_wakelock", true /* default_value */);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006417}
6418
Eric Laurentbfb1b832013-01-07 09:53:42 -08006419void AudioFlinger::OffloadThread::threadLoop_exit()
6420{
6421 if (mFlushPending || mHwPaused) {
6422 // If a flush is pending or track was paused, just discard buffered data
6423 flushHw_l();
6424 } else {
6425 mMixerStatus = MIXER_DRAIN_ALL;
6426 threadLoop_drain();
6427 }
Uday Gupta56604aa2014-05-13 11:19:17 -07006428 if (mUseAsyncWrite) {
6429 ALOG_ASSERT(mCallbackThread != 0);
6430 mCallbackThread->exit();
6431 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006432 PlaybackThread::threadLoop_exit();
6433}
6434
6435AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
6436 Vector< sp<Track> > *tracksToRemove
6437)
6438{
Eric Laurentbfb1b832013-01-07 09:53:42 -08006439 size_t count = mActiveTracks.size();
6440
6441 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07006442 bool doHwPause = false;
6443 bool doHwResume = false;
6444
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006445 ALOGV("OffloadThread::prepareTracks_l active tracks %zu", count);
Eric Laurentede6c3b2013-09-19 14:37:46 -07006446
Eric Laurentbfb1b832013-01-07 09:53:42 -08006447 // find out which tracks need to be processed
Andy Hungdae27702016-10-31 14:01:16 -07006448 for (const sp<Track> &t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08006449 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006450#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurentbfb1b832013-01-07 09:53:42 -08006451 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006452#endif
Eric Laurentfd477972013-10-25 18:10:40 -07006453 // Only consider last track started for volume and mixer state control.
6454 // In theory an older track could underrun and restart after the new one starts
6455 // but as we only care about the transition phase between two tracks on a
6456 // direct output, it is not a problem to ignore the underrun case.
Andy Hungdae27702016-10-31 14:01:16 -07006457 sp<Track> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08006458 bool last = l.get() == track;
Eric Laurentfd477972013-10-25 18:10:40 -07006459
Haynes Mathew George7844f672014-01-15 12:32:55 -08006460 if (track->isInvalid()) {
6461 ALOGW("An invalidated track shouldn't be in active list");
6462 tracksToRemove->add(track);
6463 continue;
6464 }
6465
6466 if (track->mState == TrackBase::IDLE) {
6467 ALOGW("An idle track shouldn't be in active list");
6468 continue;
6469 }
6470
Kuowei Li23666472021-01-20 10:23:25 +08006471 if (track->isPausePending()) {
6472 track->pauseAck();
6473 // It is possible a track might have been flushed or stopped.
6474 // Other operations such as flush pending might occur on the next prepare.
6475 if (track->isPausing()) {
6476 track->setPaused();
6477 }
6478 // Always perform pause if last, as an immediate flush will change
6479 // the pause state to be no longer isPausing().
Eric Laurentbfb1b832013-01-07 09:53:42 -08006480 if (last) {
Eric Laurent5cff4032015-05-26 13:49:58 -07006481 if (mHwSupportsPause && !mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07006482 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006483 mHwPaused = true;
6484 }
6485 // If we were part way through writing the mixbuffer to
6486 // the HAL we must save this until we resume
6487 // BUG - this will be wrong if a different track is made active,
6488 // in that case we want to discard the pending data in the
6489 // mixbuffer and tell the client to present it again when the
6490 // track is resumed
6491 mPausedWriteLength = mCurrentWriteLength;
6492 mPausedBytesRemaining = mBytesRemaining;
6493 mBytesRemaining = 0; // stop writing
6494 }
6495 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08006496 } else if (track->isFlushPending()) {
Eric Laurente93cc032016-05-05 10:15:10 -07006497 if (track->isStopping_1()) {
6498 track->mRetryCount = kMaxTrackStopRetriesOffload;
6499 } else {
6500 track->mRetryCount = kMaxTrackRetriesOffload;
6501 }
Haynes Mathew George7844f672014-01-15 12:32:55 -08006502 track->flushAck();
6503 if (last) {
6504 mFlushPending = true;
6505 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08006506 } else if (track->isResumePending()){
6507 track->resumeAck();
6508 if (last) {
6509 if (mPausedBytesRemaining) {
6510 // Need to continue write that was interrupted
6511 mCurrentWriteLength = mPausedWriteLength;
6512 mBytesRemaining = mPausedBytesRemaining;
6513 mPausedBytesRemaining = 0;
6514 }
6515 if (mHwPaused) {
6516 doHwResume = true;
6517 mHwPaused = false;
6518 // threadLoop_mix() will handle the case that we need to
6519 // resume an interrupted write
6520 }
6521 // enable write to audio HAL
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006522 mSleepTimeUs = 0;
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08006523
Eric Laurent3df841a2016-07-15 15:15:40 -07006524 mLeftVolFloat = mRightVolFloat = -1.0;
6525
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08006526 // Do not handle new data in this iteration even if track->framesReady()
6527 mixerStatus = MIXER_TRACKS_ENABLED;
6528 }
6529 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07006530 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Andy Hungc0691382018-09-12 18:01:57 -07006531 ALOGVV("OffloadThread: track(%d) s=%08x [OK]", track->id(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006532 if (track->mFillingUpStatus == Track::FS_FILLED) {
6533 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07006534 if (last) {
6535 // make sure processVolume_l() will apply new volume even if 0
6536 mLeftVolFloat = mRightVolFloat = -1.0;
6537 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006538 }
6539
6540 if (last) {
Eric Laurentd7e59222013-11-15 12:02:28 -08006541 sp<Track> previousTrack = mPreviousTrack.promote();
6542 if (previousTrack != 0) {
6543 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08006544 // Flush any data still being written from last track
6545 mBytesRemaining = 0;
6546 if (mPausedBytesRemaining) {
6547 // Last track was paused so we also need to flush saved
6548 // mixbuffer state and invalidate track so that it will
6549 // re-submit that unwritten data when it is next resumed
6550 mPausedBytesRemaining = 0;
6551 // Invalidate is a bit drastic - would be more efficient
6552 // to have a flag to tell client that some of the
6553 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08006554 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08006555 }
6556 // flush data already sent to the DSP if changing audio session as audio
6557 // comes from a different source. Also invalidate previous track to force a
6558 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08006559 if (previousTrack->sessionId() != track->sessionId()) {
6560 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08006561 }
6562 }
6563 }
6564 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006565 // reset retry count
Eric Laurente93cc032016-05-05 10:15:10 -07006566 if (track->isStopping_1()) {
6567 track->mRetryCount = kMaxTrackStopRetriesOffload;
6568 } else {
6569 track->mRetryCount = kMaxTrackRetriesOffload;
6570 }
Eric Laurent5850c4c2016-11-10 13:04:31 -08006571 mActiveTrack = t;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006572 mixerStatus = MIXER_TRACKS_READY;
6573 }
6574 } else {
Andy Hungc0691382018-09-12 18:01:57 -07006575 ALOGVV("OffloadThread: track(%d) s=%08x [NOT READY]", track->id(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006576 if (track->isStopping_1()) {
Eric Laurente93cc032016-05-05 10:15:10 -07006577 if (--(track->mRetryCount) <= 0) {
6578 // Hardware buffer can hold a large amount of audio so we must
6579 // wait for all current track's data to drain before we say
6580 // that the track is stopped.
6581 if (mBytesRemaining == 0) {
6582 // Only start draining when all data in mixbuffer
6583 // has been written
6584 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
6585 track->mState = TrackBase::STOPPING_2; // so presentation completes after
6586 // drain do not drain if no data was ever sent to HAL (mStandby == true)
6587 if (last && !mStandby) {
6588 // do not modify drain sequence if we are already draining. This happens
6589 // when resuming from pause after drain.
6590 if ((mDrainSequence & 1) == 0) {
6591 mSleepTimeUs = 0;
6592 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
6593 mixerStatus = MIXER_DRAIN_TRACK;
6594 mDrainSequence += 2;
6595 }
6596 if (mHwPaused) {
6597 // It is possible to move from PAUSED to STOPPING_1 without
6598 // a resume so we must ensure hardware is running
6599 doHwResume = true;
6600 mHwPaused = false;
6601 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006602 }
6603 }
Eric Laurente93cc032016-05-05 10:15:10 -07006604 } else if (last) {
6605 ALOGV("stopping1 underrun retries left %d", track->mRetryCount);
6606 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006607 }
6608 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07006609 // Drain has completed or we are in standby, signal presentation complete
6610 if (!(mDrainSequence & 1) || !last || mStandby) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08006611 track->mState = TrackBase::STOPPED;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006612 uint32_t latency = 0;
6613 status_t result = mOutput->stream->getLatency(&latency);
6614 ALOGE_IF(result != OK,
6615 "Error when retrieving output stream latency: %d", result);
6616 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08006617 int64_t framesWritten =
Phil Burk062e67a2015-02-11 13:40:50 -08006618 mBytesWritten / mOutput->getFrameSize();
Eric Laurentbfb1b832013-01-07 09:53:42 -08006619 track->presentationComplete(framesWritten, audioHALFrames);
6620 track->reset();
6621 tracksToRemove->add(track);
Dean Wheatley12473e92021-03-18 23:00:55 +11006622 // OFFLOADED stop resets frame counts.
Andy Hungf3234512018-07-03 14:51:47 -07006623 if (!mUseAsyncWrite) {
6624 // If we don't get explicit drain notification we must
6625 // register discontinuity regardless of whether this is
6626 // the previous (!last) or the upcoming (last) track
6627 // to avoid skipping the discontinuity.
Dean Wheatley12473e92021-03-18 23:00:55 +11006628 mTimestampVerifier.discontinuity(
6629 mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Andy Hungf3234512018-07-03 14:51:47 -07006630 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006631 }
6632 } else {
6633 // No buffers for this track. Give it a few chances to
6634 // fill a buffer, then remove it from active list.
6635 if (--(track->mRetryCount) <= 0) {
Andy Hungf8044752016-07-27 14:58:11 -07006636 bool running = false;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006637 uint64_t position = 0;
6638 struct timespec unused;
6639 // The running check restarts the retry counter at least once.
6640 status_t ret = mOutput->stream->getPresentationPosition(&position, &unused);
6641 if (ret == NO_ERROR && position != mOffloadUnderrunPosition) {
6642 running = true;
6643 mOffloadUnderrunPosition = position;
6644 }
6645 if (ret == NO_ERROR) {
Andy Hungf8044752016-07-27 14:58:11 -07006646 ALOGVV("underrun counter, running(%d): %lld vs %lld", running,
6647 (long long)position, (long long)mOffloadUnderrunPosition);
6648 }
6649 if (running) { // still running, give us more time.
6650 track->mRetryCount = kMaxTrackRetriesOffload;
6651 } else {
Andy Hungc0691382018-09-12 18:01:57 -07006652 ALOGV("OffloadThread: BUFFER TIMEOUT: remove track(%d) from active list",
6653 track->id());
Andy Hungf8044752016-07-27 14:58:11 -07006654 tracksToRemove->add(track);
Glenn Kastend3bb6452016-12-05 18:14:37 -08006655 // tell client process that the track was disabled because of underrun;
Andy Hungf8044752016-07-27 14:58:11 -07006656 // it will then automatically call start() when data is available
6657 track->disable();
6658 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006659 } else if (last){
6660 mixerStatus = MIXER_TRACKS_ENABLED;
6661 }
6662 }
6663 }
6664 // compute volume for this track
Wenfeng Sun79458332019-05-29 20:12:43 +08006665 if (track->isReady()) { // check ready to prevent premature start.
6666 processVolume_l(track, last);
6667 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006668 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07006669
Eric Laurentea0fade2013-10-04 16:23:48 -07006670 // make sure the pause/flush/resume sequence is executed in the right order.
6671 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
6672 // before flush and then resume HW. This can happen in case of pause/flush/resume
6673 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07006674 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006675 status_t result = mOutput->stream->pause();
6676 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07006677 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07006678 if (mFlushPending) {
6679 flushHw_l();
Eric Laurent6bf9ae22013-08-30 15:12:37 -07006680 }
Eric Laurentfd477972013-10-25 18:10:40 -07006681 if (!mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006682 status_t result = mOutput->stream->resume();
6683 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07006684 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07006685
Eric Laurentbfb1b832013-01-07 09:53:42 -08006686 // remove all the tracks that need to be...
6687 removeTracks_l(*tracksToRemove);
6688
6689 return mixerStatus;
6690}
6691
Eric Laurentbfb1b832013-01-07 09:53:42 -08006692// must be called with thread mutex locked
6693bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
6694{
Eric Laurent3b4529e2013-09-05 18:09:19 -07006695 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
6696 mWriteAckSequence, mDrainSequence);
6697 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08006698 return true;
6699 }
6700 return false;
6701}
6702
Eric Laurentbfb1b832013-01-07 09:53:42 -08006703bool AudioFlinger::OffloadThread::waitingAsyncCallback()
6704{
6705 Mutex::Autolock _l(mLock);
6706 return waitingAsyncCallback_l();
6707}
6708
6709void AudioFlinger::OffloadThread::flushHw_l()
6710{
Eric Laurente659ef42014-09-29 13:06:46 -07006711 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08006712 // Flush anything still waiting in the mixbuffer
6713 mCurrentWriteLength = 0;
6714 mBytesRemaining = 0;
6715 mPausedWriteLength = 0;
6716 mPausedBytesRemaining = 0;
Eric Laurent3eaf66b2016-04-01 14:44:17 -07006717 // reset bytes written count to reflect that DSP buffers are empty after flush.
6718 mBytesWritten = 0;
Andy Hungf8044752016-07-27 14:58:11 -07006719 mOffloadUnderrunPosition = ~0LL;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08006720
Eric Laurentbfb1b832013-01-07 09:53:42 -08006721 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07006722 // discard any pending drain or write ack by incrementing sequence
6723 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
6724 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006725 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07006726 mCallbackThread->setWriteBlocked(mWriteAckSequence);
6727 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006728 }
6729}
6730
Haynes Mathew George05317d22016-05-03 16:34:26 -07006731void AudioFlinger::OffloadThread::invalidateTracks(audio_stream_type_t streamType)
6732{
6733 Mutex::Autolock _l(mLock);
Eric Laurent13084622016-05-17 10:51:49 -07006734 if (PlaybackThread::invalidateTracks_l(streamType)) {
6735 mFlushPending = true;
6736 }
Haynes Mathew George05317d22016-05-03 16:34:26 -07006737}
6738
Eric Laurentbfb1b832013-01-07 09:53:42 -08006739// ----------------------------------------------------------------------------
6740
Eric Laurent81784c32012-11-19 14:55:58 -08006741AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurent72e3f392015-05-20 14:43:50 -07006742 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id, bool systemReady)
jiabinc52b1ff2019-10-31 17:20:42 -07006743 : MixerThread(audioFlinger, mainThread->getOutput(), id,
Eric Laurent72e3f392015-05-20 14:43:50 -07006744 systemReady, DUPLICATING),
Eric Laurent81784c32012-11-19 14:55:58 -08006745 mWaitTimeMs(UINT_MAX)
6746{
6747 addOutputTrack(mainThread);
6748}
6749
6750AudioFlinger::DuplicatingThread::~DuplicatingThread()
6751{
6752 for (size_t i = 0; i < mOutputTracks.size(); i++) {
6753 mOutputTracks[i]->destroy();
6754 }
6755}
6756
6757void AudioFlinger::DuplicatingThread::threadLoop_mix()
6758{
6759 // mix buffers...
6760 if (outputsReady(outputTracks)) {
Glenn Kastend79072e2016-01-06 08:41:20 -08006761 mAudioMixer->process();
Eric Laurent81784c32012-11-19 14:55:58 -08006762 } else {
Eric Laurent02b57082014-11-07 17:28:28 -08006763 if (mMixerBufferValid) {
6764 memset(mMixerBuffer, 0, mMixerBufferSize);
6765 } else {
6766 memset(mSinkBuffer, 0, mSinkBufferSize);
6767 }
Eric Laurent81784c32012-11-19 14:55:58 -08006768 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006769 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08006770 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08006771 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006772 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08006773}
6774
6775void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
6776{
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006777 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006778 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006779 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006780 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006781 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006782 }
6783 } else if (mBytesWritten != 0) {
6784 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
6785 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08006786 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08006787 } else {
6788 // flush remaining overflow buffers in output tracks
6789 writeFrames = 0;
6790 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006791 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08006792 }
6793}
6794
Eric Laurentbfb1b832013-01-07 09:53:42 -08006795ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08006796{
6797 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hung1c86ebe2018-05-29 20:29:08 -07006798 const ssize_t actualWritten = outputTracks[i]->write(mSinkBuffer, writeFrames);
6799
6800 // Consider the first OutputTrack for timestamp and frame counting.
6801
6802 // The threadLoop() generally assumes writing a full sink buffer size at a time.
6803 // Here, we correct for writeFrames of 0 (a stop) or underruns because
6804 // we always claim success.
6805 if (i == 0) {
6806 const ssize_t correction = mSinkBufferSize / mFrameSize - actualWritten;
6807 ALOGD_IF(correction != 0 && writeFrames != 0,
6808 "%s: writeFrames:%u actualWritten:%zd correction:%zd mFramesWritten:%lld",
6809 __func__, writeFrames, actualWritten, correction, (long long)mFramesWritten);
6810 mFramesWritten -= correction;
6811 }
6812
6813 // TODO: Report correction for the other output tracks and show in the dump.
Eric Laurent81784c32012-11-19 14:55:58 -08006814 }
Andy Hungcf10d742020-04-28 15:38:24 -07006815 if (mStandby) {
6816 mThreadMetrics.logBeginInterval();
6817 mStandby = false;
6818 }
Andy Hung25c2dac2014-02-27 14:56:00 -08006819 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08006820}
6821
6822void AudioFlinger::DuplicatingThread::threadLoop_standby()
6823{
6824 // DuplicatingThread implements standby by stopping all tracks
6825 for (size_t i = 0; i < outputTracks.size(); i++) {
6826 outputTracks[i]->stop();
6827 }
6828}
6829
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07006830void AudioFlinger::DuplicatingThread::dumpInternals_l(int fd, const Vector<String16>& args __unused)
Andy Hung1bc088a2018-02-09 15:57:31 -08006831{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07006832 MixerThread::dumpInternals_l(fd, args);
Andy Hung1bc088a2018-02-09 15:57:31 -08006833
6834 std::stringstream ss;
6835 const size_t numTracks = mOutputTracks.size();
6836 ss << " " << numTracks << " OutputTracks";
6837 if (numTracks > 0) {
6838 ss << ":";
6839 for (const auto &track : mOutputTracks) {
6840 const sp<ThreadBase> thread = track->thread().promote();
Andy Hungc0691382018-09-12 18:01:57 -07006841 ss << " (" << track->id() << " : ";
Andy Hung1bc088a2018-02-09 15:57:31 -08006842 if (thread.get() != nullptr) {
6843 ss << thread.get() << ", " << thread->id();
6844 } else {
6845 ss << "null";
6846 }
6847 ss << ")";
6848 }
6849 }
6850 ss << "\n";
6851 std::string result = ss.str();
6852 write(fd, result.c_str(), result.size());
6853}
6854
Eric Laurent81784c32012-11-19 14:55:58 -08006855void AudioFlinger::DuplicatingThread::saveOutputTracks()
6856{
6857 outputTracks = mOutputTracks;
6858}
6859
6860void AudioFlinger::DuplicatingThread::clearOutputTracks()
6861{
6862 outputTracks.clear();
6863}
6864
6865void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
6866{
6867 Mutex::Autolock _l(mLock);
Andy Hungc25b84a2015-01-14 19:04:10 -08006868 // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
6869 // Adjust for thread->sampleRate() to determine minimum buffer frame count.
6870 // Then triple buffer because Threads do not run synchronously and may not be clock locked.
6871 const size_t frameCount =
6872 3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
6873 // TODO: Consider asynchronous sample rate conversion to handle clock disparity
6874 // from different OutputTracks and their associated MixerThreads (e.g. one may
6875 // nearly empty and the other may be dropping data).
6876
Philip P. Moltmannbda45752020-07-17 16:41:18 -07006877 // TODO b/182392769: use identity util, move to server edge
6878 Identity identity = Identity();
6879 identity.uid = VALUE_OR_FATAL(legacy2aidl_uid_t_int32_t(
6880 IPCThreadState::self()->getCallingUid()));
6881 identity.pid = VALUE_OR_FATAL(legacy2aidl_pid_t_int32_t(
6882 IPCThreadState::self()->getCallingPid()));
Andy Hungc25b84a2015-01-14 19:04:10 -08006883 sp<OutputTrack> outputTrack = new OutputTrack(thread,
Eric Laurent81784c32012-11-19 14:55:58 -08006884 this,
6885 mSampleRate,
Andy Hungc25b84a2015-01-14 19:04:10 -08006886 mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08006887 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08006888 frameCount,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07006889 identity);
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07006890 status_t status = outputTrack != 0 ? outputTrack->initCheck() : (status_t) NO_MEMORY;
6891 if (status != NO_ERROR) {
6892 ALOGE("addOutputTrack() initCheck failed %d", status);
6893 return;
Eric Laurent81784c32012-11-19 14:55:58 -08006894 }
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07006895 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
6896 mOutputTracks.add(outputTrack);
6897 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
6898 updateWaitTime_l();
Eric Laurent81784c32012-11-19 14:55:58 -08006899}
6900
6901void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
6902{
6903 Mutex::Autolock _l(mLock);
6904 for (size_t i = 0; i < mOutputTracks.size(); i++) {
6905 if (mOutputTracks[i]->thread() == thread) {
6906 mOutputTracks[i]->destroy();
6907 mOutputTracks.removeAt(i);
6908 updateWaitTime_l();
Eric Laurentf6870ae2015-05-08 10:50:03 -07006909 if (thread->getOutput() == mOutput) {
6910 mOutput = NULL;
6911 }
Eric Laurent81784c32012-11-19 14:55:58 -08006912 return;
6913 }
6914 }
Eric Laurentf6870ae2015-05-08 10:50:03 -07006915 ALOGV("removeOutputTrack(): unknown thread: %p", thread);
Eric Laurent81784c32012-11-19 14:55:58 -08006916}
6917
6918// caller must hold mLock
6919void AudioFlinger::DuplicatingThread::updateWaitTime_l()
6920{
6921 mWaitTimeMs = UINT_MAX;
6922 for (size_t i = 0; i < mOutputTracks.size(); i++) {
6923 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
6924 if (strong != 0) {
6925 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
6926 if (waitTimeMs < mWaitTimeMs) {
6927 mWaitTimeMs = waitTimeMs;
6928 }
6929 }
6930 }
6931}
6932
6933
6934bool AudioFlinger::DuplicatingThread::outputsReady(
6935 const SortedVector< sp<OutputTrack> > &outputTracks)
6936{
6937 for (size_t i = 0; i < outputTracks.size(); i++) {
6938 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
6939 if (thread == 0) {
6940 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
6941 outputTracks[i].get());
6942 return false;
6943 }
6944 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
6945 // see note at standby() declaration
6946 if (playbackThread->standby() && !playbackThread->isSuspended()) {
6947 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
6948 thread.get());
6949 return false;
6950 }
6951 }
6952 return true;
6953}
6954
Kevin Rocard12381092018-04-11 09:19:59 -07006955void AudioFlinger::DuplicatingThread::sendMetadataToBackend_l(
6956 const StreamOutHalInterface::SourceMetadata& metadata)
Kevin Rocard069c2712018-03-29 19:09:14 -07006957{
Kevin Rocard12381092018-04-11 09:19:59 -07006958 for (auto& outputTrack : outputTracks) { // not mOutputTracks
6959 outputTrack->setMetadatas(metadata.tracks);
6960 }
Kevin Rocard069c2712018-03-29 19:09:14 -07006961}
6962
Eric Laurent81784c32012-11-19 14:55:58 -08006963uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
6964{
6965 return (mWaitTimeMs * 1000) / 2;
6966}
6967
6968void AudioFlinger::DuplicatingThread::cacheParameters_l()
6969{
6970 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
6971 updateWaitTime_l();
6972
6973 MixerThread::cacheParameters_l();
6974}
6975
Eric Laurent6acd1d42017-01-04 14:23:29 -08006976
Eric Laurent81784c32012-11-19 14:55:58 -08006977// ----------------------------------------------------------------------------
6978// Record
6979// ----------------------------------------------------------------------------
6980
6981AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
6982 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08006983 audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -07006984 bool systemReady
Glenn Kasten46909e72013-02-26 09:20:22 -08006985 ) :
Andy Hungcf10d742020-04-28 15:38:24 -07006986 ThreadBase(audioFlinger, id, RECORD, systemReady, false /* isOut */),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07006987 mInput(input),
Mikhail Naganov2534b382019-09-25 13:05:02 -07006988 mSource(mInput),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07006989 mActiveTracks(&this->mLocalLog),
6990 mRsmpInBuffer(NULL),
Glenn Kasten1b291842016-07-18 14:55:21 -07006991 // mRsmpInFrames, mRsmpInFramesP2, and mRsmpInFramesOA are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006992 mRsmpInRear(0)
Glenn Kastenb880f5e2014-05-07 08:43:45 -07006993 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
6994 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006995 // mFastCapture below
6996 , mFastCaptureFutex(0)
6997 // mInputSource
6998 // mPipeSink
6999 // mPipeSource
7000 , mPipeFramesP2(0)
7001 // mPipeMemory
7002 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07007003 , mFastTrackAvail(false)
Eric Laurentd8365c52017-07-16 15:27:05 -07007004 , mBtNrecSuspended(false)
Eric Laurent81784c32012-11-19 14:55:58 -08007005{
Glenn Kastend7dca052015-03-05 16:05:54 -08007006 snprintf(mThreadName, kThreadNameLength, "AudioIn_%X", id);
7007 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08007008
George Burgess IVa8f90c12020-05-14 11:27:19 -07007009 if (mInput->audioHwDev != nullptr) {
Andy Hungc8fddf32018-08-08 18:32:37 -07007010 mIsMsdDevice = strcmp(
7011 mInput->audioHwDev->moduleName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0;
7012 }
7013
Glenn Kastendeca2ae2014-02-07 10:25:56 -08007014 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007015
Andy Hungc8fddf32018-08-08 18:32:37 -07007016 // TODO: We may also match on address as well as device type for
7017 // AUDIO_DEVICE_IN_BUS, AUDIO_DEVICE_IN_BLUETOOTH_A2DP, AUDIO_DEVICE_IN_REMOTE_SUBMIX
jiabinc52b1ff2019-10-31 17:20:42 -07007018 // TODO: This property should be ensure that only contains one single device type.
7019 mTimestampCorrectedDevice = (audio_devices_t)property_get_int64(
7020 "audio.timestamp.corrected_input_device",
Andy Hungc8fddf32018-08-08 18:32:37 -07007021 (int64_t)(mIsMsdDevice ? AUDIO_DEVICE_IN_BUS // turn on by default for MSD
7022 : AUDIO_DEVICE_NONE));
7023
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007024 // create an NBAIO source for the HAL input stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07007025 mInputSource = new AudioStreamInSource(input->stream);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007026 size_t numCounterOffers = 0;
7027 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07007028#if !LOG_NDEBUG
7029 ssize_t index =
7030#else
7031 (void)
7032#endif
7033 mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007034 ALOG_ASSERT(index == 0);
7035
7036 // initialize fast capture depending on configuration
7037 bool initFastCapture;
7038 switch (kUseFastCapture) {
7039 case FastCapture_Never:
7040 initFastCapture = false;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007041 ALOGV("%p kUseFastCapture = Never, initFastCapture = false", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007042 break;
7043 case FastCapture_Always:
7044 initFastCapture = true;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007045 ALOGV("%p kUseFastCapture = Always, initFastCapture = true", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007046 break;
7047 case FastCapture_Static:
Glenn Kasteneb9487e2015-07-22 09:15:17 -07007048 initFastCapture = (mFrameCount * 1000) / mSampleRate < kMinNormalCaptureBufferSizeMs;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007049 ALOGV("%p kUseFastCapture = Static, (%lld * 1000) / %u vs %u, initFastCapture = %d",
7050 this, (long long)mFrameCount, mSampleRate, kMinNormalCaptureBufferSizeMs,
7051 initFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007052 break;
7053 // case FastCapture_Dynamic:
7054 }
7055
7056 if (initFastCapture) {
Glenn Kastend198b852015-03-16 14:55:53 -07007057 // create a Pipe for FastCapture to write to, and for us and fast tracks to read from
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007058 NBAIO_Format format = mInputSource->format();
Glenn Kasten1b291842016-07-18 14:55:21 -07007059 // quadruple-buffering of 20 ms each; this ensures we can sleep for 20ms in RecordThread
7060 size_t pipeFramesP2 = roundup(4 * FMS_20 * mSampleRate / 1000);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007061 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007062 void *pipeBuffer = nullptr;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007063 const sp<MemoryDealer> roHeap(readOnlyHeap());
7064 sp<IMemory> pipeMemory;
7065 if ((roHeap == 0) ||
7066 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07007067 (pipeBuffer = pipeMemory->unsecurePointer()) == nullptr) {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007068 ALOGE("not enough memory for pipe buffer size=%zu; "
7069 "roHeap=%p, pipeMemory=%p, pipeBuffer=%p; roHeapSize: %lld",
7070 pipeSize, roHeap.get(), pipeMemory.get(), pipeBuffer,
7071 (long long)kRecordThreadReadOnlyHeapSize);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007072 goto failed;
7073 }
7074 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
7075 memset(pipeBuffer, 0, pipeSize);
7076 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
7077 const NBAIO_Format offers[1] = {format};
7078 size_t numCounterOffers = 0;
7079 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
7080 ALOG_ASSERT(index == 0);
7081 mPipeSink = pipe;
7082 PipeReader *pipeReader = new PipeReader(*pipe);
7083 numCounterOffers = 0;
7084 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
7085 ALOG_ASSERT(index == 0);
7086 mPipeSource = pipeReader;
7087 mPipeFramesP2 = pipeFramesP2;
7088 mPipeMemory = pipeMemory;
7089
7090 // create fast capture
7091 mFastCapture = new FastCapture();
7092 FastCaptureStateQueue *sq = mFastCapture->sq();
7093#ifdef STATE_QUEUE_DUMP
7094 // FIXME
7095#endif
7096 FastCaptureState *state = sq->begin();
7097 state->mCblk = NULL;
7098 state->mInputSource = mInputSource.get();
7099 state->mInputSourceGen++;
7100 state->mPipeSink = pipe;
7101 state->mPipeSinkGen++;
7102 state->mFrameCount = mFrameCount;
7103 state->mCommand = FastCaptureState::COLD_IDLE;
7104 // already done in constructor initialization list
7105 //mFastCaptureFutex = 0;
7106 state->mColdFutexAddr = &mFastCaptureFutex;
7107 state->mColdGen++;
7108 state->mDumpState = &mFastCaptureDumpState;
7109#ifdef TEE_SINK
7110 // FIXME
7111#endif
7112 mFastCaptureNBLogWriter = audioFlinger->newWriter_l(kFastCaptureLogSize, "FastCapture");
7113 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
7114 sq->end();
7115 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
7116
7117 // start the fast capture
7118 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
7119 pid_t tid = mFastCapture->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07007120 sendPrioConfigEvent(getpid(), tid, kPriorityFastCapture, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08007121 stream()->setHalThreadPriority(kPriorityFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007122#ifdef AUDIO_WATCHDOG
7123 // FIXME
7124#endif
7125
Glenn Kasten6e6704c2014-07-03 10:20:00 -07007126 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007127 }
Andy Hung8946a282018-04-19 20:04:56 -07007128#ifdef TEE_SINK
7129 mTee.set(mInputSource->format(), NBAIO_Tee::TEE_FLAG_INPUT_THREAD);
7130 mTee.setId(std::string("_") + std::to_string(mId) + "_C");
7131#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007132failed: ;
7133
7134 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08007135}
7136
Eric Laurent81784c32012-11-19 14:55:58 -08007137AudioFlinger::RecordThread::~RecordThread()
7138{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007139 if (mFastCapture != 0) {
7140 FastCaptureStateQueue *sq = mFastCapture->sq();
7141 FastCaptureState *state = sq->begin();
7142 if (state->mCommand == FastCaptureState::COLD_IDLE) {
7143 int32_t old = android_atomic_inc(&mFastCaptureFutex);
7144 if (old == -1) {
7145 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
7146 }
7147 }
7148 state->mCommand = FastCaptureState::EXIT;
7149 sq->end();
7150 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
7151 mFastCapture->join();
7152 mFastCapture.clear();
7153 }
7154 mAudioFlinger->unregisterWriter(mFastCaptureNBLogWriter);
Glenn Kasten481fb672013-09-30 14:39:28 -07007155 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung57446612015-04-19 23:56:46 -07007156 free(mRsmpInBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08007157}
7158
7159void AudioFlinger::RecordThread::onFirstRef()
7160{
Glenn Kastend7dca052015-03-05 16:05:54 -08007161 run(mThreadName, PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08007162}
7163
Eric Laurent555530a2017-02-07 18:17:24 -08007164void AudioFlinger::RecordThread::preExit()
7165{
7166 ALOGV(" preExit()");
7167 Mutex::Autolock _l(mLock);
7168 for (size_t i = 0; i < mTracks.size(); i++) {
7169 sp<RecordTrack> track = mTracks[i];
7170 track->invalidate();
7171 }
7172 mActiveTracks.clear();
7173 mStartStopCond.broadcast();
7174}
7175
Eric Laurent81784c32012-11-19 14:55:58 -08007176bool AudioFlinger::RecordThread::threadLoop()
7177{
Eric Laurent81784c32012-11-19 14:55:58 -08007178 nsecs_t lastWarning = 0;
7179
7180 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08007181
Glenn Kastenf10ffec2013-11-20 16:40:08 -08007182reacquire_wakelock:
7183 sp<RecordTrack> activeTrack;
7184 {
7185 Mutex::Autolock _l(mLock);
Andy Hungdae27702016-10-31 14:01:16 -07007186 acquireWakeLock_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08007187 }
7188
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007189 // used to request a deferred sleep, to be executed later while mutex is unlocked
7190 uint32_t sleepUs = 0;
7191
Andy Hung446f4df2019-02-21 12:26:41 -08007192 int64_t lastLoopCountRead = -2; // never matches "previous" loop, when loopCount = 0.
7193
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007194 // loop while there is work to do
Andy Hung446f4df2019-02-21 12:26:41 -08007195 for (int64_t loopCount = 0;; ++loopCount) { // loopCount used for statistics tracking
Glenn Kastenc527a7c2013-08-13 15:43:49 -07007196 Vector< sp<EffectChain> > effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07007197
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007198 // activeTracks accumulates a copy of a subset of mActiveTracks
7199 Vector< sp<RecordTrack> > activeTracks;
7200
Glenn Kasten735f45f2014-08-18 15:51:59 -07007201 // reference to the (first and only) active fast track
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007202 sp<RecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07007203
Glenn Kasten735f45f2014-08-18 15:51:59 -07007204 // reference to a fast track which is about to be removed
7205 sp<RecordTrack> fastTrackToRemove;
7206
Eric Laurent33403f02020-05-29 18:35:06 -07007207 bool silenceFastCapture = false;
7208
Eric Laurent81784c32012-11-19 14:55:58 -08007209 { // scope for mLock
7210 Mutex::Autolock _l(mLock);
Eric Laurent000a4192014-01-29 15:17:32 -08007211
Eric Laurent021cf962014-05-13 10:18:14 -07007212 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08007213
Eric Laurent000a4192014-01-29 15:17:32 -08007214 // check exitPending here because checkForNewParameters_l() and
7215 // checkForNewParameters_l() can temporarily release mLock
7216 if (exitPending()) {
7217 break;
7218 }
7219
Eric Laurent5c25d562016-07-13 17:17:45 -07007220 // sleep with mutex unlocked
7221 if (sleepUs > 0) {
Glenn Kastenf9715e42016-07-13 14:02:03 -07007222 ATRACE_BEGIN("sleepC");
Eric Laurent5c25d562016-07-13 17:17:45 -07007223 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)sleepUs));
7224 ATRACE_END();
7225 sleepUs = 0;
7226 continue;
7227 }
7228
Glenn Kasten2b806402013-11-20 16:37:38 -08007229 // if no active track(s), then standby and release wakelock
7230 size_t size = mActiveTracks.size();
7231 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07007232 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07007233 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08007234 releaseWakeLock_l();
7235 ALOGV("RecordThread: loop stopping");
7236 // go to sleep
7237 mWaitWorkCV.wait(mLock);
7238 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08007239 goto reacquire_wakelock;
7240 }
7241
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007242 bool doBroadcast = false;
Eric Laurent5c25d562016-07-13 17:17:45 -07007243 bool allStopped = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007244 for (size_t i = 0; i < size; ) {
Glenn Kasten9e982352013-08-14 14:39:50 -07007245
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007246 activeTrack = mActiveTracks[i];
7247 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07007248 if (activeTrack->isFastTrack()) {
7249 ALOG_ASSERT(fastTrackToRemove == 0);
7250 fastTrackToRemove = activeTrack;
7251 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007252 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08007253 mActiveTracks.remove(activeTrack);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007254 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07007255 continue;
7256 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007257
7258 TrackBase::track_state activeTrackState = activeTrack->mState;
7259 switch (activeTrackState) {
7260
7261 case TrackBase::PAUSING:
7262 mActiveTracks.remove(activeTrack);
Andy Hungce685402018-10-05 17:23:27 -07007263 activeTrack->mState = TrackBase::PAUSED;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007264 doBroadcast = true;
7265 size--;
7266 continue;
7267
7268 case TrackBase::STARTING_1:
7269 sleepUs = 10000;
7270 i++;
Eric Laurent5c25d562016-07-13 17:17:45 -07007271 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007272 continue;
7273
7274 case TrackBase::STARTING_2:
7275 doBroadcast = true;
Andy Hungcf10d742020-04-28 15:38:24 -07007276 if (mStandby) {
7277 mThreadMetrics.logBeginInterval();
7278 mStandby = false;
7279 }
Glenn Kasten9e982352013-08-14 14:39:50 -07007280 activeTrack->mState = TrackBase::ACTIVE;
Eric Laurent5c25d562016-07-13 17:17:45 -07007281 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007282 break;
7283
7284 case TrackBase::ACTIVE:
Eric Laurent5c25d562016-07-13 17:17:45 -07007285 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007286 break;
7287
Andy Hungce685402018-10-05 17:23:27 -07007288 case TrackBase::IDLE: // cannot be on ActiveTracks if idle
7289 case TrackBase::PAUSED: // cannot be on ActiveTracks if paused
7290 case TrackBase::STOPPED: // cannot be on ActiveTracks if destroyed/terminated
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007291 default:
Andy Hungce685402018-10-05 17:23:27 -07007292 LOG_ALWAYS_FATAL("%s: Unexpected active track state:%d, id:%d, tracks:%zu",
7293 __func__, activeTrackState, activeTrack->id(), size);
Glenn Kasten9e982352013-08-14 14:39:50 -07007294 }
Glenn Kasten9e982352013-08-14 14:39:50 -07007295
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007296 if (activeTrack->isFastTrack()) {
7297 ALOG_ASSERT(!mFastTrackAvail);
7298 ALOG_ASSERT(fastTrack == 0);
Eric Laurent33403f02020-05-29 18:35:06 -07007299 // if the active fast track is silenced either:
7300 // 1) silence the whole capture from fast capture buffer if this is
7301 // the only active track
7302 // 2) invalidate this track: this will cause the client to reconnect and possibly
7303 // be invalidated again until unsilenced
7304 if (activeTrack->isSilenced()) {
7305 if (size > 1) {
7306 activeTrack->invalidate();
7307 ALOG_ASSERT(fastTrackToRemove == 0);
7308 fastTrackToRemove = activeTrack;
7309 removeTrack_l(activeTrack);
7310 mActiveTracks.remove(activeTrack);
7311 size--;
7312 continue;
7313 } else {
7314 silenceFastCapture = true;
7315 }
7316 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007317 fastTrack = activeTrack;
7318 }
Eric Laurent33403f02020-05-29 18:35:06 -07007319
7320 activeTracks.add(activeTrack);
7321 i++;
7322
Glenn Kasten9e982352013-08-14 14:39:50 -07007323 }
Eric Laurent5c25d562016-07-13 17:17:45 -07007324
Andy Hungdae27702016-10-31 14:01:16 -07007325 mActiveTracks.updatePowerState(this);
7326
Kevin Rocard069c2712018-03-29 19:09:14 -07007327 updateMetadata_l();
7328
Eric Laurent5c25d562016-07-13 17:17:45 -07007329 if (allStopped) {
7330 standbyIfNotAlreadyInStandby();
7331 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007332 if (doBroadcast) {
7333 mStartStopCond.broadcast();
7334 }
7335
7336 // sleep if there are no active tracks to process
Eric Tan39ec8d62018-07-24 09:49:29 -07007337 if (activeTracks.isEmpty()) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007338 if (sleepUs == 0) {
7339 sleepUs = kRecordThreadSleepUs;
7340 }
7341 continue;
7342 }
7343 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07007344
Eric Laurent81784c32012-11-19 14:55:58 -08007345 lockEffectChains_l(effectChains);
7346 }
7347
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007348 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07007349
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007350 size_t size = effectChains.size();
7351 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07007352 // thread mutex is not locked, but effect chain is locked
7353 effectChains[i]->process_l();
7354 }
7355
Glenn Kasten735f45f2014-08-18 15:51:59 -07007356 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007357 if (mFastCapture != 0) {
7358 FastCaptureStateQueue *sq = mFastCapture->sq();
7359 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07007360 bool didModify = false;
7361 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007362 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
7363 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
7364 if (state->mCommand == FastCaptureState::COLD_IDLE) {
7365 int32_t old = android_atomic_inc(&mFastCaptureFutex);
7366 if (old == -1) {
7367 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
7368 }
7369 }
7370 state->mCommand = FastCaptureState::READ_WRITE;
7371#if 0 // FIXME
7372 mFastCaptureDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08007373 FastThreadDumpState::kSamplingNforLowRamDevice :
7374 FastThreadDumpState::kSamplingN);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007375#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07007376 didModify = true;
7377 }
7378 audio_track_cblk_t *cblkOld = state->mCblk;
7379 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
7380 if (cblkNew != cblkOld) {
7381 state->mCblk = cblkNew;
7382 // block until acked if removing a fast track
7383 if (cblkOld != NULL) {
7384 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
7385 }
7386 didModify = true;
7387 }
jiabin01c8f562018-07-19 17:47:28 -07007388 AudioBufferProvider* abp = (fastTrack != 0 && fastTrack->isPatchTrack()) ?
7389 reinterpret_cast<AudioBufferProvider*>(fastTrack.get()) : nullptr;
7390 if (state->mFastPatchRecordBufferProvider != abp) {
7391 state->mFastPatchRecordBufferProvider = abp;
7392 state->mFastPatchRecordFormat = fastTrack == 0 ?
7393 AUDIO_FORMAT_INVALID : fastTrack->format();
7394 didModify = true;
7395 }
Eric Laurent33403f02020-05-29 18:35:06 -07007396 if (state->mSilenceCapture != silenceFastCapture) {
7397 state->mSilenceCapture = silenceFastCapture;
7398 didModify = true;
7399 }
Glenn Kasten735f45f2014-08-18 15:51:59 -07007400 sq->end(didModify);
7401 if (didModify) {
7402 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007403#if 0
7404 if (kUseFastCapture == FastCapture_Dynamic) {
7405 mNormalSource = mPipeSource;
7406 }
7407#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007408 }
7409 }
7410
Glenn Kasten735f45f2014-08-18 15:51:59 -07007411 // now run the fast track destructor with thread mutex unlocked
7412 fastTrackToRemove.clear();
7413
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007414 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
7415 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
7416 // slow, then this RecordThread will overrun by not calling HAL read often enough.
7417 // If destination is non-contiguous, first read past the nominal end of buffer, then
7418 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07007419
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007420 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007421 ssize_t framesRead;
Andy Hung446f4df2019-02-21 12:26:41 -08007422 const int64_t lastIoBeginNs = systemTime(); // start IO timing
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007423
7424 // If an NBAIO source is present, use it to read the normal capture's data
7425 if (mPipeSource != 0) {
Andy Hung156317a2018-08-02 11:49:29 -07007426 size_t framesToRead = min(mRsmpInFramesOA - rear, mRsmpInFramesP2 / 2);
Andy Hungd5b638f2018-04-30 13:56:10 -07007427
7428 // The audio fifo read() returns OVERRUN on overflow, and advances the read pointer
7429 // to the full buffer point (clearing the overflow condition). Upon OVERRUN error,
7430 // we immediately retry the read() to get data and prevent another overflow.
7431 for (int retries = 0; retries <= 2; ++retries) {
7432 ALOGW_IF(retries > 0, "overrun on read from pipe, retry #%d", retries);
7433 framesRead = mPipeSource->read((uint8_t*)mRsmpInBuffer + rear * mFrameSize,
7434 framesToRead);
7435 if (framesRead != OVERRUN) break;
7436 }
7437
Andy Hung7a3dc6b2018-05-01 16:39:51 -07007438 const ssize_t availableToRead = mPipeSource->availableToRead();
7439 if (availableToRead >= 0) {
Glenn Kastena2f59b32020-08-03 16:37:24 -07007440 // PipeSource is the primary clock. It is up to the AudioRecord client to keep up.
Andy Hung7a3dc6b2018-05-01 16:39:51 -07007441 LOG_ALWAYS_FATAL_IF((size_t)availableToRead > mPipeFramesP2,
7442 "more frames to read than fifo size, %zd > %zu",
7443 availableToRead, mPipeFramesP2);
7444 const size_t pipeFramesFree = mPipeFramesP2 - availableToRead;
7445 const size_t sleepFrames = min(pipeFramesFree, mRsmpInFramesP2) / 2;
7446 ALOGVV("mPipeFramesP2:%zu mRsmpInFramesP2:%zu sleepFrames:%zu availableToRead:%zd",
7447 mPipeFramesP2, mRsmpInFramesP2, sleepFrames, availableToRead);
Glenn Kasten1b291842016-07-18 14:55:21 -07007448 sleepUs = (sleepFrames * 1000000LL) / mSampleRate;
7449 }
7450 if (framesRead < 0) {
7451 status_t status = (status_t) framesRead;
7452 switch (status) {
7453 case OVERRUN:
7454 ALOGW("overrun on read from pipe");
7455 framesRead = 0;
7456 break;
7457 case NEGOTIATE:
7458 ALOGE("re-negotiation is needed");
7459 framesRead = -1; // Will cause an attempt to recover.
7460 break;
7461 default:
7462 ALOGE("unknown error %d on read from pipe", status);
7463 break;
7464 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007465 }
7466 // otherwise use the HAL / AudioStreamIn directly
7467 } else {
Glenn Kastenec6a7032016-03-14 07:40:23 -07007468 ATRACE_BEGIN("read");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007469 size_t bytesRead;
Mikhail Naganov2534b382019-09-25 13:05:02 -07007470 status_t result = mSource->read(
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007471 (uint8_t*)mRsmpInBuffer + rear * mFrameSize, mBufferSize, &bytesRead);
Glenn Kastenec6a7032016-03-14 07:40:23 -07007472 ATRACE_END();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007473 if (result < 0) {
7474 framesRead = result;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007475 } else {
7476 framesRead = bytesRead / mFrameSize;
7477 }
7478 }
7479
Andy Hung446f4df2019-02-21 12:26:41 -08007480 const int64_t lastIoEndNs = systemTime(); // end IO timing
7481
Andy Hung3f0c9022016-01-15 17:49:46 -08007482 // Update server timestamp with server stats
7483 // systemTime() is optional if the hardware supports timestamps.
Andy Hung743f6402020-06-03 13:17:04 -07007484 if (framesRead >= 0) {
7485 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += framesRead;
7486 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = lastIoEndNs;
7487 }
Andy Hung3f0c9022016-01-15 17:49:46 -08007488
7489 // Update server timestamp with kernel stats
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007490 if (mPipeSource.get() == nullptr /* don't obtain for FastCapture, could block */) {
Andy Hung3f0c9022016-01-15 17:49:46 -08007491 int64_t position, time;
Andy Hung2e2c0bb2018-06-11 19:13:11 -07007492 if (mStandby) {
Dean Wheatley12473e92021-03-18 23:00:55 +11007493 mTimestampVerifier.discontinuity(audio_is_linear_pcm(mFormat) ?
7494 mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS :
7495 mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Mikhail Naganov2534b382019-09-25 13:05:02 -07007496 } else if (mSource->getCapturePosition(&position, &time) == NO_ERROR
Andy Hungc8fddf32018-08-08 18:32:37 -07007497 && time > mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]) {
7498
7499 mTimestampVerifier.add(position, time, mSampleRate);
7500
7501 // Correct timestamps
7502 if (isTimestampCorrectionEnabled()) {
Dean Wheatley56a583e2020-05-08 15:12:17 +10007503 ALOGVV("TS_BEFORE: %d %lld %lld",
Andy Hungc8fddf32018-08-08 18:32:37 -07007504 id(), (long long)time, (long long)position);
7505 auto correctedTimestamp = mTimestampVerifier.getLastCorrectedTimestamp();
7506 position = correctedTimestamp.mFrames;
7507 time = correctedTimestamp.mTimeNs;
Dean Wheatley56a583e2020-05-08 15:12:17 +10007508 ALOGVV("TS_AFTER: %d %lld %lld",
Andy Hungc8fddf32018-08-08 18:32:37 -07007509 id(), (long long)time, (long long)position);
7510 }
7511
Andy Hung3f0c9022016-01-15 17:49:46 -08007512 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = position;
7513 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] = time;
7514 // Note: In general record buffers should tend to be empty in
7515 // a properly running pipeline.
7516 //
7517 // Also, it is not advantageous to call get_presentation_position during the read
7518 // as the read obtains a lock, preventing the timestamp call from executing.
Andy Hung2e2c0bb2018-06-11 19:13:11 -07007519 } else {
7520 mTimestampVerifier.error();
Andy Hung3f0c9022016-01-15 17:49:46 -08007521 }
7522 }
Andy Hunge6c37112019-02-26 17:38:10 -08007523
7524 // From the timestamp, input read latency is negative output write latency.
7525 const audio_input_flags_t flags = mInput != NULL ? mInput->flags : AUDIO_INPUT_FLAG_NONE;
7526 const double latencyMs = RecordTrack::checkServerLatencySupported(mFormat, flags)
7527 ? - mTimestamp.getOutputServerLatencyMs(mSampleRate) : 0.;
7528 if (latencyMs != 0.) { // note 0. means timestamp is empty.
7529 mLatencyMs.add(latencyMs);
7530 }
7531
Andy Hung3f0c9022016-01-15 17:49:46 -08007532 // Use this to track timestamp information
7533 // ALOGD("%s", mTimestamp.toString().c_str());
7534
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007535 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07007536 ALOGE("read failed: framesRead=%zd", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007537 // Force input into standby so that it tries to recover at next read attempt
7538 inputStandBy();
7539 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007540 }
7541 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07007542 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07007543 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007544 ALOG_ASSERT(framesRead > 0);
Andy Hung6427e442018-08-09 12:51:02 -07007545 mFramesRead += framesRead;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007546
Andy Hung8946a282018-04-19 20:04:56 -07007547#ifdef TEE_SINK
7548 (void)mTee.write((uint8_t*)mRsmpInBuffer + rear * mFrameSize, framesRead);
7549#endif
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007550 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07007551 {
7552 size_t part1 = mRsmpInFramesP2 - rear;
7553 if ((size_t) framesRead > part1) {
Andy Hung57446612015-04-19 23:56:46 -07007554 memcpy(mRsmpInBuffer, (uint8_t*)mRsmpInBuffer + mRsmpInFramesP2 * mFrameSize,
Glenn Kasten3d61bc12014-06-16 10:25:20 -07007555 (framesRead - part1) * mFrameSize);
7556 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007557 }
Dean Wheatleyfd56e812020-11-06 22:32:21 +11007558 mRsmpInRear = audio_utils::safe_add_overflow(mRsmpInRear, (int32_t)framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007559
7560 size = activeTracks.size();
Svet Ganovf4ddfef2018-01-16 07:37:58 -08007561
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007562 // loop over each active track
7563 for (size_t i = 0; i < size; i++) {
7564 activeTrack = activeTracks[i];
7565
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007566 // skip fast tracks, as those are handled directly by FastCapture
7567 if (activeTrack->isFastTrack()) {
7568 continue;
7569 }
7570
Andy Hung73c02e42015-03-29 01:13:58 -07007571 // TODO: This code probably should be moved to RecordTrack.
Andy Hung97a893e2015-03-29 01:03:07 -07007572 // TODO: Update the activeTrack buffer converter in case of reconfigure.
7573
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007574 enum {
7575 OVERRUN_UNKNOWN,
7576 OVERRUN_TRUE,
7577 OVERRUN_FALSE
7578 } overrun = OVERRUN_UNKNOWN;
7579
7580 // loop over getNextBuffer to handle circular sink
7581 for (;;) {
7582
7583 activeTrack->mSink.frameCount = ~0;
7584 status_t status = activeTrack->getNextBuffer(&activeTrack->mSink);
7585 size_t framesOut = activeTrack->mSink.frameCount;
7586 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
7587
Andy Hung73c02e42015-03-29 01:13:58 -07007588 // check available frames and handle overrun conditions
7589 // if the record track isn't draining fast enough.
7590 bool hasOverrun;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007591 size_t framesIn;
Andy Hung73c02e42015-03-29 01:13:58 -07007592 activeTrack->mResamplerBufferProvider->sync(&framesIn, &hasOverrun);
7593 if (hasOverrun) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007594 overrun = OVERRUN_TRUE;
7595 }
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007596 if (framesOut == 0 || framesIn == 0) {
7597 break;
7598 }
7599
Andy Hung6770c6f2015-04-07 13:43:36 -07007600 // Don't allow framesOut to be larger than what is possible with resampling
7601 // from framesIn.
7602 // This isn't strictly necessary but helps limit buffer resizing in
7603 // RecordBufferConverter. TODO: remove when no longer needed.
7604 framesOut = min(framesOut,
7605 destinationFramesPossible(
7606 framesIn, mSampleRate, activeTrack->mSampleRate));
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07007607
7608 if (activeTrack->isDirect()) {
Daniel Van Veen9e2376e2018-09-27 14:37:58 +10007609 // No RecordBufferConverter used for direct streams. Pass
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07007610 // straight from RecordThread buffer to RecordTrack buffer.
7611 AudioBufferProvider::Buffer buffer;
7612 buffer.frameCount = framesOut;
7613 status_t status = activeTrack->mResamplerBufferProvider->getNextBuffer(&buffer);
7614 if (status == OK && buffer.frameCount != 0) {
7615 ALOGV_IF(buffer.frameCount != framesOut,
7616 "%s() read less than expected (%zu vs %zu)",
7617 __func__, buffer.frameCount, framesOut);
7618 framesOut = buffer.frameCount;
Daniel Van Veen9e2376e2018-09-27 14:37:58 +10007619 memcpy(activeTrack->mSink.raw, buffer.raw, buffer.frameCount * mFrameSize);
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07007620 activeTrack->mResamplerBufferProvider->releaseBuffer(&buffer);
7621 } else {
7622 framesOut = 0;
7623 ALOGE("%s() cannot fill request, status: %d, frameCount: %zu",
7624 __func__, status, buffer.frameCount);
7625 }
7626 } else {
7627 // process frames from the RecordThread buffer provider to the RecordTrack
7628 // buffer
7629 framesOut = activeTrack->mRecordBufferConverter->convert(
7630 activeTrack->mSink.raw,
7631 activeTrack->mResamplerBufferProvider,
7632 framesOut);
7633 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007634
7635 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
7636 overrun = OVERRUN_FALSE;
7637 }
7638
7639 if (activeTrack->mFramesToDrop == 0) {
7640 if (framesOut > 0) {
7641 activeTrack->mSink.frameCount = framesOut;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08007642 // Sanitize before releasing if the track has no access to the source data
7643 // An idle UID receives silence from non virtual devices until active
7644 if (activeTrack->isSilenced()) {
Jean-Michel Trividdf87ef2019-08-20 15:42:04 -07007645 memset(activeTrack->mSink.raw, 0, framesOut * activeTrack->frameSize());
Svet Ganovf4ddfef2018-01-16 07:37:58 -08007646 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007647 activeTrack->releaseBuffer(&activeTrack->mSink);
7648 }
7649 } else {
7650 // FIXME could do a partial drop of framesOut
7651 if (activeTrack->mFramesToDrop > 0) {
Mikhail Naganov6d91ba52019-03-26 14:35:28 -07007652 activeTrack->mFramesToDrop -= (ssize_t)framesOut;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007653 if (activeTrack->mFramesToDrop <= 0) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08007654 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007655 }
7656 } else {
7657 activeTrack->mFramesToDrop += framesOut;
7658 if (activeTrack->mFramesToDrop >= 0 || activeTrack->mSyncStartEvent == 0 ||
7659 activeTrack->mSyncStartEvent->isCancelled()) {
7660 ALOGW("Synced record %s, session %d, trigger session %d",
7661 (activeTrack->mFramesToDrop >= 0) ? "timed out" : "cancelled",
7662 activeTrack->sessionId(),
7663 (activeTrack->mSyncStartEvent != 0) ?
Glenn Kastend848eb42016-03-08 13:42:11 -08007664 activeTrack->mSyncStartEvent->triggerSession() :
7665 AUDIO_SESSION_NONE);
Glenn Kasten25f4aa82014-02-07 10:50:43 -08007666 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007667 }
7668 }
7669 }
7670
7671 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007672 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07007673 }
7674 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007675
7676 switch (overrun) {
7677 case OVERRUN_TRUE:
7678 // client isn't retrieving buffers fast enough
7679 if (!activeTrack->setOverflow()) {
7680 nsecs_t now = systemTime();
7681 // FIXME should lastWarning per track?
7682 if ((now - lastWarning) > kWarningThrottleNs) {
7683 ALOGW("RecordThread: buffer overflow");
7684 lastWarning = now;
7685 }
7686 }
7687 break;
7688 case OVERRUN_FALSE:
7689 activeTrack->clearOverflow();
7690 break;
7691 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007692 break;
7693 }
7694
Andy Hung3f0c9022016-01-15 17:49:46 -08007695 // update frame information and push timestamp out
7696 activeTrack->updateTrackFrameInfo(
Andy Hung6ae58432016-02-16 18:32:24 -08007697 activeTrack->mServerProxy->framesReleased(),
Andy Hung3f0c9022016-01-15 17:49:46 -08007698 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER],
7699 mSampleRate, mTimestamp);
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07007700 }
7701
Glenn Kasten3d61bc12014-06-16 10:25:20 -07007702unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08007703 // enable changes in effect chain
7704 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07007705 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurentcccbc762019-04-05 14:20:05 -07007706 if (audio_has_proportional_frames(mFormat)
7707 && loopCount == lastLoopCountRead + 1) {
7708 const int64_t readPeriodNs = lastIoEndNs - mLastIoEndNs;
7709 const double jitterMs =
7710 TimestampVerifier<int64_t, int64_t>::computeJitterMs(
7711 {framesRead, readPeriodNs},
7712 {0, 0} /* lastTimestamp */, mSampleRate);
7713 const double processMs = (lastIoBeginNs - mLastIoEndNs) * 1e-6;
7714
7715 Mutex::Autolock _l(mLock);
7716 mIoJitterMs.add(jitterMs);
7717 mProcessTimeMs.add(processMs);
7718 }
7719 // update timing info.
7720 mLastIoBeginNs = lastIoBeginNs;
7721 mLastIoEndNs = lastIoEndNs;
7722 lastLoopCountRead = loopCount;
Eric Laurent81784c32012-11-19 14:55:58 -08007723 }
7724
Glenn Kasten93e471f2013-08-19 08:40:07 -07007725 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08007726
7727 {
7728 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07007729 for (size_t i = 0; i < mTracks.size(); i++) {
7730 sp<RecordTrack> track = mTracks[i];
7731 track->invalidate();
7732 }
Glenn Kasten2b806402013-11-20 16:37:38 -08007733 mActiveTracks.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08007734 mStartStopCond.broadcast();
7735 }
7736
7737 releaseWakeLock();
7738
7739 ALOGV("RecordThread %p exiting", this);
7740 return false;
7741}
7742
Glenn Kasten93e471f2013-08-19 08:40:07 -07007743void AudioFlinger::RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08007744{
7745 if (!mStandby) {
7746 inputStandBy();
Andy Hungcf10d742020-04-28 15:38:24 -07007747 mThreadMetrics.logEndInterval();
Eric Laurent81784c32012-11-19 14:55:58 -08007748 mStandby = true;
7749 }
7750}
7751
7752void AudioFlinger::RecordThread::inputStandBy()
7753{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007754 // Idle the fast capture if it's currently running
7755 if (mFastCapture != 0) {
7756 FastCaptureStateQueue *sq = mFastCapture->sq();
7757 FastCaptureState *state = sq->begin();
7758 if (!(state->mCommand & FastCaptureState::IDLE)) {
7759 state->mCommand = FastCaptureState::COLD_IDLE;
7760 state->mColdFutexAddr = &mFastCaptureFutex;
7761 state->mColdGen++;
7762 mFastCaptureFutex = 0;
7763 sq->end();
7764 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
7765 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
7766#if 0
7767 if (kUseFastCapture == FastCapture_Dynamic) {
7768 // FIXME
7769 }
7770#endif
7771#ifdef AUDIO_WATCHDOG
7772 // FIXME
7773#endif
7774 } else {
7775 sq->end(false /*didModify*/);
7776 }
7777 }
Mikhail Naganov2534b382019-09-25 13:05:02 -07007778 status_t result = mSource->standby();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007779 ALOGE_IF(result != OK, "Error when putting input stream into standby: %d", result);
Andy Hungad6d52d2016-07-18 13:42:03 -07007780
7781 // If going into standby, flush the pipe source.
7782 if (mPipeSource.get() != nullptr) {
7783 const ssize_t flushed = mPipeSource->flush();
7784 if (flushed > 0) {
7785 ALOGV("Input standby flushed PipeSource %zd frames", flushed);
7786 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += flushed;
7787 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
7788 }
7789 }
Eric Laurent81784c32012-11-19 14:55:58 -08007790}
7791
Glenn Kasten05997e22014-03-13 15:08:33 -07007792// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastene198c362013-08-13 09:13:36 -07007793sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
Eric Laurent81784c32012-11-19 14:55:58 -08007794 const sp<AudioFlinger::Client>& client,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07007795 const audio_attributes_t& attr,
Eric Laurentf14db3c2017-12-08 14:20:36 -08007796 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08007797 audio_format_t format,
7798 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08007799 size_t *pFrameCount,
Glenn Kastend848eb42016-03-08 13:42:11 -08007800 audio_session_t sessionId,
Eric Laurentf14db3c2017-12-08 14:20:36 -08007801 size_t *pNotificationFrameCount,
Eric Laurent09f1ed22019-04-24 17:45:17 -07007802 pid_t creatorPid,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07007803 const Identity& identity,
Eric Laurent05067782016-06-01 18:27:28 -07007804 audio_input_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08007805 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08007806 status_t *status,
Eric Laurentec376dc2021-04-08 20:41:22 +02007807 audio_port_handle_t portId,
7808 int32_t maxSharedAudioHistoryMs)
Eric Laurent81784c32012-11-19 14:55:58 -08007809{
Glenn Kasten74935e42013-12-19 08:56:45 -08007810 size_t frameCount = *pFrameCount;
Eric Laurentf14db3c2017-12-08 14:20:36 -08007811 size_t notificationFrameCount = *pNotificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08007812 sp<RecordTrack> track;
7813 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07007814 audio_input_flags_t inputFlags = mInput->flags;
Eric Laurentf14db3c2017-12-08 14:20:36 -08007815 audio_input_flags_t requestedFlags = *flags;
7816 uint32_t sampleRate;
Eric Laurentec376dc2021-04-08 20:41:22 +02007817 Identity checkedIdentity = AudioFlinger::checkIdentityPackage(identity);
Eric Laurentf14db3c2017-12-08 14:20:36 -08007818
7819 lStatus = initCheck();
7820 if (lStatus != NO_ERROR) {
7821 ALOGE("createRecordTrack_l() audio driver not initialized");
7822 goto Exit;
7823 }
7824
Mikhail Naganovce9f2652018-07-16 11:09:24 -07007825 if (!audio_is_linear_pcm(mFormat) && (*flags & AUDIO_INPUT_FLAG_DIRECT) == 0) {
7826 ALOGE("createRecordTrack_l() on an encoded stream requires AUDIO_INPUT_FLAG_DIRECT");
7827 lStatus = BAD_VALUE;
7828 goto Exit;
7829 }
7830
Eric Laurentec376dc2021-04-08 20:41:22 +02007831 if (maxSharedAudioHistoryMs != 0) {
7832 if (!captureHotwordAllowed(checkedIdentity)) {
7833 lStatus = PERMISSION_DENIED;
7834 goto Exit;
7835 }
7836 //TODO: b/185972521 allow resampling buffer resizing on fast mixers by pausing
7837 // the fast mixer thread while resizing the buffer in the normal thread
7838 if (hasFastCapture()) {
7839 lStatus = BAD_VALUE;
7840 goto Exit;
7841 }
7842 if (maxSharedAudioHistoryMs < 0
7843 || maxSharedAudioHistoryMs > AudioFlinger::kMaxSharedAudioHistoryMs) {
7844 lStatus = BAD_VALUE;
7845 goto Exit;
7846 }
7847 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08007848 if (*pSampleRate == 0) {
7849 *pSampleRate = mSampleRate;
7850 }
7851 sampleRate = *pSampleRate;
Eric Laurent05067782016-06-01 18:27:28 -07007852
7853 // special case for FAST flag considered OK if fast capture is present
7854 if (hasFastCapture()) {
7855 inputFlags = (audio_input_flags_t)(inputFlags | AUDIO_INPUT_FLAG_FAST);
7856 }
7857
Eric Laurentf14db3c2017-12-08 14:20:36 -08007858 // Check if requested flags are compatible with input stream flags
Eric Laurent05067782016-06-01 18:27:28 -07007859 if ((*flags & inputFlags) != *flags) {
7860 ALOGW("createRecordTrack_l(): mismatch between requested flags (%08x) and"
7861 " input flags (%08x)",
7862 *flags, inputFlags);
7863 *flags = (audio_input_flags_t)(*flags & inputFlags);
7864 }
Eric Laurent81784c32012-11-19 14:55:58 -08007865
Glenn Kasten90e58b12013-07-31 16:16:02 -07007866 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07007867 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07007868 if (
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07007869 // we formerly checked for a callback handler (non-0 tid),
7870 // but that is no longer required for TRANSFER_OBTAIN mode
7871 //
Phil Burk7ed66a12019-04-18 13:20:30 -07007872 // Frame count is not specified (0), or is less than or equal the pipe depth.
7873 // It is OK to provide a higher capacity than requested.
7874 // We will force it to mPipeFramesP2 below.
7875 (frameCount <= mPipeFramesP2) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07007876 // PCM data
7877 audio_is_linear_pcm(format) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08007878 // hardware format
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007879 (format == mFormat) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08007880 // hardware channel mask
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007881 (channelMask == mChannelMask) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08007882 // hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07007883 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07007884 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007885 hasFastCapture() &&
7886 // there are sufficient fast track slots available
7887 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07007888 ) {
Eric Laurent4c415062016-06-17 16:14:16 -07007889 // check compatibility with audio effects.
7890 Mutex::Autolock _l(mLock);
7891 // Do not accept FAST flag if the session has software effects
7892 sp<EffectChain> chain = getEffectChain_l(sessionId);
7893 if (chain != 0) {
Andy Hungd3bb0ad2016-10-11 17:16:43 -07007894 audio_input_flags_t old = *flags;
7895 chain->checkInputFlagCompatibility(flags);
7896 if (old != *flags) {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007897 ALOGV("%p AUDIO_INPUT_FLAGS denied by effect old=%#x new=%#x",
7898 this, (int)old, (int)*flags);
Eric Laurent4c415062016-06-17 16:14:16 -07007899 }
7900 }
Eric Laurent122f7e72016-06-29 11:53:29 -07007901 ALOGV_IF((*flags & AUDIO_INPUT_FLAG_FAST) != 0,
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007902 "%p AUDIO_INPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
7903 this, frameCount, mFrameCount);
Glenn Kasten90e58b12013-07-31 16:16:02 -07007904 } else {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007905 ALOGV("%p AUDIO_INPUT_FLAG_FAST denied: frameCount=%zu mFrameCount=%zu mPipeFramesP2=%zu "
7906 "format=%#x isLinear=%d mFormat=%#x channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007907 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007908 this, frameCount, mFrameCount, mPipeFramesP2,
7909 format, audio_is_linear_pcm(format), mFormat, channelMask, sampleRate, mSampleRate,
Glenn Kasten74105912014-07-03 12:28:53 -07007910 hasFastCapture(), tid, mFastTrackAvail);
Eric Laurent05067782016-06-01 18:27:28 -07007911 *flags = (audio_input_flags_t)(*flags & ~AUDIO_INPUT_FLAG_FAST);
Glenn Kasten74105912014-07-03 12:28:53 -07007912 }
7913 }
7914
Eric Laurentf14db3c2017-12-08 14:20:36 -08007915 // If FAST or RAW flags were corrected, ask caller to request new input from audio policy
7916 if ((*flags & AUDIO_INPUT_FLAG_FAST) !=
7917 (requestedFlags & AUDIO_INPUT_FLAG_FAST)) {
7918 *flags = (audio_input_flags_t) (*flags & ~(AUDIO_INPUT_FLAG_FAST | AUDIO_INPUT_FLAG_RAW));
7919 lStatus = BAD_TYPE;
7920 goto Exit;
7921 }
7922
Glenn Kasten74105912014-07-03 12:28:53 -07007923 // compute track buffer size in frames, and suggest the notification frame count
Eric Laurent05067782016-06-01 18:27:28 -07007924 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten74105912014-07-03 12:28:53 -07007925 // fast track: frame count is exactly the pipe depth
7926 frameCount = mPipeFramesP2;
7927 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
Eric Laurentf14db3c2017-12-08 14:20:36 -08007928 notificationFrameCount = mFrameCount;
Glenn Kasten74105912014-07-03 12:28:53 -07007929 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07007930 // not fast track: max notification period is resampled equivalent of one HAL buffer time
7931 // or 20 ms if there is a fast capture
7932 // TODO This could be a roundupRatio inline, and const
7933 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
7934 * sampleRate + mSampleRate - 1) / mSampleRate;
7935 // minimum number of notification periods is at least kMinNotifications,
7936 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
7937 static const size_t kMinNotifications = 3;
7938 static const uint32_t kMinMs = 30;
7939 // TODO This could be a roundupRatio inline
7940 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
7941 // TODO This could be a roundupRatio inline
7942 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
7943 maxNotificationFrames;
7944 const size_t minFrameCount = maxNotificationFrames *
7945 max(kMinNotifications, minNotificationsByMs);
7946 frameCount = max(frameCount, minFrameCount);
Eric Laurentf14db3c2017-12-08 14:20:36 -08007947 if (notificationFrameCount == 0 || notificationFrameCount > maxNotificationFrames) {
7948 notificationFrameCount = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07007949 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07007950 }
Glenn Kasten74935e42013-12-19 08:56:45 -08007951 *pFrameCount = frameCount;
Eric Laurentf14db3c2017-12-08 14:20:36 -08007952 *pNotificationFrameCount = notificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08007953
7954 { // scope for mLock
7955 Mutex::Autolock _l(mLock);
Eric Laurent2407ce32021-04-26 14:56:03 +02007956 int32_t startFrames = -1;
Eric Laurentec376dc2021-04-08 20:41:22 +02007957 if (!mSharedAudioPackageName.empty()
7958 && mSharedAudioPackageName == checkedIdentity.packageName
7959 && mSharedAudioSessionId == sessionId
7960 && captureHotwordAllowed(checkedIdentity)) {
Eric Laurent2407ce32021-04-26 14:56:03 +02007961 startFrames = mSharedAudioStartFrames;
Eric Laurentec376dc2021-04-08 20:41:22 +02007962 }
Eric Laurent81784c32012-11-19 14:55:58 -08007963
Kevin Rocard1f564ac2018-03-29 13:53:10 -07007964 track = new RecordTrack(this, client, attr, sampleRate,
Andy Hung8fe68032017-06-05 16:17:51 -07007965 format, channelMask, frameCount,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07007966 nullptr /* buffer */, (size_t)0 /* bufferSize */, sessionId, creatorPid,
Eric Laurent2407ce32021-04-26 14:56:03 +02007967 checkedIdentity, *flags, TrackBase::TYPE_DEFAULT, portId, startFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08007968
Glenn Kasten03003332013-08-06 15:40:54 -07007969 lStatus = track->initCheck();
7970 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07007971 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08007972 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08007973 goto Exit;
7974 }
7975 mTracks.add(track);
7976
Eric Laurent05067782016-06-01 18:27:28 -07007977 if ((*flags & AUDIO_INPUT_FLAG_FAST) && (tid != -1)) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07007978 pid_t callingPid = IPCThreadState::self()->getCallingPid();
7979 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
7980 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07007981 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Glenn Kasten90e58b12013-07-31 16:16:02 -07007982 }
Eric Laurentec376dc2021-04-08 20:41:22 +02007983
7984 if (maxSharedAudioHistoryMs != 0) {
7985 sendResizeBufferConfigEvent_l(maxSharedAudioHistoryMs);
7986 }
7987
Eric Laurent81784c32012-11-19 14:55:58 -08007988 }
Glenn Kasten05997e22014-03-13 15:08:33 -07007989
Eric Laurent81784c32012-11-19 14:55:58 -08007990 lStatus = NO_ERROR;
7991
7992Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07007993 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08007994 return track;
7995}
7996
7997status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
7998 AudioSystem::sync_event_t event,
Glenn Kastend848eb42016-03-08 13:42:11 -08007999 audio_session_t triggerSession)
Eric Laurent81784c32012-11-19 14:55:58 -08008000{
8001 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
8002 sp<ThreadBase> strongMe = this;
8003 status_t status = NO_ERROR;
8004
8005 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08008006 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08008007 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008008 recordTrack->mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
Eric Laurent81784c32012-11-19 14:55:58 -08008009 triggerSession,
8010 recordTrack->sessionId(),
8011 syncStartEventCallback,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008012 recordTrack);
Eric Laurent81784c32012-11-19 14:55:58 -08008013 // Sync event can be cancelled by the trigger session if the track is not in a
8014 // compatible state in which case we start record immediately
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008015 if (recordTrack->mSyncStartEvent->isCancelled()) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08008016 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08008017 } else {
8018 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
Ivan Lozano1b35dd62017-12-06 16:55:10 -08008019 recordTrack->mFramesToDrop = -(ssize_t)
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08008020 ((AudioSystem::kSyncRecordStartTimeOutMs * recordTrack->mSampleRate) / 1000);
Eric Laurent81784c32012-11-19 14:55:58 -08008021 }
8022 }
8023
8024 {
Glenn Kasten47c20702013-08-13 15:37:35 -07008025 // This section is a rendezvous between binder thread executing start() and RecordThread
Eric Laurent81784c32012-11-19 14:55:58 -08008026 AutoMutex lock(mLock);
Andy Hungce685402018-10-05 17:23:27 -07008027 if (recordTrack->isInvalid()) {
8028 recordTrack->clearSyncStartEvent();
Eric Laurentd52a28c2020-08-21 17:10:39 -07008029 ALOGW("%s track %d: invalidated before startInput", __func__, recordTrack->portId());
8030 return DEAD_OBJECT;
Andy Hungce685402018-10-05 17:23:27 -07008031 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008032 if (mActiveTracks.indexOf(recordTrack) >= 0) {
8033 if (recordTrack->mState == TrackBase::PAUSING) {
Andy Hungce685402018-10-05 17:23:27 -07008034 // We haven't stopped yet (moved to PAUSED and not in mActiveTracks)
8035 // so no need to startInput().
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008036 ALOGV("active record track PAUSING -> ACTIVE");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008037 recordTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008038 } else {
8039 ALOGV("active record track state %d", recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08008040 }
8041 return status;
8042 }
8043
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08008044 // TODO consider other ways of handling this, such as changing the state to :STARTING and
8045 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
8046 // or using a separate command thread
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008047 recordTrack->mState = TrackBase::STARTING_1;
Glenn Kasten2b806402013-11-20 16:37:38 -08008048 mActiveTracks.add(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07008049 status_t status = NO_ERROR;
8050 if (recordTrack->isExternalTrack()) {
8051 mLock.unlock();
Eric Laurent4eb58f12018-12-07 16:41:02 -08008052 status = AudioSystem::startInput(recordTrack->portId());
Eric Laurent83b88082014-06-20 18:31:16 -07008053 mLock.lock();
Andy Hungce685402018-10-05 17:23:27 -07008054 if (recordTrack->isInvalid()) {
8055 recordTrack->clearSyncStartEvent();
8056 if (status == NO_ERROR && recordTrack->mState == TrackBase::STARTING_1) {
8057 recordTrack->mState = TrackBase::STARTING_2;
8058 // STARTING_2 forces destroy to call stopInput.
8059 }
Eric Laurentd52a28c2020-08-21 17:10:39 -07008060 ALOGW("%s track %d: invalidated after startInput", __func__, recordTrack->portId());
8061 return DEAD_OBJECT;
Andy Hungce685402018-10-05 17:23:27 -07008062 }
8063 if (recordTrack->mState != TrackBase::STARTING_1) {
8064 ALOGW("%s(%d): unsynchronized mState:%d change",
8065 __func__, recordTrack->id(), recordTrack->mState);
8066 // Someone else has changed state, let them take over,
8067 // leave mState in the new state.
8068 recordTrack->clearSyncStartEvent();
8069 return INVALID_OPERATION;
8070 }
8071 // we're ok, but perhaps startInput has failed
Eric Laurent83b88082014-06-20 18:31:16 -07008072 if (status != NO_ERROR) {
Andy Hungce685402018-10-05 17:23:27 -07008073 ALOGW("%s(%d): startInput failed, status %d",
8074 __func__, recordTrack->id(), status);
8075 // We are in ActiveTracks if STARTING_1 and valid, so remove from ActiveTracks,
8076 // leave in STARTING_1, so destroy() will not call stopInput.
Eric Laurent83b88082014-06-20 18:31:16 -07008077 mActiveTracks.remove(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07008078 recordTrack->clearSyncStartEvent();
Eric Laurent83b88082014-06-20 18:31:16 -07008079 return status;
8080 }
Eric Laurent09f1ed22019-04-24 17:45:17 -07008081 sendIoConfigEvent_l(
8082 AUDIO_CLIENT_STARTED, recordTrack->creatorPid(), recordTrack->portId());
Eric Laurent81784c32012-11-19 14:55:58 -08008083 }
Andy Hungc2b11cb2020-04-22 09:04:01 -07008084
8085 recordTrack->logBeginInterval(patchSourcesToString(&mPatch)); // log to MediaMetrics
8086
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008087 // Catch up with current buffer indices if thread is already running.
8088 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
8089 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
8090 // see previously buffered data before it called start(), but with greater risk of overrun.
8091
Andy Hung73c02e42015-03-29 01:13:58 -07008092 recordTrack->mResamplerBufferProvider->reset();
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008093 if (!recordTrack->isDirect()) {
8094 // clear any converter state as new data will be discontinuous
8095 recordTrack->mRecordBufferConverter->reset();
8096 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008097 recordTrack->mState = TrackBase::STARTING_2;
Eric Laurent81784c32012-11-19 14:55:58 -08008098 // signal thread to start
Eric Laurent81784c32012-11-19 14:55:58 -08008099 mWaitWorkCV.broadcast();
Eric Laurent81784c32012-11-19 14:55:58 -08008100 return status;
8101 }
Eric Laurent81784c32012-11-19 14:55:58 -08008102}
8103
Eric Laurent81784c32012-11-19 14:55:58 -08008104void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
8105{
8106 sp<SyncEvent> strongEvent = event.promote();
8107
8108 if (strongEvent != 0) {
Eric Laurent8ea16e42014-02-20 16:26:11 -08008109 sp<RefBase> ptr = strongEvent->cookie().promote();
8110 if (ptr != 0) {
8111 RecordTrack *recordTrack = (RecordTrack *)ptr.get();
8112 recordTrack->handleSyncStartEvent(strongEvent);
8113 }
Eric Laurent81784c32012-11-19 14:55:58 -08008114 }
8115}
8116
Glenn Kastena8356f62013-07-25 14:37:52 -07008117bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08008118 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07008119 AutoMutex _l(mLock);
Andy Hungce685402018-10-05 17:23:27 -07008120 // if we're invalid, we can't be on the ActiveTracks.
Jean-Michel Trivi38f86712017-04-11 14:10:17 -07008121 if (mActiveTracks.indexOf(recordTrack) < 0 || recordTrack->mState == TrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08008122 return false;
8123 }
Glenn Kasten47c20702013-08-13 15:37:35 -07008124 // note that threadLoop may still be processing the track at this point [without lock]
Eric Laurent81784c32012-11-19 14:55:58 -08008125 recordTrack->mState = TrackBase::PAUSING;
Andy Hungce685402018-10-05 17:23:27 -07008126
Andy Hungabfab202019-03-07 19:45:54 -08008127 // NOTE: Waiting here is important to keep stop synchronous.
8128 // This is needed for proper patchRecord peer release.
Andy Hungce685402018-10-05 17:23:27 -07008129 while (recordTrack->mState == TrackBase::PAUSING && !recordTrack->isInvalid()) {
8130 mWaitWorkCV.broadcast(); // signal thread to stop
8131 mStartStopCond.wait(mLock);
Eric Laurent81784c32012-11-19 14:55:58 -08008132 }
Andy Hungce685402018-10-05 17:23:27 -07008133
8134 if (recordTrack->mState == TrackBase::PAUSED) { // successful stop
Eric Laurent81784c32012-11-19 14:55:58 -08008135 ALOGV("Record stopped OK");
8136 return true;
8137 }
Andy Hungce685402018-10-05 17:23:27 -07008138
8139 // don't handle anything - we've been invalidated or restarted and in a different state
8140 ALOGW_IF("%s(%d): unsynchronized stop, state: %d",
8141 __func__, recordTrack->id(), recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08008142 return false;
8143}
8144
Glenn Kasten0f11b512014-01-31 16:18:54 -08008145bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
Eric Laurent81784c32012-11-19 14:55:58 -08008146{
8147 return false;
8148}
8149
Glenn Kasten0f11b512014-01-31 16:18:54 -08008150status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08008151{
8152#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
8153 if (!isValidSyncEvent(event)) {
8154 return BAD_VALUE;
8155 }
8156
Glenn Kastend848eb42016-03-08 13:42:11 -08008157 audio_session_t eventSession = event->triggerSession();
Eric Laurent81784c32012-11-19 14:55:58 -08008158 status_t ret = NAME_NOT_FOUND;
8159
8160 Mutex::Autolock _l(mLock);
8161
8162 for (size_t i = 0; i < mTracks.size(); i++) {
8163 sp<RecordTrack> track = mTracks[i];
8164 if (eventSession == track->sessionId()) {
8165 (void) track->setSyncEvent(event);
8166 ret = NO_ERROR;
8167 }
8168 }
8169 return ret;
8170#else
8171 return BAD_VALUE;
8172#endif
8173}
8174
jiabin653cc0a2018-01-17 17:54:10 -08008175status_t AudioFlinger::RecordThread::getActiveMicrophones(
8176 std::vector<media::MicrophoneInfo>* activeMicrophones)
8177{
8178 ALOGV("RecordThread::getActiveMicrophones");
8179 AutoMutex _l(mLock);
Paul McLean8a661a32021-04-12 10:21:42 -06008180 if (mInput == nullptr || mInput->stream == nullptr) {
8181 return NO_INIT;
8182 }
jiabin9ff780e2018-03-19 18:19:52 -07008183 status_t status = mInput->stream->getActiveMicrophones(activeMicrophones);
8184 return status;
jiabin653cc0a2018-01-17 17:54:10 -08008185}
8186
Paul McLean12340082019-03-19 09:35:05 -06008187status_t AudioFlinger::RecordThread::setPreferredMicrophoneDirection(
8188 audio_microphone_direction_t direction)
Paul McLean03a6e6a2018-12-04 10:54:13 -07008189{
Paul McLean12340082019-03-19 09:35:05 -06008190 ALOGV("setPreferredMicrophoneDirection(%d)", direction);
Paul McLean03a6e6a2018-12-04 10:54:13 -07008191 AutoMutex _l(mLock);
Paul McLean8a661a32021-04-12 10:21:42 -06008192 if (mInput == nullptr || mInput->stream == nullptr) {
8193 return NO_INIT;
8194 }
Paul McLean12340082019-03-19 09:35:05 -06008195 return mInput->stream->setPreferredMicrophoneDirection(direction);
Paul McLean03a6e6a2018-12-04 10:54:13 -07008196}
8197
Paul McLean12340082019-03-19 09:35:05 -06008198status_t AudioFlinger::RecordThread::setPreferredMicrophoneFieldDimension(float zoom)
Paul McLean03a6e6a2018-12-04 10:54:13 -07008199{
Paul McLean12340082019-03-19 09:35:05 -06008200 ALOGV("setPreferredMicrophoneFieldDimension(%f)", zoom);
Paul McLean03a6e6a2018-12-04 10:54:13 -07008201 AutoMutex _l(mLock);
Paul McLean8a661a32021-04-12 10:21:42 -06008202 if (mInput == nullptr || mInput->stream == nullptr) {
8203 return NO_INIT;
8204 }
Paul McLean12340082019-03-19 09:35:05 -06008205 return mInput->stream->setPreferredMicrophoneFieldDimension(zoom);
Paul McLean03a6e6a2018-12-04 10:54:13 -07008206}
8207
Eric Laurentec376dc2021-04-08 20:41:22 +02008208status_t AudioFlinger::RecordThread::shareAudioHistory(
8209 const std::string& sharedAudioPackageName, audio_session_t sharedSessionId,
8210 int64_t sharedAudioStartMs) {
8211 AutoMutex _l(mLock);
8212 return shareAudioHistory_l(sharedAudioPackageName, sharedSessionId, sharedAudioStartMs);
8213}
8214
8215status_t AudioFlinger::RecordThread::shareAudioHistory_l(
8216 const std::string& sharedAudioPackageName, audio_session_t sharedSessionId,
8217 int64_t sharedAudioStartMs) {
8218 if (hasFastCapture()) {
8219 return BAD_VALUE;
8220 }
8221 if ((hasAudioSession_l(sharedSessionId) & ThreadBase::TRACK_SESSION) == 0) {
8222 return BAD_VALUE;
8223 }
Eric Laurent2407ce32021-04-26 14:56:03 +02008224
8225 if (sharedAudioStartMs < 0
8226 || sharedAudioStartMs > INT64_MAX / mSampleRate) {
Eric Laurentec376dc2021-04-08 20:41:22 +02008227 return BAD_VALUE;
8228 }
8229
Eric Laurent2407ce32021-04-26 14:56:03 +02008230 // Current implementation of the input resampling buffer wraps around indexes at 32 bit.
8231 // As we cannot detect more than one wraparound, only accept values up current write position
8232 // after one wraparound
8233 // We assume recent wraparounds on mRsmpInRear only given it is unlikely that the requesting
8234 // app waits several hours after the start time was computed.
8235 const int64_t sharedAudioStartFrames = sharedAudioStartMs * mSampleRate / 1000;
8236 const int32_t sharedOffset = audio_utils::safe_sub_overflow(mRsmpInRear,
8237 (int32_t)sharedAudioStartFrames);
8238 if (sharedOffset < 0
8239 || sharedOffset > mRsmpInFrames) {
8240 return BAD_VALUE;
8241 }
8242
Eric Laurentec376dc2021-04-08 20:41:22 +02008243 mSharedAudioPackageName = sharedAudioPackageName;
8244 if (mSharedAudioPackageName.empty()) {
8245 mSharedAudioSessionId = AUDIO_SESSION_NONE;
Eric Laurent2407ce32021-04-26 14:56:03 +02008246 mSharedAudioStartFrames = -1;
Eric Laurentec376dc2021-04-08 20:41:22 +02008247 } else {
8248 mSharedAudioSessionId = sharedSessionId;
Eric Laurent2407ce32021-04-26 14:56:03 +02008249 mSharedAudioStartFrames = (int32_t)sharedAudioStartFrames;
Eric Laurentec376dc2021-04-08 20:41:22 +02008250 }
8251 return NO_ERROR;
8252}
8253
Kevin Rocard069c2712018-03-29 19:09:14 -07008254void AudioFlinger::RecordThread::updateMetadata_l()
8255{
8256 if (mInput == nullptr || mInput->stream == nullptr ||
8257 !mActiveTracks.readAndClearHasChanged()) {
8258 return;
8259 }
8260 StreamInHalInterface::SinkMetadata metadata;
8261 for (const sp<RecordTrack> &track : mActiveTracks) {
Eric Laurentb9cc0ab2021-01-29 11:46:52 +01008262 // Do not forward PatchRecord metadata to audio HAL
8263 if (track->isPatchTrack()) {
8264 continue;
8265 }
Kevin Rocard069c2712018-03-29 19:09:14 -07008266 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurent94579172020-11-20 18:41:04 +01008267 record_track_metadata_v7_t trackMetadata;
8268 trackMetadata.base = {
Kevin Rocard069c2712018-03-29 19:09:14 -07008269 .source = track->attributes().source,
8270 .gain = 1, // capture tracks do not have volumes
Eric Laurent94579172020-11-20 18:41:04 +01008271 };
8272 trackMetadata.channel_mask = track->channelMask(),
8273 strncpy(trackMetadata.tags, track->attributes().tags, AUDIO_ATTRIBUTES_TAGS_MAX_SIZE);
8274
8275 metadata.tracks.push_back(trackMetadata);
Kevin Rocard069c2712018-03-29 19:09:14 -07008276 }
8277 mInput->stream->updateSinkMetadata(metadata);
8278}
8279
Eric Laurent81784c32012-11-19 14:55:58 -08008280// destroyTrack_l() must be called with ThreadBase::mLock held
8281void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
8282{
Eric Laurentbfb1b832013-01-07 09:53:42 -08008283 track->terminate();
8284 track->mState = TrackBase::STOPPED;
Eric Laurentec376dc2021-04-08 20:41:22 +02008285
Eric Laurent81784c32012-11-19 14:55:58 -08008286 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08008287 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08008288 removeTrack_l(track);
8289 }
8290}
8291
8292void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
8293{
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008294 String8 result;
8295 track->appendDump(result, false /* active */);
8296 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.string());
8297
Eric Laurent81784c32012-11-19 14:55:58 -08008298 mTracks.remove(track);
8299 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008300 if (track->isFastTrack()) {
8301 ALOG_ASSERT(!mFastTrackAvail);
8302 mFastTrackAvail = true;
8303 }
Eric Laurent81784c32012-11-19 14:55:58 -08008304}
8305
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07008306void AudioFlinger::RecordThread::dumpInternals_l(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08008307{
Mikhail Naganov913d06c2016-11-01 12:49:22 -07008308 AudioStreamIn *input = mInput;
8309 audio_input_flags_t flags = input != NULL ? input->flags : AUDIO_INPUT_FLAG_NONE;
8310 dprintf(fd, " AudioStreamIn: %p flags %#x (%s)\n",
Andy Hung9b181952019-02-25 14:53:36 -08008311 input, flags, toString(flags).c_str());
Andy Hung6427e442018-08-09 12:51:02 -07008312 dprintf(fd, " Frames read: %lld\n", (long long)mFramesRead);
Eric Tan39ec8d62018-07-24 09:49:29 -07008313 if (mActiveTracks.isEmpty()) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07008314 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08008315 }
Andy Hungbfa64962017-06-12 14:43:19 -07008316
8317 if (input != nullptr) {
8318 dprintf(fd, " Hal stream dump:\n");
8319 (void)input->stream->dump(fd);
8320 }
8321
Glenn Kasten6e6704c2014-07-03 10:20:00 -07008322 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008323 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Glenn Kasten17c9c992015-03-02 15:53:01 -08008324
Glenn Kasten2f90c512015-12-02 11:40:09 -08008325 // Make a non-atomic copy of fast capture dump state so it won't change underneath us
8326 // while we are dumping it. It may be inconsistent, but it won't mutate!
8327 // This is a large object so we place it on the heap.
8328 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
Eric Tan2942a4e2018-09-12 17:41:27 -07008329 const std::unique_ptr<FastCaptureDumpState> copy =
8330 std::make_unique<FastCaptureDumpState>(mFastCaptureDumpState);
Glenn Kasten2f90c512015-12-02 11:40:09 -08008331 copy->dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08008332}
8333
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07008334void AudioFlinger::RecordThread::dumpTracks_l(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08008335{
Eric Laurent81784c32012-11-19 14:55:58 -08008336 String8 result;
Marco Nelissenb2208842014-02-07 14:00:50 -08008337 size_t numtracks = mTracks.size();
8338 size_t numactive = mActiveTracks.size();
8339 size_t numactiveseen = 0;
Glenn Kastenc42e9b42016-03-21 11:35:03 -07008340 dprintf(fd, " %zu Tracks", numtracks);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008341 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08008342 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07008343 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008344 result.append(prefix);
Andy Hung000adb52018-06-01 15:43:26 -07008345 mTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08008346 for (size_t i = 0; i < numtracks ; ++i) {
8347 sp<RecordTrack> track = mTracks[i];
8348 if (track != 0) {
8349 bool active = mActiveTracks.indexOf(track) >= 0;
8350 if (active) {
8351 numactiveseen++;
8352 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008353 result.append(prefix);
8354 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08008355 }
Eric Laurent81784c32012-11-19 14:55:58 -08008356 }
Marco Nelissenb2208842014-02-07 14:00:50 -08008357 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07008358 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08008359 }
8360
Marco Nelissenb2208842014-02-07 14:00:50 -08008361 if (numactiveseen != numactive) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008362 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08008363 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008364 result.append(prefix);
Andy Hung000adb52018-06-01 15:43:26 -07008365 mActiveTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08008366 for (size_t i = 0; i < numactive; ++i) {
Glenn Kasten2b806402013-11-20 16:37:38 -08008367 sp<RecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08008368 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008369 result.append(prefix);
8370 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08008371 }
Glenn Kasten2b806402013-11-20 16:37:38 -08008372 }
Eric Laurent81784c32012-11-19 14:55:58 -08008373
8374 }
8375 write(fd, result.string(), result.size());
8376}
8377
Eric Laurent5ada82e2019-08-29 17:53:54 -07008378void AudioFlinger::RecordThread::setRecordSilenced(audio_port_handle_t portId, bool silenced)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008379{
8380 Mutex::Autolock _l(mLock);
8381 for (size_t i = 0; i < mTracks.size() ; i++) {
8382 sp<RecordTrack> track = mTracks[i];
Eric Laurent5ada82e2019-08-29 17:53:54 -07008383 if (track != 0 && track->portId() == portId) {
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008384 track->setSilenced(silenced);
8385 }
8386 }
8387}
Andy Hung73c02e42015-03-29 01:13:58 -07008388
8389void AudioFlinger::RecordThread::ResamplerBufferProvider::reset()
8390{
8391 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
8392 RecordThread *recordThread = (RecordThread *) threadBase.get();
Andy Hung73c02e42015-03-29 01:13:58 -07008393 mRsmpInUnrel = 0;
Eric Laurentec376dc2021-04-08 20:41:22 +02008394 const int32_t rear = recordThread->mRsmpInRear;
8395 ssize_t deltaFrames = 0;
Eric Laurent2407ce32021-04-26 14:56:03 +02008396 if (mRecordTrack->startFrames() >= 0) {
8397 int32_t startFrames = mRecordTrack->startFrames();
8398 // Accept a recent wraparound of mRsmpInRear
8399 if (startFrames <= rear) {
8400 deltaFrames = rear - startFrames;
8401 } else {
8402 deltaFrames = (int32_t)((int64_t)rear + UINT32_MAX + 1 - startFrames);
Eric Laurentec376dc2021-04-08 20:41:22 +02008403 }
Eric Laurentec376dc2021-04-08 20:41:22 +02008404 // start frame cannot be further in the past than start of resampling buffer
8405 if ((size_t) deltaFrames > recordThread->mRsmpInFrames) {
8406 deltaFrames = recordThread->mRsmpInFrames;
8407 }
8408 }
8409 mRsmpInFront = audio_utils::safe_sub_overflow(rear, static_cast<int32_t>(deltaFrames));
Andy Hung73c02e42015-03-29 01:13:58 -07008410}
8411
8412void AudioFlinger::RecordThread::ResamplerBufferProvider::sync(
8413 size_t *framesAvailable, bool *hasOverrun)
8414{
8415 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
8416 RecordThread *recordThread = (RecordThread *) threadBase.get();
8417 const int32_t rear = recordThread->mRsmpInRear;
8418 const int32_t front = mRsmpInFront;
Hongwei Wang95e37682019-04-12 11:13:36 -07008419 const ssize_t filled = audio_utils::safe_sub_overflow(rear, front);
Andy Hung73c02e42015-03-29 01:13:58 -07008420
8421 size_t framesIn;
8422 bool overrun = false;
8423 if (filled < 0) {
8424 // should not happen, but treat like a massive overrun and re-sync
8425 framesIn = 0;
8426 mRsmpInFront = rear;
8427 overrun = true;
8428 } else if ((size_t) filled <= recordThread->mRsmpInFrames) {
8429 framesIn = (size_t) filled;
8430 } else {
8431 // client is not keeping up with server, but give it latest data
8432 framesIn = recordThread->mRsmpInFrames;
Hongwei Wang95e37682019-04-12 11:13:36 -07008433 mRsmpInFront = /* front = */ audio_utils::safe_sub_overflow(
8434 rear, static_cast<int32_t>(framesIn));
Andy Hung73c02e42015-03-29 01:13:58 -07008435 overrun = true;
8436 }
8437 if (framesAvailable != NULL) {
8438 *framesAvailable = framesIn;
8439 }
8440 if (hasOverrun != NULL) {
8441 *hasOverrun = overrun;
8442 }
8443}
8444
Eric Laurent81784c32012-11-19 14:55:58 -08008445// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008446status_t AudioFlinger::RecordThread::ResamplerBufferProvider::getNextBuffer(
Glenn Kastend79072e2016-01-06 08:41:20 -08008447 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08008448{
Andy Hung73c02e42015-03-29 01:13:58 -07008449 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008450 if (threadBase == 0) {
8451 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08008452 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008453 return NOT_ENOUGH_DATA;
8454 }
8455 RecordThread *recordThread = (RecordThread *) threadBase.get();
8456 int32_t rear = recordThread->mRsmpInRear;
Andy Hung73c02e42015-03-29 01:13:58 -07008457 int32_t front = mRsmpInFront;
Hongwei Wang95e37682019-04-12 11:13:36 -07008458 ssize_t filled = audio_utils::safe_sub_overflow(rear, front);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008459 // FIXME should not be P2 (don't want to increase latency)
8460 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08008461 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07008462 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008463 front &= recordThread->mRsmpInFramesP2 - 1;
8464 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07008465 if (part1 > (size_t) filled) {
8466 part1 = filled;
8467 }
8468 size_t ask = buffer->frameCount;
8469 ALOG_ASSERT(ask > 0);
8470 if (part1 > ask) {
8471 part1 = ask;
8472 }
8473 if (part1 == 0) {
Andy Hung73c02e42015-03-29 01:13:58 -07008474 // out of data is fine since the resampler will return a short-count.
Glenn Kasten85948432013-08-19 12:09:05 -07008475 buffer->raw = NULL;
8476 buffer->frameCount = 0;
Andy Hung73c02e42015-03-29 01:13:58 -07008477 mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07008478 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08008479 }
8480
Andy Hung57446612015-04-19 23:56:46 -07008481 buffer->raw = (uint8_t*)recordThread->mRsmpInBuffer + front * recordThread->mFrameSize;
Glenn Kasten85948432013-08-19 12:09:05 -07008482 buffer->frameCount = part1;
Andy Hung73c02e42015-03-29 01:13:58 -07008483 mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08008484 return NO_ERROR;
8485}
8486
8487// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008488void AudioFlinger::RecordThread::ResamplerBufferProvider::releaseBuffer(
8489 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08008490{
Hongwei Wang95e37682019-04-12 11:13:36 -07008491 int32_t stepCount = static_cast<int32_t>(buffer->frameCount);
Glenn Kasten85948432013-08-19 12:09:05 -07008492 if (stepCount == 0) {
8493 return;
8494 }
Andy Hung73c02e42015-03-29 01:13:58 -07008495 ALOG_ASSERT(stepCount <= mRsmpInUnrel);
8496 mRsmpInUnrel -= stepCount;
Hongwei Wang95e37682019-04-12 11:13:36 -07008497 mRsmpInFront = audio_utils::safe_add_overflow(mRsmpInFront, stepCount);
Glenn Kasten85948432013-08-19 12:09:05 -07008498 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08008499 buffer->frameCount = 0;
8500}
8501
Eric Laurentd8365c52017-07-16 15:27:05 -07008502void AudioFlinger::RecordThread::checkBtNrec()
8503{
8504 Mutex::Autolock _l(mLock);
8505 checkBtNrec_l();
8506}
8507
8508void AudioFlinger::RecordThread::checkBtNrec_l()
8509{
8510 // disable AEC and NS if the device is a BT SCO headset supporting those
8511 // pre processings
jiabinc52b1ff2019-10-31 17:20:42 -07008512 bool suspend = audio_is_bluetooth_sco_device(inDeviceType()) &&
Eric Laurentd8365c52017-07-16 15:27:05 -07008513 mAudioFlinger->btNrecIsOff();
8514 if (mBtNrecSuspended.exchange(suspend) != suspend) {
8515 for (size_t i = 0; i < mEffectChains.size(); i++) {
8516 setEffectSuspended_l(FX_IID_AEC, suspend, mEffectChains[i]->sessionId());
8517 setEffectSuspended_l(FX_IID_NS, suspend, mEffectChains[i]->sessionId());
8518 }
8519 }
8520}
8521
Andy Hung97a893e2015-03-29 01:03:07 -07008522
Eric Laurent10351942014-05-08 18:49:52 -07008523bool AudioFlinger::RecordThread::checkForNewParameter_l(const String8& keyValuePair,
8524 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08008525{
8526 bool reconfig = false;
8527
Eric Laurent10351942014-05-08 18:49:52 -07008528 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08008529
Eric Laurent10351942014-05-08 18:49:52 -07008530 audio_format_t reqFormat = mFormat;
8531 uint32_t samplingRate = mSampleRate;
Glenn Kastene1635ec2015-06-08 15:46:49 -07008532 // 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 -07008533 audio_channel_mask_t channelMask = audio_channel_in_mask_from_count(mChannelCount);
8534
8535 AudioParameter param = AudioParameter(keyValuePair);
8536 int value;
Haynes Mathew George9ce67b52015-09-30 11:40:47 -07008537
8538 // scope for AutoPark extends to end of method
8539 AutoPark<FastCapture> park(mFastCapture);
8540
Eric Laurent10351942014-05-08 18:49:52 -07008541 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
8542 // channel count change can be requested. Do we mandate the first client defines the
8543 // HAL sampling rate and channel count or do we allow changes on the fly?
8544 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
8545 samplingRate = value;
8546 reconfig = true;
8547 }
8548 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung97a893e2015-03-29 01:03:07 -07008549 if (!audio_is_linear_pcm((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07008550 status = BAD_VALUE;
8551 } else {
8552 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08008553 reconfig = true;
8554 }
Eric Laurent10351942014-05-08 18:49:52 -07008555 }
8556 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
8557 audio_channel_mask_t mask = (audio_channel_mask_t) value;
Andy Hungd330ee42015-04-20 13:23:41 -07008558 if (!audio_is_input_channel(mask) ||
8559 audio_channel_count_from_in_mask(mask) > FCC_8) {
Eric Laurent10351942014-05-08 18:49:52 -07008560 status = BAD_VALUE;
8561 } else {
8562 channelMask = mask;
8563 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08008564 }
Eric Laurent10351942014-05-08 18:49:52 -07008565 }
8566 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
8567 // do not accept frame count changes if tracks are open as the track buffer
8568 // size depends on frame count and correct behavior would not be guaranteed
8569 // if frame count is changed after track creation
8570 if (mActiveTracks.size() > 0) {
8571 status = INVALID_OPERATION;
8572 } else {
8573 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08008574 }
Eric Laurent10351942014-05-08 18:49:52 -07008575 }
8576 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07008577 LOG_FATAL("Should not set routing device in RecordThread");
Eric Laurent10351942014-05-08 18:49:52 -07008578 }
8579 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
8580 mAudioSource != (audio_source_t)value) {
jiabinc52b1ff2019-10-31 17:20:42 -07008581 LOG_FATAL("Should not set audio source in RecordThread");
Eric Laurent10351942014-05-08 18:49:52 -07008582 }
Glenn Kastene198c362013-08-13 09:13:36 -07008583
Eric Laurent10351942014-05-08 18:49:52 -07008584 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008585 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07008586 if (status == INVALID_OPERATION) {
8587 inputStandBy();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008588 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07008589 }
8590 if (reconfig) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008591 if (status == BAD_VALUE) {
Mikhail Naganov560637e2021-03-31 22:40:13 +00008592 audio_config_base_t config = AUDIO_CONFIG_BASE_INITIALIZER;
8593 if (mInput->stream->getAudioProperties(&config) == OK &&
8594 audio_is_linear_pcm(config.format) && audio_is_linear_pcm(reqFormat) &&
8595 config.sample_rate <= (AUDIO_RESAMPLER_DOWN_RATIO_MAX * samplingRate) &&
8596 audio_channel_count_from_in_mask(config.channel_mask) <= FCC_8) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008597 status = NO_ERROR;
8598 }
Eric Laurent81784c32012-11-19 14:55:58 -08008599 }
Eric Laurent10351942014-05-08 18:49:52 -07008600 if (status == NO_ERROR) {
8601 readInputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07008602 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08008603 }
8604 }
Eric Laurent81784c32012-11-19 14:55:58 -08008605 }
Eric Laurent10351942014-05-08 18:49:52 -07008606
Eric Laurent81784c32012-11-19 14:55:58 -08008607 return reconfig;
8608}
8609
8610String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
8611{
Eric Laurent81784c32012-11-19 14:55:58 -08008612 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008613 if (initCheck() == NO_ERROR) {
8614 String8 out_s8;
8615 if (mInput->stream->getParameters(keys, &out_s8) == OK) {
8616 return out_s8;
8617 }
Eric Laurent81784c32012-11-19 14:55:58 -08008618 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008619 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08008620}
8621
Eric Laurent09f1ed22019-04-24 17:45:17 -07008622void AudioFlinger::RecordThread::ioConfigChanged(audio_io_config_event event, pid_t pid,
8623 audio_port_handle_t portId) {
Eric Laurent73e26b62015-04-27 16:55:58 -07008624 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
8625
8626 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08008627
8628 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07008629 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07008630 case AUDIO_INPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07008631 case AUDIO_INPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07008632 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07008633 desc->mChannelMask = mChannelMask;
8634 desc->mSamplingRate = mSampleRate;
8635 desc->mFormat = mFormat;
8636 desc->mFrameCount = mFrameCount;
Glenn Kasten4a8308b2016-04-18 14:10:01 -07008637 desc->mFrameCountHAL = mFrameCount;
Eric Laurent73e26b62015-04-27 16:55:58 -07008638 desc->mLatency = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08008639 break;
Eric Laurent09f1ed22019-04-24 17:45:17 -07008640 case AUDIO_CLIENT_STARTED:
8641 desc->mPatch = mPatch;
8642 desc->mPortId = portId;
8643 break;
Eric Laurent73e26b62015-04-27 16:55:58 -07008644 case AUDIO_INPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08008645 default:
8646 break;
8647 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07008648 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08008649}
8650
Glenn Kastendeca2ae2014-02-07 10:25:56 -08008651void AudioFlinger::RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08008652{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008653 status_t result = mInput->stream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
8654 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
Andy Hung463be252014-07-10 16:56:07 -07008655 mFormat = mHALFormat;
Mikhail Naganovce9f2652018-07-16 11:09:24 -07008656 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
8657 if (audio_is_linear_pcm(mFormat)) {
8658 LOG_ALWAYS_FATAL_IF(mChannelCount > FCC_8, "HAL channel count %d > %d",
8659 mChannelCount, FCC_8);
8660 } else {
8661 // Can have more that FCC_8 channels in encoded streams.
8662 ALOGI("HAL format %#x is not linear pcm", mFormat);
8663 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008664 result = mInput->stream->getFrameSize(&mFrameSize);
8665 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
Hayden Gomes1a89ab32020-06-12 11:05:47 -07008666 LOG_ALWAYS_FATAL_IF(mFrameSize <= 0, "Error frame size was %zu but must be greater than zero",
8667 mFrameSize);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008668 result = mInput->stream->getBufferSize(&mBufferSize);
8669 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
Glenn Kasten548efc92012-11-29 08:48:51 -08008670 mFrameCount = mBufferSize / mFrameSize;
Hayden Gomes1a89ab32020-06-12 11:05:47 -07008671 ALOGV("%p RecordThread params: mChannelCount=%u, mFormat=%#x, mFrameSize=%zu, "
8672 "mBufferSize=%zu, mFrameCount=%zu",
8673 this, mChannelCount, mFormat, mFrameSize, mBufferSize, mFrameCount);
Glenn Kasten49d00ad2014-07-21 11:22:03 -07008674
Eric Laurentec376dc2021-04-08 20:41:22 +02008675 // mRsmpInFrames must be 0 before calling resizeInputBuffer_l for the first time
8676 mRsmpInFrames = 0;
8677 resizeInputBuffer_l();
Eric Laurent81784c32012-11-19 14:55:58 -08008678
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08008679 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
8680 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Andy Hungea840382020-05-05 21:50:17 -07008681
8682 audio_input_flags_t flags = mInput->flags;
8683 mediametrics::LogItem item(mThreadMetrics.getMetricsId());
8684 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
8685 .set(AMEDIAMETRICS_PROP_ENCODING, formatToString(mFormat).c_str())
8686 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
8687 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
8688 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
8689 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
8690 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mFrameCount)
8691 .record();
Eric Laurent81784c32012-11-19 14:55:58 -08008692}
8693
Glenn Kasten5f972c02014-01-13 09:59:31 -08008694uint32_t AudioFlinger::RecordThread::getInputFramesLost()
Eric Laurent81784c32012-11-19 14:55:58 -08008695{
8696 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008697 uint32_t result;
8698 if (initCheck() == NO_ERROR && mInput->stream->getInputFramesLost(&result) == OK) {
8699 return result;
Eric Laurent81784c32012-11-19 14:55:58 -08008700 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008701 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08008702}
8703
Glenn Kastend848eb42016-03-08 13:42:11 -08008704KeyedVector<audio_session_t, bool> AudioFlinger::RecordThread::sessionIds() const
Eric Laurent81784c32012-11-19 14:55:58 -08008705{
Glenn Kastend848eb42016-03-08 13:42:11 -08008706 KeyedVector<audio_session_t, bool> ids;
Eric Laurent81784c32012-11-19 14:55:58 -08008707 Mutex::Autolock _l(mLock);
8708 for (size_t j = 0; j < mTracks.size(); ++j) {
8709 sp<RecordThread::RecordTrack> track = mTracks[j];
Glenn Kastend848eb42016-03-08 13:42:11 -08008710 audio_session_t sessionId = track->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08008711 if (ids.indexOfKey(sessionId) < 0) {
8712 ids.add(sessionId, true);
8713 }
8714 }
8715 return ids;
8716}
8717
8718AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
8719{
8720 Mutex::Autolock _l(mLock);
8721 AudioStreamIn *input = mInput;
8722 mInput = NULL;
8723 return input;
8724}
8725
8726// this method must always be called either with ThreadBase mLock held or inside the thread loop
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008727sp<StreamHalInterface> AudioFlinger::RecordThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08008728{
8729 if (mInput == NULL) {
8730 return NULL;
8731 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008732 return mInput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08008733}
8734
8735status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
8736{
Eric Laurent81784c32012-11-19 14:55:58 -08008737 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurentaaa44472014-09-12 17:41:50 -07008738 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08008739 chain->setInBuffer(NULL);
8740 chain->setOutBuffer(NULL);
8741
8742 checkSuspendOnAddEffectChain_l(chain);
8743
Eric Laurent1b928682014-10-02 19:41:47 -07008744 // make sure enabled pre processing effects state is communicated to the HAL as we
8745 // just moved them to a new input stream.
8746 chain->syncHalEffectsState();
8747
Eric Laurent81784c32012-11-19 14:55:58 -08008748 mEffectChains.add(chain);
8749
8750 return NO_ERROR;
8751}
8752
8753size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
8754{
8755 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
Eric Laurentb20cf7d2019-04-05 19:37:34 -07008756
8757 for (size_t i = 0; i < mEffectChains.size(); i++) {
8758 if (chain == mEffectChains[i]) {
8759 mEffectChains.removeAt(i);
8760 break;
8761 }
Eric Laurent81784c32012-11-19 14:55:58 -08008762 }
Eric Laurentb20cf7d2019-04-05 19:37:34 -07008763 return mEffectChains.size();
Eric Laurent81784c32012-11-19 14:55:58 -08008764}
8765
Eric Laurent1c333e22014-05-20 10:48:17 -07008766status_t AudioFlinger::RecordThread::createAudioPatch_l(const struct audio_patch *patch,
8767 audio_patch_handle_t *handle)
8768{
8769 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07008770
8771 // store new device and send to effects
jiabinc52b1ff2019-10-31 17:20:42 -07008772 mInDeviceTypeAddr.mType = patch->sources[0].ext.device.type;
jiabin0a488932020-08-07 17:32:40 -07008773 mInDeviceTypeAddr.setAddress(patch->sources[0].ext.device.address);
François Gaffie0c280aa2018-07-25 10:02:15 +02008774 audio_port_handle_t deviceId = patch->sources[0].id;
Eric Laurent054d9d32015-04-24 08:48:48 -07008775 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08008776 mEffectChains[i]->setInputDevice_l(inDeviceTypeAddr());
Eric Laurent054d9d32015-04-24 08:48:48 -07008777 }
8778
Eric Laurentd8365c52017-07-16 15:27:05 -07008779 checkBtNrec_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07008780
8781 // store new source and send to effects
8782 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
8783 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent1c333e22014-05-20 10:48:17 -07008784 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent054d9d32015-04-24 08:48:48 -07008785 mEffectChains[i]->setAudioSource_l(mAudioSource);
Eric Laurent1c333e22014-05-20 10:48:17 -07008786 }
Eric Laurent054d9d32015-04-24 08:48:48 -07008787 }
Eric Laurent1c333e22014-05-20 10:48:17 -07008788
Mikhail Naganov9ee05402016-10-13 15:58:17 -07008789 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07008790 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
8791 status = hwDevice->createAudioPatch(patch->num_sources,
8792 patch->sources,
8793 patch->num_sinks,
8794 patch->sinks,
8795 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07008796 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07008797 char *address;
8798 if (strcmp(patch->sources[0].ext.device.address, "") != 0) {
8799 address = audio_device_address_to_parameter(
8800 patch->sources[0].ext.device.type,
8801 patch->sources[0].ext.device.address);
8802 } else {
8803 address = (char *)calloc(1, 1);
8804 }
8805 AudioParameter param = AudioParameter(String8(address));
8806 free(address);
Mikhail Naganov00260b52016-10-13 12:54:24 -07008807 param.addInt(String8(AudioParameter::keyRouting),
Eric Laurent054d9d32015-04-24 08:48:48 -07008808 (int)patch->sources[0].ext.device.type);
Mikhail Naganov00260b52016-10-13 12:54:24 -07008809 param.addInt(String8(AudioParameter::keyInputSource),
Eric Laurent054d9d32015-04-24 08:48:48 -07008810 (int)patch->sinks[0].ext.mix.usecase.source);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008811 status = mInput->stream->setParameters(param.toString());
Eric Laurent054d9d32015-04-24 08:48:48 -07008812 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07008813 }
Eric Laurent054d9d32015-04-24 08:48:48 -07008814
jiabinc52b1ff2019-10-31 17:20:42 -07008815 if ((mPatch.num_sources == 0) || (mPatch.sources[0].id != deviceId)) {
Eric Laurente8726fe2015-06-26 09:39:24 -07008816 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
jiabinc52b1ff2019-10-31 17:20:42 -07008817 mPatch = *patch;
Eric Laurente8726fe2015-06-26 09:39:24 -07008818 }
Eric Laurent296fb132015-05-01 11:38:42 -07008819
Andy Hungc2b11cb2020-04-22 09:04:01 -07008820 const std::string pathSourcesAsString = patchSourcesToString(patch);
Andy Hungcf10d742020-04-28 15:38:24 -07008821 mThreadMetrics.logEndInterval();
Andy Hungea840382020-05-05 21:50:17 -07008822 mThreadMetrics.logCreatePatch(pathSourcesAsString, /* outDevices */ {});
Andy Hungcf10d742020-04-28 15:38:24 -07008823 mThreadMetrics.logBeginInterval();
Andy Hungc2b11cb2020-04-22 09:04:01 -07008824 // also dispatch to active AudioRecords
8825 for (const auto &track : mActiveTracks) {
8826 track->logEndInterval();
8827 track->logBeginInterval(pathSourcesAsString);
8828 }
Eric Laurent1c333e22014-05-20 10:48:17 -07008829 return status;
8830}
8831
8832status_t AudioFlinger::RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
8833{
8834 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07008835
jiabinc52b1ff2019-10-31 17:20:42 -07008836 mPatch = audio_patch{};
8837 mInDeviceTypeAddr.reset();
Eric Laurent054d9d32015-04-24 08:48:48 -07008838
Mikhail Naganov9ee05402016-10-13 15:58:17 -07008839 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07008840 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
8841 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07008842 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07008843 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07008844 param.addInt(String8(AudioParameter::keyRouting), 0);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008845 status = mInput->stream->setParameters(param.toString());
Eric Laurent1c333e22014-05-20 10:48:17 -07008846 }
8847 return status;
8848}
8849
jiabinc52b1ff2019-10-31 17:20:42 -07008850void AudioFlinger::RecordThread::updateOutDevices(const DeviceDescriptorBaseVector& outDevices)
8851{
wendy lin56aa82b2020-12-02 15:19:55 +08008852 Mutex::Autolock _l(mLock);
jiabinc52b1ff2019-10-31 17:20:42 -07008853 mOutDevices = outDevices;
8854 mOutDeviceTypeAddrs = deviceTypeAddrsFromDescriptors(mOutDevices);
8855 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08008856 mEffectChains[i]->setDevices_l(outDeviceTypeAddrs());
jiabinc52b1ff2019-10-31 17:20:42 -07008857 }
8858}
8859
Eric Laurentec376dc2021-04-08 20:41:22 +02008860int32_t AudioFlinger::RecordThread::getOldestFront_l()
8861{
8862 if (mTracks.size() == 0) {
8863 return 0;
8864 }
Eric Laurent2407ce32021-04-26 14:56:03 +02008865 int32_t oldestFront = mRsmpInRear;
8866 int32_t maxFilled = 0;
Eric Laurentec376dc2021-04-08 20:41:22 +02008867 for (size_t i = 0; i < mTracks.size(); i++) {
Eric Laurent2407ce32021-04-26 14:56:03 +02008868 int32_t front = mTracks[i]->mResamplerBufferProvider->getFront();
8869 int32_t filled;
8870 if (front <= mRsmpInRear) {
8871 filled = mRsmpInRear - front;
8872 } else {
8873 filled = (int32_t)((int64_t)mRsmpInRear + UINT32_MAX + 1 - front);
8874 }
8875 if (filled > maxFilled) {
8876 oldestFront = front;
8877 maxFilled = filled;
8878 }
Eric Laurentec376dc2021-04-08 20:41:22 +02008879 }
Eric Laurent2407ce32021-04-26 14:56:03 +02008880 return oldestFront;
Eric Laurentec376dc2021-04-08 20:41:22 +02008881}
8882
8883void AudioFlinger::RecordThread::updateFronts_l(int32_t offset)
8884{
8885 if (offset == 0) {
8886 return;
8887 }
8888 for (size_t i = 0; i < mTracks.size(); i++) {
8889 int32_t front = mTracks[i]->mResamplerBufferProvider->getFront();
8890 front = audio_utils::safe_sub_overflow(front, offset);
8891 mTracks[i]->mResamplerBufferProvider->setFront(front);
8892 }
8893}
8894
8895void AudioFlinger::RecordThread::resizeInputBuffer_l(int32_t maxSharedAudioHistoryMs)
8896{
8897 // This is the formula for calculating the temporary buffer size.
8898 // With 7 HAL buffers, we can guarantee ability to down-sample the input by ratio of 6:1 to
8899 // 1 full output buffer, regardless of the alignment of the available input.
8900 // The value is somewhat arbitrary, and could probably be even larger.
8901 // A larger value should allow more old data to be read after a track calls start(),
8902 // without increasing latency.
8903 //
8904 // Note this is independent of the maximum downsampling ratio permitted for capture.
8905 size_t minRsmpInFrames = mFrameCount * 7;
8906
8907 // maxSharedAudioHistoryMs != 0 indicates a request to possibly make some part of the audio
8908 // capture history available to another client using the same session ID:
8909 // dimension the resampler input buffer accordingly.
8910
8911 // Get oldest client read position: getOldestFront_l() must be called before altering
8912 // mRsmpInRear, or mRsmpInFrames
8913 int32_t previousFront = getOldestFront_l();
8914 size_t previousRsmpInFramesP2 = mRsmpInFramesP2;
8915 int32_t previousRear = mRsmpInRear;
8916 mRsmpInRear = 0;
8917
8918 if (maxSharedAudioHistoryMs != 0) {
8919 // resizeInputBuffer_l should never be called with a non zero shared history if the
8920 // buffer was not already allocated
8921 ALOG_ASSERT(mRsmpInBuffer != nullptr && mRsmpInFrames != 0,
8922 "resizeInputBuffer_l() called with shared history and unallocated buffer");
8923 size_t rsmpInFrames = (size_t)maxSharedAudioHistoryMs * mSampleRate / 1000;
8924 // never reduce resampler input buffer size
8925 if (rsmpInFrames < mRsmpInFrames) {
8926 return;
8927 }
8928 mRsmpInFrames = rsmpInFrames;
8929 }
8930 // Note: mRsmpInFrames is 0 when called with maxSharedAudioHistoryMs equals to 0 so it is always
8931 // initialized
8932 if (mRsmpInFrames < minRsmpInFrames) {
8933 mRsmpInFrames = minRsmpInFrames;
8934 }
8935 mRsmpInFramesP2 = roundup(mRsmpInFrames);
8936
8937 // TODO optimize audio capture buffer sizes ...
8938 // Here we calculate the size of the sliding buffer used as a source
8939 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
8940 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
8941 // be better to have it derived from the pipe depth in the long term.
8942 // The current value is higher than necessary. However it should not add to latency.
8943
8944 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
8945 mRsmpInFramesOA = mRsmpInFramesP2 + mFrameCount - 1;
8946
8947 void *rsmpInBuffer;
8948 (void)posix_memalign(&rsmpInBuffer, 32, mRsmpInFramesOA * mFrameSize);
8949 // if posix_memalign fails, will segv here.
8950 memset(rsmpInBuffer, 0, mRsmpInFramesOA * mFrameSize);
8951
8952 // Copy audio history if any from old buffer before freeing it
8953 if (previousRear != 0) {
8954 ALOG_ASSERT(mRsmpInBuffer != nullptr,
8955 "resizeInputBuffer_l() called with null buffer but frames already read from HAL");
8956
8957 ssize_t unread = audio_utils::safe_sub_overflow(previousRear, previousFront);
8958 previousFront &= previousRsmpInFramesP2 - 1;
8959 size_t part1 = previousRsmpInFramesP2 - previousFront;
8960 if (part1 > (size_t) unread) {
8961 part1 = unread;
8962 }
8963 if (part1 != 0) {
8964 memcpy(rsmpInBuffer, (const uint8_t*)mRsmpInBuffer + previousFront * mFrameSize,
8965 part1 * mFrameSize);
8966 mRsmpInRear = part1;
8967 part1 = unread - part1;
8968 if (part1 != 0) {
8969 memcpy((uint8_t*)rsmpInBuffer + mRsmpInRear * mFrameSize,
8970 (const uint8_t*)mRsmpInBuffer, part1 * mFrameSize);
8971 mRsmpInRear += part1;
8972 }
8973 }
8974 // Update front for all clients according to new rear
8975 updateFronts_l(audio_utils::safe_sub_overflow(previousRear, mRsmpInRear));
8976 } else {
8977 mRsmpInRear = 0;
8978 }
8979 free(mRsmpInBuffer);
8980 mRsmpInBuffer = rsmpInBuffer;
8981}
8982
Mikhail Naganov444ecc32018-05-01 17:40:05 -07008983void AudioFlinger::RecordThread::addPatchTrack(const sp<PatchRecord>& record)
Eric Laurent83b88082014-06-20 18:31:16 -07008984{
8985 Mutex::Autolock _l(mLock);
8986 mTracks.add(record);
Mikhail Naganov2534b382019-09-25 13:05:02 -07008987 if (record->getSource()) {
8988 mSource = record->getSource();
8989 }
Eric Laurent83b88082014-06-20 18:31:16 -07008990}
8991
Mikhail Naganov444ecc32018-05-01 17:40:05 -07008992void AudioFlinger::RecordThread::deletePatchTrack(const sp<PatchRecord>& record)
Eric Laurent83b88082014-06-20 18:31:16 -07008993{
8994 Mutex::Autolock _l(mLock);
Mikhail Naganov2534b382019-09-25 13:05:02 -07008995 if (mSource == record->getSource()) {
8996 mSource = mInput;
8997 }
Eric Laurent83b88082014-06-20 18:31:16 -07008998 destroyTrack_l(record);
8999}
9000
Mikhail Naganovdc769682018-05-04 15:34:08 -07009001void AudioFlinger::RecordThread::toAudioPortConfig(struct audio_port_config *config)
Eric Laurent83b88082014-06-20 18:31:16 -07009002{
Mikhail Naganovdc769682018-05-04 15:34:08 -07009003 ThreadBase::toAudioPortConfig(config);
Eric Laurent83b88082014-06-20 18:31:16 -07009004 config->role = AUDIO_PORT_ROLE_SINK;
9005 config->ext.mix.hw_module = mInput->audioHwDev->handle();
9006 config->ext.mix.usecase.source = mAudioSource;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07009007 if (mInput && mInput->flags != AUDIO_INPUT_FLAG_NONE) {
9008 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
9009 config->flags.input = mInput->flags;
9010 }
Eric Laurent83b88082014-06-20 18:31:16 -07009011}
Eric Laurent1c333e22014-05-20 10:48:17 -07009012
Eric Laurent6acd1d42017-01-04 14:23:29 -08009013// ----------------------------------------------------------------------------
9014// Mmap
9015// ----------------------------------------------------------------------------
9016
9017AudioFlinger::MmapThreadHandle::MmapThreadHandle(const sp<MmapThread>& thread)
9018 : mThread(thread)
9019{
Phil Burk9fabbf82017-08-03 12:02:00 -07009020 assert(thread != 0); // thread must start non-null and stay non-null
Eric Laurent6acd1d42017-01-04 14:23:29 -08009021}
9022
9023AudioFlinger::MmapThreadHandle::~MmapThreadHandle()
9024{
Phil Burk9fabbf82017-08-03 12:02:00 -07009025 mThread->disconnect();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009026}
9027
9028status_t AudioFlinger::MmapThreadHandle::createMmapBuffer(int32_t minSizeFrames,
9029 struct audio_mmap_buffer_info *info)
9030{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009031 return mThread->createMmapBuffer(minSizeFrames, info);
9032}
9033
9034status_t AudioFlinger::MmapThreadHandle::getMmapPosition(struct audio_mmap_position *position)
9035{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009036 return mThread->getMmapPosition(position);
9037}
9038
jiabinb7d8c5a2020-08-26 17:24:52 -07009039status_t AudioFlinger::MmapThreadHandle::getExternalPosition(uint64_t *position,
9040 int64_t *timeNanos) {
9041 return mThread->getExternalPosition(position, timeNanos);
9042}
9043
Eric Laurenta54f1282017-07-01 19:39:32 -07009044status_t AudioFlinger::MmapThreadHandle::start(const AudioClient& client,
jiabind1f1cb62020-03-24 11:57:57 -07009045 const audio_attributes_t *attr, audio_port_handle_t *handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009046
9047{
jiabind1f1cb62020-03-24 11:57:57 -07009048 return mThread->start(client, attr, handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009049}
9050
9051status_t AudioFlinger::MmapThreadHandle::stop(audio_port_handle_t handle)
9052{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009053 return mThread->stop(handle);
9054}
9055
Eric Laurent18b57012017-02-13 16:23:52 -08009056status_t AudioFlinger::MmapThreadHandle::standby()
9057{
Eric Laurent18b57012017-02-13 16:23:52 -08009058 return mThread->standby();
9059}
9060
Eric Laurent6acd1d42017-01-04 14:23:29 -08009061
9062AudioFlinger::MmapThread::MmapThread(
9063 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
Andy Hungcf10d742020-04-28 15:38:24 -07009064 AudioHwDevice *hwDev, sp<StreamHalInterface> stream, bool systemReady, bool isOut)
Andy Hungea840382020-05-05 21:50:17 -07009065 : ThreadBase(audioFlinger, id, (isOut ? MMAP_PLAYBACK : MMAP_CAPTURE), systemReady, isOut),
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009066 mSessionId(AUDIO_SESSION_NONE),
François Gaffie0c280aa2018-07-25 10:02:15 +02009067 mPortId(AUDIO_PORT_HANDLE_NONE),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009068 mHalStream(stream), mHalDevice(hwDev->hwDevice()), mAudioHwDev(hwDev),
Eric Laurent67f97292018-04-20 18:05:41 -07009069 mActiveTracks(&this->mLocalLog),
9070 mHalVolFloat(-1.0f), // Initialize to illegal value so it always gets set properly later.
9071 mNoCallbackWarningCount(0)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009072{
Eric Laurent18b57012017-02-13 16:23:52 -08009073 mStandby = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009074 readHalParameters_l();
9075}
9076
9077AudioFlinger::MmapThread::~MmapThread()
9078{
9079}
9080
9081void AudioFlinger::MmapThread::onFirstRef()
9082{
9083 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
9084}
9085
9086void AudioFlinger::MmapThread::disconnect()
9087{
Eric Laurent331679c2018-04-16 17:03:16 -07009088 ActiveTracks<MmapTrack> activeTracks;
9089 {
9090 Mutex::Autolock _l(mLock);
9091 for (const sp<MmapTrack> &t : mActiveTracks) {
9092 activeTracks.add(t);
9093 }
9094 }
9095 for (const sp<MmapTrack> &t : activeTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08009096 stop(t->portId());
9097 }
Phil Burk9fabbf82017-08-03 12:02:00 -07009098 // This will decrement references and may cause the destruction of this thread.
Eric Laurent6acd1d42017-01-04 14:23:29 -08009099 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07009100 AudioSystem::releaseOutput(mPortId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009101 } else {
Eric Laurentfee19762018-01-29 18:44:13 -08009102 AudioSystem::releaseInput(mPortId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009103 }
9104}
9105
9106
9107void AudioFlinger::MmapThread::configure(const audio_attributes_t *attr,
9108 audio_stream_type_t streamType __unused,
9109 audio_session_t sessionId,
9110 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009111 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -08009112 audio_port_handle_t portId)
9113{
9114 mAttr = *attr;
9115 mSessionId = sessionId;
9116 mCallback = callback;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009117 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009118 mPortId = portId;
9119}
9120
9121status_t AudioFlinger::MmapThread::createMmapBuffer(int32_t minSizeFrames,
9122 struct audio_mmap_buffer_info *info)
9123{
9124 if (mHalStream == 0) {
9125 return NO_INIT;
9126 }
Eric Laurent18b57012017-02-13 16:23:52 -08009127 mStandby = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009128 return mHalStream->createMmapBuffer(minSizeFrames, info);
9129}
9130
9131status_t AudioFlinger::MmapThread::getMmapPosition(struct audio_mmap_position *position)
9132{
9133 if (mHalStream == 0) {
9134 return NO_INIT;
9135 }
9136 return mHalStream->getMmapPosition(position);
9137}
9138
Eric Laurent331679c2018-04-16 17:03:16 -07009139status_t AudioFlinger::MmapThread::exitStandby()
9140{
9141 status_t ret = mHalStream->start();
9142 if (ret != NO_ERROR) {
9143 ALOGE("%s: error mHalStream->start() = %d for first track", __FUNCTION__, ret);
9144 return ret;
9145 }
Andy Hungcf10d742020-04-28 15:38:24 -07009146 if (mStandby) {
9147 mThreadMetrics.logBeginInterval();
9148 mStandby = false;
9149 }
Eric Laurent331679c2018-04-16 17:03:16 -07009150 return NO_ERROR;
9151}
9152
Eric Laurenta54f1282017-07-01 19:39:32 -07009153status_t AudioFlinger::MmapThread::start(const AudioClient& client,
jiabind1f1cb62020-03-24 11:57:57 -07009154 const audio_attributes_t *attr,
Eric Laurent6acd1d42017-01-04 14:23:29 -08009155 audio_port_handle_t *handle)
9156{
Eric Laurenta54f1282017-07-01 19:39:32 -07009157 ALOGV("%s clientUid %d mStandby %d mPortId %d *handle %d", __FUNCTION__,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07009158 client.identity.uid, mStandby, mPortId, *handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009159 if (mHalStream == 0) {
9160 return NO_INIT;
9161 }
9162
9163 status_t ret;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009164
Eric Laurenta54f1282017-07-01 19:39:32 -07009165 if (*handle == mPortId) {
Phil Burk98ab4082020-09-25 21:46:34 +00009166 // For the first track, reuse portId and session allocated when the stream was opened.
9167 ret = exitStandby();
9168 if (ret == NO_ERROR) {
9169 acquireWakeLock();
9170 }
9171 return ret;
Eric Laurenta54f1282017-07-01 19:39:32 -07009172 }
9173
9174 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
9175
9176 audio_io_handle_t io = mId;
9177 if (isOutput()) {
9178 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
9179 config.sample_rate = mSampleRate;
9180 config.channel_mask = mChannelMask;
9181 config.format = mFormat;
9182 audio_stream_type_t stream = streamType();
9183 audio_output_flags_t flags =
9184 (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009185 audio_port_handle_t deviceId = mDeviceId;
Kevin Rocard153f92d2018-12-18 18:33:28 -08009186 std::vector<audio_io_handle_t> secondaryOutputs;
Eric Laurenta54f1282017-07-01 19:39:32 -07009187 ret = AudioSystem::getOutputForAttr(&mAttr, &io,
9188 mSessionId,
9189 &stream,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07009190 client.identity,
Eric Laurenta54f1282017-07-01 19:39:32 -07009191 &config,
9192 flags,
9193 &deviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -08009194 &portId,
9195 &secondaryOutputs);
9196 ALOGD_IF(!secondaryOutputs.empty(),
9197 "MmapThread::start does not support secondary outputs, ignoring them");
Eric Laurent6acd1d42017-01-04 14:23:29 -08009198 } else {
Eric Laurenta54f1282017-07-01 19:39:32 -07009199 audio_config_base_t config;
9200 config.sample_rate = mSampleRate;
9201 config.channel_mask = mChannelMask;
9202 config.format = mFormat;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009203 audio_port_handle_t deviceId = mDeviceId;
Eric Laurenta54f1282017-07-01 19:39:32 -07009204 ret = AudioSystem::getInputForAttr(&mAttr, &io,
Mikhail Naganov2996f672019-04-18 12:29:59 -07009205 RECORD_RIID_INVALID,
Eric Laurenta54f1282017-07-01 19:39:32 -07009206 mSessionId,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07009207 client.identity,
Eric Laurenta54f1282017-07-01 19:39:32 -07009208 &config,
9209 AUDIO_INPUT_FLAG_MMAP_NOIRQ,
9210 &deviceId,
9211 &portId);
9212 }
9213 // APM should not chose a different input or output stream for the same set of attributes
9214 // and audo configuration
9215 if (ret != NO_ERROR || io != mId) {
9216 ALOGE("%s: error getting output or input from APM (error %d, io %d expected io %d)",
9217 __FUNCTION__, ret, io, mId);
9218 return BAD_VALUE;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009219 }
9220
9221 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07009222 ret = AudioSystem::startOutput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009223 } else {
Eric Laurent4eb58f12018-12-07 16:41:02 -08009224 ret = AudioSystem::startInput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009225 }
9226
Eric Laurent331679c2018-04-16 17:03:16 -07009227 Mutex::Autolock _l(mLock);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009228 // abort if start is rejected by audio policy manager
9229 if (ret != NO_ERROR) {
Phil Burk7f6b40d2017-02-09 13:18:38 -08009230 ALOGE("%s: error start rejected by AudioPolicyManager = %d", __FUNCTION__, ret);
Eric Tan39ec8d62018-07-24 09:49:29 -07009231 if (!mActiveTracks.isEmpty()) {
Eric Laurent331679c2018-04-16 17:03:16 -07009232 mLock.unlock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009233 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07009234 AudioSystem::releaseOutput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009235 } else {
Eric Laurentfee19762018-01-29 18:44:13 -08009236 AudioSystem::releaseInput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009237 }
Eric Laurent331679c2018-04-16 17:03:16 -07009238 mLock.lock();
Eric Laurent18b57012017-02-13 16:23:52 -08009239 } else {
9240 mHalStream->stop();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009241 }
9242 return PERMISSION_DENIED;
9243 }
9244
Kevin Rocard1f564ac2018-03-29 13:53:10 -07009245 // Given that MmapThread::mAttr is mutable, should a MmapTrack have attributes ?
jiabind1f1cb62020-03-24 11:57:57 -07009246 sp<MmapTrack> track = new MmapTrack(this, attr == nullptr ? mAttr : *attr, mSampleRate, mFormat,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07009247 mChannelMask, mSessionId, isOutput(), client.identity,
9248 IPCThreadState::self()->getCallingPid(), portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009249
Eric Laurent4eb58f12018-12-07 16:41:02 -08009250 if (isOutput()) {
9251 // force volume update when a new track is added
9252 mHalVolFloat = -1.0f;
9253 } else if (!track->isSilenced_l()) {
9254 for (const sp<MmapTrack> &t : mActiveTracks) {
Philip P. Moltmannbda45752020-07-17 16:41:18 -07009255 if (t->isSilenced_l() && t->uid() != client.identity.uid)
Eric Laurent4eb58f12018-12-07 16:41:02 -08009256 t->invalidate();
9257 }
9258 }
9259
9260
Eric Laurent6acd1d42017-01-04 14:23:29 -08009261 mActiveTracks.add(track);
Eric Laurenta54f1282017-07-01 19:39:32 -07009262 sp<EffectChain> chain = getEffectChain_l(mSessionId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009263 if (chain != 0) {
9264 chain->setStrategy(AudioSystem::getStrategyForStream(streamType()));
9265 chain->incTrackCnt();
9266 chain->incActiveTrackCnt();
9267 }
9268
Andy Hungc2b11cb2020-04-22 09:04:01 -07009269 track->logBeginInterval(patchSinksToString(&mPatch)); // log to MediaMetrics
Eric Laurent6acd1d42017-01-04 14:23:29 -08009270 *handle = portId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009271 broadcast_l();
9272
Eric Laurenta54f1282017-07-01 19:39:32 -07009273 ALOGV("%s DONE handle %d stream %p", __FUNCTION__, *handle, mHalStream.get());
Eric Laurent6acd1d42017-01-04 14:23:29 -08009274
9275 return NO_ERROR;
9276}
9277
9278status_t AudioFlinger::MmapThread::stop(audio_port_handle_t handle)
9279{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009280 ALOGV("%s handle %d", __FUNCTION__, handle);
9281
9282 if (mHalStream == 0) {
9283 return NO_INIT;
9284 }
9285
Eric Laurenta54f1282017-07-01 19:39:32 -07009286 if (handle == mPortId) {
9287 mHalStream->stop();
Phil Burk98ab4082020-09-25 21:46:34 +00009288 releaseWakeLock();
Eric Laurenta54f1282017-07-01 19:39:32 -07009289 return NO_ERROR;
9290 }
9291
Eric Laurent331679c2018-04-16 17:03:16 -07009292 Mutex::Autolock _l(mLock);
9293
Eric Laurent6acd1d42017-01-04 14:23:29 -08009294 sp<MmapTrack> track;
9295 for (const sp<MmapTrack> &t : mActiveTracks) {
9296 if (handle == t->portId()) {
9297 track = t;
9298 break;
9299 }
9300 }
9301 if (track == 0) {
9302 return BAD_VALUE;
9303 }
9304
9305 mActiveTracks.remove(track);
9306
Eric Laurent331679c2018-04-16 17:03:16 -07009307 mLock.unlock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009308 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07009309 AudioSystem::stopOutput(track->portId());
9310 AudioSystem::releaseOutput(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -08009311 } else {
Eric Laurentfee19762018-01-29 18:44:13 -08009312 AudioSystem::stopInput(track->portId());
9313 AudioSystem::releaseInput(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -08009314 }
Eric Laurent331679c2018-04-16 17:03:16 -07009315 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009316
9317 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
9318 if (chain != 0) {
9319 chain->decActiveTrackCnt();
9320 chain->decTrackCnt();
9321 }
9322
9323 broadcast_l();
9324
Eric Laurent6acd1d42017-01-04 14:23:29 -08009325 return NO_ERROR;
9326}
9327
Eric Laurent18b57012017-02-13 16:23:52 -08009328status_t AudioFlinger::MmapThread::standby()
9329{
9330 ALOGV("%s", __FUNCTION__);
9331
9332 if (mHalStream == 0) {
9333 return NO_INIT;
9334 }
Eric Tan39ec8d62018-07-24 09:49:29 -07009335 if (!mActiveTracks.isEmpty()) {
Eric Laurent18b57012017-02-13 16:23:52 -08009336 return INVALID_OPERATION;
9337 }
9338 mHalStream->standby();
Andy Hungcf10d742020-04-28 15:38:24 -07009339 if (!mStandby) {
9340 mThreadMetrics.logEndInterval();
9341 mStandby = true;
9342 }
Eric Laurent18b57012017-02-13 16:23:52 -08009343 releaseWakeLock();
9344 return NO_ERROR;
9345}
9346
Eric Laurent6acd1d42017-01-04 14:23:29 -08009347
9348void AudioFlinger::MmapThread::readHalParameters_l()
9349{
9350 status_t result = mHalStream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
9351 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
9352 mFormat = mHALFormat;
9353 LOG_ALWAYS_FATAL_IF(!audio_is_linear_pcm(mFormat), "HAL format %#x is not linear pcm", mFormat);
9354 result = mHalStream->getFrameSize(&mFrameSize);
9355 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
Hayden Gomes1a89ab32020-06-12 11:05:47 -07009356 LOG_ALWAYS_FATAL_IF(mFrameSize <= 0, "Error frame size was %zu but must be greater than zero",
9357 mFrameSize);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009358 result = mHalStream->getBufferSize(&mBufferSize);
9359 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
9360 mFrameCount = mBufferSize / mFrameSize;
Andy Hungc2b11cb2020-04-22 09:04:01 -07009361
Andy Hungcf10d742020-04-28 15:38:24 -07009362 // TODO: make a readHalParameters call?
9363 mediametrics::LogItem item(mThreadMetrics.getMetricsId());
Andy Hungc2b11cb2020-04-22 09:04:01 -07009364 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
9365 .set(AMEDIAMETRICS_PROP_ENCODING, formatToString(mFormat).c_str())
9366 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
9367 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
9368 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
9369 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mFrameCount)
9370 /*
9371 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
9372 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELMASK,
9373 (int32_t)mHapticChannelMask)
9374 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELCOUNT,
9375 (int32_t)mHapticChannelCount)
9376 */
9377 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_ENCODING,
9378 formatToString(mHALFormat).c_str())
9379 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_FRAMECOUNT,
9380 (int32_t)mFrameCount) // sic - added HAL
9381 .record();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009382}
9383
9384bool AudioFlinger::MmapThread::threadLoop()
9385{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009386 checkSilentMode_l();
9387
9388 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
9389
9390 while (!exitPending())
9391 {
Eric Laurent6acd1d42017-01-04 14:23:29 -08009392 Vector< sp<EffectChain> > effectChains;
9393
Andy Hung13850be2019-03-14 11:33:09 -07009394 { // under Thread lock
9395 Mutex::Autolock _l(mLock);
9396
Eric Laurent6acd1d42017-01-04 14:23:29 -08009397 if (mSignalPending) {
9398 // A signal was raised while we were unlocked
9399 mSignalPending = false;
9400 } else {
9401 if (mConfigEvents.isEmpty()) {
9402 // we're about to wait, flush the binder command buffer
9403 IPCThreadState::self()->flushCommands();
9404
9405 if (exitPending()) {
9406 break;
9407 }
9408
Eric Laurent6acd1d42017-01-04 14:23:29 -08009409 // wait until we have something to do...
9410 ALOGV("%s going to sleep", myName.string());
9411 mWaitWorkCV.wait(mLock);
9412 ALOGV("%s waking up", myName.string());
Eric Laurent6acd1d42017-01-04 14:23:29 -08009413
9414 checkSilentMode_l();
9415
9416 continue;
9417 }
9418 }
9419
9420 processConfigEvents_l();
9421
9422 processVolume_l();
9423
9424 checkInvalidTracks_l();
9425
9426 mActiveTracks.updatePowerState(this);
9427
Kevin Rocard069c2712018-03-29 19:09:14 -07009428 updateMetadata_l();
9429
Eric Laurent6acd1d42017-01-04 14:23:29 -08009430 lockEffectChains_l(effectChains);
Andy Hung13850be2019-03-14 11:33:09 -07009431 } // release Thread lock
9432
Eric Laurent6acd1d42017-01-04 14:23:29 -08009433 for (size_t i = 0; i < effectChains.size(); i ++) {
Andy Hung13850be2019-03-14 11:33:09 -07009434 effectChains[i]->process_l(); // Thread is not locked, but effect chain is locked
Eric Laurent6acd1d42017-01-04 14:23:29 -08009435 }
Andy Hung13850be2019-03-14 11:33:09 -07009436
9437 // enable changes in effect chain, including moving to another thread.
Eric Laurent6acd1d42017-01-04 14:23:29 -08009438 unlockEffectChains(effectChains);
9439 // Effect chains will be actually deleted here if they were removed from
9440 // mEffectChains list during mixing or effects processing
9441 }
9442
9443 threadLoop_exit();
9444
9445 if (!mStandby) {
9446 threadLoop_standby();
9447 mStandby = true;
9448 }
9449
Eric Laurent6acd1d42017-01-04 14:23:29 -08009450 ALOGV("Thread %p type %d exiting", this, mType);
9451 return false;
9452}
9453
9454// checkForNewParameter_l() must be called with ThreadBase::mLock held
9455bool AudioFlinger::MmapThread::checkForNewParameter_l(const String8& keyValuePair,
9456 status_t& status)
9457{
9458 AudioParameter param = AudioParameter(keyValuePair);
9459 int value;
Eric Laurente6e9a482017-07-25 19:26:02 -07009460 bool sendToHal = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009461 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07009462 LOG_FATAL("Should not happen set routing device in MmapThread");
Eric Laurent6acd1d42017-01-04 14:23:29 -08009463 }
Eric Laurente6e9a482017-07-25 19:26:02 -07009464 if (sendToHal) {
9465 status = mHalStream->setParameters(keyValuePair);
9466 } else {
9467 status = NO_ERROR;
9468 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08009469
9470 return false;
9471}
9472
9473String8 AudioFlinger::MmapThread::getParameters(const String8& keys)
9474{
9475 Mutex::Autolock _l(mLock);
9476 String8 out_s8;
9477 if (initCheck() == NO_ERROR && mHalStream->getParameters(keys, &out_s8) == OK) {
9478 return out_s8;
9479 }
9480 return String8();
9481}
9482
Eric Laurent09f1ed22019-04-24 17:45:17 -07009483void AudioFlinger::MmapThread::ioConfigChanged(audio_io_config_event event, pid_t pid,
9484 audio_port_handle_t portId __unused) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08009485 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
9486
9487 desc->mIoHandle = mId;
9488
9489 switch (event) {
9490 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07009491 case AUDIO_INPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -08009492 case AUDIO_INPUT_CONFIG_CHANGED:
9493 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07009494 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -08009495 case AUDIO_OUTPUT_CONFIG_CHANGED:
9496 desc->mPatch = mPatch;
9497 desc->mChannelMask = mChannelMask;
9498 desc->mSamplingRate = mSampleRate;
9499 desc->mFormat = mFormat;
9500 desc->mFrameCount = mFrameCount;
9501 desc->mFrameCountHAL = mFrameCount;
9502 desc->mLatency = 0;
9503 break;
9504
9505 case AUDIO_INPUT_CLOSED:
9506 case AUDIO_OUTPUT_CLOSED:
9507 default:
9508 break;
9509 }
9510 mAudioFlinger->ioConfigChanged(event, desc, pid);
9511}
9512
9513status_t AudioFlinger::MmapThread::createAudioPatch_l(const struct audio_patch *patch,
9514 audio_patch_handle_t *handle)
9515{
9516 status_t status = NO_ERROR;
9517
9518 // store new device and send to effects
9519 audio_devices_t type = AUDIO_DEVICE_NONE;
9520 audio_port_handle_t deviceId;
jiabinc52b1ff2019-10-31 17:20:42 -07009521 AudioDeviceTypeAddrVector sinkDeviceTypeAddrs;
9522 AudioDeviceTypeAddr sourceDeviceTypeAddr;
9523 uint32_t numDevices = 0;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009524 if (isOutput()) {
9525 for (unsigned int i = 0; i < patch->num_sinks; i++) {
jiabinc52b1ff2019-10-31 17:20:42 -07009526 LOG_ALWAYS_FATAL_IF(popcount(patch->sinks[i].ext.device.type) > 1
9527 && !mAudioHwDev->supportsAudioPatches(),
9528 "Enumerated device type(%#x) must not be used "
9529 "as it does not support audio patches",
9530 patch->sinks[i].ext.device.type);
Mikhail Naganov55773032020-10-01 15:08:13 -07009531 type = static_cast<audio_devices_t>(type | patch->sinks[i].ext.device.type);
jiabinc52b1ff2019-10-31 17:20:42 -07009532 sinkDeviceTypeAddrs.push_back(AudioDeviceTypeAddr(patch->sinks[i].ext.device.type,
9533 patch->sinks[i].ext.device.address));
Eric Laurent6acd1d42017-01-04 14:23:29 -08009534 }
9535 deviceId = patch->sinks[0].id;
jiabinc52b1ff2019-10-31 17:20:42 -07009536 numDevices = mPatch.num_sinks;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009537 } else {
9538 type = patch->sources[0].ext.device.type;
9539 deviceId = patch->sources[0].id;
jiabinc52b1ff2019-10-31 17:20:42 -07009540 numDevices = mPatch.num_sources;
9541 sourceDeviceTypeAddr.mType = patch->sources[0].ext.device.type;
jiabin0a488932020-08-07 17:32:40 -07009542 sourceDeviceTypeAddr.setAddress(patch->sources[0].ext.device.address);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009543 }
9544
9545 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08009546 if (isOutput()) {
9547 mEffectChains[i]->setDevices_l(sinkDeviceTypeAddrs);
9548 } else {
9549 mEffectChains[i]->setInputDevice_l(sourceDeviceTypeAddr);
9550 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08009551 }
9552
jiabinc52b1ff2019-10-31 17:20:42 -07009553 if (!isOutput()) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08009554 // store new source and send to effects
9555 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
9556 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
9557 for (size_t i = 0; i < mEffectChains.size(); i++) {
9558 mEffectChains[i]->setAudioSource_l(mAudioSource);
9559 }
9560 }
9561 }
9562
9563 if (mAudioHwDev->supportsAudioPatches()) {
9564 status = mHalDevice->createAudioPatch(patch->num_sources,
9565 patch->sources,
9566 patch->num_sinks,
9567 patch->sinks,
9568 handle);
9569 } else {
9570 char *address;
9571 if (strcmp(patch->sinks[0].ext.device.address, "") != 0) {
9572 //FIXME: we only support address on first sink with HAL version < 3.0
9573 address = audio_device_address_to_parameter(
9574 patch->sinks[0].ext.device.type,
9575 patch->sinks[0].ext.device.address);
9576 } else {
9577 address = (char *)calloc(1, 1);
9578 }
9579 AudioParameter param = AudioParameter(String8(address));
9580 free(address);
9581 param.addInt(String8(AudioParameter::keyRouting), (int)type);
9582 if (!isOutput()) {
9583 param.addInt(String8(AudioParameter::keyInputSource),
9584 (int)patch->sinks[0].ext.mix.usecase.source);
9585 }
9586 status = mHalStream->setParameters(param.toString());
9587 *handle = AUDIO_PATCH_HANDLE_NONE;
9588 }
9589
jiabinc52b1ff2019-10-31 17:20:42 -07009590 if (numDevices == 0 || mDeviceId != deviceId) {
9591 if (isOutput()) {
9592 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
9593 mOutDeviceTypeAddrs = sinkDeviceTypeAddrs;
jiabin0a957d32020-04-29 10:56:20 -07009594 checkSilentMode_l();
jiabinc52b1ff2019-10-31 17:20:42 -07009595 } else {
9596 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
9597 mInDeviceTypeAddr = sourceDeviceTypeAddr;
9598 }
Phil Burk7f6b40d2017-02-09 13:18:38 -08009599 sp<MmapStreamCallback> callback = mCallback.promote();
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009600 if (mDeviceId != deviceId && callback != 0) {
Eric Laurent734046e2018-04-16 14:50:52 -07009601 mLock.unlock();
Phil Burk7f6b40d2017-02-09 13:18:38 -08009602 callback->onRoutingChanged(deviceId);
Eric Laurent734046e2018-04-16 14:50:52 -07009603 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009604 }
jiabinc52b1ff2019-10-31 17:20:42 -07009605 mPatch = *patch;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009606 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009607 }
9608 return status;
9609}
9610
9611status_t AudioFlinger::MmapThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
9612{
9613 status_t status = NO_ERROR;
9614
jiabinc52b1ff2019-10-31 17:20:42 -07009615 mPatch = audio_patch{};
9616 mOutDeviceTypeAddrs.clear();
9617 mInDeviceTypeAddr.reset();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009618
9619 bool supportsAudioPatches = mHalDevice->supportsAudioPatches(&supportsAudioPatches) == OK ?
9620 supportsAudioPatches : false;
9621
9622 if (supportsAudioPatches) {
9623 status = mHalDevice->releaseAudioPatch(handle);
9624 } else {
9625 AudioParameter param;
9626 param.addInt(String8(AudioParameter::keyRouting), 0);
9627 status = mHalStream->setParameters(param.toString());
9628 }
9629 return status;
9630}
9631
Mikhail Naganovdc769682018-05-04 15:34:08 -07009632void AudioFlinger::MmapThread::toAudioPortConfig(struct audio_port_config *config)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009633{
Mikhail Naganovdc769682018-05-04 15:34:08 -07009634 ThreadBase::toAudioPortConfig(config);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009635 if (isOutput()) {
9636 config->role = AUDIO_PORT_ROLE_SOURCE;
9637 config->ext.mix.hw_module = mAudioHwDev->handle();
9638 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
9639 } else {
9640 config->role = AUDIO_PORT_ROLE_SINK;
9641 config->ext.mix.hw_module = mAudioHwDev->handle();
9642 config->ext.mix.usecase.source = mAudioSource;
9643 }
9644}
9645
9646status_t AudioFlinger::MmapThread::addEffectChain_l(const sp<EffectChain>& chain)
9647{
9648 audio_session_t session = chain->sessionId();
9649
9650 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
9651 // Attach all tracks with same session ID to this chain.
9652 // indicate all active tracks in the chain
9653 for (const sp<MmapTrack> &track : mActiveTracks) {
9654 if (session == track->sessionId()) {
9655 chain->incTrackCnt();
9656 chain->incActiveTrackCnt();
9657 }
9658 }
9659
9660 chain->setThread(this);
9661 chain->setInBuffer(nullptr);
9662 chain->setOutBuffer(nullptr);
9663 chain->syncHalEffectsState();
9664
9665 mEffectChains.add(chain);
9666 checkSuspendOnAddEffectChain_l(chain);
9667 return NO_ERROR;
9668}
9669
9670size_t AudioFlinger::MmapThread::removeEffectChain_l(const sp<EffectChain>& chain)
9671{
9672 audio_session_t session = chain->sessionId();
9673
9674 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
9675
9676 for (size_t i = 0; i < mEffectChains.size(); i++) {
9677 if (chain == mEffectChains[i]) {
9678 mEffectChains.removeAt(i);
9679 // detach all active tracks from the chain
9680 // detach all tracks with same session ID from this chain
9681 for (const sp<MmapTrack> &track : mActiveTracks) {
9682 if (session == track->sessionId()) {
9683 chain->decActiveTrackCnt();
9684 chain->decTrackCnt();
9685 }
9686 }
9687 break;
9688 }
9689 }
9690 return mEffectChains.size();
9691}
9692
Eric Laurent6acd1d42017-01-04 14:23:29 -08009693void AudioFlinger::MmapThread::threadLoop_standby()
9694{
9695 mHalStream->standby();
9696}
9697
9698void AudioFlinger::MmapThread::threadLoop_exit()
9699{
Phil Burk7dce7282017-09-27 13:51:41 -07009700 // Do not call callback->onTearDown() because it is redundant for thread exit
9701 // and because it can cause a recursive mutex lock on stop().
Eric Laurent6acd1d42017-01-04 14:23:29 -08009702}
9703
9704status_t AudioFlinger::MmapThread::setSyncEvent(const sp<SyncEvent>& event __unused)
9705{
9706 return BAD_VALUE;
9707}
9708
9709bool AudioFlinger::MmapThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
9710{
9711 return false;
9712}
9713
9714status_t AudioFlinger::MmapThread::checkEffectCompatibility_l(
9715 const effect_descriptor_t *desc, audio_session_t sessionId)
9716{
9717 // No global effect sessions on mmap threads
Eric Laurent3f75a5b2019-11-12 15:55:51 -08009718 if (audio_is_global_session(sessionId)) {
9719 ALOGW("checkEffectCompatibility_l(): global effect %s on MMAP thread %s",
Eric Laurent6acd1d42017-01-04 14:23:29 -08009720 desc->name, mThreadName);
9721 return BAD_VALUE;
9722 }
9723
9724 if (!isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC)) {
9725 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on capture mmap thread",
9726 desc->name);
9727 return BAD_VALUE;
9728 }
9729 if (isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Glenn Kastend3bb6452016-12-05 18:14:37 -08009730 ALOGW("checkEffectCompatibility_l(): pre processing effect %s created on playback mmap "
9731 "thread", desc->name);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009732 return BAD_VALUE;
9733 }
9734
9735 // Only allow effects without processing load or latency
9736 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) != EFFECT_FLAG_NO_PROCESS) {
9737 return BAD_VALUE;
9738 }
9739
jiabineb3bda02020-06-30 14:07:03 -07009740 if (EffectModule::isHapticGenerator(&desc->type)) {
9741 ALOGE("%s(): HapticGenerator is not supported for MmapThread", __func__);
9742 return BAD_VALUE;
9743 }
9744
Eric Laurent6acd1d42017-01-04 14:23:29 -08009745 return NO_ERROR;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009746}
9747
9748void AudioFlinger::MmapThread::checkInvalidTracks_l()
9749{
9750 for (const sp<MmapTrack> &track : mActiveTracks) {
9751 if (track->isInvalid()) {
Phil Burk7f6b40d2017-02-09 13:18:38 -08009752 sp<MmapStreamCallback> callback = mCallback.promote();
9753 if (callback != 0) {
Eric Laurent734046e2018-04-16 14:50:52 -07009754 mLock.unlock();
Eric Laurent331679c2018-04-16 17:03:16 -07009755 callback->onTearDown(track->portId());
Eric Laurent734046e2018-04-16 14:50:52 -07009756 mLock.lock();
Eric Laurent331679c2018-04-16 17:03:16 -07009757 } else if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
9758 ALOGW("Could not notify MMAP stream tear down: no onTearDown callback!");
9759 mNoCallbackWarningCount++;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009760 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08009761 }
9762 }
9763}
9764
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07009765void AudioFlinger::MmapThread::dumpInternals_l(int fd, const Vector<String16>& args __unused)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009766{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009767 dprintf(fd, " Attributes: content type %d usage %d source %d\n",
9768 mAttr.content_type, mAttr.usage, mAttr.source);
9769 dprintf(fd, " Session: %d port Id: %d\n", mSessionId, mPortId);
Eric Tan39ec8d62018-07-24 09:49:29 -07009770 if (mActiveTracks.isEmpty()) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08009771 dprintf(fd, " No active clients\n");
9772 }
9773}
9774
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07009775void AudioFlinger::MmapThread::dumpTracks_l(int fd, const Vector<String16>& args __unused)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009776{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009777 String8 result;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009778 size_t numtracks = mActiveTracks.size();
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009779 dprintf(fd, " %zu Tracks\n", numtracks);
9780 const char *prefix = " ";
Eric Laurent6acd1d42017-01-04 14:23:29 -08009781 if (numtracks) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009782 result.append(prefix);
Kevin Rocard5f2136e2018-05-11 22:03:00 -07009783 mActiveTracks[0]->appendDumpHeader(result);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009784 for (size_t i = 0; i < numtracks ; ++i) {
9785 sp<MmapTrack> track = mActiveTracks[i];
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009786 result.append(prefix);
9787 track->appendDump(result, true /* active */);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009788 }
9789 } else {
9790 dprintf(fd, "\n");
9791 }
9792 write(fd, result.string(), result.size());
9793}
9794
9795AudioFlinger::MmapPlaybackThread::MmapPlaybackThread(
9796 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
jiabinc52b1ff2019-10-31 17:20:42 -07009797 AudioHwDevice *hwDev, AudioStreamOut *output, bool systemReady)
Andy Hungcf10d742020-04-28 15:38:24 -07009798 : MmapThread(audioFlinger, id, hwDev, output->stream, systemReady, true /* isOut */),
Eric Laurent6acd1d42017-01-04 14:23:29 -08009799 mStreamType(AUDIO_STREAM_MUSIC),
Phil Burk56ecf3e2018-03-12 15:38:17 -07009800 mStreamVolume(1.0),
9801 mStreamMute(false),
Phil Burk56ecf3e2018-03-12 15:38:17 -07009802 mOutput(output)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009803{
9804 snprintf(mThreadName, kThreadNameLength, "AudioMmapOut_%X", id);
9805 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
9806 mMasterVolume = audioFlinger->masterVolume_l();
9807 mMasterMute = audioFlinger->masterMute_l();
9808 if (mAudioHwDev) {
9809 if (mAudioHwDev->canSetMasterVolume()) {
9810 mMasterVolume = 1.0;
9811 }
9812
9813 if (mAudioHwDev->canSetMasterMute()) {
9814 mMasterMute = false;
9815 }
9816 }
9817}
9818
9819void AudioFlinger::MmapPlaybackThread::configure(const audio_attributes_t *attr,
9820 audio_stream_type_t streamType,
9821 audio_session_t sessionId,
9822 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009823 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -08009824 audio_port_handle_t portId)
9825{
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009826 MmapThread::configure(attr, streamType, sessionId, callback, deviceId, portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009827 mStreamType = streamType;
9828}
9829
9830AudioStreamOut* AudioFlinger::MmapPlaybackThread::clearOutput()
9831{
9832 Mutex::Autolock _l(mLock);
9833 AudioStreamOut *output = mOutput;
9834 mOutput = NULL;
9835 return output;
9836}
9837
9838void AudioFlinger::MmapPlaybackThread::setMasterVolume(float value)
9839{
9840 Mutex::Autolock _l(mLock);
9841 // Don't apply master volume in SW if our HAL can do it for us.
9842 if (mAudioHwDev &&
9843 mAudioHwDev->canSetMasterVolume()) {
9844 mMasterVolume = 1.0;
9845 } else {
9846 mMasterVolume = value;
9847 }
9848}
9849
9850void AudioFlinger::MmapPlaybackThread::setMasterMute(bool muted)
9851{
9852 Mutex::Autolock _l(mLock);
9853 // Don't apply master mute in SW if our HAL can do it for us.
9854 if (mAudioHwDev && mAudioHwDev->canSetMasterMute()) {
9855 mMasterMute = false;
9856 } else {
9857 mMasterMute = muted;
9858 }
9859}
9860
9861void AudioFlinger::MmapPlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
9862{
9863 Mutex::Autolock _l(mLock);
9864 if (stream == mStreamType) {
9865 mStreamVolume = value;
9866 broadcast_l();
9867 }
9868}
9869
9870float AudioFlinger::MmapPlaybackThread::streamVolume(audio_stream_type_t stream) const
9871{
9872 Mutex::Autolock _l(mLock);
9873 if (stream == mStreamType) {
9874 return mStreamVolume;
9875 }
9876 return 0.0f;
9877}
9878
9879void AudioFlinger::MmapPlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
9880{
9881 Mutex::Autolock _l(mLock);
9882 if (stream == mStreamType) {
9883 mStreamMute= muted;
9884 broadcast_l();
9885 }
9886}
9887
9888void AudioFlinger::MmapPlaybackThread::invalidateTracks(audio_stream_type_t streamType)
9889{
9890 Mutex::Autolock _l(mLock);
9891 if (streamType == mStreamType) {
9892 for (const sp<MmapTrack> &track : mActiveTracks) {
9893 track->invalidate();
9894 }
9895 broadcast_l();
9896 }
9897}
9898
9899void AudioFlinger::MmapPlaybackThread::processVolume_l()
9900{
9901 float volume;
9902
9903 if (mMasterMute || mStreamMute) {
9904 volume = 0;
9905 } else {
9906 volume = mMasterVolume * mStreamVolume;
9907 }
9908
9909 if (volume != mHalVolFloat) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08009910
9911 // Convert volumes from float to 8.24
9912 uint32_t vol = (uint32_t)(volume * (1 << 24));
9913
9914 // Delegate volume control to effect in track effect chain if needed
9915 // only one effect chain can be present on DirectOutputThread, so if
9916 // there is one, the track is connected to it
9917 if (!mEffectChains.isEmpty()) {
9918 mEffectChains[0]->setVolume_l(&vol, &vol);
9919 volume = (float)vol / (1 << 24);
9920 }
Eric Laurentdff774a2017-04-21 15:29:38 -07009921 // Try to use HW volume control and fall back to SW control if not implemented
Phil Burk56ecf3e2018-03-12 15:38:17 -07009922 if (mOutput->stream->setVolume(volume, volume) == NO_ERROR) {
9923 mHalVolFloat = volume; // HW volume control worked, so update value.
9924 mNoCallbackWarningCount = 0;
9925 } else {
Eric Laurentdff774a2017-04-21 15:29:38 -07009926 sp<MmapStreamCallback> callback = mCallback.promote();
9927 if (callback != 0) {
9928 int channelCount;
9929 if (isOutput()) {
9930 channelCount = audio_channel_count_from_out_mask(mChannelMask);
9931 } else {
9932 channelCount = audio_channel_count_from_in_mask(mChannelMask);
9933 }
9934 Vector<float> values;
9935 for (int i = 0; i < channelCount; i++) {
9936 values.add(volume);
9937 }
Phil Burk56ecf3e2018-03-12 15:38:17 -07009938 mHalVolFloat = volume; // SW volume control worked, so update value.
9939 mNoCallbackWarningCount = 0;
Eric Laurent734046e2018-04-16 14:50:52 -07009940 mLock.unlock();
9941 callback->onVolumeChanged(mChannelMask, values);
9942 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009943 } else {
Phil Burk56ecf3e2018-03-12 15:38:17 -07009944 if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
9945 ALOGW("Could not set MMAP stream volume: no volume callback!");
9946 mNoCallbackWarningCount++;
9947 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08009948 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08009949 }
9950 }
9951}
9952
Kevin Rocard069c2712018-03-29 19:09:14 -07009953void AudioFlinger::MmapPlaybackThread::updateMetadata_l()
9954{
9955 if (mOutput == nullptr || mOutput->stream == nullptr ||
9956 !mActiveTracks.readAndClearHasChanged()) {
9957 return;
9958 }
9959 StreamOutHalInterface::SourceMetadata metadata;
9960 for (const sp<MmapTrack> &track : mActiveTracks) {
9961 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurent94579172020-11-20 18:41:04 +01009962 playback_track_metadata_v7_t trackMetadata;
9963 trackMetadata.base = {
Kevin Rocard069c2712018-03-29 19:09:14 -07009964 .usage = track->attributes().usage,
9965 .content_type = track->attributes().content_type,
9966 .gain = mHalVolFloat, // TODO: propagate from aaudio pre-mix volume
Eric Laurent94579172020-11-20 18:41:04 +01009967 };
9968 trackMetadata.channel_mask = track->channelMask(),
9969 strncpy(trackMetadata.tags, track->attributes().tags, AUDIO_ATTRIBUTES_TAGS_MAX_SIZE);
9970 metadata.tracks.push_back(trackMetadata);
Kevin Rocard069c2712018-03-29 19:09:14 -07009971 }
9972 mOutput->stream->updateSourceMetadata(metadata);
9973}
9974
Eric Laurent6acd1d42017-01-04 14:23:29 -08009975void AudioFlinger::MmapPlaybackThread::checkSilentMode_l()
9976{
9977 if (!mMasterMute) {
9978 char value[PROPERTY_VALUE_MAX];
9979 if (property_get("ro.audio.silent", value, "0") > 0) {
9980 char *endptr;
9981 unsigned long ul = strtoul(value, &endptr, 0);
9982 if (*endptr == '\0' && ul != 0) {
9983 ALOGD("Silence is golden");
9984 // The setprop command will not allow a property to be changed after
9985 // the first time it is set, so we don't have to worry about un-muting.
9986 setMasterMute_l(true);
9987 }
9988 }
9989 }
9990}
9991
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07009992void AudioFlinger::MmapPlaybackThread::toAudioPortConfig(struct audio_port_config *config)
9993{
9994 MmapThread::toAudioPortConfig(config);
9995 if (mOutput && mOutput->flags != AUDIO_OUTPUT_FLAG_NONE) {
9996 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
9997 config->flags.output = mOutput->flags;
9998 }
9999}
10000
jiabinb7d8c5a2020-08-26 17:24:52 -070010001status_t AudioFlinger::MmapPlaybackThread::getExternalPosition(uint64_t *position,
10002 int64_t *timeNanos)
10003{
10004 if (mOutput == nullptr) {
10005 return NO_INIT;
10006 }
10007 struct timespec timestamp;
10008 status_t status = mOutput->getPresentationPosition(position, &timestamp);
10009 if (status == NO_ERROR) {
10010 *timeNanos = timestamp.tv_sec * NANOS_PER_SECOND + timestamp.tv_nsec;
10011 }
10012 return status;
10013}
10014
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -070010015void AudioFlinger::MmapPlaybackThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010016{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -070010017 MmapThread::dumpInternals_l(fd, args);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010018
Glenn Kastend3bb6452016-12-05 18:14:37 -080010019 dprintf(fd, " Stream type: %d Stream volume: %f HAL volume: %f Stream mute %d\n",
10020 mStreamType, mStreamVolume, mHalVolFloat, mStreamMute);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010021 dprintf(fd, " Master volume: %f Master mute %d\n", mMasterVolume, mMasterMute);
10022}
10023
10024AudioFlinger::MmapCaptureThread::MmapCaptureThread(
10025 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
jiabinc52b1ff2019-10-31 17:20:42 -070010026 AudioHwDevice *hwDev, AudioStreamIn *input, bool systemReady)
Andy Hungcf10d742020-04-28 15:38:24 -070010027 : MmapThread(audioFlinger, id, hwDev, input->stream, systemReady, false /* isOut */),
Eric Laurent6acd1d42017-01-04 14:23:29 -080010028 mInput(input)
10029{
10030 snprintf(mThreadName, kThreadNameLength, "AudioMmapIn_%X", id);
10031 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
10032}
10033
Eric Laurent331679c2018-04-16 17:03:16 -070010034status_t AudioFlinger::MmapCaptureThread::exitStandby()
10035{
Phil Burkf054fc32018-12-06 09:45:59 -080010036 {
10037 // mInput might have been cleared by clearInput()
10038 Mutex::Autolock _l(mLock);
10039 if (mInput != nullptr && mInput->stream != nullptr) {
10040 mInput->stream->setGain(1.0f);
10041 }
10042 }
Eric Laurent331679c2018-04-16 17:03:16 -070010043 return MmapThread::exitStandby();
10044}
10045
Eric Laurent6acd1d42017-01-04 14:23:29 -080010046AudioFlinger::AudioStreamIn* AudioFlinger::MmapCaptureThread::clearInput()
10047{
10048 Mutex::Autolock _l(mLock);
10049 AudioStreamIn *input = mInput;
10050 mInput = NULL;
10051 return input;
10052}
Kevin Rocard069c2712018-03-29 19:09:14 -070010053
Eric Laurent331679c2018-04-16 17:03:16 -070010054
10055void AudioFlinger::MmapCaptureThread::processVolume_l()
10056{
10057 bool changed = false;
10058 bool silenced = false;
10059
10060 sp<MmapStreamCallback> callback = mCallback.promote();
10061 if (callback == 0) {
10062 if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
10063 ALOGW("Could not set MMAP stream silenced: no onStreamSilenced callback!");
10064 mNoCallbackWarningCount++;
10065 }
10066 }
10067
10068 // After a change occurred in track silenced state, mute capture in audio DSP if at least one
10069 // track is silenced and unmute otherwise
10070 for (size_t i = 0; i < mActiveTracks.size() && !silenced; i++) {
10071 if (!mActiveTracks[i]->getAndSetSilencedNotified_l()) {
10072 changed = true;
10073 silenced = mActiveTracks[i]->isSilenced_l();
10074 }
10075 }
10076
10077 if (changed) {
10078 mInput->stream->setGain(silenced ? 0.0f: 1.0f);
10079 }
10080}
10081
Kevin Rocard069c2712018-03-29 19:09:14 -070010082void AudioFlinger::MmapCaptureThread::updateMetadata_l()
10083{
10084 if (mInput == nullptr || mInput->stream == nullptr ||
10085 !mActiveTracks.readAndClearHasChanged()) {
10086 return;
10087 }
10088 StreamInHalInterface::SinkMetadata metadata;
10089 for (const sp<MmapTrack> &track : mActiveTracks) {
10090 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurent94579172020-11-20 18:41:04 +010010091 record_track_metadata_v7_t trackMetadata;
10092 trackMetadata.base = {
Kevin Rocard069c2712018-03-29 19:09:14 -070010093 .source = track->attributes().source,
10094 .gain = 1, // capture tracks do not have volumes
Eric Laurent94579172020-11-20 18:41:04 +010010095 };
10096 trackMetadata.channel_mask = track->channelMask(),
10097 strncpy(trackMetadata.tags, track->attributes().tags, AUDIO_ATTRIBUTES_TAGS_MAX_SIZE);
10098 metadata.tracks.push_back(trackMetadata);
Kevin Rocard069c2712018-03-29 19:09:14 -070010099 }
10100 mInput->stream->updateSinkMetadata(metadata);
10101}
10102
Eric Laurent5ada82e2019-08-29 17:53:54 -070010103void AudioFlinger::MmapCaptureThread::setRecordSilenced(audio_port_handle_t portId, bool silenced)
Eric Laurent331679c2018-04-16 17:03:16 -070010104{
10105 Mutex::Autolock _l(mLock);
10106 for (size_t i = 0; i < mActiveTracks.size() ; i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -070010107 if (mActiveTracks[i]->portId() == portId) {
Eric Laurent331679c2018-04-16 17:03:16 -070010108 mActiveTracks[i]->setSilenced_l(silenced);
10109 broadcast_l();
10110 }
10111 }
10112}
10113
Mikhail Naganov32abc2b2018-05-24 12:57:11 -070010114void AudioFlinger::MmapCaptureThread::toAudioPortConfig(struct audio_port_config *config)
10115{
10116 MmapThread::toAudioPortConfig(config);
10117 if (mInput && mInput->flags != AUDIO_INPUT_FLAG_NONE) {
10118 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
10119 config->flags.input = mInput->flags;
10120 }
10121}
10122
jiabinb7d8c5a2020-08-26 17:24:52 -070010123status_t AudioFlinger::MmapCaptureThread::getExternalPosition(
10124 uint64_t *position, int64_t *timeNanos)
10125{
10126 if (mInput == nullptr) {
10127 return NO_INIT;
10128 }
10129 return mInput->getCapturePosition((int64_t*)position, timeNanos);
10130}
10131
Glenn Kasten63238ef2015-03-02 15:50:29 -080010132} // namespace android