blob: d42a6ca108a26b26172c7ee86fcd268326544adf [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, ");
Andy Hungfba71252021-05-07 11:58:32 -0700818 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY) s.append("low-frequency, ");
Andy Hungf98ec8d2015-05-19 12:53:24 -0700819 if (mask & AUDIO_CHANNEL_OUT_BACK_LEFT) s.append("back-left, ");
820 if (mask & AUDIO_CHANNEL_OUT_BACK_RIGHT) s.append("back-right, ");
821 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT_OF_CENTER) s.append("front-left-of-center, ");
822 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT_OF_CENTER) s.append("front-right-of-center, ");
823 if (mask & AUDIO_CHANNEL_OUT_BACK_CENTER) s.append("back-center, ");
824 if (mask & AUDIO_CHANNEL_OUT_SIDE_LEFT) s.append("side-left, ");
825 if (mask & AUDIO_CHANNEL_OUT_SIDE_RIGHT) s.append("side-right, ");
826 if (mask & AUDIO_CHANNEL_OUT_TOP_CENTER) s.append("top-center ,");
827 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_LEFT) s.append("top-front-left, ");
828 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_CENTER) s.append("top-front-center, ");
829 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_RIGHT) s.append("top-front-right, ");
830 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_LEFT) s.append("top-back-left, ");
Andy Hungae81b4c2021-05-07 08:54:28 -0700831 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_CENTER) s.append("top-back-center, ");
832 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_RIGHT) s.append("top-back-right, ");
833 if (mask & AUDIO_CHANNEL_OUT_TOP_SIDE_LEFT) s.append("top-side-left, ");
834 if (mask & AUDIO_CHANNEL_OUT_TOP_SIDE_RIGHT) s.append("top-side-right, ");
835 if (mask & AUDIO_CHANNEL_OUT_BOTTOM_FRONT_LEFT) s.append("bottom-front-left, ");
836 if (mask & AUDIO_CHANNEL_OUT_BOTTOM_FRONT_CENTER) s.append("bottom-front-center, ");
837 if (mask & AUDIO_CHANNEL_OUT_BOTTOM_FRONT_RIGHT) s.append("bottom-front-right, ");
Andy Hungfba71252021-05-07 11:58:32 -0700838 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY_2) s.append("low-frequency-2, ");
Andy Hungae81b4c2021-05-07 08:54:28 -0700839 if (mask & AUDIO_CHANNEL_OUT_HAPTIC_B) s.append("haptic-B, ");
840 if (mask & AUDIO_CHANNEL_OUT_HAPTIC_A) s.append("haptic-A, ");
Andy Hungf98ec8d2015-05-19 12:53:24 -0700841 if (mask & ~AUDIO_CHANNEL_OUT_ALL) s.append("unknown, ");
842 } else {
843 if (mask & AUDIO_CHANNEL_IN_LEFT) s.append("left, ");
844 if (mask & AUDIO_CHANNEL_IN_RIGHT) s.append("right, ");
845 if (mask & AUDIO_CHANNEL_IN_FRONT) s.append("front, ");
846 if (mask & AUDIO_CHANNEL_IN_BACK) s.append("back, ");
847 if (mask & AUDIO_CHANNEL_IN_LEFT_PROCESSED) s.append("left-processed, ");
848 if (mask & AUDIO_CHANNEL_IN_RIGHT_PROCESSED) s.append("right-processed, ");
849 if (mask & AUDIO_CHANNEL_IN_FRONT_PROCESSED) s.append("front-processed, ");
850 if (mask & AUDIO_CHANNEL_IN_BACK_PROCESSED) s.append("back-processed, ");
851 if (mask & AUDIO_CHANNEL_IN_PRESSURE) s.append("pressure, ");
852 if (mask & AUDIO_CHANNEL_IN_X_AXIS) s.append("X, ");
853 if (mask & AUDIO_CHANNEL_IN_Y_AXIS) s.append("Y, ");
854 if (mask & AUDIO_CHANNEL_IN_Z_AXIS) s.append("Z, ");
Mikhail Naganovc9948492018-05-10 17:25:28 -0700855 if (mask & AUDIO_CHANNEL_IN_BACK_LEFT) s.append("back-left, ");
856 if (mask & AUDIO_CHANNEL_IN_BACK_RIGHT) s.append("back-right, ");
857 if (mask & AUDIO_CHANNEL_IN_CENTER) s.append("center, ");
Andy Hungfba71252021-05-07 11:58:32 -0700858 if (mask & AUDIO_CHANNEL_IN_LOW_FREQUENCY) s.append("low-frequency, ");
Andy Hungae81b4c2021-05-07 08:54:28 -0700859 if (mask & AUDIO_CHANNEL_IN_TOP_LEFT) s.append("top-left, ");
860 if (mask & AUDIO_CHANNEL_IN_TOP_RIGHT) s.append("top-right, ");
Andy Hungf98ec8d2015-05-19 12:53:24 -0700861 if (mask & AUDIO_CHANNEL_IN_VOICE_UPLINK) s.append("voice-uplink, ");
862 if (mask & AUDIO_CHANNEL_IN_VOICE_DNLINK) s.append("voice-dnlink, ");
863 if (mask & ~AUDIO_CHANNEL_IN_ALL) s.append("unknown, ");
864 }
865 const int len = s.length();
866 if (len > 2) {
Glenn Kasten57c4e6f2016-03-18 14:54:07 -0700867 (void) s.lockBuffer(len); // needed?
Andy Hungf98ec8d2015-05-19 12:53:24 -0700868 s.unlockBuffer(len - 2); // remove trailing ", "
869 }
870 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -0800871 }
Andy Hungf98ec8d2015-05-19 12:53:24 -0700872 case AUDIO_CHANNEL_REPRESENTATION_INDEX:
873 s.appendFormat("index mask, bits:%#x", audio_channel_mask_get_bits(mask));
874 return s;
875 default:
876 s.appendFormat("unknown mask, representation:%d bits:%#x",
877 representation, audio_channel_mask_get_bits(mask));
878 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -0800879 }
Marco Nelissenb2208842014-02-07 14:00:50 -0800880}
881
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -0700882void AudioFlinger::ThreadBase::dump(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -0800883{
Glenn Kasten1bfe09a2017-02-21 13:05:56 -0800884 dprintf(fd, "\n%s thread %p, name %s, tid %d, type %d (%s):\n", isOutput() ? "Output" : "Input",
885 this, mThreadName, getTid(), type(), threadTypeToString(type()));
886
Eric Laurent81784c32012-11-19 14:55:58 -0800887 bool locked = AudioFlinger::dumpTryLock(mLock);
888 if (!locked) {
Glenn Kasten1bfe09a2017-02-21 13:05:56 -0800889 dprintf(fd, " Thread may be deadlocked\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800890 }
891
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -0700892 dumpBase_l(fd, args);
893 dumpInternals_l(fd, args);
894 dumpTracks_l(fd, args);
895 dumpEffectChains_l(fd, args);
896
897 if (locked) {
898 mLock.unlock();
899 }
900
901 dprintf(fd, " Local log:\n");
902 mLocalLog.dump(fd, " " /* prefix */, 40 /* lines */);
903}
904
905void AudioFlinger::ThreadBase::dumpBase_l(int fd, const Vector<String16>& args __unused)
906{
Elliott Hughes87cebad2014-05-22 10:14:43 -0700907 dprintf(fd, " I/O handle: %d\n", mId);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700908 dprintf(fd, " Standby: %s\n", mStandby ? "yes" : "no");
Glenn Kasten97b7b752014-09-28 13:04:24 -0700909 dprintf(fd, " Sample rate: %u Hz\n", mSampleRate);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700910 dprintf(fd, " HAL frame count: %zu\n", mFrameCount);
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700911 dprintf(fd, " HAL format: 0x%x (%s)\n", mHALFormat, formatToString(mHALFormat).c_str());
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700912 dprintf(fd, " HAL buffer size: %zu bytes\n", mBufferSize);
Glenn Kasten97b7b752014-09-28 13:04:24 -0700913 dprintf(fd, " Channel count: %u\n", mChannelCount);
914 dprintf(fd, " Channel mask: 0x%08x (%s)\n", mChannelMask,
Marco Nelissenb2208842014-02-07 14:00:50 -0800915 channelMaskToString(mChannelMask, mType != RECORD).string());
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700916 dprintf(fd, " Processing format: 0x%x (%s)\n", mFormat, formatToString(mFormat).c_str());
Glenn Kastenf87c2f52015-08-21 08:03:57 -0700917 dprintf(fd, " Processing frame size: %zu bytes\n", mFrameSize);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700918 dprintf(fd, " Pending config events:");
Marco Nelissenb2208842014-02-07 14:00:50 -0800919 size_t numConfig = mConfigEvents.size();
920 if (numConfig) {
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -0700921 const size_t SIZE = 256;
922 char buffer[SIZE];
Marco Nelissenb2208842014-02-07 14:00:50 -0800923 for (size_t i = 0; i < numConfig; i++) {
924 mConfigEvents[i]->dump(buffer, SIZE);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700925 dprintf(fd, "\n %s", buffer);
Marco Nelissenb2208842014-02-07 14:00:50 -0800926 }
Elliott Hughes87cebad2014-05-22 10:14:43 -0700927 dprintf(fd, "\n");
Marco Nelissenb2208842014-02-07 14:00:50 -0800928 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -0700929 dprintf(fd, " none\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800930 }
Andy Hung293558a2017-03-21 12:19:20 -0700931 // Note: output device may be used by capture threads for effects such as AEC.
jiabinc52b1ff2019-10-31 17:20:42 -0700932 dprintf(fd, " Output devices: %s (%s)\n",
933 dumpDeviceTypes(outDeviceTypes()).c_str(), toString(outDeviceTypes()).c_str());
934 dprintf(fd, " Input device: %#x (%s)\n",
935 inDeviceType(), toString(inDeviceType()).c_str());
Andy Hung9b181952019-02-25 14:53:36 -0800936 dprintf(fd, " Audio source: %d (%s)\n", mAudioSource, toString(mAudioSource).c_str());
Eric Laurent81784c32012-11-19 14:55:58 -0800937
Andy Hung2e2c0bb2018-06-11 19:13:11 -0700938 // Dump timestamp statistics for the Thread types that support it.
939 if (mType == RECORD
940 || mType == MIXER
941 || mType == DUPLICATING
Andy Hungf3234512018-07-03 14:51:47 -0700942 || mType == DIRECT
943 || mType == OFFLOAD) {
Andy Hung2e2c0bb2018-06-11 19:13:11 -0700944 dprintf(fd, " Timestamp stats: %s\n", mTimestampVerifier.toString().c_str());
Andy Hungc8fddf32018-08-08 18:32:37 -0700945 dprintf(fd, " Timestamp corrected: %s\n", isTimestampCorrectionEnabled() ? "yes" : "no");
Andy Hung2e2c0bb2018-06-11 19:13:11 -0700946 }
947
Andy Hung446f4df2019-02-21 12:26:41 -0800948 if (mLastIoBeginNs > 0) { // MMAP may not set this
949 dprintf(fd, " Last %s occurred (msecs): %lld\n",
950 isOutput() ? "write" : "read",
951 (long long) (systemTime() - mLastIoBeginNs) / NANOS_PER_MILLISECOND);
952 }
953
954 if (mProcessTimeMs.getN() > 0) {
955 dprintf(fd, " Process time ms stats: %s\n", mProcessTimeMs.toString().c_str());
956 }
957
958 if (mIoJitterMs.getN() > 0) {
959 dprintf(fd, " Hal %s jitter ms stats: %s\n",
960 isOutput() ? "write" : "read",
961 mIoJitterMs.toString().c_str());
962 }
963
Andy Hunge6c37112019-02-26 17:38:10 -0800964 if (mLatencyMs.getN() > 0) {
965 dprintf(fd, " Threadloop %s latency stats: %s\n",
966 isOutput() ? "write" : "read",
967 mLatencyMs.toString().c_str());
968 }
Eric Laurent81784c32012-11-19 14:55:58 -0800969}
970
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -0700971void AudioFlinger::ThreadBase::dumpEffectChains_l(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -0800972{
973 const size_t SIZE = 256;
974 char buffer[SIZE];
Eric Laurent81784c32012-11-19 14:55:58 -0800975
Marco Nelissenb2208842014-02-07 14:00:50 -0800976 size_t numEffectChains = mEffectChains.size();
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +0000977 snprintf(buffer, SIZE, " %zu Effect Chains\n", numEffectChains);
Eric Laurent81784c32012-11-19 14:55:58 -0800978 write(fd, buffer, strlen(buffer));
979
Marco Nelissenb2208842014-02-07 14:00:50 -0800980 for (size_t i = 0; i < numEffectChains; ++i) {
Eric Laurent81784c32012-11-19 14:55:58 -0800981 sp<EffectChain> chain = mEffectChains[i];
982 if (chain != 0) {
983 chain->dump(fd, args);
984 }
985 }
986}
987
Andy Hungdae27702016-10-31 14:01:16 -0700988void AudioFlinger::ThreadBase::acquireWakeLock()
Eric Laurent81784c32012-11-19 14:55:58 -0800989{
990 Mutex::Autolock _l(mLock);
Andy Hungdae27702016-10-31 14:01:16 -0700991 acquireWakeLock_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800992}
993
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100994String16 AudioFlinger::ThreadBase::getWakeLockTag()
995{
996 switch (mType) {
Glenn Kastenbcb14862015-03-05 17:11:21 -0800997 case MIXER:
998 return String16("AudioMix");
999 case DIRECT:
1000 return String16("AudioDirectOut");
1001 case DUPLICATING:
1002 return String16("AudioDup");
1003 case RECORD:
1004 return String16("AudioIn");
1005 case OFFLOAD:
1006 return String16("AudioOffload");
Andy Hungea840382020-05-05 21:50:17 -07001007 case MMAP_PLAYBACK:
1008 return String16("MmapPlayback");
1009 case MMAP_CAPTURE:
1010 return String16("MmapCapture");
Glenn Kastenbcb14862015-03-05 17:11:21 -08001011 default:
1012 ALOG_ASSERT(false);
1013 return String16("AudioUnknown");
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001014 }
1015}
1016
Andy Hungdae27702016-10-31 14:01:16 -07001017void AudioFlinger::ThreadBase::acquireWakeLock_l()
Eric Laurent81784c32012-11-19 14:55:58 -08001018{
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001019 getPowerManager_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001020 if (mPowerManager != 0) {
1021 sp<IBinder> binder = new BBinder();
Andy Hungdae27702016-10-31 14:01:16 -07001022 // Uses AID_AUDIOSERVER for wakelock. updateWakeLockUids_l() updates with client uids.
Chris Ye6597d732020-02-28 22:38:25 -08001023 binder::Status status = mPowerManager->acquireWakeLockAsync(binder,
1024 POWERMANAGER_PARTIAL_WAKE_LOCK,
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001025 getWakeLockTag(),
Marco Nelissendcb346b2015-09-09 10:47:29 -07001026 String16("audioserver"),
Chris Ye6597d732020-02-28 22:38:25 -08001027 {} /* workSource */,
1028 {} /* historyTag */);
1029 if (status.isOk()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001030 mWakeLockToken = binder;
1031 }
Chris Ye6597d732020-02-28 22:38:25 -08001032 ALOGV("acquireWakeLock_l() %s status %d", mThreadName, status.exceptionCode());
Eric Laurent81784c32012-11-19 14:55:58 -08001033 }
Wei Jia3f273d12015-11-24 09:06:49 -08001034
Andy Hung3f0c9022016-01-15 17:49:46 -08001035 gBoottime.acquire(mWakeLockToken);
Andy Hung818e7a32016-02-16 18:08:07 -08001036 mTimestamp.mTimebaseOffset[ExtendedTimestamp::TIMEBASE_BOOTTIME] =
1037 gBoottime.getBoottimeOffset();
Eric Laurent81784c32012-11-19 14:55:58 -08001038}
1039
1040void AudioFlinger::ThreadBase::releaseWakeLock()
1041{
1042 Mutex::Autolock _l(mLock);
1043 releaseWakeLock_l();
1044}
1045
1046void AudioFlinger::ThreadBase::releaseWakeLock_l()
1047{
Andy Hung3f0c9022016-01-15 17:49:46 -08001048 gBoottime.release(mWakeLockToken);
Eric Laurent81784c32012-11-19 14:55:58 -08001049 if (mWakeLockToken != 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -08001050 ALOGV("releaseWakeLock_l() %s", mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08001051 if (mPowerManager != 0) {
Chris Ye6597d732020-02-28 22:38:25 -08001052 mPowerManager->releaseWakeLockAsync(mWakeLockToken, 0);
Eric Laurent81784c32012-11-19 14:55:58 -08001053 }
1054 mWakeLockToken.clear();
1055 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001056}
1057
1058void AudioFlinger::ThreadBase::getPowerManager_l() {
Eric Laurent72e3f392015-05-20 14:43:50 -07001059 if (mSystemReady && mPowerManager == 0) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001060 // use checkService() to avoid blocking if power service is not up yet
1061 sp<IBinder> binder =
1062 defaultServiceManager()->checkService(String16("power"));
1063 if (binder == 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -08001064 ALOGW("Thread %s cannot connect to the power manager service", mThreadName);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001065 } else {
Chris Ye6597d732020-02-28 22:38:25 -08001066 mPowerManager = interface_cast<os::IPowerManager>(binder);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001067 binder->linkToDeath(mDeathRecipient);
1068 }
1069 }
1070}
1071
Andy Hungd01b0f12016-11-07 16:10:30 -08001072void AudioFlinger::ThreadBase::updateWakeLockUids_l(const SortedVector<uid_t> &uids) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001073 getPowerManager_l();
Andy Hungdae27702016-10-31 14:01:16 -07001074
1075#if !LOG_NDEBUG
1076 std::stringstream s;
Andy Hungd01b0f12016-11-07 16:10:30 -08001077 for (uid_t uid : uids) {
Andy Hungdae27702016-10-31 14:01:16 -07001078 s << uid << " ";
1079 }
1080 ALOGD("updateWakeLockUids_l %s uids:%s", mThreadName, s.str().c_str());
1081#endif
1082
Andy Hung438e7572015-12-14 15:51:17 -08001083 if (mWakeLockToken == NULL) { // token may be NULL if AudioFlinger::systemReady() not called.
1084 if (mSystemReady) {
1085 ALOGE("no wake lock to update, but system ready!");
1086 } else {
1087 ALOGW("no wake lock to update, system not ready yet");
1088 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001089 return;
1090 }
1091 if (mPowerManager != 0) {
Andy Hung1f12a8a2016-11-07 16:10:30 -08001092 std::vector<int> uidsAsInt(uids.begin(), uids.end()); // powermanager expects uids as ints
Chris Ye6597d732020-02-28 22:38:25 -08001093 binder::Status status = mPowerManager->updateWakeLockUidsAsync(
1094 mWakeLockToken, uidsAsInt);
1095 ALOGV("updateWakeLockUids_l() %s status %d", mThreadName, status.exceptionCode());
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001096 }
1097}
1098
Eric Laurent81784c32012-11-19 14:55:58 -08001099void AudioFlinger::ThreadBase::clearPowerManager()
1100{
1101 Mutex::Autolock _l(mLock);
1102 releaseWakeLock_l();
1103 mPowerManager.clear();
1104}
1105
jiabinc52b1ff2019-10-31 17:20:42 -07001106void AudioFlinger::ThreadBase::updateOutDevices(
1107 const DeviceDescriptorBaseVector& outDevices __unused)
1108{
1109 ALOGE("%s should only be called in RecordThread", __func__);
1110}
1111
Eric Laurentec376dc2021-04-08 20:41:22 +02001112void AudioFlinger::ThreadBase::resizeInputBuffer_l(int32_t maxSharedAudioHistoryMs __unused)
1113{
1114 ALOGE("%s should only be called in RecordThread", __func__);
1115}
1116
Glenn Kasten0f11b512014-01-31 16:18:54 -08001117void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001118{
1119 sp<ThreadBase> thread = mThread.promote();
1120 if (thread != 0) {
1121 thread->clearPowerManager();
1122 }
1123 ALOGW("power manager service died !!!");
1124}
1125
Eric Laurent81784c32012-11-19 14:55:58 -08001126void AudioFlinger::ThreadBase::setEffectSuspended_l(
Glenn Kastend848eb42016-03-08 13:42:11 -08001127 const effect_uuid_t *type, bool suspend, audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001128{
1129 sp<EffectChain> chain = getEffectChain_l(sessionId);
1130 if (chain != 0) {
1131 if (type != NULL) {
1132 chain->setEffectSuspended_l(type, suspend);
1133 } else {
1134 chain->setEffectSuspendedAll_l(suspend);
1135 }
1136 }
1137
1138 updateSuspendedSessions_l(type, suspend, sessionId);
1139}
1140
1141void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1142{
1143 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
1144 if (index < 0) {
1145 return;
1146 }
1147
1148 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
1149 mSuspendedSessions.valueAt(index);
1150
1151 for (size_t i = 0; i < sessionEffects.size(); i++) {
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07001152 const sp<SuspendedSessionDesc>& desc = sessionEffects.valueAt(i);
Eric Laurent81784c32012-11-19 14:55:58 -08001153 for (int j = 0; j < desc->mRefCount; j++) {
1154 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1155 chain->setEffectSuspendedAll_l(true);
1156 } else {
1157 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
1158 desc->mType.timeLow);
1159 chain->setEffectSuspended_l(&desc->mType, true);
1160 }
1161 }
1162 }
1163}
1164
1165void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1166 bool suspend,
Glenn Kastend848eb42016-03-08 13:42:11 -08001167 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001168{
1169 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
1170
1171 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1172
1173 if (suspend) {
1174 if (index >= 0) {
1175 sessionEffects = mSuspendedSessions.valueAt(index);
1176 } else {
1177 mSuspendedSessions.add(sessionId, sessionEffects);
1178 }
1179 } else {
1180 if (index < 0) {
1181 return;
1182 }
1183 sessionEffects = mSuspendedSessions.valueAt(index);
1184 }
1185
1186
1187 int key = EffectChain::kKeyForSuspendAll;
1188 if (type != NULL) {
1189 key = type->timeLow;
1190 }
1191 index = sessionEffects.indexOfKey(key);
1192
1193 sp<SuspendedSessionDesc> desc;
1194 if (suspend) {
1195 if (index >= 0) {
1196 desc = sessionEffects.valueAt(index);
1197 } else {
1198 desc = new SuspendedSessionDesc();
1199 if (type != NULL) {
1200 desc->mType = *type;
1201 }
1202 sessionEffects.add(key, desc);
1203 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
1204 }
1205 desc->mRefCount++;
1206 } else {
1207 if (index < 0) {
1208 return;
1209 }
1210 desc = sessionEffects.valueAt(index);
1211 if (--desc->mRefCount == 0) {
1212 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
1213 sessionEffects.removeItemsAt(index);
1214 if (sessionEffects.isEmpty()) {
1215 ALOGV("updateSuspendedSessions_l() restore removing session %d",
1216 sessionId);
1217 mSuspendedSessions.removeItem(sessionId);
1218 }
1219 }
1220 }
1221 if (!sessionEffects.isEmpty()) {
1222 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1223 }
1224}
1225
Eric Laurent6b446ce2019-12-13 10:56:31 -08001226void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(bool enabled,
1227 audio_session_t sessionId,
1228 bool threadLocked) {
1229 if (!threadLocked) {
1230 mLock.lock();
1231 }
Eric Laurent81784c32012-11-19 14:55:58 -08001232
Eric Laurent81784c32012-11-19 14:55:58 -08001233 if (mType != RECORD) {
1234 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1235 // another session. This gives the priority to well behaved effect control panels
1236 // and applications not using global effects.
1237 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
1238 // global effects
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001239 if (!audio_is_global_session(sessionId)) {
Eric Laurent81784c32012-11-19 14:55:58 -08001240 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1241 }
1242 }
1243
Eric Laurent6b446ce2019-12-13 10:56:31 -08001244 if (!threadLocked) {
1245 mLock.unlock();
Eric Laurent81784c32012-11-19 14:55:58 -08001246 }
1247}
1248
Eric Laurent4c415062016-06-17 16:14:16 -07001249// checkEffectCompatibility_l() must be called with ThreadBase::mLock held
1250status_t AudioFlinger::RecordThread::checkEffectCompatibility_l(
1251 const effect_descriptor_t *desc, audio_session_t sessionId)
1252{
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001253 // No global output effect sessions on record threads
1254 if (sessionId == AUDIO_SESSION_OUTPUT_MIX
1255 || sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Eric Laurent4c415062016-06-17 16:14:16 -07001256 ALOGW("checkEffectCompatibility_l(): global effect %s on record thread %s",
1257 desc->name, mThreadName);
1258 return BAD_VALUE;
1259 }
1260 // only pre processing effects on record thread
1261 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC) {
1262 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on record thread %s",
1263 desc->name, mThreadName);
1264 return BAD_VALUE;
1265 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001266
1267 // always allow effects without processing load or latency
1268 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1269 return NO_ERROR;
1270 }
1271
Eric Laurent4c415062016-06-17 16:14:16 -07001272 audio_input_flags_t flags = mInput->flags;
1273 if (hasFastCapture() || (flags & AUDIO_INPUT_FLAG_FAST)) {
1274 if (flags & AUDIO_INPUT_FLAG_RAW) {
1275 ALOGW("checkEffectCompatibility_l(): effect %s on record thread %s in raw mode",
1276 desc->name, mThreadName);
1277 return BAD_VALUE;
1278 }
1279 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1280 ALOGW("checkEffectCompatibility_l(): non HW effect %s on record thread %s in fast mode",
1281 desc->name, mThreadName);
1282 return BAD_VALUE;
1283 }
1284 }
jiabineb3bda02020-06-30 14:07:03 -07001285
1286 if (EffectModule::isHapticGenerator(&desc->type)) {
1287 ALOGE("%s(): HapticGenerator is not supported in RecordThread", __func__);
1288 return BAD_VALUE;
1289 }
Eric Laurent4c415062016-06-17 16:14:16 -07001290 return NO_ERROR;
1291}
1292
1293// checkEffectCompatibility_l() must be called with ThreadBase::mLock held
1294status_t AudioFlinger::PlaybackThread::checkEffectCompatibility_l(
1295 const effect_descriptor_t *desc, audio_session_t sessionId)
1296{
1297 // no preprocessing on playback threads
1298 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC) {
1299 ALOGW("checkEffectCompatibility_l(): pre processing effect %s created on playback"
1300 " thread %s", desc->name, mThreadName);
1301 return BAD_VALUE;
1302 }
1303
Eric Laurent3e4de772017-07-16 16:55:08 -07001304 // always allow effects without processing load or latency
1305 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1306 return NO_ERROR;
1307 }
1308
jiabineb3bda02020-06-30 14:07:03 -07001309 if (EffectModule::isHapticGenerator(&desc->type) && mHapticChannelCount == 0) {
1310 ALOGW("%s: thread doesn't support haptic playback while the effect is HapticGenerator",
1311 __func__);
1312 return BAD_VALUE;
1313 }
1314
Eric Laurent4c415062016-06-17 16:14:16 -07001315 switch (mType) {
1316 case MIXER: {
Andy Hung9aad48c2017-11-29 10:29:19 -08001317#ifndef MULTICHANNEL_EFFECT_CHAIN
Eric Laurent4c415062016-06-17 16:14:16 -07001318 // Reject any effect on mixer multichannel sinks.
1319 // TODO: fix both format and multichannel issues with effects.
1320 if (mChannelCount != FCC_2) {
1321 ALOGW("checkEffectCompatibility_l(): effect %s for multichannel(%d) on MIXER"
1322 " thread %s", desc->name, mChannelCount, mThreadName);
1323 return BAD_VALUE;
1324 }
Andy Hung9aad48c2017-11-29 10:29:19 -08001325#endif
Eric Laurent4c415062016-06-17 16:14:16 -07001326 audio_output_flags_t flags = mOutput->flags;
1327 if (hasFastMixer() || (flags & AUDIO_OUTPUT_FLAG_FAST)) {
1328 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1329 // global effects are applied only to non fast tracks if they are SW
1330 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1331 break;
1332 }
1333 } else if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1334 // only post processing on output stage session
1335 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
1336 ALOGW("checkEffectCompatibility_l(): non post processing effect %s not allowed"
1337 " on output stage session", desc->name);
1338 return BAD_VALUE;
1339 }
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001340 } else if (sessionId == AUDIO_SESSION_DEVICE) {
1341 // only post processing on output stage session
1342 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
1343 ALOGW("checkEffectCompatibility_l(): non post processing effect %s not allowed"
1344 " on device session", desc->name);
1345 return BAD_VALUE;
1346 }
Eric Laurent4c415062016-06-17 16:14:16 -07001347 } else {
1348 // no restriction on effects applied on non fast tracks
1349 if ((hasAudioSession_l(sessionId) & ThreadBase::FAST_SESSION) == 0) {
1350 break;
1351 }
1352 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001353
Eric Laurent4c415062016-06-17 16:14:16 -07001354 if (flags & AUDIO_OUTPUT_FLAG_RAW) {
1355 ALOGW("checkEffectCompatibility_l(): effect %s on playback thread in raw mode",
1356 desc->name);
1357 return BAD_VALUE;
1358 }
1359 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1360 ALOGW("checkEffectCompatibility_l(): non HW effect %s on playback thread"
1361 " in fast mode", desc->name);
1362 return BAD_VALUE;
1363 }
1364 }
1365 } break;
1366 case OFFLOAD:
Jean-Michel Trivi773ee952016-07-11 16:53:18 -07001367 // nothing actionable on offload threads, if the effect:
1368 // - is offloadable: the effect can be created
1369 // - is NOT offloadable: the effect should still be created, but EffectHandle::enable()
1370 // will take care of invalidating the tracks of the thread
Eric Laurent4c415062016-06-17 16:14:16 -07001371 break;
1372 case DIRECT:
1373 // Reject any effect on Direct output threads for now, since the format of
1374 // mSinkBuffer is not guaranteed to be compatible with effect processing (PCM 16 stereo).
1375 ALOGW("checkEffectCompatibility_l(): effect %s on DIRECT output thread %s",
1376 desc->name, mThreadName);
1377 return BAD_VALUE;
1378 case DUPLICATING:
Andy Hung9aad48c2017-11-29 10:29:19 -08001379#ifndef MULTICHANNEL_EFFECT_CHAIN
Eric Laurent4c415062016-06-17 16:14:16 -07001380 // Reject any effect on mixer multichannel sinks.
1381 // TODO: fix both format and multichannel issues with effects.
1382 if (mChannelCount != FCC_2) {
1383 ALOGW("checkEffectCompatibility_l(): effect %s for multichannel(%d)"
1384 " on DUPLICATING thread %s", desc->name, mChannelCount, mThreadName);
1385 return BAD_VALUE;
1386 }
Andy Hung9aad48c2017-11-29 10:29:19 -08001387#endif
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001388 if (audio_is_global_session(sessionId)) {
Eric Laurent4c415062016-06-17 16:14:16 -07001389 ALOGW("checkEffectCompatibility_l(): global effect %s on DUPLICATING"
1390 " thread %s", desc->name, mThreadName);
1391 return BAD_VALUE;
1392 }
1393 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
1394 ALOGW("checkEffectCompatibility_l(): post processing effect %s on"
1395 " DUPLICATING thread %s", desc->name, mThreadName);
1396 return BAD_VALUE;
1397 }
1398 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) != 0) {
1399 ALOGW("checkEffectCompatibility_l(): HW tunneled effect %s on"
1400 " DUPLICATING thread %s", desc->name, mThreadName);
1401 return BAD_VALUE;
1402 }
1403 break;
1404 default:
1405 LOG_ALWAYS_FATAL("checkEffectCompatibility_l(): wrong thread type %d", mType);
1406 }
1407
1408 return NO_ERROR;
1409}
1410
Eric Laurent81784c32012-11-19 14:55:58 -08001411// ThreadBase::createEffect_l() must be called with AudioFlinger::mLock held
1412sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
1413 const sp<AudioFlinger::Client>& client,
1414 const sp<IEffectClient>& effectClient,
1415 int32_t priority,
Glenn Kastend848eb42016-03-08 13:42:11 -08001416 audio_session_t sessionId,
Eric Laurent81784c32012-11-19 14:55:58 -08001417 effect_descriptor_t *desc,
1418 int *enabled,
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001419 status_t *status,
Eric Laurent2fe0acd2020-03-13 14:30:46 -07001420 bool pinned,
1421 bool probe)
Eric Laurent81784c32012-11-19 14:55:58 -08001422{
1423 sp<EffectModule> effect;
1424 sp<EffectHandle> handle;
1425 status_t lStatus;
1426 sp<EffectChain> chain;
1427 bool chainCreated = false;
1428 bool effectCreated = false;
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001429 audio_unique_id_t effectId = AUDIO_UNIQUE_ID_USE_UNSPECIFIED;
Eric Laurent81784c32012-11-19 14:55:58 -08001430
1431 lStatus = initCheck();
1432 if (lStatus != NO_ERROR) {
1433 ALOGW("createEffect_l() Audio driver not initialized.");
1434 goto Exit;
1435 }
1436
Eric Laurent81784c32012-11-19 14:55:58 -08001437 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
1438
1439 { // scope for mLock
1440 Mutex::Autolock _l(mLock);
1441
Eric Laurent4c415062016-06-17 16:14:16 -07001442 lStatus = checkEffectCompatibility_l(desc, sessionId);
Eric Laurent2fe0acd2020-03-13 14:30:46 -07001443 if (probe || lStatus != NO_ERROR) {
Eric Laurent4c415062016-06-17 16:14:16 -07001444 goto Exit;
1445 }
1446
Eric Laurent81784c32012-11-19 14:55:58 -08001447 // check for existing effect chain with the requested audio session
1448 chain = getEffectChain_l(sessionId);
1449 if (chain == 0) {
1450 // create a new chain for this session
1451 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
1452 chain = new EffectChain(this, sessionId);
1453 addEffectChain_l(chain);
1454 chain->setStrategy(getStrategyForSession_l(sessionId));
1455 chainCreated = true;
1456 } else {
1457 effect = chain->getEffectFromDesc_l(desc);
1458 }
1459
1460 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
1461
1462 if (effect == 0) {
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001463 effectId = mAudioFlinger->nextUniqueId(AUDIO_UNIQUE_ID_USE_EFFECT);
Eric Laurent81784c32012-11-19 14:55:58 -08001464 // create a new effect module if none present in the chain
Eric Laurent6b446ce2019-12-13 10:56:31 -08001465 lStatus = chain->createEffect_l(effect, desc, effectId, sessionId, pinned);
Eric Laurent81784c32012-11-19 14:55:58 -08001466 if (lStatus != NO_ERROR) {
1467 goto Exit;
1468 }
1469 effectCreated = true;
1470
jiabinc52b1ff2019-10-31 17:20:42 -07001471 // FIXME: use vector of device and address when effect interface is ready.
jiabin8f278ee2019-11-11 12:16:27 -08001472 effect->setDevices(outDeviceTypeAddrs());
1473 effect->setInputDevice(inDeviceTypeAddr());
Eric Laurent81784c32012-11-19 14:55:58 -08001474 effect->setMode(mAudioFlinger->getMode());
1475 effect->setAudioSource(mAudioSource);
1476 }
jiabin1319f5a2021-03-30 22:21:24 +00001477 if (effect->isHapticGenerator()) {
1478 // TODO(b/184194057): Use the vibrator information from the vibrator that will be used
1479 // for the HapticGenerator.
1480 const media::AudioVibratorInfo* defaultVibratorInfo =
1481 mAudioFlinger->getDefaultVibratorInfo_l();
1482 if (defaultVibratorInfo != nullptr) {
1483 // Only set the vibrator info when it is a valid one.
1484 effect->setVibratorInfo(defaultVibratorInfo);
1485 }
1486 }
Eric Laurent81784c32012-11-19 14:55:58 -08001487 // create effect handle and connect it to effect module
1488 handle = new EffectHandle(effect, client, effectClient, priority);
Glenn Kastene75da402013-11-20 13:54:52 -08001489 lStatus = handle->initCheck();
1490 if (lStatus == OK) {
1491 lStatus = effect->addHandle(handle.get());
1492 }
Eric Laurent81784c32012-11-19 14:55:58 -08001493 if (enabled != NULL) {
1494 *enabled = (int)effect->isEnabled();
1495 }
1496 }
1497
1498Exit:
Eric Laurent2fe0acd2020-03-13 14:30:46 -07001499 if (!probe && lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurent81784c32012-11-19 14:55:58 -08001500 Mutex::Autolock _l(mLock);
1501 if (effectCreated) {
1502 chain->removeEffect_l(effect);
1503 }
Eric Laurent81784c32012-11-19 14:55:58 -08001504 if (chainCreated) {
1505 removeEffectChain_l(chain);
1506 }
haobo101735295ff7b0d2017-03-17 17:44:03 +08001507 // handle must be cleared by caller to avoid deadlock.
Eric Laurent81784c32012-11-19 14:55:58 -08001508 }
1509
Glenn Kasten9156ef32013-08-06 15:39:08 -07001510 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001511 return handle;
1512}
1513
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001514void AudioFlinger::ThreadBase::disconnectEffectHandle(EffectHandle *handle,
1515 bool unpinIfLast)
1516{
1517 bool remove = false;
1518 sp<EffectModule> effect;
1519 {
1520 Mutex::Autolock _l(mLock);
Eric Laurent41709552019-12-16 19:34:05 -08001521 sp<EffectBase> effectBase = handle->effect().promote();
1522 if (effectBase == nullptr) {
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001523 return;
1524 }
Eric Laurentb82e6b72019-11-22 17:25:04 -08001525 effect = effectBase->asEffectModule();
1526 if (effect == nullptr) {
1527 return;
1528 }
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001529 // restore suspended effects if the disconnected handle was enabled and the last one.
1530 remove = (effect->removeHandle(handle) == 0) && (!effect->isPinned() || unpinIfLast);
1531 if (remove) {
1532 removeEffect_l(effect, true);
1533 }
1534 }
1535 if (remove) {
1536 mAudioFlinger->updateOrphanEffectChains(effect);
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001537 if (handle->enabled()) {
Eric Laurent6b446ce2019-12-13 10:56:31 -08001538 effect->checkSuspendOnEffectEnabled(false, false /*threadLocked*/);
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001539 }
1540 }
1541}
1542
Eric Laurent6b446ce2019-12-13 10:56:31 -08001543void AudioFlinger::ThreadBase::onEffectEnable(const sp<EffectModule>& effect) {
Andy Hungea840382020-05-05 21:50:17 -07001544 if (isOffloadOrMmap()) {
Eric Laurent6b446ce2019-12-13 10:56:31 -08001545 Mutex::Autolock _l(mLock);
1546 broadcast_l();
1547 }
1548 if (!effect->isOffloadable()) {
1549 if (mType == ThreadBase::OFFLOAD) {
1550 PlaybackThread *t = (PlaybackThread *)this;
1551 t->invalidateTracks(AUDIO_STREAM_MUSIC);
1552 }
1553 if (effect->sessionId() == AUDIO_SESSION_OUTPUT_MIX) {
1554 mAudioFlinger->onNonOffloadableGlobalEffectEnable();
1555 }
1556 }
1557}
1558
1559void AudioFlinger::ThreadBase::onEffectDisable() {
Andy Hungea840382020-05-05 21:50:17 -07001560 if (isOffloadOrMmap()) {
Eric Laurent6b446ce2019-12-13 10:56:31 -08001561 Mutex::Autolock _l(mLock);
1562 broadcast_l();
1563 }
1564}
1565
Glenn Kastend848eb42016-03-08 13:42:11 -08001566sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(audio_session_t sessionId,
1567 int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08001568{
1569 Mutex::Autolock _l(mLock);
1570 return getEffect_l(sessionId, effectId);
1571}
1572
Glenn Kastend848eb42016-03-08 13:42:11 -08001573sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(audio_session_t sessionId,
1574 int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08001575{
1576 sp<EffectChain> chain = getEffectChain_l(sessionId);
1577 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
1578}
1579
Eric Laurent6c796322019-04-09 14:13:17 -07001580std::vector<int> AudioFlinger::ThreadBase::getEffectIds_l(audio_session_t sessionId)
1581{
1582 sp<EffectChain> chain = getEffectChain_l(sessionId);
1583 return chain != nullptr ? chain->getEffectIds() : std::vector<int>{};
1584}
1585
Eric Laurent81784c32012-11-19 14:55:58 -08001586// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
1587// PlaybackThread::mLock held
1588status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
1589{
1590 // check for existing effect chain with the requested audio session
Glenn Kastend848eb42016-03-08 13:42:11 -08001591 audio_session_t sessionId = effect->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08001592 sp<EffectChain> chain = getEffectChain_l(sessionId);
1593 bool chainCreated = false;
1594
Eric Laurent5baf2af2013-09-12 17:37:00 -07001595 ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(),
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001596 "addEffect_l() on offloaded thread %p: effect %s does not support offload flags %#x",
Eric Laurent5baf2af2013-09-12 17:37:00 -07001597 this, effect->desc().name, effect->desc().flags);
1598
Eric Laurent81784c32012-11-19 14:55:58 -08001599 if (chain == 0) {
1600 // create a new chain for this session
1601 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
1602 chain = new EffectChain(this, sessionId);
1603 addEffectChain_l(chain);
1604 chain->setStrategy(getStrategyForSession_l(sessionId));
1605 chainCreated = true;
1606 }
1607 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
1608
1609 if (chain->getEffectFromId_l(effect->id()) != 0) {
1610 ALOGW("addEffect_l() %p effect %s already present in chain %p",
1611 this, effect->desc().name, chain.get());
1612 return BAD_VALUE;
1613 }
1614
Eric Laurent5baf2af2013-09-12 17:37:00 -07001615 effect->setOffloaded(mType == OFFLOAD, mId);
1616
Eric Laurent81784c32012-11-19 14:55:58 -08001617 status_t status = chain->addEffect_l(effect);
1618 if (status != NO_ERROR) {
1619 if (chainCreated) {
1620 removeEffectChain_l(chain);
1621 }
1622 return status;
1623 }
1624
jiabin8f278ee2019-11-11 12:16:27 -08001625 effect->setDevices(outDeviceTypeAddrs());
1626 effect->setInputDevice(inDeviceTypeAddr());
Eric Laurent81784c32012-11-19 14:55:58 -08001627 effect->setMode(mAudioFlinger->getMode());
1628 effect->setAudioSource(mAudioSource);
Eric Laurentd8365c52017-07-16 15:27:05 -07001629
Eric Laurent81784c32012-11-19 14:55:58 -08001630 return NO_ERROR;
1631}
1632
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001633void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect, bool release) {
Eric Laurent81784c32012-11-19 14:55:58 -08001634
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001635 ALOGV("%s %p effect %p", __FUNCTION__, this, effect.get());
Eric Laurent81784c32012-11-19 14:55:58 -08001636 effect_descriptor_t desc = effect->desc();
1637 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
1638 detachAuxEffect_l(effect->id());
1639 }
1640
Eric Laurent6b446ce2019-12-13 10:56:31 -08001641 sp<EffectChain> chain = effect->callback()->chain().promote();
Eric Laurent81784c32012-11-19 14:55:58 -08001642 if (chain != 0) {
1643 // remove effect chain if removing last effect
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001644 if (chain->removeEffect_l(effect, release) == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08001645 removeEffectChain_l(chain);
1646 }
1647 } else {
1648 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
1649 }
1650}
1651
1652void AudioFlinger::ThreadBase::lockEffectChains_l(
1653 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1654{
1655 effectChains = mEffectChains;
1656 for (size_t i = 0; i < mEffectChains.size(); i++) {
1657 mEffectChains[i]->lock();
1658 }
1659}
1660
1661void AudioFlinger::ThreadBase::unlockEffectChains(
1662 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1663{
1664 for (size_t i = 0; i < effectChains.size(); i++) {
1665 effectChains[i]->unlock();
1666 }
1667}
1668
Glenn Kastend848eb42016-03-08 13:42:11 -08001669sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001670{
1671 Mutex::Autolock _l(mLock);
1672 return getEffectChain_l(sessionId);
1673}
1674
Glenn Kastend848eb42016-03-08 13:42:11 -08001675sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(audio_session_t sessionId)
1676 const
Eric Laurent81784c32012-11-19 14:55:58 -08001677{
1678 size_t size = mEffectChains.size();
1679 for (size_t i = 0; i < size; i++) {
1680 if (mEffectChains[i]->sessionId() == sessionId) {
1681 return mEffectChains[i];
1682 }
1683 }
1684 return 0;
1685}
1686
1687void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
1688{
1689 Mutex::Autolock _l(mLock);
1690 size_t size = mEffectChains.size();
1691 for (size_t i = 0; i < size; i++) {
1692 mEffectChains[i]->setMode_l(mode);
1693 }
1694}
1695
Mikhail Naganovdc769682018-05-04 15:34:08 -07001696void AudioFlinger::ThreadBase::toAudioPortConfig(struct audio_port_config *config)
Eric Laurent83b88082014-06-20 18:31:16 -07001697{
1698 config->type = AUDIO_PORT_TYPE_MIX;
1699 config->ext.mix.handle = mId;
1700 config->sample_rate = mSampleRate;
1701 config->format = mFormat;
1702 config->channel_mask = mChannelMask;
1703 config->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
1704 AUDIO_PORT_CONFIG_FORMAT;
1705}
1706
Eric Laurent72e3f392015-05-20 14:43:50 -07001707void AudioFlinger::ThreadBase::systemReady()
1708{
1709 Mutex::Autolock _l(mLock);
1710 if (mSystemReady) {
1711 return;
1712 }
1713 mSystemReady = true;
1714
1715 for (size_t i = 0; i < mPendingConfigEvents.size(); i++) {
1716 sendConfigEvent_l(mPendingConfigEvents.editItemAt(i));
1717 }
1718 mPendingConfigEvents.clear();
1719}
1720
Andy Hungdae27702016-10-31 14:01:16 -07001721template <typename T>
1722ssize_t AudioFlinger::ThreadBase::ActiveTracks<T>::add(const sp<T> &track) {
1723 ssize_t index = mActiveTracks.indexOf(track);
1724 if (index >= 0) {
1725 ALOGW("ActiveTracks<T>::add track %p already there", track.get());
1726 return index;
1727 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001728 logTrack("add", track);
Andy Hungdae27702016-10-31 14:01:16 -07001729 mActiveTracksGeneration++;
1730 mLatestActiveTrack = track;
1731 ++mBatteryCounter[track->uid()].second;
Kevin Rocard069c2712018-03-29 19:09:14 -07001732 mHasChanged = true;
Andy Hungdae27702016-10-31 14:01:16 -07001733 return mActiveTracks.add(track);
1734}
1735
1736template <typename T>
1737ssize_t AudioFlinger::ThreadBase::ActiveTracks<T>::remove(const sp<T> &track) {
1738 ssize_t index = mActiveTracks.remove(track);
1739 if (index < 0) {
1740 ALOGW("ActiveTracks<T>::remove nonexistent track %p", track.get());
1741 return index;
1742 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001743 logTrack("remove", track);
Andy Hungdae27702016-10-31 14:01:16 -07001744 mActiveTracksGeneration++;
1745 --mBatteryCounter[track->uid()].second;
1746 // mLatestActiveTrack is not cleared even if is the same as track.
Kevin Rocard069c2712018-03-29 19:09:14 -07001747 mHasChanged = true;
Andy Hung8946a282018-04-19 20:04:56 -07001748#ifdef TEE_SINK
1749 track->dumpTee(-1 /* fd */, "_REMOVE");
1750#endif
Andy Hungc2b11cb2020-04-22 09:04:01 -07001751 track->logEndInterval(); // log to MediaMetrics
Andy Hungdae27702016-10-31 14:01:16 -07001752 return index;
1753}
1754
1755template <typename T>
1756void AudioFlinger::ThreadBase::ActiveTracks<T>::clear() {
1757 for (const sp<T> &track : mActiveTracks) {
1758 BatteryNotifier::getInstance().noteStopAudio(track->uid());
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001759 logTrack("clear", track);
Andy Hungdae27702016-10-31 14:01:16 -07001760 }
1761 mLastActiveTracksGeneration = mActiveTracksGeneration;
Kevin Rocard069c2712018-03-29 19:09:14 -07001762 if (!mActiveTracks.empty()) { mHasChanged = true; }
Andy Hungdae27702016-10-31 14:01:16 -07001763 mActiveTracks.clear();
1764 mLatestActiveTrack.clear();
1765 mBatteryCounter.clear();
1766}
1767
1768template <typename T>
1769void AudioFlinger::ThreadBase::ActiveTracks<T>::updatePowerState(
1770 sp<ThreadBase> thread, bool force) {
1771 // Updates ActiveTracks client uids to the thread wakelock.
1772 if (mActiveTracksGeneration != mLastActiveTracksGeneration || force) {
1773 thread->updateWakeLockUids_l(getWakeLockUids());
1774 mLastActiveTracksGeneration = mActiveTracksGeneration;
1775 }
1776
1777 // Updates BatteryNotifier uids
1778 for (auto it = mBatteryCounter.begin(); it != mBatteryCounter.end();) {
1779 const uid_t uid = it->first;
1780 ssize_t &previous = it->second.first;
1781 ssize_t &current = it->second.second;
1782 if (current > 0) {
1783 if (previous == 0) {
1784 BatteryNotifier::getInstance().noteStartAudio(uid);
1785 }
1786 previous = current;
1787 ++it;
1788 } else if (current == 0) {
1789 if (previous > 0) {
1790 BatteryNotifier::getInstance().noteStopAudio(uid);
1791 }
1792 it = mBatteryCounter.erase(it); // std::map<> is stable on iterator erase.
1793 } else /* (current < 0) */ {
1794 LOG_ALWAYS_FATAL("negative battery count %zd", current);
1795 }
1796 }
1797}
Eric Laurent83b88082014-06-20 18:31:16 -07001798
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001799template <typename T>
Kevin Rocard069c2712018-03-29 19:09:14 -07001800bool AudioFlinger::ThreadBase::ActiveTracks<T>::readAndClearHasChanged() {
1801 const bool hasChanged = mHasChanged;
1802 mHasChanged = false;
1803 return hasChanged;
1804}
1805
1806template <typename T>
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001807void AudioFlinger::ThreadBase::ActiveTracks<T>::logTrack(
1808 const char *funcName, const sp<T> &track) const {
1809 if (mLocalLog != nullptr) {
1810 String8 result;
1811 track->appendDump(result, false /* active */);
1812 mLocalLog->log("AT::%-10s(%p) %s", funcName, track.get(), result.string());
1813 }
1814}
1815
Eric Laurent6acd1d42017-01-04 14:23:29 -08001816void AudioFlinger::ThreadBase::broadcast_l()
1817{
1818 // Thread could be blocked waiting for async
1819 // so signal it to handle state changes immediately
1820 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
1821 // be lost so we also flag to prevent it blocking on mWaitWorkCV
1822 mSignalPending = true;
1823 mWaitWorkCV.broadcast();
1824}
1825
Andy Hungd0979812019-02-21 15:51:44 -08001826// Call only from threadLoop() or when it is idle.
1827// Do not call from high performance code as this may do binder rpc to the MediaMetrics service.
1828void AudioFlinger::ThreadBase::sendStatistics(bool force)
1829{
1830 // Do not log if we have no stats.
1831 // We choose the timestamp verifier because it is the most likely item to be present.
1832 const int64_t nstats = mTimestampVerifier.getN() - mLastRecordedTimestampVerifierN;
1833 if (nstats == 0) {
1834 return;
1835 }
1836
1837 // Don't log more frequently than once per 12 hours.
1838 // We use BOOTTIME to include suspend time.
1839 const int64_t timeNs = systemTime(SYSTEM_TIME_BOOTTIME);
1840 const int64_t sinceNs = timeNs - mLastRecordedTimeNs; // ok if mLastRecordedTimeNs = 0
1841 if (!force && sinceNs <= 12 * NANOS_PER_HOUR) {
1842 return;
1843 }
1844
1845 mLastRecordedTimestampVerifierN = mTimestampVerifier.getN();
1846 mLastRecordedTimeNs = timeNs;
1847
Ray Essickf27e9872019-12-07 06:28:46 -08001848 std::unique_ptr<mediametrics::Item> item(mediametrics::Item::create("audiothread"));
Andy Hungd0979812019-02-21 15:51:44 -08001849
1850#define MM_PREFIX "android.media.audiothread." // avoid cut-n-paste errors.
1851
1852 // thread configuration
1853 item->setInt32(MM_PREFIX "id", (int32_t)mId); // IO handle
1854 // item->setInt32(MM_PREFIX "portId", (int32_t)mPortId);
1855 item->setCString(MM_PREFIX "type", threadTypeToString(mType));
1856 item->setInt32(MM_PREFIX "sampleRate", (int32_t)mSampleRate);
1857 item->setInt64(MM_PREFIX "channelMask", (int64_t)mChannelMask);
1858 item->setCString(MM_PREFIX "encoding", toString(mFormat).c_str());
1859 item->setInt32(MM_PREFIX "frameCount", (int32_t)mFrameCount);
jiabinc52b1ff2019-10-31 17:20:42 -07001860 item->setCString(MM_PREFIX "outDevice", toString(outDeviceTypes()).c_str());
1861 item->setCString(MM_PREFIX "inDevice", toString(inDeviceType()).c_str());
Andy Hungd0979812019-02-21 15:51:44 -08001862
1863 // thread statistics
1864 if (mIoJitterMs.getN() > 0) {
1865 item->setDouble(MM_PREFIX "ioJitterMs.mean", mIoJitterMs.getMean());
1866 item->setDouble(MM_PREFIX "ioJitterMs.std", mIoJitterMs.getStdDev());
1867 }
1868 if (mProcessTimeMs.getN() > 0) {
1869 item->setDouble(MM_PREFIX "processTimeMs.mean", mProcessTimeMs.getMean());
1870 item->setDouble(MM_PREFIX "processTimeMs.std", mProcessTimeMs.getStdDev());
1871 }
1872 const auto tsjitter = mTimestampVerifier.getJitterMs();
1873 if (tsjitter.getN() > 0) {
1874 item->setDouble(MM_PREFIX "timestampJitterMs.mean", tsjitter.getMean());
1875 item->setDouble(MM_PREFIX "timestampJitterMs.std", tsjitter.getStdDev());
1876 }
1877 if (mLatencyMs.getN() > 0) {
1878 item->setDouble(MM_PREFIX "latencyMs.mean", mLatencyMs.getMean());
1879 item->setDouble(MM_PREFIX "latencyMs.std", mLatencyMs.getStdDev());
1880 }
1881
1882 item->selfrecord();
1883}
1884
Eric Laurent81784c32012-11-19 14:55:58 -08001885// ----------------------------------------------------------------------------
1886// Playback
1887// ----------------------------------------------------------------------------
1888
1889AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1890 AudioStreamOut* output,
1891 audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -07001892 type_t type,
Eric Laurente93cc032016-05-05 10:15:10 -07001893 bool systemReady)
Andy Hungcf10d742020-04-28 15:38:24 -07001894 : ThreadBase(audioFlinger, id, type, systemReady, true /* isOut */),
Andy Hung2098f272014-02-27 14:00:06 -08001895 mNormalFrameCount(0), mSinkBuffer(NULL),
Andy Hung6146c082014-03-18 11:56:15 -07001896 mMixerBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung69aed5f2014-02-25 17:24:40 -08001897 mMixerBuffer(NULL),
1898 mMixerBufferSize(0),
1899 mMixerBufferFormat(AUDIO_FORMAT_INVALID),
1900 mMixerBufferValid(false),
Andy Hung6146c082014-03-18 11:56:15 -07001901 mEffectBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung98ef9782014-03-04 14:46:50 -08001902 mEffectBuffer(NULL),
1903 mEffectBufferSize(0),
1904 mEffectBufferFormat(AUDIO_FORMAT_INVALID),
1905 mEffectBufferValid(false),
Glenn Kastenc1fac192013-08-06 07:41:36 -07001906 mSuspended(0), mBytesWritten(0),
Andy Hungc54b1ff2016-02-23 14:07:07 -08001907 mFramesWritten(0),
Andy Hung238fa3d2016-07-28 10:53:22 -07001908 mSuspendedFrames(0),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001909 mActiveTracks(&this->mLocalLog),
Eric Laurent81784c32012-11-19 14:55:58 -08001910 // mStreamTypes[] initialized in constructor body
Andy Hung1bc088a2018-02-09 15:57:31 -08001911 mTracks(type == MIXER),
Eric Laurent81784c32012-11-19 14:55:58 -08001912 mOutput(output),
Andy Hung446f4df2019-02-21 12:26:41 -08001913 mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
Eric Laurent81784c32012-11-19 14:55:58 -08001914 mMixerStatus(MIXER_IDLE),
1915 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
Eric Laurentad9cb8b2015-05-26 16:38:19 -07001916 mStandbyDelayNs(AudioFlinger::mStandbyTimeInNsecs),
Eric Laurentbfb1b832013-01-07 09:53:42 -08001917 mBytesRemaining(0),
1918 mCurrentWriteLength(0),
1919 mUseAsyncWrite(false),
Eric Laurent3b4529e2013-09-05 18:09:19 -07001920 mWriteAckSequence(0),
1921 mDrainSequence(0),
Eric Laurent81784c32012-11-19 14:55:58 -08001922 mScreenState(AudioFlinger::mScreenState),
1923 // index 0 is reserved for normal mixer's submix
Glenn Kastendc2c50b2016-04-21 08:13:14 -07001924 mFastTrackAvailMask(((1 << FastMixerState::sMaxFastTracks) - 1) & ~1),
Eric Laurent7c29ec92017-09-20 17:54:22 -07001925 mHwSupportsPause(false), mHwPaused(false), mFlushPending(false),
Eric Laurent74c38dc2020-12-23 18:19:44 +01001926 mLeftVolFloat(-1.0), mRightVolFloat(-1.0),
1927 mDownStreamPatch{}
Eric Laurent81784c32012-11-19 14:55:58 -08001928{
Glenn Kastend7dca052015-03-05 16:05:54 -08001929 snprintf(mThreadName, kThreadNameLength, "AudioOut_%X", id);
1930 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08001931
1932 // Assumes constructor is called by AudioFlinger with it's mLock held, but
1933 // it would be safer to explicitly pass initial masterVolume/masterMute as
1934 // parameter.
1935 //
1936 // If the HAL we are using has support for master volume or master mute,
1937 // then do not attenuate or mute during mixing (just leave the volume at 1.0
1938 // and the mute set to false).
1939 mMasterVolume = audioFlinger->masterVolume_l();
1940 mMasterMute = audioFlinger->masterMute_l();
George Burgess IV5e4d86f2020-02-18 12:55:36 -08001941 if (mOutput->audioHwDev) {
Eric Laurent81784c32012-11-19 14:55:58 -08001942 if (mOutput->audioHwDev->canSetMasterVolume()) {
1943 mMasterVolume = 1.0;
1944 }
1945
1946 if (mOutput->audioHwDev->canSetMasterMute()) {
1947 mMasterMute = false;
1948 }
Andy Hungc8fddf32018-08-08 18:32:37 -07001949 mIsMsdDevice = strcmp(
1950 mOutput->audioHwDev->moduleName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0;
Eric Laurent81784c32012-11-19 14:55:58 -08001951 }
1952
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001953 readOutputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001954
Andy Hungc8fddf32018-08-08 18:32:37 -07001955 // TODO: We may also match on address as well as device type for
1956 // AUDIO_DEVICE_OUT_BUS, AUDIO_DEVICE_OUT_ALL_A2DP, AUDIO_DEVICE_OUT_REMOTE_SUBMIX
Dean Wheatleyf8726f02019-12-02 14:12:01 +11001957 if (type == MIXER || type == DIRECT || type == OFFLOAD) {
jiabinc52b1ff2019-10-31 17:20:42 -07001958 // TODO: This property should be ensure that only contains one single device type.
1959 mTimestampCorrectedDevice = (audio_devices_t)property_get_int64(
1960 "audio.timestamp.corrected_output_device",
Andy Hungc8fddf32018-08-08 18:32:37 -07001961 (int64_t)(mIsMsdDevice ? AUDIO_DEVICE_OUT_BUS // turn on by default for MSD
1962 : AUDIO_DEVICE_NONE));
1963 }
1964
Mikhail Naganovf33115d2020-09-25 23:03:05 +00001965 for (int i = AUDIO_STREAM_MIN; i < AUDIO_STREAM_FOR_POLICY_CNT; ++i) {
1966 const audio_stream_type_t stream{static_cast<audio_stream_type_t>(i)};
Eric Laurent98e38192018-02-15 18:31:53 -08001967 mStreamTypes[stream].volume = 0.0f;
Eric Laurent81784c32012-11-19 14:55:58 -08001968 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
1969 }
Eric Laurent35f8c7c2020-02-08 11:42:35 -08001970 // Audio patch and call assistant volume are always max
Eric Laurent98e38192018-02-15 18:31:53 -08001971 mStreamTypes[AUDIO_STREAM_PATCH].volume = 1.0f;
1972 mStreamTypes[AUDIO_STREAM_PATCH].mute = false;
Eric Laurent35f8c7c2020-02-08 11:42:35 -08001973 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].volume = 1.0f;
1974 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].mute = false;
Eric Laurent81784c32012-11-19 14:55:58 -08001975}
1976
1977AudioFlinger::PlaybackThread::~PlaybackThread()
1978{
Glenn Kasten9e58b552013-01-18 15:09:48 -08001979 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung010a1a12014-03-13 13:57:33 -07001980 free(mSinkBuffer);
Andy Hung69aed5f2014-02-25 17:24:40 -08001981 free(mMixerBuffer);
Andy Hung98ef9782014-03-04 14:46:50 -08001982 free(mEffectBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08001983}
1984
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001985// Thread virtuals
1986
1987void AudioFlinger::PlaybackThread::onFirstRef()
Eric Laurent81784c32012-11-19 14:55:58 -08001988{
jiabinf6eb4c32020-02-25 14:06:25 -08001989 if (mOutput == nullptr || mOutput->stream == nullptr) {
1990 ALOGE("The stream is not open yet"); // This should not happen.
1991 } else {
1992 // setEventCallback will need a strong pointer as a parameter. Calling it
1993 // here instead of constructor of PlaybackThread so that the onFirstRef
1994 // callback would not be made on an incompletely constructed object.
1995 if (mOutput->stream->setEventCallback(this) != OK) {
jiabinf1a36052020-08-19 14:33:31 -07001996 ALOGD("Failed to add event callback");
jiabinf6eb4c32020-02-25 14:06:25 -08001997 }
1998 }
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001999 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08002000}
2001
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002002// ThreadBase virtuals
2003void AudioFlinger::PlaybackThread::preExit()
2004{
2005 ALOGV(" preExit()");
2006 // FIXME this is using hard-coded strings but in the future, this functionality will be
2007 // converted to use audio HAL extensions required to support tunneling
2008 status_t result = mOutput->stream->setParameters(String8("exiting=1"));
2009 ALOGE_IF(result != OK, "Error when setting parameters on exit: %d", result);
2010}
2011
2012void AudioFlinger::PlaybackThread::dumpTracks_l(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08002013{
Eric Laurent81784c32012-11-19 14:55:58 -08002014 String8 result;
2015
Marco Nelissenb2208842014-02-07 14:00:50 -08002016 result.appendFormat(" Stream volumes in dB: ");
Eric Laurent81784c32012-11-19 14:55:58 -08002017 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
2018 const stream_type_t *st = &mStreamTypes[i];
2019 if (i > 0) {
2020 result.appendFormat(", ");
2021 }
2022 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
2023 if (st->mute) {
2024 result.append("M");
2025 }
2026 }
2027 result.append("\n");
2028 write(fd, result.string(), result.length());
2029 result.clear();
2030
Eric Laurent81784c32012-11-19 14:55:58 -08002031 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
2032 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
Elliott Hughes87cebad2014-05-22 10:14:43 -07002033 dprintf(fd, " Normal mixer raw underrun counters: partial=%u empty=%u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08002034 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Marco Nelissenb2208842014-02-07 14:00:50 -08002035
2036 size_t numtracks = mTracks.size();
2037 size_t numactive = mActiveTracks.size();
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002038 dprintf(fd, " %zu Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08002039 size_t numactiveseen = 0;
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002040 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08002041 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002042 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002043 result.append(prefix);
Andy Hungf6ab58d2018-05-25 12:50:39 -07002044 mTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08002045 for (size_t i = 0; i < numtracks; ++i) {
2046 sp<Track> track = mTracks[i];
2047 if (track != 0) {
2048 bool active = mActiveTracks.indexOf(track) >= 0;
2049 if (active) {
2050 numactiveseen++;
2051 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002052 result.append(prefix);
2053 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08002054 }
2055 }
2056 } else {
2057 result.append("\n");
2058 }
2059 if (numactiveseen != numactive) {
2060 // some tracks in the active list were not in the tracks list
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002061 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08002062 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002063 result.append(prefix);
Andy Hungf6ab58d2018-05-25 12:50:39 -07002064 mActiveTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08002065 for (size_t i = 0; i < numactive; ++i) {
Andy Hungdae27702016-10-31 14:01:16 -07002066 sp<Track> track = mActiveTracks[i];
2067 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002068 result.append(prefix);
2069 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08002070 }
2071 }
2072 }
2073
2074 write(fd, result.string(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08002075}
2076
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002077void AudioFlinger::PlaybackThread::dumpInternals_l(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08002078{
Andy Hung04cb8f72020-03-20 13:44:33 -07002079 dprintf(fd, " Master volume: %f\n", mMasterVolume);
Mikhail Naganovdfb411f2018-09-11 13:39:56 -07002080 dprintf(fd, " Master mute: %s\n", mMasterMute ? "on" : "off");
jiabin245cdd92018-12-07 17:55:15 -08002081 if (mHapticChannelMask != AUDIO_CHANNEL_NONE) {
2082 dprintf(fd, " Haptic channel mask: %#x (%s)\n", mHapticChannelMask,
2083 channelMaskToString(mHapticChannelMask, true /* output */).c_str());
2084 }
Elliott Hughes87cebad2014-05-22 10:14:43 -07002085 dprintf(fd, " Normal frame count: %zu\n", mNormalFrameCount);
Elliott Hughes87cebad2014-05-22 10:14:43 -07002086 dprintf(fd, " Total writes: %d\n", mNumWrites);
2087 dprintf(fd, " Delayed writes: %d\n", mNumDelayedWrites);
2088 dprintf(fd, " Blocked in write: %s\n", mInWrite ? "yes" : "no");
2089 dprintf(fd, " Suspend count: %d\n", mSuspended);
2090 dprintf(fd, " Sink buffer : %p\n", mSinkBuffer);
2091 dprintf(fd, " Mixer buffer: %p\n", mMixerBuffer);
2092 dprintf(fd, " Effect buffer: %p\n", mEffectBuffer);
2093 dprintf(fd, " Fast track availMask=%#x\n", mFastTrackAvailMask);
Eric Laurent42537be2016-01-08 17:16:42 -08002094 dprintf(fd, " Standby delay ns=%lld\n", (long long)mStandbyDelayNs);
Glenn Kasten97b7b752014-09-28 13:04:24 -07002095 AudioStreamOut *output = mOutput;
2096 audio_output_flags_t flags = output != NULL ? output->flags : AUDIO_OUTPUT_FLAG_NONE;
Mikhail Naganov913d06c2016-11-01 12:49:22 -07002097 dprintf(fd, " AudioStreamOut: %p flags %#x (%s)\n",
Andy Hung9b181952019-02-25 14:53:36 -08002098 output, flags, toString(flags).c_str());
Andy Hungb54c8542016-09-21 12:55:15 -07002099 dprintf(fd, " Frames written: %lld\n", (long long)mFramesWritten);
2100 dprintf(fd, " Suspended frames: %lld\n", (long long)mSuspendedFrames);
2101 if (mPipeSink.get() != nullptr) {
2102 dprintf(fd, " PipeSink frames written: %lld\n", (long long)mPipeSink->framesWritten());
2103 }
2104 if (output != nullptr) {
2105 dprintf(fd, " Hal stream dump:\n");
2106 (void)output->stream->dump(fd);
2107 }
Eric Laurent81784c32012-11-19 14:55:58 -08002108}
2109
Eric Laurent81784c32012-11-19 14:55:58 -08002110// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
2111sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
2112 const sp<AudioFlinger::Client>& client,
2113 audio_stream_type_t streamType,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07002114 const audio_attributes_t& attr,
Eric Laurent21da6472017-11-09 16:29:26 -08002115 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08002116 audio_format_t format,
2117 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08002118 size_t *pFrameCount,
Eric Laurent21da6472017-11-09 16:29:26 -08002119 size_t *pNotificationFrameCount,
2120 uint32_t notificationsPerBuffer,
2121 float speed,
Eric Laurent81784c32012-11-19 14:55:58 -08002122 const sp<IMemory>& sharedBuffer,
Glenn Kastend848eb42016-03-08 13:42:11 -08002123 audio_session_t sessionId,
Eric Laurent05067782016-06-01 18:27:28 -07002124 audio_output_flags_t *flags,
Eric Laurent09f1ed22019-04-24 17:45:17 -07002125 pid_t creatorPid,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07002126 const Identity& identity,
Eric Laurent81784c32012-11-19 14:55:58 -08002127 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002128 status_t *status,
jiabinf6eb4c32020-02-25 14:06:25 -08002129 audio_port_handle_t portId,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07002130 const sp<media::IAudioTrackCallback>& callback)
Eric Laurent81784c32012-11-19 14:55:58 -08002131{
Glenn Kasten74935e42013-12-19 08:56:45 -08002132 size_t frameCount = *pFrameCount;
Eric Laurent21da6472017-11-09 16:29:26 -08002133 size_t notificationFrameCount = *pNotificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08002134 sp<Track> track;
2135 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07002136 audio_output_flags_t outputFlags = mOutput->flags;
Eric Laurent21da6472017-11-09 16:29:26 -08002137 audio_output_flags_t requestedFlags = *flags;
Eric Laurent9b11c022018-06-06 19:19:22 -07002138 uint32_t sampleRate;
2139
2140 if (sharedBuffer != 0 && checkIMemory(sharedBuffer) != NO_ERROR) {
2141 lStatus = BAD_VALUE;
2142 goto Exit;
2143 }
Eric Laurent21da6472017-11-09 16:29:26 -08002144
2145 if (*pSampleRate == 0) {
2146 *pSampleRate = mSampleRate;
2147 }
Eric Laurent9b11c022018-06-06 19:19:22 -07002148 sampleRate = *pSampleRate;
Eric Laurent05067782016-06-01 18:27:28 -07002149
2150 // special case for FAST flag considered OK if fast mixer is present
2151 if (hasFastMixer()) {
2152 outputFlags = (audio_output_flags_t)(outputFlags | AUDIO_OUTPUT_FLAG_FAST);
2153 }
2154
2155 // Check if requested flags are compatible with output stream flags
2156 if ((*flags & outputFlags) != *flags) {
2157 ALOGW("createTrack_l(): mismatch between requested flags (%08x) and output flags (%08x)",
2158 *flags, outputFlags);
2159 *flags = (audio_output_flags_t)(*flags & outputFlags);
2160 }
Eric Laurent81784c32012-11-19 14:55:58 -08002161
Eric Laurent81784c32012-11-19 14:55:58 -08002162 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07002163 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
Eric Laurent81784c32012-11-19 14:55:58 -08002164 if (
Eric Laurent81784c32012-11-19 14:55:58 -08002165 // PCM data
2166 audio_is_linear_pcm(format) &&
Andy Hung1f439e12015-05-19 12:57:41 -07002167 // TODO: extract as a data library function that checks that a computationally
2168 // expensive downmixer is not required: isFastOutputChannelConversion()
jiabin245cdd92018-12-07 17:55:15 -08002169 (channelMask == (mChannelMask | mHapticChannelMask) ||
Andy Hung1f439e12015-05-19 12:57:41 -07002170 mChannelMask != AUDIO_CHANNEL_OUT_STEREO ||
2171 (channelMask == AUDIO_CHANNEL_OUT_MONO
2172 /* && mChannelMask == AUDIO_CHANNEL_OUT_STEREO */)) &&
Eric Laurent81784c32012-11-19 14:55:58 -08002173 // hardware sample rate
2174 (sampleRate == mSampleRate) &&
Eric Laurent81784c32012-11-19 14:55:58 -08002175 // normal mixer has an associated fast mixer
2176 hasFastMixer() &&
2177 // there are sufficient fast track slots available
2178 (mFastTrackAvailMask != 0)
2179 // FIXME test that MixerThread for this fast track has a capable output HAL
2180 // FIXME add a permission test also?
2181 ) {
Andy Hunge0a269a2016-03-23 15:13:42 -07002182 // static tracks can have any nonzero framecount, streaming tracks check against minimum.
2183 if (sharedBuffer == 0) {
Glenn Kasten03490092014-05-27 12:30:54 -07002184 // read the fast track multiplier property the first time it is needed
2185 int ok = pthread_once(&sFastTrackMultiplierOnce, sFastTrackMultiplierInit);
2186 if (ok != 0) {
2187 ALOGE("%s pthread_once failed: %d", __func__, ok);
2188 }
Andy Hunge0a269a2016-03-23 15:13:42 -07002189 frameCount = max(frameCount, mFrameCount * sFastTrackMultiplier); // incl framecount 0
Eric Laurent81784c32012-11-19 14:55:58 -08002190 }
Eric Laurent4c415062016-06-17 16:14:16 -07002191
2192 // check compatibility with audio effects.
2193 { // scope for mLock
2194 Mutex::Autolock _l(mLock);
Andy Hungd3bb0ad2016-10-11 17:16:43 -07002195 for (audio_session_t session : {
Eric Laurent3f75a5b2019-11-12 15:55:51 -08002196 AUDIO_SESSION_DEVICE,
Andy Hungd3bb0ad2016-10-11 17:16:43 -07002197 AUDIO_SESSION_OUTPUT_STAGE,
2198 AUDIO_SESSION_OUTPUT_MIX,
2199 sessionId,
2200 }) {
2201 sp<EffectChain> chain = getEffectChain_l(session);
2202 if (chain.get() != nullptr) {
2203 audio_output_flags_t old = *flags;
2204 chain->checkOutputFlagCompatibility(flags);
2205 if (old != *flags) {
2206 ALOGV("AUDIO_OUTPUT_FLAGS denied by effect, session=%d old=%#x new=%#x",
2207 (int)session, (int)old, (int)*flags);
2208 }
Eric Laurent4c415062016-06-17 16:14:16 -07002209 }
2210 }
2211 }
Eric Laurent122f7e72016-06-29 11:53:29 -07002212 ALOGV_IF((*flags & AUDIO_OUTPUT_FLAG_FAST) != 0,
Eric Laurent4c415062016-06-17 16:14:16 -07002213 "AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
2214 frameCount, mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08002215 } else {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002216 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: sharedBuffer=%p frameCount=%zu "
2217 "mFrameCount=%zu format=%#x mFormat=%#x isLinear=%d channelMask=%#x "
Andy Hung6146c082014-03-18 11:56:15 -07002218 "sampleRate=%u mSampleRate=%u "
Eric Laurent81784c32012-11-19 14:55:58 -08002219 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
Glenn Kastend79072e2016-01-06 08:41:20 -08002220 sharedBuffer.get(), frameCount, mFrameCount, format, mFormat,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07002221 audio_is_linear_pcm(format), channelMask, sampleRate,
2222 mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
Eric Laurent4c415062016-06-17 16:14:16 -07002223 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_FAST);
Andy Hung0e48d252015-01-26 11:43:15 -08002224 }
2225 }
Eric Laurent21da6472017-11-09 16:29:26 -08002226
2227 if (!audio_has_proportional_frames(format)) {
2228 if (sharedBuffer != 0) {
2229 // Same comment as below about ignoring frameCount parameter for set()
2230 frameCount = sharedBuffer->size();
2231 } else if (frameCount == 0) {
2232 frameCount = mNormalFrameCount;
2233 }
2234 if (notificationFrameCount != frameCount) {
2235 notificationFrameCount = frameCount;
2236 }
2237 } else if (sharedBuffer != 0) {
2238 // FIXME: Ensure client side memory buffers need
2239 // not have additional alignment beyond sample
2240 // (e.g. 16 bit stereo accessed as 32 bit frame).
2241 size_t alignment = audio_bytes_per_sample(format);
2242 if (alignment & 1) {
2243 // for AUDIO_FORMAT_PCM_24_BIT_PACKED (not exposed through Java).
2244 alignment = 1;
2245 }
2246 uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
2247 size_t frameSize = channelCount * audio_bytes_per_sample(format);
2248 if (channelCount > 1) {
2249 // More than 2 channels does not require stronger alignment than stereo
2250 alignment <<= 1;
2251 }
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07002252 if (((uintptr_t)sharedBuffer->unsecurePointer() & (alignment - 1)) != 0) {
Eric Laurent21da6472017-11-09 16:29:26 -08002253 ALOGE("Invalid buffer alignment: address %p, channel count %u",
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07002254 sharedBuffer->unsecurePointer(), channelCount);
Eric Laurent21da6472017-11-09 16:29:26 -08002255 lStatus = BAD_VALUE;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002256 goto Exit;
2257 }
Eric Laurent21da6472017-11-09 16:29:26 -08002258
2259 // When initializing a shared buffer AudioTrack via constructors,
2260 // there's no frameCount parameter.
2261 // But when initializing a shared buffer AudioTrack via set(),
2262 // there _is_ a frameCount parameter. We silently ignore it.
2263 frameCount = sharedBuffer->size() / frameSize;
2264 } else {
2265 size_t minFrameCount = 0;
2266 // For fast tracks we try to respect the application's request for notifications per buffer.
2267 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
2268 if (notificationsPerBuffer > 0) {
2269 // Avoid possible arithmetic overflow during multiplication.
2270 if (notificationsPerBuffer > SIZE_MAX / mFrameCount) {
2271 ALOGE("Requested notificationPerBuffer=%u ignored for HAL frameCount=%zu",
2272 notificationsPerBuffer, mFrameCount);
2273 } else {
2274 minFrameCount = mFrameCount * notificationsPerBuffer;
2275 }
2276 }
2277 } else {
2278 // For normal PCM streaming tracks, update minimum frame count.
2279 // Buffer depth is forced to be at least 2 x the normal mixer frame count and
2280 // cover audio hardware latency.
2281 // This is probably too conservative, but legacy application code may depend on it.
2282 // If you change this calculation, also review the start threshold which is related.
2283 uint32_t latencyMs = latency_l();
2284 if (latencyMs == 0) {
2285 ALOGE("Error when retrieving output stream latency");
2286 lStatus = UNKNOWN_ERROR;
2287 goto Exit;
2288 }
2289
2290 minFrameCount = AudioSystem::calculateMinFrameCount(latencyMs, mNormalFrameCount,
2291 mSampleRate, sampleRate, speed /*, 0 mNotificationsPerBufferReq*/);
2292
Eric Laurent81784c32012-11-19 14:55:58 -08002293 }
Eric Laurent21da6472017-11-09 16:29:26 -08002294 if (frameCount < minFrameCount) {
Eric Laurent81784c32012-11-19 14:55:58 -08002295 frameCount = minFrameCount;
2296 }
Eric Laurent81784c32012-11-19 14:55:58 -08002297 }
Eric Laurent21da6472017-11-09 16:29:26 -08002298
2299 // Make sure that application is notified with sufficient margin before underrun.
2300 // The client can divide the AudioTrack buffer into sub-buffers,
2301 // and expresses its desire to server as the notification frame count.
2302 if (sharedBuffer == 0 && audio_is_linear_pcm(format)) {
2303 size_t maxNotificationFrames;
2304 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
2305 // notify every HAL buffer, regardless of the size of the track buffer
2306 maxNotificationFrames = mFrameCount;
2307 } else {
Andy Hungfa117802019-04-12 13:50:39 -07002308 // Triple buffer the notification period for a triple buffered mixer period;
2309 // otherwise, double buffering for the notification period is fine.
2310 //
2311 // TODO: This should be moved to AudioTrack to modify the notification period
2312 // on AudioTrack::setBufferSizeInFrames() changes.
2313 const int nBuffering =
2314 (uint64_t{frameCount} * mSampleRate)
2315 / (uint64_t{mNormalFrameCount} * sampleRate) == 3 ? 3 : 2;
2316
Eric Laurent21da6472017-11-09 16:29:26 -08002317 maxNotificationFrames = frameCount / nBuffering;
2318 // If client requested a fast track but this was denied, then use the smaller maximum.
2319 if (requestedFlags & AUDIO_OUTPUT_FLAG_FAST) {
2320 size_t maxNotificationFramesFastDenied = FMS_20 * sampleRate / 1000;
2321 if (maxNotificationFrames > maxNotificationFramesFastDenied) {
2322 maxNotificationFrames = maxNotificationFramesFastDenied;
2323 }
2324 }
2325 }
2326 if (notificationFrameCount == 0 || notificationFrameCount > maxNotificationFrames) {
2327 if (notificationFrameCount == 0) {
2328 ALOGD("Client defaulted notificationFrames to %zu for frameCount %zu",
2329 maxNotificationFrames, frameCount);
2330 } else {
2331 ALOGW("Client adjusted notificationFrames from %zu to %zu for frameCount %zu",
2332 notificationFrameCount, maxNotificationFrames, frameCount);
2333 }
2334 notificationFrameCount = maxNotificationFrames;
2335 }
2336 }
2337
Glenn Kasten74935e42013-12-19 08:56:45 -08002338 *pFrameCount = frameCount;
Eric Laurent21da6472017-11-09 16:29:26 -08002339 *pNotificationFrameCount = notificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08002340
Glenn Kastenc3df8382014-03-13 15:05:25 -07002341 switch (mType) {
2342
2343 case DIRECT:
Phil Burkfdb3c072016-02-09 10:47:02 -08002344 if (audio_is_linear_pcm(format)) { // TODO maybe use audio_has_proportional_frames()?
Eric Laurent81784c32012-11-19 14:55:58 -08002345 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002346 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
2347 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08002348 sampleRate, format, channelMask, mOutput, mFormat);
2349 lStatus = BAD_VALUE;
2350 goto Exit;
2351 }
2352 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002353 break;
2354
2355 case OFFLOAD:
Eric Laurentbfb1b832013-01-07 09:53:42 -08002356 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002357 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
2358 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002359 sampleRate, format, channelMask, mOutput, mFormat);
2360 lStatus = BAD_VALUE;
2361 goto Exit;
2362 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002363 break;
2364
2365 default:
Glenn Kasten993fa062014-05-02 11:14:34 -07002366 if (!audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002367 ALOGE("createTrack_l() Bad parameter: format %#x \""
2368 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002369 format, mOutput, mFormat);
2370 lStatus = BAD_VALUE;
2371 goto Exit;
2372 }
Andy Hungcd044842014-08-07 11:04:34 -07002373 if (sampleRate > mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Eric Laurent81784c32012-11-19 14:55:58 -08002374 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
2375 lStatus = BAD_VALUE;
2376 goto Exit;
2377 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002378 break;
2379
Eric Laurent81784c32012-11-19 14:55:58 -08002380 }
2381
2382 lStatus = initCheck();
2383 if (lStatus != NO_ERROR) {
Glenn Kasten15e57982013-09-24 11:52:37 -07002384 ALOGE("createTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08002385 goto Exit;
2386 }
2387
2388 { // scope for mLock
2389 Mutex::Autolock _l(mLock);
2390
2391 // all tracks in same audio session must share the same routing strategy otherwise
2392 // conflicts will happen when tracks are moved from one output to another by audio policy
2393 // manager
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08002394 product_strategy_t strategy = AudioSystem::getStrategyForStream(streamType);
Eric Laurent81784c32012-11-19 14:55:58 -08002395 for (size_t i = 0; i < mTracks.size(); ++i) {
2396 sp<Track> t = mTracks[i];
Eric Laurent83b88082014-06-20 18:31:16 -07002397 if (t != 0 && t->isExternalTrack()) {
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08002398 product_strategy_t actual = AudioSystem::getStrategyForStream(t->streamType());
Eric Laurent81784c32012-11-19 14:55:58 -08002399 if (sessionId == t->sessionId() && strategy != actual) {
2400 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
2401 strategy, actual);
2402 lStatus = BAD_VALUE;
2403 goto Exit;
2404 }
2405 }
2406 }
2407
yucliuc9c49cd2020-07-13 16:25:21 -07002408 // Set DIRECT flag if current thread is DirectOutputThread. This can
2409 // happen when the playback is rerouted to direct output thread by
2410 // dynamic audio policy.
2411 // Do NOT report the flag changes back to client, since the client
2412 // doesn't explicitly request a direct flag.
2413 audio_output_flags_t trackFlags = *flags;
2414 if (mType == DIRECT) {
2415 trackFlags = static_cast<audio_output_flags_t>(trackFlags | AUDIO_OUTPUT_FLAG_DIRECT);
2416 }
2417
Kevin Rocard1f564ac2018-03-29 13:53:10 -07002418 track = new Track(this, client, streamType, attr, sampleRate, format,
Andy Hung8fe68032017-06-05 16:17:51 -07002419 channelMask, frameCount,
2420 nullptr /* buffer */, (size_t)0 /* bufferSize */, sharedBuffer,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07002421 sessionId, creatorPid, identity, trackFlags, TrackBase::TYPE_DEFAULT,
2422 portId, SIZE_MAX /*frameCountToBeReady*/);
Glenn Kasten03003332013-08-06 15:40:54 -07002423
Glenn Kasten03003332013-08-06 15:40:54 -07002424 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
2425 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08002426 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08002427 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08002428 goto Exit;
2429 }
2430 mTracks.add(track);
jiabinf6eb4c32020-02-25 14:06:25 -08002431 {
2432 Mutex::Autolock _atCbL(mAudioTrackCbLock);
2433 if (callback.get() != nullptr) {
jiabin18a4b1c2020-09-17 11:40:42 -07002434 mAudioTrackCallbacks.emplace(track, callback);
jiabinf6eb4c32020-02-25 14:06:25 -08002435 }
2436 }
Eric Laurent81784c32012-11-19 14:55:58 -08002437
2438 sp<EffectChain> chain = getEffectChain_l(sessionId);
2439 if (chain != 0) {
2440 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
2441 track->setMainBuffer(chain->inBuffer());
2442 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
2443 chain->incTrackCnt();
2444 }
2445
Eric Laurent05067782016-06-01 18:27:28 -07002446 if ((*flags & AUDIO_OUTPUT_FLAG_FAST) && (tid != -1)) {
Eric Laurent81784c32012-11-19 14:55:58 -08002447 pid_t callingPid = IPCThreadState::self()->getCallingPid();
2448 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
2449 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07002450 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08002451 }
2452 }
2453
2454 lStatus = NO_ERROR;
2455
2456Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07002457 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08002458 return track;
2459}
2460
Andy Hung1bc088a2018-02-09 15:57:31 -08002461template<typename T>
Andy Hung1bc088a2018-02-09 15:57:31 -08002462ssize_t AudioFlinger::PlaybackThread::Tracks<T>::remove(const sp<T> &track)
2463{
Andy Hungc0691382018-09-12 18:01:57 -07002464 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08002465 const ssize_t index = mTracks.remove(track);
2466 if (index >= 0) {
Andy Hungc0691382018-09-12 18:01:57 -07002467 if (mSaveDeletedTrackIds) {
Andy Hung1bc088a2018-02-09 15:57:31 -08002468 // We can't directly access mAudioMixer since the caller may be outside of threadLoop.
Andy Hungc0691382018-09-12 18:01:57 -07002469 // Instead, we add to mDeletedTrackIds which is solely used for mAudioMixer update,
Andy Hung1bc088a2018-02-09 15:57:31 -08002470 // to be handled when MixerThread::prepareTracks_l() next changes mAudioMixer.
Andy Hungc0691382018-09-12 18:01:57 -07002471 mDeletedTrackIds.emplace(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08002472 }
Andy Hung1bc088a2018-02-09 15:57:31 -08002473 }
2474 return index;
2475}
2476
Eric Laurent81784c32012-11-19 14:55:58 -08002477uint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const
2478{
2479 return latency;
2480}
2481
2482uint32_t AudioFlinger::PlaybackThread::latency() const
2483{
2484 Mutex::Autolock _l(mLock);
2485 return latency_l();
2486}
2487uint32_t AudioFlinger::PlaybackThread::latency_l() const
2488{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002489 uint32_t latency;
2490 if (initCheck() == NO_ERROR && mOutput->stream->getLatency(&latency) == OK) {
2491 return correctLatency_l(latency);
Eric Laurent81784c32012-11-19 14:55:58 -08002492 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002493 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002494}
2495
2496void AudioFlinger::PlaybackThread::setMasterVolume(float value)
2497{
2498 Mutex::Autolock _l(mLock);
2499 // Don't apply master volume in SW if our HAL can do it for us.
2500 if (mOutput && mOutput->audioHwDev &&
2501 mOutput->audioHwDev->canSetMasterVolume()) {
2502 mMasterVolume = 1.0;
2503 } else {
2504 mMasterVolume = value;
2505 }
2506}
2507
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01002508void AudioFlinger::PlaybackThread::setMasterBalance(float balance)
2509{
2510 mMasterBalance.store(balance);
2511}
2512
Eric Laurent81784c32012-11-19 14:55:58 -08002513void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
2514{
Eric Laurent6acd1d42017-01-04 14:23:29 -08002515 if (isDuplicating()) {
2516 return;
2517 }
Eric Laurent81784c32012-11-19 14:55:58 -08002518 Mutex::Autolock _l(mLock);
2519 // Don't apply master mute in SW if our HAL can do it for us.
2520 if (mOutput && mOutput->audioHwDev &&
2521 mOutput->audioHwDev->canSetMasterMute()) {
2522 mMasterMute = false;
2523 } else {
2524 mMasterMute = muted;
2525 }
2526}
2527
2528void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
2529{
2530 Mutex::Autolock _l(mLock);
2531 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002532 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002533}
2534
2535void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
2536{
2537 Mutex::Autolock _l(mLock);
2538 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002539 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002540}
2541
2542float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
2543{
2544 Mutex::Autolock _l(mLock);
2545 return mStreamTypes[stream].volume;
2546}
2547
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09002548void AudioFlinger::PlaybackThread::setVolumeForOutput_l(float left, float right) const
2549{
2550 mOutput->stream->setVolume(left, right);
2551}
2552
Eric Laurent81784c32012-11-19 14:55:58 -08002553// addTrack_l() must be called with ThreadBase::mLock held
2554status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
2555{
2556 status_t status = ALREADY_EXISTS;
2557
Eric Laurent81784c32012-11-19 14:55:58 -08002558 if (mActiveTracks.indexOf(track) < 0) {
2559 // the track is newly added, make sure it fills up all its
2560 // buffers before playing. This is to ensure the client will
2561 // effectively get the latency it requested.
Eric Laurent83b88082014-06-20 18:31:16 -07002562 if (track->isExternalTrack()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002563 TrackBase::track_state state = track->mState;
2564 mLock.unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002565 status = AudioSystem::startOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002566 mLock.lock();
2567 // abort track was stopped/paused while we released the lock
2568 if (state != track->mState) {
2569 if (status == NO_ERROR) {
2570 mLock.unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002571 AudioSystem::stopOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002572 mLock.lock();
2573 }
2574 return INVALID_OPERATION;
2575 }
2576 // abort if start is rejected by audio policy manager
2577 if (status != NO_ERROR) {
2578 return PERMISSION_DENIED;
2579 }
2580#ifdef ADD_BATTERY_DATA
2581 // to track the speaker usage
2582 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
2583#endif
Eric Laurent09f1ed22019-04-24 17:45:17 -07002584 sendIoConfigEvent_l(AUDIO_CLIENT_STARTED, track->creatorPid(), track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002585 }
2586
Eric Laurent51716182016-02-29 18:00:56 -08002587 // set retry count for buffer fill
2588 if (track->isOffloaded()) {
Eric Laurente93cc032016-05-05 10:15:10 -07002589 if (track->isStopping_1()) {
2590 track->mRetryCount = kMaxTrackStopRetriesOffload;
2591 } else {
2592 track->mRetryCount = kMaxTrackStartupRetriesOffload;
2593 }
2594 track->mFillingUpStatus = mStandby ? Track::FS_FILLING : Track::FS_FILLED;
Eric Laurent51716182016-02-29 18:00:56 -08002595 } else {
2596 track->mRetryCount = kMaxTrackStartupRetries;
Eric Laurente93cc032016-05-05 10:15:10 -07002597 track->mFillingUpStatus =
2598 track->sharedBuffer() != 0 ? Track::FS_FILLED : Track::FS_FILLING;
Eric Laurent51716182016-02-29 18:00:56 -08002599 }
2600
jiabineb3bda02020-06-30 14:07:03 -07002601 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2602 if (mHapticChannelMask != AUDIO_CHANNEL_NONE
2603 && ((track->channelMask() & AUDIO_CHANNEL_HAPTIC_ALL) != AUDIO_CHANNEL_NONE
2604 || (chain != nullptr && chain->containsHapticGeneratingEffect_l()))) {
jiabin57303cc2018-12-18 15:45:57 -08002605 // Unlock due to VibratorService will lock for this call and will
2606 // call Tracks.mute/unmute which also require thread's lock.
2607 mLock.unlock();
2608 const int intensity = AudioFlinger::onExternalVibrationStart(
2609 track->getExternalVibration());
2610 mLock.lock();
jiabine70bc7f2020-06-30 22:07:55 -07002611 track->setHapticIntensity(static_cast<os::HapticScale>(intensity));
jiabin57303cc2018-12-18 15:45:57 -08002612 // Haptic playback should be enabled by vibrator service.
2613 if (track->getHapticPlaybackEnabled()) {
2614 // Disable haptic playback of all active track to ensure only
2615 // one track playing haptic if current track should play haptic.
2616 for (const auto &t : mActiveTracks) {
2617 t->setHapticPlaybackEnabled(false);
2618 }
jiabin245cdd92018-12-07 17:55:15 -08002619 }
jiabine70bc7f2020-06-30 22:07:55 -07002620
2621 // Set haptic intensity for effect
2622 if (chain != nullptr) {
2623 chain->setHapticIntensity_l(track->id(), intensity);
2624 }
jiabin245cdd92018-12-07 17:55:15 -08002625 }
2626
Eric Laurent81784c32012-11-19 14:55:58 -08002627 track->mResetDone = false;
2628 track->mPresentationCompleteFrames = 0;
2629 mActiveTracks.add(track);
Eric Laurentd0107bc2013-06-11 14:38:48 -07002630 if (chain != 0) {
2631 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
2632 track->sessionId());
2633 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08002634 }
2635
Andy Hungc2b11cb2020-04-22 09:04:01 -07002636 track->logBeginInterval(patchSinksToString(&mPatch)); // log to MediaMetrics
Eric Laurent81784c32012-11-19 14:55:58 -08002637 status = NO_ERROR;
2638 }
2639
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08002640 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002641 return status;
2642}
2643
Eric Laurentbfb1b832013-01-07 09:53:42 -08002644bool AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002645{
Eric Laurentbfb1b832013-01-07 09:53:42 -08002646 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08002647 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002648 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
2649 track->mState = TrackBase::STOPPED;
2650 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08002651 removeTrack_l(track);
Eric Laurentab5cdba2014-06-09 17:22:27 -07002652 } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002653 track->mState = TrackBase::STOPPING_1;
Eric Laurent81784c32012-11-19 14:55:58 -08002654 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002655
2656 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08002657}
2658
2659void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
2660{
2661 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Andy Hung2148bf02016-11-28 19:01:02 -08002662
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002663 String8 result;
2664 track->appendDump(result, false /* active */);
2665 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.string());
Andy Hung2148bf02016-11-28 19:01:02 -08002666
Eric Laurent81784c32012-11-19 14:55:58 -08002667 mTracks.remove(track);
jiabin18a4b1c2020-09-17 11:40:42 -07002668 {
2669 Mutex::Autolock _atCbL(mAudioTrackCbLock);
2670 mAudioTrackCallbacks.erase(track);
2671 }
Eric Laurent81784c32012-11-19 14:55:58 -08002672 if (track->isFastTrack()) {
2673 int index = track->mFastIndex;
Glenn Kastendc2c50b2016-04-21 08:13:14 -07002674 ALOG_ASSERT(0 < index && index < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08002675 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
2676 mFastTrackAvailMask |= 1 << index;
2677 // redundant as track is about to be destroyed, for dumpsys only
2678 track->mFastIndex = -1;
2679 }
2680 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2681 if (chain != 0) {
2682 chain->decTrackCnt();
2683 }
2684}
2685
2686String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
2687{
Eric Laurent81784c32012-11-19 14:55:58 -08002688 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002689 String8 out_s8;
2690 if (initCheck() == NO_ERROR && mOutput->stream->getParameters(keys, &out_s8) == OK) {
2691 return out_s8;
Eric Laurent81784c32012-11-19 14:55:58 -08002692 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002693 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08002694}
2695
Mikhail Naganovac917ac2018-11-28 14:03:52 -08002696status_t AudioFlinger::DirectOutputThread::selectPresentation(int presentationId, int programId) {
2697 Mutex::Autolock _l(mLock);
2698 if (mOutput == nullptr || mOutput->stream == nullptr) {
2699 return NO_INIT;
2700 }
2701 return mOutput->stream->selectPresentation(presentationId, programId);
2702}
2703
Eric Laurent09f1ed22019-04-24 17:45:17 -07002704void AudioFlinger::PlaybackThread::ioConfigChanged(audio_io_config_event event, pid_t pid,
2705 audio_port_handle_t portId) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002706 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
2707 ALOGV("PlaybackThread::ioConfigChanged, thread %p, event %d", this, event);
Eric Laurent81784c32012-11-19 14:55:58 -08002708
Eric Laurent73e26b62015-04-27 16:55:58 -07002709 desc->mIoHandle = mId;
Eric Laurent74c38dc2020-12-23 18:19:44 +01002710 struct audio_patch patch = mPatch;
2711 if (isMsdDevice()) {
2712 patch = mDownStreamPatch;
2713 }
Eric Laurent81784c32012-11-19 14:55:58 -08002714
2715 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002716 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07002717 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07002718 case AUDIO_OUTPUT_CONFIG_CHANGED:
Eric Laurent74c38dc2020-12-23 18:19:44 +01002719 desc->mPatch = patch;
Eric Laurent73e26b62015-04-27 16:55:58 -07002720 desc->mChannelMask = mChannelMask;
2721 desc->mSamplingRate = mSampleRate;
2722 desc->mFormat = mFormat;
2723 desc->mFrameCount = mNormalFrameCount; // FIXME see
Eric Laurent81784c32012-11-19 14:55:58 -08002724 // AudioFlinger::frameCount(audio_io_handle_t)
Glenn Kasten4a8308b2016-04-18 14:10:01 -07002725 desc->mFrameCountHAL = mFrameCount;
Eric Laurent73e26b62015-04-27 16:55:58 -07002726 desc->mLatency = latency_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002727 break;
Eric Laurent09f1ed22019-04-24 17:45:17 -07002728 case AUDIO_CLIENT_STARTED:
Eric Laurent74c38dc2020-12-23 18:19:44 +01002729 desc->mPatch = patch;
Eric Laurent09f1ed22019-04-24 17:45:17 -07002730 desc->mPortId = portId;
2731 break;
Eric Laurent73e26b62015-04-27 16:55:58 -07002732 case AUDIO_OUTPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08002733 default:
2734 break;
2735 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002736 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08002737}
2738
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002739void AudioFlinger::PlaybackThread::onWriteReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002740{
Eric Laurent3b4529e2013-09-05 18:09:19 -07002741 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002742}
2743
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002744void AudioFlinger::PlaybackThread::onDrainReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002745{
Eric Laurent3b4529e2013-09-05 18:09:19 -07002746 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002747}
2748
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002749void AudioFlinger::PlaybackThread::onError()
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002750{
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002751 mCallbackThread->setAsyncError();
2752}
2753
jiabinf6eb4c32020-02-25 14:06:25 -08002754void AudioFlinger::PlaybackThread::onCodecFormatChanged(
2755 const std::basic_string<uint8_t>& metadataBs)
2756{
2757 std::thread([this, metadataBs]() {
2758 audio_utils::metadata::Data metadata =
2759 audio_utils::metadata::dataFromByteString(metadataBs);
2760 if (metadata.empty()) {
2761 ALOGW("Can not transform the buffer to audio metadata, %s, %d",
2762 reinterpret_cast<char*>(const_cast<uint8_t*>(metadataBs.data())),
2763 (int)metadataBs.size());
2764 return;
2765 }
2766
2767 audio_utils::metadata::ByteString metaDataStr =
2768 audio_utils::metadata::byteStringFromData(metadata);
2769 std::vector metadataVec(metaDataStr.begin(), metaDataStr.end());
2770 Mutex::Autolock _l(mAudioTrackCbLock);
jiabin18a4b1c2020-09-17 11:40:42 -07002771 for (const auto& callbackPair : mAudioTrackCallbacks) {
2772 callbackPair.second->onCodecFormatChanged(metadataVec);
jiabinf6eb4c32020-02-25 14:06:25 -08002773 }
2774 }).detach();
2775}
2776
Eric Laurent3b4529e2013-09-05 18:09:19 -07002777void AudioFlinger::PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002778{
2779 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002780 // reject out of sequence requests
2781 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
2782 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002783 mWaitWorkCV.signal();
2784 }
2785}
2786
Eric Laurent3b4529e2013-09-05 18:09:19 -07002787void AudioFlinger::PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002788{
2789 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002790 // reject out of sequence requests
2791 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
Andy Hungf3234512018-07-03 14:51:47 -07002792 // Register discontinuity when HW drain is completed because that can cause
2793 // the timestamp frame position to reset to 0 for direct and offload threads.
2794 // (Out of sequence requests are ignored, since the discontinuity would be handled
2795 // elsewhere, e.g. in flush).
Dean Wheatley12473e92021-03-18 23:00:55 +11002796 mTimestampVerifier.discontinuity(mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002797 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002798 mWaitWorkCV.signal();
2799 }
2800}
2801
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002802void AudioFlinger::PlaybackThread::readOutputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08002803{
Glenn Kastenadad3d72014-02-21 14:51:43 -08002804 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Mikhail Naganov560637e2021-03-31 22:40:13 +00002805 const audio_config_base_t audioConfig = mOutput->getAudioProperties();
2806 mSampleRate = audioConfig.sample_rate;
2807 mChannelMask = audioConfig.channel_mask;
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002808 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002809 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002810 }
Andy Hung9a592762014-07-21 21:56:01 -07002811 if ((mType == MIXER || mType == DUPLICATING)
2812 && !isValidPcmSinkChannelMask(mChannelMask)) {
2813 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output",
2814 mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002815 }
Andy Hunge5412692014-05-16 11:25:07 -07002816 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01002817 mBalance.setChannelMask(mChannelMask);
Phil Burkca5e6142015-07-14 09:42:29 -07002818
2819 // Get actual HAL format.
Mikhail Naganov560637e2021-03-31 22:40:13 +00002820 status_t result = mOutput->stream->getAudioProperties(nullptr, nullptr, &mHALFormat);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002821 LOG_ALWAYS_FATAL_IF(result != OK, "Error when retrieving output stream format: %d", result);
Phil Burkca5e6142015-07-14 09:42:29 -07002822 // Get format from the shim, which will be different than the HAL format
2823 // if playing compressed audio over HDMI passthrough.
Mikhail Naganov560637e2021-03-31 22:40:13 +00002824 mFormat = audioConfig.format;
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002825 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002826 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002827 }
Andy Hung6146c082014-03-18 11:56:15 -07002828 if ((mType == MIXER || mType == DUPLICATING)
2829 && !isValidPcmSinkFormat(mFormat)) {
2830 LOG_FATAL("HAL format %#x not supported for mixed output",
2831 mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002832 }
Phil Burk062e67a2015-02-11 13:40:50 -08002833 mFrameSize = mOutput->getFrameSize();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002834 result = mOutput->stream->getBufferSize(&mBufferSize);
2835 LOG_ALWAYS_FATAL_IF(result != OK,
2836 "Error when retrieving output stream buffer size: %d", result);
Glenn Kasten70949c42013-08-06 07:40:12 -07002837 mFrameCount = mBufferSize / mFrameSize;
Dean Wheatley77cbebd2019-04-23 14:18:44 +10002838 if ((mType == MIXER || mType == DUPLICATING) && (mFrameCount & 15)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002839 ALOGW("HAL output buffer size is %zu frames but AudioMixer requires multiples of 16 frames",
Eric Laurent81784c32012-11-19 14:55:58 -08002840 mFrameCount);
2841 }
2842
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002843 if (mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING) {
2844 if (mOutput->stream->setCallback(this) == OK) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002845 mUseAsyncWrite = true;
Eric Laurent4de95592013-09-26 15:28:21 -07002846 mCallbackThread = new AudioFlinger::AsyncCallbackThread(this);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002847 }
2848 }
2849
Eric Laurentd1f69b02014-12-15 14:33:13 -08002850 mHwSupportsPause = false;
2851 if (mOutput->flags & AUDIO_OUTPUT_FLAG_DIRECT) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002852 bool supportsPause = false, supportsResume = false;
2853 if (mOutput->stream->supportsPauseAndResume(&supportsPause, &supportsResume) == OK) {
2854 if (supportsPause && supportsResume) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08002855 mHwSupportsPause = true;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002856 } else if (supportsPause) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08002857 ALOGW("direct output implements pause but not resume");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002858 } else if (supportsResume) {
2859 ALOGW("direct output implements resume but not pause");
Eric Laurentd1f69b02014-12-15 14:33:13 -08002860 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002861 }
2862 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07002863 if (!mHwSupportsPause && mOutput->flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) {
2864 LOG_ALWAYS_FATAL("HW_AV_SYNC requested but HAL does not implement pause and resume");
2865 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002866
Andy Hungfbfc3952015-01-15 13:33:51 -08002867 if (mType == DUPLICATING && mMixerBufferEnabled && mEffectBufferEnabled) {
2868 // For best precision, we use float instead of the associated output
2869 // device format (typically PCM 16 bit).
2870
2871 mFormat = AUDIO_FORMAT_PCM_FLOAT;
2872 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
2873 mBufferSize = mFrameSize * mFrameCount;
2874
2875 // TODO: We currently use the associated output device channel mask and sample rate.
2876 // (1) Perhaps use the ORed channel mask of all downstream MixerThreads
2877 // (if a valid mask) to avoid premature downmix.
2878 // (2) Perhaps use the maximum sample rate of all downstream MixerThreads
2879 // instead of the output device sample rate to avoid loss of high frequency information.
2880 // This may need to be updated as MixerThread/OutputTracks are added and not here.
2881 }
2882
Andy Hung09a50072014-02-27 14:30:47 -08002883 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08002884 double multiplier = 1.0;
2885 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
2886 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08002887 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
2888 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Haynes Mathew George227a14b2016-05-09 12:45:48 -07002889
Eric Laurent81784c32012-11-19 14:55:58 -08002890 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
2891 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
2892 maxNormalFrameCount = maxNormalFrameCount & ~15;
2893 if (maxNormalFrameCount < minNormalFrameCount) {
2894 maxNormalFrameCount = minNormalFrameCount;
2895 }
2896 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
2897 if (multiplier <= 1.0) {
2898 multiplier = 1.0;
2899 } else if (multiplier <= 2.0) {
2900 if (2 * mFrameCount <= maxNormalFrameCount) {
2901 multiplier = 2.0;
2902 } else {
2903 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
2904 }
2905 } else {
Haynes Mathew George227a14b2016-05-09 12:45:48 -07002906 multiplier = floor(multiplier);
Eric Laurent81784c32012-11-19 14:55:58 -08002907 }
2908 }
2909 mNormalFrameCount = multiplier * mFrameCount;
2910 // round up to nearest 16 frames to satisfy AudioMixer
Eric Laurentab5cdba2014-06-09 17:22:27 -07002911 if (mType == MIXER || mType == DUPLICATING) {
2912 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
2913 }
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002914 ALOGI("HAL output buffer size %zu frames, normal sink buffer size %zu frames", mFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08002915 mNormalFrameCount);
2916
Andy Hung08fb1742015-05-31 23:22:10 -07002917 // Check if we want to throttle the processing to no more than 2x normal rate
2918 mThreadThrottle = property_get_bool("af.thread.throttle", true /* default_value */);
Andy Hung40eb1a12015-06-18 13:42:02 -07002919 mThreadThrottleTimeMs = 0;
2920 mThreadThrottleEndMs = 0;
Andy Hung08fb1742015-05-31 23:22:10 -07002921 mHalfBufferMs = mNormalFrameCount * 1000 / (2 * mSampleRate);
2922
Andy Hung010a1a12014-03-13 13:57:33 -07002923 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
2924 // Originally this was int16_t[] array, need to remove legacy implications.
2925 free(mSinkBuffer);
2926 mSinkBuffer = NULL;
Andy Hung5b10a202014-03-13 13:59:29 -07002927 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
2928 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
2929 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07002930 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08002931
Andy Hung69aed5f2014-02-25 17:24:40 -08002932 // We resize the mMixerBuffer according to the requirements of the sink buffer which
2933 // drives the output.
2934 free(mMixerBuffer);
2935 mMixerBuffer = NULL;
2936 if (mMixerBufferEnabled) {
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01002937 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // no longer valid: AUDIO_FORMAT_PCM_16_BIT.
Andy Hung69aed5f2014-02-25 17:24:40 -08002938 mMixerBufferSize = mNormalFrameCount * mChannelCount
2939 * audio_bytes_per_sample(mMixerBufferFormat);
2940 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
2941 }
Andy Hung98ef9782014-03-04 14:46:50 -08002942 free(mEffectBuffer);
2943 mEffectBuffer = NULL;
2944 if (mEffectBufferEnabled) {
rago94a1ee82017-07-21 15:11:02 -07002945 mEffectBufferFormat = EFFECT_BUFFER_FORMAT;
Andy Hung98ef9782014-03-04 14:46:50 -08002946 mEffectBufferSize = mNormalFrameCount * mChannelCount
2947 * audio_bytes_per_sample(mEffectBufferFormat);
2948 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
2949 }
Andy Hung69aed5f2014-02-25 17:24:40 -08002950
Mikhail Naganov55773032020-10-01 15:08:13 -07002951 mHapticChannelMask = static_cast<audio_channel_mask_t>(mChannelMask & AUDIO_CHANNEL_HAPTIC_ALL);
2952 mChannelMask = static_cast<audio_channel_mask_t>(mChannelMask & ~mHapticChannelMask);
jiabin245cdd92018-12-07 17:55:15 -08002953 mHapticChannelCount = audio_channel_count_from_out_mask(mHapticChannelMask);
2954 mChannelCount -= mHapticChannelCount;
2955
Eric Laurent81784c32012-11-19 14:55:58 -08002956 // force reconfiguration of effect chains and engines to take new buffer size and audio
2957 // parameters into account
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002958 // Note that mLock is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08002959 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
2960 // matter.
2961 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
2962 Vector< sp<EffectChain> > effectChains = mEffectChains;
2963 for (size_t i = 0; i < effectChains.size(); i ++) {
Eric Laurent6c796322019-04-09 14:13:17 -07002964 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(),
2965 this/* srcThread */, this/* dstThread */);
Eric Laurent81784c32012-11-19 14:55:58 -08002966 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08002967
George Burgess IV5e4d86f2020-02-18 12:55:36 -08002968 audio_output_flags_t flags = mOutput->flags;
Andy Hungcf10d742020-04-28 15:38:24 -07002969 mediametrics::LogItem item(mThreadMetrics.getMetricsId()); // TODO: method in ThreadMetrics?
Andy Hungb68f5eb2019-12-03 16:49:17 -08002970 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
2971 .set(AMEDIAMETRICS_PROP_ENCODING, formatToString(mFormat).c_str())
2972 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
2973 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
2974 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
2975 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mNormalFrameCount)
2976 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
2977 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELMASK,
2978 (int32_t)mHapticChannelMask)
2979 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELCOUNT,
2980 (int32_t)mHapticChannelCount)
2981 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_ENCODING,
2982 formatToString(mHALFormat).c_str())
2983 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_FRAMECOUNT,
2984 (int32_t)mFrameCount) // sic - added HAL
2985 ;
2986 uint32_t latencyMs;
2987 if (mOutput->stream->getLatency(&latencyMs) == NO_ERROR) {
2988 item.set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_LATENCYMS, (double)latencyMs);
2989 }
2990 item.record();
Eric Laurent81784c32012-11-19 14:55:58 -08002991}
2992
Kevin Rocard069c2712018-03-29 19:09:14 -07002993void AudioFlinger::PlaybackThread::updateMetadata_l()
2994{
Kevin Rocard12381092018-04-11 09:19:59 -07002995 if (mOutput == nullptr || mOutput->stream == nullptr ) {
2996 return; // That should not happen
2997 }
2998 bool hasChanged = mActiveTracks.readAndClearHasChanged();
2999 for (const sp<Track> &track : mActiveTracks) {
3000 // Do not short-circuit as all hasChanged states must be reset
3001 // as all the metadata are going to be sent
3002 hasChanged |= track->readAndClearHasChanged();
3003 }
3004 if (!hasChanged) {
3005 return; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -07003006 }
3007 StreamOutHalInterface::SourceMetadata metadata;
Kevin Rocard12381092018-04-11 09:19:59 -07003008 auto backInserter = std::back_inserter(metadata.tracks);
Kevin Rocard069c2712018-03-29 19:09:14 -07003009 for (const sp<Track> &track : mActiveTracks) {
3010 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurentb9cc0ab2021-01-29 11:46:52 +01003011 // Do not forward metadata for PatchTrack with unspecified stream type
3012 if (track->streamType() != AUDIO_STREAM_PATCH) {
3013 track->copyMetadataTo(backInserter);
3014 }
Kevin Rocard069c2712018-03-29 19:09:14 -07003015 }
Kevin Rocard12381092018-04-11 09:19:59 -07003016 sendMetadataToBackend_l(metadata);
Kevin Rocard80ee2722018-04-11 15:53:48 +00003017}
Kevin Rocardc86a7f72018-04-03 09:00:09 -07003018
Kevin Rocard12381092018-04-11 09:19:59 -07003019void AudioFlinger::PlaybackThread::sendMetadataToBackend_l(
3020 const StreamOutHalInterface::SourceMetadata& metadata)
3021{
3022 mOutput->stream->updateSourceMetadata(metadata);
3023};
3024
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003025status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
Eric Laurent81784c32012-11-19 14:55:58 -08003026{
3027 if (halFrames == NULL || dspFrames == NULL) {
3028 return BAD_VALUE;
3029 }
3030 Mutex::Autolock _l(mLock);
3031 if (initCheck() != NO_ERROR) {
3032 return INVALID_OPERATION;
3033 }
Andy Hung818e7a32016-02-16 18:08:07 -08003034 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08003035 *halFrames = framesWritten;
3036
3037 if (isSuspended()) {
3038 // return an estimation of rendered frames when the output is suspended
3039 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08003040 *dspFrames = (uint32_t)
3041 (framesWritten >= (int64_t)latencyFrames ? framesWritten - latencyFrames : 0);
Eric Laurent81784c32012-11-19 14:55:58 -08003042 return NO_ERROR;
3043 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003044 status_t status;
3045 uint32_t frames;
Phil Burk062e67a2015-02-11 13:40:50 -08003046 status = mOutput->getRenderPosition(&frames);
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003047 *dspFrames = (size_t)frames;
3048 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08003049 }
3050}
3051
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08003052product_strategy_t AudioFlinger::PlaybackThread::getStrategyForSession_l(audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08003053{
3054 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
3055 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
3056 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
3057 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
3058 }
3059 for (size_t i = 0; i < mTracks.size(); i++) {
3060 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08003061 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003062 return AudioSystem::getStrategyForStream(track->streamType());
3063 }
3064 }
3065 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
3066}
3067
3068
Phil Burk062e67a2015-02-11 13:40:50 -08003069AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurent81784c32012-11-19 14:55:58 -08003070{
3071 Mutex::Autolock _l(mLock);
3072 return mOutput;
3073}
3074
Phil Burk062e67a2015-02-11 13:40:50 -08003075AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
Eric Laurent81784c32012-11-19 14:55:58 -08003076{
3077 Mutex::Autolock _l(mLock);
3078 AudioStreamOut *output = mOutput;
3079 mOutput = NULL;
3080 // FIXME FastMixer might also have a raw ptr to mOutputSink;
3081 // must push a NULL and wait for ack
3082 mOutputSink.clear();
3083 mPipeSink.clear();
3084 mNormalSink.clear();
3085 return output;
3086}
3087
3088// this method must always be called either with ThreadBase mLock held or inside the thread loop
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003089sp<StreamHalInterface> AudioFlinger::PlaybackThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08003090{
3091 if (mOutput == NULL) {
3092 return NULL;
3093 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003094 return mOutput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08003095}
3096
3097uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
3098{
3099 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
3100}
3101
3102status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
3103{
3104 if (!isValidSyncEvent(event)) {
3105 return BAD_VALUE;
3106 }
3107
3108 Mutex::Autolock _l(mLock);
3109
3110 for (size_t i = 0; i < mTracks.size(); ++i) {
3111 sp<Track> track = mTracks[i];
3112 if (event->triggerSession() == track->sessionId()) {
3113 (void) track->setSyncEvent(event);
3114 return NO_ERROR;
3115 }
3116 }
3117
3118 return NAME_NOT_FOUND;
3119}
3120
3121bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
3122{
3123 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
3124}
3125
3126void AudioFlinger::PlaybackThread::threadLoop_removeTracks(
3127 const Vector< sp<Track> >& tracksToRemove)
3128{
Andy Hungfe726a62018-09-27 15:17:25 -07003129 // Miscellaneous track cleanup when removed from the active list,
3130 // called without Thread lock but synchronized with threadLoop processing.
Eric Laurentbfb1b832013-01-07 09:53:42 -08003131#ifdef ADD_BATTERY_DATA
Andy Hungfe726a62018-09-27 15:17:25 -07003132 for (const auto& track : tracksToRemove) {
3133 if (track->isExternalTrack()) {
3134 // to track the speaker usage
3135 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Eric Laurent81784c32012-11-19 14:55:58 -08003136 }
3137 }
Andy Hungfe726a62018-09-27 15:17:25 -07003138#else
3139 (void)tracksToRemove; // suppress unused warning
3140#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003141}
3142
3143void AudioFlinger::PlaybackThread::checkSilentMode_l()
3144{
3145 if (!mMasterMute) {
3146 char value[PROPERTY_VALUE_MAX];
jiabin0a957d32020-04-29 10:56:20 -07003147 if (mOutDeviceTypeAddrs.empty()) {
3148 ALOGD("ro.audio.silent is ignored since no output device is set");
3149 return;
3150 }
jiabinc52b1ff2019-10-31 17:20:42 -07003151 if (isSingleDeviceType(outDeviceTypes(), AUDIO_DEVICE_OUT_REMOTE_SUBMIX)) {
Jean-Michel Trivi32f37c22016-03-31 16:00:32 -07003152 ALOGD("ro.audio.silent will be ignored for threads on AUDIO_DEVICE_OUT_REMOTE_SUBMIX");
3153 return;
3154 }
Eric Laurent81784c32012-11-19 14:55:58 -08003155 if (property_get("ro.audio.silent", value, "0") > 0) {
3156 char *endptr;
3157 unsigned long ul = strtoul(value, &endptr, 0);
3158 if (*endptr == '\0' && ul != 0) {
3159 ALOGD("Silence is golden");
3160 // The setprop command will not allow a property to be changed after
3161 // the first time it is set, so we don't have to worry about un-muting.
3162 setMasterMute_l(true);
3163 }
3164 }
3165 }
3166}
3167
3168// shared by MIXER and DIRECT, overridden by DUPLICATING
Eric Laurentbfb1b832013-01-07 09:53:42 -08003169ssize_t AudioFlinger::PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08003170{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07003171 LOG_HIST_TS();
Eric Laurent81784c32012-11-19 14:55:58 -08003172 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003173 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07003174 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08003175
3176 // If an NBAIO sink is present, use it to write the normal mixer's submix
3177 if (mNormalSink != 0) {
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003178
Andy Hung010a1a12014-03-13 13:57:33 -07003179 const size_t count = mBytesRemaining / mFrameSize;
3180
Simon Wilson2d590962012-11-29 15:18:50 -08003181 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08003182 // update the setpoint when AudioFlinger::mScreenState changes
3183 uint32_t screenState = AudioFlinger::mScreenState;
3184 if (screenState != mScreenState) {
3185 mScreenState = screenState;
3186 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
3187 if (pipe != NULL) {
3188 pipe->setAvgFrames((mScreenState & 1) ?
3189 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
3190 }
3191 }
Andy Hung010a1a12014-03-13 13:57:33 -07003192 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08003193 ATRACE_END();
Eric Laurent81784c32012-11-19 14:55:58 -08003194 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07003195 bytesWritten = framesWritten * mFrameSize;
Andy Hung8946a282018-04-19 20:04:56 -07003196#ifdef TEE_SINK
3197 mTee.write((char *)mSinkBuffer + offset, framesWritten);
3198#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003199 } else {
3200 bytesWritten = framesWritten;
3201 }
3202 // otherwise use the HAL / AudioStreamOut directly
3203 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003204 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07003205
Eric Laurentbfb1b832013-01-07 09:53:42 -08003206 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003207 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
3208 mWriteAckSequence += 2;
3209 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003210 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003211 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003212 }
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07003213 ATRACE_BEGIN("write");
Glenn Kasten767094d2013-08-23 13:51:43 -07003214 // FIXME We should have an implementation of timestamps for direct output threads.
3215 // They are used e.g for multichannel PCM playback over HDMI.
Phil Burk062e67a2015-02-11 13:40:50 -08003216 bytesWritten = mOutput->write((char *)mSinkBuffer + offset, mBytesRemaining);
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07003217 ATRACE_END();
Eric Laurent51716182016-02-29 18:00:56 -08003218
Eric Laurentbfb1b832013-01-07 09:53:42 -08003219 if (mUseAsyncWrite &&
3220 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
3221 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07003222 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003223 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003224 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003225 }
Eric Laurent81784c32012-11-19 14:55:58 -08003226 }
3227
Eric Laurent81784c32012-11-19 14:55:58 -08003228 mNumWrites++;
3229 mInWrite = false;
Andy Hungcf10d742020-04-28 15:38:24 -07003230 if (mStandby) {
3231 mThreadMetrics.logBeginInterval();
3232 mStandby = false;
3233 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003234 return bytesWritten;
3235}
3236
3237void AudioFlinger::PlaybackThread::threadLoop_drain()
3238{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003239 bool supportsDrain = false;
3240 if (mOutput->stream->supportsDrain(&supportsDrain) == OK && supportsDrain) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003241 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
3242 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003243 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
3244 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003245 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003246 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003247 }
Mikhail Naganovcbc8f612016-10-11 18:05:13 -07003248 status_t result = mOutput->stream->drain(mMixerStatus == MIXER_DRAIN_TRACK);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003249 ALOGE_IF(result != OK, "Error when draining stream: %d", result);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003250 }
3251}
3252
3253void AudioFlinger::PlaybackThread::threadLoop_exit()
3254{
Eric Laurent275e8e92014-11-30 15:14:47 -08003255 {
3256 Mutex::Autolock _l(mLock);
3257 for (size_t i = 0; i < mTracks.size(); i++) {
3258 sp<Track> track = mTracks[i];
3259 track->invalidate();
3260 }
Andy Hungdae27702016-10-31 14:01:16 -07003261 // Clear ActiveTracks to update BatteryNotifier in case active tracks remain.
3262 // After we exit there are no more track changes sent to BatteryNotifier
3263 // because that requires an active threadLoop.
3264 // TODO: should we decActiveTrackCnt() of the cleared track effect chain?
3265 mActiveTracks.clear();
Eric Laurent275e8e92014-11-30 15:14:47 -08003266 }
Eric Laurent81784c32012-11-19 14:55:58 -08003267}
3268
3269/*
3270The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08003271 - mSinkBufferSize from frame count * frame size
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003272 - mActiveSleepTimeUs from activeSleepTimeUs()
3273 - mIdleSleepTimeUs from idleSleepTimeUs()
Eric Laurent42537be2016-01-08 17:16:42 -08003274 - mStandbyDelayNs from mActiveSleepTimeUs (DIRECT only) or forced to at least
3275 kDefaultStandbyTimeInNsecs when connected to an A2DP device.
Eric Laurent81784c32012-11-19 14:55:58 -08003276 - maxPeriod from frame count and sample rate (MIXER only)
3277
3278The parameters that affect these derived values are:
3279 - frame count
3280 - frame size
3281 - sample rate
3282 - device type: A2DP or not
3283 - device latency
3284 - format: PCM or not
3285 - active sleep time
3286 - idle sleep time
3287*/
3288
3289void AudioFlinger::PlaybackThread::cacheParameters_l()
3290{
Andy Hung25c2dac2014-02-27 14:56:00 -08003291 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003292 mActiveSleepTimeUs = activeSleepTimeUs();
3293 mIdleSleepTimeUs = idleSleepTimeUs();
Eric Laurent42537be2016-01-08 17:16:42 -08003294
3295 // make sure standby delay is not too short when connected to an A2DP sink to avoid
3296 // truncating audio when going to standby.
3297 mStandbyDelayNs = AudioFlinger::mStandbyTimeInNsecs;
jiabinc52b1ff2019-10-31 17:20:42 -07003298 if (!Intersection(outDeviceTypes(), getAudioDeviceOutAllA2dpSet()).empty()) {
Eric Laurent42537be2016-01-08 17:16:42 -08003299 if (mStandbyDelayNs < kDefaultStandbyTimeInNsecs) {
3300 mStandbyDelayNs = kDefaultStandbyTimeInNsecs;
3301 }
3302 }
Eric Laurent81784c32012-11-19 14:55:58 -08003303}
3304
Eric Laurent13084622016-05-17 10:51:49 -07003305bool AudioFlinger::PlaybackThread::invalidateTracks_l(audio_stream_type_t streamType)
Eric Laurent81784c32012-11-19 14:55:58 -08003306{
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003307 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %zu",
Eric Laurent81784c32012-11-19 14:55:58 -08003308 this, streamType, mTracks.size());
Eric Laurent13084622016-05-17 10:51:49 -07003309 bool trackMatch = false;
Eric Laurent81784c32012-11-19 14:55:58 -08003310 size_t size = mTracks.size();
3311 for (size_t i = 0; i < size; i++) {
3312 sp<Track> t = mTracks[i];
Eric Laurentd60560a2015-04-10 11:31:20 -07003313 if (t->streamType() == streamType && t->isExternalTrack()) {
Glenn Kasten5736c352012-12-04 12:12:34 -08003314 t->invalidate();
Eric Laurent13084622016-05-17 10:51:49 -07003315 trackMatch = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003316 }
3317 }
Eric Laurent13084622016-05-17 10:51:49 -07003318 return trackMatch;
Eric Laurent81784c32012-11-19 14:55:58 -08003319}
3320
Haynes Mathew George05317d22016-05-03 16:34:26 -07003321void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
3322{
3323 Mutex::Autolock _l(mLock);
3324 invalidateTracks_l(streamType);
3325}
3326
Eric Laurent81784c32012-11-19 14:55:58 -08003327status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
3328{
Glenn Kastend848eb42016-03-08 13:42:11 -08003329 audio_session_t session = chain->sessionId();
Mikhail Naganov022b9952017-01-04 16:36:51 -08003330 sp<EffectBufferHalInterface> halInBuffer, halOutBuffer;
Kevin Rocard7588ff42018-01-08 11:11:30 -08003331 status_t result = mAudioFlinger->mEffectsFactoryHal->mirrorBuffer(
Mikhail Naganov022b9952017-01-04 16:36:51 -08003332 mEffectBufferEnabled ? mEffectBuffer : mSinkBuffer,
3333 mEffectBufferEnabled ? mEffectBufferSize : mSinkBufferSize,
3334 &halInBuffer);
3335 if (result != OK) return result;
3336 halOutBuffer = halInBuffer;
rago94a1ee82017-07-21 15:11:02 -07003337 effect_buffer_t *buffer = reinterpret_cast<effect_buffer_t*>(halInBuffer->externalData());
Eric Laurent81784c32012-11-19 14:55:58 -08003338 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Eric Laurent3f75a5b2019-11-12 15:55:51 -08003339 if (!audio_is_global_session(session)) {
Eric Laurent81784c32012-11-19 14:55:58 -08003340 // Only one effect chain can be present in direct output thread and it uses
Andy Hung2098f272014-02-27 14:00:06 -08003341 // the sink buffer as input
Eric Laurent81784c32012-11-19 14:55:58 -08003342 if (mType != DIRECT) {
jiabin245cdd92018-12-07 17:55:15 -08003343 size_t numSamples = mNormalFrameCount * (mChannelCount + mHapticChannelCount);
Kevin Rocard7588ff42018-01-08 11:11:30 -08003344 status_t result = mAudioFlinger->mEffectsFactoryHal->allocateBuffer(
rago94a1ee82017-07-21 15:11:02 -07003345 numSamples * sizeof(effect_buffer_t),
Mikhail Naganov022b9952017-01-04 16:36:51 -08003346 &halInBuffer);
3347 if (result != OK) return result;
rago94a1ee82017-07-21 15:11:02 -07003348#ifdef FLOAT_EFFECT_CHAIN
3349 buffer = halInBuffer->audioBuffer()->f32;
3350#else
Mikhail Naganov022b9952017-01-04 16:36:51 -08003351 buffer = halInBuffer->audioBuffer()->s16;
rago94a1ee82017-07-21 15:11:02 -07003352#endif
Mikhail Naganov022b9952017-01-04 16:36:51 -08003353 ALOGV("addEffectChain_l() creating new input buffer %p session %d",
3354 buffer, session);
Eric Laurent81784c32012-11-19 14:55:58 -08003355 }
3356
3357 // Attach all tracks with same session ID to this chain.
3358 for (size_t i = 0; i < mTracks.size(); ++i) {
3359 sp<Track> track = mTracks[i];
3360 if (session == track->sessionId()) {
3361 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(),
3362 buffer);
3363 track->setMainBuffer(buffer);
3364 chain->incTrackCnt();
3365 }
3366 }
3367
3368 // indicate all active tracks in the chain
Andy Hungdae27702016-10-31 14:01:16 -07003369 for (const sp<Track> &track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08003370 if (session == track->sessionId()) {
3371 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
3372 chain->incActiveTrackCnt();
3373 }
3374 }
3375 }
Eric Laurentaaa44472014-09-12 17:41:50 -07003376 chain->setThread(this);
Mikhail Naganov022b9952017-01-04 16:36:51 -08003377 chain->setInBuffer(halInBuffer);
3378 chain->setOutBuffer(halOutBuffer);
Eric Laurent3f75a5b2019-11-12 15:55:51 -08003379 // Effect chain for session AUDIO_SESSION_DEVICE is inserted at end of effect
3380 // chains list in order to be processed last as it contains output device effects.
3381 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted just before to apply post
3382 // processing effects specific to an output stream before effects applied to all streams
3383 // routed to a given device.
Eric Laurent81784c32012-11-19 14:55:58 -08003384 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
3385 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Glenn Kastend848eb42016-03-08 13:42:11 -08003386 // after track specific effects and before output stage.
Eric Laurent81784c32012-11-19 14:55:58 -08003387 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
Glenn Kastend848eb42016-03-08 13:42:11 -08003388 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX.
Eric Laurent81784c32012-11-19 14:55:58 -08003389 // Effect chain for other sessions are inserted at beginning of effect
3390 // chains list to be processed before output mix effects. Relative order between other
Glenn Kastend848eb42016-03-08 13:42:11 -08003391 // sessions is not important.
3392 static_assert(AUDIO_SESSION_OUTPUT_MIX == 0 &&
Eric Laurent3f75a5b2019-11-12 15:55:51 -08003393 AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX &&
3394 AUDIO_SESSION_DEVICE < AUDIO_SESSION_OUTPUT_STAGE,
Glenn Kastend848eb42016-03-08 13:42:11 -08003395 "audio_session_t constants misdefined");
Eric Laurent81784c32012-11-19 14:55:58 -08003396 size_t size = mEffectChains.size();
3397 size_t i = 0;
3398 for (i = 0; i < size; i++) {
3399 if (mEffectChains[i]->sessionId() < session) {
3400 break;
3401 }
3402 }
3403 mEffectChains.insertAt(chain, i);
3404 checkSuspendOnAddEffectChain_l(chain);
3405
3406 return NO_ERROR;
3407}
3408
3409size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
3410{
Glenn Kastend848eb42016-03-08 13:42:11 -08003411 audio_session_t session = chain->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08003412
3413 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
3414
3415 for (size_t i = 0; i < mEffectChains.size(); i++) {
3416 if (chain == mEffectChains[i]) {
3417 mEffectChains.removeAt(i);
3418 // detach all active tracks from the chain
Andy Hungdae27702016-10-31 14:01:16 -07003419 for (const sp<Track> &track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08003420 if (session == track->sessionId()) {
3421 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
3422 chain.get(), session);
3423 chain->decActiveTrackCnt();
3424 }
3425 }
3426
3427 // detach all tracks with same session ID from this chain
3428 for (size_t i = 0; i < mTracks.size(); ++i) {
3429 sp<Track> track = mTracks[i];
3430 if (session == track->sessionId()) {
rago94a1ee82017-07-21 15:11:02 -07003431 track->setMainBuffer(reinterpret_cast<effect_buffer_t*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08003432 chain->decTrackCnt();
3433 }
3434 }
3435 break;
3436 }
3437 }
3438 return mEffectChains.size();
3439}
3440
3441status_t AudioFlinger::PlaybackThread::attachAuxEffect(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003442 const sp<AudioFlinger::PlaybackThread::Track>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003443{
3444 Mutex::Autolock _l(mLock);
3445 return attachAuxEffect_l(track, EffectId);
3446}
3447
3448status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003449 const sp<AudioFlinger::PlaybackThread::Track>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003450{
3451 status_t status = NO_ERROR;
3452
3453 if (EffectId == 0) {
3454 track->setAuxBuffer(0, NULL);
3455 } else {
3456 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
3457 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
3458 if (effect != 0) {
3459 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
3460 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
3461 } else {
3462 status = INVALID_OPERATION;
3463 }
3464 } else {
3465 status = BAD_VALUE;
3466 }
3467 }
3468 return status;
3469}
3470
3471void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
3472{
3473 for (size_t i = 0; i < mTracks.size(); ++i) {
3474 sp<Track> track = mTracks[i];
3475 if (track->auxEffectId() == effectId) {
3476 attachAuxEffect_l(track, 0);
3477 }
3478 }
3479}
3480
3481bool AudioFlinger::PlaybackThread::threadLoop()
3482{
Glenn Kasten388d5712017-04-07 14:38:41 -07003483 tlNBLogWriter = mNBLogWriter.get();
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003484
Eric Laurent81784c32012-11-19 14:55:58 -08003485 Vector< sp<Track> > tracksToRemove;
3486
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003487 mStandbyTimeNs = systemTime();
Andy Hung446f4df2019-02-21 12:26:41 -08003488 int64_t lastLoopCountWritten = -2; // never matches "previous" loop, when loopCount = 0.
Eric Laurent81784c32012-11-19 14:55:58 -08003489
3490 // MIXER
3491 nsecs_t lastWarning = 0;
3492
3493 // DUPLICATING
3494 // FIXME could this be made local to while loop?
3495 writeFrames = 0;
3496
3497 cacheParameters_l();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003498 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003499
3500 if (mType == MIXER) {
3501 sleepTimeShift = 0;
3502 }
3503
3504 CpuStats cpuStats;
3505 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
3506
3507 acquireWakeLock();
3508
Glenn Kasteneef598c2017-04-03 14:41:13 -07003509 // mNBLogWriter logging APIs can only be called by a single thread, typically the
3510 // thread associated with this PlaybackThread.
3511 // If you want to share the mNBLogWriter with other threads (for example, binder threads)
3512 // then all such threads must agree to hold a common mutex before logging.
Glenn Kasten9e58b552013-01-18 15:09:48 -08003513 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
3514 // and then that string will be logged at the next convenient opportunity.
Glenn Kasteneef598c2017-04-03 14:41:13 -07003515 // See reference to logString below.
Glenn Kasten9e58b552013-01-18 15:09:48 -08003516 const char *logString = NULL;
3517
rago1bb90822017-05-02 18:31:48 -07003518 // Estimated time for next buffer to be written to hal. This is used only on
3519 // suspended mode (for now) to help schedule the wait time until next iteration.
3520 nsecs_t timeLoopNextNs = 0;
3521
Eric Laurent664539d2013-09-23 18:24:31 -07003522 checkSilentMode_l();
Glenn Kasteneef598c2017-04-03 14:41:13 -07003523
Andy Hung2dbffc22018-08-08 18:50:41 -07003524 audio_patch_handle_t lastDownstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Andy Hungf3234512018-07-03 14:51:47 -07003525
Andy Hung446f4df2019-02-21 12:26:41 -08003526 // loopCount is used for statistics and diagnostics.
3527 for (int64_t loopCount = 0; !exitPending(); ++loopCount)
Eric Laurent81784c32012-11-19 14:55:58 -08003528 {
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08003529 // Log merge requests are performed during AudioFlinger binder transactions, but
3530 // that does not cover audio playback. It's requested here for that reason.
3531 mAudioFlinger->requestLogMerge();
3532
Eric Laurent81784c32012-11-19 14:55:58 -08003533 cpuStats.sample(myName);
3534
3535 Vector< sp<EffectChain> > effectChains;
Andy Hung6e6a2e62019-04-30 16:38:41 -07003536 audio_session_t activeHapticSessionId = AUDIO_SESSION_NONE;
Andy Hungc1646382019-04-30 16:12:10 -07003537 std::vector<sp<Track>> activeTracks;
Eric Laurent81784c32012-11-19 14:55:58 -08003538
Andy Hung2dbffc22018-08-08 18:50:41 -07003539 // If the device is AUDIO_DEVICE_OUT_BUS, check for downstream latency.
3540 //
jiabinc52b1ff2019-10-31 17:20:42 -07003541 // Note: we access outDeviceTypes() outside of mLock.
3542 if (isMsdDevice() && outDeviceTypes().count(AUDIO_DEVICE_OUT_BUS) != 0) {
Andy Hung2dbffc22018-08-08 18:50:41 -07003543 // Here, we try for the AF lock, but do not block on it as the latency
3544 // is more informational.
3545 if (mAudioFlinger->mLock.tryLock() == NO_ERROR) {
3546 std::vector<PatchPanel::SoftwarePatch> swPatches;
3547 double latencyMs;
3548 status_t status = INVALID_OPERATION;
3549 audio_patch_handle_t downstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
3550 if (mAudioFlinger->mPatchPanel.getDownstreamSoftwarePatches(id(), &swPatches) == OK
3551 && swPatches.size() > 0) {
3552 status = swPatches[0].getLatencyMs_l(&latencyMs);
3553 downstreamPatchHandle = swPatches[0].getPatchHandle();
3554 }
3555 if (downstreamPatchHandle != lastDownstreamPatchHandle) {
Dean Wheatley30d28422018-11-06 10:27:40 +11003556 mDownstreamLatencyStatMs.reset();
Andy Hung2dbffc22018-08-08 18:50:41 -07003557 lastDownstreamPatchHandle = downstreamPatchHandle;
3558 }
3559 if (status == OK) {
3560 // verify downstream latency (we assume a max reasonable
Mikhail Naganov6aa0a312018-11-09 11:00:01 -08003561 // latency of 5 seconds).
3562 const double minLatency = 0., maxLatency = 5000.;
3563 if (latencyMs >= minLatency && latencyMs <= maxLatency) {
Dean Wheatley56a583e2020-05-08 15:12:17 +10003564 ALOGVV("new downstream latency %lf ms", latencyMs);
Andy Hung2dbffc22018-08-08 18:50:41 -07003565 } else {
3566 ALOGD("out of range downstream latency %lf ms", latencyMs);
Mikhail Naganov6aa0a312018-11-09 11:00:01 -08003567 if (latencyMs < minLatency) latencyMs = minLatency;
3568 else if (latencyMs > maxLatency) latencyMs = maxLatency;
Andy Hung2dbffc22018-08-08 18:50:41 -07003569 }
Dean Wheatley30d28422018-11-06 10:27:40 +11003570 mDownstreamLatencyStatMs.add(latencyMs);
Andy Hung2dbffc22018-08-08 18:50:41 -07003571 }
3572 mAudioFlinger->mLock.unlock();
3573 }
3574 } else {
3575 if (lastDownstreamPatchHandle != AUDIO_PATCH_HANDLE_NONE) {
3576 // our device is no longer AUDIO_DEVICE_OUT_BUS, reset patch handle and stats.
Dean Wheatley30d28422018-11-06 10:27:40 +11003577 mDownstreamLatencyStatMs.reset();
Andy Hung2dbffc22018-08-08 18:50:41 -07003578 lastDownstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
3579 }
3580 }
3581
Eric Laurent81784c32012-11-19 14:55:58 -08003582 { // scope for mLock
3583
3584 Mutex::Autolock _l(mLock);
3585
Eric Laurent021cf962014-05-13 10:18:14 -07003586 processConfigEvents_l();
Eric Laurent10351942014-05-08 18:49:52 -07003587
Glenn Kasteneef598c2017-04-03 14:41:13 -07003588 // See comment at declaration of logString for why this is done under mLock
Glenn Kasten9e58b552013-01-18 15:09:48 -08003589 if (logString != NULL) {
3590 mNBLogWriter->logTimestamp();
3591 mNBLogWriter->log(logString);
3592 logString = NULL;
3593 }
3594
Dean Wheatley12473e92021-03-18 23:00:55 +11003595 collectTimestamps_l();
Andy Hungc8fddf32018-08-08 18:32:37 -07003596
Eric Laurent81784c32012-11-19 14:55:58 -08003597 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003598 if (mSignalPending) {
3599 // A signal was raised while we were unlocked
3600 mSignalPending = false;
3601 } else if (waitingAsyncCallback_l()) {
3602 if (exitPending()) {
3603 break;
3604 }
Marco Nelissen078538c2015-05-12 09:17:57 -07003605 bool released = false;
Eric Laurent64667972016-03-30 18:19:46 -07003606 if (!keepWakeLock()) {
Marco Nelissen078538c2015-05-12 09:17:57 -07003607 releaseWakeLock_l();
3608 released = true;
3609 }
Andy Hung10cbff12017-02-21 17:30:14 -08003610
3611 const int64_t waitNs = computeWaitTimeNs_l();
3612 ALOGV("wait async completion (wait time: %lld)", (long long)waitNs);
3613 status_t status = mWaitWorkCV.waitRelative(mLock, waitNs);
3614 if (status == TIMED_OUT) {
3615 mSignalPending = true; // if timeout recheck everything
3616 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003617 ALOGV("async completion/wake");
Marco Nelissen078538c2015-05-12 09:17:57 -07003618 if (released) {
3619 acquireWakeLock_l();
3620 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003621 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3622 mSleepTimeUs = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07003623
3624 continue;
3625 }
Eric Tan39ec8d62018-07-24 09:49:29 -07003626 if ((mActiveTracks.isEmpty() && systemTime() > mStandbyTimeNs) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08003627 isSuspended()) {
3628 // put audio hardware into standby after short delay
3629 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003630
3631 threadLoop_standby();
3632
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07003633 // This is where we go into standby
3634 if (!mStandby) {
3635 LOG_AUDIO_STATE();
Andy Hungcf10d742020-04-28 15:38:24 -07003636 mThreadMetrics.logEndInterval();
3637 mStandby = true;
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07003638 }
Andy Hungd0979812019-02-21 15:51:44 -08003639 sendStatistics(false /* force */);
Eric Laurent81784c32012-11-19 14:55:58 -08003640 }
3641
Eric Tan39ec8d62018-07-24 09:49:29 -07003642 if (mActiveTracks.isEmpty() && mConfigEvents.isEmpty()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003643 // we're about to wait, flush the binder command buffer
3644 IPCThreadState::self()->flushCommands();
3645
3646 clearOutputTracks();
3647
3648 if (exitPending()) {
3649 break;
3650 }
3651
3652 releaseWakeLock_l();
3653 // wait until we have something to do...
3654 ALOGV("%s going to sleep", myName.string());
3655 mWaitWorkCV.wait(mLock);
3656 ALOGV("%s waking up", myName.string());
3657 acquireWakeLock_l();
3658
3659 mMixerStatus = MIXER_IDLE;
3660 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
3661 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003662 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003663 checkSilentMode_l();
3664
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003665 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3666 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003667 if (mType == MIXER) {
3668 sleepTimeShift = 0;
3669 }
3670
3671 continue;
3672 }
3673 }
Eric Laurent81784c32012-11-19 14:55:58 -08003674 // mMixerStatusIgnoringFastTracks is also updated internally
3675 mMixerStatus = prepareTracks_l(&tracksToRemove);
3676
Andy Hungdae27702016-10-31 14:01:16 -07003677 mActiveTracks.updatePowerState(this);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003678
Kevin Rocard069c2712018-03-29 19:09:14 -07003679 updateMetadata_l();
3680
Eric Laurent81784c32012-11-19 14:55:58 -08003681 // prevent any changes in effect chain list and in each effect chain
3682 // during mixing and effect process as the audio buffers could be deleted
3683 // or modified if an effect is created or deleted
3684 lockEffectChains_l(effectChains);
Andy Hung6e6a2e62019-04-30 16:38:41 -07003685
3686 // Determine which session to pick up haptic data.
3687 // This must be done under the same lock as prepareTracks_l().
jiabineb3bda02020-06-30 14:07:03 -07003688 // The haptic data from the effect is at a higher priority than the one from track.
Andy Hung6e6a2e62019-04-30 16:38:41 -07003689 // TODO: Write haptic data directly to sink buffer when mixing.
3690 if (mHapticChannelCount > 0 && effectChains.size() > 0) {
3691 for (const auto& track : mActiveTracks) {
jiabineb3bda02020-06-30 14:07:03 -07003692 sp<EffectChain> effectChain = getEffectChain_l(track->sessionId());
3693 if (effectChain != nullptr && effectChain->containsHapticGeneratingEffect_l()) {
3694 activeHapticSessionId = track->sessionId();
3695 break;
3696 }
Andy Hung6e6a2e62019-04-30 16:38:41 -07003697 if (track->getHapticPlaybackEnabled()) {
3698 activeHapticSessionId = track->sessionId();
3699 break;
3700 }
3701 }
3702 }
3703
Andy Hungc1646382019-04-30 16:12:10 -07003704 // Acquire a local copy of active tracks with lock (release w/o lock).
3705 //
3706 // Control methods on the track acquire the ThreadBase lock (e.g. start()
3707 // stop(), pause(), etc.), but the threadLoop is entitled to call audio
3708 // data / buffer methods on tracks from activeTracks without the ThreadBase lock.
3709 activeTracks.insert(activeTracks.end(), mActiveTracks.begin(), mActiveTracks.end());
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003710 } // mLock scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08003711
Eric Laurentbfb1b832013-01-07 09:53:42 -08003712 if (mBytesRemaining == 0) {
3713 mCurrentWriteLength = 0;
3714 if (mMixerStatus == MIXER_TRACKS_READY) {
3715 // threadLoop_mix() sets mCurrentWriteLength
3716 threadLoop_mix();
3717 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
3718 && (mMixerStatus != MIXER_DRAIN_ALL)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003719 // threadLoop_sleepTime sets mSleepTimeUs to 0 if data
Eric Laurentbfb1b832013-01-07 09:53:42 -08003720 // must be written to HAL
3721 threadLoop_sleepTime();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003722 if (mSleepTimeUs == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08003723 mCurrentWriteLength = mSinkBufferSize;
Andy Hungc1646382019-04-30 16:12:10 -07003724
3725 // Tally underrun frames as we are inserting 0s here.
3726 for (const auto& track : activeTracks) {
Andy Hunge2e830f2019-12-03 12:54:46 -08003727 if (track->mFillingUpStatus == Track::FS_ACTIVE
3728 && !track->isStopped()
3729 && !track->isPaused()
3730 && !track->isTerminated()) {
3731 ALOGV("%s: track(%d) %s underrun due to thread sleep of %zu frames",
3732 __func__, track->id(), track->getTrackStateAsString(),
3733 mNormalFrameCount);
Andy Hungc1646382019-04-30 16:12:10 -07003734 track->mAudioTrackServerProxy->tallyUnderrunFrames(mNormalFrameCount);
3735 }
3736 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003737 }
3738 }
Andy Hung98ef9782014-03-04 14:46:50 -08003739 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003740 // mMixerBuffer with data if mMixerBufferValid is true and mSleepTimeUs == 0.
Andy Hung98ef9782014-03-04 14:46:50 -08003741 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
3742 // or mSinkBuffer (if there are no effects).
3743 //
3744 // This is done pre-effects computation; if effects change to
3745 // support higher precision, this needs to move.
3746 //
3747 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003748 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08003749 if (mMixerBufferValid) {
3750 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
3751 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
3752
Andy Hung2ddee192015-12-18 17:34:44 -08003753 // mono blend occurs for mixer threads only (not direct or offloaded)
3754 // and is handled here if we're going directly to the sink.
3755 if (requireMonoBlend() && !mEffectBufferValid) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003756 mono_blend(mMixerBuffer, mMixerBufferFormat, mChannelCount, mNormalFrameCount,
3757 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003758 }
3759
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01003760 if (!hasFastMixer()) {
3761 // Balance must take effect after mono conversion.
3762 // We do it here if there is no FastMixer.
3763 // mBalance detects zero balance within the class for speed (not needed here).
3764 mBalance.setBalance(mMasterBalance.load());
3765 mBalance.process((float *)mMixerBuffer, mNormalFrameCount);
3766 }
3767
Andy Hung98ef9782014-03-04 14:46:50 -08003768 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
jiabin245cdd92018-12-07 17:55:15 -08003769 mNormalFrameCount * (mChannelCount + mHapticChannelCount));
3770
3771 // If we're going directly to the sink and there are haptic channels,
3772 // we should adjust channels as the sample data is partially interleaved
3773 // in this case.
3774 if (!mEffectBufferValid && mHapticChannelCount > 0) {
3775 adjust_channels_non_destructive(buffer, mChannelCount, buffer,
3776 mChannelCount + mHapticChannelCount,
3777 audio_bytes_per_sample(format),
3778 audio_bytes_per_frame(mChannelCount, format) * mNormalFrameCount);
3779 }
Andy Hung98ef9782014-03-04 14:46:50 -08003780 }
3781
Eric Laurentbfb1b832013-01-07 09:53:42 -08003782 mBytesRemaining = mCurrentWriteLength;
3783 if (isSuspended()) {
Andy Hung238fa3d2016-07-28 10:53:22 -07003784 // Simulate write to HAL when suspended (e.g. BT SCO phone call).
3785 mSleepTimeUs = suspendSleepTimeUs(); // assumes full buffer.
3786 const size_t framesRemaining = mBytesRemaining / mFrameSize;
3787 mBytesWritten += mBytesRemaining;
3788 mFramesWritten += framesRemaining;
3789 mSuspendedFrames += framesRemaining; // to adjust kernel HAL position
Eric Laurentbfb1b832013-01-07 09:53:42 -08003790 mBytesRemaining = 0;
3791 }
Eric Laurent81784c32012-11-19 14:55:58 -08003792
Eric Laurentbfb1b832013-01-07 09:53:42 -08003793 // only process effects if we're going to write
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003794 if (mSleepTimeUs == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003795 for (size_t i = 0; i < effectChains.size(); i ++) {
3796 effectChains[i]->process_l();
jiabin47affe52019-04-04 18:02:07 -07003797 // TODO: Write haptic data directly to sink buffer when mixing.
Andy Hung6e6a2e62019-04-30 16:38:41 -07003798 if (activeHapticSessionId != AUDIO_SESSION_NONE
3799 && activeHapticSessionId == effectChains[i]->sessionId()) {
jiabin47affe52019-04-04 18:02:07 -07003800 // Haptic data is active in this case, copy it directly from
3801 // in buffer to out buffer.
3802 const size_t audioBufferSize = mNormalFrameCount
3803 * audio_bytes_per_frame(mChannelCount, EFFECT_BUFFER_FORMAT);
3804 memcpy_by_audio_format(
3805 (uint8_t*)effectChains[i]->outBuffer() + audioBufferSize,
3806 EFFECT_BUFFER_FORMAT,
3807 (const uint8_t*)effectChains[i]->inBuffer() + audioBufferSize,
3808 EFFECT_BUFFER_FORMAT, mNormalFrameCount * mHapticChannelCount);
3809 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003810 }
Eric Laurent81784c32012-11-19 14:55:58 -08003811 }
3812 }
Eric Laurent59fe0102013-09-27 18:48:26 -07003813 // Process effect chains for offloaded thread even if no audio
3814 // was read from audio track: process only updates effect state
3815 // and thus does have to be synchronized with audio writes but may have
3816 // to be called while waiting for async write callback
3817 if (mType == OFFLOAD) {
3818 for (size_t i = 0; i < effectChains.size(); i ++) {
3819 effectChains[i]->process_l();
3820 }
3821 }
Eric Laurent81784c32012-11-19 14:55:58 -08003822
Andy Hung98ef9782014-03-04 14:46:50 -08003823 // Only if the Effects buffer is enabled and there is data in the
3824 // Effects buffer (buffer valid), we need to
3825 // copy into the sink buffer.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003826 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08003827 if (mEffectBufferValid) {
3828 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
Andy Hung2ddee192015-12-18 17:34:44 -08003829
3830 if (requireMonoBlend()) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003831 mono_blend(mEffectBuffer, mEffectBufferFormat, mChannelCount, mNormalFrameCount,
3832 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003833 }
3834
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01003835 if (!hasFastMixer()) {
3836 // Balance must take effect after mono conversion.
3837 // We do it here if there is no FastMixer.
3838 // mBalance detects zero balance within the class for speed (not needed here).
3839 mBalance.setBalance(mMasterBalance.load());
3840 mBalance.process((float *)mEffectBuffer, mNormalFrameCount);
3841 }
3842
Andy Hung98ef9782014-03-04 14:46:50 -08003843 memcpy_by_audio_format(mSinkBuffer, mFormat, mEffectBuffer, mEffectBufferFormat,
jiabin245cdd92018-12-07 17:55:15 -08003844 mNormalFrameCount * (mChannelCount + mHapticChannelCount));
3845 // The sample data is partially interleaved when haptic channels exist,
3846 // we need to adjust channels here.
3847 if (mHapticChannelCount > 0) {
3848 adjust_channels_non_destructive(mSinkBuffer, mChannelCount, mSinkBuffer,
3849 mChannelCount + mHapticChannelCount,
3850 audio_bytes_per_sample(mFormat),
3851 audio_bytes_per_frame(mChannelCount, mFormat) * mNormalFrameCount);
3852 }
Andy Hung98ef9782014-03-04 14:46:50 -08003853 }
3854
Eric Laurent81784c32012-11-19 14:55:58 -08003855 // enable changes in effect chain
3856 unlockEffectChains(effectChains);
3857
Eric Laurentbfb1b832013-01-07 09:53:42 -08003858 if (!waitingAsyncCallback()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003859 // mSleepTimeUs == 0 means we must write to audio hardware
3860 if (mSleepTimeUs == 0) {
Andy Hung08fb1742015-05-31 23:22:10 -07003861 ssize_t ret = 0;
Andy Hung446f4df2019-02-21 12:26:41 -08003862 // writePeriodNs is updated >= 0 when ret > 0.
3863 int64_t writePeriodNs = -1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003864 if (mBytesRemaining) {
Andy Hung69488c42016-05-16 18:43:33 -07003865 // FIXME rewrite to reduce number of system calls
Andy Hung446f4df2019-02-21 12:26:41 -08003866 const int64_t lastIoBeginNs = systemTime();
Andy Hung08fb1742015-05-31 23:22:10 -07003867 ret = threadLoop_write();
Andy Hung446f4df2019-02-21 12:26:41 -08003868 const int64_t lastIoEndNs = systemTime();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003869 if (ret < 0) {
3870 mBytesRemaining = 0;
Andy Hung446f4df2019-02-21 12:26:41 -08003871 } else if (ret > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003872 mBytesWritten += ret;
3873 mBytesRemaining -= ret;
Andy Hung446f4df2019-02-21 12:26:41 -08003874 const int64_t frames = ret / mFrameSize;
3875 mFramesWritten += frames;
3876
3877 writePeriodNs = lastIoEndNs - mLastIoEndNs;
3878 // process information relating to write time.
3879 if (audio_has_proportional_frames(mFormat)) {
3880 // we are in a continuous mixing cycle
3881 if (mMixerStatus == MIXER_TRACKS_READY &&
3882 loopCount == lastLoopCountWritten + 1) {
3883
3884 const double jitterMs =
3885 TimestampVerifier<int64_t, int64_t>::computeJitterMs(
3886 {frames, writePeriodNs},
3887 {0, 0} /* lastTimestamp */, mSampleRate);
3888 const double processMs =
3889 (lastIoBeginNs - mLastIoEndNs) * 1e-6;
3890
3891 Mutex::Autolock _l(mLock);
3892 mIoJitterMs.add(jitterMs);
3893 mProcessTimeMs.add(processMs);
3894 }
3895
3896 // write blocked detection
3897 const int64_t deltaWriteNs = lastIoEndNs - lastIoBeginNs;
3898 if (mType == MIXER && deltaWriteNs > maxPeriod) {
3899 mNumDelayedWrites++;
3900 if ((lastIoEndNs - lastWarning) > kWarningThrottleNs) {
3901 ATRACE_NAME("underrun");
3902 ALOGW("write blocked for %lld msecs, "
3903 "%d delayed writes, thread %d",
3904 (long long)deltaWriteNs / NANOS_PER_MILLISECOND,
3905 mNumDelayedWrites, mId);
3906 lastWarning = lastIoEndNs;
3907 }
3908 }
3909 }
3910 // update timing info.
3911 mLastIoBeginNs = lastIoBeginNs;
3912 mLastIoEndNs = lastIoEndNs;
3913 lastLoopCountWritten = loopCount;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003914 }
3915 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
3916 (mMixerStatus == MIXER_DRAIN_ALL)) {
3917 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08003918 }
Andy Hung08fb1742015-05-31 23:22:10 -07003919 if (mType == MIXER && !mStandby) {
Andy Hung08fb1742015-05-31 23:22:10 -07003920
3921 if (mThreadThrottle
3922 && mMixerStatus == MIXER_TRACKS_READY // we are mixing (active tracks)
Andy Hung446f4df2019-02-21 12:26:41 -08003923 && writePeriodNs > 0) { // we have write period info
Andy Hung08fb1742015-05-31 23:22:10 -07003924 // Limit MixerThread data processing to no more than twice the
3925 // expected processing rate.
3926 //
3927 // This helps prevent underruns with NuPlayer and other applications
3928 // which may set up buffers that are close to the minimum size, or use
3929 // deep buffers, and rely on a double-buffering sleep strategy to fill.
3930 //
3931 // The throttle smooths out sudden large data drains from the device,
3932 // e.g. when it comes out of standby, which often causes problems with
3933 // (1) mixer threads without a fast mixer (which has its own warm-up)
3934 // (2) minimum buffer sized tracks (even if the track is full,
3935 // the app won't fill fast enough to handle the sudden draw).
Haynes Mathew Georgef92b2172016-05-09 11:34:15 -07003936 //
3937 // Total time spent in last processing cycle equals time spent in
3938 // 1. threadLoop_write, as well as time spent in
3939 // 2. threadLoop_mix (significant for heavy mixing, especially
3940 // on low tier processors)
Andy Hung08fb1742015-05-31 23:22:10 -07003941
Andy Hung446f4df2019-02-21 12:26:41 -08003942 // it's OK if deltaMs is an overestimate.
3943
3944 const int32_t deltaMs = writePeriodNs / NANOS_PER_MILLISECOND;
Ivan Lozanoe02bc542017-10-26 09:51:54 -07003945
Ivan Lozanoea04d392017-11-07 14:37:07 -08003946 const int32_t throttleMs = (int32_t)mHalfBufferMs - deltaMs;
Andy Hung08fb1742015-05-31 23:22:10 -07003947 if ((signed)mHalfBufferMs >= throttleMs && throttleMs > 0) {
Andy Hungcf10d742020-04-28 15:38:24 -07003948 mThreadMetrics.logThrottleMs((double)throttleMs);
Andy Hungb68f5eb2019-12-03 16:49:17 -08003949
Andy Hung08fb1742015-05-31 23:22:10 -07003950 usleep(throttleMs * 1000);
Andy Hung40eb1a12015-06-18 13:42:02 -07003951 // notify of throttle start on verbose log
3952 ALOGV_IF(mThreadThrottleEndMs == mThreadThrottleTimeMs,
3953 "mixer(%p) throttle begin:"
3954 " ret(%zd) deltaMs(%d) requires sleep %d ms",
Andy Hung08fb1742015-05-31 23:22:10 -07003955 this, ret, deltaMs, throttleMs);
Andy Hung40eb1a12015-06-18 13:42:02 -07003956 mThreadThrottleTimeMs += throttleMs;
Andy Hung0a31ddd2016-07-06 19:10:29 -07003957 // Throttle must be attributed to the previous mixer loop's write time
3958 // to allow back-to-back throttling.
Andy Hung446f4df2019-02-21 12:26:41 -08003959 // This also ensures proper timing statistics.
3960 mLastIoEndNs = systemTime(); // we fetch the write end time again.
Andy Hung40eb1a12015-06-18 13:42:02 -07003961 } else {
3962 uint32_t diff = mThreadThrottleTimeMs - mThreadThrottleEndMs;
3963 if (diff > 0) {
3964 // notify of throttle end on debug log
Andy Hung3ea004d2016-05-05 16:48:37 -07003965 // but prevent spamming for bluetooth
jiabinc52b1ff2019-10-31 17:20:42 -07003966 ALOGD_IF(!isSingleDeviceType(
3967 outDeviceTypes(), audio_is_a2dp_out_device) &&
3968 !isSingleDeviceType(
3969 outDeviceTypes(), audio_is_hearing_aid_out_device),
Andy Hung3ea004d2016-05-05 16:48:37 -07003970 "mixer(%p) throttle end: throttle time(%u)", this, diff);
Andy Hung40eb1a12015-06-18 13:42:02 -07003971 mThreadThrottleEndMs = mThreadThrottleTimeMs;
3972 }
Andy Hung08fb1742015-05-31 23:22:10 -07003973 }
3974 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003975 }
Eric Laurent81784c32012-11-19 14:55:58 -08003976
Eric Laurentbfb1b832013-01-07 09:53:42 -08003977 } else {
Glenn Kastene7754022014-10-31 12:11:26 -07003978 ATRACE_BEGIN("sleep");
Eric Laurente93cc032016-05-05 10:15:10 -07003979 Mutex::Autolock _l(mLock);
rago1bb90822017-05-02 18:31:48 -07003980 // suspended requires accurate metering of sleep time.
3981 if (isSuspended()) {
3982 // advance by expected sleepTime
3983 timeLoopNextNs += microseconds((nsecs_t)mSleepTimeUs);
3984 const nsecs_t nowNs = systemTime();
3985
3986 // compute expected next time vs current time.
3987 // (negative deltas are treated as delays).
3988 nsecs_t deltaNs = timeLoopNextNs - nowNs;
3989 if (deltaNs < -kMaxNextBufferDelayNs) {
3990 // Delays longer than the max allowed trigger a reset.
3991 ALOGV("DelayNs: %lld, resetting timeLoopNextNs", (long long) deltaNs);
3992 deltaNs = microseconds((nsecs_t)mSleepTimeUs);
3993 timeLoopNextNs = nowNs + deltaNs;
3994 } else if (deltaNs < 0) {
3995 // Delays within the max delay allowed: zero the delta/sleepTime
3996 // to help the system catch up in the next iteration(s)
3997 ALOGV("DelayNs: %lld, catching-up", (long long) deltaNs);
3998 deltaNs = 0;
3999 }
4000 // update sleep time (which is >= 0)
4001 mSleepTimeUs = deltaNs / 1000;
4002 }
Eric Laurente93cc032016-05-05 10:15:10 -07004003 if (!mSignalPending && mConfigEvents.isEmpty() && !exitPending()) {
4004 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)mSleepTimeUs));
Eric Laurent51716182016-02-29 18:00:56 -08004005 }
Glenn Kastene7754022014-10-31 12:11:26 -07004006 ATRACE_END();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004007 }
Eric Laurent81784c32012-11-19 14:55:58 -08004008 }
4009
4010 // Finally let go of removed track(s), without the lock held
4011 // since we can't guarantee the destructors won't acquire that
4012 // same lock. This will also mutate and push a new fast mixer state.
4013 threadLoop_removeTracks(tracksToRemove);
4014 tracksToRemove.clear();
4015
4016 // FIXME I don't understand the need for this here;
4017 // it was in the original code but maybe the
4018 // assignment in saveOutputTracks() makes this unnecessary?
4019 clearOutputTracks();
4020
4021 // Effect chains will be actually deleted here if they were removed from
4022 // mEffectChains list during mixing or effects processing
4023 effectChains.clear();
4024
4025 // FIXME Note that the above .clear() is no longer necessary since effectChains
4026 // is now local to this block, but will keep it for now (at least until merge done).
4027 }
4028
Eric Laurentbfb1b832013-01-07 09:53:42 -08004029 threadLoop_exit();
4030
Eric Laurentcf817a22014-08-04 20:36:31 -07004031 if (!mStandby) {
4032 threadLoop_standby();
4033 mStandby = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004034 }
4035
4036 releaseWakeLock();
4037
4038 ALOGV("Thread %p type %d exiting", this, mType);
4039 return false;
4040}
4041
Dean Wheatley12473e92021-03-18 23:00:55 +11004042void AudioFlinger::PlaybackThread::collectTimestamps_l()
4043{
4044 // Collect timestamp statistics for the Playback Thread types that support it.
4045 if (mType != MIXER
4046 && mType != DUPLICATING
4047 && mType != DIRECT
4048 && mType != OFFLOAD) {
4049 return;
4050 }
4051 if (mStandby) {
4052 mTimestampVerifier.discontinuity(discontinuityForStandbyOrFlush());
4053 return;
4054 } else if (mHwPaused) {
4055 mTimestampVerifier.discontinuity(mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS);
4056 return;
4057 }
4058
4059 // Gather the framesReleased counters for all active tracks,
4060 // and associate with the sink frames written out. We need
4061 // this to convert the sink timestamp to the track timestamp.
4062 bool kernelLocationUpdate = false;
4063 ExtendedTimestamp timestamp; // use private copy to fetch
4064
4065 // Always query HAL timestamp and update timestamp verifier. In standby or pause,
4066 // HAL may be draining some small duration buffered data for fade out.
4067 if (threadloop_getHalTimestamp_l(&timestamp) == OK) {
4068 mTimestampVerifier.add(timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL],
4069 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4070 mSampleRate);
4071
4072 if (isTimestampCorrectionEnabled()) {
4073 ALOGVV("TS_BEFORE: %d %lld %lld", id(),
4074 (long long)timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4075 (long long)timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]);
4076 auto correctedTimestamp = mTimestampVerifier.getLastCorrectedTimestamp();
4077 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4078 = correctedTimestamp.mFrames;
4079 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]
4080 = correctedTimestamp.mTimeNs;
4081 ALOGVV("TS_AFTER: %d %lld %lld", id(),
4082 (long long)timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4083 (long long)timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]);
4084
4085 // Note: Downstream latency only added if timestamp correction enabled.
4086 if (mDownstreamLatencyStatMs.getN() > 0) { // we have latency info.
4087 const int64_t newPosition =
4088 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4089 - int64_t(mDownstreamLatencyStatMs.getMean() * mSampleRate * 1e-3);
4090 // prevent retrograde
4091 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = max(
4092 newPosition,
4093 (mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4094 - mSuspendedFrames));
4095 }
4096 }
4097
4098 // We always fetch the timestamp here because often the downstream
4099 // sink will block while writing.
4100
4101 // We keep track of the last valid kernel position in case we are in underrun
4102 // and the normal mixer period is the same as the fast mixer period, or there
4103 // is some error from the HAL.
4104 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
4105 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
4106 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
4107 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
4108 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4109
4110 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
4111 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER];
4112 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
4113 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER];
4114 }
4115
4116 if (timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
4117 kernelLocationUpdate = true;
4118 } else {
4119 ALOGVV("getTimestamp error - no valid kernel position");
4120 }
4121
4122 // copy over kernel info
4123 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] =
4124 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4125 + mSuspendedFrames; // add frames discarded when suspended
4126 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] =
4127 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4128 } else {
4129 mTimestampVerifier.error();
4130 }
4131
4132 // mFramesWritten for non-offloaded tracks are contiguous
4133 // even after standby() is called. This is useful for the track frame
4134 // to sink frame mapping.
4135 bool serverLocationUpdate = false;
4136 if (mFramesWritten != mLastFramesWritten) {
4137 serverLocationUpdate = true;
4138 mLastFramesWritten = mFramesWritten;
4139 }
4140 // Only update timestamps if there is a meaningful change.
4141 // Either the kernel timestamp must be valid or we have written something.
4142 if (kernelLocationUpdate || serverLocationUpdate) {
4143 if (serverLocationUpdate) {
4144 // use the time before we called the HAL write - it is a bit more accurate
4145 // to when the server last read data than the current time here.
4146 //
4147 // If we haven't written anything, mLastIoBeginNs will be -1
4148 // and we use systemTime().
4149 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] = mFramesWritten;
4150 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = mLastIoBeginNs == -1
4151 ? systemTime() : mLastIoBeginNs;
4152 }
4153
4154 for (const sp<Track> &t : mActiveTracks) {
4155 if (!t->isFastTrack()) {
4156 t->updateTrackFrameInfo(
4157 t->mAudioTrackServerProxy->framesReleased(),
4158 mFramesWritten,
4159 mSampleRate,
4160 mTimestamp);
4161 }
4162 }
4163 }
4164
4165 if (audio_has_proportional_frames(mFormat)) {
4166 const double latencyMs = mTimestamp.getOutputServerLatencyMs(mSampleRate);
4167 if (latencyMs != 0.) { // note 0. means timestamp is empty.
4168 mLatencyMs.add(latencyMs);
4169 }
4170 }
4171#if 0
4172 // logFormat example
4173 if (z % 100 == 0) {
4174 timespec ts;
4175 clock_gettime(CLOCK_MONOTONIC, &ts);
4176 LOGT("This is an integer %d, this is a float %f, this is my "
4177 "pid %p %% %s %t", 42, 3.14, "and this is a timestamp", ts);
4178 LOGT("A deceptive null-terminated string %\0");
4179 }
4180 ++z;
4181#endif
4182}
4183
Eric Laurentbfb1b832013-01-07 09:53:42 -08004184// removeTracks_l() must be called with ThreadBase::mLock held
4185void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
4186{
Andy Hungfe726a62018-09-27 15:17:25 -07004187 for (const auto& track : tracksToRemove) {
4188 mActiveTracks.remove(track);
4189 ALOGV("%s(%d): removing track on session %d", __func__, track->id(), track->sessionId());
4190 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
4191 if (chain != 0) {
4192 ALOGV("%s(%d): stopping track on chain %p for session Id: %d",
4193 __func__, track->id(), chain.get(), track->sessionId());
4194 chain->decActiveTrackCnt();
4195 }
4196 // If an external client track, inform APM we're no longer active, and remove if needed.
4197 // We do this under lock so that the state is consistent if the Track is destroyed.
4198 if (track->isExternalTrack()) {
4199 AudioSystem::stopOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08004200 if (track->isTerminated()) {
Andy Hungfe726a62018-09-27 15:17:25 -07004201 AudioSystem::releaseOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08004202 }
4203 }
Andy Hungfe726a62018-09-27 15:17:25 -07004204 if (track->isTerminated()) {
4205 // remove from our tracks vector
4206 removeTrack_l(track);
4207 }
jiabineb3bda02020-06-30 14:07:03 -07004208 if (mHapticChannelCount > 0 &&
4209 ((track->channelMask() & AUDIO_CHANNEL_HAPTIC_ALL) != AUDIO_CHANNEL_NONE
4210 || (chain != nullptr && chain->containsHapticGeneratingEffect_l()))) {
jiabin57303cc2018-12-18 15:45:57 -08004211 mLock.unlock();
4212 // Unlock due to VibratorService will lock for this call and will
4213 // call Tracks.mute/unmute which also require thread's lock.
4214 AudioFlinger::onExternalVibrationStop(track->getExternalVibration());
4215 mLock.lock();
jiabine70bc7f2020-06-30 22:07:55 -07004216
4217 // When the track is stop, set the haptic intensity as MUTE
4218 // for the HapticGenerator effect.
4219 if (chain != nullptr) {
4220 chain->setHapticIntensity_l(track->id(), static_cast<int>(os::HapticScale::MUTE));
4221 }
jiabin245cdd92018-12-07 17:55:15 -08004222 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004223 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004224}
Eric Laurent81784c32012-11-19 14:55:58 -08004225
Eric Laurentaccc1472013-09-20 09:36:34 -07004226status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
4227{
4228 if (mNormalSink != 0) {
Andy Hung818e7a32016-02-16 18:08:07 -08004229 ExtendedTimestamp ets;
4230 status_t status = mNormalSink->getTimestamp(ets);
4231 if (status == NO_ERROR) {
4232 status = ets.getBestTimestamp(&timestamp);
4233 }
4234 return status;
Eric Laurentaccc1472013-09-20 09:36:34 -07004235 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004236 if ((mType == OFFLOAD || mType == DIRECT) && mOutput != NULL) {
Dean Wheatley12473e92021-03-18 23:00:55 +11004237 collectTimestamps_l();
4238 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] <= 0) {
4239 return INVALID_OPERATION;
Eric Laurentaccc1472013-09-20 09:36:34 -07004240 }
Dean Wheatley12473e92021-03-18 23:00:55 +11004241 timestamp.mPosition = mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
4242 const int64_t timeNs = mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4243 timestamp.mTime.tv_sec = timeNs / NANOS_PER_SECOND;
4244 timestamp.mTime.tv_nsec = timeNs - (timestamp.mTime.tv_sec * NANOS_PER_SECOND);
4245 return NO_ERROR;
Eric Laurentaccc1472013-09-20 09:36:34 -07004246 }
4247 return INVALID_OPERATION;
4248}
Eric Laurent1c333e22014-05-20 10:48:17 -07004249
Eric Laurenteab90452019-06-24 15:17:46 -07004250// For dedicated VoIP outputs, let the HAL apply the stream volume. Track volume is
4251// still applied by the mixer.
4252// All tracks attached to a mixer with flag VOIP_RX are tied to the same
4253// stream type STREAM_VOICE_CALL so this will only change the HAL volume once even
4254// if more than one track are active
4255status_t AudioFlinger::PlaybackThread::handleVoipVolume_l(float *volume)
4256{
4257 status_t result = NO_ERROR;
4258 if ((mOutput->flags & AUDIO_OUTPUT_FLAG_VOIP_RX) != 0) {
4259 if (*volume != mLeftVolFloat) {
4260 result = mOutput->stream->setVolume(*volume, *volume);
4261 ALOGE_IF(result != OK,
4262 "Error when setting output stream volume: %d", result);
4263 if (result == NO_ERROR) {
4264 mLeftVolFloat = *volume;
4265 }
4266 }
4267 // if stream volume was successfully sent to the HAL, mLeftVolFloat == v here and we
4268 // remove stream volume contribution from software volume.
4269 if (mLeftVolFloat == *volume) {
4270 *volume = 1.0f;
4271 }
4272 }
4273 return result;
4274}
4275
Eric Laurent054d9d32015-04-24 08:48:48 -07004276status_t AudioFlinger::MixerThread::createAudioPatch_l(const struct audio_patch *patch,
4277 audio_patch_handle_t *handle)
4278{
Andy Hungf60abce2016-08-26 11:37:54 -07004279 status_t status;
4280 if (property_get_bool("af.patch_park", false /* default_value */)) {
4281 // Park FastMixer to avoid potential DOS issues with writing to the HAL
4282 // or if HAL does not properly lock against access.
4283 AutoPark<FastMixer> park(mFastMixer);
4284 status = PlaybackThread::createAudioPatch_l(patch, handle);
4285 } else {
4286 status = PlaybackThread::createAudioPatch_l(patch, handle);
4287 }
Eric Laurent054d9d32015-04-24 08:48:48 -07004288 return status;
4289}
4290
Eric Laurent1c333e22014-05-20 10:48:17 -07004291status_t AudioFlinger::PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
4292 audio_patch_handle_t *handle)
4293{
4294 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07004295
4296 // store new device and send to effects
4297 audio_devices_t type = AUDIO_DEVICE_NONE;
jiabinc52b1ff2019-10-31 17:20:42 -07004298 AudioDeviceTypeAddrVector deviceTypeAddrs;
Eric Laurent054d9d32015-04-24 08:48:48 -07004299 for (unsigned int i = 0; i < patch->num_sinks; i++) {
jiabinc52b1ff2019-10-31 17:20:42 -07004300 LOG_ALWAYS_FATAL_IF(popcount(patch->sinks[i].ext.device.type) > 1
4301 && !mOutput->audioHwDev->supportsAudioPatches(),
4302 "Enumerated device type(%#x) must not be used "
4303 "as it does not support audio patches",
4304 patch->sinks[i].ext.device.type);
Mikhail Naganov55773032020-10-01 15:08:13 -07004305 type = static_cast<audio_devices_t>(type | patch->sinks[i].ext.device.type);
jiabinc52b1ff2019-10-31 17:20:42 -07004306 deviceTypeAddrs.push_back(AudioDeviceTypeAddr(patch->sinks[i].ext.device.type,
4307 patch->sinks[i].ext.device.address));
Eric Laurent054d9d32015-04-24 08:48:48 -07004308 }
4309
François Gaffie0c280aa2018-07-25 10:02:15 +02004310 audio_port_handle_t sinkPortId = patch->sinks[0].id;
Eric Laurent054d9d32015-04-24 08:48:48 -07004311#ifdef ADD_BATTERY_DATA
4312 // when changing the audio output device, call addBatteryData to notify
4313 // the change
jiabinc52b1ff2019-10-31 17:20:42 -07004314 if (outDeviceTypes() != deviceTypes) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004315 uint32_t params = 0;
4316 // check whether speaker is on
jiabinc52b1ff2019-10-31 17:20:42 -07004317 if (deviceTypes.count(AUDIO_DEVICE_OUT_SPEAKER) > 0) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004318 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent1c333e22014-05-20 10:48:17 -07004319 }
4320
Eric Laurent054d9d32015-04-24 08:48:48 -07004321 // check if any other device (except speaker) is on
jiabinc52b1ff2019-10-31 17:20:42 -07004322 if (!isSingleDeviceType(deviceTypes, AUDIO_DEVICE_OUT_SPEAKER)) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004323 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
4324 }
4325
4326 if (params != 0) {
4327 addBatteryData(params);
4328 }
4329 }
4330#endif
4331
4332 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08004333 mEffectChains[i]->setDevices_l(deviceTypeAddrs);
Eric Laurent054d9d32015-04-24 08:48:48 -07004334 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07004335
jiabinc52b1ff2019-10-31 17:20:42 -07004336 // mPatch.num_sinks is not set when the thread is created so that
4337 // the first patch creation triggers an ioConfigChanged callback
4338 bool configChanged = (mPatch.num_sinks == 0) ||
4339 (mPatch.sinks[0].id != sinkPortId);
Eric Laurent296fb132015-05-01 11:38:42 -07004340 mPatch = *patch;
jiabinc52b1ff2019-10-31 17:20:42 -07004341 mOutDeviceTypeAddrs = deviceTypeAddrs;
jiabin0a957d32020-04-29 10:56:20 -07004342 checkSilentMode_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07004343
Mikhail Naganov9ee05402016-10-13 15:58:17 -07004344 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07004345 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
4346 status = hwDevice->createAudioPatch(patch->num_sources,
4347 patch->sources,
4348 patch->num_sinks,
4349 patch->sinks,
4350 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07004351 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07004352 char *address;
4353 if (strcmp(patch->sinks[0].ext.device.address, "") != 0) {
4354 //FIXME: we only support address on first sink with HAL version < 3.0
4355 address = audio_device_address_to_parameter(
4356 patch->sinks[0].ext.device.type,
4357 patch->sinks[0].ext.device.address);
4358 } else {
4359 address = (char *)calloc(1, 1);
4360 }
4361 AudioParameter param = AudioParameter(String8(address));
4362 free(address);
Mikhail Naganov00260b52016-10-13 12:54:24 -07004363 param.addInt(String8(AudioParameter::keyRouting), (int)type);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004364 status = mOutput->stream->setParameters(param.toString());
Eric Laurent054d9d32015-04-24 08:48:48 -07004365 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07004366 }
Andy Hungc2b11cb2020-04-22 09:04:01 -07004367 const std::string patchSinksAsString = patchSinksToString(patch);
Andy Hungcf10d742020-04-28 15:38:24 -07004368
4369 mThreadMetrics.logEndInterval();
Andy Hungea840382020-05-05 21:50:17 -07004370 mThreadMetrics.logCreatePatch(/* inDevices */ {}, patchSinksAsString);
Andy Hungcf10d742020-04-28 15:38:24 -07004371 mThreadMetrics.logBeginInterval();
Andy Hungc2b11cb2020-04-22 09:04:01 -07004372 // also dispatch to active AudioTracks for MediaMetrics
4373 for (const auto &track : mActiveTracks) {
4374 track->logEndInterval();
4375 track->logBeginInterval(patchSinksAsString);
4376 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08004377
Eric Laurente8726fe2015-06-26 09:39:24 -07004378 if (configChanged) {
4379 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
4380 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004381 return status;
4382}
4383
Eric Laurent054d9d32015-04-24 08:48:48 -07004384status_t AudioFlinger::MixerThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
4385{
Andy Hungf60abce2016-08-26 11:37:54 -07004386 status_t status;
4387 if (property_get_bool("af.patch_park", false /* default_value */)) {
4388 // Park FastMixer to avoid potential DOS issues with writing to the HAL
4389 // or if HAL does not properly lock against access.
4390 AutoPark<FastMixer> park(mFastMixer);
4391 status = PlaybackThread::releaseAudioPatch_l(handle);
4392 } else {
4393 status = PlaybackThread::releaseAudioPatch_l(handle);
4394 }
Eric Laurent054d9d32015-04-24 08:48:48 -07004395 return status;
4396}
4397
Eric Laurent1c333e22014-05-20 10:48:17 -07004398status_t AudioFlinger::PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
4399{
4400 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07004401
jiabinc52b1ff2019-10-31 17:20:42 -07004402 mPatch = audio_patch{};
4403 mOutDeviceTypeAddrs.clear();
Eric Laurent054d9d32015-04-24 08:48:48 -07004404
Mikhail Naganov9ee05402016-10-13 15:58:17 -07004405 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07004406 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
4407 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07004408 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07004409 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07004410 param.addInt(String8(AudioParameter::keyRouting), 0);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004411 status = mOutput->stream->setParameters(param.toString());
Eric Laurent1c333e22014-05-20 10:48:17 -07004412 }
4413 return status;
4414}
4415
Eric Laurent83b88082014-06-20 18:31:16 -07004416void AudioFlinger::PlaybackThread::addPatchTrack(const sp<PatchTrack>& track)
4417{
4418 Mutex::Autolock _l(mLock);
4419 mTracks.add(track);
4420}
4421
4422void AudioFlinger::PlaybackThread::deletePatchTrack(const sp<PatchTrack>& track)
4423{
4424 Mutex::Autolock _l(mLock);
4425 destroyTrack_l(track);
4426}
4427
Mikhail Naganovdc769682018-05-04 15:34:08 -07004428void AudioFlinger::PlaybackThread::toAudioPortConfig(struct audio_port_config *config)
Eric Laurent83b88082014-06-20 18:31:16 -07004429{
Mikhail Naganovdc769682018-05-04 15:34:08 -07004430 ThreadBase::toAudioPortConfig(config);
Eric Laurent83b88082014-06-20 18:31:16 -07004431 config->role = AUDIO_PORT_ROLE_SOURCE;
4432 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
4433 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07004434 if (mOutput && mOutput->flags != AUDIO_OUTPUT_FLAG_NONE) {
4435 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
4436 config->flags.output = mOutput->flags;
4437 }
Eric Laurent83b88082014-06-20 18:31:16 -07004438}
4439
Eric Laurent81784c32012-11-19 14:55:58 -08004440// ----------------------------------------------------------------------------
4441
4442AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
jiabinc52b1ff2019-10-31 17:20:42 -07004443 audio_io_handle_t id, bool systemReady, type_t type)
4444 : PlaybackThread(audioFlinger, output, id, type, systemReady),
Eric Laurent81784c32012-11-19 14:55:58 -08004445 // mAudioMixer below
4446 // mFastMixer below
Andy Hung2ddee192015-12-18 17:34:44 -08004447 mFastMixerFutex(0),
4448 mMasterMono(false)
Eric Laurent81784c32012-11-19 14:55:58 -08004449 // mOutputSink below
4450 // mPipeSink below
4451 // mNormalSink below
4452{
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01004453 setMasterBalance(audioFlinger->getMasterBalance_l());
jiabinc52b1ff2019-10-31 17:20:42 -07004454 ALOGV("MixerThread() id=%d type=%d", id, type);
Glenn Kasten49f36ba2017-12-06 13:02:02 -08004455 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%#x, mFrameSize=%zu, "
Glenn Kastenc42e9b42016-03-21 11:35:03 -07004456 "mFrameCount=%zu, mNormalFrameCount=%zu",
Eric Laurent81784c32012-11-19 14:55:58 -08004457 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
4458 mNormalFrameCount);
4459 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
4460
Andy Hungfbfc3952015-01-15 13:33:51 -08004461 if (type == DUPLICATING) {
4462 // The Duplicating thread uses the AudioMixer and delivers data to OutputTracks
4463 // (downstream MixerThreads) in DuplicatingThread::threadLoop_write().
4464 // Do not create or use mFastMixer, mOutputSink, mPipeSink, or mNormalSink.
4465 return;
4466 }
Eric Laurent81784c32012-11-19 14:55:58 -08004467 // create an NBAIO sink for the HAL output stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07004468 mOutputSink = new AudioStreamOutSink(output->stream);
Eric Laurent81784c32012-11-19 14:55:58 -08004469 size_t numCounterOffers = 0;
jiabin245cdd92018-12-07 17:55:15 -08004470 const NBAIO_Format offers[1] = {Format_from_SR_C(
4471 mSampleRate, mChannelCount + mHapticChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07004472#if !LOG_NDEBUG
4473 ssize_t index =
4474#else
4475 (void)
4476#endif
4477 mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08004478 ALOG_ASSERT(index == 0);
4479
4480 // initialize fast mixer depending on configuration
4481 bool initFastMixer;
4482 switch (kUseFastMixer) {
4483 case FastMixer_Never:
4484 initFastMixer = false;
4485 break;
4486 case FastMixer_Always:
4487 initFastMixer = true;
4488 break;
4489 case FastMixer_Static:
4490 case FastMixer_Dynamic:
Andy Hungfda69402017-02-15 14:33:12 -08004491 // FastMixer was designed to operate with a HAL that pulls at a regular rate,
4492 // where the period is less than an experimentally determined threshold that can be
4493 // scheduled reliably with CFS. However, the BT A2DP HAL is
4494 // bursty (does not pull at a regular rate) and so cannot operate with FastMixer.
4495 initFastMixer = mFrameCount < mNormalFrameCount
jiabinc52b1ff2019-10-31 17:20:42 -07004496 && Intersection(outDeviceTypes(), getAudioDeviceOutAllA2dpSet()).empty();
Eric Laurent81784c32012-11-19 14:55:58 -08004497 break;
4498 }
Andy Hungfda69402017-02-15 14:33:12 -08004499 ALOGW_IF(initFastMixer == false && mFrameCount < mNormalFrameCount,
4500 "FastMixer is preferred for this sink as frameCount %zu is less than threshold %zu",
4501 mFrameCount, mNormalFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08004502 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07004503 audio_format_t fastMixerFormat;
4504 if (mMixerBufferEnabled && mEffectBufferEnabled) {
4505 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
4506 } else {
4507 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
4508 }
4509 if (mFormat != fastMixerFormat) {
4510 // change our Sink format to accept our intermediate precision
4511 mFormat = fastMixerFormat;
4512 free(mSinkBuffer);
jiabin245cdd92018-12-07 17:55:15 -08004513 mFrameSize = audio_bytes_per_frame(mChannelCount + mHapticChannelCount, mFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07004514 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
4515 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
4516 }
Eric Laurent81784c32012-11-19 14:55:58 -08004517
4518 // create a MonoPipe to connect our submix to FastMixer
4519 NBAIO_Format format = mOutputSink->format();
Andy Hung8946a282018-04-19 20:04:56 -07004520
Andy Hung1258c1a2014-05-23 21:22:17 -07004521 // adjust format to match that of the Fast Mixer
Glenn Kasten49f36ba2017-12-06 13:02:02 -08004522 ALOGV("format changed from %#x to %#x", format.mFormat, fastMixerFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07004523 format.mFormat = fastMixerFormat;
4524 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
4525
Eric Laurent81784c32012-11-19 14:55:58 -08004526 // This pipe depth compensates for scheduling latency of the normal mixer thread.
4527 // When it wakes up after a maximum latency, it runs a few cycles quickly before
4528 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
4529 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
4530 const NBAIO_Format offers[1] = {format};
4531 size_t numCounterOffers = 0;
Andy Hung8946a282018-04-19 20:04:56 -07004532#if !LOG_NDEBUG
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07004533 ssize_t index =
4534#else
4535 (void)
4536#endif
4537 monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08004538 ALOG_ASSERT(index == 0);
4539 monoPipe->setAvgFrames((mScreenState & 1) ?
4540 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
4541 mPipeSink = monoPipe;
4542
Eric Laurent81784c32012-11-19 14:55:58 -08004543 // create fast mixer and configure it initially with just one fast track for our submix
Andy Hung8946a282018-04-19 20:04:56 -07004544 mFastMixer = new FastMixer(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08004545 FastMixerStateQueue *sq = mFastMixer->sq();
4546#ifdef STATE_QUEUE_DUMP
4547 sq->setObserverDump(&mStateQueueObserverDump);
4548 sq->setMutatorDump(&mStateQueueMutatorDump);
4549#endif
4550 FastMixerState *state = sq->begin();
4551 FastTrack *fastTrack = &state->mFastTracks[0];
4552 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
4553 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
4554 fastTrack->mVolumeProvider = NULL;
Mikhail Naganov55773032020-10-01 15:08:13 -07004555 fastTrack->mChannelMask = static_cast<audio_channel_mask_t>(
4556 mChannelMask | mHapticChannelMask); // mPipeSink channel mask for
4557 // audio to FastMixer
Andy Hunge8a1ced2014-05-09 15:02:21 -07004558 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
jiabin245cdd92018-12-07 17:55:15 -08004559 fastTrack->mHapticPlaybackEnabled = mHapticChannelMask != AUDIO_CHANNEL_NONE;
jiabine70bc7f2020-06-30 22:07:55 -07004560 fastTrack->mHapticIntensity = os::HapticScale::NONE;
Eric Laurent81784c32012-11-19 14:55:58 -08004561 fastTrack->mGeneration++;
4562 state->mFastTracksGen++;
4563 state->mTrackMask = 1;
4564 // fast mixer will use the HAL output sink
4565 state->mOutputSink = mOutputSink.get();
4566 state->mOutputSinkGen++;
4567 state->mFrameCount = mFrameCount;
jiabin245cdd92018-12-07 17:55:15 -08004568 // specify sink channel mask when haptic channel mask present as it can not
4569 // be calculated directly from channel count
4570 state->mSinkChannelMask = mHapticChannelMask == AUDIO_CHANNEL_NONE
Mikhail Naganov55773032020-10-01 15:08:13 -07004571 ? AUDIO_CHANNEL_NONE
4572 : static_cast<audio_channel_mask_t>(mChannelMask | mHapticChannelMask);
Eric Laurent81784c32012-11-19 14:55:58 -08004573 state->mCommand = FastMixerState::COLD_IDLE;
4574 // already done in constructor initialization list
4575 //mFastMixerFutex = 0;
4576 state->mColdFutexAddr = &mFastMixerFutex;
4577 state->mColdGen++;
4578 state->mDumpState = &mFastMixerDumpState;
Glenn Kasten9e58b552013-01-18 15:09:48 -08004579 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
4580 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08004581 sq->end();
4582 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
4583
Eric Tan0513b5d2018-09-17 10:32:48 -07004584 NBLog::thread_info_t info;
4585 info.id = mId;
4586 info.type = NBLog::FASTMIXER;
4587 mFastMixerNBLogWriter->log<NBLog::EVENT_THREAD_INFO>(info);
4588
Eric Laurent81784c32012-11-19 14:55:58 -08004589 // start the fast mixer
4590 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
4591 pid_t tid = mFastMixer->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07004592 sendPrioConfigEvent(getpid(), tid, kPriorityFastMixer, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08004593 stream()->setHalThreadPriority(kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08004594
4595#ifdef AUDIO_WATCHDOG
4596 // create and start the watchdog
4597 mAudioWatchdog = new AudioWatchdog();
4598 mAudioWatchdog->setDump(&mAudioWatchdogDump);
4599 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
4600 tid = mAudioWatchdog->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07004601 sendPrioConfigEvent(getpid(), tid, kPriorityFastMixer, false /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08004602#endif
Andy Hung8946a282018-04-19 20:04:56 -07004603 } else {
4604#ifdef TEE_SINK
4605 // Only use the MixerThread tee if there is no FastMixer.
4606 mTee.set(mOutputSink->format(), NBAIO_Tee::TEE_FLAG_OUTPUT_THREAD);
4607 mTee.setId(std::string("_") + std::to_string(mId) + "_M");
4608#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004609 }
4610
4611 switch (kUseFastMixer) {
4612 case FastMixer_Never:
4613 case FastMixer_Dynamic:
4614 mNormalSink = mOutputSink;
4615 break;
4616 case FastMixer_Always:
4617 mNormalSink = mPipeSink;
4618 break;
4619 case FastMixer_Static:
4620 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
4621 break;
4622 }
4623}
4624
4625AudioFlinger::MixerThread::~MixerThread()
4626{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004627 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004628 FastMixerStateQueue *sq = mFastMixer->sq();
4629 FastMixerState *state = sq->begin();
4630 if (state->mCommand == FastMixerState::COLD_IDLE) {
4631 int32_t old = android_atomic_inc(&mFastMixerFutex);
4632 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07004633 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08004634 }
4635 }
4636 state->mCommand = FastMixerState::EXIT;
4637 sq->end();
4638 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
4639 mFastMixer->join();
4640 // Though the fast mixer thread has exited, it's state queue is still valid.
4641 // We'll use that extract the final state which contains one remaining fast track
4642 // corresponding to our sub-mix.
4643 state = sq->begin();
4644 ALOG_ASSERT(state->mTrackMask == 1);
4645 FastTrack *fastTrack = &state->mFastTracks[0];
4646 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
4647 delete fastTrack->mBufferProvider;
4648 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004649 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08004650#ifdef AUDIO_WATCHDOG
4651 if (mAudioWatchdog != 0) {
4652 mAudioWatchdog->requestExit();
4653 mAudioWatchdog->requestExitAndWait();
4654 mAudioWatchdog.clear();
4655 }
4656#endif
4657 }
Glenn Kasten9e58b552013-01-18 15:09:48 -08004658 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08004659 delete mAudioMixer;
4660}
4661
4662
4663uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
4664{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004665 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004666 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
4667 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
4668 }
4669 return latency;
4670}
4671
Eric Laurentbfb1b832013-01-07 09:53:42 -08004672ssize_t AudioFlinger::MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08004673{
4674 // FIXME we should only do one push per cycle; confirm this is true
4675 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004676 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004677 FastMixerStateQueue *sq = mFastMixer->sq();
4678 FastMixerState *state = sq->begin();
4679 if (state->mCommand != FastMixerState::MIX_WRITE &&
4680 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
4681 if (state->mCommand == FastMixerState::COLD_IDLE) {
Eric Laurenta2ab4502015-09-09 12:25:51 -07004682
4683 // FIXME workaround for first HAL write being CPU bound on some devices
4684 ATRACE_BEGIN("write");
4685 mOutput->write((char *)mSinkBuffer, 0);
4686 ATRACE_END();
4687
Eric Laurent81784c32012-11-19 14:55:58 -08004688 int32_t old = android_atomic_inc(&mFastMixerFutex);
4689 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07004690 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08004691 }
4692#ifdef AUDIO_WATCHDOG
4693 if (mAudioWatchdog != 0) {
4694 mAudioWatchdog->resume();
4695 }
4696#endif
4697 }
4698 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kastend797a9d2015-03-02 14:19:25 -08004699#ifdef FAST_THREAD_STATISTICS
Glenn Kasten4182c4e2013-07-15 14:45:07 -07004700 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08004701 FastThreadDumpState::kSamplingNforLowRamDevice : FastThreadDumpState::kSamplingN);
Glenn Kastend797a9d2015-03-02 14:19:25 -08004702#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004703 sq->end();
4704 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
4705 if (kUseFastMixer == FastMixer_Dynamic) {
4706 mNormalSink = mPipeSink;
4707 }
4708 } else {
4709 sq->end(false /*didModify*/);
4710 }
4711 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004712 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08004713}
4714
4715void AudioFlinger::MixerThread::threadLoop_standby()
4716{
4717 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004718 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004719 FastMixerStateQueue *sq = mFastMixer->sq();
4720 FastMixerState *state = sq->begin();
4721 if (!(state->mCommand & FastMixerState::IDLE)) {
Andy Hung2148bf02016-11-28 19:01:02 -08004722 // Report any frames trapped in the Monopipe
4723 MonoPipe *monoPipe = (MonoPipe *)mPipeSink.get();
4724 const long long pipeFrames = monoPipe->maxFrames() - monoPipe->availableToWrite();
4725 mLocalLog.log("threadLoop_standby: framesWritten:%lld suspendedFrames:%lld "
4726 "monoPipeWritten:%lld monoPipeLeft:%lld",
4727 (long long)mFramesWritten, (long long)mSuspendedFrames,
4728 (long long)mPipeSink->framesWritten(), pipeFrames);
4729 mLocalLog.log("threadLoop_standby: %s", mTimestamp.toString().c_str());
4730
Eric Laurent81784c32012-11-19 14:55:58 -08004731 state->mCommand = FastMixerState::COLD_IDLE;
4732 state->mColdFutexAddr = &mFastMixerFutex;
4733 state->mColdGen++;
4734 mFastMixerFutex = 0;
4735 sq->end();
4736 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
4737 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
4738 if (kUseFastMixer == FastMixer_Dynamic) {
4739 mNormalSink = mOutputSink;
4740 }
4741#ifdef AUDIO_WATCHDOG
4742 if (mAudioWatchdog != 0) {
4743 mAudioWatchdog->pause();
4744 }
4745#endif
4746 } else {
4747 sq->end(false /*didModify*/);
4748 }
4749 }
4750 PlaybackThread::threadLoop_standby();
4751}
4752
Eric Laurentbfb1b832013-01-07 09:53:42 -08004753bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
4754{
4755 return false;
4756}
4757
4758bool AudioFlinger::PlaybackThread::shouldStandby_l()
4759{
4760 return !mStandby;
4761}
4762
4763bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
4764{
4765 Mutex::Autolock _l(mLock);
4766 return waitingAsyncCallback_l();
4767}
4768
Eric Laurent81784c32012-11-19 14:55:58 -08004769// shared by MIXER and DIRECT, overridden by DUPLICATING
4770void AudioFlinger::PlaybackThread::threadLoop_standby()
4771{
4772 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
Phil Burk062e67a2015-02-11 13:40:50 -08004773 mOutput->standby();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004774 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004775 // discard any pending drain or write ack by incrementing sequence
4776 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
4777 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004778 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004779 mCallbackThread->setWriteBlocked(mWriteAckSequence);
4780 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004781 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08004782 mHwPaused = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004783}
4784
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08004785void AudioFlinger::PlaybackThread::onAddNewTrack_l()
4786{
4787 ALOGV("signal playback thread");
4788 broadcast_l();
4789}
4790
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07004791void AudioFlinger::PlaybackThread::onAsyncError()
4792{
4793 for (int i = AUDIO_STREAM_SYSTEM; i < (int)AUDIO_STREAM_CNT; i++) {
4794 invalidateTracks((audio_stream_type_t)i);
4795 }
4796}
4797
Eric Laurent81784c32012-11-19 14:55:58 -08004798void AudioFlinger::MixerThread::threadLoop_mix()
4799{
Eric Laurent81784c32012-11-19 14:55:58 -08004800 // mix buffers...
Glenn Kastend79072e2016-01-06 08:41:20 -08004801 mAudioMixer->process();
Andy Hung25c2dac2014-02-27 14:56:00 -08004802 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004803 // increase sleep time progressively when application underrun condition clears.
4804 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
4805 // that a steady state of alternating ready/not ready conditions keeps the sleep time
4806 // such that we would underrun the audio HAL.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004807 if ((mSleepTimeUs == 0) && (sleepTimeShift > 0)) {
Eric Laurent81784c32012-11-19 14:55:58 -08004808 sleepTimeShift--;
4809 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004810 mSleepTimeUs = 0;
4811 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08004812 //TODO: delay standby when effects have a tail
Glenn Kasten4c053ea2014-09-28 14:41:07 -07004813
Eric Laurent81784c32012-11-19 14:55:58 -08004814}
4815
4816void AudioFlinger::MixerThread::threadLoop_sleepTime()
4817{
4818 // If no tracks are ready, sleep once for the duration of an output
4819 // buffer size, then write 0s to the output
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004820 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004821 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Andy Hung06d13222018-05-03 20:13:31 -07004822 if (mPipeSink.get() != nullptr && mPipeSink == mNormalSink) {
4823 // Using the Monopipe availableToWrite, we estimate the
4824 // sleep time to retry for more data (before we underrun).
4825 MonoPipe *monoPipe = static_cast<MonoPipe *>(mPipeSink.get());
4826 const ssize_t availableToWrite = mPipeSink->availableToWrite();
4827 const size_t pipeFrames = monoPipe->maxFrames();
4828 const size_t framesLeft = pipeFrames - max(availableToWrite, 0);
4829 // HAL_framecount <= framesDelay ~ framesLeft / 2 <= Normal_Mixer_framecount
4830 const size_t framesDelay = std::min(
4831 mNormalFrameCount, max(framesLeft / 2, mFrameCount));
4832 ALOGV("pipeFrames:%zu framesLeft:%zu framesDelay:%zu",
4833 pipeFrames, framesLeft, framesDelay);
4834 mSleepTimeUs = framesDelay * MICROS_PER_SECOND / mSampleRate;
4835 } else {
4836 mSleepTimeUs = mActiveSleepTimeUs >> sleepTimeShift;
4837 if (mSleepTimeUs < kMinThreadSleepTimeUs) {
4838 mSleepTimeUs = kMinThreadSleepTimeUs;
4839 }
4840 // reduce sleep time in case of consecutive application underruns to avoid
4841 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
4842 // duration we would end up writing less data than needed by the audio HAL if
4843 // the condition persists.
4844 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
4845 sleepTimeShift++;
4846 }
Eric Laurent81784c32012-11-19 14:55:58 -08004847 }
4848 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004849 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08004850 }
4851 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08004852 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
4853 // before effects processing or output.
4854 if (mMixerBufferValid) {
4855 memset(mMixerBuffer, 0, mMixerBufferSize);
4856 } else {
4857 memset(mSinkBuffer, 0, mSinkBufferSize);
4858 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004859 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08004860 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
4861 "anticipated start");
4862 }
4863 // TODO add standby time extension fct of effect tail
4864}
4865
4866// prepareTracks_l() must be called with ThreadBase::mLock held
4867AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
4868 Vector< sp<Track> > *tracksToRemove)
4869{
Andy Hungc0691382018-09-12 18:01:57 -07004870 // clean up deleted track ids in AudioMixer before allocating new tracks
4871 (void)mTracks.processDeletedTrackIds([this](int trackId) {
4872 // for each trackId, destroy it in the AudioMixer
4873 if (mAudioMixer->exists(trackId)) {
4874 mAudioMixer->destroy(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08004875 }
4876 });
Andy Hungc0691382018-09-12 18:01:57 -07004877 mTracks.clearDeletedTrackIds();
Eric Laurent81784c32012-11-19 14:55:58 -08004878
4879 mixer_state mixerStatus = MIXER_IDLE;
4880 // find out which tracks need to be processed
4881 size_t count = mActiveTracks.size();
4882 size_t mixedTracks = 0;
4883 size_t tracksWithEffect = 0;
4884 // counts only _active_ fast tracks
4885 size_t fastTracks = 0;
4886 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
4887
4888 float masterVolume = mMasterVolume;
4889 bool masterMute = mMasterMute;
4890
4891 if (masterMute) {
4892 masterVolume = 0;
4893 }
4894 // Delegate master volume control to effect in output mix effect chain if needed
4895 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
4896 if (chain != 0) {
4897 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
4898 chain->setVolume_l(&v, &v);
4899 masterVolume = (float)((v + (1 << 23)) >> 24);
4900 chain.clear();
4901 }
4902
4903 // prepare a new state to push
4904 FastMixerStateQueue *sq = NULL;
4905 FastMixerState *state = NULL;
4906 bool didModify = false;
4907 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Andy Hungf2285312017-02-14 18:31:59 -08004908 bool coldIdle = false;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004909 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004910 sq = mFastMixer->sq();
4911 state = sq->begin();
Andy Hungf2285312017-02-14 18:31:59 -08004912 coldIdle = state->mCommand == FastMixerState::COLD_IDLE;
Eric Laurent81784c32012-11-19 14:55:58 -08004913 }
4914
Andy Hung69aed5f2014-02-25 17:24:40 -08004915 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08004916 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08004917
Andy Hungbd3b2b02018-05-21 10:53:11 -07004918 // DeferredOperations handles statistics after setting mixerStatus.
4919 class DeferredOperations {
4920 public:
Andy Hungea840382020-05-05 21:50:17 -07004921 DeferredOperations(mixer_state *mixerStatus, ThreadMetrics *threadMetrics)
4922 : mMixerStatus(mixerStatus)
4923 , mThreadMetrics(threadMetrics) {}
Andy Hungbd3b2b02018-05-21 10:53:11 -07004924
4925 // when leaving scope, tally frames properly.
4926 ~DeferredOperations() {
4927 // Tally underrun frames only if we are actually mixing (MIXER_TRACKS_READY)
4928 // because that is when the underrun occurs.
4929 // We do not distinguish between FastTracks and NormalTracks here.
Andy Hungea840382020-05-05 21:50:17 -07004930 size_t maxUnderrunFrames = 0;
Andy Hungb68f5eb2019-12-03 16:49:17 -08004931 if (*mMixerStatus == MIXER_TRACKS_READY && mUnderrunFrames.size() > 0) {
Andy Hungbd3b2b02018-05-21 10:53:11 -07004932 for (const auto &underrun : mUnderrunFrames) {
Andy Hungc2b11cb2020-04-22 09:04:01 -07004933 underrun.first->tallyUnderrunFrames(underrun.second);
Andy Hungea840382020-05-05 21:50:17 -07004934 maxUnderrunFrames = max(underrun.second, maxUnderrunFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07004935 }
4936 }
Andy Hungea840382020-05-05 21:50:17 -07004937 // send the max underrun frames for this mixer period
4938 mThreadMetrics->logUnderrunFrames(maxUnderrunFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07004939 }
4940
4941 // tallyUnderrunFrames() is called to update the track counters
4942 // with the number of underrun frames for a particular mixer period.
4943 // We defer tallying until we know the final mixer status.
4944 void tallyUnderrunFrames(sp<Track> track, size_t underrunFrames) {
4945 mUnderrunFrames.emplace_back(track, underrunFrames);
4946 }
4947
4948 private:
4949 const mixer_state * const mMixerStatus;
Andy Hungea840382020-05-05 21:50:17 -07004950 ThreadMetrics * const mThreadMetrics;
Andy Hungbd3b2b02018-05-21 10:53:11 -07004951 std::vector<std::pair<sp<Track>, size_t>> mUnderrunFrames;
Andy Hungea840382020-05-05 21:50:17 -07004952 } deferredOperations(&mixerStatus, &mThreadMetrics);
Andy Hungb68f5eb2019-12-03 16:49:17 -08004953 // implicit nested scope for variable capture
Andy Hungbd3b2b02018-05-21 10:53:11 -07004954
jiabin245cdd92018-12-07 17:55:15 -08004955 bool noFastHapticTrack = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004956 for (size_t i=0 ; i<count ; i++) {
Andy Hungdae27702016-10-31 14:01:16 -07004957 const sp<Track> t = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08004958
4959 // this const just means the local variable doesn't change
4960 Track* const track = t.get();
4961
4962 // process fast tracks
4963 if (track->isFastTrack()) {
Andy Hungae22b482019-05-09 15:38:55 -07004964 LOG_ALWAYS_FATAL_IF(mFastMixer.get() == nullptr,
4965 "%s(%d): FastTrack(%d) present without FastMixer",
4966 __func__, id(), track->id());
4967
jiabin245cdd92018-12-07 17:55:15 -08004968 if (track->getHapticPlaybackEnabled()) {
4969 noFastHapticTrack = false;
4970 }
Eric Laurent81784c32012-11-19 14:55:58 -08004971
4972 // It's theoretically possible (though unlikely) for a fast track to be created
4973 // and then removed within the same normal mix cycle. This is not a problem, as
4974 // the track never becomes active so it's fast mixer slot is never touched.
4975 // The converse, of removing an (active) track and then creating a new track
4976 // at the identical fast mixer slot within the same normal mix cycle,
4977 // is impossible because the slot isn't marked available until the end of each cycle.
4978 int j = track->mFastIndex;
Glenn Kastendc2c50b2016-04-21 08:13:14 -07004979 ALOG_ASSERT(0 < j && j < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08004980 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
4981 FastTrack *fastTrack = &state->mFastTracks[j];
4982
4983 // Determine whether the track is currently in underrun condition,
4984 // and whether it had a recent underrun.
4985 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
4986 FastTrackUnderruns underruns = ftDump->mUnderruns;
4987 uint32_t recentFull = (underruns.mBitFields.mFull -
4988 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
4989 uint32_t recentPartial = (underruns.mBitFields.mPartial -
4990 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
4991 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
4992 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
4993 uint32_t recentUnderruns = recentPartial + recentEmpty;
4994 track->mObservedUnderruns = underruns;
4995 // don't count underruns that occur while stopping or pausing
4996 // or stopped which can occur when flush() is called while active
Andy Hungbd3b2b02018-05-21 10:53:11 -07004997 size_t underrunFrames = 0;
Glenn Kasten82aaf942013-07-17 16:05:07 -07004998 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
4999 recentUnderruns > 0) {
5000 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
Andy Hungbd3b2b02018-05-21 10:53:11 -07005001 underrunFrames = recentUnderruns * mFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08005002 }
Andy Hungbd3b2b02018-05-21 10:53:11 -07005003 // Immediately account for FastTrack underruns.
5004 track->mAudioTrackServerProxy->tallyUnderrunFrames(underrunFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08005005
5006 // This is similar to the state machine for normal tracks,
5007 // with a few modifications for fast tracks.
5008 bool isActive = true;
5009 switch (track->mState) {
5010 case TrackBase::STOPPING_1:
5011 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08005012 if (recentUnderruns > 0 || track->isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -08005013 track->mState = TrackBase::STOPPING_2;
5014 }
5015 break;
5016 case TrackBase::PAUSING:
5017 // ramp down is not yet implemented
5018 track->setPaused();
5019 break;
5020 case TrackBase::RESUMING:
5021 // ramp up is not yet implemented
5022 track->mState = TrackBase::ACTIVE;
5023 break;
5024 case TrackBase::ACTIVE:
5025 if (recentFull > 0 || recentPartial > 0) {
5026 // track has provided at least some frames recently: reset retry count
5027 track->mRetryCount = kMaxTrackRetries;
5028 }
5029 if (recentUnderruns == 0) {
5030 // no recent underruns: stay active
5031 break;
5032 }
5033 // there has recently been an underrun of some kind
5034 if (track->sharedBuffer() == 0) {
5035 // were any of the recent underruns "empty" (no frames available)?
5036 if (recentEmpty == 0) {
5037 // no, then ignore the partial underruns as they are allowed indefinitely
5038 break;
5039 }
5040 // there has recently been an "empty" underrun: decrement the retry counter
5041 if (--(track->mRetryCount) > 0) {
5042 break;
5043 }
5044 // indicate to client process that the track was disabled because of underrun;
5045 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08005046 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08005047 // remove from active list, but state remains ACTIVE [confusing but true]
5048 isActive = false;
5049 break;
5050 }
Chih-Hung Hsieh2b487032018-09-13 14:16:02 -07005051 FALLTHROUGH_INTENDED;
Eric Laurent81784c32012-11-19 14:55:58 -08005052 case TrackBase::STOPPING_2:
5053 case TrackBase::PAUSED:
Eric Laurent81784c32012-11-19 14:55:58 -08005054 case TrackBase::STOPPED:
5055 case TrackBase::FLUSHED: // flush() while active
5056 // Check for presentation complete if track is inactive
5057 // We have consumed all the buffers of this track.
5058 // This would be incomplete if we auto-paused on underrun
5059 {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005060 uint32_t latency = 0;
5061 status_t result = mOutput->stream->getLatency(&latency);
5062 ALOGE_IF(result != OK,
5063 "Error when retrieving output stream latency: %d", result);
5064 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08005065 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005066 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
5067 // track stays in active list until presentation is complete
5068 break;
5069 }
5070 }
5071 if (track->isStopping_2()) {
5072 track->mState = TrackBase::STOPPED;
5073 }
5074 if (track->isStopped()) {
5075 // Can't reset directly, as fast mixer is still polling this track
5076 // track->reset();
5077 // So instead mark this track as needing to be reset after push with ack
5078 resetMask |= 1 << i;
5079 }
5080 isActive = false;
5081 break;
5082 case TrackBase::IDLE:
5083 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08005084 LOG_ALWAYS_FATAL("unexpected track state %d", track->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08005085 }
5086
5087 if (isActive) {
5088 // was it previously inactive?
5089 if (!(state->mTrackMask & (1 << j))) {
5090 ExtendedAudioBufferProvider *eabp = track;
5091 VolumeProvider *vp = track;
5092 fastTrack->mBufferProvider = eabp;
5093 fastTrack->mVolumeProvider = vp;
Eric Laurent81784c32012-11-19 14:55:58 -08005094 fastTrack->mChannelMask = track->mChannelMask;
Andy Hunge8a1ced2014-05-09 15:02:21 -07005095 fastTrack->mFormat = track->mFormat;
jiabin245cdd92018-12-07 17:55:15 -08005096 fastTrack->mHapticPlaybackEnabled = track->getHapticPlaybackEnabled();
jiabin77270b82018-12-18 15:41:29 -08005097 fastTrack->mHapticIntensity = track->getHapticIntensity();
Eric Laurent81784c32012-11-19 14:55:58 -08005098 fastTrack->mGeneration++;
5099 state->mTrackMask |= 1 << j;
5100 didModify = true;
5101 // no acknowledgement required for newly active tracks
5102 }
Kevin Rocard12381092018-04-11 09:19:59 -07005103 sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
Eric Laurenteab90452019-06-24 15:17:46 -07005104 float volume;
5105 if (track->isPlaybackRestricted() || mStreamTypes[track->streamType()].mute) {
5106 volume = 0.f;
5107 } else {
5108 volume = masterVolume * mStreamTypes[track->streamType()].volume;
5109 }
5110
5111 handleVoipVolume_l(&volume);
5112
Eric Laurent81784c32012-11-19 14:55:58 -08005113 // cache the combined master volume and stream type volume for fast mixer; this
5114 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005115 const float vh = track->getVolumeHandler()->getVolume(
Eric Laurenteab90452019-06-24 15:17:46 -07005116 proxy->framesReleased()).first;
5117 volume *= vh;
Kevin Rocardb0eeaf122018-04-11 08:30:16 -07005118 track->mCachedVolume = volume;
Kevin Rocard12381092018-04-11 09:19:59 -07005119 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
5120 float vlf = volume * float_from_gain(gain_minifloat_unpack_left(vlr));
5121 float vrf = volume * float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurenteab90452019-06-24 15:17:46 -07005122
Kevin Rocard12381092018-04-11 09:19:59 -07005123 track->setFinalVolume((vlf + vrf) / 2.f);
Eric Laurent81784c32012-11-19 14:55:58 -08005124 ++fastTracks;
5125 } else {
5126 // was it previously active?
5127 if (state->mTrackMask & (1 << j)) {
5128 fastTrack->mBufferProvider = NULL;
5129 fastTrack->mGeneration++;
5130 state->mTrackMask &= ~(1 << j);
5131 didModify = true;
5132 // If any fast tracks were removed, we must wait for acknowledgement
5133 // because we're about to decrement the last sp<> on those tracks.
5134 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
5135 } else {
Glenn Kastenbf848af2017-12-22 11:55:01 -08005136 // ALOGW rather than LOG_ALWAYS_FATAL because it seems there are cases where an
5137 // AudioTrack may start (which may not be with a start() but with a write()
5138 // after underrun) and immediately paused or released. In that case the
5139 // FastTrack state hasn't had time to update.
5140 // TODO Remove the ALOGW when this theory is confirmed.
5141 ALOGW("fast track %d should have been active; "
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08005142 "mState=%d, mTrackMask=%#x, recentUnderruns=%u, isShared=%d",
5143 j, track->mState, state->mTrackMask, recentUnderruns,
5144 track->sharedBuffer() != 0);
Glenn Kastenbf848af2017-12-22 11:55:01 -08005145 // Since the FastMixer state already has the track inactive, do nothing here.
Eric Laurent81784c32012-11-19 14:55:58 -08005146 }
5147 tracksToRemove->add(track);
5148 // Avoids a misleading display in dumpsys
5149 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
5150 }
jiabin245cdd92018-12-07 17:55:15 -08005151 if (fastTrack->mHapticPlaybackEnabled != track->getHapticPlaybackEnabled()) {
5152 fastTrack->mHapticPlaybackEnabled = track->getHapticPlaybackEnabled();
5153 didModify = true;
5154 }
Eric Laurent81784c32012-11-19 14:55:58 -08005155 continue;
5156 }
5157
5158 { // local variable scope to avoid goto warning
5159
5160 audio_track_cblk_t* cblk = track->cblk();
5161
5162 // The first time a track is added we wait
5163 // for all its buffers to be filled before processing it
Andy Hungc0691382018-09-12 18:01:57 -07005164 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08005165
5166 // if an active track doesn't exist in the AudioMixer, create it.
Andy Hungc0691382018-09-12 18:01:57 -07005167 // use the trackId as the AudioMixer name.
5168 if (!mAudioMixer->exists(trackId)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08005169 status_t status = mAudioMixer->create(
Andy Hungc0691382018-09-12 18:01:57 -07005170 trackId,
Andy Hung1bc088a2018-02-09 15:57:31 -08005171 track->mChannelMask,
5172 track->mFormat,
5173 track->mSessionId);
5174 if (status != OK) {
Andy Hungc0691382018-09-12 18:01:57 -07005175 ALOGW("%s(): AudioMixer cannot create track(%d)"
5176 " mask %#x, format %#x, sessionId %d",
5177 __func__, trackId,
5178 track->mChannelMask, track->mFormat, track->mSessionId);
Andy Hung1bc088a2018-02-09 15:57:31 -08005179 tracksToRemove->add(track);
5180 track->invalidate(); // consider it dead.
5181 continue;
5182 }
5183 }
5184
Eric Laurent81784c32012-11-19 14:55:58 -08005185 // make sure that we have enough frames to mix one full buffer.
5186 // enforce this condition only once to enable draining the buffer in case the client
5187 // app does not call stop() and relies on underrun to stop:
5188 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
5189 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005190 size_t desiredFrames;
Andy Hung8edb8dc2015-03-26 19:13:55 -07005191 const uint32_t sampleRate = track->mAudioTrackServerProxy->getSampleRate();
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07005192 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07005193
5194 desiredFrames = sourceFramesNeededWithTimestretch(
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07005195 sampleRate, mNormalFrameCount, mSampleRate, playbackRate.mSpeed);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005196 // TODO: ONLY USED FOR LEGACY RESAMPLERS, remove when they are removed.
5197 // add frames already consumed but not yet released by the resampler
5198 // because mAudioTrackServerProxy->framesReady() will include these frames
Andy Hungc0691382018-09-12 18:01:57 -07005199 desiredFrames += mAudioMixer->getUnreleasedFrames(trackId);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005200
Eric Laurent81784c32012-11-19 14:55:58 -08005201 uint32_t minFrames = 1;
5202 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
5203 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005204 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08005205 }
Eric Laurent13e4c962013-12-20 17:36:01 -08005206
5207 size_t framesReady = track->framesReady();
Glenn Kastene7754022014-10-31 12:11:26 -07005208 if (ATRACE_ENABLED()) {
5209 // I wish we had formatted trace names
Andy Hung1bc088a2018-02-09 15:57:31 -08005210 std::string traceName("nRdy");
Andy Hungc0691382018-09-12 18:01:57 -07005211 traceName += std::to_string(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08005212 ATRACE_INT(traceName.c_str(), framesReady);
Glenn Kastene7754022014-10-31 12:11:26 -07005213 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005214 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08005215 !track->isPaused() && !track->isTerminated())
5216 {
Andy Hungc0691382018-09-12 18:01:57 -07005217 ALOGVV("track(%d) s=%08x [OK] on thread %p", trackId, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08005218
5219 mixedTracks++;
5220
Andy Hung69aed5f2014-02-25 17:24:40 -08005221 // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
5222 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08005223 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08005224 if (track->mainBuffer() != mSinkBuffer &&
5225 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08005226 if (mEffectBufferEnabled) {
5227 mEffectBufferValid = true; // Later can set directly.
5228 }
Eric Laurent81784c32012-11-19 14:55:58 -08005229 chain = getEffectChain_l(track->sessionId());
5230 // Delegate volume control to effect in track effect chain if needed
5231 if (chain != 0) {
5232 tracksWithEffect++;
5233 } else {
Andy Hungc0691382018-09-12 18:01:57 -07005234 ALOGW("prepareTracks_l(): track(%d) attached to effect but no chain found on "
Eric Laurent81784c32012-11-19 14:55:58 -08005235 "session %d",
Andy Hungc0691382018-09-12 18:01:57 -07005236 trackId, track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08005237 }
5238 }
5239
5240
5241 int param = AudioMixer::VOLUME;
5242 if (track->mFillingUpStatus == Track::FS_FILLED) {
5243 // no ramp for the first volume setting
5244 track->mFillingUpStatus = Track::FS_ACTIVE;
5245 if (track->mState == TrackBase::RESUMING) {
5246 track->mState = TrackBase::ACTIVE;
Revathi Uddaraju453bcb52017-08-14 14:19:40 +08005247 // If a new track is paused immediately after start, do not ramp on resume.
5248 if (cblk->mServer != 0) {
5249 param = AudioMixer::RAMP_VOLUME;
5250 }
Eric Laurent81784c32012-11-19 14:55:58 -08005251 }
Andy Hungc0691382018-09-12 18:01:57 -07005252 mAudioMixer->setParameter(trackId, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Eric Laurent7c29ec92017-09-20 17:54:22 -07005253 mLeftVolFloat = -1.0;
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005254 // FIXME should not make a decision based on mServer
5255 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005256 // If the track is stopped before the first frame was mixed,
5257 // do not apply ramp
5258 param = AudioMixer::RAMP_VOLUME;
5259 }
5260
5261 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07005262 uint32_t vl, vr; // in U8.24 integer format
5263 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Eric Laurent7c29ec92017-09-20 17:54:22 -07005264 // read original volumes with volume control
Eric Laurenteab90452019-06-24 15:17:46 -07005265 float v = masterVolume * mStreamTypes[track->streamType()].volume;
Andy Hung333ab962019-05-28 20:23:35 -07005266 // Always fetch volumeshaper volume to ensure state is updated.
5267 const sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
5268 const float vh = track->getVolumeHandler()->getVolume(
5269 track->mAudioTrackServerProxy->framesReleased()).first;
Eric Laurent7c29ec92017-09-20 17:54:22 -07005270
Eric Laurenteab90452019-06-24 15:17:46 -07005271 if (mStreamTypes[track->streamType()].mute || track->isPlaybackRestricted()) {
5272 v = 0;
5273 }
5274
5275 handleVoipVolume_l(&v);
5276
5277 if (track->isPausing()) {
Andy Hung6be49402014-05-30 10:42:03 -07005278 vl = vr = 0;
5279 vlf = vrf = vaf = 0.;
Eric Laurenteab90452019-06-24 15:17:46 -07005280 track->setPaused();
Eric Laurent81784c32012-11-19 14:55:58 -08005281 } else {
Glenn Kastenc56f3422014-03-21 17:53:17 -07005282 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07005283 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
5284 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08005285 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07005286 if (vlf > GAIN_FLOAT_UNITY) {
5287 ALOGV("Track left volume out of range: %.3g", vlf);
5288 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08005289 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07005290 if (vrf > GAIN_FLOAT_UNITY) {
5291 ALOGV("Track right volume out of range: %.3g", vrf);
5292 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08005293 }
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005294 // now apply the master volume and stream type volume and shaper volume
5295 vlf *= v * vh;
5296 vrf *= v * vh;
Eric Laurent81784c32012-11-19 14:55:58 -08005297 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07005298 // then derive vl and vr as U8.24 versions for the effect chain
5299 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
5300 vl = (uint32_t) (scaleto8_24 * vlf);
5301 vr = (uint32_t) (scaleto8_24 * vrf);
5302 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08005303 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08005304 // send level comes from shared memory and so may be corrupt
5305 if (sendLevel > MAX_GAIN_INT) {
5306 ALOGV("Track send level out of range: %04X", sendLevel);
5307 sendLevel = MAX_GAIN_INT;
5308 }
Andy Hung6be49402014-05-30 10:42:03 -07005309 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
5310 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08005311 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005312
Kevin Rocard12381092018-04-11 09:19:59 -07005313 track->setFinalVolume((vrf + vlf) / 2.f);
5314
Eric Laurent81784c32012-11-19 14:55:58 -08005315 // Delegate volume control to effect in track effect chain if needed
5316 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
5317 // Do not ramp volume if volume is controlled by effect
5318 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08005319 // Update remaining floating point volume levels
5320 vlf = (float)vl / (1 << 24);
5321 vrf = (float)vr / (1 << 24);
Eric Laurent81784c32012-11-19 14:55:58 -08005322 track->mHasVolumeController = true;
5323 } else {
5324 // force no volume ramp when volume controller was just disabled or removed
5325 // from effect chain to avoid volume spike
5326 if (track->mHasVolumeController) {
5327 param = AudioMixer::VOLUME;
5328 }
5329 track->mHasVolumeController = false;
5330 }
5331
Eric Laurent81784c32012-11-19 14:55:58 -08005332 // XXX: these things DON'T need to be done each time
Andy Hungc0691382018-09-12 18:01:57 -07005333 mAudioMixer->setBufferProvider(trackId, track);
5334 mAudioMixer->enable(trackId);
Eric Laurent81784c32012-11-19 14:55:58 -08005335
Andy Hungc0691382018-09-12 18:01:57 -07005336 mAudioMixer->setParameter(trackId, param, AudioMixer::VOLUME0, &vlf);
5337 mAudioMixer->setParameter(trackId, param, AudioMixer::VOLUME1, &vrf);
5338 mAudioMixer->setParameter(trackId, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08005339 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005340 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005341 AudioMixer::TRACK,
5342 AudioMixer::FORMAT, (void *)track->format());
5343 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005344 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005345 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00005346 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Andy Hung9a592762014-07-21 21:56:01 -07005347 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005348 trackId,
Andy Hung9a592762014-07-21 21:56:01 -07005349 AudioMixer::TRACK,
jiabin245cdd92018-12-07 17:55:15 -08005350 AudioMixer::MIXER_CHANNEL_MASK,
5351 (void *)(uintptr_t)(mChannelMask | mHapticChannelMask));
Glenn Kastene3aa6592012-12-04 12:22:46 -08005352 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07005353 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Andy Hung333ab962019-05-28 20:23:35 -07005354 uint32_t reqSampleRate = proxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08005355 if (reqSampleRate == 0) {
5356 reqSampleRate = mSampleRate;
5357 } else if (reqSampleRate > maxSampleRate) {
5358 reqSampleRate = maxSampleRate;
5359 }
Eric Laurent81784c32012-11-19 14:55:58 -08005360 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005361 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005362 AudioMixer::RESAMPLE,
5363 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00005364 (void *)(uintptr_t)reqSampleRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005365
Andy Hung333ab962019-05-28 20:23:35 -07005366 AudioPlaybackRate playbackRate = proxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07005367 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005368 trackId,
Andy Hung8edb8dc2015-03-26 19:13:55 -07005369 AudioMixer::TIMESTRETCH,
5370 AudioMixer::PLAYBACK_RATE,
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07005371 &playbackRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005372
Andy Hung69aed5f2014-02-25 17:24:40 -08005373 /*
5374 * Select the appropriate output buffer for the track.
5375 *
Andy Hung98ef9782014-03-04 14:46:50 -08005376 * Tracks with effects go into their own effects chain buffer
5377 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08005378 *
5379 * Other tracks can use mMixerBuffer for higher precision
5380 * channel accumulation. If this buffer is enabled
5381 * (mMixerBufferEnabled true), then selected tracks will accumulate
5382 * into it.
5383 *
5384 */
5385 if (mMixerBufferEnabled
5386 && (track->mainBuffer() == mSinkBuffer
5387 || track->mainBuffer() == mMixerBuffer)) {
5388 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005389 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08005390 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08005391 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
Andy Hung69aed5f2014-02-25 17:24:40 -08005392 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005393 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08005394 AudioMixer::TRACK,
5395 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
5396 // TODO: override track->mainBuffer()?
5397 mMixerBufferValid = true;
5398 } else {
5399 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005400 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08005401 AudioMixer::TRACK,
rago94a1ee82017-07-21 15:11:02 -07005402 AudioMixer::MIXER_FORMAT, (void *)EFFECT_BUFFER_FORMAT);
Andy Hung69aed5f2014-02-25 17:24:40 -08005403 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005404 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08005405 AudioMixer::TRACK,
5406 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
5407 }
Eric Laurent81784c32012-11-19 14:55:58 -08005408 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005409 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005410 AudioMixer::TRACK,
5411 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
jiabin245cdd92018-12-07 17:55:15 -08005412 mAudioMixer->setParameter(
5413 trackId,
5414 AudioMixer::TRACK,
5415 AudioMixer::HAPTIC_ENABLED, (void *)(uintptr_t)track->getHapticPlaybackEnabled());
jiabin77270b82018-12-18 15:41:29 -08005416 mAudioMixer->setParameter(
5417 trackId,
5418 AudioMixer::TRACK,
5419 AudioMixer::HAPTIC_INTENSITY, (void *)(uintptr_t)track->getHapticIntensity());
Eric Laurent81784c32012-11-19 14:55:58 -08005420
5421 // reset retry count
5422 track->mRetryCount = kMaxTrackRetries;
5423
5424 // If one track is ready, set the mixer ready if:
5425 // - the mixer was not ready during previous round OR
5426 // - no other track is not ready
5427 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
5428 mixerStatus != MIXER_TRACKS_ENABLED) {
5429 mixerStatus = MIXER_TRACKS_READY;
5430 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08005431
5432 // Enable the next few lines to instrument a test for underrun log handling.
5433 // TODO: Remove when we have a better way of testing the underrun log.
5434#if 0
5435 static int i;
5436 if ((++i & 0xf) == 0) {
5437 deferredOperations.tallyUnderrunFrames(track, 10 /* underrunFrames */);
5438 }
5439#endif
Eric Laurent81784c32012-11-19 14:55:58 -08005440 } else {
Andy Hungbd3b2b02018-05-21 10:53:11 -07005441 size_t underrunFrames = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005442 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Andy Hungb68f5eb2019-12-03 16:49:17 -08005443 ALOGV("track(%d) underrun, track state %s framesReady(%zu) < framesDesired(%zd)",
5444 trackId, track->getTrackStateAsString(), framesReady, desiredFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07005445 underrunFrames = desiredFrames;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005446 }
Andy Hungbd3b2b02018-05-21 10:53:11 -07005447 deferredOperations.tallyUnderrunFrames(track, underrunFrames);
Phil Burk2812d9e2016-01-04 10:34:30 -08005448
Eric Laurent81784c32012-11-19 14:55:58 -08005449 // clear effect chain input buffer if an active track underruns to avoid sending
5450 // previous audio buffer again to effects
5451 chain = getEffectChain_l(track->sessionId());
5452 if (chain != 0) {
5453 chain->clearInputBuffer();
5454 }
5455
Andy Hungc0691382018-09-12 18:01:57 -07005456 ALOGVV("track(%d) s=%08x [NOT READY] on thread %p", trackId, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08005457 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
5458 track->isStopped() || track->isPaused()) {
5459 // We have consumed all the buffers of this track.
5460 // Remove it from the list of active tracks.
5461 // TODO: use actual buffer filling status instead of latency when available from
5462 // audio HAL
5463 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08005464 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005465 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
5466 if (track->isStopped()) {
5467 track->reset();
5468 }
5469 tracksToRemove->add(track);
5470 }
5471 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08005472 // No buffers for this track. Give it a few chances to
5473 // fill a buffer, then remove it from active list.
5474 if (--(track->mRetryCount) <= 0) {
Andy Hungc0691382018-09-12 18:01:57 -07005475 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p",
5476 trackId, this);
Eric Laurent81784c32012-11-19 14:55:58 -08005477 tracksToRemove->add(track);
5478 // indicate to client process that the track was disabled because of underrun;
5479 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08005480 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08005481 // If one track is not ready, mark the mixer also not ready if:
5482 // - the mixer was ready during previous round OR
5483 // - no other track is ready
5484 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
5485 mixerStatus != MIXER_TRACKS_READY) {
5486 mixerStatus = MIXER_TRACKS_ENABLED;
5487 }
5488 }
Andy Hungc0691382018-09-12 18:01:57 -07005489 mAudioMixer->disable(trackId);
Eric Laurent81784c32012-11-19 14:55:58 -08005490 }
5491
5492 } // local variable scope to avoid goto warning
Eric Laurent81784c32012-11-19 14:55:58 -08005493
5494 }
5495
jiabin245cdd92018-12-07 17:55:15 -08005496 if (mHapticChannelMask != AUDIO_CHANNEL_NONE && sq != NULL) {
5497 // When there is no fast track playing haptic and FastMixer exists,
5498 // enabling the first FastTrack, which provides mixed data from normal
5499 // tracks, to play haptic data.
5500 FastTrack *fastTrack = &state->mFastTracks[0];
5501 if (fastTrack->mHapticPlaybackEnabled != noFastHapticTrack) {
5502 fastTrack->mHapticPlaybackEnabled = noFastHapticTrack;
5503 didModify = true;
5504 }
5505 }
5506
Eric Laurent81784c32012-11-19 14:55:58 -08005507 // Push the new FastMixer state if necessary
5508 bool pauseAudioWatchdog = false;
5509 if (didModify) {
5510 state->mFastTracksGen++;
5511 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
5512 if (kUseFastMixer == FastMixer_Dynamic &&
5513 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
5514 state->mCommand = FastMixerState::COLD_IDLE;
5515 state->mColdFutexAddr = &mFastMixerFutex;
5516 state->mColdGen++;
5517 mFastMixerFutex = 0;
5518 if (kUseFastMixer == FastMixer_Dynamic) {
5519 mNormalSink = mOutputSink;
5520 }
5521 // If we go into cold idle, need to wait for acknowledgement
5522 // so that fast mixer stops doing I/O.
5523 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
5524 pauseAudioWatchdog = true;
5525 }
Eric Laurent81784c32012-11-19 14:55:58 -08005526 }
5527 if (sq != NULL) {
5528 sq->end(didModify);
Andy Hungf2285312017-02-14 18:31:59 -08005529 // No need to block if the FastMixer is in COLD_IDLE as the FastThread
5530 // is not active. (We BLOCK_UNTIL_ACKED when entering COLD_IDLE
5531 // when bringing the output sink into standby.)
5532 //
5533 // We will get the latest FastMixer state when we come out of COLD_IDLE.
5534 //
5535 // This occurs with BT suspend when we idle the FastMixer with
5536 // active tracks, which may be added or removed.
5537 sq->push(coldIdle ? FastMixerStateQueue::BLOCK_NEVER : block);
Eric Laurent81784c32012-11-19 14:55:58 -08005538 }
5539#ifdef AUDIO_WATCHDOG
5540 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
5541 mAudioWatchdog->pause();
5542 }
5543#endif
5544
5545 // Now perform the deferred reset on fast tracks that have stopped
5546 while (resetMask != 0) {
5547 size_t i = __builtin_ctz(resetMask);
5548 ALOG_ASSERT(i < count);
5549 resetMask &= ~(1 << i);
Andy Hungdae27702016-10-31 14:01:16 -07005550 sp<Track> track = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08005551 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
5552 track->reset();
5553 }
5554
Andy Hung80d03d22018-04-10 10:32:11 -07005555 // Track destruction may occur outside of threadLoop once it is removed from active tracks.
5556 // Ensure the AudioMixer doesn't have a raw "buffer provider" pointer to the track if
5557 // it ceases to be active, to allow safe removal from the AudioMixer at the start
5558 // of prepareTracks_l(); this releases any outstanding buffer back to the track.
5559 // See also the implementation of destroyTrack_l().
5560 for (const auto &track : *tracksToRemove) {
Andy Hungc0691382018-09-12 18:01:57 -07005561 const int trackId = track->id();
5562 if (mAudioMixer->exists(trackId)) { // Normal tracks here, fast tracks in FastMixer.
5563 mAudioMixer->setBufferProvider(trackId, nullptr /* bufferProvider */);
Andy Hung80d03d22018-04-10 10:32:11 -07005564 }
5565 }
5566
Eric Laurent81784c32012-11-19 14:55:58 -08005567 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08005568 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08005569
Eric Laurent97d547d2014-09-02 14:45:53 -07005570 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0) {
5571 mEffectBufferValid = true;
Marco Nelissenac302142014-10-20 13:15:38 -07005572 }
5573
5574 if (mEffectBufferValid) {
Marco Nelissen57088b52014-10-17 16:39:39 -07005575 // as long as there are effects we should clear the effects buffer, to avoid
5576 // passing a non-clean buffer to the effect chain
5577 memset(mEffectBuffer, 0, mEffectBufferSize);
Eric Laurent97d547d2014-09-02 14:45:53 -07005578 }
Andy Hung69aed5f2014-02-25 17:24:40 -08005579 // sink or mix buffer must be cleared if all tracks are connected to an
5580 // effect chain as in this case the mixer will not write to the sink or mix buffer
5581 // and track effects will accumulate into it
Eric Laurentbfb1b832013-01-07 09:53:42 -08005582 if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
5583 (mixedTracks == 0 && fastTracks > 0))) {
Eric Laurent81784c32012-11-19 14:55:58 -08005584 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08005585 if (mMixerBufferValid) {
5586 memset(mMixerBuffer, 0, mMixerBufferSize);
5587 // TODO: In testing, mSinkBuffer below need not be cleared because
5588 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
5589 // after mixing.
5590 //
5591 // To enforce this guarantee:
5592 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
5593 // (mixedTracks == 0 && fastTracks > 0))
5594 // must imply MIXER_TRACKS_READY.
5595 // Later, we may clear buffers regardless, and skip much of this logic.
5596 }
Andy Hung98ef9782014-03-04 14:46:50 -08005597 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07005598 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08005599 }
5600
5601 // if any fast tracks, then status is ready
5602 mMixerStatusIgnoringFastTracks = mixerStatus;
5603 if (fastTracks > 0) {
5604 mixerStatus = MIXER_TRACKS_READY;
5605 }
5606 return mixerStatus;
5607}
5608
Eric Laurentad7dd962016-09-22 12:38:37 -07005609// trackCountForUid_l() must be called with ThreadBase::mLock held
Andy Hung1bc088a2018-02-09 15:57:31 -08005610uint32_t AudioFlinger::PlaybackThread::trackCountForUid_l(uid_t uid) const
Eric Laurentad7dd962016-09-22 12:38:37 -07005611{
5612 uint32_t trackCount = 0;
5613 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hung1f12a8a2016-11-07 16:10:30 -08005614 if (mTracks[i]->uid() == uid) {
Eric Laurentad7dd962016-09-22 12:38:37 -07005615 trackCount++;
5616 }
5617 }
5618 return trackCount;
5619}
5620
Andy Hung1bc088a2018-02-09 15:57:31 -08005621// isTrackAllowed_l() must be called with ThreadBase::mLock held
5622bool AudioFlinger::MixerThread::isTrackAllowed_l(
5623 audio_channel_mask_t channelMask, audio_format_t format,
5624 audio_session_t sessionId, uid_t uid) const
Eric Laurent81784c32012-11-19 14:55:58 -08005625{
Andy Hung1bc088a2018-02-09 15:57:31 -08005626 if (!PlaybackThread::isTrackAllowed_l(channelMask, format, sessionId, uid)) {
5627 return false;
Eric Laurentad7dd962016-09-22 12:38:37 -07005628 }
Andy Hung1bc088a2018-02-09 15:57:31 -08005629 // Check validity as we don't call AudioMixer::create() here.
Mikhail Naganov7ad7a252019-07-30 14:42:32 -07005630 if (!mAudioMixer->isValidFormat(format)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08005631 ALOGW("%s: invalid format: %#x", __func__, format);
5632 return false;
5633 }
Mikhail Naganov7ad7a252019-07-30 14:42:32 -07005634 if (!mAudioMixer->isValidChannelMask(channelMask)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08005635 ALOGW("%s: invalid channelMask: %#x", __func__, channelMask);
5636 return false;
5637 }
5638 return true;
Eric Laurent81784c32012-11-19 14:55:58 -08005639}
5640
Eric Laurent10351942014-05-08 18:49:52 -07005641// checkForNewParameter_l() must be called with ThreadBase::mLock held
5642bool AudioFlinger::MixerThread::checkForNewParameter_l(const String8& keyValuePair,
5643 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08005644{
Eric Laurent81784c32012-11-19 14:55:58 -08005645 bool reconfig = false;
Eric Laurent10351942014-05-08 18:49:52 -07005646 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08005647
Glenn Kastenc05b8d72016-03-24 09:48:17 -07005648 AutoPark<FastMixer> park(mFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08005649
Eric Laurent10351942014-05-08 18:49:52 -07005650 AudioParameter param = AudioParameter(keyValuePair);
5651 int value;
5652 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
5653 reconfig = true;
5654 }
5655 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07005656 if (!isValidPcmSinkFormat((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07005657 status = BAD_VALUE;
5658 } else {
5659 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08005660 reconfig = true;
5661 }
Eric Laurent10351942014-05-08 18:49:52 -07005662 }
5663 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07005664 if (!isValidPcmSinkChannelMask((audio_channel_mask_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07005665 status = BAD_VALUE;
5666 } else {
5667 // no need to save value, since it's constant
5668 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08005669 }
Eric Laurent10351942014-05-08 18:49:52 -07005670 }
5671 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
5672 // do not accept frame count changes if tracks are open as the track buffer
5673 // size depends on frame count and correct behavior would not be guaranteed
5674 // if frame count is changed after track creation
5675 if (!mTracks.isEmpty()) {
5676 status = INVALID_OPERATION;
5677 } else {
5678 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08005679 }
Eric Laurent10351942014-05-08 18:49:52 -07005680 }
5681 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07005682 LOG_FATAL("Should not set routing device in MixerThread");
Eric Laurent10351942014-05-08 18:49:52 -07005683 }
Eric Laurent81784c32012-11-19 14:55:58 -08005684
Eric Laurent10351942014-05-08 18:49:52 -07005685 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005686 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07005687 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08005688 mOutput->standby();
Andy Hungcf10d742020-04-28 15:38:24 -07005689 if (!mStandby) {
5690 mThreadMetrics.logEndInterval();
5691 mStandby = true;
5692 }
Eric Laurent10351942014-05-08 18:49:52 -07005693 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005694 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent81784c32012-11-19 14:55:58 -08005695 }
Eric Laurent10351942014-05-08 18:49:52 -07005696 if (status == NO_ERROR && reconfig) {
5697 readOutputParameters_l();
5698 delete mAudioMixer;
5699 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
Andy Hung1bc088a2018-02-09 15:57:31 -08005700 for (const auto &track : mTracks) {
Andy Hungc0691382018-09-12 18:01:57 -07005701 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08005702 status_t status = mAudioMixer->create(
Andy Hungc0691382018-09-12 18:01:57 -07005703 trackId,
Andy Hung1bc088a2018-02-09 15:57:31 -08005704 track->mChannelMask,
5705 track->mFormat,
5706 track->mSessionId);
5707 ALOGW_IF(status != NO_ERROR,
Andy Hungc0691382018-09-12 18:01:57 -07005708 "%s(): AudioMixer cannot create track(%d)"
5709 " mask %#x, format %#x, sessionId %d",
Andy Hung1bc088a2018-02-09 15:57:31 -08005710 __func__,
Andy Hungc0691382018-09-12 18:01:57 -07005711 trackId, track->mChannelMask, track->mFormat, track->mSessionId);
Eric Laurent10351942014-05-08 18:49:52 -07005712 }
Eric Laurent73e26b62015-04-27 16:55:58 -07005713 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07005714 }
Eric Laurent81784c32012-11-19 14:55:58 -08005715 }
5716
Dean Wheatley68918102021-03-19 22:09:19 +11005717 return reconfig;
Eric Laurent81784c32012-11-19 14:55:58 -08005718}
5719
5720
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07005721void AudioFlinger::MixerThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -08005722{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07005723 PlaybackThread::dumpInternals_l(fd, args);
Andy Hung40eb1a12015-06-18 13:42:02 -07005724 dprintf(fd, " Thread throttle time (msecs): %u\n", mThreadThrottleTimeMs);
Andy Hung8ed196a2018-01-05 13:21:11 -08005725 dprintf(fd, " AudioMixer tracks: %s\n", mAudioMixer->trackNames().c_str());
Andy Hung2ddee192015-12-18 17:34:44 -08005726 dprintf(fd, " Master mono: %s\n", mMasterMono ? "on" : "off");
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01005727 dprintf(fd, " Master balance: %f (%s)\n", mMasterBalance.load(),
5728 (hasFastMixer() ? std::to_string(mFastMixer->getMasterBalance())
5729 : mBalance.toString()).c_str());
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08005730 if (hasFastMixer()) {
5731 dprintf(fd, " FastMixer thread %p tid=%d", mFastMixer.get(), mFastMixer->getTid());
5732
5733 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
5734 // while we are dumping it. It may be inconsistent, but it won't mutate!
5735 // This is a large object so we place it on the heap.
5736 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
Eric Tan2942a4e2018-09-12 17:41:27 -07005737 const std::unique_ptr<FastMixerDumpState> copy =
5738 std::make_unique<FastMixerDumpState>(mFastMixerDumpState);
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08005739 copy->dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08005740
5741#ifdef STATE_QUEUE_DUMP
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08005742 // Similar for state queue
5743 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
5744 observerCopy.dump(fd);
5745 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
5746 mutatorCopy.dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08005747#endif
5748
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08005749#ifdef AUDIO_WATCHDOG
5750 if (mAudioWatchdog != 0) {
5751 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
5752 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
5753 wdCopy.dump(fd);
5754 }
5755#endif
5756
5757 } else {
5758 dprintf(fd, " No FastMixer\n");
5759 }
Eric Laurent81784c32012-11-19 14:55:58 -08005760}
5761
5762uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
5763{
5764 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
5765}
5766
5767uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
5768{
5769 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
5770}
5771
5772void AudioFlinger::MixerThread::cacheParameters_l()
5773{
5774 PlaybackThread::cacheParameters_l();
5775
5776 // FIXME: Relaxed timing because of a certain device that can't meet latency
5777 // Should be reduced to 2x after the vendor fixes the driver issue
5778 // increase threshold again due to low power audio mode. The way this warning
5779 // threshold is calculated and its usefulness should be reconsidered anyway.
5780 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
5781}
5782
5783// ----------------------------------------------------------------------------
5784
5785AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
jiabinc52b1ff2019-10-31 17:20:42 -07005786 AudioStreamOut* output, audio_io_handle_t id, ThreadBase::type_t type, bool systemReady)
5787 : PlaybackThread(audioFlinger, output, id, type, systemReady)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005788{
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01005789 setMasterBalance(audioFlinger->getMasterBalance_l());
Eric Laurentbfb1b832013-01-07 09:53:42 -08005790}
5791
Eric Laurent81784c32012-11-19 14:55:58 -08005792AudioFlinger::DirectOutputThread::~DirectOutputThread()
5793{
5794}
5795
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07005796void AudioFlinger::DirectOutputThread::dumpInternals_l(int fd, const Vector<String16>& args)
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01005797{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07005798 PlaybackThread::dumpInternals_l(fd, args);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01005799 dprintf(fd, " Master balance: %f Left: %f Right: %f\n",
5800 mMasterBalance.load(), mMasterBalanceLeft, mMasterBalanceRight);
5801}
5802
5803void AudioFlinger::DirectOutputThread::setMasterBalance(float balance)
5804{
5805 Mutex::Autolock _l(mLock);
5806 if (mMasterBalance != balance) {
5807 mMasterBalance.store(balance);
5808 mBalance.computeStereoBalance(balance, &mMasterBalanceLeft, &mMasterBalanceRight);
5809 broadcast_l();
5810 }
5811}
5812
Eric Laurent5850c4c2016-11-10 13:04:31 -08005813void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005814{
Eric Laurentbfb1b832013-01-07 09:53:42 -08005815 float left, right;
5816
Andy Hung333ab962019-05-28 20:23:35 -07005817 // Ensure volumeshaper state always advances even when muted.
5818 const sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
5819 const auto [shaperVolume, shaperActive] = track->getVolumeHandler()->getVolume(
5820 proxy->framesReleased());
5821 mVolumeShaperActive = shaperActive;
5822
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08005823 if (mMasterMute || mStreamTypes[track->streamType()].mute || track->isPlaybackRestricted()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08005824 left = right = 0;
5825 } else {
5826 float typeVolume = mStreamTypes[track->streamType()].volume;
Andy Hung333ab962019-05-28 20:23:35 -07005827 const float v = mMasterVolume * typeVolume * shaperVolume;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005828
Glenn Kastenc56f3422014-03-21 17:53:17 -07005829 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
5830 left = float_from_gain(gain_minifloat_unpack_left(vlr));
5831 if (left > GAIN_FLOAT_UNITY) {
5832 left = GAIN_FLOAT_UNITY;
5833 }
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01005834 left *= v * mMasterBalanceLeft; // DirectOutputThread balance applied as track volume
Glenn Kastenc56f3422014-03-21 17:53:17 -07005835 right = float_from_gain(gain_minifloat_unpack_right(vlr));
5836 if (right > GAIN_FLOAT_UNITY) {
5837 right = GAIN_FLOAT_UNITY;
5838 }
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01005839 right *= v * mMasterBalanceRight;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005840 }
5841
5842 if (lastTrack) {
Kevin Rocard12381092018-04-11 09:19:59 -07005843 track->setFinalVolume((left + right) / 2.f);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005844 if (left != mLeftVolFloat || right != mRightVolFloat) {
5845 mLeftVolFloat = left;
5846 mRightVolFloat = right;
5847
Eric Laurentbfb1b832013-01-07 09:53:42 -08005848 // Delegate volume control to effect in track effect chain if needed
5849 // only one effect chain can be present on DirectOutputThread, so if
5850 // there is one, the track is connected to it
5851 if (!mEffectChains.isEmpty()) {
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09005852 // if effect chain exists, volume is handled by it.
5853 // Convert volumes from float to 8.24
5854 uint32_t vl = (uint32_t)(left * (1 << 24));
5855 uint32_t vr = (uint32_t)(right * (1 << 24));
5856 // Direct/Offload effect chains set output volume in setVolume_l().
5857 (void)mEffectChains[0]->setVolume_l(&vl, &vr);
5858 } else {
5859 // otherwise we directly set the volume.
5860 setVolumeForOutput_l(left, right);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005861 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005862 }
5863 }
5864}
5865
Phil Burk43b4dcc2015-06-09 16:53:44 -07005866void AudioFlinger::DirectOutputThread::onAddNewTrack_l()
5867{
5868 sp<Track> previousTrack = mPreviousTrack.promote();
Andy Hungdae27702016-10-31 14:01:16 -07005869 sp<Track> latestTrack = mActiveTracks.getLatest();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005870
Eric Laurent0f0631e2015-07-06 18:01:25 -07005871 if (previousTrack != 0 && latestTrack != 0) {
5872 if (mType == DIRECT) {
5873 if (previousTrack.get() != latestTrack.get()) {
5874 mFlushPending = true;
5875 }
5876 } else /* mType == OFFLOAD */ {
5877 if (previousTrack->sessionId() != latestTrack->sessionId()) {
5878 mFlushPending = true;
5879 }
5880 }
Revathi Uddaraju20413a92016-10-13 17:16:14 +08005881 } else if (previousTrack == 0) {
5882 // there could be an old track added back during track transition for direct
5883 // output, so always issues flush to flush data of the previous track if it
5884 // was already destroyed with HAL paused, then flush can resume the playback
5885 mFlushPending = true;
Phil Burk43b4dcc2015-06-09 16:53:44 -07005886 }
5887 PlaybackThread::onAddNewTrack_l();
5888}
Eric Laurentbfb1b832013-01-07 09:53:42 -08005889
Eric Laurent81784c32012-11-19 14:55:58 -08005890AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
5891 Vector< sp<Track> > *tracksToRemove
5892)
5893{
Eric Laurentd595b7c2013-04-03 17:27:56 -07005894 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08005895 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005896 bool doHwPause = false;
5897 bool doHwResume = false;
Eric Laurent81784c32012-11-19 14:55:58 -08005898
5899 // find out which tracks need to be processed
Andy Hungdae27702016-10-31 14:01:16 -07005900 for (const sp<Track> &t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08005901 if (t->isInvalid()) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07005902 ALOGW("An invalidated track shouldn't be in active list");
Eric Laurent5850c4c2016-11-10 13:04:31 -08005903 tracksToRemove->add(t);
Phil Burk43b4dcc2015-06-09 16:53:44 -07005904 continue;
5905 }
5906
Eric Laurent5850c4c2016-11-10 13:04:31 -08005907 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005908#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurent81784c32012-11-19 14:55:58 -08005909 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005910#endif
Eric Laurentfd477972013-10-25 18:10:40 -07005911 // Only consider last track started for volume and mixer state control.
5912 // In theory an older track could underrun and restart after the new one starts
5913 // but as we only care about the transition phase between two tracks on a
5914 // direct output, it is not a problem to ignore the underrun case.
Andy Hungdae27702016-10-31 14:01:16 -07005915 sp<Track> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08005916 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08005917
Kuowei Li23666472021-01-20 10:23:25 +08005918 if (track->isPausePending()) {
5919 track->pauseAck();
5920 // It is possible a track might have been flushed or stopped.
5921 // Other operations such as flush pending might occur on the next prepare.
5922 if (track->isPausing()) {
5923 track->setPaused();
5924 }
5925 // Always perform pause, as an immediate flush will change
5926 // the pause state to be no longer isPausing().
Phil Burk6fc2a7c2015-04-30 16:08:10 -07005927 if (mHwSupportsPause && last && !mHwPaused) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005928 doHwPause = true;
5929 mHwPaused = true;
5930 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08005931 } else if (track->isFlushPending()) {
5932 track->flushAck();
5933 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07005934 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005935 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07005936 } else if (track->isResumePending()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005937 track->resumeAck();
Eric Laurent3df841a2016-07-15 15:15:40 -07005938 if (last) {
5939 mLeftVolFloat = mRightVolFloat = -1.0;
5940 if (mHwPaused) {
5941 doHwResume = true;
5942 mHwPaused = false;
5943 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08005944 }
5945 }
5946
Eric Laurent81784c32012-11-19 14:55:58 -08005947 // The first time a track is added we wait
Phil Burk99adee32014-12-10 16:46:30 -08005948 // for all its buffers to be filled before processing it.
5949 // Allow draining the buffer in case the client
5950 // app does not call stop() and relies on underrun to stop:
5951 // hence the test on (track->mRetryCount > 1).
Andy Hung455982f2021-04-27 17:46:12 -07005952 // If track->mRetryCount <= 1 then track is about to be disabled, paused, removed,
5953 // so we accept any nonzero amount of data delivered by the AudioTrack (which will
5954 // reset the retry counter).
Phil Burkca5e6142015-07-14 09:42:29 -07005955 // Do not use a high threshold for compressed audio.
Andy Hung455982f2021-04-27 17:46:12 -07005956
5957 // target retry count that we will use is based on the time we wait for retries.
5958 const int32_t targetRetryCount = kMaxTrackRetriesDirectMs * 1000 / mActiveSleepTimeUs;
5959 // the retry threshold is when we accept any size for PCM data. This is slightly
5960 // smaller than the retry count so we can push small bits of data without a glitch.
5961 const int32_t retryThreshold = targetRetryCount > 2 ? targetRetryCount - 1 : 1;
Eric Laurent81784c32012-11-19 14:55:58 -08005962 uint32_t minFrames;
Phil Burk99adee32014-12-10 16:46:30 -08005963 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
Andy Hung455982f2021-04-27 17:46:12 -07005964 && (track->mRetryCount > retryThreshold) && audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005965 minFrames = mNormalFrameCount;
5966 } else {
5967 minFrames = 1;
5968 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005969
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07005970 const size_t framesReady = track->framesReady();
5971 const int trackId = track->id();
5972 if (ATRACE_ENABLED()) {
5973 std::string traceName("nRdy");
5974 traceName += std::to_string(trackId);
5975 ATRACE_INT(traceName.c_str(), framesReady);
5976 }
5977 if ((framesReady >= minFrames) && track->isReady() && !track->isPaused() &&
Eric Laurentab5cdba2014-06-09 17:22:27 -07005978 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08005979 {
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07005980 ALOGVV("track(%d) s=%08x [OK]", trackId, cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08005981
5982 if (track->mFillingUpStatus == Track::FS_FILLED) {
5983 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07005984 if (last) {
5985 // make sure processVolume_l() will apply new volume even if 0
5986 mLeftVolFloat = mRightVolFloat = -1.0;
5987 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08005988 if (!mHwSupportsPause) {
5989 track->resumeAck();
Eric Laurent81784c32012-11-19 14:55:58 -08005990 }
5991 }
5992
5993 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08005994 processVolume_l(track, last);
5995 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07005996 sp<Track> previousTrack = mPreviousTrack.promote();
5997 if (previousTrack != 0) {
5998 if (track != previousTrack.get()) {
5999 // Flush any data still being written from last track
6000 mBytesRemaining = 0;
Eric Laurent0f0631e2015-07-06 18:01:25 -07006001 // Invalidate previous track to force a seek when resuming.
6002 previousTrack->invalidate();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006003 }
6004 }
6005 mPreviousTrack = track;
6006
Eric Laurentd595b7c2013-04-03 17:27:56 -07006007 // reset retry count
Andy Hung455982f2021-04-27 17:46:12 -07006008 track->mRetryCount = targetRetryCount;
Eric Laurent5850c4c2016-11-10 13:04:31 -08006009 mActiveTrack = t;
Eric Laurentd595b7c2013-04-03 17:27:56 -07006010 mixerStatus = MIXER_TRACKS_READY;
Eric Laurent5cff4032015-05-26 13:49:58 -07006011 if (mHwPaused) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08006012 doHwResume = true;
6013 mHwPaused = false;
6014 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07006015 }
Eric Laurent81784c32012-11-19 14:55:58 -08006016 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07006017 // clear effect chain input buffer if the last active track started underruns
6018 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07006019 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08006020 mEffectChains[0]->clearInputBuffer();
6021 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07006022 if (track->isStopping_1()) {
6023 track->mState = TrackBase::STOPPING_2;
Eric Laurentb369caf2015-03-30 20:51:47 -07006024 if (last && mHwPaused) {
6025 doHwResume = true;
6026 mHwPaused = false;
6027 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07006028 }
6029 if ((track->sharedBuffer() != 0) || track->isStopped() ||
6030 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08006031 // We have consumed all the buffers of this track.
6032 // Remove it from the list of active tracks.
Eric Laurentab5cdba2014-06-09 17:22:27 -07006033 size_t audioHALFrames;
Phil Burkfdb3c072016-02-09 10:47:02 -08006034 if (audio_has_proportional_frames(mFormat)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07006035 audioHALFrames = (latency_l() * mSampleRate) / 1000;
6036 } else {
6037 audioHALFrames = 0;
6038 }
6039
Andy Hung818e7a32016-02-16 18:08:07 -08006040 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurentfd477972013-10-25 18:10:40 -07006041 if (mStandby || !last ||
Aniket Kumar Lata179a0742019-01-30 14:16:16 -08006042 track->presentationComplete(framesWritten, audioHALFrames) ||
Jindong32dc26e2019-11-11 18:10:01 +08006043 track->isPaused() || mHwPaused) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07006044 if (track->isStopping_2()) {
6045 track->mState = TrackBase::STOPPED;
6046 }
Eric Laurent81784c32012-11-19 14:55:58 -08006047 if (track->isStopped()) {
6048 track->reset();
6049 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07006050 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08006051 }
6052 } else {
6053 // No buffers for this track. Give it a few chances to
6054 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07006055 // Only consider last track started for mixer state control
Eric Laurent81784c32012-11-19 14:55:58 -08006056 if (--(track->mRetryCount) <= 0) {
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07006057 ALOGV("BUFFER TIMEOUT: remove track(%d) from active list", trackId);
Eric Laurentd595b7c2013-04-03 17:27:56 -07006058 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08006059 // indicate to client process that the track was disabled because of underrun;
6060 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08006061 track->disable();
Haynes Mathew George5c6daae2017-01-24 20:06:05 -08006062 // only do hw pause when track is going to be removed due to BUFFER TIMEOUT.
6063 // unlike mixerthread, HAL can be paused for direct output
Phil Burkca5e6142015-07-14 09:42:29 -07006064 ALOGW("pause because of UNDERRUN, framesReady = %zu,"
6065 "minFrames = %u, mFormat = %#x",
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07006066 framesReady, minFrames, mFormat);
Haynes Mathew George5c6daae2017-01-24 20:06:05 -08006067 if (last && mHwSupportsPause && !mHwPaused && !mStandby) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08006068 doHwPause = true;
6069 mHwPaused = true;
6070 }
Haynes Mathew George5c6daae2017-01-24 20:06:05 -08006071 } else if (last) {
6072 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurent81784c32012-11-19 14:55:58 -08006073 }
6074 }
6075 }
6076 }
6077
Eric Laurentd1f69b02014-12-15 14:33:13 -08006078 // if an active track did not command a flush, check for pending flush on stopped tracks
Phil Burk43b4dcc2015-06-09 16:53:44 -07006079 if (!mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006080 for (size_t i = 0; i < mTracks.size(); i++) {
6081 if (mTracks[i]->isFlushPending()) {
6082 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006083 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006084 }
6085 }
6086 }
6087
6088 // make sure the pause/flush/resume sequence is executed in the right order.
6089 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
6090 // before flush and then resume HW. This can happen in case of pause/flush/resume
6091 // if resume is received before pause is executed.
6092 if (mHwSupportsPause && !mStandby &&
Phil Burk43b4dcc2015-06-09 16:53:44 -07006093 (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006094 status_t result = mOutput->stream->pause();
6095 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08006096 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07006097 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006098 flushHw_l();
6099 }
6100 if (mHwSupportsPause && !mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006101 status_t result = mOutput->stream->resume();
6102 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08006103 }
Eric Laurent81784c32012-11-19 14:55:58 -08006104 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08006105 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08006106
6107 return mixerStatus;
6108}
6109
6110void AudioFlinger::DirectOutputThread::threadLoop_mix()
6111{
Eric Laurent81784c32012-11-19 14:55:58 -08006112 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08006113 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08006114 // output audio to hardware
6115 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07006116 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08006117 buffer.frameCount = frameCount;
Phil Burk062e67a2015-02-11 13:40:50 -08006118 status_t status = mActiveTrack->getNextBuffer(&buffer);
6119 if (status != NO_ERROR || buffer.raw == NULL) {
Eric Laurent51716182016-02-29 18:00:56 -08006120 // no need to pad with 0 for compressed audio
6121 if (audio_has_proportional_frames(mFormat)) {
6122 memset(curBuf, 0, frameCount * mFrameSize);
6123 }
Eric Laurent81784c32012-11-19 14:55:58 -08006124 break;
6125 }
6126 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
6127 frameCount -= buffer.frameCount;
6128 curBuf += buffer.frameCount * mFrameSize;
6129 mActiveTrack->releaseBuffer(&buffer);
6130 }
Andy Hung2098f272014-02-27 14:00:06 -08006131 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006132 mSleepTimeUs = 0;
6133 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08006134 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08006135}
6136
6137void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
6138{
Eric Laurentd1f69b02014-12-15 14:33:13 -08006139 // do not write to HAL when paused
Eric Laurent0f7b5f22014-12-19 10:43:21 -08006140 if (mHwPaused || (usesHwAvSync() && mStandby)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006141 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006142 return;
6143 }
Andy Hung85ba3332021-04-27 17:40:26 -07006144 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
6145 mSleepTimeUs = mActiveSleepTimeUs;
6146 } else {
6147 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006148 }
Andy Hung85ba3332021-04-27 17:40:26 -07006149 // Note: In S or later, we do not write zeroes for
6150 // linear or proportional PCM direct tracks in underrun.
Eric Laurent81784c32012-11-19 14:55:58 -08006151}
6152
Eric Laurentd1f69b02014-12-15 14:33:13 -08006153void AudioFlinger::DirectOutputThread::threadLoop_exit()
6154{
6155 {
6156 Mutex::Autolock _l(mLock);
Eric Laurentd1f69b02014-12-15 14:33:13 -08006157 for (size_t i = 0; i < mTracks.size(); i++) {
6158 if (mTracks[i]->isFlushPending()) {
6159 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006160 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006161 }
6162 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07006163 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006164 flushHw_l();
6165 }
6166 }
6167 PlaybackThread::threadLoop_exit();
6168}
6169
6170// must be called with thread mutex locked
6171bool AudioFlinger::DirectOutputThread::shouldStandby_l()
6172{
6173 bool trackPaused = false;
Eric Laurentb369caf2015-03-30 20:51:47 -07006174 bool trackStopped = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006175
6176 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
6177 // after a timeout and we will enter standby then.
6178 if (mTracks.size() > 0) {
6179 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
Eric Laurentb369caf2015-03-30 20:51:47 -07006180 trackStopped = mTracks[mTracks.size() - 1]->isStopped() ||
6181 mTracks[mTracks.size() - 1]->mState == TrackBase::IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006182 }
6183
Eric Laurent5cff4032015-05-26 13:49:58 -07006184 return !mStandby && !(trackPaused || (mHwPaused && !trackStopped));
Eric Laurentd1f69b02014-12-15 14:33:13 -08006185}
6186
Eric Laurent10351942014-05-08 18:49:52 -07006187// checkForNewParameter_l() must be called with ThreadBase::mLock held
6188bool AudioFlinger::DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
6189 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08006190{
6191 bool reconfig = false;
Eric Laurent10351942014-05-08 18:49:52 -07006192 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006193
Eric Laurent10351942014-05-08 18:49:52 -07006194 AudioParameter param = AudioParameter(keyValuePair);
6195 int value;
6196 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07006197 LOG_FATAL("Should not set routing device in DirectOutputThread");
Eric Laurent81784c32012-11-19 14:55:58 -08006198 }
Eric Laurent10351942014-05-08 18:49:52 -07006199 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6200 // do not accept frame count changes if tracks are open as the track buffer
6201 // size depends on frame count and correct behavior would not be garantied
6202 // if frame count is changed after track creation
6203 if (!mTracks.isEmpty()) {
6204 status = INVALID_OPERATION;
6205 } else {
6206 reconfig = true;
6207 }
6208 }
6209 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006210 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07006211 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08006212 mOutput->standby();
Andy Hungcf10d742020-04-28 15:38:24 -07006213 if (!mStandby) {
6214 mThreadMetrics.logEndInterval();
6215 mStandby = true;
6216 }
Eric Laurent10351942014-05-08 18:49:52 -07006217 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006218 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07006219 }
6220 if (status == NO_ERROR && reconfig) {
6221 readOutputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07006222 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07006223 }
6224 }
6225
Dean Wheatley68918102021-03-19 22:09:19 +11006226 return reconfig;
Eric Laurent81784c32012-11-19 14:55:58 -08006227}
6228
6229uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
6230{
6231 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08006232 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006233 time = PlaybackThread::activeSleepTimeUs();
6234 } else {
Eric Laurent51716182016-02-29 18:00:56 -08006235 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006236 }
6237 return time;
6238}
6239
6240uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
6241{
6242 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08006243 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006244 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
6245 } else {
Eric Laurent51716182016-02-29 18:00:56 -08006246 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006247 }
6248 return time;
6249}
6250
6251uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
6252{
6253 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08006254 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006255 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
6256 } else {
Eric Laurent51716182016-02-29 18:00:56 -08006257 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006258 }
6259 return time;
6260}
6261
6262void AudioFlinger::DirectOutputThread::cacheParameters_l()
6263{
6264 PlaybackThread::cacheParameters_l();
6265
6266 // use shorter standby delay as on normal output to release
6267 // hardware resources as soon as possible
Eric Laurentb369caf2015-03-30 20:51:47 -07006268 // no delay on outputs with HW A/V sync
6269 if (usesHwAvSync()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006270 mStandbyDelayNs = 0;
Phil Burkfdb3c072016-02-09 10:47:02 -08006271 } else if ((mType == OFFLOAD) && !audio_has_proportional_frames(mFormat)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006272 mStandbyDelayNs = kOffloadStandbyDelayNs;
Eric Laurent5cff4032015-05-26 13:49:58 -07006273 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006274 mStandbyDelayNs = microseconds(mActiveSleepTimeUs*2);
Eric Laurent972a1732013-09-04 09:42:59 -07006275 }
Eric Laurent81784c32012-11-19 14:55:58 -08006276}
6277
Eric Laurente659ef42014-09-29 13:06:46 -07006278void AudioFlinger::DirectOutputThread::flushHw_l()
6279{
Phil Burk062e67a2015-02-11 13:40:50 -08006280 mOutput->flush();
Eric Laurentd1f69b02014-12-15 14:33:13 -08006281 mHwPaused = false;
Phil Burk43b4dcc2015-06-09 16:53:44 -07006282 mFlushPending = false;
Dean Wheatley12473e92021-03-18 23:00:55 +11006283 mTimestampVerifier.discontinuity(discontinuityForStandbyOrFlush());
Sampath Shetty999f0e82020-01-15 10:19:06 +11006284 mTimestamp.clear();
Eric Laurente659ef42014-09-29 13:06:46 -07006285}
6286
Andy Hung10cbff12017-02-21 17:30:14 -08006287int64_t AudioFlinger::DirectOutputThread::computeWaitTimeNs_l() const {
6288 // If a VolumeShaper is active, we must wake up periodically to update volume.
6289 const int64_t NS_PER_MS = 1000000;
6290 return mVolumeShaperActive ?
6291 kMinNormalSinkBufferSizeMs * NS_PER_MS : PlaybackThread::computeWaitTimeNs_l();
6292}
6293
Eric Laurent81784c32012-11-19 14:55:58 -08006294// ----------------------------------------------------------------------------
6295
Eric Laurentbfb1b832013-01-07 09:53:42 -08006296AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
Eric Laurent4de95592013-09-26 15:28:21 -07006297 const wp<AudioFlinger::PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006298 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07006299 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07006300 mWriteAckSequence(0),
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006301 mDrainSequence(0),
6302 mAsyncError(false)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006303{
6304}
6305
6306AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
6307{
6308}
6309
6310void AudioFlinger::AsyncCallbackThread::onFirstRef()
6311{
6312 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
6313}
6314
6315bool AudioFlinger::AsyncCallbackThread::threadLoop()
6316{
6317 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07006318 uint32_t writeAckSequence;
6319 uint32_t drainSequence;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006320 bool asyncError;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006321
6322 {
6323 Mutex::Autolock _l(mLock);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08006324 while (!((mWriteAckSequence & 1) ||
6325 (mDrainSequence & 1) ||
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006326 mAsyncError ||
Haynes Mathew George24a325d2013-12-03 21:26:02 -08006327 exitPending())) {
6328 mWaitWorkCV.wait(mLock);
6329 }
6330
Eric Laurentbfb1b832013-01-07 09:53:42 -08006331 if (exitPending()) {
6332 break;
6333 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07006334 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
6335 mWriteAckSequence, mDrainSequence);
6336 writeAckSequence = mWriteAckSequence;
6337 mWriteAckSequence &= ~1;
6338 drainSequence = mDrainSequence;
6339 mDrainSequence &= ~1;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006340 asyncError = mAsyncError;
6341 mAsyncError = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006342 }
6343 {
Eric Laurent4de95592013-09-26 15:28:21 -07006344 sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
6345 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07006346 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07006347 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006348 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07006349 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07006350 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006351 }
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006352 if (asyncError) {
6353 playbackThread->onAsyncError();
6354 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006355 }
6356 }
6357 }
6358 return false;
6359}
6360
6361void AudioFlinger::AsyncCallbackThread::exit()
6362{
6363 ALOGV("AsyncCallbackThread::exit");
6364 Mutex::Autolock _l(mLock);
6365 requestExit();
6366 mWaitWorkCV.broadcast();
6367}
6368
Eric Laurent3b4529e2013-09-05 18:09:19 -07006369void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006370{
6371 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07006372 // bit 0 is cleared
6373 mWriteAckSequence = sequence << 1;
6374}
6375
6376void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
6377{
6378 Mutex::Autolock _l(mLock);
6379 // ignore unexpected callbacks
6380 if (mWriteAckSequence & 2) {
6381 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006382 mWaitWorkCV.signal();
6383 }
6384}
6385
Eric Laurent3b4529e2013-09-05 18:09:19 -07006386void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006387{
6388 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07006389 // bit 0 is cleared
6390 mDrainSequence = sequence << 1;
6391}
6392
6393void AudioFlinger::AsyncCallbackThread::resetDraining()
6394{
6395 Mutex::Autolock _l(mLock);
6396 // ignore unexpected callbacks
6397 if (mDrainSequence & 2) {
6398 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006399 mWaitWorkCV.signal();
6400 }
6401}
6402
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006403void AudioFlinger::AsyncCallbackThread::setAsyncError()
6404{
6405 Mutex::Autolock _l(mLock);
6406 mAsyncError = true;
6407 mWaitWorkCV.signal();
6408}
6409
Eric Laurentbfb1b832013-01-07 09:53:42 -08006410
6411// ----------------------------------------------------------------------------
6412AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
jiabinc52b1ff2019-10-31 17:20:42 -07006413 AudioStreamOut* output, audio_io_handle_t id, bool systemReady)
6414 : DirectOutputThread(audioFlinger, output, id, OFFLOAD, systemReady),
Andy Hungf8044752016-07-27 14:58:11 -07006415 mPausedWriteLength(0), mPausedBytesRemaining(0), mKeepWakeLock(true),
6416 mOffloadUnderrunPosition(~0LL)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006417{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07006418 //FIXME: mStandby should be set to true by ThreadBase constructo
Eric Laurentfd477972013-10-25 18:10:40 -07006419 mStandby = true;
Eric Laurent64667972016-03-30 18:19:46 -07006420 mKeepWakeLock = property_get_bool("ro.audio.offload_wakelock", true /* default_value */);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006421}
6422
Eric Laurentbfb1b832013-01-07 09:53:42 -08006423void AudioFlinger::OffloadThread::threadLoop_exit()
6424{
6425 if (mFlushPending || mHwPaused) {
6426 // If a flush is pending or track was paused, just discard buffered data
6427 flushHw_l();
6428 } else {
6429 mMixerStatus = MIXER_DRAIN_ALL;
6430 threadLoop_drain();
6431 }
Uday Gupta56604aa2014-05-13 11:19:17 -07006432 if (mUseAsyncWrite) {
6433 ALOG_ASSERT(mCallbackThread != 0);
6434 mCallbackThread->exit();
6435 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006436 PlaybackThread::threadLoop_exit();
6437}
6438
6439AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
6440 Vector< sp<Track> > *tracksToRemove
6441)
6442{
Eric Laurentbfb1b832013-01-07 09:53:42 -08006443 size_t count = mActiveTracks.size();
6444
6445 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07006446 bool doHwPause = false;
6447 bool doHwResume = false;
6448
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006449 ALOGV("OffloadThread::prepareTracks_l active tracks %zu", count);
Eric Laurentede6c3b2013-09-19 14:37:46 -07006450
Eric Laurentbfb1b832013-01-07 09:53:42 -08006451 // find out which tracks need to be processed
Andy Hungdae27702016-10-31 14:01:16 -07006452 for (const sp<Track> &t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08006453 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006454#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurentbfb1b832013-01-07 09:53:42 -08006455 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006456#endif
Eric Laurentfd477972013-10-25 18:10:40 -07006457 // Only consider last track started for volume and mixer state control.
6458 // In theory an older track could underrun and restart after the new one starts
6459 // but as we only care about the transition phase between two tracks on a
6460 // direct output, it is not a problem to ignore the underrun case.
Andy Hungdae27702016-10-31 14:01:16 -07006461 sp<Track> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08006462 bool last = l.get() == track;
Eric Laurentfd477972013-10-25 18:10:40 -07006463
Haynes Mathew George7844f672014-01-15 12:32:55 -08006464 if (track->isInvalid()) {
6465 ALOGW("An invalidated track shouldn't be in active list");
6466 tracksToRemove->add(track);
6467 continue;
6468 }
6469
6470 if (track->mState == TrackBase::IDLE) {
6471 ALOGW("An idle track shouldn't be in active list");
6472 continue;
6473 }
6474
Kuowei Li23666472021-01-20 10:23:25 +08006475 if (track->isPausePending()) {
6476 track->pauseAck();
6477 // It is possible a track might have been flushed or stopped.
6478 // Other operations such as flush pending might occur on the next prepare.
6479 if (track->isPausing()) {
6480 track->setPaused();
6481 }
6482 // Always perform pause if last, as an immediate flush will change
6483 // the pause state to be no longer isPausing().
Eric Laurentbfb1b832013-01-07 09:53:42 -08006484 if (last) {
Eric Laurent5cff4032015-05-26 13:49:58 -07006485 if (mHwSupportsPause && !mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07006486 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006487 mHwPaused = true;
6488 }
6489 // If we were part way through writing the mixbuffer to
6490 // the HAL we must save this until we resume
6491 // BUG - this will be wrong if a different track is made active,
6492 // in that case we want to discard the pending data in the
6493 // mixbuffer and tell the client to present it again when the
6494 // track is resumed
6495 mPausedWriteLength = mCurrentWriteLength;
6496 mPausedBytesRemaining = mBytesRemaining;
6497 mBytesRemaining = 0; // stop writing
6498 }
6499 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08006500 } else if (track->isFlushPending()) {
Eric Laurente93cc032016-05-05 10:15:10 -07006501 if (track->isStopping_1()) {
6502 track->mRetryCount = kMaxTrackStopRetriesOffload;
6503 } else {
6504 track->mRetryCount = kMaxTrackRetriesOffload;
6505 }
Haynes Mathew George7844f672014-01-15 12:32:55 -08006506 track->flushAck();
6507 if (last) {
6508 mFlushPending = true;
6509 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08006510 } else if (track->isResumePending()){
6511 track->resumeAck();
6512 if (last) {
6513 if (mPausedBytesRemaining) {
6514 // Need to continue write that was interrupted
6515 mCurrentWriteLength = mPausedWriteLength;
6516 mBytesRemaining = mPausedBytesRemaining;
6517 mPausedBytesRemaining = 0;
6518 }
6519 if (mHwPaused) {
6520 doHwResume = true;
6521 mHwPaused = false;
6522 // threadLoop_mix() will handle the case that we need to
6523 // resume an interrupted write
6524 }
6525 // enable write to audio HAL
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006526 mSleepTimeUs = 0;
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08006527
Eric Laurent3df841a2016-07-15 15:15:40 -07006528 mLeftVolFloat = mRightVolFloat = -1.0;
6529
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08006530 // Do not handle new data in this iteration even if track->framesReady()
6531 mixerStatus = MIXER_TRACKS_ENABLED;
6532 }
6533 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07006534 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Andy Hungc0691382018-09-12 18:01:57 -07006535 ALOGVV("OffloadThread: track(%d) s=%08x [OK]", track->id(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006536 if (track->mFillingUpStatus == Track::FS_FILLED) {
6537 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07006538 if (last) {
6539 // make sure processVolume_l() will apply new volume even if 0
6540 mLeftVolFloat = mRightVolFloat = -1.0;
6541 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006542 }
6543
6544 if (last) {
Eric Laurentd7e59222013-11-15 12:02:28 -08006545 sp<Track> previousTrack = mPreviousTrack.promote();
6546 if (previousTrack != 0) {
6547 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08006548 // Flush any data still being written from last track
6549 mBytesRemaining = 0;
6550 if (mPausedBytesRemaining) {
6551 // Last track was paused so we also need to flush saved
6552 // mixbuffer state and invalidate track so that it will
6553 // re-submit that unwritten data when it is next resumed
6554 mPausedBytesRemaining = 0;
6555 // Invalidate is a bit drastic - would be more efficient
6556 // to have a flag to tell client that some of the
6557 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08006558 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08006559 }
6560 // flush data already sent to the DSP if changing audio session as audio
6561 // comes from a different source. Also invalidate previous track to force a
6562 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08006563 if (previousTrack->sessionId() != track->sessionId()) {
6564 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08006565 }
6566 }
6567 }
6568 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006569 // reset retry count
Eric Laurente93cc032016-05-05 10:15:10 -07006570 if (track->isStopping_1()) {
6571 track->mRetryCount = kMaxTrackStopRetriesOffload;
6572 } else {
6573 track->mRetryCount = kMaxTrackRetriesOffload;
6574 }
Eric Laurent5850c4c2016-11-10 13:04:31 -08006575 mActiveTrack = t;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006576 mixerStatus = MIXER_TRACKS_READY;
6577 }
6578 } else {
Andy Hungc0691382018-09-12 18:01:57 -07006579 ALOGVV("OffloadThread: track(%d) s=%08x [NOT READY]", track->id(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006580 if (track->isStopping_1()) {
Eric Laurente93cc032016-05-05 10:15:10 -07006581 if (--(track->mRetryCount) <= 0) {
6582 // Hardware buffer can hold a large amount of audio so we must
6583 // wait for all current track's data to drain before we say
6584 // that the track is stopped.
6585 if (mBytesRemaining == 0) {
6586 // Only start draining when all data in mixbuffer
6587 // has been written
6588 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
6589 track->mState = TrackBase::STOPPING_2; // so presentation completes after
6590 // drain do not drain if no data was ever sent to HAL (mStandby == true)
6591 if (last && !mStandby) {
6592 // do not modify drain sequence if we are already draining. This happens
6593 // when resuming from pause after drain.
6594 if ((mDrainSequence & 1) == 0) {
6595 mSleepTimeUs = 0;
6596 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
6597 mixerStatus = MIXER_DRAIN_TRACK;
6598 mDrainSequence += 2;
6599 }
6600 if (mHwPaused) {
6601 // It is possible to move from PAUSED to STOPPING_1 without
6602 // a resume so we must ensure hardware is running
6603 doHwResume = true;
6604 mHwPaused = false;
6605 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006606 }
6607 }
Eric Laurente93cc032016-05-05 10:15:10 -07006608 } else if (last) {
6609 ALOGV("stopping1 underrun retries left %d", track->mRetryCount);
6610 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006611 }
6612 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07006613 // Drain has completed or we are in standby, signal presentation complete
6614 if (!(mDrainSequence & 1) || !last || mStandby) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08006615 track->mState = TrackBase::STOPPED;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006616 uint32_t latency = 0;
6617 status_t result = mOutput->stream->getLatency(&latency);
6618 ALOGE_IF(result != OK,
6619 "Error when retrieving output stream latency: %d", result);
6620 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08006621 int64_t framesWritten =
Phil Burk062e67a2015-02-11 13:40:50 -08006622 mBytesWritten / mOutput->getFrameSize();
Eric Laurentbfb1b832013-01-07 09:53:42 -08006623 track->presentationComplete(framesWritten, audioHALFrames);
6624 track->reset();
6625 tracksToRemove->add(track);
Dean Wheatley12473e92021-03-18 23:00:55 +11006626 // OFFLOADED stop resets frame counts.
Andy Hungf3234512018-07-03 14:51:47 -07006627 if (!mUseAsyncWrite) {
6628 // If we don't get explicit drain notification we must
6629 // register discontinuity regardless of whether this is
6630 // the previous (!last) or the upcoming (last) track
6631 // to avoid skipping the discontinuity.
Dean Wheatley12473e92021-03-18 23:00:55 +11006632 mTimestampVerifier.discontinuity(
6633 mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Andy Hungf3234512018-07-03 14:51:47 -07006634 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006635 }
6636 } else {
6637 // No buffers for this track. Give it a few chances to
6638 // fill a buffer, then remove it from active list.
6639 if (--(track->mRetryCount) <= 0) {
Andy Hungf8044752016-07-27 14:58:11 -07006640 bool running = false;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006641 uint64_t position = 0;
6642 struct timespec unused;
6643 // The running check restarts the retry counter at least once.
6644 status_t ret = mOutput->stream->getPresentationPosition(&position, &unused);
6645 if (ret == NO_ERROR && position != mOffloadUnderrunPosition) {
6646 running = true;
6647 mOffloadUnderrunPosition = position;
6648 }
6649 if (ret == NO_ERROR) {
Andy Hungf8044752016-07-27 14:58:11 -07006650 ALOGVV("underrun counter, running(%d): %lld vs %lld", running,
6651 (long long)position, (long long)mOffloadUnderrunPosition);
6652 }
6653 if (running) { // still running, give us more time.
6654 track->mRetryCount = kMaxTrackRetriesOffload;
6655 } else {
Andy Hungc0691382018-09-12 18:01:57 -07006656 ALOGV("OffloadThread: BUFFER TIMEOUT: remove track(%d) from active list",
6657 track->id());
Andy Hungf8044752016-07-27 14:58:11 -07006658 tracksToRemove->add(track);
Glenn Kastend3bb6452016-12-05 18:14:37 -08006659 // tell client process that the track was disabled because of underrun;
Andy Hungf8044752016-07-27 14:58:11 -07006660 // it will then automatically call start() when data is available
6661 track->disable();
6662 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006663 } else if (last){
6664 mixerStatus = MIXER_TRACKS_ENABLED;
6665 }
6666 }
6667 }
6668 // compute volume for this track
Wenfeng Sun79458332019-05-29 20:12:43 +08006669 if (track->isReady()) { // check ready to prevent premature start.
6670 processVolume_l(track, last);
6671 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006672 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07006673
Eric Laurentea0fade2013-10-04 16:23:48 -07006674 // make sure the pause/flush/resume sequence is executed in the right order.
6675 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
6676 // before flush and then resume HW. This can happen in case of pause/flush/resume
6677 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07006678 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006679 status_t result = mOutput->stream->pause();
6680 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07006681 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07006682 if (mFlushPending) {
6683 flushHw_l();
Eric Laurent6bf9ae22013-08-30 15:12:37 -07006684 }
Eric Laurentfd477972013-10-25 18:10:40 -07006685 if (!mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006686 status_t result = mOutput->stream->resume();
6687 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07006688 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07006689
Eric Laurentbfb1b832013-01-07 09:53:42 -08006690 // remove all the tracks that need to be...
6691 removeTracks_l(*tracksToRemove);
6692
6693 return mixerStatus;
6694}
6695
Eric Laurentbfb1b832013-01-07 09:53:42 -08006696// must be called with thread mutex locked
6697bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
6698{
Eric Laurent3b4529e2013-09-05 18:09:19 -07006699 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
6700 mWriteAckSequence, mDrainSequence);
6701 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08006702 return true;
6703 }
6704 return false;
6705}
6706
Eric Laurentbfb1b832013-01-07 09:53:42 -08006707bool AudioFlinger::OffloadThread::waitingAsyncCallback()
6708{
6709 Mutex::Autolock _l(mLock);
6710 return waitingAsyncCallback_l();
6711}
6712
6713void AudioFlinger::OffloadThread::flushHw_l()
6714{
Eric Laurente659ef42014-09-29 13:06:46 -07006715 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08006716 // Flush anything still waiting in the mixbuffer
6717 mCurrentWriteLength = 0;
6718 mBytesRemaining = 0;
6719 mPausedWriteLength = 0;
6720 mPausedBytesRemaining = 0;
Eric Laurent3eaf66b2016-04-01 14:44:17 -07006721 // reset bytes written count to reflect that DSP buffers are empty after flush.
6722 mBytesWritten = 0;
Andy Hungf8044752016-07-27 14:58:11 -07006723 mOffloadUnderrunPosition = ~0LL;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08006724
Eric Laurentbfb1b832013-01-07 09:53:42 -08006725 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07006726 // discard any pending drain or write ack by incrementing sequence
6727 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
6728 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006729 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07006730 mCallbackThread->setWriteBlocked(mWriteAckSequence);
6731 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006732 }
6733}
6734
Haynes Mathew George05317d22016-05-03 16:34:26 -07006735void AudioFlinger::OffloadThread::invalidateTracks(audio_stream_type_t streamType)
6736{
6737 Mutex::Autolock _l(mLock);
Eric Laurent13084622016-05-17 10:51:49 -07006738 if (PlaybackThread::invalidateTracks_l(streamType)) {
6739 mFlushPending = true;
6740 }
Haynes Mathew George05317d22016-05-03 16:34:26 -07006741}
6742
Eric Laurentbfb1b832013-01-07 09:53:42 -08006743// ----------------------------------------------------------------------------
6744
Eric Laurent81784c32012-11-19 14:55:58 -08006745AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurent72e3f392015-05-20 14:43:50 -07006746 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id, bool systemReady)
jiabinc52b1ff2019-10-31 17:20:42 -07006747 : MixerThread(audioFlinger, mainThread->getOutput(), id,
Eric Laurent72e3f392015-05-20 14:43:50 -07006748 systemReady, DUPLICATING),
Eric Laurent81784c32012-11-19 14:55:58 -08006749 mWaitTimeMs(UINT_MAX)
6750{
6751 addOutputTrack(mainThread);
6752}
6753
6754AudioFlinger::DuplicatingThread::~DuplicatingThread()
6755{
6756 for (size_t i = 0; i < mOutputTracks.size(); i++) {
6757 mOutputTracks[i]->destroy();
6758 }
6759}
6760
6761void AudioFlinger::DuplicatingThread::threadLoop_mix()
6762{
6763 // mix buffers...
6764 if (outputsReady(outputTracks)) {
Glenn Kastend79072e2016-01-06 08:41:20 -08006765 mAudioMixer->process();
Eric Laurent81784c32012-11-19 14:55:58 -08006766 } else {
Eric Laurent02b57082014-11-07 17:28:28 -08006767 if (mMixerBufferValid) {
6768 memset(mMixerBuffer, 0, mMixerBufferSize);
6769 } else {
6770 memset(mSinkBuffer, 0, mSinkBufferSize);
6771 }
Eric Laurent81784c32012-11-19 14:55:58 -08006772 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006773 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08006774 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08006775 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006776 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08006777}
6778
6779void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
6780{
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006781 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006782 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006783 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006784 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006785 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006786 }
6787 } else if (mBytesWritten != 0) {
6788 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
6789 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08006790 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08006791 } else {
6792 // flush remaining overflow buffers in output tracks
6793 writeFrames = 0;
6794 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006795 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08006796 }
6797}
6798
Eric Laurentbfb1b832013-01-07 09:53:42 -08006799ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08006800{
6801 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hung1c86ebe2018-05-29 20:29:08 -07006802 const ssize_t actualWritten = outputTracks[i]->write(mSinkBuffer, writeFrames);
6803
6804 // Consider the first OutputTrack for timestamp and frame counting.
6805
6806 // The threadLoop() generally assumes writing a full sink buffer size at a time.
6807 // Here, we correct for writeFrames of 0 (a stop) or underruns because
6808 // we always claim success.
6809 if (i == 0) {
6810 const ssize_t correction = mSinkBufferSize / mFrameSize - actualWritten;
6811 ALOGD_IF(correction != 0 && writeFrames != 0,
6812 "%s: writeFrames:%u actualWritten:%zd correction:%zd mFramesWritten:%lld",
6813 __func__, writeFrames, actualWritten, correction, (long long)mFramesWritten);
6814 mFramesWritten -= correction;
6815 }
6816
6817 // TODO: Report correction for the other output tracks and show in the dump.
Eric Laurent81784c32012-11-19 14:55:58 -08006818 }
Andy Hungcf10d742020-04-28 15:38:24 -07006819 if (mStandby) {
6820 mThreadMetrics.logBeginInterval();
6821 mStandby = false;
6822 }
Andy Hung25c2dac2014-02-27 14:56:00 -08006823 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08006824}
6825
6826void AudioFlinger::DuplicatingThread::threadLoop_standby()
6827{
6828 // DuplicatingThread implements standby by stopping all tracks
6829 for (size_t i = 0; i < outputTracks.size(); i++) {
6830 outputTracks[i]->stop();
6831 }
6832}
6833
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07006834void AudioFlinger::DuplicatingThread::dumpInternals_l(int fd, const Vector<String16>& args __unused)
Andy Hung1bc088a2018-02-09 15:57:31 -08006835{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07006836 MixerThread::dumpInternals_l(fd, args);
Andy Hung1bc088a2018-02-09 15:57:31 -08006837
6838 std::stringstream ss;
6839 const size_t numTracks = mOutputTracks.size();
6840 ss << " " << numTracks << " OutputTracks";
6841 if (numTracks > 0) {
6842 ss << ":";
6843 for (const auto &track : mOutputTracks) {
6844 const sp<ThreadBase> thread = track->thread().promote();
Andy Hungc0691382018-09-12 18:01:57 -07006845 ss << " (" << track->id() << " : ";
Andy Hung1bc088a2018-02-09 15:57:31 -08006846 if (thread.get() != nullptr) {
6847 ss << thread.get() << ", " << thread->id();
6848 } else {
6849 ss << "null";
6850 }
6851 ss << ")";
6852 }
6853 }
6854 ss << "\n";
6855 std::string result = ss.str();
6856 write(fd, result.c_str(), result.size());
6857}
6858
Eric Laurent81784c32012-11-19 14:55:58 -08006859void AudioFlinger::DuplicatingThread::saveOutputTracks()
6860{
6861 outputTracks = mOutputTracks;
6862}
6863
6864void AudioFlinger::DuplicatingThread::clearOutputTracks()
6865{
6866 outputTracks.clear();
6867}
6868
6869void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
6870{
6871 Mutex::Autolock _l(mLock);
Andy Hungc25b84a2015-01-14 19:04:10 -08006872 // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
6873 // Adjust for thread->sampleRate() to determine minimum buffer frame count.
6874 // Then triple buffer because Threads do not run synchronously and may not be clock locked.
6875 const size_t frameCount =
6876 3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
6877 // TODO: Consider asynchronous sample rate conversion to handle clock disparity
6878 // from different OutputTracks and their associated MixerThreads (e.g. one may
6879 // nearly empty and the other may be dropping data).
6880
Philip P. Moltmannbda45752020-07-17 16:41:18 -07006881 // TODO b/182392769: use identity util, move to server edge
6882 Identity identity = Identity();
6883 identity.uid = VALUE_OR_FATAL(legacy2aidl_uid_t_int32_t(
6884 IPCThreadState::self()->getCallingUid()));
6885 identity.pid = VALUE_OR_FATAL(legacy2aidl_pid_t_int32_t(
6886 IPCThreadState::self()->getCallingPid()));
Andy Hungc25b84a2015-01-14 19:04:10 -08006887 sp<OutputTrack> outputTrack = new OutputTrack(thread,
Eric Laurent81784c32012-11-19 14:55:58 -08006888 this,
6889 mSampleRate,
Andy Hungc25b84a2015-01-14 19:04:10 -08006890 mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08006891 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08006892 frameCount,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07006893 identity);
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07006894 status_t status = outputTrack != 0 ? outputTrack->initCheck() : (status_t) NO_MEMORY;
6895 if (status != NO_ERROR) {
6896 ALOGE("addOutputTrack() initCheck failed %d", status);
6897 return;
Eric Laurent81784c32012-11-19 14:55:58 -08006898 }
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07006899 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
6900 mOutputTracks.add(outputTrack);
6901 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
6902 updateWaitTime_l();
Eric Laurent81784c32012-11-19 14:55:58 -08006903}
6904
6905void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
6906{
6907 Mutex::Autolock _l(mLock);
6908 for (size_t i = 0; i < mOutputTracks.size(); i++) {
6909 if (mOutputTracks[i]->thread() == thread) {
6910 mOutputTracks[i]->destroy();
6911 mOutputTracks.removeAt(i);
6912 updateWaitTime_l();
Eric Laurentf6870ae2015-05-08 10:50:03 -07006913 if (thread->getOutput() == mOutput) {
6914 mOutput = NULL;
6915 }
Eric Laurent81784c32012-11-19 14:55:58 -08006916 return;
6917 }
6918 }
Eric Laurentf6870ae2015-05-08 10:50:03 -07006919 ALOGV("removeOutputTrack(): unknown thread: %p", thread);
Eric Laurent81784c32012-11-19 14:55:58 -08006920}
6921
6922// caller must hold mLock
6923void AudioFlinger::DuplicatingThread::updateWaitTime_l()
6924{
6925 mWaitTimeMs = UINT_MAX;
6926 for (size_t i = 0; i < mOutputTracks.size(); i++) {
6927 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
6928 if (strong != 0) {
6929 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
6930 if (waitTimeMs < mWaitTimeMs) {
6931 mWaitTimeMs = waitTimeMs;
6932 }
6933 }
6934 }
6935}
6936
6937
6938bool AudioFlinger::DuplicatingThread::outputsReady(
6939 const SortedVector< sp<OutputTrack> > &outputTracks)
6940{
6941 for (size_t i = 0; i < outputTracks.size(); i++) {
6942 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
6943 if (thread == 0) {
6944 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
6945 outputTracks[i].get());
6946 return false;
6947 }
6948 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
6949 // see note at standby() declaration
6950 if (playbackThread->standby() && !playbackThread->isSuspended()) {
6951 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
6952 thread.get());
6953 return false;
6954 }
6955 }
6956 return true;
6957}
6958
Kevin Rocard12381092018-04-11 09:19:59 -07006959void AudioFlinger::DuplicatingThread::sendMetadataToBackend_l(
6960 const StreamOutHalInterface::SourceMetadata& metadata)
Kevin Rocard069c2712018-03-29 19:09:14 -07006961{
Kevin Rocard12381092018-04-11 09:19:59 -07006962 for (auto& outputTrack : outputTracks) { // not mOutputTracks
6963 outputTrack->setMetadatas(metadata.tracks);
6964 }
Kevin Rocard069c2712018-03-29 19:09:14 -07006965}
6966
Eric Laurent81784c32012-11-19 14:55:58 -08006967uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
6968{
6969 return (mWaitTimeMs * 1000) / 2;
6970}
6971
6972void AudioFlinger::DuplicatingThread::cacheParameters_l()
6973{
6974 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
6975 updateWaitTime_l();
6976
6977 MixerThread::cacheParameters_l();
6978}
6979
Eric Laurent6acd1d42017-01-04 14:23:29 -08006980
Eric Laurent81784c32012-11-19 14:55:58 -08006981// ----------------------------------------------------------------------------
6982// Record
6983// ----------------------------------------------------------------------------
6984
6985AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
6986 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08006987 audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -07006988 bool systemReady
Glenn Kasten46909e72013-02-26 09:20:22 -08006989 ) :
Andy Hungcf10d742020-04-28 15:38:24 -07006990 ThreadBase(audioFlinger, id, RECORD, systemReady, false /* isOut */),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07006991 mInput(input),
Mikhail Naganov2534b382019-09-25 13:05:02 -07006992 mSource(mInput),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07006993 mActiveTracks(&this->mLocalLog),
6994 mRsmpInBuffer(NULL),
Glenn Kasten1b291842016-07-18 14:55:21 -07006995 // mRsmpInFrames, mRsmpInFramesP2, and mRsmpInFramesOA are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006996 mRsmpInRear(0)
Glenn Kastenb880f5e2014-05-07 08:43:45 -07006997 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
6998 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006999 // mFastCapture below
7000 , mFastCaptureFutex(0)
7001 // mInputSource
7002 // mPipeSink
7003 // mPipeSource
7004 , mPipeFramesP2(0)
7005 // mPipeMemory
7006 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07007007 , mFastTrackAvail(false)
Eric Laurentd8365c52017-07-16 15:27:05 -07007008 , mBtNrecSuspended(false)
Eric Laurent81784c32012-11-19 14:55:58 -08007009{
Glenn Kastend7dca052015-03-05 16:05:54 -08007010 snprintf(mThreadName, kThreadNameLength, "AudioIn_%X", id);
7011 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08007012
George Burgess IVa8f90c12020-05-14 11:27:19 -07007013 if (mInput->audioHwDev != nullptr) {
Andy Hungc8fddf32018-08-08 18:32:37 -07007014 mIsMsdDevice = strcmp(
7015 mInput->audioHwDev->moduleName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0;
7016 }
7017
Glenn Kastendeca2ae2014-02-07 10:25:56 -08007018 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007019
Andy Hungc8fddf32018-08-08 18:32:37 -07007020 // TODO: We may also match on address as well as device type for
7021 // AUDIO_DEVICE_IN_BUS, AUDIO_DEVICE_IN_BLUETOOTH_A2DP, AUDIO_DEVICE_IN_REMOTE_SUBMIX
jiabinc52b1ff2019-10-31 17:20:42 -07007022 // TODO: This property should be ensure that only contains one single device type.
7023 mTimestampCorrectedDevice = (audio_devices_t)property_get_int64(
7024 "audio.timestamp.corrected_input_device",
Andy Hungc8fddf32018-08-08 18:32:37 -07007025 (int64_t)(mIsMsdDevice ? AUDIO_DEVICE_IN_BUS // turn on by default for MSD
7026 : AUDIO_DEVICE_NONE));
7027
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007028 // create an NBAIO source for the HAL input stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07007029 mInputSource = new AudioStreamInSource(input->stream);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007030 size_t numCounterOffers = 0;
7031 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07007032#if !LOG_NDEBUG
7033 ssize_t index =
7034#else
7035 (void)
7036#endif
7037 mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007038 ALOG_ASSERT(index == 0);
7039
7040 // initialize fast capture depending on configuration
7041 bool initFastCapture;
7042 switch (kUseFastCapture) {
7043 case FastCapture_Never:
7044 initFastCapture = false;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007045 ALOGV("%p kUseFastCapture = Never, initFastCapture = false", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007046 break;
7047 case FastCapture_Always:
7048 initFastCapture = true;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007049 ALOGV("%p kUseFastCapture = Always, initFastCapture = true", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007050 break;
7051 case FastCapture_Static:
Glenn Kasteneb9487e2015-07-22 09:15:17 -07007052 initFastCapture = (mFrameCount * 1000) / mSampleRate < kMinNormalCaptureBufferSizeMs;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007053 ALOGV("%p kUseFastCapture = Static, (%lld * 1000) / %u vs %u, initFastCapture = %d",
7054 this, (long long)mFrameCount, mSampleRate, kMinNormalCaptureBufferSizeMs,
7055 initFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007056 break;
7057 // case FastCapture_Dynamic:
7058 }
7059
7060 if (initFastCapture) {
Glenn Kastend198b852015-03-16 14:55:53 -07007061 // create a Pipe for FastCapture to write to, and for us and fast tracks to read from
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007062 NBAIO_Format format = mInputSource->format();
Glenn Kasten1b291842016-07-18 14:55:21 -07007063 // quadruple-buffering of 20 ms each; this ensures we can sleep for 20ms in RecordThread
7064 size_t pipeFramesP2 = roundup(4 * FMS_20 * mSampleRate / 1000);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007065 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007066 void *pipeBuffer = nullptr;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007067 const sp<MemoryDealer> roHeap(readOnlyHeap());
7068 sp<IMemory> pipeMemory;
7069 if ((roHeap == 0) ||
7070 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07007071 (pipeBuffer = pipeMemory->unsecurePointer()) == nullptr) {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007072 ALOGE("not enough memory for pipe buffer size=%zu; "
7073 "roHeap=%p, pipeMemory=%p, pipeBuffer=%p; roHeapSize: %lld",
7074 pipeSize, roHeap.get(), pipeMemory.get(), pipeBuffer,
7075 (long long)kRecordThreadReadOnlyHeapSize);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007076 goto failed;
7077 }
7078 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
7079 memset(pipeBuffer, 0, pipeSize);
7080 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
7081 const NBAIO_Format offers[1] = {format};
7082 size_t numCounterOffers = 0;
7083 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
7084 ALOG_ASSERT(index == 0);
7085 mPipeSink = pipe;
7086 PipeReader *pipeReader = new PipeReader(*pipe);
7087 numCounterOffers = 0;
7088 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
7089 ALOG_ASSERT(index == 0);
7090 mPipeSource = pipeReader;
7091 mPipeFramesP2 = pipeFramesP2;
7092 mPipeMemory = pipeMemory;
7093
7094 // create fast capture
7095 mFastCapture = new FastCapture();
7096 FastCaptureStateQueue *sq = mFastCapture->sq();
7097#ifdef STATE_QUEUE_DUMP
7098 // FIXME
7099#endif
7100 FastCaptureState *state = sq->begin();
7101 state->mCblk = NULL;
7102 state->mInputSource = mInputSource.get();
7103 state->mInputSourceGen++;
7104 state->mPipeSink = pipe;
7105 state->mPipeSinkGen++;
7106 state->mFrameCount = mFrameCount;
7107 state->mCommand = FastCaptureState::COLD_IDLE;
7108 // already done in constructor initialization list
7109 //mFastCaptureFutex = 0;
7110 state->mColdFutexAddr = &mFastCaptureFutex;
7111 state->mColdGen++;
7112 state->mDumpState = &mFastCaptureDumpState;
7113#ifdef TEE_SINK
7114 // FIXME
7115#endif
7116 mFastCaptureNBLogWriter = audioFlinger->newWriter_l(kFastCaptureLogSize, "FastCapture");
7117 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
7118 sq->end();
7119 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
7120
7121 // start the fast capture
7122 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
7123 pid_t tid = mFastCapture->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07007124 sendPrioConfigEvent(getpid(), tid, kPriorityFastCapture, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08007125 stream()->setHalThreadPriority(kPriorityFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007126#ifdef AUDIO_WATCHDOG
7127 // FIXME
7128#endif
7129
Glenn Kasten6e6704c2014-07-03 10:20:00 -07007130 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007131 }
Andy Hung8946a282018-04-19 20:04:56 -07007132#ifdef TEE_SINK
7133 mTee.set(mInputSource->format(), NBAIO_Tee::TEE_FLAG_INPUT_THREAD);
7134 mTee.setId(std::string("_") + std::to_string(mId) + "_C");
7135#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007136failed: ;
7137
7138 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08007139}
7140
Eric Laurent81784c32012-11-19 14:55:58 -08007141AudioFlinger::RecordThread::~RecordThread()
7142{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007143 if (mFastCapture != 0) {
7144 FastCaptureStateQueue *sq = mFastCapture->sq();
7145 FastCaptureState *state = sq->begin();
7146 if (state->mCommand == FastCaptureState::COLD_IDLE) {
7147 int32_t old = android_atomic_inc(&mFastCaptureFutex);
7148 if (old == -1) {
7149 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
7150 }
7151 }
7152 state->mCommand = FastCaptureState::EXIT;
7153 sq->end();
7154 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
7155 mFastCapture->join();
7156 mFastCapture.clear();
7157 }
7158 mAudioFlinger->unregisterWriter(mFastCaptureNBLogWriter);
Glenn Kasten481fb672013-09-30 14:39:28 -07007159 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung57446612015-04-19 23:56:46 -07007160 free(mRsmpInBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08007161}
7162
7163void AudioFlinger::RecordThread::onFirstRef()
7164{
Glenn Kastend7dca052015-03-05 16:05:54 -08007165 run(mThreadName, PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08007166}
7167
Eric Laurent555530a2017-02-07 18:17:24 -08007168void AudioFlinger::RecordThread::preExit()
7169{
7170 ALOGV(" preExit()");
7171 Mutex::Autolock _l(mLock);
7172 for (size_t i = 0; i < mTracks.size(); i++) {
7173 sp<RecordTrack> track = mTracks[i];
7174 track->invalidate();
7175 }
7176 mActiveTracks.clear();
7177 mStartStopCond.broadcast();
7178}
7179
Eric Laurent81784c32012-11-19 14:55:58 -08007180bool AudioFlinger::RecordThread::threadLoop()
7181{
Eric Laurent81784c32012-11-19 14:55:58 -08007182 nsecs_t lastWarning = 0;
7183
7184 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08007185
Glenn Kastenf10ffec2013-11-20 16:40:08 -08007186reacquire_wakelock:
7187 sp<RecordTrack> activeTrack;
7188 {
7189 Mutex::Autolock _l(mLock);
Andy Hungdae27702016-10-31 14:01:16 -07007190 acquireWakeLock_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08007191 }
7192
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007193 // used to request a deferred sleep, to be executed later while mutex is unlocked
7194 uint32_t sleepUs = 0;
7195
Andy Hung446f4df2019-02-21 12:26:41 -08007196 int64_t lastLoopCountRead = -2; // never matches "previous" loop, when loopCount = 0.
7197
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007198 // loop while there is work to do
Andy Hung446f4df2019-02-21 12:26:41 -08007199 for (int64_t loopCount = 0;; ++loopCount) { // loopCount used for statistics tracking
Glenn Kastenc527a7c2013-08-13 15:43:49 -07007200 Vector< sp<EffectChain> > effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07007201
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007202 // activeTracks accumulates a copy of a subset of mActiveTracks
7203 Vector< sp<RecordTrack> > activeTracks;
7204
Glenn Kasten735f45f2014-08-18 15:51:59 -07007205 // reference to the (first and only) active fast track
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007206 sp<RecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07007207
Glenn Kasten735f45f2014-08-18 15:51:59 -07007208 // reference to a fast track which is about to be removed
7209 sp<RecordTrack> fastTrackToRemove;
7210
Eric Laurent33403f02020-05-29 18:35:06 -07007211 bool silenceFastCapture = false;
7212
Eric Laurent81784c32012-11-19 14:55:58 -08007213 { // scope for mLock
7214 Mutex::Autolock _l(mLock);
Eric Laurent000a4192014-01-29 15:17:32 -08007215
Eric Laurent021cf962014-05-13 10:18:14 -07007216 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08007217
Eric Laurent000a4192014-01-29 15:17:32 -08007218 // check exitPending here because checkForNewParameters_l() and
7219 // checkForNewParameters_l() can temporarily release mLock
7220 if (exitPending()) {
7221 break;
7222 }
7223
Eric Laurent5c25d562016-07-13 17:17:45 -07007224 // sleep with mutex unlocked
7225 if (sleepUs > 0) {
Glenn Kastenf9715e42016-07-13 14:02:03 -07007226 ATRACE_BEGIN("sleepC");
Eric Laurent5c25d562016-07-13 17:17:45 -07007227 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)sleepUs));
7228 ATRACE_END();
7229 sleepUs = 0;
7230 continue;
7231 }
7232
Glenn Kasten2b806402013-11-20 16:37:38 -08007233 // if no active track(s), then standby and release wakelock
7234 size_t size = mActiveTracks.size();
7235 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07007236 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07007237 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08007238 releaseWakeLock_l();
7239 ALOGV("RecordThread: loop stopping");
7240 // go to sleep
7241 mWaitWorkCV.wait(mLock);
7242 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08007243 goto reacquire_wakelock;
7244 }
7245
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007246 bool doBroadcast = false;
Eric Laurent5c25d562016-07-13 17:17:45 -07007247 bool allStopped = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007248 for (size_t i = 0; i < size; ) {
Glenn Kasten9e982352013-08-14 14:39:50 -07007249
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007250 activeTrack = mActiveTracks[i];
7251 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07007252 if (activeTrack->isFastTrack()) {
7253 ALOG_ASSERT(fastTrackToRemove == 0);
7254 fastTrackToRemove = activeTrack;
7255 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007256 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08007257 mActiveTracks.remove(activeTrack);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007258 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07007259 continue;
7260 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007261
7262 TrackBase::track_state activeTrackState = activeTrack->mState;
7263 switch (activeTrackState) {
7264
7265 case TrackBase::PAUSING:
7266 mActiveTracks.remove(activeTrack);
Andy Hungce685402018-10-05 17:23:27 -07007267 activeTrack->mState = TrackBase::PAUSED;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007268 doBroadcast = true;
7269 size--;
7270 continue;
7271
7272 case TrackBase::STARTING_1:
7273 sleepUs = 10000;
7274 i++;
Eric Laurent5c25d562016-07-13 17:17:45 -07007275 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007276 continue;
7277
7278 case TrackBase::STARTING_2:
7279 doBroadcast = true;
Andy Hungcf10d742020-04-28 15:38:24 -07007280 if (mStandby) {
7281 mThreadMetrics.logBeginInterval();
7282 mStandby = false;
7283 }
Glenn Kasten9e982352013-08-14 14:39:50 -07007284 activeTrack->mState = TrackBase::ACTIVE;
Eric Laurent5c25d562016-07-13 17:17:45 -07007285 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007286 break;
7287
7288 case TrackBase::ACTIVE:
Eric Laurent5c25d562016-07-13 17:17:45 -07007289 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007290 break;
7291
Andy Hungce685402018-10-05 17:23:27 -07007292 case TrackBase::IDLE: // cannot be on ActiveTracks if idle
7293 case TrackBase::PAUSED: // cannot be on ActiveTracks if paused
7294 case TrackBase::STOPPED: // cannot be on ActiveTracks if destroyed/terminated
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007295 default:
Andy Hungce685402018-10-05 17:23:27 -07007296 LOG_ALWAYS_FATAL("%s: Unexpected active track state:%d, id:%d, tracks:%zu",
7297 __func__, activeTrackState, activeTrack->id(), size);
Glenn Kasten9e982352013-08-14 14:39:50 -07007298 }
Glenn Kasten9e982352013-08-14 14:39:50 -07007299
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007300 if (activeTrack->isFastTrack()) {
7301 ALOG_ASSERT(!mFastTrackAvail);
7302 ALOG_ASSERT(fastTrack == 0);
Eric Laurent33403f02020-05-29 18:35:06 -07007303 // if the active fast track is silenced either:
7304 // 1) silence the whole capture from fast capture buffer if this is
7305 // the only active track
7306 // 2) invalidate this track: this will cause the client to reconnect and possibly
7307 // be invalidated again until unsilenced
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02007308 bool invalidate = false;
Eric Laurent33403f02020-05-29 18:35:06 -07007309 if (activeTrack->isSilenced()) {
7310 if (size > 1) {
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02007311 invalidate = true;
Eric Laurent33403f02020-05-29 18:35:06 -07007312 } else {
7313 silenceFastCapture = true;
7314 }
7315 }
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02007316 // Invalidate fast tracks if access to audio history is required as this is not
7317 // possible with fast tracks. Once the fast track has been invalidated, no new
7318 // fast track will be created until mMaxSharedAudioHistoryMs is cleared.
7319 if (mMaxSharedAudioHistoryMs != 0) {
7320 invalidate = true;
7321 }
7322 if (invalidate) {
7323 activeTrack->invalidate();
7324 ALOG_ASSERT(fastTrackToRemove == 0);
7325 fastTrackToRemove = activeTrack;
7326 removeTrack_l(activeTrack);
7327 mActiveTracks.remove(activeTrack);
7328 size--;
7329 continue;
7330 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007331 fastTrack = activeTrack;
7332 }
Eric Laurent33403f02020-05-29 18:35:06 -07007333
7334 activeTracks.add(activeTrack);
7335 i++;
7336
Glenn Kasten9e982352013-08-14 14:39:50 -07007337 }
Eric Laurent5c25d562016-07-13 17:17:45 -07007338
Andy Hungdae27702016-10-31 14:01:16 -07007339 mActiveTracks.updatePowerState(this);
7340
Kevin Rocard069c2712018-03-29 19:09:14 -07007341 updateMetadata_l();
7342
Eric Laurent5c25d562016-07-13 17:17:45 -07007343 if (allStopped) {
7344 standbyIfNotAlreadyInStandby();
7345 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007346 if (doBroadcast) {
7347 mStartStopCond.broadcast();
7348 }
7349
7350 // sleep if there are no active tracks to process
Eric Tan39ec8d62018-07-24 09:49:29 -07007351 if (activeTracks.isEmpty()) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007352 if (sleepUs == 0) {
7353 sleepUs = kRecordThreadSleepUs;
7354 }
7355 continue;
7356 }
7357 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07007358
Eric Laurent81784c32012-11-19 14:55:58 -08007359 lockEffectChains_l(effectChains);
7360 }
7361
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007362 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07007363
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007364 size_t size = effectChains.size();
7365 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07007366 // thread mutex is not locked, but effect chain is locked
7367 effectChains[i]->process_l();
7368 }
7369
Glenn Kasten735f45f2014-08-18 15:51:59 -07007370 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007371 if (mFastCapture != 0) {
7372 FastCaptureStateQueue *sq = mFastCapture->sq();
7373 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07007374 bool didModify = false;
7375 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007376 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
7377 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
7378 if (state->mCommand == FastCaptureState::COLD_IDLE) {
7379 int32_t old = android_atomic_inc(&mFastCaptureFutex);
7380 if (old == -1) {
7381 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
7382 }
7383 }
7384 state->mCommand = FastCaptureState::READ_WRITE;
7385#if 0 // FIXME
7386 mFastCaptureDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08007387 FastThreadDumpState::kSamplingNforLowRamDevice :
7388 FastThreadDumpState::kSamplingN);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007389#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07007390 didModify = true;
7391 }
7392 audio_track_cblk_t *cblkOld = state->mCblk;
7393 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
7394 if (cblkNew != cblkOld) {
7395 state->mCblk = cblkNew;
7396 // block until acked if removing a fast track
7397 if (cblkOld != NULL) {
7398 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
7399 }
7400 didModify = true;
7401 }
jiabin01c8f562018-07-19 17:47:28 -07007402 AudioBufferProvider* abp = (fastTrack != 0 && fastTrack->isPatchTrack()) ?
7403 reinterpret_cast<AudioBufferProvider*>(fastTrack.get()) : nullptr;
7404 if (state->mFastPatchRecordBufferProvider != abp) {
7405 state->mFastPatchRecordBufferProvider = abp;
7406 state->mFastPatchRecordFormat = fastTrack == 0 ?
7407 AUDIO_FORMAT_INVALID : fastTrack->format();
7408 didModify = true;
7409 }
Eric Laurent33403f02020-05-29 18:35:06 -07007410 if (state->mSilenceCapture != silenceFastCapture) {
7411 state->mSilenceCapture = silenceFastCapture;
7412 didModify = true;
7413 }
Glenn Kasten735f45f2014-08-18 15:51:59 -07007414 sq->end(didModify);
7415 if (didModify) {
7416 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007417#if 0
7418 if (kUseFastCapture == FastCapture_Dynamic) {
7419 mNormalSource = mPipeSource;
7420 }
7421#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007422 }
7423 }
7424
Glenn Kasten735f45f2014-08-18 15:51:59 -07007425 // now run the fast track destructor with thread mutex unlocked
7426 fastTrackToRemove.clear();
7427
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007428 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
7429 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
7430 // slow, then this RecordThread will overrun by not calling HAL read often enough.
7431 // If destination is non-contiguous, first read past the nominal end of buffer, then
7432 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07007433
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007434 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007435 ssize_t framesRead;
Andy Hung446f4df2019-02-21 12:26:41 -08007436 const int64_t lastIoBeginNs = systemTime(); // start IO timing
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007437
7438 // If an NBAIO source is present, use it to read the normal capture's data
7439 if (mPipeSource != 0) {
Andy Hung156317a2018-08-02 11:49:29 -07007440 size_t framesToRead = min(mRsmpInFramesOA - rear, mRsmpInFramesP2 / 2);
Andy Hungd5b638f2018-04-30 13:56:10 -07007441
7442 // The audio fifo read() returns OVERRUN on overflow, and advances the read pointer
7443 // to the full buffer point (clearing the overflow condition). Upon OVERRUN error,
7444 // we immediately retry the read() to get data and prevent another overflow.
7445 for (int retries = 0; retries <= 2; ++retries) {
7446 ALOGW_IF(retries > 0, "overrun on read from pipe, retry #%d", retries);
7447 framesRead = mPipeSource->read((uint8_t*)mRsmpInBuffer + rear * mFrameSize,
7448 framesToRead);
7449 if (framesRead != OVERRUN) break;
7450 }
7451
Andy Hung7a3dc6b2018-05-01 16:39:51 -07007452 const ssize_t availableToRead = mPipeSource->availableToRead();
7453 if (availableToRead >= 0) {
Glenn Kastena2f59b32020-08-03 16:37:24 -07007454 // PipeSource is the primary clock. It is up to the AudioRecord client to keep up.
Andy Hung7a3dc6b2018-05-01 16:39:51 -07007455 LOG_ALWAYS_FATAL_IF((size_t)availableToRead > mPipeFramesP2,
7456 "more frames to read than fifo size, %zd > %zu",
7457 availableToRead, mPipeFramesP2);
7458 const size_t pipeFramesFree = mPipeFramesP2 - availableToRead;
7459 const size_t sleepFrames = min(pipeFramesFree, mRsmpInFramesP2) / 2;
7460 ALOGVV("mPipeFramesP2:%zu mRsmpInFramesP2:%zu sleepFrames:%zu availableToRead:%zd",
7461 mPipeFramesP2, mRsmpInFramesP2, sleepFrames, availableToRead);
Glenn Kasten1b291842016-07-18 14:55:21 -07007462 sleepUs = (sleepFrames * 1000000LL) / mSampleRate;
7463 }
7464 if (framesRead < 0) {
7465 status_t status = (status_t) framesRead;
7466 switch (status) {
7467 case OVERRUN:
7468 ALOGW("overrun on read from pipe");
7469 framesRead = 0;
7470 break;
7471 case NEGOTIATE:
7472 ALOGE("re-negotiation is needed");
7473 framesRead = -1; // Will cause an attempt to recover.
7474 break;
7475 default:
7476 ALOGE("unknown error %d on read from pipe", status);
7477 break;
7478 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007479 }
7480 // otherwise use the HAL / AudioStreamIn directly
7481 } else {
Glenn Kastenec6a7032016-03-14 07:40:23 -07007482 ATRACE_BEGIN("read");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007483 size_t bytesRead;
Mikhail Naganov2534b382019-09-25 13:05:02 -07007484 status_t result = mSource->read(
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007485 (uint8_t*)mRsmpInBuffer + rear * mFrameSize, mBufferSize, &bytesRead);
Glenn Kastenec6a7032016-03-14 07:40:23 -07007486 ATRACE_END();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007487 if (result < 0) {
7488 framesRead = result;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007489 } else {
7490 framesRead = bytesRead / mFrameSize;
7491 }
7492 }
7493
Andy Hung446f4df2019-02-21 12:26:41 -08007494 const int64_t lastIoEndNs = systemTime(); // end IO timing
7495
Andy Hung3f0c9022016-01-15 17:49:46 -08007496 // Update server timestamp with server stats
7497 // systemTime() is optional if the hardware supports timestamps.
Andy Hung743f6402020-06-03 13:17:04 -07007498 if (framesRead >= 0) {
7499 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += framesRead;
7500 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = lastIoEndNs;
7501 }
Andy Hung3f0c9022016-01-15 17:49:46 -08007502
7503 // Update server timestamp with kernel stats
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007504 if (mPipeSource.get() == nullptr /* don't obtain for FastCapture, could block */) {
Andy Hung3f0c9022016-01-15 17:49:46 -08007505 int64_t position, time;
Andy Hung2e2c0bb2018-06-11 19:13:11 -07007506 if (mStandby) {
Dean Wheatley12473e92021-03-18 23:00:55 +11007507 mTimestampVerifier.discontinuity(audio_is_linear_pcm(mFormat) ?
7508 mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS :
7509 mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Mikhail Naganov2534b382019-09-25 13:05:02 -07007510 } else if (mSource->getCapturePosition(&position, &time) == NO_ERROR
Andy Hungc8fddf32018-08-08 18:32:37 -07007511 && time > mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]) {
7512
7513 mTimestampVerifier.add(position, time, mSampleRate);
7514
7515 // Correct timestamps
7516 if (isTimestampCorrectionEnabled()) {
Dean Wheatley56a583e2020-05-08 15:12:17 +10007517 ALOGVV("TS_BEFORE: %d %lld %lld",
Andy Hungc8fddf32018-08-08 18:32:37 -07007518 id(), (long long)time, (long long)position);
7519 auto correctedTimestamp = mTimestampVerifier.getLastCorrectedTimestamp();
7520 position = correctedTimestamp.mFrames;
7521 time = correctedTimestamp.mTimeNs;
Dean Wheatley56a583e2020-05-08 15:12:17 +10007522 ALOGVV("TS_AFTER: %d %lld %lld",
Andy Hungc8fddf32018-08-08 18:32:37 -07007523 id(), (long long)time, (long long)position);
7524 }
7525
Andy Hung3f0c9022016-01-15 17:49:46 -08007526 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = position;
7527 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] = time;
7528 // Note: In general record buffers should tend to be empty in
7529 // a properly running pipeline.
7530 //
7531 // Also, it is not advantageous to call get_presentation_position during the read
7532 // as the read obtains a lock, preventing the timestamp call from executing.
Andy Hung2e2c0bb2018-06-11 19:13:11 -07007533 } else {
7534 mTimestampVerifier.error();
Andy Hung3f0c9022016-01-15 17:49:46 -08007535 }
7536 }
Andy Hunge6c37112019-02-26 17:38:10 -08007537
7538 // From the timestamp, input read latency is negative output write latency.
7539 const audio_input_flags_t flags = mInput != NULL ? mInput->flags : AUDIO_INPUT_FLAG_NONE;
7540 const double latencyMs = RecordTrack::checkServerLatencySupported(mFormat, flags)
7541 ? - mTimestamp.getOutputServerLatencyMs(mSampleRate) : 0.;
7542 if (latencyMs != 0.) { // note 0. means timestamp is empty.
7543 mLatencyMs.add(latencyMs);
7544 }
7545
Andy Hung3f0c9022016-01-15 17:49:46 -08007546 // Use this to track timestamp information
7547 // ALOGD("%s", mTimestamp.toString().c_str());
7548
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007549 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07007550 ALOGE("read failed: framesRead=%zd", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007551 // Force input into standby so that it tries to recover at next read attempt
7552 inputStandBy();
7553 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007554 }
7555 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07007556 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07007557 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007558 ALOG_ASSERT(framesRead > 0);
Andy Hung6427e442018-08-09 12:51:02 -07007559 mFramesRead += framesRead;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007560
Andy Hung8946a282018-04-19 20:04:56 -07007561#ifdef TEE_SINK
7562 (void)mTee.write((uint8_t*)mRsmpInBuffer + rear * mFrameSize, framesRead);
7563#endif
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007564 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07007565 {
7566 size_t part1 = mRsmpInFramesP2 - rear;
7567 if ((size_t) framesRead > part1) {
Andy Hung57446612015-04-19 23:56:46 -07007568 memcpy(mRsmpInBuffer, (uint8_t*)mRsmpInBuffer + mRsmpInFramesP2 * mFrameSize,
Glenn Kasten3d61bc12014-06-16 10:25:20 -07007569 (framesRead - part1) * mFrameSize);
7570 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007571 }
Dean Wheatleyfd56e812020-11-06 22:32:21 +11007572 mRsmpInRear = audio_utils::safe_add_overflow(mRsmpInRear, (int32_t)framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007573
7574 size = activeTracks.size();
Svet Ganovf4ddfef2018-01-16 07:37:58 -08007575
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007576 // loop over each active track
7577 for (size_t i = 0; i < size; i++) {
7578 activeTrack = activeTracks[i];
7579
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007580 // skip fast tracks, as those are handled directly by FastCapture
7581 if (activeTrack->isFastTrack()) {
7582 continue;
7583 }
7584
Andy Hung73c02e42015-03-29 01:13:58 -07007585 // TODO: This code probably should be moved to RecordTrack.
Andy Hung97a893e2015-03-29 01:03:07 -07007586 // TODO: Update the activeTrack buffer converter in case of reconfigure.
7587
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007588 enum {
7589 OVERRUN_UNKNOWN,
7590 OVERRUN_TRUE,
7591 OVERRUN_FALSE
7592 } overrun = OVERRUN_UNKNOWN;
7593
7594 // loop over getNextBuffer to handle circular sink
7595 for (;;) {
7596
7597 activeTrack->mSink.frameCount = ~0;
7598 status_t status = activeTrack->getNextBuffer(&activeTrack->mSink);
7599 size_t framesOut = activeTrack->mSink.frameCount;
7600 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
7601
Andy Hung73c02e42015-03-29 01:13:58 -07007602 // check available frames and handle overrun conditions
7603 // if the record track isn't draining fast enough.
7604 bool hasOverrun;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007605 size_t framesIn;
Andy Hung73c02e42015-03-29 01:13:58 -07007606 activeTrack->mResamplerBufferProvider->sync(&framesIn, &hasOverrun);
7607 if (hasOverrun) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007608 overrun = OVERRUN_TRUE;
7609 }
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007610 if (framesOut == 0 || framesIn == 0) {
7611 break;
7612 }
7613
Andy Hung6770c6f2015-04-07 13:43:36 -07007614 // Don't allow framesOut to be larger than what is possible with resampling
7615 // from framesIn.
7616 // This isn't strictly necessary but helps limit buffer resizing in
7617 // RecordBufferConverter. TODO: remove when no longer needed.
7618 framesOut = min(framesOut,
7619 destinationFramesPossible(
7620 framesIn, mSampleRate, activeTrack->mSampleRate));
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07007621
7622 if (activeTrack->isDirect()) {
Daniel Van Veen9e2376e2018-09-27 14:37:58 +10007623 // No RecordBufferConverter used for direct streams. Pass
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07007624 // straight from RecordThread buffer to RecordTrack buffer.
7625 AudioBufferProvider::Buffer buffer;
7626 buffer.frameCount = framesOut;
7627 status_t status = activeTrack->mResamplerBufferProvider->getNextBuffer(&buffer);
7628 if (status == OK && buffer.frameCount != 0) {
7629 ALOGV_IF(buffer.frameCount != framesOut,
7630 "%s() read less than expected (%zu vs %zu)",
7631 __func__, buffer.frameCount, framesOut);
7632 framesOut = buffer.frameCount;
Daniel Van Veen9e2376e2018-09-27 14:37:58 +10007633 memcpy(activeTrack->mSink.raw, buffer.raw, buffer.frameCount * mFrameSize);
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07007634 activeTrack->mResamplerBufferProvider->releaseBuffer(&buffer);
7635 } else {
7636 framesOut = 0;
7637 ALOGE("%s() cannot fill request, status: %d, frameCount: %zu",
7638 __func__, status, buffer.frameCount);
7639 }
7640 } else {
7641 // process frames from the RecordThread buffer provider to the RecordTrack
7642 // buffer
7643 framesOut = activeTrack->mRecordBufferConverter->convert(
7644 activeTrack->mSink.raw,
7645 activeTrack->mResamplerBufferProvider,
7646 framesOut);
7647 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007648
7649 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
7650 overrun = OVERRUN_FALSE;
7651 }
7652
7653 if (activeTrack->mFramesToDrop == 0) {
7654 if (framesOut > 0) {
7655 activeTrack->mSink.frameCount = framesOut;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08007656 // Sanitize before releasing if the track has no access to the source data
7657 // An idle UID receives silence from non virtual devices until active
7658 if (activeTrack->isSilenced()) {
Jean-Michel Trividdf87ef2019-08-20 15:42:04 -07007659 memset(activeTrack->mSink.raw, 0, framesOut * activeTrack->frameSize());
Svet Ganovf4ddfef2018-01-16 07:37:58 -08007660 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007661 activeTrack->releaseBuffer(&activeTrack->mSink);
7662 }
7663 } else {
7664 // FIXME could do a partial drop of framesOut
7665 if (activeTrack->mFramesToDrop > 0) {
Mikhail Naganov6d91ba52019-03-26 14:35:28 -07007666 activeTrack->mFramesToDrop -= (ssize_t)framesOut;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007667 if (activeTrack->mFramesToDrop <= 0) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08007668 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007669 }
7670 } else {
7671 activeTrack->mFramesToDrop += framesOut;
7672 if (activeTrack->mFramesToDrop >= 0 || activeTrack->mSyncStartEvent == 0 ||
7673 activeTrack->mSyncStartEvent->isCancelled()) {
7674 ALOGW("Synced record %s, session %d, trigger session %d",
7675 (activeTrack->mFramesToDrop >= 0) ? "timed out" : "cancelled",
7676 activeTrack->sessionId(),
7677 (activeTrack->mSyncStartEvent != 0) ?
Glenn Kastend848eb42016-03-08 13:42:11 -08007678 activeTrack->mSyncStartEvent->triggerSession() :
7679 AUDIO_SESSION_NONE);
Glenn Kasten25f4aa82014-02-07 10:50:43 -08007680 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007681 }
7682 }
7683 }
7684
7685 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007686 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07007687 }
7688 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007689
7690 switch (overrun) {
7691 case OVERRUN_TRUE:
7692 // client isn't retrieving buffers fast enough
7693 if (!activeTrack->setOverflow()) {
7694 nsecs_t now = systemTime();
7695 // FIXME should lastWarning per track?
7696 if ((now - lastWarning) > kWarningThrottleNs) {
7697 ALOGW("RecordThread: buffer overflow");
7698 lastWarning = now;
7699 }
7700 }
7701 break;
7702 case OVERRUN_FALSE:
7703 activeTrack->clearOverflow();
7704 break;
7705 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007706 break;
7707 }
7708
Andy Hung3f0c9022016-01-15 17:49:46 -08007709 // update frame information and push timestamp out
7710 activeTrack->updateTrackFrameInfo(
Andy Hung6ae58432016-02-16 18:32:24 -08007711 activeTrack->mServerProxy->framesReleased(),
Andy Hung3f0c9022016-01-15 17:49:46 -08007712 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER],
7713 mSampleRate, mTimestamp);
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07007714 }
7715
Glenn Kasten3d61bc12014-06-16 10:25:20 -07007716unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08007717 // enable changes in effect chain
7718 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07007719 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurentcccbc762019-04-05 14:20:05 -07007720 if (audio_has_proportional_frames(mFormat)
7721 && loopCount == lastLoopCountRead + 1) {
7722 const int64_t readPeriodNs = lastIoEndNs - mLastIoEndNs;
7723 const double jitterMs =
7724 TimestampVerifier<int64_t, int64_t>::computeJitterMs(
7725 {framesRead, readPeriodNs},
7726 {0, 0} /* lastTimestamp */, mSampleRate);
7727 const double processMs = (lastIoBeginNs - mLastIoEndNs) * 1e-6;
7728
7729 Mutex::Autolock _l(mLock);
7730 mIoJitterMs.add(jitterMs);
7731 mProcessTimeMs.add(processMs);
7732 }
7733 // update timing info.
7734 mLastIoBeginNs = lastIoBeginNs;
7735 mLastIoEndNs = lastIoEndNs;
7736 lastLoopCountRead = loopCount;
Eric Laurent81784c32012-11-19 14:55:58 -08007737 }
7738
Glenn Kasten93e471f2013-08-19 08:40:07 -07007739 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08007740
7741 {
7742 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07007743 for (size_t i = 0; i < mTracks.size(); i++) {
7744 sp<RecordTrack> track = mTracks[i];
7745 track->invalidate();
7746 }
Glenn Kasten2b806402013-11-20 16:37:38 -08007747 mActiveTracks.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08007748 mStartStopCond.broadcast();
7749 }
7750
7751 releaseWakeLock();
7752
7753 ALOGV("RecordThread %p exiting", this);
7754 return false;
7755}
7756
Glenn Kasten93e471f2013-08-19 08:40:07 -07007757void AudioFlinger::RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08007758{
7759 if (!mStandby) {
7760 inputStandBy();
Andy Hungcf10d742020-04-28 15:38:24 -07007761 mThreadMetrics.logEndInterval();
Eric Laurent81784c32012-11-19 14:55:58 -08007762 mStandby = true;
7763 }
7764}
7765
7766void AudioFlinger::RecordThread::inputStandBy()
7767{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007768 // Idle the fast capture if it's currently running
7769 if (mFastCapture != 0) {
7770 FastCaptureStateQueue *sq = mFastCapture->sq();
7771 FastCaptureState *state = sq->begin();
7772 if (!(state->mCommand & FastCaptureState::IDLE)) {
7773 state->mCommand = FastCaptureState::COLD_IDLE;
7774 state->mColdFutexAddr = &mFastCaptureFutex;
7775 state->mColdGen++;
7776 mFastCaptureFutex = 0;
7777 sq->end();
7778 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
7779 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
7780#if 0
7781 if (kUseFastCapture == FastCapture_Dynamic) {
7782 // FIXME
7783 }
7784#endif
7785#ifdef AUDIO_WATCHDOG
7786 // FIXME
7787#endif
7788 } else {
7789 sq->end(false /*didModify*/);
7790 }
7791 }
Mikhail Naganov2534b382019-09-25 13:05:02 -07007792 status_t result = mSource->standby();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007793 ALOGE_IF(result != OK, "Error when putting input stream into standby: %d", result);
Andy Hungad6d52d2016-07-18 13:42:03 -07007794
7795 // If going into standby, flush the pipe source.
7796 if (mPipeSource.get() != nullptr) {
7797 const ssize_t flushed = mPipeSource->flush();
7798 if (flushed > 0) {
7799 ALOGV("Input standby flushed PipeSource %zd frames", flushed);
7800 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += flushed;
7801 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
7802 }
7803 }
Eric Laurent81784c32012-11-19 14:55:58 -08007804}
7805
Glenn Kasten05997e22014-03-13 15:08:33 -07007806// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastene198c362013-08-13 09:13:36 -07007807sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
Eric Laurent81784c32012-11-19 14:55:58 -08007808 const sp<AudioFlinger::Client>& client,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07007809 const audio_attributes_t& attr,
Eric Laurentf14db3c2017-12-08 14:20:36 -08007810 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08007811 audio_format_t format,
7812 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08007813 size_t *pFrameCount,
Glenn Kastend848eb42016-03-08 13:42:11 -08007814 audio_session_t sessionId,
Eric Laurentf14db3c2017-12-08 14:20:36 -08007815 size_t *pNotificationFrameCount,
Eric Laurent09f1ed22019-04-24 17:45:17 -07007816 pid_t creatorPid,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07007817 const Identity& identity,
Eric Laurent05067782016-06-01 18:27:28 -07007818 audio_input_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08007819 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08007820 status_t *status,
Eric Laurentec376dc2021-04-08 20:41:22 +02007821 audio_port_handle_t portId,
7822 int32_t maxSharedAudioHistoryMs)
Eric Laurent81784c32012-11-19 14:55:58 -08007823{
Glenn Kasten74935e42013-12-19 08:56:45 -08007824 size_t frameCount = *pFrameCount;
Eric Laurentf14db3c2017-12-08 14:20:36 -08007825 size_t notificationFrameCount = *pNotificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08007826 sp<RecordTrack> track;
7827 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07007828 audio_input_flags_t inputFlags = mInput->flags;
Eric Laurentf14db3c2017-12-08 14:20:36 -08007829 audio_input_flags_t requestedFlags = *flags;
7830 uint32_t sampleRate;
Eric Laurentec376dc2021-04-08 20:41:22 +02007831 Identity checkedIdentity = AudioFlinger::checkIdentityPackage(identity);
Eric Laurentf14db3c2017-12-08 14:20:36 -08007832
7833 lStatus = initCheck();
7834 if (lStatus != NO_ERROR) {
7835 ALOGE("createRecordTrack_l() audio driver not initialized");
7836 goto Exit;
7837 }
7838
Mikhail Naganovce9f2652018-07-16 11:09:24 -07007839 if (!audio_is_linear_pcm(mFormat) && (*flags & AUDIO_INPUT_FLAG_DIRECT) == 0) {
7840 ALOGE("createRecordTrack_l() on an encoded stream requires AUDIO_INPUT_FLAG_DIRECT");
7841 lStatus = BAD_VALUE;
7842 goto Exit;
7843 }
7844
Eric Laurentec376dc2021-04-08 20:41:22 +02007845 if (maxSharedAudioHistoryMs != 0) {
7846 if (!captureHotwordAllowed(checkedIdentity)) {
7847 lStatus = PERMISSION_DENIED;
7848 goto Exit;
7849 }
Eric Laurentec376dc2021-04-08 20:41:22 +02007850 if (maxSharedAudioHistoryMs < 0
7851 || maxSharedAudioHistoryMs > AudioFlinger::kMaxSharedAudioHistoryMs) {
7852 lStatus = BAD_VALUE;
7853 goto Exit;
7854 }
7855 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08007856 if (*pSampleRate == 0) {
7857 *pSampleRate = mSampleRate;
7858 }
7859 sampleRate = *pSampleRate;
Eric Laurent05067782016-06-01 18:27:28 -07007860
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02007861 // special case for FAST flag considered OK if fast capture is present and access to
7862 // audio history is not required
7863 if (hasFastCapture() && mMaxSharedAudioHistoryMs == 0) {
Eric Laurent05067782016-06-01 18:27:28 -07007864 inputFlags = (audio_input_flags_t)(inputFlags | AUDIO_INPUT_FLAG_FAST);
7865 }
7866
Eric Laurentf14db3c2017-12-08 14:20:36 -08007867 // Check if requested flags are compatible with input stream flags
Eric Laurent05067782016-06-01 18:27:28 -07007868 if ((*flags & inputFlags) != *flags) {
7869 ALOGW("createRecordTrack_l(): mismatch between requested flags (%08x) and"
7870 " input flags (%08x)",
7871 *flags, inputFlags);
7872 *flags = (audio_input_flags_t)(*flags & inputFlags);
7873 }
Eric Laurent81784c32012-11-19 14:55:58 -08007874
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02007875 // client expresses a preference for FAST and no access to audio history,
7876 // but we get the final say
7877 if (*flags & AUDIO_INPUT_FLAG_FAST && maxSharedAudioHistoryMs == 0) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07007878 if (
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07007879 // we formerly checked for a callback handler (non-0 tid),
7880 // but that is no longer required for TRANSFER_OBTAIN mode
7881 //
Phil Burk7ed66a12019-04-18 13:20:30 -07007882 // Frame count is not specified (0), or is less than or equal the pipe depth.
7883 // It is OK to provide a higher capacity than requested.
7884 // We will force it to mPipeFramesP2 below.
7885 (frameCount <= mPipeFramesP2) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07007886 // PCM data
7887 audio_is_linear_pcm(format) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08007888 // hardware format
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007889 (format == mFormat) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08007890 // hardware channel mask
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007891 (channelMask == mChannelMask) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08007892 // hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07007893 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07007894 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007895 hasFastCapture() &&
7896 // there are sufficient fast track slots available
7897 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07007898 ) {
Eric Laurent4c415062016-06-17 16:14:16 -07007899 // check compatibility with audio effects.
7900 Mutex::Autolock _l(mLock);
7901 // Do not accept FAST flag if the session has software effects
7902 sp<EffectChain> chain = getEffectChain_l(sessionId);
7903 if (chain != 0) {
Andy Hungd3bb0ad2016-10-11 17:16:43 -07007904 audio_input_flags_t old = *flags;
7905 chain->checkInputFlagCompatibility(flags);
7906 if (old != *flags) {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007907 ALOGV("%p AUDIO_INPUT_FLAGS denied by effect old=%#x new=%#x",
7908 this, (int)old, (int)*flags);
Eric Laurent4c415062016-06-17 16:14:16 -07007909 }
7910 }
Eric Laurent122f7e72016-06-29 11:53:29 -07007911 ALOGV_IF((*flags & AUDIO_INPUT_FLAG_FAST) != 0,
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007912 "%p AUDIO_INPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
7913 this, frameCount, mFrameCount);
Glenn Kasten90e58b12013-07-31 16:16:02 -07007914 } else {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007915 ALOGV("%p AUDIO_INPUT_FLAG_FAST denied: frameCount=%zu mFrameCount=%zu mPipeFramesP2=%zu "
7916 "format=%#x isLinear=%d mFormat=%#x channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007917 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007918 this, frameCount, mFrameCount, mPipeFramesP2,
7919 format, audio_is_linear_pcm(format), mFormat, channelMask, sampleRate, mSampleRate,
Glenn Kasten74105912014-07-03 12:28:53 -07007920 hasFastCapture(), tid, mFastTrackAvail);
Eric Laurent05067782016-06-01 18:27:28 -07007921 *flags = (audio_input_flags_t)(*flags & ~AUDIO_INPUT_FLAG_FAST);
Glenn Kasten74105912014-07-03 12:28:53 -07007922 }
7923 }
7924
Eric Laurentf14db3c2017-12-08 14:20:36 -08007925 // If FAST or RAW flags were corrected, ask caller to request new input from audio policy
7926 if ((*flags & AUDIO_INPUT_FLAG_FAST) !=
7927 (requestedFlags & AUDIO_INPUT_FLAG_FAST)) {
7928 *flags = (audio_input_flags_t) (*flags & ~(AUDIO_INPUT_FLAG_FAST | AUDIO_INPUT_FLAG_RAW));
7929 lStatus = BAD_TYPE;
7930 goto Exit;
7931 }
7932
Glenn Kasten74105912014-07-03 12:28:53 -07007933 // compute track buffer size in frames, and suggest the notification frame count
Eric Laurent05067782016-06-01 18:27:28 -07007934 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten74105912014-07-03 12:28:53 -07007935 // fast track: frame count is exactly the pipe depth
7936 frameCount = mPipeFramesP2;
7937 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
Eric Laurentf14db3c2017-12-08 14:20:36 -08007938 notificationFrameCount = mFrameCount;
Glenn Kasten74105912014-07-03 12:28:53 -07007939 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07007940 // not fast track: max notification period is resampled equivalent of one HAL buffer time
7941 // or 20 ms if there is a fast capture
7942 // TODO This could be a roundupRatio inline, and const
7943 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
7944 * sampleRate + mSampleRate - 1) / mSampleRate;
7945 // minimum number of notification periods is at least kMinNotifications,
7946 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
7947 static const size_t kMinNotifications = 3;
7948 static const uint32_t kMinMs = 30;
7949 // TODO This could be a roundupRatio inline
7950 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
7951 // TODO This could be a roundupRatio inline
7952 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
7953 maxNotificationFrames;
7954 const size_t minFrameCount = maxNotificationFrames *
7955 max(kMinNotifications, minNotificationsByMs);
7956 frameCount = max(frameCount, minFrameCount);
Eric Laurentf14db3c2017-12-08 14:20:36 -08007957 if (notificationFrameCount == 0 || notificationFrameCount > maxNotificationFrames) {
7958 notificationFrameCount = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07007959 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07007960 }
Glenn Kasten74935e42013-12-19 08:56:45 -08007961 *pFrameCount = frameCount;
Eric Laurentf14db3c2017-12-08 14:20:36 -08007962 *pNotificationFrameCount = notificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08007963
7964 { // scope for mLock
7965 Mutex::Autolock _l(mLock);
Eric Laurent2407ce32021-04-26 14:56:03 +02007966 int32_t startFrames = -1;
Eric Laurentec376dc2021-04-08 20:41:22 +02007967 if (!mSharedAudioPackageName.empty()
7968 && mSharedAudioPackageName == checkedIdentity.packageName
7969 && mSharedAudioSessionId == sessionId
7970 && captureHotwordAllowed(checkedIdentity)) {
Eric Laurent2407ce32021-04-26 14:56:03 +02007971 startFrames = mSharedAudioStartFrames;
Eric Laurentec376dc2021-04-08 20:41:22 +02007972 }
Eric Laurent81784c32012-11-19 14:55:58 -08007973
Kevin Rocard1f564ac2018-03-29 13:53:10 -07007974 track = new RecordTrack(this, client, attr, sampleRate,
Andy Hung8fe68032017-06-05 16:17:51 -07007975 format, channelMask, frameCount,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07007976 nullptr /* buffer */, (size_t)0 /* bufferSize */, sessionId, creatorPid,
Eric Laurent2407ce32021-04-26 14:56:03 +02007977 checkedIdentity, *flags, TrackBase::TYPE_DEFAULT, portId, startFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08007978
Glenn Kasten03003332013-08-06 15:40:54 -07007979 lStatus = track->initCheck();
7980 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07007981 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08007982 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08007983 goto Exit;
7984 }
7985 mTracks.add(track);
7986
Eric Laurent05067782016-06-01 18:27:28 -07007987 if ((*flags & AUDIO_INPUT_FLAG_FAST) && (tid != -1)) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07007988 pid_t callingPid = IPCThreadState::self()->getCallingPid();
7989 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
7990 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07007991 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Glenn Kasten90e58b12013-07-31 16:16:02 -07007992 }
Eric Laurentec376dc2021-04-08 20:41:22 +02007993
7994 if (maxSharedAudioHistoryMs != 0) {
7995 sendResizeBufferConfigEvent_l(maxSharedAudioHistoryMs);
7996 }
Eric Laurent81784c32012-11-19 14:55:58 -08007997 }
Glenn Kasten05997e22014-03-13 15:08:33 -07007998
Eric Laurent81784c32012-11-19 14:55:58 -08007999 lStatus = NO_ERROR;
8000
8001Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07008002 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08008003 return track;
8004}
8005
8006status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
8007 AudioSystem::sync_event_t event,
Glenn Kastend848eb42016-03-08 13:42:11 -08008008 audio_session_t triggerSession)
Eric Laurent81784c32012-11-19 14:55:58 -08008009{
8010 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
8011 sp<ThreadBase> strongMe = this;
8012 status_t status = NO_ERROR;
8013
8014 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08008015 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08008016 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008017 recordTrack->mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
Eric Laurent81784c32012-11-19 14:55:58 -08008018 triggerSession,
8019 recordTrack->sessionId(),
8020 syncStartEventCallback,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008021 recordTrack);
Eric Laurent81784c32012-11-19 14:55:58 -08008022 // Sync event can be cancelled by the trigger session if the track is not in a
8023 // compatible state in which case we start record immediately
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008024 if (recordTrack->mSyncStartEvent->isCancelled()) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08008025 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08008026 } else {
8027 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
Ivan Lozano1b35dd62017-12-06 16:55:10 -08008028 recordTrack->mFramesToDrop = -(ssize_t)
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08008029 ((AudioSystem::kSyncRecordStartTimeOutMs * recordTrack->mSampleRate) / 1000);
Eric Laurent81784c32012-11-19 14:55:58 -08008030 }
8031 }
8032
8033 {
Glenn Kasten47c20702013-08-13 15:37:35 -07008034 // This section is a rendezvous between binder thread executing start() and RecordThread
Eric Laurent81784c32012-11-19 14:55:58 -08008035 AutoMutex lock(mLock);
Andy Hungce685402018-10-05 17:23:27 -07008036 if (recordTrack->isInvalid()) {
8037 recordTrack->clearSyncStartEvent();
Eric Laurentd52a28c2020-08-21 17:10:39 -07008038 ALOGW("%s track %d: invalidated before startInput", __func__, recordTrack->portId());
8039 return DEAD_OBJECT;
Andy Hungce685402018-10-05 17:23:27 -07008040 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008041 if (mActiveTracks.indexOf(recordTrack) >= 0) {
8042 if (recordTrack->mState == TrackBase::PAUSING) {
Andy Hungce685402018-10-05 17:23:27 -07008043 // We haven't stopped yet (moved to PAUSED and not in mActiveTracks)
8044 // so no need to startInput().
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008045 ALOGV("active record track PAUSING -> ACTIVE");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008046 recordTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008047 } else {
8048 ALOGV("active record track state %d", recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08008049 }
8050 return status;
8051 }
8052
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08008053 // TODO consider other ways of handling this, such as changing the state to :STARTING and
8054 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
8055 // or using a separate command thread
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008056 recordTrack->mState = TrackBase::STARTING_1;
Glenn Kasten2b806402013-11-20 16:37:38 -08008057 mActiveTracks.add(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07008058 status_t status = NO_ERROR;
8059 if (recordTrack->isExternalTrack()) {
8060 mLock.unlock();
Eric Laurent4eb58f12018-12-07 16:41:02 -08008061 status = AudioSystem::startInput(recordTrack->portId());
Eric Laurent83b88082014-06-20 18:31:16 -07008062 mLock.lock();
Andy Hungce685402018-10-05 17:23:27 -07008063 if (recordTrack->isInvalid()) {
8064 recordTrack->clearSyncStartEvent();
8065 if (status == NO_ERROR && recordTrack->mState == TrackBase::STARTING_1) {
8066 recordTrack->mState = TrackBase::STARTING_2;
8067 // STARTING_2 forces destroy to call stopInput.
8068 }
Eric Laurentd52a28c2020-08-21 17:10:39 -07008069 ALOGW("%s track %d: invalidated after startInput", __func__, recordTrack->portId());
8070 return DEAD_OBJECT;
Andy Hungce685402018-10-05 17:23:27 -07008071 }
8072 if (recordTrack->mState != TrackBase::STARTING_1) {
8073 ALOGW("%s(%d): unsynchronized mState:%d change",
8074 __func__, recordTrack->id(), recordTrack->mState);
8075 // Someone else has changed state, let them take over,
8076 // leave mState in the new state.
8077 recordTrack->clearSyncStartEvent();
8078 return INVALID_OPERATION;
8079 }
8080 // we're ok, but perhaps startInput has failed
Eric Laurent83b88082014-06-20 18:31:16 -07008081 if (status != NO_ERROR) {
Andy Hungce685402018-10-05 17:23:27 -07008082 ALOGW("%s(%d): startInput failed, status %d",
8083 __func__, recordTrack->id(), status);
8084 // We are in ActiveTracks if STARTING_1 and valid, so remove from ActiveTracks,
8085 // leave in STARTING_1, so destroy() will not call stopInput.
Eric Laurent83b88082014-06-20 18:31:16 -07008086 mActiveTracks.remove(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07008087 recordTrack->clearSyncStartEvent();
Eric Laurent83b88082014-06-20 18:31:16 -07008088 return status;
8089 }
Eric Laurent09f1ed22019-04-24 17:45:17 -07008090 sendIoConfigEvent_l(
8091 AUDIO_CLIENT_STARTED, recordTrack->creatorPid(), recordTrack->portId());
Eric Laurent81784c32012-11-19 14:55:58 -08008092 }
Andy Hungc2b11cb2020-04-22 09:04:01 -07008093
8094 recordTrack->logBeginInterval(patchSourcesToString(&mPatch)); // log to MediaMetrics
8095
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008096 // Catch up with current buffer indices if thread is already running.
8097 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
8098 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
8099 // see previously buffered data before it called start(), but with greater risk of overrun.
8100
Andy Hung73c02e42015-03-29 01:13:58 -07008101 recordTrack->mResamplerBufferProvider->reset();
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008102 if (!recordTrack->isDirect()) {
8103 // clear any converter state as new data will be discontinuous
8104 recordTrack->mRecordBufferConverter->reset();
8105 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008106 recordTrack->mState = TrackBase::STARTING_2;
Eric Laurent81784c32012-11-19 14:55:58 -08008107 // signal thread to start
Eric Laurent81784c32012-11-19 14:55:58 -08008108 mWaitWorkCV.broadcast();
Eric Laurent81784c32012-11-19 14:55:58 -08008109 return status;
8110 }
Eric Laurent81784c32012-11-19 14:55:58 -08008111}
8112
Eric Laurent81784c32012-11-19 14:55:58 -08008113void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
8114{
8115 sp<SyncEvent> strongEvent = event.promote();
8116
8117 if (strongEvent != 0) {
Eric Laurent8ea16e42014-02-20 16:26:11 -08008118 sp<RefBase> ptr = strongEvent->cookie().promote();
8119 if (ptr != 0) {
8120 RecordTrack *recordTrack = (RecordTrack *)ptr.get();
8121 recordTrack->handleSyncStartEvent(strongEvent);
8122 }
Eric Laurent81784c32012-11-19 14:55:58 -08008123 }
8124}
8125
Glenn Kastena8356f62013-07-25 14:37:52 -07008126bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08008127 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07008128 AutoMutex _l(mLock);
Andy Hungce685402018-10-05 17:23:27 -07008129 // if we're invalid, we can't be on the ActiveTracks.
Jean-Michel Trivi38f86712017-04-11 14:10:17 -07008130 if (mActiveTracks.indexOf(recordTrack) < 0 || recordTrack->mState == TrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08008131 return false;
8132 }
Glenn Kasten47c20702013-08-13 15:37:35 -07008133 // note that threadLoop may still be processing the track at this point [without lock]
Eric Laurent81784c32012-11-19 14:55:58 -08008134 recordTrack->mState = TrackBase::PAUSING;
Andy Hungce685402018-10-05 17:23:27 -07008135
Andy Hungabfab202019-03-07 19:45:54 -08008136 // NOTE: Waiting here is important to keep stop synchronous.
8137 // This is needed for proper patchRecord peer release.
Andy Hungce685402018-10-05 17:23:27 -07008138 while (recordTrack->mState == TrackBase::PAUSING && !recordTrack->isInvalid()) {
8139 mWaitWorkCV.broadcast(); // signal thread to stop
8140 mStartStopCond.wait(mLock);
Eric Laurent81784c32012-11-19 14:55:58 -08008141 }
Andy Hungce685402018-10-05 17:23:27 -07008142
8143 if (recordTrack->mState == TrackBase::PAUSED) { // successful stop
Eric Laurent81784c32012-11-19 14:55:58 -08008144 ALOGV("Record stopped OK");
8145 return true;
8146 }
Andy Hungce685402018-10-05 17:23:27 -07008147
8148 // don't handle anything - we've been invalidated or restarted and in a different state
8149 ALOGW_IF("%s(%d): unsynchronized stop, state: %d",
8150 __func__, recordTrack->id(), recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08008151 return false;
8152}
8153
Glenn Kasten0f11b512014-01-31 16:18:54 -08008154bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
Eric Laurent81784c32012-11-19 14:55:58 -08008155{
8156 return false;
8157}
8158
Glenn Kasten0f11b512014-01-31 16:18:54 -08008159status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08008160{
8161#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
8162 if (!isValidSyncEvent(event)) {
8163 return BAD_VALUE;
8164 }
8165
Glenn Kastend848eb42016-03-08 13:42:11 -08008166 audio_session_t eventSession = event->triggerSession();
Eric Laurent81784c32012-11-19 14:55:58 -08008167 status_t ret = NAME_NOT_FOUND;
8168
8169 Mutex::Autolock _l(mLock);
8170
8171 for (size_t i = 0; i < mTracks.size(); i++) {
8172 sp<RecordTrack> track = mTracks[i];
8173 if (eventSession == track->sessionId()) {
8174 (void) track->setSyncEvent(event);
8175 ret = NO_ERROR;
8176 }
8177 }
8178 return ret;
8179#else
8180 return BAD_VALUE;
8181#endif
8182}
8183
jiabin653cc0a2018-01-17 17:54:10 -08008184status_t AudioFlinger::RecordThread::getActiveMicrophones(
8185 std::vector<media::MicrophoneInfo>* activeMicrophones)
8186{
8187 ALOGV("RecordThread::getActiveMicrophones");
8188 AutoMutex _l(mLock);
Paul McLean8a661a32021-04-12 10:21:42 -06008189 if (mInput == nullptr || mInput->stream == nullptr) {
8190 return NO_INIT;
8191 }
jiabin9ff780e2018-03-19 18:19:52 -07008192 status_t status = mInput->stream->getActiveMicrophones(activeMicrophones);
8193 return status;
jiabin653cc0a2018-01-17 17:54:10 -08008194}
8195
Paul McLean12340082019-03-19 09:35:05 -06008196status_t AudioFlinger::RecordThread::setPreferredMicrophoneDirection(
8197 audio_microphone_direction_t direction)
Paul McLean03a6e6a2018-12-04 10:54:13 -07008198{
Paul McLean12340082019-03-19 09:35:05 -06008199 ALOGV("setPreferredMicrophoneDirection(%d)", direction);
Paul McLean03a6e6a2018-12-04 10:54:13 -07008200 AutoMutex _l(mLock);
Paul McLean8a661a32021-04-12 10:21:42 -06008201 if (mInput == nullptr || mInput->stream == nullptr) {
8202 return NO_INIT;
8203 }
Paul McLean12340082019-03-19 09:35:05 -06008204 return mInput->stream->setPreferredMicrophoneDirection(direction);
Paul McLean03a6e6a2018-12-04 10:54:13 -07008205}
8206
Paul McLean12340082019-03-19 09:35:05 -06008207status_t AudioFlinger::RecordThread::setPreferredMicrophoneFieldDimension(float zoom)
Paul McLean03a6e6a2018-12-04 10:54:13 -07008208{
Paul McLean12340082019-03-19 09:35:05 -06008209 ALOGV("setPreferredMicrophoneFieldDimension(%f)", zoom);
Paul McLean03a6e6a2018-12-04 10:54:13 -07008210 AutoMutex _l(mLock);
Paul McLean8a661a32021-04-12 10:21:42 -06008211 if (mInput == nullptr || mInput->stream == nullptr) {
8212 return NO_INIT;
8213 }
Paul McLean12340082019-03-19 09:35:05 -06008214 return mInput->stream->setPreferredMicrophoneFieldDimension(zoom);
Paul McLean03a6e6a2018-12-04 10:54:13 -07008215}
8216
Eric Laurentec376dc2021-04-08 20:41:22 +02008217status_t AudioFlinger::RecordThread::shareAudioHistory(
8218 const std::string& sharedAudioPackageName, audio_session_t sharedSessionId,
8219 int64_t sharedAudioStartMs) {
8220 AutoMutex _l(mLock);
8221 return shareAudioHistory_l(sharedAudioPackageName, sharedSessionId, sharedAudioStartMs);
8222}
8223
8224status_t AudioFlinger::RecordThread::shareAudioHistory_l(
8225 const std::string& sharedAudioPackageName, audio_session_t sharedSessionId,
8226 int64_t sharedAudioStartMs) {
Eric Laurentec376dc2021-04-08 20:41:22 +02008227 if ((hasAudioSession_l(sharedSessionId) & ThreadBase::TRACK_SESSION) == 0) {
8228 return BAD_VALUE;
8229 }
Eric Laurent2407ce32021-04-26 14:56:03 +02008230
8231 if (sharedAudioStartMs < 0
8232 || sharedAudioStartMs > INT64_MAX / mSampleRate) {
Eric Laurentec376dc2021-04-08 20:41:22 +02008233 return BAD_VALUE;
8234 }
8235
Eric Laurent2407ce32021-04-26 14:56:03 +02008236 // Current implementation of the input resampling buffer wraps around indexes at 32 bit.
8237 // As we cannot detect more than one wraparound, only accept values up current write position
8238 // after one wraparound
8239 // We assume recent wraparounds on mRsmpInRear only given it is unlikely that the requesting
8240 // app waits several hours after the start time was computed.
8241 const int64_t sharedAudioStartFrames = sharedAudioStartMs * mSampleRate / 1000;
8242 const int32_t sharedOffset = audio_utils::safe_sub_overflow(mRsmpInRear,
8243 (int32_t)sharedAudioStartFrames);
8244 if (sharedOffset < 0
8245 || sharedOffset > mRsmpInFrames) {
8246 return BAD_VALUE;
8247 }
8248
Eric Laurentec376dc2021-04-08 20:41:22 +02008249 mSharedAudioPackageName = sharedAudioPackageName;
8250 if (mSharedAudioPackageName.empty()) {
8251 mSharedAudioSessionId = AUDIO_SESSION_NONE;
Eric Laurent2407ce32021-04-26 14:56:03 +02008252 mSharedAudioStartFrames = -1;
Eric Laurentec376dc2021-04-08 20:41:22 +02008253 } else {
8254 mSharedAudioSessionId = sharedSessionId;
Eric Laurent2407ce32021-04-26 14:56:03 +02008255 mSharedAudioStartFrames = (int32_t)sharedAudioStartFrames;
Eric Laurentec376dc2021-04-08 20:41:22 +02008256 }
8257 return NO_ERROR;
8258}
8259
Kevin Rocard069c2712018-03-29 19:09:14 -07008260void AudioFlinger::RecordThread::updateMetadata_l()
8261{
8262 if (mInput == nullptr || mInput->stream == nullptr ||
8263 !mActiveTracks.readAndClearHasChanged()) {
8264 return;
8265 }
8266 StreamInHalInterface::SinkMetadata metadata;
8267 for (const sp<RecordTrack> &track : mActiveTracks) {
Eric Laurentb9cc0ab2021-01-29 11:46:52 +01008268 // Do not forward PatchRecord metadata to audio HAL
8269 if (track->isPatchTrack()) {
8270 continue;
8271 }
Kevin Rocard069c2712018-03-29 19:09:14 -07008272 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurent94579172020-11-20 18:41:04 +01008273 record_track_metadata_v7_t trackMetadata;
8274 trackMetadata.base = {
Kevin Rocard069c2712018-03-29 19:09:14 -07008275 .source = track->attributes().source,
8276 .gain = 1, // capture tracks do not have volumes
Eric Laurent94579172020-11-20 18:41:04 +01008277 };
8278 trackMetadata.channel_mask = track->channelMask(),
8279 strncpy(trackMetadata.tags, track->attributes().tags, AUDIO_ATTRIBUTES_TAGS_MAX_SIZE);
8280
8281 metadata.tracks.push_back(trackMetadata);
Kevin Rocard069c2712018-03-29 19:09:14 -07008282 }
8283 mInput->stream->updateSinkMetadata(metadata);
8284}
8285
Eric Laurent81784c32012-11-19 14:55:58 -08008286// destroyTrack_l() must be called with ThreadBase::mLock held
8287void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
8288{
Eric Laurentbfb1b832013-01-07 09:53:42 -08008289 track->terminate();
8290 track->mState = TrackBase::STOPPED;
Eric Laurentec376dc2021-04-08 20:41:22 +02008291
Eric Laurent81784c32012-11-19 14:55:58 -08008292 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08008293 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08008294 removeTrack_l(track);
8295 }
8296}
8297
8298void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
8299{
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008300 String8 result;
8301 track->appendDump(result, false /* active */);
8302 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.string());
8303
Eric Laurent81784c32012-11-19 14:55:58 -08008304 mTracks.remove(track);
8305 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008306 if (track->isFastTrack()) {
8307 ALOG_ASSERT(!mFastTrackAvail);
8308 mFastTrackAvail = true;
8309 }
Eric Laurent81784c32012-11-19 14:55:58 -08008310}
8311
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07008312void AudioFlinger::RecordThread::dumpInternals_l(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08008313{
Mikhail Naganov913d06c2016-11-01 12:49:22 -07008314 AudioStreamIn *input = mInput;
8315 audio_input_flags_t flags = input != NULL ? input->flags : AUDIO_INPUT_FLAG_NONE;
8316 dprintf(fd, " AudioStreamIn: %p flags %#x (%s)\n",
Andy Hung9b181952019-02-25 14:53:36 -08008317 input, flags, toString(flags).c_str());
Andy Hung6427e442018-08-09 12:51:02 -07008318 dprintf(fd, " Frames read: %lld\n", (long long)mFramesRead);
Eric Tan39ec8d62018-07-24 09:49:29 -07008319 if (mActiveTracks.isEmpty()) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07008320 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08008321 }
Andy Hungbfa64962017-06-12 14:43:19 -07008322
8323 if (input != nullptr) {
8324 dprintf(fd, " Hal stream dump:\n");
8325 (void)input->stream->dump(fd);
8326 }
8327
Glenn Kasten6e6704c2014-07-03 10:20:00 -07008328 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008329 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Glenn Kasten17c9c992015-03-02 15:53:01 -08008330
Glenn Kasten2f90c512015-12-02 11:40:09 -08008331 // Make a non-atomic copy of fast capture dump state so it won't change underneath us
8332 // while we are dumping it. It may be inconsistent, but it won't mutate!
8333 // This is a large object so we place it on the heap.
8334 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
Eric Tan2942a4e2018-09-12 17:41:27 -07008335 const std::unique_ptr<FastCaptureDumpState> copy =
8336 std::make_unique<FastCaptureDumpState>(mFastCaptureDumpState);
Glenn Kasten2f90c512015-12-02 11:40:09 -08008337 copy->dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08008338}
8339
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07008340void AudioFlinger::RecordThread::dumpTracks_l(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08008341{
Eric Laurent81784c32012-11-19 14:55:58 -08008342 String8 result;
Marco Nelissenb2208842014-02-07 14:00:50 -08008343 size_t numtracks = mTracks.size();
8344 size_t numactive = mActiveTracks.size();
8345 size_t numactiveseen = 0;
Glenn Kastenc42e9b42016-03-21 11:35:03 -07008346 dprintf(fd, " %zu Tracks", numtracks);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008347 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08008348 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07008349 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008350 result.append(prefix);
Andy Hung000adb52018-06-01 15:43:26 -07008351 mTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08008352 for (size_t i = 0; i < numtracks ; ++i) {
8353 sp<RecordTrack> track = mTracks[i];
8354 if (track != 0) {
8355 bool active = mActiveTracks.indexOf(track) >= 0;
8356 if (active) {
8357 numactiveseen++;
8358 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008359 result.append(prefix);
8360 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08008361 }
Eric Laurent81784c32012-11-19 14:55:58 -08008362 }
Marco Nelissenb2208842014-02-07 14:00:50 -08008363 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07008364 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08008365 }
8366
Marco Nelissenb2208842014-02-07 14:00:50 -08008367 if (numactiveseen != numactive) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008368 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08008369 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008370 result.append(prefix);
Andy Hung000adb52018-06-01 15:43:26 -07008371 mActiveTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08008372 for (size_t i = 0; i < numactive; ++i) {
Glenn Kasten2b806402013-11-20 16:37:38 -08008373 sp<RecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08008374 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008375 result.append(prefix);
8376 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08008377 }
Glenn Kasten2b806402013-11-20 16:37:38 -08008378 }
Eric Laurent81784c32012-11-19 14:55:58 -08008379
8380 }
8381 write(fd, result.string(), result.size());
8382}
8383
Eric Laurent5ada82e2019-08-29 17:53:54 -07008384void AudioFlinger::RecordThread::setRecordSilenced(audio_port_handle_t portId, bool silenced)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008385{
8386 Mutex::Autolock _l(mLock);
8387 for (size_t i = 0; i < mTracks.size() ; i++) {
8388 sp<RecordTrack> track = mTracks[i];
Eric Laurent5ada82e2019-08-29 17:53:54 -07008389 if (track != 0 && track->portId() == portId) {
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008390 track->setSilenced(silenced);
8391 }
8392 }
8393}
Andy Hung73c02e42015-03-29 01:13:58 -07008394
8395void AudioFlinger::RecordThread::ResamplerBufferProvider::reset()
8396{
8397 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
8398 RecordThread *recordThread = (RecordThread *) threadBase.get();
Andy Hung73c02e42015-03-29 01:13:58 -07008399 mRsmpInUnrel = 0;
Eric Laurentec376dc2021-04-08 20:41:22 +02008400 const int32_t rear = recordThread->mRsmpInRear;
8401 ssize_t deltaFrames = 0;
Eric Laurent2407ce32021-04-26 14:56:03 +02008402 if (mRecordTrack->startFrames() >= 0) {
8403 int32_t startFrames = mRecordTrack->startFrames();
8404 // Accept a recent wraparound of mRsmpInRear
8405 if (startFrames <= rear) {
8406 deltaFrames = rear - startFrames;
8407 } else {
8408 deltaFrames = (int32_t)((int64_t)rear + UINT32_MAX + 1 - startFrames);
Eric Laurentec376dc2021-04-08 20:41:22 +02008409 }
Eric Laurentec376dc2021-04-08 20:41:22 +02008410 // start frame cannot be further in the past than start of resampling buffer
8411 if ((size_t) deltaFrames > recordThread->mRsmpInFrames) {
8412 deltaFrames = recordThread->mRsmpInFrames;
8413 }
8414 }
8415 mRsmpInFront = audio_utils::safe_sub_overflow(rear, static_cast<int32_t>(deltaFrames));
Andy Hung73c02e42015-03-29 01:13:58 -07008416}
8417
8418void AudioFlinger::RecordThread::ResamplerBufferProvider::sync(
8419 size_t *framesAvailable, bool *hasOverrun)
8420{
8421 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
8422 RecordThread *recordThread = (RecordThread *) threadBase.get();
8423 const int32_t rear = recordThread->mRsmpInRear;
8424 const int32_t front = mRsmpInFront;
Hongwei Wang95e37682019-04-12 11:13:36 -07008425 const ssize_t filled = audio_utils::safe_sub_overflow(rear, front);
Andy Hung73c02e42015-03-29 01:13:58 -07008426
8427 size_t framesIn;
8428 bool overrun = false;
8429 if (filled < 0) {
8430 // should not happen, but treat like a massive overrun and re-sync
8431 framesIn = 0;
8432 mRsmpInFront = rear;
8433 overrun = true;
8434 } else if ((size_t) filled <= recordThread->mRsmpInFrames) {
8435 framesIn = (size_t) filled;
8436 } else {
8437 // client is not keeping up with server, but give it latest data
8438 framesIn = recordThread->mRsmpInFrames;
Hongwei Wang95e37682019-04-12 11:13:36 -07008439 mRsmpInFront = /* front = */ audio_utils::safe_sub_overflow(
8440 rear, static_cast<int32_t>(framesIn));
Andy Hung73c02e42015-03-29 01:13:58 -07008441 overrun = true;
8442 }
8443 if (framesAvailable != NULL) {
8444 *framesAvailable = framesIn;
8445 }
8446 if (hasOverrun != NULL) {
8447 *hasOverrun = overrun;
8448 }
8449}
8450
Eric Laurent81784c32012-11-19 14:55:58 -08008451// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008452status_t AudioFlinger::RecordThread::ResamplerBufferProvider::getNextBuffer(
Glenn Kastend79072e2016-01-06 08:41:20 -08008453 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08008454{
Andy Hung73c02e42015-03-29 01:13:58 -07008455 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008456 if (threadBase == 0) {
8457 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08008458 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008459 return NOT_ENOUGH_DATA;
8460 }
8461 RecordThread *recordThread = (RecordThread *) threadBase.get();
8462 int32_t rear = recordThread->mRsmpInRear;
Andy Hung73c02e42015-03-29 01:13:58 -07008463 int32_t front = mRsmpInFront;
Hongwei Wang95e37682019-04-12 11:13:36 -07008464 ssize_t filled = audio_utils::safe_sub_overflow(rear, front);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008465 // FIXME should not be P2 (don't want to increase latency)
8466 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08008467 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07008468 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008469
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008470 front &= recordThread->mRsmpInFramesP2 - 1;
8471 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07008472 if (part1 > (size_t) filled) {
8473 part1 = filled;
8474 }
8475 size_t ask = buffer->frameCount;
8476 ALOG_ASSERT(ask > 0);
8477 if (part1 > ask) {
8478 part1 = ask;
8479 }
8480 if (part1 == 0) {
Andy Hung73c02e42015-03-29 01:13:58 -07008481 // out of data is fine since the resampler will return a short-count.
Glenn Kasten85948432013-08-19 12:09:05 -07008482 buffer->raw = NULL;
8483 buffer->frameCount = 0;
Andy Hung73c02e42015-03-29 01:13:58 -07008484 mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07008485 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08008486 }
8487
Andy Hung57446612015-04-19 23:56:46 -07008488 buffer->raw = (uint8_t*)recordThread->mRsmpInBuffer + front * recordThread->mFrameSize;
Glenn Kasten85948432013-08-19 12:09:05 -07008489 buffer->frameCount = part1;
Andy Hung73c02e42015-03-29 01:13:58 -07008490 mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08008491 return NO_ERROR;
8492}
8493
8494// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008495void AudioFlinger::RecordThread::ResamplerBufferProvider::releaseBuffer(
8496 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08008497{
Hongwei Wang95e37682019-04-12 11:13:36 -07008498 int32_t stepCount = static_cast<int32_t>(buffer->frameCount);
Glenn Kasten85948432013-08-19 12:09:05 -07008499 if (stepCount == 0) {
8500 return;
8501 }
Andy Hung73c02e42015-03-29 01:13:58 -07008502 ALOG_ASSERT(stepCount <= mRsmpInUnrel);
8503 mRsmpInUnrel -= stepCount;
Hongwei Wang95e37682019-04-12 11:13:36 -07008504 mRsmpInFront = audio_utils::safe_add_overflow(mRsmpInFront, stepCount);
Glenn Kasten85948432013-08-19 12:09:05 -07008505 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08008506 buffer->frameCount = 0;
8507}
8508
Eric Laurentd8365c52017-07-16 15:27:05 -07008509void AudioFlinger::RecordThread::checkBtNrec()
8510{
8511 Mutex::Autolock _l(mLock);
8512 checkBtNrec_l();
8513}
8514
8515void AudioFlinger::RecordThread::checkBtNrec_l()
8516{
8517 // disable AEC and NS if the device is a BT SCO headset supporting those
8518 // pre processings
jiabinc52b1ff2019-10-31 17:20:42 -07008519 bool suspend = audio_is_bluetooth_sco_device(inDeviceType()) &&
Eric Laurentd8365c52017-07-16 15:27:05 -07008520 mAudioFlinger->btNrecIsOff();
8521 if (mBtNrecSuspended.exchange(suspend) != suspend) {
8522 for (size_t i = 0; i < mEffectChains.size(); i++) {
8523 setEffectSuspended_l(FX_IID_AEC, suspend, mEffectChains[i]->sessionId());
8524 setEffectSuspended_l(FX_IID_NS, suspend, mEffectChains[i]->sessionId());
8525 }
8526 }
8527}
8528
Andy Hung97a893e2015-03-29 01:03:07 -07008529
Eric Laurent10351942014-05-08 18:49:52 -07008530bool AudioFlinger::RecordThread::checkForNewParameter_l(const String8& keyValuePair,
8531 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08008532{
8533 bool reconfig = false;
8534
Eric Laurent10351942014-05-08 18:49:52 -07008535 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08008536
Eric Laurent10351942014-05-08 18:49:52 -07008537 audio_format_t reqFormat = mFormat;
8538 uint32_t samplingRate = mSampleRate;
Glenn Kastene1635ec2015-06-08 15:46:49 -07008539 // 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 -07008540 audio_channel_mask_t channelMask = audio_channel_in_mask_from_count(mChannelCount);
8541
8542 AudioParameter param = AudioParameter(keyValuePair);
8543 int value;
Haynes Mathew George9ce67b52015-09-30 11:40:47 -07008544
8545 // scope for AutoPark extends to end of method
8546 AutoPark<FastCapture> park(mFastCapture);
8547
Eric Laurent10351942014-05-08 18:49:52 -07008548 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
8549 // channel count change can be requested. Do we mandate the first client defines the
8550 // HAL sampling rate and channel count or do we allow changes on the fly?
8551 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
8552 samplingRate = value;
8553 reconfig = true;
8554 }
8555 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung97a893e2015-03-29 01:03:07 -07008556 if (!audio_is_linear_pcm((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07008557 status = BAD_VALUE;
8558 } else {
8559 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08008560 reconfig = true;
8561 }
Eric Laurent10351942014-05-08 18:49:52 -07008562 }
8563 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
8564 audio_channel_mask_t mask = (audio_channel_mask_t) value;
Andy Hungd330ee42015-04-20 13:23:41 -07008565 if (!audio_is_input_channel(mask) ||
8566 audio_channel_count_from_in_mask(mask) > FCC_8) {
Eric Laurent10351942014-05-08 18:49:52 -07008567 status = BAD_VALUE;
8568 } else {
8569 channelMask = mask;
8570 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08008571 }
Eric Laurent10351942014-05-08 18:49:52 -07008572 }
8573 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
8574 // do not accept frame count changes if tracks are open as the track buffer
8575 // size depends on frame count and correct behavior would not be guaranteed
8576 // if frame count is changed after track creation
8577 if (mActiveTracks.size() > 0) {
8578 status = INVALID_OPERATION;
8579 } else {
8580 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08008581 }
Eric Laurent10351942014-05-08 18:49:52 -07008582 }
8583 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07008584 LOG_FATAL("Should not set routing device in RecordThread");
Eric Laurent10351942014-05-08 18:49:52 -07008585 }
8586 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
8587 mAudioSource != (audio_source_t)value) {
jiabinc52b1ff2019-10-31 17:20:42 -07008588 LOG_FATAL("Should not set audio source in RecordThread");
Eric Laurent10351942014-05-08 18:49:52 -07008589 }
Glenn Kastene198c362013-08-13 09:13:36 -07008590
Eric Laurent10351942014-05-08 18:49:52 -07008591 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008592 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07008593 if (status == INVALID_OPERATION) {
8594 inputStandBy();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008595 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07008596 }
8597 if (reconfig) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008598 if (status == BAD_VALUE) {
Mikhail Naganov560637e2021-03-31 22:40:13 +00008599 audio_config_base_t config = AUDIO_CONFIG_BASE_INITIALIZER;
8600 if (mInput->stream->getAudioProperties(&config) == OK &&
8601 audio_is_linear_pcm(config.format) && audio_is_linear_pcm(reqFormat) &&
8602 config.sample_rate <= (AUDIO_RESAMPLER_DOWN_RATIO_MAX * samplingRate) &&
8603 audio_channel_count_from_in_mask(config.channel_mask) <= FCC_8) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008604 status = NO_ERROR;
8605 }
Eric Laurent81784c32012-11-19 14:55:58 -08008606 }
Eric Laurent10351942014-05-08 18:49:52 -07008607 if (status == NO_ERROR) {
8608 readInputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07008609 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08008610 }
8611 }
Eric Laurent81784c32012-11-19 14:55:58 -08008612 }
Eric Laurent10351942014-05-08 18:49:52 -07008613
Eric Laurent81784c32012-11-19 14:55:58 -08008614 return reconfig;
8615}
8616
8617String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
8618{
Eric Laurent81784c32012-11-19 14:55:58 -08008619 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008620 if (initCheck() == NO_ERROR) {
8621 String8 out_s8;
8622 if (mInput->stream->getParameters(keys, &out_s8) == OK) {
8623 return out_s8;
8624 }
Eric Laurent81784c32012-11-19 14:55:58 -08008625 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008626 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08008627}
8628
Eric Laurent09f1ed22019-04-24 17:45:17 -07008629void AudioFlinger::RecordThread::ioConfigChanged(audio_io_config_event event, pid_t pid,
8630 audio_port_handle_t portId) {
Eric Laurent73e26b62015-04-27 16:55:58 -07008631 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
8632
8633 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08008634
8635 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07008636 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07008637 case AUDIO_INPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07008638 case AUDIO_INPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07008639 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07008640 desc->mChannelMask = mChannelMask;
8641 desc->mSamplingRate = mSampleRate;
8642 desc->mFormat = mFormat;
8643 desc->mFrameCount = mFrameCount;
Glenn Kasten4a8308b2016-04-18 14:10:01 -07008644 desc->mFrameCountHAL = mFrameCount;
Eric Laurent73e26b62015-04-27 16:55:58 -07008645 desc->mLatency = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08008646 break;
Eric Laurent09f1ed22019-04-24 17:45:17 -07008647 case AUDIO_CLIENT_STARTED:
8648 desc->mPatch = mPatch;
8649 desc->mPortId = portId;
8650 break;
Eric Laurent73e26b62015-04-27 16:55:58 -07008651 case AUDIO_INPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08008652 default:
8653 break;
8654 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07008655 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08008656}
8657
Glenn Kastendeca2ae2014-02-07 10:25:56 -08008658void AudioFlinger::RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08008659{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008660 status_t result = mInput->stream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
8661 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
Andy Hung463be252014-07-10 16:56:07 -07008662 mFormat = mHALFormat;
Mikhail Naganovce9f2652018-07-16 11:09:24 -07008663 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
8664 if (audio_is_linear_pcm(mFormat)) {
8665 LOG_ALWAYS_FATAL_IF(mChannelCount > FCC_8, "HAL channel count %d > %d",
8666 mChannelCount, FCC_8);
8667 } else {
8668 // Can have more that FCC_8 channels in encoded streams.
8669 ALOGI("HAL format %#x is not linear pcm", mFormat);
8670 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008671 result = mInput->stream->getFrameSize(&mFrameSize);
8672 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
Hayden Gomes1a89ab32020-06-12 11:05:47 -07008673 LOG_ALWAYS_FATAL_IF(mFrameSize <= 0, "Error frame size was %zu but must be greater than zero",
8674 mFrameSize);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008675 result = mInput->stream->getBufferSize(&mBufferSize);
8676 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
Glenn Kasten548efc92012-11-29 08:48:51 -08008677 mFrameCount = mBufferSize / mFrameSize;
Hayden Gomes1a89ab32020-06-12 11:05:47 -07008678 ALOGV("%p RecordThread params: mChannelCount=%u, mFormat=%#x, mFrameSize=%zu, "
8679 "mBufferSize=%zu, mFrameCount=%zu",
8680 this, mChannelCount, mFormat, mFrameSize, mBufferSize, mFrameCount);
Glenn Kasten49d00ad2014-07-21 11:22:03 -07008681
Eric Laurentec376dc2021-04-08 20:41:22 +02008682 // mRsmpInFrames must be 0 before calling resizeInputBuffer_l for the first time
8683 mRsmpInFrames = 0;
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008684 resizeInputBuffer_l(0 /*maxSharedAudioHistoryMs*/);
Eric Laurent81784c32012-11-19 14:55:58 -08008685
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08008686 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
8687 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Andy Hungea840382020-05-05 21:50:17 -07008688
8689 audio_input_flags_t flags = mInput->flags;
8690 mediametrics::LogItem item(mThreadMetrics.getMetricsId());
8691 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
8692 .set(AMEDIAMETRICS_PROP_ENCODING, formatToString(mFormat).c_str())
8693 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
8694 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
8695 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
8696 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
8697 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mFrameCount)
8698 .record();
Eric Laurent81784c32012-11-19 14:55:58 -08008699}
8700
Glenn Kasten5f972c02014-01-13 09:59:31 -08008701uint32_t AudioFlinger::RecordThread::getInputFramesLost()
Eric Laurent81784c32012-11-19 14:55:58 -08008702{
8703 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008704 uint32_t result;
8705 if (initCheck() == NO_ERROR && mInput->stream->getInputFramesLost(&result) == OK) {
8706 return result;
Eric Laurent81784c32012-11-19 14:55:58 -08008707 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008708 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08008709}
8710
Glenn Kastend848eb42016-03-08 13:42:11 -08008711KeyedVector<audio_session_t, bool> AudioFlinger::RecordThread::sessionIds() const
Eric Laurent81784c32012-11-19 14:55:58 -08008712{
Glenn Kastend848eb42016-03-08 13:42:11 -08008713 KeyedVector<audio_session_t, bool> ids;
Eric Laurent81784c32012-11-19 14:55:58 -08008714 Mutex::Autolock _l(mLock);
8715 for (size_t j = 0; j < mTracks.size(); ++j) {
8716 sp<RecordThread::RecordTrack> track = mTracks[j];
Glenn Kastend848eb42016-03-08 13:42:11 -08008717 audio_session_t sessionId = track->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08008718 if (ids.indexOfKey(sessionId) < 0) {
8719 ids.add(sessionId, true);
8720 }
8721 }
8722 return ids;
8723}
8724
8725AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
8726{
8727 Mutex::Autolock _l(mLock);
8728 AudioStreamIn *input = mInput;
8729 mInput = NULL;
8730 return input;
8731}
8732
8733// this method must always be called either with ThreadBase mLock held or inside the thread loop
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008734sp<StreamHalInterface> AudioFlinger::RecordThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08008735{
8736 if (mInput == NULL) {
8737 return NULL;
8738 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008739 return mInput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08008740}
8741
8742status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
8743{
Eric Laurent81784c32012-11-19 14:55:58 -08008744 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurentaaa44472014-09-12 17:41:50 -07008745 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08008746 chain->setInBuffer(NULL);
8747 chain->setOutBuffer(NULL);
8748
8749 checkSuspendOnAddEffectChain_l(chain);
8750
Eric Laurent1b928682014-10-02 19:41:47 -07008751 // make sure enabled pre processing effects state is communicated to the HAL as we
8752 // just moved them to a new input stream.
8753 chain->syncHalEffectsState();
8754
Eric Laurent81784c32012-11-19 14:55:58 -08008755 mEffectChains.add(chain);
8756
8757 return NO_ERROR;
8758}
8759
8760size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
8761{
8762 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
Eric Laurentb20cf7d2019-04-05 19:37:34 -07008763
8764 for (size_t i = 0; i < mEffectChains.size(); i++) {
8765 if (chain == mEffectChains[i]) {
8766 mEffectChains.removeAt(i);
8767 break;
8768 }
Eric Laurent81784c32012-11-19 14:55:58 -08008769 }
Eric Laurentb20cf7d2019-04-05 19:37:34 -07008770 return mEffectChains.size();
Eric Laurent81784c32012-11-19 14:55:58 -08008771}
8772
Eric Laurent1c333e22014-05-20 10:48:17 -07008773status_t AudioFlinger::RecordThread::createAudioPatch_l(const struct audio_patch *patch,
8774 audio_patch_handle_t *handle)
8775{
8776 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07008777
8778 // store new device and send to effects
jiabinc52b1ff2019-10-31 17:20:42 -07008779 mInDeviceTypeAddr.mType = patch->sources[0].ext.device.type;
jiabin0a488932020-08-07 17:32:40 -07008780 mInDeviceTypeAddr.setAddress(patch->sources[0].ext.device.address);
François Gaffie0c280aa2018-07-25 10:02:15 +02008781 audio_port_handle_t deviceId = patch->sources[0].id;
Eric Laurent054d9d32015-04-24 08:48:48 -07008782 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08008783 mEffectChains[i]->setInputDevice_l(inDeviceTypeAddr());
Eric Laurent054d9d32015-04-24 08:48:48 -07008784 }
8785
Eric Laurentd8365c52017-07-16 15:27:05 -07008786 checkBtNrec_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07008787
8788 // store new source and send to effects
8789 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
8790 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent1c333e22014-05-20 10:48:17 -07008791 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent054d9d32015-04-24 08:48:48 -07008792 mEffectChains[i]->setAudioSource_l(mAudioSource);
Eric Laurent1c333e22014-05-20 10:48:17 -07008793 }
Eric Laurent054d9d32015-04-24 08:48:48 -07008794 }
Eric Laurent1c333e22014-05-20 10:48:17 -07008795
Mikhail Naganov9ee05402016-10-13 15:58:17 -07008796 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07008797 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
8798 status = hwDevice->createAudioPatch(patch->num_sources,
8799 patch->sources,
8800 patch->num_sinks,
8801 patch->sinks,
8802 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07008803 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07008804 char *address;
8805 if (strcmp(patch->sources[0].ext.device.address, "") != 0) {
8806 address = audio_device_address_to_parameter(
8807 patch->sources[0].ext.device.type,
8808 patch->sources[0].ext.device.address);
8809 } else {
8810 address = (char *)calloc(1, 1);
8811 }
8812 AudioParameter param = AudioParameter(String8(address));
8813 free(address);
Mikhail Naganov00260b52016-10-13 12:54:24 -07008814 param.addInt(String8(AudioParameter::keyRouting),
Eric Laurent054d9d32015-04-24 08:48:48 -07008815 (int)patch->sources[0].ext.device.type);
Mikhail Naganov00260b52016-10-13 12:54:24 -07008816 param.addInt(String8(AudioParameter::keyInputSource),
Eric Laurent054d9d32015-04-24 08:48:48 -07008817 (int)patch->sinks[0].ext.mix.usecase.source);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008818 status = mInput->stream->setParameters(param.toString());
Eric Laurent054d9d32015-04-24 08:48:48 -07008819 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07008820 }
Eric Laurent054d9d32015-04-24 08:48:48 -07008821
jiabinc52b1ff2019-10-31 17:20:42 -07008822 if ((mPatch.num_sources == 0) || (mPatch.sources[0].id != deviceId)) {
Eric Laurente8726fe2015-06-26 09:39:24 -07008823 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
jiabinc52b1ff2019-10-31 17:20:42 -07008824 mPatch = *patch;
Eric Laurente8726fe2015-06-26 09:39:24 -07008825 }
Eric Laurent296fb132015-05-01 11:38:42 -07008826
Andy Hungc2b11cb2020-04-22 09:04:01 -07008827 const std::string pathSourcesAsString = patchSourcesToString(patch);
Andy Hungcf10d742020-04-28 15:38:24 -07008828 mThreadMetrics.logEndInterval();
Andy Hungea840382020-05-05 21:50:17 -07008829 mThreadMetrics.logCreatePatch(pathSourcesAsString, /* outDevices */ {});
Andy Hungcf10d742020-04-28 15:38:24 -07008830 mThreadMetrics.logBeginInterval();
Andy Hungc2b11cb2020-04-22 09:04:01 -07008831 // also dispatch to active AudioRecords
8832 for (const auto &track : mActiveTracks) {
8833 track->logEndInterval();
8834 track->logBeginInterval(pathSourcesAsString);
8835 }
Eric Laurent1c333e22014-05-20 10:48:17 -07008836 return status;
8837}
8838
8839status_t AudioFlinger::RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
8840{
8841 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07008842
jiabinc52b1ff2019-10-31 17:20:42 -07008843 mPatch = audio_patch{};
8844 mInDeviceTypeAddr.reset();
Eric Laurent054d9d32015-04-24 08:48:48 -07008845
Mikhail Naganov9ee05402016-10-13 15:58:17 -07008846 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07008847 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
8848 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07008849 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07008850 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07008851 param.addInt(String8(AudioParameter::keyRouting), 0);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008852 status = mInput->stream->setParameters(param.toString());
Eric Laurent1c333e22014-05-20 10:48:17 -07008853 }
8854 return status;
8855}
8856
jiabinc52b1ff2019-10-31 17:20:42 -07008857void AudioFlinger::RecordThread::updateOutDevices(const DeviceDescriptorBaseVector& outDevices)
8858{
wendy lin56aa82b2020-12-02 15:19:55 +08008859 Mutex::Autolock _l(mLock);
jiabinc52b1ff2019-10-31 17:20:42 -07008860 mOutDevices = outDevices;
8861 mOutDeviceTypeAddrs = deviceTypeAddrsFromDescriptors(mOutDevices);
8862 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08008863 mEffectChains[i]->setDevices_l(outDeviceTypeAddrs());
jiabinc52b1ff2019-10-31 17:20:42 -07008864 }
8865}
8866
Eric Laurentec376dc2021-04-08 20:41:22 +02008867int32_t AudioFlinger::RecordThread::getOldestFront_l()
8868{
8869 if (mTracks.size() == 0) {
8870 return 0;
8871 }
Eric Laurent2407ce32021-04-26 14:56:03 +02008872 int32_t oldestFront = mRsmpInRear;
8873 int32_t maxFilled = 0;
Eric Laurentec376dc2021-04-08 20:41:22 +02008874 for (size_t i = 0; i < mTracks.size(); i++) {
Eric Laurent2407ce32021-04-26 14:56:03 +02008875 int32_t front = mTracks[i]->mResamplerBufferProvider->getFront();
8876 int32_t filled;
8877 if (front <= mRsmpInRear) {
8878 filled = mRsmpInRear - front;
8879 } else {
8880 filled = (int32_t)((int64_t)mRsmpInRear + UINT32_MAX + 1 - front);
8881 }
8882 if (filled > maxFilled) {
8883 oldestFront = front;
8884 maxFilled = filled;
8885 }
Eric Laurentec376dc2021-04-08 20:41:22 +02008886 }
Eric Laurent2407ce32021-04-26 14:56:03 +02008887 return oldestFront;
Eric Laurentec376dc2021-04-08 20:41:22 +02008888}
8889
8890void AudioFlinger::RecordThread::updateFronts_l(int32_t offset)
8891{
8892 if (offset == 0) {
8893 return;
8894 }
8895 for (size_t i = 0; i < mTracks.size(); i++) {
8896 int32_t front = mTracks[i]->mResamplerBufferProvider->getFront();
8897 front = audio_utils::safe_sub_overflow(front, offset);
8898 mTracks[i]->mResamplerBufferProvider->setFront(front);
8899 }
8900}
8901
8902void AudioFlinger::RecordThread::resizeInputBuffer_l(int32_t maxSharedAudioHistoryMs)
8903{
8904 // This is the formula for calculating the temporary buffer size.
8905 // With 7 HAL buffers, we can guarantee ability to down-sample the input by ratio of 6:1 to
8906 // 1 full output buffer, regardless of the alignment of the available input.
8907 // The value is somewhat arbitrary, and could probably be even larger.
8908 // A larger value should allow more old data to be read after a track calls start(),
8909 // without increasing latency.
8910 //
8911 // Note this is independent of the maximum downsampling ratio permitted for capture.
8912 size_t minRsmpInFrames = mFrameCount * 7;
8913
8914 // maxSharedAudioHistoryMs != 0 indicates a request to possibly make some part of the audio
8915 // capture history available to another client using the same session ID:
8916 // dimension the resampler input buffer accordingly.
8917
8918 // Get oldest client read position: getOldestFront_l() must be called before altering
8919 // mRsmpInRear, or mRsmpInFrames
8920 int32_t previousFront = getOldestFront_l();
8921 size_t previousRsmpInFramesP2 = mRsmpInFramesP2;
8922 int32_t previousRear = mRsmpInRear;
8923 mRsmpInRear = 0;
8924
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008925 ALOG_ASSERT(maxSharedAudioHistoryMs >= 0
8926 && maxSharedAudioHistoryMs <= AudioFlinger::kMaxSharedAudioHistoryMs,
8927 "resizeInputBuffer_l() called with invalid max shared history %d",
8928 maxSharedAudioHistoryMs);
Eric Laurentec376dc2021-04-08 20:41:22 +02008929 if (maxSharedAudioHistoryMs != 0) {
8930 // resizeInputBuffer_l should never be called with a non zero shared history if the
8931 // buffer was not already allocated
8932 ALOG_ASSERT(mRsmpInBuffer != nullptr && mRsmpInFrames != 0,
8933 "resizeInputBuffer_l() called with shared history and unallocated buffer");
8934 size_t rsmpInFrames = (size_t)maxSharedAudioHistoryMs * mSampleRate / 1000;
8935 // never reduce resampler input buffer size
8936 if (rsmpInFrames < mRsmpInFrames) {
8937 return;
8938 }
8939 mRsmpInFrames = rsmpInFrames;
8940 }
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008941 mMaxSharedAudioHistoryMs = maxSharedAudioHistoryMs;
Eric Laurentec376dc2021-04-08 20:41:22 +02008942 // Note: mRsmpInFrames is 0 when called with maxSharedAudioHistoryMs equals to 0 so it is always
8943 // initialized
8944 if (mRsmpInFrames < minRsmpInFrames) {
8945 mRsmpInFrames = minRsmpInFrames;
8946 }
8947 mRsmpInFramesP2 = roundup(mRsmpInFrames);
8948
8949 // TODO optimize audio capture buffer sizes ...
8950 // Here we calculate the size of the sliding buffer used as a source
8951 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
8952 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
8953 // be better to have it derived from the pipe depth in the long term.
8954 // The current value is higher than necessary. However it should not add to latency.
8955
8956 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
8957 mRsmpInFramesOA = mRsmpInFramesP2 + mFrameCount - 1;
8958
8959 void *rsmpInBuffer;
8960 (void)posix_memalign(&rsmpInBuffer, 32, mRsmpInFramesOA * mFrameSize);
8961 // if posix_memalign fails, will segv here.
8962 memset(rsmpInBuffer, 0, mRsmpInFramesOA * mFrameSize);
8963
8964 // Copy audio history if any from old buffer before freeing it
8965 if (previousRear != 0) {
8966 ALOG_ASSERT(mRsmpInBuffer != nullptr,
8967 "resizeInputBuffer_l() called with null buffer but frames already read from HAL");
8968
8969 ssize_t unread = audio_utils::safe_sub_overflow(previousRear, previousFront);
8970 previousFront &= previousRsmpInFramesP2 - 1;
8971 size_t part1 = previousRsmpInFramesP2 - previousFront;
8972 if (part1 > (size_t) unread) {
8973 part1 = unread;
8974 }
8975 if (part1 != 0) {
8976 memcpy(rsmpInBuffer, (const uint8_t*)mRsmpInBuffer + previousFront * mFrameSize,
8977 part1 * mFrameSize);
8978 mRsmpInRear = part1;
8979 part1 = unread - part1;
8980 if (part1 != 0) {
8981 memcpy((uint8_t*)rsmpInBuffer + mRsmpInRear * mFrameSize,
8982 (const uint8_t*)mRsmpInBuffer, part1 * mFrameSize);
8983 mRsmpInRear += part1;
8984 }
8985 }
8986 // Update front for all clients according to new rear
8987 updateFronts_l(audio_utils::safe_sub_overflow(previousRear, mRsmpInRear));
8988 } else {
8989 mRsmpInRear = 0;
8990 }
8991 free(mRsmpInBuffer);
8992 mRsmpInBuffer = rsmpInBuffer;
8993}
8994
Mikhail Naganov444ecc32018-05-01 17:40:05 -07008995void AudioFlinger::RecordThread::addPatchTrack(const sp<PatchRecord>& record)
Eric Laurent83b88082014-06-20 18:31:16 -07008996{
8997 Mutex::Autolock _l(mLock);
8998 mTracks.add(record);
Mikhail Naganov2534b382019-09-25 13:05:02 -07008999 if (record->getSource()) {
9000 mSource = record->getSource();
9001 }
Eric Laurent83b88082014-06-20 18:31:16 -07009002}
9003
Mikhail Naganov444ecc32018-05-01 17:40:05 -07009004void AudioFlinger::RecordThread::deletePatchTrack(const sp<PatchRecord>& record)
Eric Laurent83b88082014-06-20 18:31:16 -07009005{
9006 Mutex::Autolock _l(mLock);
Mikhail Naganov2534b382019-09-25 13:05:02 -07009007 if (mSource == record->getSource()) {
9008 mSource = mInput;
9009 }
Eric Laurent83b88082014-06-20 18:31:16 -07009010 destroyTrack_l(record);
9011}
9012
Mikhail Naganovdc769682018-05-04 15:34:08 -07009013void AudioFlinger::RecordThread::toAudioPortConfig(struct audio_port_config *config)
Eric Laurent83b88082014-06-20 18:31:16 -07009014{
Mikhail Naganovdc769682018-05-04 15:34:08 -07009015 ThreadBase::toAudioPortConfig(config);
Eric Laurent83b88082014-06-20 18:31:16 -07009016 config->role = AUDIO_PORT_ROLE_SINK;
9017 config->ext.mix.hw_module = mInput->audioHwDev->handle();
9018 config->ext.mix.usecase.source = mAudioSource;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07009019 if (mInput && mInput->flags != AUDIO_INPUT_FLAG_NONE) {
9020 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
9021 config->flags.input = mInput->flags;
9022 }
Eric Laurent83b88082014-06-20 18:31:16 -07009023}
Eric Laurent1c333e22014-05-20 10:48:17 -07009024
Eric Laurent6acd1d42017-01-04 14:23:29 -08009025// ----------------------------------------------------------------------------
9026// Mmap
9027// ----------------------------------------------------------------------------
9028
9029AudioFlinger::MmapThreadHandle::MmapThreadHandle(const sp<MmapThread>& thread)
9030 : mThread(thread)
9031{
Phil Burk9fabbf82017-08-03 12:02:00 -07009032 assert(thread != 0); // thread must start non-null and stay non-null
Eric Laurent6acd1d42017-01-04 14:23:29 -08009033}
9034
9035AudioFlinger::MmapThreadHandle::~MmapThreadHandle()
9036{
Phil Burk9fabbf82017-08-03 12:02:00 -07009037 mThread->disconnect();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009038}
9039
9040status_t AudioFlinger::MmapThreadHandle::createMmapBuffer(int32_t minSizeFrames,
9041 struct audio_mmap_buffer_info *info)
9042{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009043 return mThread->createMmapBuffer(minSizeFrames, info);
9044}
9045
9046status_t AudioFlinger::MmapThreadHandle::getMmapPosition(struct audio_mmap_position *position)
9047{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009048 return mThread->getMmapPosition(position);
9049}
9050
jiabinb7d8c5a2020-08-26 17:24:52 -07009051status_t AudioFlinger::MmapThreadHandle::getExternalPosition(uint64_t *position,
9052 int64_t *timeNanos) {
9053 return mThread->getExternalPosition(position, timeNanos);
9054}
9055
Eric Laurenta54f1282017-07-01 19:39:32 -07009056status_t AudioFlinger::MmapThreadHandle::start(const AudioClient& client,
jiabind1f1cb62020-03-24 11:57:57 -07009057 const audio_attributes_t *attr, audio_port_handle_t *handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009058
9059{
jiabind1f1cb62020-03-24 11:57:57 -07009060 return mThread->start(client, attr, handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009061}
9062
9063status_t AudioFlinger::MmapThreadHandle::stop(audio_port_handle_t handle)
9064{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009065 return mThread->stop(handle);
9066}
9067
Eric Laurent18b57012017-02-13 16:23:52 -08009068status_t AudioFlinger::MmapThreadHandle::standby()
9069{
Eric Laurent18b57012017-02-13 16:23:52 -08009070 return mThread->standby();
9071}
9072
Eric Laurent6acd1d42017-01-04 14:23:29 -08009073
9074AudioFlinger::MmapThread::MmapThread(
9075 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
Andy Hungcf10d742020-04-28 15:38:24 -07009076 AudioHwDevice *hwDev, sp<StreamHalInterface> stream, bool systemReady, bool isOut)
Andy Hungea840382020-05-05 21:50:17 -07009077 : ThreadBase(audioFlinger, id, (isOut ? MMAP_PLAYBACK : MMAP_CAPTURE), systemReady, isOut),
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009078 mSessionId(AUDIO_SESSION_NONE),
François Gaffie0c280aa2018-07-25 10:02:15 +02009079 mPortId(AUDIO_PORT_HANDLE_NONE),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009080 mHalStream(stream), mHalDevice(hwDev->hwDevice()), mAudioHwDev(hwDev),
Eric Laurent67f97292018-04-20 18:05:41 -07009081 mActiveTracks(&this->mLocalLog),
9082 mHalVolFloat(-1.0f), // Initialize to illegal value so it always gets set properly later.
9083 mNoCallbackWarningCount(0)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009084{
Eric Laurent18b57012017-02-13 16:23:52 -08009085 mStandby = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009086 readHalParameters_l();
9087}
9088
9089AudioFlinger::MmapThread::~MmapThread()
9090{
9091}
9092
9093void AudioFlinger::MmapThread::onFirstRef()
9094{
9095 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
9096}
9097
9098void AudioFlinger::MmapThread::disconnect()
9099{
Eric Laurent331679c2018-04-16 17:03:16 -07009100 ActiveTracks<MmapTrack> activeTracks;
9101 {
9102 Mutex::Autolock _l(mLock);
9103 for (const sp<MmapTrack> &t : mActiveTracks) {
9104 activeTracks.add(t);
9105 }
9106 }
9107 for (const sp<MmapTrack> &t : activeTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08009108 stop(t->portId());
9109 }
Phil Burk9fabbf82017-08-03 12:02:00 -07009110 // This will decrement references and may cause the destruction of this thread.
Eric Laurent6acd1d42017-01-04 14:23:29 -08009111 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07009112 AudioSystem::releaseOutput(mPortId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009113 } else {
Eric Laurentfee19762018-01-29 18:44:13 -08009114 AudioSystem::releaseInput(mPortId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009115 }
9116}
9117
9118
9119void AudioFlinger::MmapThread::configure(const audio_attributes_t *attr,
9120 audio_stream_type_t streamType __unused,
9121 audio_session_t sessionId,
9122 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009123 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -08009124 audio_port_handle_t portId)
9125{
9126 mAttr = *attr;
9127 mSessionId = sessionId;
9128 mCallback = callback;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009129 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009130 mPortId = portId;
9131}
9132
9133status_t AudioFlinger::MmapThread::createMmapBuffer(int32_t minSizeFrames,
9134 struct audio_mmap_buffer_info *info)
9135{
9136 if (mHalStream == 0) {
9137 return NO_INIT;
9138 }
Eric Laurent18b57012017-02-13 16:23:52 -08009139 mStandby = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009140 return mHalStream->createMmapBuffer(minSizeFrames, info);
9141}
9142
9143status_t AudioFlinger::MmapThread::getMmapPosition(struct audio_mmap_position *position)
9144{
9145 if (mHalStream == 0) {
9146 return NO_INIT;
9147 }
9148 return mHalStream->getMmapPosition(position);
9149}
9150
Eric Laurent331679c2018-04-16 17:03:16 -07009151status_t AudioFlinger::MmapThread::exitStandby()
9152{
9153 status_t ret = mHalStream->start();
9154 if (ret != NO_ERROR) {
9155 ALOGE("%s: error mHalStream->start() = %d for first track", __FUNCTION__, ret);
9156 return ret;
9157 }
Andy Hungcf10d742020-04-28 15:38:24 -07009158 if (mStandby) {
9159 mThreadMetrics.logBeginInterval();
9160 mStandby = false;
9161 }
Eric Laurent331679c2018-04-16 17:03:16 -07009162 return NO_ERROR;
9163}
9164
Eric Laurenta54f1282017-07-01 19:39:32 -07009165status_t AudioFlinger::MmapThread::start(const AudioClient& client,
jiabind1f1cb62020-03-24 11:57:57 -07009166 const audio_attributes_t *attr,
Eric Laurent6acd1d42017-01-04 14:23:29 -08009167 audio_port_handle_t *handle)
9168{
Eric Laurenta54f1282017-07-01 19:39:32 -07009169 ALOGV("%s clientUid %d mStandby %d mPortId %d *handle %d", __FUNCTION__,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07009170 client.identity.uid, mStandby, mPortId, *handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009171 if (mHalStream == 0) {
9172 return NO_INIT;
9173 }
9174
9175 status_t ret;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009176
Eric Laurenta54f1282017-07-01 19:39:32 -07009177 if (*handle == mPortId) {
Phil Burk98ab4082020-09-25 21:46:34 +00009178 // For the first track, reuse portId and session allocated when the stream was opened.
9179 ret = exitStandby();
9180 if (ret == NO_ERROR) {
9181 acquireWakeLock();
9182 }
9183 return ret;
Eric Laurenta54f1282017-07-01 19:39:32 -07009184 }
9185
9186 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
9187
9188 audio_io_handle_t io = mId;
9189 if (isOutput()) {
9190 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
9191 config.sample_rate = mSampleRate;
9192 config.channel_mask = mChannelMask;
9193 config.format = mFormat;
9194 audio_stream_type_t stream = streamType();
9195 audio_output_flags_t flags =
9196 (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009197 audio_port_handle_t deviceId = mDeviceId;
Kevin Rocard153f92d2018-12-18 18:33:28 -08009198 std::vector<audio_io_handle_t> secondaryOutputs;
Eric Laurenta54f1282017-07-01 19:39:32 -07009199 ret = AudioSystem::getOutputForAttr(&mAttr, &io,
9200 mSessionId,
9201 &stream,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07009202 client.identity,
Eric Laurenta54f1282017-07-01 19:39:32 -07009203 &config,
9204 flags,
9205 &deviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -08009206 &portId,
9207 &secondaryOutputs);
9208 ALOGD_IF(!secondaryOutputs.empty(),
9209 "MmapThread::start does not support secondary outputs, ignoring them");
Eric Laurent6acd1d42017-01-04 14:23:29 -08009210 } else {
Eric Laurenta54f1282017-07-01 19:39:32 -07009211 audio_config_base_t config;
9212 config.sample_rate = mSampleRate;
9213 config.channel_mask = mChannelMask;
9214 config.format = mFormat;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009215 audio_port_handle_t deviceId = mDeviceId;
Eric Laurenta54f1282017-07-01 19:39:32 -07009216 ret = AudioSystem::getInputForAttr(&mAttr, &io,
Mikhail Naganov2996f672019-04-18 12:29:59 -07009217 RECORD_RIID_INVALID,
Eric Laurenta54f1282017-07-01 19:39:32 -07009218 mSessionId,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07009219 client.identity,
Eric Laurenta54f1282017-07-01 19:39:32 -07009220 &config,
9221 AUDIO_INPUT_FLAG_MMAP_NOIRQ,
9222 &deviceId,
9223 &portId);
9224 }
9225 // APM should not chose a different input or output stream for the same set of attributes
9226 // and audo configuration
9227 if (ret != NO_ERROR || io != mId) {
9228 ALOGE("%s: error getting output or input from APM (error %d, io %d expected io %d)",
9229 __FUNCTION__, ret, io, mId);
9230 return BAD_VALUE;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009231 }
9232
9233 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07009234 ret = AudioSystem::startOutput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009235 } else {
Eric Laurent4eb58f12018-12-07 16:41:02 -08009236 ret = AudioSystem::startInput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009237 }
9238
Eric Laurent331679c2018-04-16 17:03:16 -07009239 Mutex::Autolock _l(mLock);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009240 // abort if start is rejected by audio policy manager
9241 if (ret != NO_ERROR) {
Phil Burk7f6b40d2017-02-09 13:18:38 -08009242 ALOGE("%s: error start rejected by AudioPolicyManager = %d", __FUNCTION__, ret);
Eric Tan39ec8d62018-07-24 09:49:29 -07009243 if (!mActiveTracks.isEmpty()) {
Eric Laurent331679c2018-04-16 17:03:16 -07009244 mLock.unlock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009245 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07009246 AudioSystem::releaseOutput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009247 } else {
Eric Laurentfee19762018-01-29 18:44:13 -08009248 AudioSystem::releaseInput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009249 }
Eric Laurent331679c2018-04-16 17:03:16 -07009250 mLock.lock();
Eric Laurent18b57012017-02-13 16:23:52 -08009251 } else {
9252 mHalStream->stop();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009253 }
9254 return PERMISSION_DENIED;
9255 }
9256
Kevin Rocard1f564ac2018-03-29 13:53:10 -07009257 // Given that MmapThread::mAttr is mutable, should a MmapTrack have attributes ?
jiabind1f1cb62020-03-24 11:57:57 -07009258 sp<MmapTrack> track = new MmapTrack(this, attr == nullptr ? mAttr : *attr, mSampleRate, mFormat,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07009259 mChannelMask, mSessionId, isOutput(), client.identity,
9260 IPCThreadState::self()->getCallingPid(), portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009261
Eric Laurent4eb58f12018-12-07 16:41:02 -08009262 if (isOutput()) {
9263 // force volume update when a new track is added
9264 mHalVolFloat = -1.0f;
9265 } else if (!track->isSilenced_l()) {
9266 for (const sp<MmapTrack> &t : mActiveTracks) {
Philip P. Moltmannbda45752020-07-17 16:41:18 -07009267 if (t->isSilenced_l() && t->uid() != client.identity.uid)
Eric Laurent4eb58f12018-12-07 16:41:02 -08009268 t->invalidate();
9269 }
9270 }
9271
9272
Eric Laurent6acd1d42017-01-04 14:23:29 -08009273 mActiveTracks.add(track);
Eric Laurenta54f1282017-07-01 19:39:32 -07009274 sp<EffectChain> chain = getEffectChain_l(mSessionId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009275 if (chain != 0) {
9276 chain->setStrategy(AudioSystem::getStrategyForStream(streamType()));
9277 chain->incTrackCnt();
9278 chain->incActiveTrackCnt();
9279 }
9280
Andy Hungc2b11cb2020-04-22 09:04:01 -07009281 track->logBeginInterval(patchSinksToString(&mPatch)); // log to MediaMetrics
Eric Laurent6acd1d42017-01-04 14:23:29 -08009282 *handle = portId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009283 broadcast_l();
9284
Eric Laurenta54f1282017-07-01 19:39:32 -07009285 ALOGV("%s DONE handle %d stream %p", __FUNCTION__, *handle, mHalStream.get());
Eric Laurent6acd1d42017-01-04 14:23:29 -08009286
9287 return NO_ERROR;
9288}
9289
9290status_t AudioFlinger::MmapThread::stop(audio_port_handle_t handle)
9291{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009292 ALOGV("%s handle %d", __FUNCTION__, handle);
9293
9294 if (mHalStream == 0) {
9295 return NO_INIT;
9296 }
9297
Eric Laurenta54f1282017-07-01 19:39:32 -07009298 if (handle == mPortId) {
9299 mHalStream->stop();
Phil Burk98ab4082020-09-25 21:46:34 +00009300 releaseWakeLock();
Eric Laurenta54f1282017-07-01 19:39:32 -07009301 return NO_ERROR;
9302 }
9303
Eric Laurent331679c2018-04-16 17:03:16 -07009304 Mutex::Autolock _l(mLock);
9305
Eric Laurent6acd1d42017-01-04 14:23:29 -08009306 sp<MmapTrack> track;
9307 for (const sp<MmapTrack> &t : mActiveTracks) {
9308 if (handle == t->portId()) {
9309 track = t;
9310 break;
9311 }
9312 }
9313 if (track == 0) {
9314 return BAD_VALUE;
9315 }
9316
9317 mActiveTracks.remove(track);
9318
Eric Laurent331679c2018-04-16 17:03:16 -07009319 mLock.unlock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009320 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07009321 AudioSystem::stopOutput(track->portId());
9322 AudioSystem::releaseOutput(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -08009323 } else {
Eric Laurentfee19762018-01-29 18:44:13 -08009324 AudioSystem::stopInput(track->portId());
9325 AudioSystem::releaseInput(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -08009326 }
Eric Laurent331679c2018-04-16 17:03:16 -07009327 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009328
9329 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
9330 if (chain != 0) {
9331 chain->decActiveTrackCnt();
9332 chain->decTrackCnt();
9333 }
9334
9335 broadcast_l();
9336
Eric Laurent6acd1d42017-01-04 14:23:29 -08009337 return NO_ERROR;
9338}
9339
Eric Laurent18b57012017-02-13 16:23:52 -08009340status_t AudioFlinger::MmapThread::standby()
9341{
9342 ALOGV("%s", __FUNCTION__);
9343
9344 if (mHalStream == 0) {
9345 return NO_INIT;
9346 }
Eric Tan39ec8d62018-07-24 09:49:29 -07009347 if (!mActiveTracks.isEmpty()) {
Eric Laurent18b57012017-02-13 16:23:52 -08009348 return INVALID_OPERATION;
9349 }
9350 mHalStream->standby();
Andy Hungcf10d742020-04-28 15:38:24 -07009351 if (!mStandby) {
9352 mThreadMetrics.logEndInterval();
9353 mStandby = true;
9354 }
Eric Laurent18b57012017-02-13 16:23:52 -08009355 releaseWakeLock();
9356 return NO_ERROR;
9357}
9358
Eric Laurent6acd1d42017-01-04 14:23:29 -08009359
9360void AudioFlinger::MmapThread::readHalParameters_l()
9361{
9362 status_t result = mHalStream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
9363 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
9364 mFormat = mHALFormat;
9365 LOG_ALWAYS_FATAL_IF(!audio_is_linear_pcm(mFormat), "HAL format %#x is not linear pcm", mFormat);
9366 result = mHalStream->getFrameSize(&mFrameSize);
9367 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
Hayden Gomes1a89ab32020-06-12 11:05:47 -07009368 LOG_ALWAYS_FATAL_IF(mFrameSize <= 0, "Error frame size was %zu but must be greater than zero",
9369 mFrameSize);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009370 result = mHalStream->getBufferSize(&mBufferSize);
9371 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
9372 mFrameCount = mBufferSize / mFrameSize;
Andy Hungc2b11cb2020-04-22 09:04:01 -07009373
Andy Hungcf10d742020-04-28 15:38:24 -07009374 // TODO: make a readHalParameters call?
9375 mediametrics::LogItem item(mThreadMetrics.getMetricsId());
Andy Hungc2b11cb2020-04-22 09:04:01 -07009376 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
9377 .set(AMEDIAMETRICS_PROP_ENCODING, formatToString(mFormat).c_str())
9378 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
9379 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
9380 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
9381 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mFrameCount)
9382 /*
9383 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
9384 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELMASK,
9385 (int32_t)mHapticChannelMask)
9386 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELCOUNT,
9387 (int32_t)mHapticChannelCount)
9388 */
9389 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_ENCODING,
9390 formatToString(mHALFormat).c_str())
9391 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_FRAMECOUNT,
9392 (int32_t)mFrameCount) // sic - added HAL
9393 .record();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009394}
9395
9396bool AudioFlinger::MmapThread::threadLoop()
9397{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009398 checkSilentMode_l();
9399
9400 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
9401
9402 while (!exitPending())
9403 {
Eric Laurent6acd1d42017-01-04 14:23:29 -08009404 Vector< sp<EffectChain> > effectChains;
9405
Andy Hung13850be2019-03-14 11:33:09 -07009406 { // under Thread lock
9407 Mutex::Autolock _l(mLock);
9408
Eric Laurent6acd1d42017-01-04 14:23:29 -08009409 if (mSignalPending) {
9410 // A signal was raised while we were unlocked
9411 mSignalPending = false;
9412 } else {
9413 if (mConfigEvents.isEmpty()) {
9414 // we're about to wait, flush the binder command buffer
9415 IPCThreadState::self()->flushCommands();
9416
9417 if (exitPending()) {
9418 break;
9419 }
9420
Eric Laurent6acd1d42017-01-04 14:23:29 -08009421 // wait until we have something to do...
9422 ALOGV("%s going to sleep", myName.string());
9423 mWaitWorkCV.wait(mLock);
9424 ALOGV("%s waking up", myName.string());
Eric Laurent6acd1d42017-01-04 14:23:29 -08009425
9426 checkSilentMode_l();
9427
9428 continue;
9429 }
9430 }
9431
9432 processConfigEvents_l();
9433
9434 processVolume_l();
9435
9436 checkInvalidTracks_l();
9437
9438 mActiveTracks.updatePowerState(this);
9439
Kevin Rocard069c2712018-03-29 19:09:14 -07009440 updateMetadata_l();
9441
Eric Laurent6acd1d42017-01-04 14:23:29 -08009442 lockEffectChains_l(effectChains);
Andy Hung13850be2019-03-14 11:33:09 -07009443 } // release Thread lock
9444
Eric Laurent6acd1d42017-01-04 14:23:29 -08009445 for (size_t i = 0; i < effectChains.size(); i ++) {
Andy Hung13850be2019-03-14 11:33:09 -07009446 effectChains[i]->process_l(); // Thread is not locked, but effect chain is locked
Eric Laurent6acd1d42017-01-04 14:23:29 -08009447 }
Andy Hung13850be2019-03-14 11:33:09 -07009448
9449 // enable changes in effect chain, including moving to another thread.
Eric Laurent6acd1d42017-01-04 14:23:29 -08009450 unlockEffectChains(effectChains);
9451 // Effect chains will be actually deleted here if they were removed from
9452 // mEffectChains list during mixing or effects processing
9453 }
9454
9455 threadLoop_exit();
9456
9457 if (!mStandby) {
9458 threadLoop_standby();
9459 mStandby = true;
9460 }
9461
Eric Laurent6acd1d42017-01-04 14:23:29 -08009462 ALOGV("Thread %p type %d exiting", this, mType);
9463 return false;
9464}
9465
9466// checkForNewParameter_l() must be called with ThreadBase::mLock held
9467bool AudioFlinger::MmapThread::checkForNewParameter_l(const String8& keyValuePair,
9468 status_t& status)
9469{
9470 AudioParameter param = AudioParameter(keyValuePair);
9471 int value;
Eric Laurente6e9a482017-07-25 19:26:02 -07009472 bool sendToHal = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009473 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07009474 LOG_FATAL("Should not happen set routing device in MmapThread");
Eric Laurent6acd1d42017-01-04 14:23:29 -08009475 }
Eric Laurente6e9a482017-07-25 19:26:02 -07009476 if (sendToHal) {
9477 status = mHalStream->setParameters(keyValuePair);
9478 } else {
9479 status = NO_ERROR;
9480 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08009481
9482 return false;
9483}
9484
9485String8 AudioFlinger::MmapThread::getParameters(const String8& keys)
9486{
9487 Mutex::Autolock _l(mLock);
9488 String8 out_s8;
9489 if (initCheck() == NO_ERROR && mHalStream->getParameters(keys, &out_s8) == OK) {
9490 return out_s8;
9491 }
9492 return String8();
9493}
9494
Eric Laurent09f1ed22019-04-24 17:45:17 -07009495void AudioFlinger::MmapThread::ioConfigChanged(audio_io_config_event event, pid_t pid,
9496 audio_port_handle_t portId __unused) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08009497 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
9498
9499 desc->mIoHandle = mId;
9500
9501 switch (event) {
9502 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07009503 case AUDIO_INPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -08009504 case AUDIO_INPUT_CONFIG_CHANGED:
9505 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07009506 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -08009507 case AUDIO_OUTPUT_CONFIG_CHANGED:
9508 desc->mPatch = mPatch;
9509 desc->mChannelMask = mChannelMask;
9510 desc->mSamplingRate = mSampleRate;
9511 desc->mFormat = mFormat;
9512 desc->mFrameCount = mFrameCount;
9513 desc->mFrameCountHAL = mFrameCount;
9514 desc->mLatency = 0;
9515 break;
9516
9517 case AUDIO_INPUT_CLOSED:
9518 case AUDIO_OUTPUT_CLOSED:
9519 default:
9520 break;
9521 }
9522 mAudioFlinger->ioConfigChanged(event, desc, pid);
9523}
9524
9525status_t AudioFlinger::MmapThread::createAudioPatch_l(const struct audio_patch *patch,
9526 audio_patch_handle_t *handle)
9527{
9528 status_t status = NO_ERROR;
9529
9530 // store new device and send to effects
9531 audio_devices_t type = AUDIO_DEVICE_NONE;
9532 audio_port_handle_t deviceId;
jiabinc52b1ff2019-10-31 17:20:42 -07009533 AudioDeviceTypeAddrVector sinkDeviceTypeAddrs;
9534 AudioDeviceTypeAddr sourceDeviceTypeAddr;
9535 uint32_t numDevices = 0;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009536 if (isOutput()) {
9537 for (unsigned int i = 0; i < patch->num_sinks; i++) {
jiabinc52b1ff2019-10-31 17:20:42 -07009538 LOG_ALWAYS_FATAL_IF(popcount(patch->sinks[i].ext.device.type) > 1
9539 && !mAudioHwDev->supportsAudioPatches(),
9540 "Enumerated device type(%#x) must not be used "
9541 "as it does not support audio patches",
9542 patch->sinks[i].ext.device.type);
Mikhail Naganov55773032020-10-01 15:08:13 -07009543 type = static_cast<audio_devices_t>(type | patch->sinks[i].ext.device.type);
jiabinc52b1ff2019-10-31 17:20:42 -07009544 sinkDeviceTypeAddrs.push_back(AudioDeviceTypeAddr(patch->sinks[i].ext.device.type,
9545 patch->sinks[i].ext.device.address));
Eric Laurent6acd1d42017-01-04 14:23:29 -08009546 }
9547 deviceId = patch->sinks[0].id;
jiabinc52b1ff2019-10-31 17:20:42 -07009548 numDevices = mPatch.num_sinks;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009549 } else {
9550 type = patch->sources[0].ext.device.type;
9551 deviceId = patch->sources[0].id;
jiabinc52b1ff2019-10-31 17:20:42 -07009552 numDevices = mPatch.num_sources;
9553 sourceDeviceTypeAddr.mType = patch->sources[0].ext.device.type;
jiabin0a488932020-08-07 17:32:40 -07009554 sourceDeviceTypeAddr.setAddress(patch->sources[0].ext.device.address);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009555 }
9556
9557 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08009558 if (isOutput()) {
9559 mEffectChains[i]->setDevices_l(sinkDeviceTypeAddrs);
9560 } else {
9561 mEffectChains[i]->setInputDevice_l(sourceDeviceTypeAddr);
9562 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08009563 }
9564
jiabinc52b1ff2019-10-31 17:20:42 -07009565 if (!isOutput()) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08009566 // store new source and send to effects
9567 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
9568 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
9569 for (size_t i = 0; i < mEffectChains.size(); i++) {
9570 mEffectChains[i]->setAudioSource_l(mAudioSource);
9571 }
9572 }
9573 }
9574
9575 if (mAudioHwDev->supportsAudioPatches()) {
9576 status = mHalDevice->createAudioPatch(patch->num_sources,
9577 patch->sources,
9578 patch->num_sinks,
9579 patch->sinks,
9580 handle);
9581 } else {
9582 char *address;
9583 if (strcmp(patch->sinks[0].ext.device.address, "") != 0) {
9584 //FIXME: we only support address on first sink with HAL version < 3.0
9585 address = audio_device_address_to_parameter(
9586 patch->sinks[0].ext.device.type,
9587 patch->sinks[0].ext.device.address);
9588 } else {
9589 address = (char *)calloc(1, 1);
9590 }
9591 AudioParameter param = AudioParameter(String8(address));
9592 free(address);
9593 param.addInt(String8(AudioParameter::keyRouting), (int)type);
9594 if (!isOutput()) {
9595 param.addInt(String8(AudioParameter::keyInputSource),
9596 (int)patch->sinks[0].ext.mix.usecase.source);
9597 }
9598 status = mHalStream->setParameters(param.toString());
9599 *handle = AUDIO_PATCH_HANDLE_NONE;
9600 }
9601
jiabinc52b1ff2019-10-31 17:20:42 -07009602 if (numDevices == 0 || mDeviceId != deviceId) {
9603 if (isOutput()) {
9604 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
9605 mOutDeviceTypeAddrs = sinkDeviceTypeAddrs;
jiabin0a957d32020-04-29 10:56:20 -07009606 checkSilentMode_l();
jiabinc52b1ff2019-10-31 17:20:42 -07009607 } else {
9608 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
9609 mInDeviceTypeAddr = sourceDeviceTypeAddr;
9610 }
Phil Burk7f6b40d2017-02-09 13:18:38 -08009611 sp<MmapStreamCallback> callback = mCallback.promote();
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009612 if (mDeviceId != deviceId && callback != 0) {
Eric Laurent734046e2018-04-16 14:50:52 -07009613 mLock.unlock();
Phil Burk7f6b40d2017-02-09 13:18:38 -08009614 callback->onRoutingChanged(deviceId);
Eric Laurent734046e2018-04-16 14:50:52 -07009615 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009616 }
jiabinc52b1ff2019-10-31 17:20:42 -07009617 mPatch = *patch;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009618 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009619 }
9620 return status;
9621}
9622
9623status_t AudioFlinger::MmapThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
9624{
9625 status_t status = NO_ERROR;
9626
jiabinc52b1ff2019-10-31 17:20:42 -07009627 mPatch = audio_patch{};
9628 mOutDeviceTypeAddrs.clear();
9629 mInDeviceTypeAddr.reset();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009630
9631 bool supportsAudioPatches = mHalDevice->supportsAudioPatches(&supportsAudioPatches) == OK ?
9632 supportsAudioPatches : false;
9633
9634 if (supportsAudioPatches) {
9635 status = mHalDevice->releaseAudioPatch(handle);
9636 } else {
9637 AudioParameter param;
9638 param.addInt(String8(AudioParameter::keyRouting), 0);
9639 status = mHalStream->setParameters(param.toString());
9640 }
9641 return status;
9642}
9643
Mikhail Naganovdc769682018-05-04 15:34:08 -07009644void AudioFlinger::MmapThread::toAudioPortConfig(struct audio_port_config *config)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009645{
Mikhail Naganovdc769682018-05-04 15:34:08 -07009646 ThreadBase::toAudioPortConfig(config);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009647 if (isOutput()) {
9648 config->role = AUDIO_PORT_ROLE_SOURCE;
9649 config->ext.mix.hw_module = mAudioHwDev->handle();
9650 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
9651 } else {
9652 config->role = AUDIO_PORT_ROLE_SINK;
9653 config->ext.mix.hw_module = mAudioHwDev->handle();
9654 config->ext.mix.usecase.source = mAudioSource;
9655 }
9656}
9657
9658status_t AudioFlinger::MmapThread::addEffectChain_l(const sp<EffectChain>& chain)
9659{
9660 audio_session_t session = chain->sessionId();
9661
9662 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
9663 // Attach all tracks with same session ID to this chain.
9664 // indicate all active tracks in the chain
9665 for (const sp<MmapTrack> &track : mActiveTracks) {
9666 if (session == track->sessionId()) {
9667 chain->incTrackCnt();
9668 chain->incActiveTrackCnt();
9669 }
9670 }
9671
9672 chain->setThread(this);
9673 chain->setInBuffer(nullptr);
9674 chain->setOutBuffer(nullptr);
9675 chain->syncHalEffectsState();
9676
9677 mEffectChains.add(chain);
9678 checkSuspendOnAddEffectChain_l(chain);
9679 return NO_ERROR;
9680}
9681
9682size_t AudioFlinger::MmapThread::removeEffectChain_l(const sp<EffectChain>& chain)
9683{
9684 audio_session_t session = chain->sessionId();
9685
9686 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
9687
9688 for (size_t i = 0; i < mEffectChains.size(); i++) {
9689 if (chain == mEffectChains[i]) {
9690 mEffectChains.removeAt(i);
9691 // detach all active tracks from the chain
9692 // detach all tracks with same session ID from this chain
9693 for (const sp<MmapTrack> &track : mActiveTracks) {
9694 if (session == track->sessionId()) {
9695 chain->decActiveTrackCnt();
9696 chain->decTrackCnt();
9697 }
9698 }
9699 break;
9700 }
9701 }
9702 return mEffectChains.size();
9703}
9704
Eric Laurent6acd1d42017-01-04 14:23:29 -08009705void AudioFlinger::MmapThread::threadLoop_standby()
9706{
9707 mHalStream->standby();
9708}
9709
9710void AudioFlinger::MmapThread::threadLoop_exit()
9711{
Phil Burk7dce7282017-09-27 13:51:41 -07009712 // Do not call callback->onTearDown() because it is redundant for thread exit
9713 // and because it can cause a recursive mutex lock on stop().
Eric Laurent6acd1d42017-01-04 14:23:29 -08009714}
9715
9716status_t AudioFlinger::MmapThread::setSyncEvent(const sp<SyncEvent>& event __unused)
9717{
9718 return BAD_VALUE;
9719}
9720
9721bool AudioFlinger::MmapThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
9722{
9723 return false;
9724}
9725
9726status_t AudioFlinger::MmapThread::checkEffectCompatibility_l(
9727 const effect_descriptor_t *desc, audio_session_t sessionId)
9728{
9729 // No global effect sessions on mmap threads
Eric Laurent3f75a5b2019-11-12 15:55:51 -08009730 if (audio_is_global_session(sessionId)) {
9731 ALOGW("checkEffectCompatibility_l(): global effect %s on MMAP thread %s",
Eric Laurent6acd1d42017-01-04 14:23:29 -08009732 desc->name, mThreadName);
9733 return BAD_VALUE;
9734 }
9735
9736 if (!isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC)) {
9737 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on capture mmap thread",
9738 desc->name);
9739 return BAD_VALUE;
9740 }
9741 if (isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Glenn Kastend3bb6452016-12-05 18:14:37 -08009742 ALOGW("checkEffectCompatibility_l(): pre processing effect %s created on playback mmap "
9743 "thread", desc->name);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009744 return BAD_VALUE;
9745 }
9746
9747 // Only allow effects without processing load or latency
9748 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) != EFFECT_FLAG_NO_PROCESS) {
9749 return BAD_VALUE;
9750 }
9751
jiabineb3bda02020-06-30 14:07:03 -07009752 if (EffectModule::isHapticGenerator(&desc->type)) {
9753 ALOGE("%s(): HapticGenerator is not supported for MmapThread", __func__);
9754 return BAD_VALUE;
9755 }
9756
Eric Laurent6acd1d42017-01-04 14:23:29 -08009757 return NO_ERROR;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009758}
9759
9760void AudioFlinger::MmapThread::checkInvalidTracks_l()
9761{
9762 for (const sp<MmapTrack> &track : mActiveTracks) {
9763 if (track->isInvalid()) {
Phil Burk7f6b40d2017-02-09 13:18:38 -08009764 sp<MmapStreamCallback> callback = mCallback.promote();
9765 if (callback != 0) {
Eric Laurent734046e2018-04-16 14:50:52 -07009766 mLock.unlock();
Eric Laurent331679c2018-04-16 17:03:16 -07009767 callback->onTearDown(track->portId());
Eric Laurent734046e2018-04-16 14:50:52 -07009768 mLock.lock();
Eric Laurent331679c2018-04-16 17:03:16 -07009769 } else if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
9770 ALOGW("Could not notify MMAP stream tear down: no onTearDown callback!");
9771 mNoCallbackWarningCount++;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009772 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08009773 }
9774 }
9775}
9776
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07009777void AudioFlinger::MmapThread::dumpInternals_l(int fd, const Vector<String16>& args __unused)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009778{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009779 dprintf(fd, " Attributes: content type %d usage %d source %d\n",
9780 mAttr.content_type, mAttr.usage, mAttr.source);
9781 dprintf(fd, " Session: %d port Id: %d\n", mSessionId, mPortId);
Eric Tan39ec8d62018-07-24 09:49:29 -07009782 if (mActiveTracks.isEmpty()) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08009783 dprintf(fd, " No active clients\n");
9784 }
9785}
9786
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07009787void AudioFlinger::MmapThread::dumpTracks_l(int fd, const Vector<String16>& args __unused)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009788{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009789 String8 result;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009790 size_t numtracks = mActiveTracks.size();
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009791 dprintf(fd, " %zu Tracks\n", numtracks);
9792 const char *prefix = " ";
Eric Laurent6acd1d42017-01-04 14:23:29 -08009793 if (numtracks) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009794 result.append(prefix);
Kevin Rocard5f2136e2018-05-11 22:03:00 -07009795 mActiveTracks[0]->appendDumpHeader(result);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009796 for (size_t i = 0; i < numtracks ; ++i) {
9797 sp<MmapTrack> track = mActiveTracks[i];
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009798 result.append(prefix);
9799 track->appendDump(result, true /* active */);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009800 }
9801 } else {
9802 dprintf(fd, "\n");
9803 }
9804 write(fd, result.string(), result.size());
9805}
9806
9807AudioFlinger::MmapPlaybackThread::MmapPlaybackThread(
9808 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
jiabinc52b1ff2019-10-31 17:20:42 -07009809 AudioHwDevice *hwDev, AudioStreamOut *output, bool systemReady)
Andy Hungcf10d742020-04-28 15:38:24 -07009810 : MmapThread(audioFlinger, id, hwDev, output->stream, systemReady, true /* isOut */),
Eric Laurent6acd1d42017-01-04 14:23:29 -08009811 mStreamType(AUDIO_STREAM_MUSIC),
Phil Burk56ecf3e2018-03-12 15:38:17 -07009812 mStreamVolume(1.0),
9813 mStreamMute(false),
Phil Burk56ecf3e2018-03-12 15:38:17 -07009814 mOutput(output)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009815{
9816 snprintf(mThreadName, kThreadNameLength, "AudioMmapOut_%X", id);
9817 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
9818 mMasterVolume = audioFlinger->masterVolume_l();
9819 mMasterMute = audioFlinger->masterMute_l();
9820 if (mAudioHwDev) {
9821 if (mAudioHwDev->canSetMasterVolume()) {
9822 mMasterVolume = 1.0;
9823 }
9824
9825 if (mAudioHwDev->canSetMasterMute()) {
9826 mMasterMute = false;
9827 }
9828 }
9829}
9830
9831void AudioFlinger::MmapPlaybackThread::configure(const audio_attributes_t *attr,
9832 audio_stream_type_t streamType,
9833 audio_session_t sessionId,
9834 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009835 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -08009836 audio_port_handle_t portId)
9837{
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009838 MmapThread::configure(attr, streamType, sessionId, callback, deviceId, portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009839 mStreamType = streamType;
9840}
9841
9842AudioStreamOut* AudioFlinger::MmapPlaybackThread::clearOutput()
9843{
9844 Mutex::Autolock _l(mLock);
9845 AudioStreamOut *output = mOutput;
9846 mOutput = NULL;
9847 return output;
9848}
9849
9850void AudioFlinger::MmapPlaybackThread::setMasterVolume(float value)
9851{
9852 Mutex::Autolock _l(mLock);
9853 // Don't apply master volume in SW if our HAL can do it for us.
9854 if (mAudioHwDev &&
9855 mAudioHwDev->canSetMasterVolume()) {
9856 mMasterVolume = 1.0;
9857 } else {
9858 mMasterVolume = value;
9859 }
9860}
9861
9862void AudioFlinger::MmapPlaybackThread::setMasterMute(bool muted)
9863{
9864 Mutex::Autolock _l(mLock);
9865 // Don't apply master mute in SW if our HAL can do it for us.
9866 if (mAudioHwDev && mAudioHwDev->canSetMasterMute()) {
9867 mMasterMute = false;
9868 } else {
9869 mMasterMute = muted;
9870 }
9871}
9872
9873void AudioFlinger::MmapPlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
9874{
9875 Mutex::Autolock _l(mLock);
9876 if (stream == mStreamType) {
9877 mStreamVolume = value;
9878 broadcast_l();
9879 }
9880}
9881
9882float AudioFlinger::MmapPlaybackThread::streamVolume(audio_stream_type_t stream) const
9883{
9884 Mutex::Autolock _l(mLock);
9885 if (stream == mStreamType) {
9886 return mStreamVolume;
9887 }
9888 return 0.0f;
9889}
9890
9891void AudioFlinger::MmapPlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
9892{
9893 Mutex::Autolock _l(mLock);
9894 if (stream == mStreamType) {
9895 mStreamMute= muted;
9896 broadcast_l();
9897 }
9898}
9899
9900void AudioFlinger::MmapPlaybackThread::invalidateTracks(audio_stream_type_t streamType)
9901{
9902 Mutex::Autolock _l(mLock);
9903 if (streamType == mStreamType) {
9904 for (const sp<MmapTrack> &track : mActiveTracks) {
9905 track->invalidate();
9906 }
9907 broadcast_l();
9908 }
9909}
9910
9911void AudioFlinger::MmapPlaybackThread::processVolume_l()
9912{
9913 float volume;
9914
9915 if (mMasterMute || mStreamMute) {
9916 volume = 0;
9917 } else {
9918 volume = mMasterVolume * mStreamVolume;
9919 }
9920
9921 if (volume != mHalVolFloat) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08009922
9923 // Convert volumes from float to 8.24
9924 uint32_t vol = (uint32_t)(volume * (1 << 24));
9925
9926 // Delegate volume control to effect in track effect chain if needed
9927 // only one effect chain can be present on DirectOutputThread, so if
9928 // there is one, the track is connected to it
9929 if (!mEffectChains.isEmpty()) {
9930 mEffectChains[0]->setVolume_l(&vol, &vol);
9931 volume = (float)vol / (1 << 24);
9932 }
Eric Laurentdff774a2017-04-21 15:29:38 -07009933 // Try to use HW volume control and fall back to SW control if not implemented
Phil Burk56ecf3e2018-03-12 15:38:17 -07009934 if (mOutput->stream->setVolume(volume, volume) == NO_ERROR) {
9935 mHalVolFloat = volume; // HW volume control worked, so update value.
9936 mNoCallbackWarningCount = 0;
9937 } else {
Eric Laurentdff774a2017-04-21 15:29:38 -07009938 sp<MmapStreamCallback> callback = mCallback.promote();
9939 if (callback != 0) {
9940 int channelCount;
9941 if (isOutput()) {
9942 channelCount = audio_channel_count_from_out_mask(mChannelMask);
9943 } else {
9944 channelCount = audio_channel_count_from_in_mask(mChannelMask);
9945 }
9946 Vector<float> values;
9947 for (int i = 0; i < channelCount; i++) {
9948 values.add(volume);
9949 }
Phil Burk56ecf3e2018-03-12 15:38:17 -07009950 mHalVolFloat = volume; // SW volume control worked, so update value.
9951 mNoCallbackWarningCount = 0;
Eric Laurent734046e2018-04-16 14:50:52 -07009952 mLock.unlock();
9953 callback->onVolumeChanged(mChannelMask, values);
9954 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009955 } else {
Phil Burk56ecf3e2018-03-12 15:38:17 -07009956 if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
9957 ALOGW("Could not set MMAP stream volume: no volume callback!");
9958 mNoCallbackWarningCount++;
9959 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08009960 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08009961 }
9962 }
9963}
9964
Kevin Rocard069c2712018-03-29 19:09:14 -07009965void AudioFlinger::MmapPlaybackThread::updateMetadata_l()
9966{
9967 if (mOutput == nullptr || mOutput->stream == nullptr ||
9968 !mActiveTracks.readAndClearHasChanged()) {
9969 return;
9970 }
9971 StreamOutHalInterface::SourceMetadata metadata;
9972 for (const sp<MmapTrack> &track : mActiveTracks) {
9973 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurent94579172020-11-20 18:41:04 +01009974 playback_track_metadata_v7_t trackMetadata;
9975 trackMetadata.base = {
Kevin Rocard069c2712018-03-29 19:09:14 -07009976 .usage = track->attributes().usage,
9977 .content_type = track->attributes().content_type,
9978 .gain = mHalVolFloat, // TODO: propagate from aaudio pre-mix volume
Eric Laurent94579172020-11-20 18:41:04 +01009979 };
9980 trackMetadata.channel_mask = track->channelMask(),
9981 strncpy(trackMetadata.tags, track->attributes().tags, AUDIO_ATTRIBUTES_TAGS_MAX_SIZE);
9982 metadata.tracks.push_back(trackMetadata);
Kevin Rocard069c2712018-03-29 19:09:14 -07009983 }
9984 mOutput->stream->updateSourceMetadata(metadata);
9985}
9986
Eric Laurent6acd1d42017-01-04 14:23:29 -08009987void AudioFlinger::MmapPlaybackThread::checkSilentMode_l()
9988{
9989 if (!mMasterMute) {
9990 char value[PROPERTY_VALUE_MAX];
9991 if (property_get("ro.audio.silent", value, "0") > 0) {
9992 char *endptr;
9993 unsigned long ul = strtoul(value, &endptr, 0);
9994 if (*endptr == '\0' && ul != 0) {
9995 ALOGD("Silence is golden");
9996 // The setprop command will not allow a property to be changed after
9997 // the first time it is set, so we don't have to worry about un-muting.
9998 setMasterMute_l(true);
9999 }
10000 }
10001 }
10002}
10003
Mikhail Naganov32abc2b2018-05-24 12:57:11 -070010004void AudioFlinger::MmapPlaybackThread::toAudioPortConfig(struct audio_port_config *config)
10005{
10006 MmapThread::toAudioPortConfig(config);
10007 if (mOutput && mOutput->flags != AUDIO_OUTPUT_FLAG_NONE) {
10008 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
10009 config->flags.output = mOutput->flags;
10010 }
10011}
10012
jiabinb7d8c5a2020-08-26 17:24:52 -070010013status_t AudioFlinger::MmapPlaybackThread::getExternalPosition(uint64_t *position,
10014 int64_t *timeNanos)
10015{
10016 if (mOutput == nullptr) {
10017 return NO_INIT;
10018 }
10019 struct timespec timestamp;
10020 status_t status = mOutput->getPresentationPosition(position, &timestamp);
10021 if (status == NO_ERROR) {
10022 *timeNanos = timestamp.tv_sec * NANOS_PER_SECOND + timestamp.tv_nsec;
10023 }
10024 return status;
10025}
10026
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -070010027void AudioFlinger::MmapPlaybackThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010028{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -070010029 MmapThread::dumpInternals_l(fd, args);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010030
Glenn Kastend3bb6452016-12-05 18:14:37 -080010031 dprintf(fd, " Stream type: %d Stream volume: %f HAL volume: %f Stream mute %d\n",
10032 mStreamType, mStreamVolume, mHalVolFloat, mStreamMute);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010033 dprintf(fd, " Master volume: %f Master mute %d\n", mMasterVolume, mMasterMute);
10034}
10035
10036AudioFlinger::MmapCaptureThread::MmapCaptureThread(
10037 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
jiabinc52b1ff2019-10-31 17:20:42 -070010038 AudioHwDevice *hwDev, AudioStreamIn *input, bool systemReady)
Andy Hungcf10d742020-04-28 15:38:24 -070010039 : MmapThread(audioFlinger, id, hwDev, input->stream, systemReady, false /* isOut */),
Eric Laurent6acd1d42017-01-04 14:23:29 -080010040 mInput(input)
10041{
10042 snprintf(mThreadName, kThreadNameLength, "AudioMmapIn_%X", id);
10043 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
10044}
10045
Eric Laurent331679c2018-04-16 17:03:16 -070010046status_t AudioFlinger::MmapCaptureThread::exitStandby()
10047{
Phil Burkf054fc32018-12-06 09:45:59 -080010048 {
10049 // mInput might have been cleared by clearInput()
10050 Mutex::Autolock _l(mLock);
10051 if (mInput != nullptr && mInput->stream != nullptr) {
10052 mInput->stream->setGain(1.0f);
10053 }
10054 }
Eric Laurent331679c2018-04-16 17:03:16 -070010055 return MmapThread::exitStandby();
10056}
10057
Eric Laurent6acd1d42017-01-04 14:23:29 -080010058AudioFlinger::AudioStreamIn* AudioFlinger::MmapCaptureThread::clearInput()
10059{
10060 Mutex::Autolock _l(mLock);
10061 AudioStreamIn *input = mInput;
10062 mInput = NULL;
10063 return input;
10064}
Kevin Rocard069c2712018-03-29 19:09:14 -070010065
Eric Laurent331679c2018-04-16 17:03:16 -070010066
10067void AudioFlinger::MmapCaptureThread::processVolume_l()
10068{
10069 bool changed = false;
10070 bool silenced = false;
10071
10072 sp<MmapStreamCallback> callback = mCallback.promote();
10073 if (callback == 0) {
10074 if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
10075 ALOGW("Could not set MMAP stream silenced: no onStreamSilenced callback!");
10076 mNoCallbackWarningCount++;
10077 }
10078 }
10079
10080 // After a change occurred in track silenced state, mute capture in audio DSP if at least one
10081 // track is silenced and unmute otherwise
10082 for (size_t i = 0; i < mActiveTracks.size() && !silenced; i++) {
10083 if (!mActiveTracks[i]->getAndSetSilencedNotified_l()) {
10084 changed = true;
10085 silenced = mActiveTracks[i]->isSilenced_l();
10086 }
10087 }
10088
10089 if (changed) {
10090 mInput->stream->setGain(silenced ? 0.0f: 1.0f);
10091 }
10092}
10093
Kevin Rocard069c2712018-03-29 19:09:14 -070010094void AudioFlinger::MmapCaptureThread::updateMetadata_l()
10095{
10096 if (mInput == nullptr || mInput->stream == nullptr ||
10097 !mActiveTracks.readAndClearHasChanged()) {
10098 return;
10099 }
10100 StreamInHalInterface::SinkMetadata metadata;
10101 for (const sp<MmapTrack> &track : mActiveTracks) {
10102 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurent94579172020-11-20 18:41:04 +010010103 record_track_metadata_v7_t trackMetadata;
10104 trackMetadata.base = {
Kevin Rocard069c2712018-03-29 19:09:14 -070010105 .source = track->attributes().source,
10106 .gain = 1, // capture tracks do not have volumes
Eric Laurent94579172020-11-20 18:41:04 +010010107 };
10108 trackMetadata.channel_mask = track->channelMask(),
10109 strncpy(trackMetadata.tags, track->attributes().tags, AUDIO_ATTRIBUTES_TAGS_MAX_SIZE);
10110 metadata.tracks.push_back(trackMetadata);
Kevin Rocard069c2712018-03-29 19:09:14 -070010111 }
10112 mInput->stream->updateSinkMetadata(metadata);
10113}
10114
Eric Laurent5ada82e2019-08-29 17:53:54 -070010115void AudioFlinger::MmapCaptureThread::setRecordSilenced(audio_port_handle_t portId, bool silenced)
Eric Laurent331679c2018-04-16 17:03:16 -070010116{
10117 Mutex::Autolock _l(mLock);
10118 for (size_t i = 0; i < mActiveTracks.size() ; i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -070010119 if (mActiveTracks[i]->portId() == portId) {
Eric Laurent331679c2018-04-16 17:03:16 -070010120 mActiveTracks[i]->setSilenced_l(silenced);
10121 broadcast_l();
10122 }
10123 }
10124}
10125
Mikhail Naganov32abc2b2018-05-24 12:57:11 -070010126void AudioFlinger::MmapCaptureThread::toAudioPortConfig(struct audio_port_config *config)
10127{
10128 MmapThread::toAudioPortConfig(config);
10129 if (mInput && mInput->flags != AUDIO_INPUT_FLAG_NONE) {
10130 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
10131 config->flags.input = mInput->flags;
10132 }
10133}
10134
jiabinb7d8c5a2020-08-26 17:24:52 -070010135status_t AudioFlinger::MmapCaptureThread::getExternalPosition(
10136 uint64_t *position, int64_t *timeNanos)
10137{
10138 if (mInput == nullptr) {
10139 return NO_INIT;
10140 }
10141 return mInput->getCapturePosition((int64_t*)position, timeNanos);
10142}
10143
Glenn Kasten63238ef2015-03-02 15:50:29 -080010144} // namespace android