blob: d8786118ee4f5fcf508e43ff37f313ddabff1818 [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() {
Jasmine Chaeaa10e42021-05-11 10:11:14 +08001801 bool hasChanged = mHasChanged;
Kevin Rocard069c2712018-03-29 19:09:14 -07001802 mHasChanged = false;
Jasmine Chaeaa10e42021-05-11 10:11:14 +08001803
1804 for (const sp<T> &track : mActiveTracks) {
1805 // Do not short-circuit as all hasChanged states must be reset
1806 // as all the metadata are going to be sent
1807 hasChanged |= track->readAndClearHasChanged();
1808 }
Kevin Rocard069c2712018-03-29 19:09:14 -07001809 return hasChanged;
1810}
1811
1812template <typename T>
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001813void AudioFlinger::ThreadBase::ActiveTracks<T>::logTrack(
1814 const char *funcName, const sp<T> &track) const {
1815 if (mLocalLog != nullptr) {
1816 String8 result;
1817 track->appendDump(result, false /* active */);
1818 mLocalLog->log("AT::%-10s(%p) %s", funcName, track.get(), result.string());
1819 }
1820}
1821
Eric Laurent6acd1d42017-01-04 14:23:29 -08001822void AudioFlinger::ThreadBase::broadcast_l()
1823{
1824 // Thread could be blocked waiting for async
1825 // so signal it to handle state changes immediately
1826 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
1827 // be lost so we also flag to prevent it blocking on mWaitWorkCV
1828 mSignalPending = true;
1829 mWaitWorkCV.broadcast();
1830}
1831
Andy Hungd0979812019-02-21 15:51:44 -08001832// Call only from threadLoop() or when it is idle.
1833// Do not call from high performance code as this may do binder rpc to the MediaMetrics service.
1834void AudioFlinger::ThreadBase::sendStatistics(bool force)
1835{
1836 // Do not log if we have no stats.
1837 // We choose the timestamp verifier because it is the most likely item to be present.
1838 const int64_t nstats = mTimestampVerifier.getN() - mLastRecordedTimestampVerifierN;
1839 if (nstats == 0) {
1840 return;
1841 }
1842
1843 // Don't log more frequently than once per 12 hours.
1844 // We use BOOTTIME to include suspend time.
1845 const int64_t timeNs = systemTime(SYSTEM_TIME_BOOTTIME);
1846 const int64_t sinceNs = timeNs - mLastRecordedTimeNs; // ok if mLastRecordedTimeNs = 0
1847 if (!force && sinceNs <= 12 * NANOS_PER_HOUR) {
1848 return;
1849 }
1850
1851 mLastRecordedTimestampVerifierN = mTimestampVerifier.getN();
1852 mLastRecordedTimeNs = timeNs;
1853
Ray Essickf27e9872019-12-07 06:28:46 -08001854 std::unique_ptr<mediametrics::Item> item(mediametrics::Item::create("audiothread"));
Andy Hungd0979812019-02-21 15:51:44 -08001855
1856#define MM_PREFIX "android.media.audiothread." // avoid cut-n-paste errors.
1857
1858 // thread configuration
1859 item->setInt32(MM_PREFIX "id", (int32_t)mId); // IO handle
1860 // item->setInt32(MM_PREFIX "portId", (int32_t)mPortId);
1861 item->setCString(MM_PREFIX "type", threadTypeToString(mType));
1862 item->setInt32(MM_PREFIX "sampleRate", (int32_t)mSampleRate);
1863 item->setInt64(MM_PREFIX "channelMask", (int64_t)mChannelMask);
1864 item->setCString(MM_PREFIX "encoding", toString(mFormat).c_str());
1865 item->setInt32(MM_PREFIX "frameCount", (int32_t)mFrameCount);
jiabinc52b1ff2019-10-31 17:20:42 -07001866 item->setCString(MM_PREFIX "outDevice", toString(outDeviceTypes()).c_str());
1867 item->setCString(MM_PREFIX "inDevice", toString(inDeviceType()).c_str());
Andy Hungd0979812019-02-21 15:51:44 -08001868
1869 // thread statistics
1870 if (mIoJitterMs.getN() > 0) {
1871 item->setDouble(MM_PREFIX "ioJitterMs.mean", mIoJitterMs.getMean());
1872 item->setDouble(MM_PREFIX "ioJitterMs.std", mIoJitterMs.getStdDev());
1873 }
1874 if (mProcessTimeMs.getN() > 0) {
1875 item->setDouble(MM_PREFIX "processTimeMs.mean", mProcessTimeMs.getMean());
1876 item->setDouble(MM_PREFIX "processTimeMs.std", mProcessTimeMs.getStdDev());
1877 }
1878 const auto tsjitter = mTimestampVerifier.getJitterMs();
1879 if (tsjitter.getN() > 0) {
1880 item->setDouble(MM_PREFIX "timestampJitterMs.mean", tsjitter.getMean());
1881 item->setDouble(MM_PREFIX "timestampJitterMs.std", tsjitter.getStdDev());
1882 }
1883 if (mLatencyMs.getN() > 0) {
1884 item->setDouble(MM_PREFIX "latencyMs.mean", mLatencyMs.getMean());
1885 item->setDouble(MM_PREFIX "latencyMs.std", mLatencyMs.getStdDev());
1886 }
1887
1888 item->selfrecord();
1889}
1890
Eric Laurent81784c32012-11-19 14:55:58 -08001891// ----------------------------------------------------------------------------
1892// Playback
1893// ----------------------------------------------------------------------------
1894
1895AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1896 AudioStreamOut* output,
1897 audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -07001898 type_t type,
Eric Laurente93cc032016-05-05 10:15:10 -07001899 bool systemReady)
Andy Hungcf10d742020-04-28 15:38:24 -07001900 : ThreadBase(audioFlinger, id, type, systemReady, true /* isOut */),
Andy Hung2098f272014-02-27 14:00:06 -08001901 mNormalFrameCount(0), mSinkBuffer(NULL),
Andy Hung6146c082014-03-18 11:56:15 -07001902 mMixerBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung69aed5f2014-02-25 17:24:40 -08001903 mMixerBuffer(NULL),
1904 mMixerBufferSize(0),
1905 mMixerBufferFormat(AUDIO_FORMAT_INVALID),
1906 mMixerBufferValid(false),
Andy Hung6146c082014-03-18 11:56:15 -07001907 mEffectBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung98ef9782014-03-04 14:46:50 -08001908 mEffectBuffer(NULL),
1909 mEffectBufferSize(0),
1910 mEffectBufferFormat(AUDIO_FORMAT_INVALID),
1911 mEffectBufferValid(false),
Glenn Kastenc1fac192013-08-06 07:41:36 -07001912 mSuspended(0), mBytesWritten(0),
Andy Hungc54b1ff2016-02-23 14:07:07 -08001913 mFramesWritten(0),
Andy Hung238fa3d2016-07-28 10:53:22 -07001914 mSuspendedFrames(0),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001915 mActiveTracks(&this->mLocalLog),
Eric Laurent81784c32012-11-19 14:55:58 -08001916 // mStreamTypes[] initialized in constructor body
Andy Hung1bc088a2018-02-09 15:57:31 -08001917 mTracks(type == MIXER),
Eric Laurent81784c32012-11-19 14:55:58 -08001918 mOutput(output),
Andy Hung446f4df2019-02-21 12:26:41 -08001919 mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
Eric Laurent81784c32012-11-19 14:55:58 -08001920 mMixerStatus(MIXER_IDLE),
1921 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
Eric Laurentad9cb8b2015-05-26 16:38:19 -07001922 mStandbyDelayNs(AudioFlinger::mStandbyTimeInNsecs),
Eric Laurentbfb1b832013-01-07 09:53:42 -08001923 mBytesRemaining(0),
1924 mCurrentWriteLength(0),
1925 mUseAsyncWrite(false),
Eric Laurent3b4529e2013-09-05 18:09:19 -07001926 mWriteAckSequence(0),
1927 mDrainSequence(0),
Eric Laurent81784c32012-11-19 14:55:58 -08001928 mScreenState(AudioFlinger::mScreenState),
1929 // index 0 is reserved for normal mixer's submix
Glenn Kastendc2c50b2016-04-21 08:13:14 -07001930 mFastTrackAvailMask(((1 << FastMixerState::sMaxFastTracks) - 1) & ~1),
Eric Laurent7c29ec92017-09-20 17:54:22 -07001931 mHwSupportsPause(false), mHwPaused(false), mFlushPending(false),
Eric Laurent74c38dc2020-12-23 18:19:44 +01001932 mLeftVolFloat(-1.0), mRightVolFloat(-1.0),
1933 mDownStreamPatch{}
Eric Laurent81784c32012-11-19 14:55:58 -08001934{
Glenn Kastend7dca052015-03-05 16:05:54 -08001935 snprintf(mThreadName, kThreadNameLength, "AudioOut_%X", id);
1936 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08001937
1938 // Assumes constructor is called by AudioFlinger with it's mLock held, but
1939 // it would be safer to explicitly pass initial masterVolume/masterMute as
1940 // parameter.
1941 //
1942 // If the HAL we are using has support for master volume or master mute,
1943 // then do not attenuate or mute during mixing (just leave the volume at 1.0
1944 // and the mute set to false).
1945 mMasterVolume = audioFlinger->masterVolume_l();
1946 mMasterMute = audioFlinger->masterMute_l();
George Burgess IV5e4d86f2020-02-18 12:55:36 -08001947 if (mOutput->audioHwDev) {
Eric Laurent81784c32012-11-19 14:55:58 -08001948 if (mOutput->audioHwDev->canSetMasterVolume()) {
1949 mMasterVolume = 1.0;
1950 }
1951
1952 if (mOutput->audioHwDev->canSetMasterMute()) {
1953 mMasterMute = false;
1954 }
Andy Hungc8fddf32018-08-08 18:32:37 -07001955 mIsMsdDevice = strcmp(
1956 mOutput->audioHwDev->moduleName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0;
Eric Laurent81784c32012-11-19 14:55:58 -08001957 }
1958
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001959 readOutputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001960
Andy Hungc8fddf32018-08-08 18:32:37 -07001961 // TODO: We may also match on address as well as device type for
1962 // AUDIO_DEVICE_OUT_BUS, AUDIO_DEVICE_OUT_ALL_A2DP, AUDIO_DEVICE_OUT_REMOTE_SUBMIX
Dean Wheatleyf8726f02019-12-02 14:12:01 +11001963 if (type == MIXER || type == DIRECT || type == OFFLOAD) {
jiabinc52b1ff2019-10-31 17:20:42 -07001964 // TODO: This property should be ensure that only contains one single device type.
1965 mTimestampCorrectedDevice = (audio_devices_t)property_get_int64(
1966 "audio.timestamp.corrected_output_device",
Andy Hungc8fddf32018-08-08 18:32:37 -07001967 (int64_t)(mIsMsdDevice ? AUDIO_DEVICE_OUT_BUS // turn on by default for MSD
1968 : AUDIO_DEVICE_NONE));
1969 }
1970
Mikhail Naganovf33115d2020-09-25 23:03:05 +00001971 for (int i = AUDIO_STREAM_MIN; i < AUDIO_STREAM_FOR_POLICY_CNT; ++i) {
1972 const audio_stream_type_t stream{static_cast<audio_stream_type_t>(i)};
Eric Laurent98e38192018-02-15 18:31:53 -08001973 mStreamTypes[stream].volume = 0.0f;
Eric Laurent81784c32012-11-19 14:55:58 -08001974 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
1975 }
Eric Laurent35f8c7c2020-02-08 11:42:35 -08001976 // Audio patch and call assistant volume are always max
Eric Laurent98e38192018-02-15 18:31:53 -08001977 mStreamTypes[AUDIO_STREAM_PATCH].volume = 1.0f;
1978 mStreamTypes[AUDIO_STREAM_PATCH].mute = false;
Eric Laurent35f8c7c2020-02-08 11:42:35 -08001979 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].volume = 1.0f;
1980 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].mute = false;
Eric Laurent81784c32012-11-19 14:55:58 -08001981}
1982
1983AudioFlinger::PlaybackThread::~PlaybackThread()
1984{
Glenn Kasten9e58b552013-01-18 15:09:48 -08001985 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung010a1a12014-03-13 13:57:33 -07001986 free(mSinkBuffer);
Andy Hung69aed5f2014-02-25 17:24:40 -08001987 free(mMixerBuffer);
Andy Hung98ef9782014-03-04 14:46:50 -08001988 free(mEffectBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08001989}
1990
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001991// Thread virtuals
1992
1993void AudioFlinger::PlaybackThread::onFirstRef()
Eric Laurent81784c32012-11-19 14:55:58 -08001994{
Jasmine Chaeaa10e42021-05-11 10:11:14 +08001995 if (!isStreamInitialized()) {
jiabinf6eb4c32020-02-25 14:06:25 -08001996 ALOGE("The stream is not open yet"); // This should not happen.
1997 } else {
1998 // setEventCallback will need a strong pointer as a parameter. Calling it
1999 // here instead of constructor of PlaybackThread so that the onFirstRef
2000 // callback would not be made on an incompletely constructed object.
2001 if (mOutput->stream->setEventCallback(this) != OK) {
jiabinf1a36052020-08-19 14:33:31 -07002002 ALOGD("Failed to add event callback");
jiabinf6eb4c32020-02-25 14:06:25 -08002003 }
2004 }
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002005 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08002006}
2007
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002008// ThreadBase virtuals
2009void AudioFlinger::PlaybackThread::preExit()
2010{
2011 ALOGV(" preExit()");
2012 // FIXME this is using hard-coded strings but in the future, this functionality will be
2013 // converted to use audio HAL extensions required to support tunneling
2014 status_t result = mOutput->stream->setParameters(String8("exiting=1"));
2015 ALOGE_IF(result != OK, "Error when setting parameters on exit: %d", result);
2016}
2017
2018void AudioFlinger::PlaybackThread::dumpTracks_l(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08002019{
Eric Laurent81784c32012-11-19 14:55:58 -08002020 String8 result;
2021
Marco Nelissenb2208842014-02-07 14:00:50 -08002022 result.appendFormat(" Stream volumes in dB: ");
Eric Laurent81784c32012-11-19 14:55:58 -08002023 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
2024 const stream_type_t *st = &mStreamTypes[i];
2025 if (i > 0) {
2026 result.appendFormat(", ");
2027 }
2028 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
2029 if (st->mute) {
2030 result.append("M");
2031 }
2032 }
2033 result.append("\n");
2034 write(fd, result.string(), result.length());
2035 result.clear();
2036
Eric Laurent81784c32012-11-19 14:55:58 -08002037 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
2038 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
Elliott Hughes87cebad2014-05-22 10:14:43 -07002039 dprintf(fd, " Normal mixer raw underrun counters: partial=%u empty=%u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08002040 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Marco Nelissenb2208842014-02-07 14:00:50 -08002041
2042 size_t numtracks = mTracks.size();
2043 size_t numactive = mActiveTracks.size();
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002044 dprintf(fd, " %zu Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08002045 size_t numactiveseen = 0;
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002046 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08002047 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002048 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002049 result.append(prefix);
Andy Hungf6ab58d2018-05-25 12:50:39 -07002050 mTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08002051 for (size_t i = 0; i < numtracks; ++i) {
2052 sp<Track> track = mTracks[i];
2053 if (track != 0) {
2054 bool active = mActiveTracks.indexOf(track) >= 0;
2055 if (active) {
2056 numactiveseen++;
2057 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002058 result.append(prefix);
2059 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08002060 }
2061 }
2062 } else {
2063 result.append("\n");
2064 }
2065 if (numactiveseen != numactive) {
2066 // some tracks in the active list were not in the tracks list
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002067 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08002068 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002069 result.append(prefix);
Andy Hungf6ab58d2018-05-25 12:50:39 -07002070 mActiveTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08002071 for (size_t i = 0; i < numactive; ++i) {
Andy Hungdae27702016-10-31 14:01:16 -07002072 sp<Track> track = mActiveTracks[i];
2073 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002074 result.append(prefix);
2075 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08002076 }
2077 }
2078 }
2079
2080 write(fd, result.string(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08002081}
2082
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002083void AudioFlinger::PlaybackThread::dumpInternals_l(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08002084{
Andy Hung04cb8f72020-03-20 13:44:33 -07002085 dprintf(fd, " Master volume: %f\n", mMasterVolume);
Mikhail Naganovdfb411f2018-09-11 13:39:56 -07002086 dprintf(fd, " Master mute: %s\n", mMasterMute ? "on" : "off");
jiabin245cdd92018-12-07 17:55:15 -08002087 if (mHapticChannelMask != AUDIO_CHANNEL_NONE) {
2088 dprintf(fd, " Haptic channel mask: %#x (%s)\n", mHapticChannelMask,
2089 channelMaskToString(mHapticChannelMask, true /* output */).c_str());
2090 }
Elliott Hughes87cebad2014-05-22 10:14:43 -07002091 dprintf(fd, " Normal frame count: %zu\n", mNormalFrameCount);
Elliott Hughes87cebad2014-05-22 10:14:43 -07002092 dprintf(fd, " Total writes: %d\n", mNumWrites);
2093 dprintf(fd, " Delayed writes: %d\n", mNumDelayedWrites);
2094 dprintf(fd, " Blocked in write: %s\n", mInWrite ? "yes" : "no");
2095 dprintf(fd, " Suspend count: %d\n", mSuspended);
2096 dprintf(fd, " Sink buffer : %p\n", mSinkBuffer);
2097 dprintf(fd, " Mixer buffer: %p\n", mMixerBuffer);
2098 dprintf(fd, " Effect buffer: %p\n", mEffectBuffer);
2099 dprintf(fd, " Fast track availMask=%#x\n", mFastTrackAvailMask);
Eric Laurent42537be2016-01-08 17:16:42 -08002100 dprintf(fd, " Standby delay ns=%lld\n", (long long)mStandbyDelayNs);
Glenn Kasten97b7b752014-09-28 13:04:24 -07002101 AudioStreamOut *output = mOutput;
2102 audio_output_flags_t flags = output != NULL ? output->flags : AUDIO_OUTPUT_FLAG_NONE;
Mikhail Naganov913d06c2016-11-01 12:49:22 -07002103 dprintf(fd, " AudioStreamOut: %p flags %#x (%s)\n",
Andy Hung9b181952019-02-25 14:53:36 -08002104 output, flags, toString(flags).c_str());
Andy Hungb54c8542016-09-21 12:55:15 -07002105 dprintf(fd, " Frames written: %lld\n", (long long)mFramesWritten);
2106 dprintf(fd, " Suspended frames: %lld\n", (long long)mSuspendedFrames);
2107 if (mPipeSink.get() != nullptr) {
2108 dprintf(fd, " PipeSink frames written: %lld\n", (long long)mPipeSink->framesWritten());
2109 }
2110 if (output != nullptr) {
2111 dprintf(fd, " Hal stream dump:\n");
2112 (void)output->stream->dump(fd);
2113 }
Eric Laurent81784c32012-11-19 14:55:58 -08002114}
2115
Eric Laurent81784c32012-11-19 14:55:58 -08002116// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
2117sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
2118 const sp<AudioFlinger::Client>& client,
2119 audio_stream_type_t streamType,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07002120 const audio_attributes_t& attr,
Eric Laurent21da6472017-11-09 16:29:26 -08002121 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08002122 audio_format_t format,
2123 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08002124 size_t *pFrameCount,
Eric Laurent21da6472017-11-09 16:29:26 -08002125 size_t *pNotificationFrameCount,
2126 uint32_t notificationsPerBuffer,
2127 float speed,
Eric Laurent81784c32012-11-19 14:55:58 -08002128 const sp<IMemory>& sharedBuffer,
Glenn Kastend848eb42016-03-08 13:42:11 -08002129 audio_session_t sessionId,
Eric Laurent05067782016-06-01 18:27:28 -07002130 audio_output_flags_t *flags,
Eric Laurent09f1ed22019-04-24 17:45:17 -07002131 pid_t creatorPid,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07002132 const Identity& identity,
Eric Laurent81784c32012-11-19 14:55:58 -08002133 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002134 status_t *status,
jiabinf6eb4c32020-02-25 14:06:25 -08002135 audio_port_handle_t portId,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07002136 const sp<media::IAudioTrackCallback>& callback)
Eric Laurent81784c32012-11-19 14:55:58 -08002137{
Glenn Kasten74935e42013-12-19 08:56:45 -08002138 size_t frameCount = *pFrameCount;
Eric Laurent21da6472017-11-09 16:29:26 -08002139 size_t notificationFrameCount = *pNotificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08002140 sp<Track> track;
2141 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07002142 audio_output_flags_t outputFlags = mOutput->flags;
Eric Laurent21da6472017-11-09 16:29:26 -08002143 audio_output_flags_t requestedFlags = *flags;
Eric Laurent9b11c022018-06-06 19:19:22 -07002144 uint32_t sampleRate;
2145
2146 if (sharedBuffer != 0 && checkIMemory(sharedBuffer) != NO_ERROR) {
2147 lStatus = BAD_VALUE;
2148 goto Exit;
2149 }
Eric Laurent21da6472017-11-09 16:29:26 -08002150
2151 if (*pSampleRate == 0) {
2152 *pSampleRate = mSampleRate;
2153 }
Eric Laurent9b11c022018-06-06 19:19:22 -07002154 sampleRate = *pSampleRate;
Eric Laurent05067782016-06-01 18:27:28 -07002155
2156 // special case for FAST flag considered OK if fast mixer is present
2157 if (hasFastMixer()) {
2158 outputFlags = (audio_output_flags_t)(outputFlags | AUDIO_OUTPUT_FLAG_FAST);
2159 }
2160
2161 // Check if requested flags are compatible with output stream flags
2162 if ((*flags & outputFlags) != *flags) {
2163 ALOGW("createTrack_l(): mismatch between requested flags (%08x) and output flags (%08x)",
2164 *flags, outputFlags);
2165 *flags = (audio_output_flags_t)(*flags & outputFlags);
2166 }
Eric Laurent81784c32012-11-19 14:55:58 -08002167
Eric Laurent81784c32012-11-19 14:55:58 -08002168 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07002169 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
Eric Laurent81784c32012-11-19 14:55:58 -08002170 if (
Eric Laurent81784c32012-11-19 14:55:58 -08002171 // PCM data
2172 audio_is_linear_pcm(format) &&
Andy Hung1f439e12015-05-19 12:57:41 -07002173 // TODO: extract as a data library function that checks that a computationally
2174 // expensive downmixer is not required: isFastOutputChannelConversion()
jiabin245cdd92018-12-07 17:55:15 -08002175 (channelMask == (mChannelMask | mHapticChannelMask) ||
Andy Hung1f439e12015-05-19 12:57:41 -07002176 mChannelMask != AUDIO_CHANNEL_OUT_STEREO ||
2177 (channelMask == AUDIO_CHANNEL_OUT_MONO
2178 /* && mChannelMask == AUDIO_CHANNEL_OUT_STEREO */)) &&
Eric Laurent81784c32012-11-19 14:55:58 -08002179 // hardware sample rate
2180 (sampleRate == mSampleRate) &&
Eric Laurent81784c32012-11-19 14:55:58 -08002181 // normal mixer has an associated fast mixer
2182 hasFastMixer() &&
2183 // there are sufficient fast track slots available
2184 (mFastTrackAvailMask != 0)
2185 // FIXME test that MixerThread for this fast track has a capable output HAL
2186 // FIXME add a permission test also?
2187 ) {
Andy Hunge0a269a2016-03-23 15:13:42 -07002188 // static tracks can have any nonzero framecount, streaming tracks check against minimum.
2189 if (sharedBuffer == 0) {
Glenn Kasten03490092014-05-27 12:30:54 -07002190 // read the fast track multiplier property the first time it is needed
2191 int ok = pthread_once(&sFastTrackMultiplierOnce, sFastTrackMultiplierInit);
2192 if (ok != 0) {
2193 ALOGE("%s pthread_once failed: %d", __func__, ok);
2194 }
Andy Hunge0a269a2016-03-23 15:13:42 -07002195 frameCount = max(frameCount, mFrameCount * sFastTrackMultiplier); // incl framecount 0
Eric Laurent81784c32012-11-19 14:55:58 -08002196 }
Eric Laurent4c415062016-06-17 16:14:16 -07002197
2198 // check compatibility with audio effects.
2199 { // scope for mLock
2200 Mutex::Autolock _l(mLock);
Andy Hungd3bb0ad2016-10-11 17:16:43 -07002201 for (audio_session_t session : {
Eric Laurent3f75a5b2019-11-12 15:55:51 -08002202 AUDIO_SESSION_DEVICE,
Andy Hungd3bb0ad2016-10-11 17:16:43 -07002203 AUDIO_SESSION_OUTPUT_STAGE,
2204 AUDIO_SESSION_OUTPUT_MIX,
2205 sessionId,
2206 }) {
2207 sp<EffectChain> chain = getEffectChain_l(session);
2208 if (chain.get() != nullptr) {
2209 audio_output_flags_t old = *flags;
2210 chain->checkOutputFlagCompatibility(flags);
2211 if (old != *flags) {
2212 ALOGV("AUDIO_OUTPUT_FLAGS denied by effect, session=%d old=%#x new=%#x",
2213 (int)session, (int)old, (int)*flags);
2214 }
Eric Laurent4c415062016-06-17 16:14:16 -07002215 }
2216 }
2217 }
Eric Laurent122f7e72016-06-29 11:53:29 -07002218 ALOGV_IF((*flags & AUDIO_OUTPUT_FLAG_FAST) != 0,
Eric Laurent4c415062016-06-17 16:14:16 -07002219 "AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
2220 frameCount, mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08002221 } else {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002222 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: sharedBuffer=%p frameCount=%zu "
2223 "mFrameCount=%zu format=%#x mFormat=%#x isLinear=%d channelMask=%#x "
Andy Hung6146c082014-03-18 11:56:15 -07002224 "sampleRate=%u mSampleRate=%u "
Eric Laurent81784c32012-11-19 14:55:58 -08002225 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
Glenn Kastend79072e2016-01-06 08:41:20 -08002226 sharedBuffer.get(), frameCount, mFrameCount, format, mFormat,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07002227 audio_is_linear_pcm(format), channelMask, sampleRate,
2228 mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
Eric Laurent4c415062016-06-17 16:14:16 -07002229 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_FAST);
Andy Hung0e48d252015-01-26 11:43:15 -08002230 }
2231 }
Eric Laurent21da6472017-11-09 16:29:26 -08002232
2233 if (!audio_has_proportional_frames(format)) {
2234 if (sharedBuffer != 0) {
2235 // Same comment as below about ignoring frameCount parameter for set()
2236 frameCount = sharedBuffer->size();
2237 } else if (frameCount == 0) {
2238 frameCount = mNormalFrameCount;
2239 }
2240 if (notificationFrameCount != frameCount) {
2241 notificationFrameCount = frameCount;
2242 }
2243 } else if (sharedBuffer != 0) {
2244 // FIXME: Ensure client side memory buffers need
2245 // not have additional alignment beyond sample
2246 // (e.g. 16 bit stereo accessed as 32 bit frame).
2247 size_t alignment = audio_bytes_per_sample(format);
2248 if (alignment & 1) {
2249 // for AUDIO_FORMAT_PCM_24_BIT_PACKED (not exposed through Java).
2250 alignment = 1;
2251 }
2252 uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
2253 size_t frameSize = channelCount * audio_bytes_per_sample(format);
2254 if (channelCount > 1) {
2255 // More than 2 channels does not require stronger alignment than stereo
2256 alignment <<= 1;
2257 }
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07002258 if (((uintptr_t)sharedBuffer->unsecurePointer() & (alignment - 1)) != 0) {
Eric Laurent21da6472017-11-09 16:29:26 -08002259 ALOGE("Invalid buffer alignment: address %p, channel count %u",
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07002260 sharedBuffer->unsecurePointer(), channelCount);
Eric Laurent21da6472017-11-09 16:29:26 -08002261 lStatus = BAD_VALUE;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002262 goto Exit;
2263 }
Eric Laurent21da6472017-11-09 16:29:26 -08002264
2265 // When initializing a shared buffer AudioTrack via constructors,
2266 // there's no frameCount parameter.
2267 // But when initializing a shared buffer AudioTrack via set(),
2268 // there _is_ a frameCount parameter. We silently ignore it.
2269 frameCount = sharedBuffer->size() / frameSize;
2270 } else {
2271 size_t minFrameCount = 0;
2272 // For fast tracks we try to respect the application's request for notifications per buffer.
2273 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
2274 if (notificationsPerBuffer > 0) {
2275 // Avoid possible arithmetic overflow during multiplication.
2276 if (notificationsPerBuffer > SIZE_MAX / mFrameCount) {
2277 ALOGE("Requested notificationPerBuffer=%u ignored for HAL frameCount=%zu",
2278 notificationsPerBuffer, mFrameCount);
2279 } else {
2280 minFrameCount = mFrameCount * notificationsPerBuffer;
2281 }
2282 }
2283 } else {
2284 // For normal PCM streaming tracks, update minimum frame count.
2285 // Buffer depth is forced to be at least 2 x the normal mixer frame count and
2286 // cover audio hardware latency.
2287 // This is probably too conservative, but legacy application code may depend on it.
2288 // If you change this calculation, also review the start threshold which is related.
2289 uint32_t latencyMs = latency_l();
2290 if (latencyMs == 0) {
2291 ALOGE("Error when retrieving output stream latency");
2292 lStatus = UNKNOWN_ERROR;
2293 goto Exit;
2294 }
2295
2296 minFrameCount = AudioSystem::calculateMinFrameCount(latencyMs, mNormalFrameCount,
2297 mSampleRate, sampleRate, speed /*, 0 mNotificationsPerBufferReq*/);
2298
Eric Laurent81784c32012-11-19 14:55:58 -08002299 }
Eric Laurent21da6472017-11-09 16:29:26 -08002300 if (frameCount < minFrameCount) {
Eric Laurent81784c32012-11-19 14:55:58 -08002301 frameCount = minFrameCount;
2302 }
Eric Laurent81784c32012-11-19 14:55:58 -08002303 }
Eric Laurent21da6472017-11-09 16:29:26 -08002304
2305 // Make sure that application is notified with sufficient margin before underrun.
2306 // The client can divide the AudioTrack buffer into sub-buffers,
2307 // and expresses its desire to server as the notification frame count.
2308 if (sharedBuffer == 0 && audio_is_linear_pcm(format)) {
2309 size_t maxNotificationFrames;
2310 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
2311 // notify every HAL buffer, regardless of the size of the track buffer
2312 maxNotificationFrames = mFrameCount;
2313 } else {
Andy Hungfa117802019-04-12 13:50:39 -07002314 // Triple buffer the notification period for a triple buffered mixer period;
2315 // otherwise, double buffering for the notification period is fine.
2316 //
2317 // TODO: This should be moved to AudioTrack to modify the notification period
2318 // on AudioTrack::setBufferSizeInFrames() changes.
2319 const int nBuffering =
2320 (uint64_t{frameCount} * mSampleRate)
2321 / (uint64_t{mNormalFrameCount} * sampleRate) == 3 ? 3 : 2;
2322
Eric Laurent21da6472017-11-09 16:29:26 -08002323 maxNotificationFrames = frameCount / nBuffering;
2324 // If client requested a fast track but this was denied, then use the smaller maximum.
2325 if (requestedFlags & AUDIO_OUTPUT_FLAG_FAST) {
2326 size_t maxNotificationFramesFastDenied = FMS_20 * sampleRate / 1000;
2327 if (maxNotificationFrames > maxNotificationFramesFastDenied) {
2328 maxNotificationFrames = maxNotificationFramesFastDenied;
2329 }
2330 }
2331 }
2332 if (notificationFrameCount == 0 || notificationFrameCount > maxNotificationFrames) {
2333 if (notificationFrameCount == 0) {
2334 ALOGD("Client defaulted notificationFrames to %zu for frameCount %zu",
2335 maxNotificationFrames, frameCount);
2336 } else {
2337 ALOGW("Client adjusted notificationFrames from %zu to %zu for frameCount %zu",
2338 notificationFrameCount, maxNotificationFrames, frameCount);
2339 }
2340 notificationFrameCount = maxNotificationFrames;
2341 }
2342 }
2343
Glenn Kasten74935e42013-12-19 08:56:45 -08002344 *pFrameCount = frameCount;
Eric Laurent21da6472017-11-09 16:29:26 -08002345 *pNotificationFrameCount = notificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08002346
Glenn Kastenc3df8382014-03-13 15:05:25 -07002347 switch (mType) {
2348
2349 case DIRECT:
Phil Burkfdb3c072016-02-09 10:47:02 -08002350 if (audio_is_linear_pcm(format)) { // TODO maybe use audio_has_proportional_frames()?
Eric Laurent81784c32012-11-19 14:55:58 -08002351 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002352 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
2353 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08002354 sampleRate, format, channelMask, mOutput, mFormat);
2355 lStatus = BAD_VALUE;
2356 goto Exit;
2357 }
2358 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002359 break;
2360
2361 case OFFLOAD:
Eric Laurentbfb1b832013-01-07 09:53:42 -08002362 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002363 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
2364 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002365 sampleRate, format, channelMask, mOutput, mFormat);
2366 lStatus = BAD_VALUE;
2367 goto Exit;
2368 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002369 break;
2370
2371 default:
Glenn Kasten993fa062014-05-02 11:14:34 -07002372 if (!audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002373 ALOGE("createTrack_l() Bad parameter: format %#x \""
2374 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002375 format, mOutput, mFormat);
2376 lStatus = BAD_VALUE;
2377 goto Exit;
2378 }
Andy Hungcd044842014-08-07 11:04:34 -07002379 if (sampleRate > mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Eric Laurent81784c32012-11-19 14:55:58 -08002380 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
2381 lStatus = BAD_VALUE;
2382 goto Exit;
2383 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002384 break;
2385
Eric Laurent81784c32012-11-19 14:55:58 -08002386 }
2387
2388 lStatus = initCheck();
2389 if (lStatus != NO_ERROR) {
Glenn Kasten15e57982013-09-24 11:52:37 -07002390 ALOGE("createTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08002391 goto Exit;
2392 }
2393
2394 { // scope for mLock
2395 Mutex::Autolock _l(mLock);
2396
2397 // all tracks in same audio session must share the same routing strategy otherwise
2398 // conflicts will happen when tracks are moved from one output to another by audio policy
2399 // manager
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08002400 product_strategy_t strategy = AudioSystem::getStrategyForStream(streamType);
Eric Laurent81784c32012-11-19 14:55:58 -08002401 for (size_t i = 0; i < mTracks.size(); ++i) {
2402 sp<Track> t = mTracks[i];
Eric Laurent83b88082014-06-20 18:31:16 -07002403 if (t != 0 && t->isExternalTrack()) {
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08002404 product_strategy_t actual = AudioSystem::getStrategyForStream(t->streamType());
Eric Laurent81784c32012-11-19 14:55:58 -08002405 if (sessionId == t->sessionId() && strategy != actual) {
2406 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
2407 strategy, actual);
2408 lStatus = BAD_VALUE;
2409 goto Exit;
2410 }
2411 }
2412 }
2413
yucliuc9c49cd2020-07-13 16:25:21 -07002414 // Set DIRECT flag if current thread is DirectOutputThread. This can
2415 // happen when the playback is rerouted to direct output thread by
2416 // dynamic audio policy.
2417 // Do NOT report the flag changes back to client, since the client
2418 // doesn't explicitly request a direct flag.
2419 audio_output_flags_t trackFlags = *flags;
2420 if (mType == DIRECT) {
2421 trackFlags = static_cast<audio_output_flags_t>(trackFlags | AUDIO_OUTPUT_FLAG_DIRECT);
2422 }
2423
Kevin Rocard1f564ac2018-03-29 13:53:10 -07002424 track = new Track(this, client, streamType, attr, sampleRate, format,
Andy Hung8fe68032017-06-05 16:17:51 -07002425 channelMask, frameCount,
2426 nullptr /* buffer */, (size_t)0 /* bufferSize */, sharedBuffer,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07002427 sessionId, creatorPid, identity, trackFlags, TrackBase::TYPE_DEFAULT,
2428 portId, SIZE_MAX /*frameCountToBeReady*/);
Glenn Kasten03003332013-08-06 15:40:54 -07002429
Glenn Kasten03003332013-08-06 15:40:54 -07002430 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
2431 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08002432 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08002433 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08002434 goto Exit;
2435 }
2436 mTracks.add(track);
jiabinf6eb4c32020-02-25 14:06:25 -08002437 {
2438 Mutex::Autolock _atCbL(mAudioTrackCbLock);
2439 if (callback.get() != nullptr) {
jiabin18a4b1c2020-09-17 11:40:42 -07002440 mAudioTrackCallbacks.emplace(track, callback);
jiabinf6eb4c32020-02-25 14:06:25 -08002441 }
2442 }
Eric Laurent81784c32012-11-19 14:55:58 -08002443
2444 sp<EffectChain> chain = getEffectChain_l(sessionId);
2445 if (chain != 0) {
2446 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
2447 track->setMainBuffer(chain->inBuffer());
2448 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
2449 chain->incTrackCnt();
2450 }
2451
Eric Laurent05067782016-06-01 18:27:28 -07002452 if ((*flags & AUDIO_OUTPUT_FLAG_FAST) && (tid != -1)) {
Eric Laurent81784c32012-11-19 14:55:58 -08002453 pid_t callingPid = IPCThreadState::self()->getCallingPid();
2454 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
2455 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07002456 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08002457 }
2458 }
2459
2460 lStatus = NO_ERROR;
2461
2462Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07002463 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08002464 return track;
2465}
2466
Andy Hung1bc088a2018-02-09 15:57:31 -08002467template<typename T>
Andy Hung1bc088a2018-02-09 15:57:31 -08002468ssize_t AudioFlinger::PlaybackThread::Tracks<T>::remove(const sp<T> &track)
2469{
Andy Hungc0691382018-09-12 18:01:57 -07002470 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08002471 const ssize_t index = mTracks.remove(track);
2472 if (index >= 0) {
Andy Hungc0691382018-09-12 18:01:57 -07002473 if (mSaveDeletedTrackIds) {
Andy Hung1bc088a2018-02-09 15:57:31 -08002474 // We can't directly access mAudioMixer since the caller may be outside of threadLoop.
Andy Hungc0691382018-09-12 18:01:57 -07002475 // Instead, we add to mDeletedTrackIds which is solely used for mAudioMixer update,
Andy Hung1bc088a2018-02-09 15:57:31 -08002476 // to be handled when MixerThread::prepareTracks_l() next changes mAudioMixer.
Andy Hungc0691382018-09-12 18:01:57 -07002477 mDeletedTrackIds.emplace(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08002478 }
Andy Hung1bc088a2018-02-09 15:57:31 -08002479 }
2480 return index;
2481}
2482
Eric Laurent81784c32012-11-19 14:55:58 -08002483uint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const
2484{
2485 return latency;
2486}
2487
2488uint32_t AudioFlinger::PlaybackThread::latency() const
2489{
2490 Mutex::Autolock _l(mLock);
2491 return latency_l();
2492}
2493uint32_t AudioFlinger::PlaybackThread::latency_l() const
2494{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002495 uint32_t latency;
2496 if (initCheck() == NO_ERROR && mOutput->stream->getLatency(&latency) == OK) {
2497 return correctLatency_l(latency);
Eric Laurent81784c32012-11-19 14:55:58 -08002498 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002499 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002500}
2501
2502void AudioFlinger::PlaybackThread::setMasterVolume(float value)
2503{
2504 Mutex::Autolock _l(mLock);
2505 // Don't apply master volume in SW if our HAL can do it for us.
2506 if (mOutput && mOutput->audioHwDev &&
2507 mOutput->audioHwDev->canSetMasterVolume()) {
2508 mMasterVolume = 1.0;
2509 } else {
2510 mMasterVolume = value;
2511 }
2512}
2513
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01002514void AudioFlinger::PlaybackThread::setMasterBalance(float balance)
2515{
2516 mMasterBalance.store(balance);
2517}
2518
Eric Laurent81784c32012-11-19 14:55:58 -08002519void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
2520{
Eric Laurent6acd1d42017-01-04 14:23:29 -08002521 if (isDuplicating()) {
2522 return;
2523 }
Eric Laurent81784c32012-11-19 14:55:58 -08002524 Mutex::Autolock _l(mLock);
2525 // Don't apply master mute in SW if our HAL can do it for us.
2526 if (mOutput && mOutput->audioHwDev &&
2527 mOutput->audioHwDev->canSetMasterMute()) {
2528 mMasterMute = false;
2529 } else {
2530 mMasterMute = muted;
2531 }
2532}
2533
2534void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
2535{
2536 Mutex::Autolock _l(mLock);
2537 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002538 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002539}
2540
2541void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
2542{
2543 Mutex::Autolock _l(mLock);
2544 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002545 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002546}
2547
2548float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
2549{
2550 Mutex::Autolock _l(mLock);
2551 return mStreamTypes[stream].volume;
2552}
2553
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09002554void AudioFlinger::PlaybackThread::setVolumeForOutput_l(float left, float right) const
2555{
2556 mOutput->stream->setVolume(left, right);
2557}
2558
Eric Laurent81784c32012-11-19 14:55:58 -08002559// addTrack_l() must be called with ThreadBase::mLock held
2560status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
2561{
2562 status_t status = ALREADY_EXISTS;
2563
Eric Laurent81784c32012-11-19 14:55:58 -08002564 if (mActiveTracks.indexOf(track) < 0) {
2565 // the track is newly added, make sure it fills up all its
2566 // buffers before playing. This is to ensure the client will
2567 // effectively get the latency it requested.
Eric Laurent83b88082014-06-20 18:31:16 -07002568 if (track->isExternalTrack()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002569 TrackBase::track_state state = track->mState;
2570 mLock.unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002571 status = AudioSystem::startOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002572 mLock.lock();
2573 // abort track was stopped/paused while we released the lock
2574 if (state != track->mState) {
2575 if (status == NO_ERROR) {
2576 mLock.unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002577 AudioSystem::stopOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002578 mLock.lock();
2579 }
2580 return INVALID_OPERATION;
2581 }
2582 // abort if start is rejected by audio policy manager
2583 if (status != NO_ERROR) {
2584 return PERMISSION_DENIED;
2585 }
2586#ifdef ADD_BATTERY_DATA
2587 // to track the speaker usage
2588 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
2589#endif
Eric Laurent09f1ed22019-04-24 17:45:17 -07002590 sendIoConfigEvent_l(AUDIO_CLIENT_STARTED, track->creatorPid(), track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002591 }
2592
Eric Laurent51716182016-02-29 18:00:56 -08002593 // set retry count for buffer fill
2594 if (track->isOffloaded()) {
Eric Laurente93cc032016-05-05 10:15:10 -07002595 if (track->isStopping_1()) {
2596 track->mRetryCount = kMaxTrackStopRetriesOffload;
2597 } else {
2598 track->mRetryCount = kMaxTrackStartupRetriesOffload;
2599 }
2600 track->mFillingUpStatus = mStandby ? Track::FS_FILLING : Track::FS_FILLED;
Eric Laurent51716182016-02-29 18:00:56 -08002601 } else {
2602 track->mRetryCount = kMaxTrackStartupRetries;
Eric Laurente93cc032016-05-05 10:15:10 -07002603 track->mFillingUpStatus =
2604 track->sharedBuffer() != 0 ? Track::FS_FILLED : Track::FS_FILLING;
Eric Laurent51716182016-02-29 18:00:56 -08002605 }
2606
jiabineb3bda02020-06-30 14:07:03 -07002607 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2608 if (mHapticChannelMask != AUDIO_CHANNEL_NONE
2609 && ((track->channelMask() & AUDIO_CHANNEL_HAPTIC_ALL) != AUDIO_CHANNEL_NONE
2610 || (chain != nullptr && chain->containsHapticGeneratingEffect_l()))) {
jiabin57303cc2018-12-18 15:45:57 -08002611 // Unlock due to VibratorService will lock for this call and will
2612 // call Tracks.mute/unmute which also require thread's lock.
2613 mLock.unlock();
2614 const int intensity = AudioFlinger::onExternalVibrationStart(
2615 track->getExternalVibration());
2616 mLock.lock();
jiabine70bc7f2020-06-30 22:07:55 -07002617 track->setHapticIntensity(static_cast<os::HapticScale>(intensity));
jiabin57303cc2018-12-18 15:45:57 -08002618 // Haptic playback should be enabled by vibrator service.
2619 if (track->getHapticPlaybackEnabled()) {
2620 // Disable haptic playback of all active track to ensure only
2621 // one track playing haptic if current track should play haptic.
2622 for (const auto &t : mActiveTracks) {
2623 t->setHapticPlaybackEnabled(false);
2624 }
jiabin245cdd92018-12-07 17:55:15 -08002625 }
jiabine70bc7f2020-06-30 22:07:55 -07002626
2627 // Set haptic intensity for effect
2628 if (chain != nullptr) {
2629 chain->setHapticIntensity_l(track->id(), intensity);
2630 }
jiabin245cdd92018-12-07 17:55:15 -08002631 }
2632
Eric Laurent81784c32012-11-19 14:55:58 -08002633 track->mResetDone = false;
2634 track->mPresentationCompleteFrames = 0;
2635 mActiveTracks.add(track);
Eric Laurentd0107bc2013-06-11 14:38:48 -07002636 if (chain != 0) {
2637 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
2638 track->sessionId());
2639 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08002640 }
2641
Andy Hungc2b11cb2020-04-22 09:04:01 -07002642 track->logBeginInterval(patchSinksToString(&mPatch)); // log to MediaMetrics
Eric Laurent81784c32012-11-19 14:55:58 -08002643 status = NO_ERROR;
2644 }
2645
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08002646 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002647 return status;
2648}
2649
Eric Laurentbfb1b832013-01-07 09:53:42 -08002650bool AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002651{
Eric Laurentbfb1b832013-01-07 09:53:42 -08002652 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08002653 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002654 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
2655 track->mState = TrackBase::STOPPED;
2656 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08002657 removeTrack_l(track);
Eric Laurentab5cdba2014-06-09 17:22:27 -07002658 } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002659 track->mState = TrackBase::STOPPING_1;
Eric Laurent81784c32012-11-19 14:55:58 -08002660 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002661
2662 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08002663}
2664
2665void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
2666{
2667 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Andy Hung2148bf02016-11-28 19:01:02 -08002668
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002669 String8 result;
2670 track->appendDump(result, false /* active */);
2671 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.string());
Andy Hung2148bf02016-11-28 19:01:02 -08002672
Eric Laurent81784c32012-11-19 14:55:58 -08002673 mTracks.remove(track);
jiabin18a4b1c2020-09-17 11:40:42 -07002674 {
2675 Mutex::Autolock _atCbL(mAudioTrackCbLock);
2676 mAudioTrackCallbacks.erase(track);
2677 }
Eric Laurent81784c32012-11-19 14:55:58 -08002678 if (track->isFastTrack()) {
2679 int index = track->mFastIndex;
Glenn Kastendc2c50b2016-04-21 08:13:14 -07002680 ALOG_ASSERT(0 < index && index < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08002681 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
2682 mFastTrackAvailMask |= 1 << index;
2683 // redundant as track is about to be destroyed, for dumpsys only
2684 track->mFastIndex = -1;
2685 }
2686 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2687 if (chain != 0) {
2688 chain->decTrackCnt();
2689 }
2690}
2691
2692String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
2693{
Eric Laurent81784c32012-11-19 14:55:58 -08002694 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002695 String8 out_s8;
2696 if (initCheck() == NO_ERROR && mOutput->stream->getParameters(keys, &out_s8) == OK) {
2697 return out_s8;
Eric Laurent81784c32012-11-19 14:55:58 -08002698 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002699 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08002700}
2701
Mikhail Naganovac917ac2018-11-28 14:03:52 -08002702status_t AudioFlinger::DirectOutputThread::selectPresentation(int presentationId, int programId) {
2703 Mutex::Autolock _l(mLock);
Jasmine Chaeaa10e42021-05-11 10:11:14 +08002704 if (!isStreamInitialized()) {
Mikhail Naganovac917ac2018-11-28 14:03:52 -08002705 return NO_INIT;
2706 }
2707 return mOutput->stream->selectPresentation(presentationId, programId);
2708}
2709
Eric Laurent09f1ed22019-04-24 17:45:17 -07002710void AudioFlinger::PlaybackThread::ioConfigChanged(audio_io_config_event event, pid_t pid,
2711 audio_port_handle_t portId) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002712 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
2713 ALOGV("PlaybackThread::ioConfigChanged, thread %p, event %d", this, event);
Eric Laurent81784c32012-11-19 14:55:58 -08002714
Eric Laurent73e26b62015-04-27 16:55:58 -07002715 desc->mIoHandle = mId;
Eric Laurent74c38dc2020-12-23 18:19:44 +01002716 struct audio_patch patch = mPatch;
2717 if (isMsdDevice()) {
2718 patch = mDownStreamPatch;
2719 }
Eric Laurent81784c32012-11-19 14:55:58 -08002720
2721 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002722 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07002723 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07002724 case AUDIO_OUTPUT_CONFIG_CHANGED:
Eric Laurent74c38dc2020-12-23 18:19:44 +01002725 desc->mPatch = patch;
Eric Laurent73e26b62015-04-27 16:55:58 -07002726 desc->mChannelMask = mChannelMask;
2727 desc->mSamplingRate = mSampleRate;
2728 desc->mFormat = mFormat;
2729 desc->mFrameCount = mNormalFrameCount; // FIXME see
Eric Laurent81784c32012-11-19 14:55:58 -08002730 // AudioFlinger::frameCount(audio_io_handle_t)
Glenn Kasten4a8308b2016-04-18 14:10:01 -07002731 desc->mFrameCountHAL = mFrameCount;
Eric Laurent73e26b62015-04-27 16:55:58 -07002732 desc->mLatency = latency_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002733 break;
Eric Laurent09f1ed22019-04-24 17:45:17 -07002734 case AUDIO_CLIENT_STARTED:
Eric Laurent74c38dc2020-12-23 18:19:44 +01002735 desc->mPatch = patch;
Eric Laurent09f1ed22019-04-24 17:45:17 -07002736 desc->mPortId = portId;
2737 break;
Eric Laurent73e26b62015-04-27 16:55:58 -07002738 case AUDIO_OUTPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08002739 default:
2740 break;
2741 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002742 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08002743}
2744
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002745void AudioFlinger::PlaybackThread::onWriteReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002746{
Eric Laurent3b4529e2013-09-05 18:09:19 -07002747 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002748}
2749
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002750void AudioFlinger::PlaybackThread::onDrainReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002751{
Eric Laurent3b4529e2013-09-05 18:09:19 -07002752 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002753}
2754
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002755void AudioFlinger::PlaybackThread::onError()
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002756{
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002757 mCallbackThread->setAsyncError();
2758}
2759
jiabinf6eb4c32020-02-25 14:06:25 -08002760void AudioFlinger::PlaybackThread::onCodecFormatChanged(
2761 const std::basic_string<uint8_t>& metadataBs)
2762{
2763 std::thread([this, metadataBs]() {
2764 audio_utils::metadata::Data metadata =
2765 audio_utils::metadata::dataFromByteString(metadataBs);
2766 if (metadata.empty()) {
2767 ALOGW("Can not transform the buffer to audio metadata, %s, %d",
2768 reinterpret_cast<char*>(const_cast<uint8_t*>(metadataBs.data())),
2769 (int)metadataBs.size());
2770 return;
2771 }
2772
2773 audio_utils::metadata::ByteString metaDataStr =
2774 audio_utils::metadata::byteStringFromData(metadata);
2775 std::vector metadataVec(metaDataStr.begin(), metaDataStr.end());
2776 Mutex::Autolock _l(mAudioTrackCbLock);
jiabin18a4b1c2020-09-17 11:40:42 -07002777 for (const auto& callbackPair : mAudioTrackCallbacks) {
2778 callbackPair.second->onCodecFormatChanged(metadataVec);
jiabinf6eb4c32020-02-25 14:06:25 -08002779 }
2780 }).detach();
2781}
2782
Eric Laurent3b4529e2013-09-05 18:09:19 -07002783void AudioFlinger::PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002784{
2785 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002786 // reject out of sequence requests
2787 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
2788 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002789 mWaitWorkCV.signal();
2790 }
2791}
2792
Eric Laurent3b4529e2013-09-05 18:09:19 -07002793void AudioFlinger::PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002794{
2795 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002796 // reject out of sequence requests
2797 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
Andy Hungf3234512018-07-03 14:51:47 -07002798 // Register discontinuity when HW drain is completed because that can cause
2799 // the timestamp frame position to reset to 0 for direct and offload threads.
2800 // (Out of sequence requests are ignored, since the discontinuity would be handled
2801 // elsewhere, e.g. in flush).
Dean Wheatley12473e92021-03-18 23:00:55 +11002802 mTimestampVerifier.discontinuity(mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002803 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002804 mWaitWorkCV.signal();
2805 }
2806}
2807
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002808void AudioFlinger::PlaybackThread::readOutputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08002809{
Glenn Kastenadad3d72014-02-21 14:51:43 -08002810 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Mikhail Naganov560637e2021-03-31 22:40:13 +00002811 const audio_config_base_t audioConfig = mOutput->getAudioProperties();
2812 mSampleRate = audioConfig.sample_rate;
2813 mChannelMask = audioConfig.channel_mask;
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002814 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002815 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002816 }
Andy Hung9a592762014-07-21 21:56:01 -07002817 if ((mType == MIXER || mType == DUPLICATING)
2818 && !isValidPcmSinkChannelMask(mChannelMask)) {
2819 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output",
2820 mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002821 }
Andy Hunge5412692014-05-16 11:25:07 -07002822 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01002823 mBalance.setChannelMask(mChannelMask);
Phil Burkca5e6142015-07-14 09:42:29 -07002824
2825 // Get actual HAL format.
Mikhail Naganov560637e2021-03-31 22:40:13 +00002826 status_t result = mOutput->stream->getAudioProperties(nullptr, nullptr, &mHALFormat);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002827 LOG_ALWAYS_FATAL_IF(result != OK, "Error when retrieving output stream format: %d", result);
Phil Burkca5e6142015-07-14 09:42:29 -07002828 // Get format from the shim, which will be different than the HAL format
2829 // if playing compressed audio over HDMI passthrough.
Mikhail Naganov560637e2021-03-31 22:40:13 +00002830 mFormat = audioConfig.format;
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002831 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002832 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002833 }
Andy Hung6146c082014-03-18 11:56:15 -07002834 if ((mType == MIXER || mType == DUPLICATING)
2835 && !isValidPcmSinkFormat(mFormat)) {
2836 LOG_FATAL("HAL format %#x not supported for mixed output",
2837 mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002838 }
Phil Burk062e67a2015-02-11 13:40:50 -08002839 mFrameSize = mOutput->getFrameSize();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002840 result = mOutput->stream->getBufferSize(&mBufferSize);
2841 LOG_ALWAYS_FATAL_IF(result != OK,
2842 "Error when retrieving output stream buffer size: %d", result);
Glenn Kasten70949c42013-08-06 07:40:12 -07002843 mFrameCount = mBufferSize / mFrameSize;
Dean Wheatley77cbebd2019-04-23 14:18:44 +10002844 if ((mType == MIXER || mType == DUPLICATING) && (mFrameCount & 15)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002845 ALOGW("HAL output buffer size is %zu frames but AudioMixer requires multiples of 16 frames",
Eric Laurent81784c32012-11-19 14:55:58 -08002846 mFrameCount);
2847 }
2848
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002849 if (mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING) {
2850 if (mOutput->stream->setCallback(this) == OK) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002851 mUseAsyncWrite = true;
Eric Laurent4de95592013-09-26 15:28:21 -07002852 mCallbackThread = new AudioFlinger::AsyncCallbackThread(this);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002853 }
2854 }
2855
Eric Laurentd1f69b02014-12-15 14:33:13 -08002856 mHwSupportsPause = false;
2857 if (mOutput->flags & AUDIO_OUTPUT_FLAG_DIRECT) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002858 bool supportsPause = false, supportsResume = false;
2859 if (mOutput->stream->supportsPauseAndResume(&supportsPause, &supportsResume) == OK) {
2860 if (supportsPause && supportsResume) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08002861 mHwSupportsPause = true;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002862 } else if (supportsPause) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08002863 ALOGW("direct output implements pause but not resume");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002864 } else if (supportsResume) {
2865 ALOGW("direct output implements resume but not pause");
Eric Laurentd1f69b02014-12-15 14:33:13 -08002866 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002867 }
2868 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07002869 if (!mHwSupportsPause && mOutput->flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) {
2870 LOG_ALWAYS_FATAL("HW_AV_SYNC requested but HAL does not implement pause and resume");
2871 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002872
Andy Hungfbfc3952015-01-15 13:33:51 -08002873 if (mType == DUPLICATING && mMixerBufferEnabled && mEffectBufferEnabled) {
2874 // For best precision, we use float instead of the associated output
2875 // device format (typically PCM 16 bit).
2876
2877 mFormat = AUDIO_FORMAT_PCM_FLOAT;
2878 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
2879 mBufferSize = mFrameSize * mFrameCount;
2880
2881 // TODO: We currently use the associated output device channel mask and sample rate.
2882 // (1) Perhaps use the ORed channel mask of all downstream MixerThreads
2883 // (if a valid mask) to avoid premature downmix.
2884 // (2) Perhaps use the maximum sample rate of all downstream MixerThreads
2885 // instead of the output device sample rate to avoid loss of high frequency information.
2886 // This may need to be updated as MixerThread/OutputTracks are added and not here.
2887 }
2888
Andy Hung09a50072014-02-27 14:30:47 -08002889 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08002890 double multiplier = 1.0;
2891 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
2892 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08002893 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
2894 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Haynes Mathew George227a14b2016-05-09 12:45:48 -07002895
Eric Laurent81784c32012-11-19 14:55:58 -08002896 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
2897 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
2898 maxNormalFrameCount = maxNormalFrameCount & ~15;
2899 if (maxNormalFrameCount < minNormalFrameCount) {
2900 maxNormalFrameCount = minNormalFrameCount;
2901 }
2902 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
2903 if (multiplier <= 1.0) {
2904 multiplier = 1.0;
2905 } else if (multiplier <= 2.0) {
2906 if (2 * mFrameCount <= maxNormalFrameCount) {
2907 multiplier = 2.0;
2908 } else {
2909 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
2910 }
2911 } else {
Haynes Mathew George227a14b2016-05-09 12:45:48 -07002912 multiplier = floor(multiplier);
Eric Laurent81784c32012-11-19 14:55:58 -08002913 }
2914 }
2915 mNormalFrameCount = multiplier * mFrameCount;
2916 // round up to nearest 16 frames to satisfy AudioMixer
Eric Laurentab5cdba2014-06-09 17:22:27 -07002917 if (mType == MIXER || mType == DUPLICATING) {
2918 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
2919 }
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002920 ALOGI("HAL output buffer size %zu frames, normal sink buffer size %zu frames", mFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08002921 mNormalFrameCount);
2922
Andy Hung08fb1742015-05-31 23:22:10 -07002923 // Check if we want to throttle the processing to no more than 2x normal rate
2924 mThreadThrottle = property_get_bool("af.thread.throttle", true /* default_value */);
Andy Hung40eb1a12015-06-18 13:42:02 -07002925 mThreadThrottleTimeMs = 0;
2926 mThreadThrottleEndMs = 0;
Andy Hung08fb1742015-05-31 23:22:10 -07002927 mHalfBufferMs = mNormalFrameCount * 1000 / (2 * mSampleRate);
2928
Andy Hung010a1a12014-03-13 13:57:33 -07002929 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
2930 // Originally this was int16_t[] array, need to remove legacy implications.
2931 free(mSinkBuffer);
2932 mSinkBuffer = NULL;
Andy Hung5b10a202014-03-13 13:59:29 -07002933 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
2934 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
2935 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07002936 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08002937
Andy Hung69aed5f2014-02-25 17:24:40 -08002938 // We resize the mMixerBuffer according to the requirements of the sink buffer which
2939 // drives the output.
2940 free(mMixerBuffer);
2941 mMixerBuffer = NULL;
2942 if (mMixerBufferEnabled) {
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01002943 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // no longer valid: AUDIO_FORMAT_PCM_16_BIT.
Andy Hung69aed5f2014-02-25 17:24:40 -08002944 mMixerBufferSize = mNormalFrameCount * mChannelCount
2945 * audio_bytes_per_sample(mMixerBufferFormat);
2946 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
2947 }
Andy Hung98ef9782014-03-04 14:46:50 -08002948 free(mEffectBuffer);
2949 mEffectBuffer = NULL;
2950 if (mEffectBufferEnabled) {
rago94a1ee82017-07-21 15:11:02 -07002951 mEffectBufferFormat = EFFECT_BUFFER_FORMAT;
Andy Hung98ef9782014-03-04 14:46:50 -08002952 mEffectBufferSize = mNormalFrameCount * mChannelCount
2953 * audio_bytes_per_sample(mEffectBufferFormat);
2954 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
2955 }
Andy Hung69aed5f2014-02-25 17:24:40 -08002956
Mikhail Naganov55773032020-10-01 15:08:13 -07002957 mHapticChannelMask = static_cast<audio_channel_mask_t>(mChannelMask & AUDIO_CHANNEL_HAPTIC_ALL);
2958 mChannelMask = static_cast<audio_channel_mask_t>(mChannelMask & ~mHapticChannelMask);
jiabin245cdd92018-12-07 17:55:15 -08002959 mHapticChannelCount = audio_channel_count_from_out_mask(mHapticChannelMask);
2960 mChannelCount -= mHapticChannelCount;
2961
Eric Laurent81784c32012-11-19 14:55:58 -08002962 // force reconfiguration of effect chains and engines to take new buffer size and audio
2963 // parameters into account
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002964 // Note that mLock is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08002965 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
2966 // matter.
2967 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
2968 Vector< sp<EffectChain> > effectChains = mEffectChains;
2969 for (size_t i = 0; i < effectChains.size(); i ++) {
Eric Laurent6c796322019-04-09 14:13:17 -07002970 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(),
2971 this/* srcThread */, this/* dstThread */);
Eric Laurent81784c32012-11-19 14:55:58 -08002972 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08002973
George Burgess IV5e4d86f2020-02-18 12:55:36 -08002974 audio_output_flags_t flags = mOutput->flags;
Andy Hungcf10d742020-04-28 15:38:24 -07002975 mediametrics::LogItem item(mThreadMetrics.getMetricsId()); // TODO: method in ThreadMetrics?
Andy Hungb68f5eb2019-12-03 16:49:17 -08002976 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
2977 .set(AMEDIAMETRICS_PROP_ENCODING, formatToString(mFormat).c_str())
2978 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
2979 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
2980 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
2981 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mNormalFrameCount)
2982 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
2983 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELMASK,
2984 (int32_t)mHapticChannelMask)
2985 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELCOUNT,
2986 (int32_t)mHapticChannelCount)
2987 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_ENCODING,
2988 formatToString(mHALFormat).c_str())
2989 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_FRAMECOUNT,
2990 (int32_t)mFrameCount) // sic - added HAL
2991 ;
2992 uint32_t latencyMs;
2993 if (mOutput->stream->getLatency(&latencyMs) == NO_ERROR) {
2994 item.set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_LATENCYMS, (double)latencyMs);
2995 }
2996 item.record();
Eric Laurent81784c32012-11-19 14:55:58 -08002997}
2998
Kevin Rocard069c2712018-03-29 19:09:14 -07002999void AudioFlinger::PlaybackThread::updateMetadata_l()
3000{
Jasmine Chaeaa10e42021-05-11 10:11:14 +08003001 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
Kevin Rocard12381092018-04-11 09:19:59 -07003002 return; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -07003003 }
3004 StreamOutHalInterface::SourceMetadata metadata;
Kevin Rocard12381092018-04-11 09:19:59 -07003005 auto backInserter = std::back_inserter(metadata.tracks);
Kevin Rocard069c2712018-03-29 19:09:14 -07003006 for (const sp<Track> &track : mActiveTracks) {
3007 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurentb9cc0ab2021-01-29 11:46:52 +01003008 // Do not forward metadata for PatchTrack with unspecified stream type
3009 if (track->streamType() != AUDIO_STREAM_PATCH) {
3010 track->copyMetadataTo(backInserter);
3011 }
Kevin Rocard069c2712018-03-29 19:09:14 -07003012 }
Kevin Rocard12381092018-04-11 09:19:59 -07003013 sendMetadataToBackend_l(metadata);
Kevin Rocard80ee2722018-04-11 15:53:48 +00003014}
Kevin Rocardc86a7f72018-04-03 09:00:09 -07003015
Kevin Rocard12381092018-04-11 09:19:59 -07003016void AudioFlinger::PlaybackThread::sendMetadataToBackend_l(
3017 const StreamOutHalInterface::SourceMetadata& metadata)
3018{
3019 mOutput->stream->updateSourceMetadata(metadata);
3020};
3021
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003022status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
Eric Laurent81784c32012-11-19 14:55:58 -08003023{
3024 if (halFrames == NULL || dspFrames == NULL) {
3025 return BAD_VALUE;
3026 }
3027 Mutex::Autolock _l(mLock);
3028 if (initCheck() != NO_ERROR) {
3029 return INVALID_OPERATION;
3030 }
Andy Hung818e7a32016-02-16 18:08:07 -08003031 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08003032 *halFrames = framesWritten;
3033
3034 if (isSuspended()) {
3035 // return an estimation of rendered frames when the output is suspended
3036 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08003037 *dspFrames = (uint32_t)
3038 (framesWritten >= (int64_t)latencyFrames ? framesWritten - latencyFrames : 0);
Eric Laurent81784c32012-11-19 14:55:58 -08003039 return NO_ERROR;
3040 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003041 status_t status;
3042 uint32_t frames;
Phil Burk062e67a2015-02-11 13:40:50 -08003043 status = mOutput->getRenderPosition(&frames);
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003044 *dspFrames = (size_t)frames;
3045 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08003046 }
3047}
3048
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08003049product_strategy_t AudioFlinger::PlaybackThread::getStrategyForSession_l(audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08003050{
3051 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
3052 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
3053 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
3054 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
3055 }
3056 for (size_t i = 0; i < mTracks.size(); i++) {
3057 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08003058 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003059 return AudioSystem::getStrategyForStream(track->streamType());
3060 }
3061 }
3062 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
3063}
3064
3065
Phil Burk062e67a2015-02-11 13:40:50 -08003066AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurent81784c32012-11-19 14:55:58 -08003067{
3068 Mutex::Autolock _l(mLock);
3069 return mOutput;
3070}
3071
Phil Burk062e67a2015-02-11 13:40:50 -08003072AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
Eric Laurent81784c32012-11-19 14:55:58 -08003073{
3074 Mutex::Autolock _l(mLock);
3075 AudioStreamOut *output = mOutput;
3076 mOutput = NULL;
3077 // FIXME FastMixer might also have a raw ptr to mOutputSink;
3078 // must push a NULL and wait for ack
3079 mOutputSink.clear();
3080 mPipeSink.clear();
3081 mNormalSink.clear();
3082 return output;
3083}
3084
3085// this method must always be called either with ThreadBase mLock held or inside the thread loop
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003086sp<StreamHalInterface> AudioFlinger::PlaybackThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08003087{
3088 if (mOutput == NULL) {
3089 return NULL;
3090 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003091 return mOutput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08003092}
3093
3094uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
3095{
3096 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
3097}
3098
3099status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
3100{
3101 if (!isValidSyncEvent(event)) {
3102 return BAD_VALUE;
3103 }
3104
3105 Mutex::Autolock _l(mLock);
3106
3107 for (size_t i = 0; i < mTracks.size(); ++i) {
3108 sp<Track> track = mTracks[i];
3109 if (event->triggerSession() == track->sessionId()) {
3110 (void) track->setSyncEvent(event);
3111 return NO_ERROR;
3112 }
3113 }
3114
3115 return NAME_NOT_FOUND;
3116}
3117
3118bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
3119{
3120 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
3121}
3122
3123void AudioFlinger::PlaybackThread::threadLoop_removeTracks(
3124 const Vector< sp<Track> >& tracksToRemove)
3125{
Andy Hungfe726a62018-09-27 15:17:25 -07003126 // Miscellaneous track cleanup when removed from the active list,
3127 // called without Thread lock but synchronized with threadLoop processing.
Eric Laurentbfb1b832013-01-07 09:53:42 -08003128#ifdef ADD_BATTERY_DATA
Andy Hungfe726a62018-09-27 15:17:25 -07003129 for (const auto& track : tracksToRemove) {
3130 if (track->isExternalTrack()) {
3131 // to track the speaker usage
3132 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Eric Laurent81784c32012-11-19 14:55:58 -08003133 }
3134 }
Andy Hungfe726a62018-09-27 15:17:25 -07003135#else
3136 (void)tracksToRemove; // suppress unused warning
3137#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003138}
3139
3140void AudioFlinger::PlaybackThread::checkSilentMode_l()
3141{
3142 if (!mMasterMute) {
3143 char value[PROPERTY_VALUE_MAX];
jiabin0a957d32020-04-29 10:56:20 -07003144 if (mOutDeviceTypeAddrs.empty()) {
3145 ALOGD("ro.audio.silent is ignored since no output device is set");
3146 return;
3147 }
jiabinc52b1ff2019-10-31 17:20:42 -07003148 if (isSingleDeviceType(outDeviceTypes(), AUDIO_DEVICE_OUT_REMOTE_SUBMIX)) {
Jean-Michel Trivi32f37c22016-03-31 16:00:32 -07003149 ALOGD("ro.audio.silent will be ignored for threads on AUDIO_DEVICE_OUT_REMOTE_SUBMIX");
3150 return;
3151 }
Eric Laurent81784c32012-11-19 14:55:58 -08003152 if (property_get("ro.audio.silent", value, "0") > 0) {
3153 char *endptr;
3154 unsigned long ul = strtoul(value, &endptr, 0);
3155 if (*endptr == '\0' && ul != 0) {
3156 ALOGD("Silence is golden");
3157 // The setprop command will not allow a property to be changed after
3158 // the first time it is set, so we don't have to worry about un-muting.
3159 setMasterMute_l(true);
3160 }
3161 }
3162 }
3163}
3164
3165// shared by MIXER and DIRECT, overridden by DUPLICATING
Eric Laurentbfb1b832013-01-07 09:53:42 -08003166ssize_t AudioFlinger::PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08003167{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07003168 LOG_HIST_TS();
Eric Laurent81784c32012-11-19 14:55:58 -08003169 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003170 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07003171 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08003172
3173 // If an NBAIO sink is present, use it to write the normal mixer's submix
3174 if (mNormalSink != 0) {
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003175
Andy Hung010a1a12014-03-13 13:57:33 -07003176 const size_t count = mBytesRemaining / mFrameSize;
3177
Simon Wilson2d590962012-11-29 15:18:50 -08003178 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08003179 // update the setpoint when AudioFlinger::mScreenState changes
3180 uint32_t screenState = AudioFlinger::mScreenState;
3181 if (screenState != mScreenState) {
3182 mScreenState = screenState;
3183 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
3184 if (pipe != NULL) {
3185 pipe->setAvgFrames((mScreenState & 1) ?
3186 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
3187 }
3188 }
Andy Hung010a1a12014-03-13 13:57:33 -07003189 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08003190 ATRACE_END();
Eric Laurent81784c32012-11-19 14:55:58 -08003191 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07003192 bytesWritten = framesWritten * mFrameSize;
Andy Hung8946a282018-04-19 20:04:56 -07003193#ifdef TEE_SINK
3194 mTee.write((char *)mSinkBuffer + offset, framesWritten);
3195#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003196 } else {
3197 bytesWritten = framesWritten;
3198 }
3199 // otherwise use the HAL / AudioStreamOut directly
3200 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003201 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07003202
Eric Laurentbfb1b832013-01-07 09:53:42 -08003203 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003204 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
3205 mWriteAckSequence += 2;
3206 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003207 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003208 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003209 }
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07003210 ATRACE_BEGIN("write");
Glenn Kasten767094d2013-08-23 13:51:43 -07003211 // FIXME We should have an implementation of timestamps for direct output threads.
3212 // They are used e.g for multichannel PCM playback over HDMI.
Phil Burk062e67a2015-02-11 13:40:50 -08003213 bytesWritten = mOutput->write((char *)mSinkBuffer + offset, mBytesRemaining);
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07003214 ATRACE_END();
Eric Laurent51716182016-02-29 18:00:56 -08003215
Eric Laurentbfb1b832013-01-07 09:53:42 -08003216 if (mUseAsyncWrite &&
3217 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
3218 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07003219 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003220 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003221 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003222 }
Eric Laurent81784c32012-11-19 14:55:58 -08003223 }
3224
Eric Laurent81784c32012-11-19 14:55:58 -08003225 mNumWrites++;
3226 mInWrite = false;
Andy Hungcf10d742020-04-28 15:38:24 -07003227 if (mStandby) {
3228 mThreadMetrics.logBeginInterval();
3229 mStandby = false;
3230 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003231 return bytesWritten;
3232}
3233
3234void AudioFlinger::PlaybackThread::threadLoop_drain()
3235{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003236 bool supportsDrain = false;
3237 if (mOutput->stream->supportsDrain(&supportsDrain) == OK && supportsDrain) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003238 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
3239 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003240 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
3241 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003242 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003243 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003244 }
Mikhail Naganovcbc8f612016-10-11 18:05:13 -07003245 status_t result = mOutput->stream->drain(mMixerStatus == MIXER_DRAIN_TRACK);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003246 ALOGE_IF(result != OK, "Error when draining stream: %d", result);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003247 }
3248}
3249
3250void AudioFlinger::PlaybackThread::threadLoop_exit()
3251{
Eric Laurent275e8e92014-11-30 15:14:47 -08003252 {
3253 Mutex::Autolock _l(mLock);
3254 for (size_t i = 0; i < mTracks.size(); i++) {
3255 sp<Track> track = mTracks[i];
3256 track->invalidate();
3257 }
Andy Hungdae27702016-10-31 14:01:16 -07003258 // Clear ActiveTracks to update BatteryNotifier in case active tracks remain.
3259 // After we exit there are no more track changes sent to BatteryNotifier
3260 // because that requires an active threadLoop.
3261 // TODO: should we decActiveTrackCnt() of the cleared track effect chain?
3262 mActiveTracks.clear();
Eric Laurent275e8e92014-11-30 15:14:47 -08003263 }
Eric Laurent81784c32012-11-19 14:55:58 -08003264}
3265
3266/*
3267The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08003268 - mSinkBufferSize from frame count * frame size
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003269 - mActiveSleepTimeUs from activeSleepTimeUs()
3270 - mIdleSleepTimeUs from idleSleepTimeUs()
Eric Laurent42537be2016-01-08 17:16:42 -08003271 - mStandbyDelayNs from mActiveSleepTimeUs (DIRECT only) or forced to at least
3272 kDefaultStandbyTimeInNsecs when connected to an A2DP device.
Eric Laurent81784c32012-11-19 14:55:58 -08003273 - maxPeriod from frame count and sample rate (MIXER only)
3274
3275The parameters that affect these derived values are:
3276 - frame count
3277 - frame size
3278 - sample rate
3279 - device type: A2DP or not
3280 - device latency
3281 - format: PCM or not
3282 - active sleep time
3283 - idle sleep time
3284*/
3285
3286void AudioFlinger::PlaybackThread::cacheParameters_l()
3287{
Andy Hung25c2dac2014-02-27 14:56:00 -08003288 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003289 mActiveSleepTimeUs = activeSleepTimeUs();
3290 mIdleSleepTimeUs = idleSleepTimeUs();
Eric Laurent42537be2016-01-08 17:16:42 -08003291
3292 // make sure standby delay is not too short when connected to an A2DP sink to avoid
3293 // truncating audio when going to standby.
3294 mStandbyDelayNs = AudioFlinger::mStandbyTimeInNsecs;
jiabinc52b1ff2019-10-31 17:20:42 -07003295 if (!Intersection(outDeviceTypes(), getAudioDeviceOutAllA2dpSet()).empty()) {
Eric Laurent42537be2016-01-08 17:16:42 -08003296 if (mStandbyDelayNs < kDefaultStandbyTimeInNsecs) {
3297 mStandbyDelayNs = kDefaultStandbyTimeInNsecs;
3298 }
3299 }
Eric Laurent81784c32012-11-19 14:55:58 -08003300}
3301
Eric Laurent13084622016-05-17 10:51:49 -07003302bool AudioFlinger::PlaybackThread::invalidateTracks_l(audio_stream_type_t streamType)
Eric Laurent81784c32012-11-19 14:55:58 -08003303{
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003304 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %zu",
Eric Laurent81784c32012-11-19 14:55:58 -08003305 this, streamType, mTracks.size());
Eric Laurent13084622016-05-17 10:51:49 -07003306 bool trackMatch = false;
Eric Laurent81784c32012-11-19 14:55:58 -08003307 size_t size = mTracks.size();
3308 for (size_t i = 0; i < size; i++) {
3309 sp<Track> t = mTracks[i];
Eric Laurentd60560a2015-04-10 11:31:20 -07003310 if (t->streamType() == streamType && t->isExternalTrack()) {
Glenn Kasten5736c352012-12-04 12:12:34 -08003311 t->invalidate();
Eric Laurent13084622016-05-17 10:51:49 -07003312 trackMatch = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003313 }
3314 }
Eric Laurent13084622016-05-17 10:51:49 -07003315 return trackMatch;
Eric Laurent81784c32012-11-19 14:55:58 -08003316}
3317
Haynes Mathew George05317d22016-05-03 16:34:26 -07003318void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
3319{
3320 Mutex::Autolock _l(mLock);
3321 invalidateTracks_l(streamType);
3322}
3323
Eric Laurent81784c32012-11-19 14:55:58 -08003324status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
3325{
Glenn Kastend848eb42016-03-08 13:42:11 -08003326 audio_session_t session = chain->sessionId();
Mikhail Naganov022b9952017-01-04 16:36:51 -08003327 sp<EffectBufferHalInterface> halInBuffer, halOutBuffer;
Kevin Rocard7588ff42018-01-08 11:11:30 -08003328 status_t result = mAudioFlinger->mEffectsFactoryHal->mirrorBuffer(
Mikhail Naganov022b9952017-01-04 16:36:51 -08003329 mEffectBufferEnabled ? mEffectBuffer : mSinkBuffer,
3330 mEffectBufferEnabled ? mEffectBufferSize : mSinkBufferSize,
3331 &halInBuffer);
3332 if (result != OK) return result;
3333 halOutBuffer = halInBuffer;
rago94a1ee82017-07-21 15:11:02 -07003334 effect_buffer_t *buffer = reinterpret_cast<effect_buffer_t*>(halInBuffer->externalData());
Eric Laurent81784c32012-11-19 14:55:58 -08003335 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Eric Laurent3f75a5b2019-11-12 15:55:51 -08003336 if (!audio_is_global_session(session)) {
Eric Laurent81784c32012-11-19 14:55:58 -08003337 // Only one effect chain can be present in direct output thread and it uses
Andy Hung2098f272014-02-27 14:00:06 -08003338 // the sink buffer as input
Eric Laurent81784c32012-11-19 14:55:58 -08003339 if (mType != DIRECT) {
jiabin245cdd92018-12-07 17:55:15 -08003340 size_t numSamples = mNormalFrameCount * (mChannelCount + mHapticChannelCount);
Kevin Rocard7588ff42018-01-08 11:11:30 -08003341 status_t result = mAudioFlinger->mEffectsFactoryHal->allocateBuffer(
rago94a1ee82017-07-21 15:11:02 -07003342 numSamples * sizeof(effect_buffer_t),
Mikhail Naganov022b9952017-01-04 16:36:51 -08003343 &halInBuffer);
3344 if (result != OK) return result;
rago94a1ee82017-07-21 15:11:02 -07003345#ifdef FLOAT_EFFECT_CHAIN
3346 buffer = halInBuffer->audioBuffer()->f32;
3347#else
Mikhail Naganov022b9952017-01-04 16:36:51 -08003348 buffer = halInBuffer->audioBuffer()->s16;
rago94a1ee82017-07-21 15:11:02 -07003349#endif
Mikhail Naganov022b9952017-01-04 16:36:51 -08003350 ALOGV("addEffectChain_l() creating new input buffer %p session %d",
3351 buffer, session);
Eric Laurent81784c32012-11-19 14:55:58 -08003352 }
3353
3354 // Attach all tracks with same session ID to this chain.
3355 for (size_t i = 0; i < mTracks.size(); ++i) {
3356 sp<Track> track = mTracks[i];
3357 if (session == track->sessionId()) {
3358 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(),
3359 buffer);
3360 track->setMainBuffer(buffer);
3361 chain->incTrackCnt();
3362 }
3363 }
3364
3365 // indicate all active tracks in the chain
Andy Hungdae27702016-10-31 14:01:16 -07003366 for (const sp<Track> &track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08003367 if (session == track->sessionId()) {
3368 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
3369 chain->incActiveTrackCnt();
3370 }
3371 }
3372 }
Eric Laurentaaa44472014-09-12 17:41:50 -07003373 chain->setThread(this);
Mikhail Naganov022b9952017-01-04 16:36:51 -08003374 chain->setInBuffer(halInBuffer);
3375 chain->setOutBuffer(halOutBuffer);
Eric Laurent3f75a5b2019-11-12 15:55:51 -08003376 // Effect chain for session AUDIO_SESSION_DEVICE is inserted at end of effect
3377 // chains list in order to be processed last as it contains output device effects.
3378 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted just before to apply post
3379 // processing effects specific to an output stream before effects applied to all streams
3380 // routed to a given device.
Eric Laurent81784c32012-11-19 14:55:58 -08003381 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
3382 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Glenn Kastend848eb42016-03-08 13:42:11 -08003383 // after track specific effects and before output stage.
Eric Laurent81784c32012-11-19 14:55:58 -08003384 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
Glenn Kastend848eb42016-03-08 13:42:11 -08003385 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX.
Eric Laurent81784c32012-11-19 14:55:58 -08003386 // Effect chain for other sessions are inserted at beginning of effect
3387 // chains list to be processed before output mix effects. Relative order between other
Glenn Kastend848eb42016-03-08 13:42:11 -08003388 // sessions is not important.
3389 static_assert(AUDIO_SESSION_OUTPUT_MIX == 0 &&
Eric Laurent3f75a5b2019-11-12 15:55:51 -08003390 AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX &&
3391 AUDIO_SESSION_DEVICE < AUDIO_SESSION_OUTPUT_STAGE,
Glenn Kastend848eb42016-03-08 13:42:11 -08003392 "audio_session_t constants misdefined");
Eric Laurent81784c32012-11-19 14:55:58 -08003393 size_t size = mEffectChains.size();
3394 size_t i = 0;
3395 for (i = 0; i < size; i++) {
3396 if (mEffectChains[i]->sessionId() < session) {
3397 break;
3398 }
3399 }
3400 mEffectChains.insertAt(chain, i);
3401 checkSuspendOnAddEffectChain_l(chain);
3402
3403 return NO_ERROR;
3404}
3405
3406size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
3407{
Glenn Kastend848eb42016-03-08 13:42:11 -08003408 audio_session_t session = chain->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08003409
3410 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
3411
3412 for (size_t i = 0; i < mEffectChains.size(); i++) {
3413 if (chain == mEffectChains[i]) {
3414 mEffectChains.removeAt(i);
3415 // detach all active tracks from the chain
Andy Hungdae27702016-10-31 14:01:16 -07003416 for (const sp<Track> &track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08003417 if (session == track->sessionId()) {
3418 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
3419 chain.get(), session);
3420 chain->decActiveTrackCnt();
3421 }
3422 }
3423
3424 // detach all tracks with same session ID from this chain
3425 for (size_t i = 0; i < mTracks.size(); ++i) {
3426 sp<Track> track = mTracks[i];
3427 if (session == track->sessionId()) {
rago94a1ee82017-07-21 15:11:02 -07003428 track->setMainBuffer(reinterpret_cast<effect_buffer_t*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08003429 chain->decTrackCnt();
3430 }
3431 }
3432 break;
3433 }
3434 }
3435 return mEffectChains.size();
3436}
3437
3438status_t AudioFlinger::PlaybackThread::attachAuxEffect(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003439 const sp<AudioFlinger::PlaybackThread::Track>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003440{
3441 Mutex::Autolock _l(mLock);
3442 return attachAuxEffect_l(track, EffectId);
3443}
3444
3445status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003446 const sp<AudioFlinger::PlaybackThread::Track>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003447{
3448 status_t status = NO_ERROR;
3449
3450 if (EffectId == 0) {
3451 track->setAuxBuffer(0, NULL);
3452 } else {
3453 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
3454 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
3455 if (effect != 0) {
3456 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
3457 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
3458 } else {
3459 status = INVALID_OPERATION;
3460 }
3461 } else {
3462 status = BAD_VALUE;
3463 }
3464 }
3465 return status;
3466}
3467
3468void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
3469{
3470 for (size_t i = 0; i < mTracks.size(); ++i) {
3471 sp<Track> track = mTracks[i];
3472 if (track->auxEffectId() == effectId) {
3473 attachAuxEffect_l(track, 0);
3474 }
3475 }
3476}
3477
3478bool AudioFlinger::PlaybackThread::threadLoop()
3479{
Glenn Kasten388d5712017-04-07 14:38:41 -07003480 tlNBLogWriter = mNBLogWriter.get();
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003481
Eric Laurent81784c32012-11-19 14:55:58 -08003482 Vector< sp<Track> > tracksToRemove;
3483
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003484 mStandbyTimeNs = systemTime();
Andy Hung446f4df2019-02-21 12:26:41 -08003485 int64_t lastLoopCountWritten = -2; // never matches "previous" loop, when loopCount = 0.
Eric Laurent81784c32012-11-19 14:55:58 -08003486
3487 // MIXER
3488 nsecs_t lastWarning = 0;
3489
3490 // DUPLICATING
3491 // FIXME could this be made local to while loop?
3492 writeFrames = 0;
3493
3494 cacheParameters_l();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003495 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003496
3497 if (mType == MIXER) {
3498 sleepTimeShift = 0;
3499 }
3500
3501 CpuStats cpuStats;
3502 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
3503
3504 acquireWakeLock();
3505
Glenn Kasteneef598c2017-04-03 14:41:13 -07003506 // mNBLogWriter logging APIs can only be called by a single thread, typically the
3507 // thread associated with this PlaybackThread.
3508 // If you want to share the mNBLogWriter with other threads (for example, binder threads)
3509 // then all such threads must agree to hold a common mutex before logging.
Glenn Kasten9e58b552013-01-18 15:09:48 -08003510 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
3511 // and then that string will be logged at the next convenient opportunity.
Glenn Kasteneef598c2017-04-03 14:41:13 -07003512 // See reference to logString below.
Glenn Kasten9e58b552013-01-18 15:09:48 -08003513 const char *logString = NULL;
3514
rago1bb90822017-05-02 18:31:48 -07003515 // Estimated time for next buffer to be written to hal. This is used only on
3516 // suspended mode (for now) to help schedule the wait time until next iteration.
3517 nsecs_t timeLoopNextNs = 0;
3518
Eric Laurent664539d2013-09-23 18:24:31 -07003519 checkSilentMode_l();
Glenn Kasteneef598c2017-04-03 14:41:13 -07003520
Andy Hung2dbffc22018-08-08 18:50:41 -07003521 audio_patch_handle_t lastDownstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Andy Hungf3234512018-07-03 14:51:47 -07003522
Andy Hung446f4df2019-02-21 12:26:41 -08003523 // loopCount is used for statistics and diagnostics.
3524 for (int64_t loopCount = 0; !exitPending(); ++loopCount)
Eric Laurent81784c32012-11-19 14:55:58 -08003525 {
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08003526 // Log merge requests are performed during AudioFlinger binder transactions, but
3527 // that does not cover audio playback. It's requested here for that reason.
3528 mAudioFlinger->requestLogMerge();
3529
Eric Laurent81784c32012-11-19 14:55:58 -08003530 cpuStats.sample(myName);
3531
3532 Vector< sp<EffectChain> > effectChains;
Andy Hung6e6a2e62019-04-30 16:38:41 -07003533 audio_session_t activeHapticSessionId = AUDIO_SESSION_NONE;
Andy Hungc1646382019-04-30 16:12:10 -07003534 std::vector<sp<Track>> activeTracks;
Eric Laurent81784c32012-11-19 14:55:58 -08003535
Andy Hung2dbffc22018-08-08 18:50:41 -07003536 // If the device is AUDIO_DEVICE_OUT_BUS, check for downstream latency.
3537 //
jiabinc52b1ff2019-10-31 17:20:42 -07003538 // Note: we access outDeviceTypes() outside of mLock.
3539 if (isMsdDevice() && outDeviceTypes().count(AUDIO_DEVICE_OUT_BUS) != 0) {
Andy Hung2dbffc22018-08-08 18:50:41 -07003540 // Here, we try for the AF lock, but do not block on it as the latency
3541 // is more informational.
3542 if (mAudioFlinger->mLock.tryLock() == NO_ERROR) {
3543 std::vector<PatchPanel::SoftwarePatch> swPatches;
3544 double latencyMs;
3545 status_t status = INVALID_OPERATION;
3546 audio_patch_handle_t downstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
3547 if (mAudioFlinger->mPatchPanel.getDownstreamSoftwarePatches(id(), &swPatches) == OK
3548 && swPatches.size() > 0) {
3549 status = swPatches[0].getLatencyMs_l(&latencyMs);
3550 downstreamPatchHandle = swPatches[0].getPatchHandle();
3551 }
3552 if (downstreamPatchHandle != lastDownstreamPatchHandle) {
Dean Wheatley30d28422018-11-06 10:27:40 +11003553 mDownstreamLatencyStatMs.reset();
Andy Hung2dbffc22018-08-08 18:50:41 -07003554 lastDownstreamPatchHandle = downstreamPatchHandle;
3555 }
3556 if (status == OK) {
3557 // verify downstream latency (we assume a max reasonable
Mikhail Naganov6aa0a312018-11-09 11:00:01 -08003558 // latency of 5 seconds).
3559 const double minLatency = 0., maxLatency = 5000.;
3560 if (latencyMs >= minLatency && latencyMs <= maxLatency) {
Dean Wheatley56a583e2020-05-08 15:12:17 +10003561 ALOGVV("new downstream latency %lf ms", latencyMs);
Andy Hung2dbffc22018-08-08 18:50:41 -07003562 } else {
3563 ALOGD("out of range downstream latency %lf ms", latencyMs);
Mikhail Naganov6aa0a312018-11-09 11:00:01 -08003564 if (latencyMs < minLatency) latencyMs = minLatency;
3565 else if (latencyMs > maxLatency) latencyMs = maxLatency;
Andy Hung2dbffc22018-08-08 18:50:41 -07003566 }
Dean Wheatley30d28422018-11-06 10:27:40 +11003567 mDownstreamLatencyStatMs.add(latencyMs);
Andy Hung2dbffc22018-08-08 18:50:41 -07003568 }
3569 mAudioFlinger->mLock.unlock();
3570 }
3571 } else {
3572 if (lastDownstreamPatchHandle != AUDIO_PATCH_HANDLE_NONE) {
3573 // our device is no longer AUDIO_DEVICE_OUT_BUS, reset patch handle and stats.
Dean Wheatley30d28422018-11-06 10:27:40 +11003574 mDownstreamLatencyStatMs.reset();
Andy Hung2dbffc22018-08-08 18:50:41 -07003575 lastDownstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
3576 }
3577 }
3578
Eric Laurent81784c32012-11-19 14:55:58 -08003579 { // scope for mLock
3580
3581 Mutex::Autolock _l(mLock);
3582
Eric Laurent021cf962014-05-13 10:18:14 -07003583 processConfigEvents_l();
Eric Laurent10351942014-05-08 18:49:52 -07003584
Glenn Kasteneef598c2017-04-03 14:41:13 -07003585 // See comment at declaration of logString for why this is done under mLock
Glenn Kasten9e58b552013-01-18 15:09:48 -08003586 if (logString != NULL) {
3587 mNBLogWriter->logTimestamp();
3588 mNBLogWriter->log(logString);
3589 logString = NULL;
3590 }
3591
Dean Wheatley12473e92021-03-18 23:00:55 +11003592 collectTimestamps_l();
Andy Hungc8fddf32018-08-08 18:32:37 -07003593
Eric Laurent81784c32012-11-19 14:55:58 -08003594 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003595 if (mSignalPending) {
3596 // A signal was raised while we were unlocked
3597 mSignalPending = false;
3598 } else if (waitingAsyncCallback_l()) {
3599 if (exitPending()) {
3600 break;
3601 }
Marco Nelissen078538c2015-05-12 09:17:57 -07003602 bool released = false;
Eric Laurent64667972016-03-30 18:19:46 -07003603 if (!keepWakeLock()) {
Marco Nelissen078538c2015-05-12 09:17:57 -07003604 releaseWakeLock_l();
3605 released = true;
3606 }
Andy Hung10cbff12017-02-21 17:30:14 -08003607
3608 const int64_t waitNs = computeWaitTimeNs_l();
3609 ALOGV("wait async completion (wait time: %lld)", (long long)waitNs);
3610 status_t status = mWaitWorkCV.waitRelative(mLock, waitNs);
3611 if (status == TIMED_OUT) {
3612 mSignalPending = true; // if timeout recheck everything
3613 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003614 ALOGV("async completion/wake");
Marco Nelissen078538c2015-05-12 09:17:57 -07003615 if (released) {
3616 acquireWakeLock_l();
3617 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003618 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3619 mSleepTimeUs = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07003620
3621 continue;
3622 }
Eric Tan39ec8d62018-07-24 09:49:29 -07003623 if ((mActiveTracks.isEmpty() && systemTime() > mStandbyTimeNs) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08003624 isSuspended()) {
3625 // put audio hardware into standby after short delay
3626 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003627
3628 threadLoop_standby();
3629
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07003630 // This is where we go into standby
3631 if (!mStandby) {
3632 LOG_AUDIO_STATE();
Andy Hungcf10d742020-04-28 15:38:24 -07003633 mThreadMetrics.logEndInterval();
3634 mStandby = true;
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07003635 }
Andy Hungd0979812019-02-21 15:51:44 -08003636 sendStatistics(false /* force */);
Eric Laurent81784c32012-11-19 14:55:58 -08003637 }
3638
Eric Tan39ec8d62018-07-24 09:49:29 -07003639 if (mActiveTracks.isEmpty() && mConfigEvents.isEmpty()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003640 // we're about to wait, flush the binder command buffer
3641 IPCThreadState::self()->flushCommands();
3642
3643 clearOutputTracks();
3644
3645 if (exitPending()) {
3646 break;
3647 }
3648
3649 releaseWakeLock_l();
3650 // wait until we have something to do...
3651 ALOGV("%s going to sleep", myName.string());
3652 mWaitWorkCV.wait(mLock);
3653 ALOGV("%s waking up", myName.string());
3654 acquireWakeLock_l();
3655
3656 mMixerStatus = MIXER_IDLE;
3657 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
3658 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003659 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003660 checkSilentMode_l();
3661
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003662 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3663 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003664 if (mType == MIXER) {
3665 sleepTimeShift = 0;
3666 }
3667
3668 continue;
3669 }
3670 }
Eric Laurent81784c32012-11-19 14:55:58 -08003671 // mMixerStatusIgnoringFastTracks is also updated internally
3672 mMixerStatus = prepareTracks_l(&tracksToRemove);
3673
Andy Hungdae27702016-10-31 14:01:16 -07003674 mActiveTracks.updatePowerState(this);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003675
Kevin Rocard069c2712018-03-29 19:09:14 -07003676 updateMetadata_l();
3677
Eric Laurent81784c32012-11-19 14:55:58 -08003678 // prevent any changes in effect chain list and in each effect chain
3679 // during mixing and effect process as the audio buffers could be deleted
3680 // or modified if an effect is created or deleted
3681 lockEffectChains_l(effectChains);
Andy Hung6e6a2e62019-04-30 16:38:41 -07003682
3683 // Determine which session to pick up haptic data.
3684 // This must be done under the same lock as prepareTracks_l().
jiabineb3bda02020-06-30 14:07:03 -07003685 // The haptic data from the effect is at a higher priority than the one from track.
Andy Hung6e6a2e62019-04-30 16:38:41 -07003686 // TODO: Write haptic data directly to sink buffer when mixing.
3687 if (mHapticChannelCount > 0 && effectChains.size() > 0) {
3688 for (const auto& track : mActiveTracks) {
jiabineb3bda02020-06-30 14:07:03 -07003689 sp<EffectChain> effectChain = getEffectChain_l(track->sessionId());
3690 if (effectChain != nullptr && effectChain->containsHapticGeneratingEffect_l()) {
3691 activeHapticSessionId = track->sessionId();
3692 break;
3693 }
Andy Hung6e6a2e62019-04-30 16:38:41 -07003694 if (track->getHapticPlaybackEnabled()) {
3695 activeHapticSessionId = track->sessionId();
3696 break;
3697 }
3698 }
3699 }
3700
Andy Hungc1646382019-04-30 16:12:10 -07003701 // Acquire a local copy of active tracks with lock (release w/o lock).
3702 //
3703 // Control methods on the track acquire the ThreadBase lock (e.g. start()
3704 // stop(), pause(), etc.), but the threadLoop is entitled to call audio
3705 // data / buffer methods on tracks from activeTracks without the ThreadBase lock.
3706 activeTracks.insert(activeTracks.end(), mActiveTracks.begin(), mActiveTracks.end());
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003707 } // mLock scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08003708
Eric Laurentbfb1b832013-01-07 09:53:42 -08003709 if (mBytesRemaining == 0) {
3710 mCurrentWriteLength = 0;
3711 if (mMixerStatus == MIXER_TRACKS_READY) {
3712 // threadLoop_mix() sets mCurrentWriteLength
3713 threadLoop_mix();
3714 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
3715 && (mMixerStatus != MIXER_DRAIN_ALL)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003716 // threadLoop_sleepTime sets mSleepTimeUs to 0 if data
Eric Laurentbfb1b832013-01-07 09:53:42 -08003717 // must be written to HAL
3718 threadLoop_sleepTime();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003719 if (mSleepTimeUs == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08003720 mCurrentWriteLength = mSinkBufferSize;
Andy Hungc1646382019-04-30 16:12:10 -07003721
3722 // Tally underrun frames as we are inserting 0s here.
3723 for (const auto& track : activeTracks) {
Andy Hunge2e830f2019-12-03 12:54:46 -08003724 if (track->mFillingUpStatus == Track::FS_ACTIVE
3725 && !track->isStopped()
3726 && !track->isPaused()
3727 && !track->isTerminated()) {
3728 ALOGV("%s: track(%d) %s underrun due to thread sleep of %zu frames",
3729 __func__, track->id(), track->getTrackStateAsString(),
3730 mNormalFrameCount);
Andy Hungc1646382019-04-30 16:12:10 -07003731 track->mAudioTrackServerProxy->tallyUnderrunFrames(mNormalFrameCount);
3732 }
3733 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003734 }
3735 }
Andy Hung98ef9782014-03-04 14:46:50 -08003736 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003737 // mMixerBuffer with data if mMixerBufferValid is true and mSleepTimeUs == 0.
Andy Hung98ef9782014-03-04 14:46:50 -08003738 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
3739 // or mSinkBuffer (if there are no effects).
3740 //
3741 // This is done pre-effects computation; if effects change to
3742 // support higher precision, this needs to move.
3743 //
3744 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003745 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08003746 if (mMixerBufferValid) {
3747 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
3748 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
3749
Andy Hung2ddee192015-12-18 17:34:44 -08003750 // mono blend occurs for mixer threads only (not direct or offloaded)
3751 // and is handled here if we're going directly to the sink.
3752 if (requireMonoBlend() && !mEffectBufferValid) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003753 mono_blend(mMixerBuffer, mMixerBufferFormat, mChannelCount, mNormalFrameCount,
3754 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003755 }
3756
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01003757 if (!hasFastMixer()) {
3758 // Balance must take effect after mono conversion.
3759 // We do it here if there is no FastMixer.
3760 // mBalance detects zero balance within the class for speed (not needed here).
3761 mBalance.setBalance(mMasterBalance.load());
3762 mBalance.process((float *)mMixerBuffer, mNormalFrameCount);
3763 }
3764
Andy Hung98ef9782014-03-04 14:46:50 -08003765 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
jiabin245cdd92018-12-07 17:55:15 -08003766 mNormalFrameCount * (mChannelCount + mHapticChannelCount));
3767
3768 // If we're going directly to the sink and there are haptic channels,
3769 // we should adjust channels as the sample data is partially interleaved
3770 // in this case.
3771 if (!mEffectBufferValid && mHapticChannelCount > 0) {
3772 adjust_channels_non_destructive(buffer, mChannelCount, buffer,
3773 mChannelCount + mHapticChannelCount,
3774 audio_bytes_per_sample(format),
3775 audio_bytes_per_frame(mChannelCount, format) * mNormalFrameCount);
3776 }
Andy Hung98ef9782014-03-04 14:46:50 -08003777 }
3778
Eric Laurentbfb1b832013-01-07 09:53:42 -08003779 mBytesRemaining = mCurrentWriteLength;
3780 if (isSuspended()) {
Andy Hung238fa3d2016-07-28 10:53:22 -07003781 // Simulate write to HAL when suspended (e.g. BT SCO phone call).
3782 mSleepTimeUs = suspendSleepTimeUs(); // assumes full buffer.
3783 const size_t framesRemaining = mBytesRemaining / mFrameSize;
3784 mBytesWritten += mBytesRemaining;
3785 mFramesWritten += framesRemaining;
3786 mSuspendedFrames += framesRemaining; // to adjust kernel HAL position
Eric Laurentbfb1b832013-01-07 09:53:42 -08003787 mBytesRemaining = 0;
3788 }
Eric Laurent81784c32012-11-19 14:55:58 -08003789
Eric Laurentbfb1b832013-01-07 09:53:42 -08003790 // only process effects if we're going to write
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003791 if (mSleepTimeUs == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003792 for (size_t i = 0; i < effectChains.size(); i ++) {
3793 effectChains[i]->process_l();
jiabin47affe52019-04-04 18:02:07 -07003794 // TODO: Write haptic data directly to sink buffer when mixing.
Andy Hung6e6a2e62019-04-30 16:38:41 -07003795 if (activeHapticSessionId != AUDIO_SESSION_NONE
3796 && activeHapticSessionId == effectChains[i]->sessionId()) {
jiabin47affe52019-04-04 18:02:07 -07003797 // Haptic data is active in this case, copy it directly from
3798 // in buffer to out buffer.
3799 const size_t audioBufferSize = mNormalFrameCount
3800 * audio_bytes_per_frame(mChannelCount, EFFECT_BUFFER_FORMAT);
3801 memcpy_by_audio_format(
3802 (uint8_t*)effectChains[i]->outBuffer() + audioBufferSize,
3803 EFFECT_BUFFER_FORMAT,
3804 (const uint8_t*)effectChains[i]->inBuffer() + audioBufferSize,
3805 EFFECT_BUFFER_FORMAT, mNormalFrameCount * mHapticChannelCount);
3806 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003807 }
Eric Laurent81784c32012-11-19 14:55:58 -08003808 }
3809 }
Eric Laurent59fe0102013-09-27 18:48:26 -07003810 // Process effect chains for offloaded thread even if no audio
3811 // was read from audio track: process only updates effect state
3812 // and thus does have to be synchronized with audio writes but may have
3813 // to be called while waiting for async write callback
3814 if (mType == OFFLOAD) {
3815 for (size_t i = 0; i < effectChains.size(); i ++) {
3816 effectChains[i]->process_l();
3817 }
3818 }
Eric Laurent81784c32012-11-19 14:55:58 -08003819
Andy Hung98ef9782014-03-04 14:46:50 -08003820 // Only if the Effects buffer is enabled and there is data in the
3821 // Effects buffer (buffer valid), we need to
3822 // copy into the sink buffer.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003823 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08003824 if (mEffectBufferValid) {
3825 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
Andy Hung2ddee192015-12-18 17:34:44 -08003826
3827 if (requireMonoBlend()) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003828 mono_blend(mEffectBuffer, mEffectBufferFormat, mChannelCount, mNormalFrameCount,
3829 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003830 }
3831
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01003832 if (!hasFastMixer()) {
3833 // Balance must take effect after mono conversion.
3834 // We do it here if there is no FastMixer.
3835 // mBalance detects zero balance within the class for speed (not needed here).
3836 mBalance.setBalance(mMasterBalance.load());
3837 mBalance.process((float *)mEffectBuffer, mNormalFrameCount);
3838 }
3839
Andy Hung98ef9782014-03-04 14:46:50 -08003840 memcpy_by_audio_format(mSinkBuffer, mFormat, mEffectBuffer, mEffectBufferFormat,
jiabin245cdd92018-12-07 17:55:15 -08003841 mNormalFrameCount * (mChannelCount + mHapticChannelCount));
3842 // The sample data is partially interleaved when haptic channels exist,
3843 // we need to adjust channels here.
3844 if (mHapticChannelCount > 0) {
3845 adjust_channels_non_destructive(mSinkBuffer, mChannelCount, mSinkBuffer,
3846 mChannelCount + mHapticChannelCount,
3847 audio_bytes_per_sample(mFormat),
3848 audio_bytes_per_frame(mChannelCount, mFormat) * mNormalFrameCount);
3849 }
Andy Hung98ef9782014-03-04 14:46:50 -08003850 }
3851
Eric Laurent81784c32012-11-19 14:55:58 -08003852 // enable changes in effect chain
3853 unlockEffectChains(effectChains);
3854
Eric Laurentbfb1b832013-01-07 09:53:42 -08003855 if (!waitingAsyncCallback()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003856 // mSleepTimeUs == 0 means we must write to audio hardware
3857 if (mSleepTimeUs == 0) {
Andy Hung08fb1742015-05-31 23:22:10 -07003858 ssize_t ret = 0;
Andy Hung446f4df2019-02-21 12:26:41 -08003859 // writePeriodNs is updated >= 0 when ret > 0.
3860 int64_t writePeriodNs = -1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003861 if (mBytesRemaining) {
Andy Hung69488c42016-05-16 18:43:33 -07003862 // FIXME rewrite to reduce number of system calls
Andy Hung446f4df2019-02-21 12:26:41 -08003863 const int64_t lastIoBeginNs = systemTime();
Andy Hung08fb1742015-05-31 23:22:10 -07003864 ret = threadLoop_write();
Andy Hung446f4df2019-02-21 12:26:41 -08003865 const int64_t lastIoEndNs = systemTime();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003866 if (ret < 0) {
3867 mBytesRemaining = 0;
Andy Hung446f4df2019-02-21 12:26:41 -08003868 } else if (ret > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003869 mBytesWritten += ret;
3870 mBytesRemaining -= ret;
Andy Hung446f4df2019-02-21 12:26:41 -08003871 const int64_t frames = ret / mFrameSize;
3872 mFramesWritten += frames;
3873
3874 writePeriodNs = lastIoEndNs - mLastIoEndNs;
3875 // process information relating to write time.
3876 if (audio_has_proportional_frames(mFormat)) {
3877 // we are in a continuous mixing cycle
3878 if (mMixerStatus == MIXER_TRACKS_READY &&
3879 loopCount == lastLoopCountWritten + 1) {
3880
3881 const double jitterMs =
3882 TimestampVerifier<int64_t, int64_t>::computeJitterMs(
3883 {frames, writePeriodNs},
3884 {0, 0} /* lastTimestamp */, mSampleRate);
3885 const double processMs =
3886 (lastIoBeginNs - mLastIoEndNs) * 1e-6;
3887
3888 Mutex::Autolock _l(mLock);
3889 mIoJitterMs.add(jitterMs);
3890 mProcessTimeMs.add(processMs);
3891 }
3892
3893 // write blocked detection
3894 const int64_t deltaWriteNs = lastIoEndNs - lastIoBeginNs;
3895 if (mType == MIXER && deltaWriteNs > maxPeriod) {
3896 mNumDelayedWrites++;
3897 if ((lastIoEndNs - lastWarning) > kWarningThrottleNs) {
3898 ATRACE_NAME("underrun");
3899 ALOGW("write blocked for %lld msecs, "
3900 "%d delayed writes, thread %d",
3901 (long long)deltaWriteNs / NANOS_PER_MILLISECOND,
3902 mNumDelayedWrites, mId);
3903 lastWarning = lastIoEndNs;
3904 }
3905 }
3906 }
3907 // update timing info.
3908 mLastIoBeginNs = lastIoBeginNs;
3909 mLastIoEndNs = lastIoEndNs;
3910 lastLoopCountWritten = loopCount;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003911 }
3912 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
3913 (mMixerStatus == MIXER_DRAIN_ALL)) {
3914 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08003915 }
Andy Hung08fb1742015-05-31 23:22:10 -07003916 if (mType == MIXER && !mStandby) {
Andy Hung08fb1742015-05-31 23:22:10 -07003917
3918 if (mThreadThrottle
3919 && mMixerStatus == MIXER_TRACKS_READY // we are mixing (active tracks)
Andy Hung446f4df2019-02-21 12:26:41 -08003920 && writePeriodNs > 0) { // we have write period info
Andy Hung08fb1742015-05-31 23:22:10 -07003921 // Limit MixerThread data processing to no more than twice the
3922 // expected processing rate.
3923 //
3924 // This helps prevent underruns with NuPlayer and other applications
3925 // which may set up buffers that are close to the minimum size, or use
3926 // deep buffers, and rely on a double-buffering sleep strategy to fill.
3927 //
3928 // The throttle smooths out sudden large data drains from the device,
3929 // e.g. when it comes out of standby, which often causes problems with
3930 // (1) mixer threads without a fast mixer (which has its own warm-up)
3931 // (2) minimum buffer sized tracks (even if the track is full,
3932 // the app won't fill fast enough to handle the sudden draw).
Haynes Mathew Georgef92b2172016-05-09 11:34:15 -07003933 //
3934 // Total time spent in last processing cycle equals time spent in
3935 // 1. threadLoop_write, as well as time spent in
3936 // 2. threadLoop_mix (significant for heavy mixing, especially
3937 // on low tier processors)
Andy Hung08fb1742015-05-31 23:22:10 -07003938
Andy Hung446f4df2019-02-21 12:26:41 -08003939 // it's OK if deltaMs is an overestimate.
3940
3941 const int32_t deltaMs = writePeriodNs / NANOS_PER_MILLISECOND;
Ivan Lozanoe02bc542017-10-26 09:51:54 -07003942
Ivan Lozanoea04d392017-11-07 14:37:07 -08003943 const int32_t throttleMs = (int32_t)mHalfBufferMs - deltaMs;
Andy Hung08fb1742015-05-31 23:22:10 -07003944 if ((signed)mHalfBufferMs >= throttleMs && throttleMs > 0) {
Andy Hungcf10d742020-04-28 15:38:24 -07003945 mThreadMetrics.logThrottleMs((double)throttleMs);
Andy Hungb68f5eb2019-12-03 16:49:17 -08003946
Andy Hung08fb1742015-05-31 23:22:10 -07003947 usleep(throttleMs * 1000);
Andy Hung40eb1a12015-06-18 13:42:02 -07003948 // notify of throttle start on verbose log
3949 ALOGV_IF(mThreadThrottleEndMs == mThreadThrottleTimeMs,
3950 "mixer(%p) throttle begin:"
3951 " ret(%zd) deltaMs(%d) requires sleep %d ms",
Andy Hung08fb1742015-05-31 23:22:10 -07003952 this, ret, deltaMs, throttleMs);
Andy Hung40eb1a12015-06-18 13:42:02 -07003953 mThreadThrottleTimeMs += throttleMs;
Andy Hung0a31ddd2016-07-06 19:10:29 -07003954 // Throttle must be attributed to the previous mixer loop's write time
3955 // to allow back-to-back throttling.
Andy Hung446f4df2019-02-21 12:26:41 -08003956 // This also ensures proper timing statistics.
3957 mLastIoEndNs = systemTime(); // we fetch the write end time again.
Andy Hung40eb1a12015-06-18 13:42:02 -07003958 } else {
3959 uint32_t diff = mThreadThrottleTimeMs - mThreadThrottleEndMs;
3960 if (diff > 0) {
3961 // notify of throttle end on debug log
Andy Hung3ea004d2016-05-05 16:48:37 -07003962 // but prevent spamming for bluetooth
jiabinc52b1ff2019-10-31 17:20:42 -07003963 ALOGD_IF(!isSingleDeviceType(
3964 outDeviceTypes(), audio_is_a2dp_out_device) &&
3965 !isSingleDeviceType(
3966 outDeviceTypes(), audio_is_hearing_aid_out_device),
Andy Hung3ea004d2016-05-05 16:48:37 -07003967 "mixer(%p) throttle end: throttle time(%u)", this, diff);
Andy Hung40eb1a12015-06-18 13:42:02 -07003968 mThreadThrottleEndMs = mThreadThrottleTimeMs;
3969 }
Andy Hung08fb1742015-05-31 23:22:10 -07003970 }
3971 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003972 }
Eric Laurent81784c32012-11-19 14:55:58 -08003973
Eric Laurentbfb1b832013-01-07 09:53:42 -08003974 } else {
Glenn Kastene7754022014-10-31 12:11:26 -07003975 ATRACE_BEGIN("sleep");
Eric Laurente93cc032016-05-05 10:15:10 -07003976 Mutex::Autolock _l(mLock);
rago1bb90822017-05-02 18:31:48 -07003977 // suspended requires accurate metering of sleep time.
3978 if (isSuspended()) {
3979 // advance by expected sleepTime
3980 timeLoopNextNs += microseconds((nsecs_t)mSleepTimeUs);
3981 const nsecs_t nowNs = systemTime();
3982
3983 // compute expected next time vs current time.
3984 // (negative deltas are treated as delays).
3985 nsecs_t deltaNs = timeLoopNextNs - nowNs;
3986 if (deltaNs < -kMaxNextBufferDelayNs) {
3987 // Delays longer than the max allowed trigger a reset.
3988 ALOGV("DelayNs: %lld, resetting timeLoopNextNs", (long long) deltaNs);
3989 deltaNs = microseconds((nsecs_t)mSleepTimeUs);
3990 timeLoopNextNs = nowNs + deltaNs;
3991 } else if (deltaNs < 0) {
3992 // Delays within the max delay allowed: zero the delta/sleepTime
3993 // to help the system catch up in the next iteration(s)
3994 ALOGV("DelayNs: %lld, catching-up", (long long) deltaNs);
3995 deltaNs = 0;
3996 }
3997 // update sleep time (which is >= 0)
3998 mSleepTimeUs = deltaNs / 1000;
3999 }
Eric Laurente93cc032016-05-05 10:15:10 -07004000 if (!mSignalPending && mConfigEvents.isEmpty() && !exitPending()) {
4001 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)mSleepTimeUs));
Eric Laurent51716182016-02-29 18:00:56 -08004002 }
Glenn Kastene7754022014-10-31 12:11:26 -07004003 ATRACE_END();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004004 }
Eric Laurent81784c32012-11-19 14:55:58 -08004005 }
4006
4007 // Finally let go of removed track(s), without the lock held
4008 // since we can't guarantee the destructors won't acquire that
4009 // same lock. This will also mutate and push a new fast mixer state.
4010 threadLoop_removeTracks(tracksToRemove);
4011 tracksToRemove.clear();
4012
4013 // FIXME I don't understand the need for this here;
4014 // it was in the original code but maybe the
4015 // assignment in saveOutputTracks() makes this unnecessary?
4016 clearOutputTracks();
4017
4018 // Effect chains will be actually deleted here if they were removed from
4019 // mEffectChains list during mixing or effects processing
4020 effectChains.clear();
4021
4022 // FIXME Note that the above .clear() is no longer necessary since effectChains
4023 // is now local to this block, but will keep it for now (at least until merge done).
4024 }
4025
Eric Laurentbfb1b832013-01-07 09:53:42 -08004026 threadLoop_exit();
4027
Eric Laurentcf817a22014-08-04 20:36:31 -07004028 if (!mStandby) {
4029 threadLoop_standby();
4030 mStandby = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004031 }
4032
4033 releaseWakeLock();
4034
4035 ALOGV("Thread %p type %d exiting", this, mType);
4036 return false;
4037}
4038
Dean Wheatley12473e92021-03-18 23:00:55 +11004039void AudioFlinger::PlaybackThread::collectTimestamps_l()
4040{
4041 // Collect timestamp statistics for the Playback Thread types that support it.
4042 if (mType != MIXER
4043 && mType != DUPLICATING
4044 && mType != DIRECT
4045 && mType != OFFLOAD) {
4046 return;
4047 }
4048 if (mStandby) {
4049 mTimestampVerifier.discontinuity(discontinuityForStandbyOrFlush());
4050 return;
4051 } else if (mHwPaused) {
4052 mTimestampVerifier.discontinuity(mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS);
4053 return;
4054 }
4055
4056 // Gather the framesReleased counters for all active tracks,
4057 // and associate with the sink frames written out. We need
4058 // this to convert the sink timestamp to the track timestamp.
4059 bool kernelLocationUpdate = false;
4060 ExtendedTimestamp timestamp; // use private copy to fetch
4061
4062 // Always query HAL timestamp and update timestamp verifier. In standby or pause,
4063 // HAL may be draining some small duration buffered data for fade out.
4064 if (threadloop_getHalTimestamp_l(&timestamp) == OK) {
4065 mTimestampVerifier.add(timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL],
4066 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4067 mSampleRate);
4068
4069 if (isTimestampCorrectionEnabled()) {
4070 ALOGVV("TS_BEFORE: %d %lld %lld", id(),
4071 (long long)timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4072 (long long)timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]);
4073 auto correctedTimestamp = mTimestampVerifier.getLastCorrectedTimestamp();
4074 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4075 = correctedTimestamp.mFrames;
4076 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]
4077 = correctedTimestamp.mTimeNs;
4078 ALOGVV("TS_AFTER: %d %lld %lld", id(),
4079 (long long)timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4080 (long long)timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]);
4081
4082 // Note: Downstream latency only added if timestamp correction enabled.
4083 if (mDownstreamLatencyStatMs.getN() > 0) { // we have latency info.
4084 const int64_t newPosition =
4085 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4086 - int64_t(mDownstreamLatencyStatMs.getMean() * mSampleRate * 1e-3);
4087 // prevent retrograde
4088 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = max(
4089 newPosition,
4090 (mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4091 - mSuspendedFrames));
4092 }
4093 }
4094
4095 // We always fetch the timestamp here because often the downstream
4096 // sink will block while writing.
4097
4098 // We keep track of the last valid kernel position in case we are in underrun
4099 // and the normal mixer period is the same as the fast mixer period, or there
4100 // is some error from the HAL.
4101 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
4102 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
4103 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
4104 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
4105 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4106
4107 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
4108 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER];
4109 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
4110 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER];
4111 }
4112
4113 if (timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
4114 kernelLocationUpdate = true;
4115 } else {
4116 ALOGVV("getTimestamp error - no valid kernel position");
4117 }
4118
4119 // copy over kernel info
4120 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] =
4121 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4122 + mSuspendedFrames; // add frames discarded when suspended
4123 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] =
4124 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4125 } else {
4126 mTimestampVerifier.error();
4127 }
4128
4129 // mFramesWritten for non-offloaded tracks are contiguous
4130 // even after standby() is called. This is useful for the track frame
4131 // to sink frame mapping.
4132 bool serverLocationUpdate = false;
4133 if (mFramesWritten != mLastFramesWritten) {
4134 serverLocationUpdate = true;
4135 mLastFramesWritten = mFramesWritten;
4136 }
4137 // Only update timestamps if there is a meaningful change.
4138 // Either the kernel timestamp must be valid or we have written something.
4139 if (kernelLocationUpdate || serverLocationUpdate) {
4140 if (serverLocationUpdate) {
4141 // use the time before we called the HAL write - it is a bit more accurate
4142 // to when the server last read data than the current time here.
4143 //
4144 // If we haven't written anything, mLastIoBeginNs will be -1
4145 // and we use systemTime().
4146 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] = mFramesWritten;
4147 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = mLastIoBeginNs == -1
4148 ? systemTime() : mLastIoBeginNs;
4149 }
4150
4151 for (const sp<Track> &t : mActiveTracks) {
4152 if (!t->isFastTrack()) {
4153 t->updateTrackFrameInfo(
4154 t->mAudioTrackServerProxy->framesReleased(),
4155 mFramesWritten,
4156 mSampleRate,
4157 mTimestamp);
4158 }
4159 }
4160 }
4161
4162 if (audio_has_proportional_frames(mFormat)) {
4163 const double latencyMs = mTimestamp.getOutputServerLatencyMs(mSampleRate);
4164 if (latencyMs != 0.) { // note 0. means timestamp is empty.
4165 mLatencyMs.add(latencyMs);
4166 }
4167 }
4168#if 0
4169 // logFormat example
4170 if (z % 100 == 0) {
4171 timespec ts;
4172 clock_gettime(CLOCK_MONOTONIC, &ts);
4173 LOGT("This is an integer %d, this is a float %f, this is my "
4174 "pid %p %% %s %t", 42, 3.14, "and this is a timestamp", ts);
4175 LOGT("A deceptive null-terminated string %\0");
4176 }
4177 ++z;
4178#endif
4179}
4180
Eric Laurentbfb1b832013-01-07 09:53:42 -08004181// removeTracks_l() must be called with ThreadBase::mLock held
4182void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
4183{
Andy Hungfe726a62018-09-27 15:17:25 -07004184 for (const auto& track : tracksToRemove) {
4185 mActiveTracks.remove(track);
4186 ALOGV("%s(%d): removing track on session %d", __func__, track->id(), track->sessionId());
4187 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
4188 if (chain != 0) {
4189 ALOGV("%s(%d): stopping track on chain %p for session Id: %d",
4190 __func__, track->id(), chain.get(), track->sessionId());
4191 chain->decActiveTrackCnt();
4192 }
4193 // If an external client track, inform APM we're no longer active, and remove if needed.
4194 // We do this under lock so that the state is consistent if the Track is destroyed.
4195 if (track->isExternalTrack()) {
4196 AudioSystem::stopOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08004197 if (track->isTerminated()) {
Andy Hungfe726a62018-09-27 15:17:25 -07004198 AudioSystem::releaseOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08004199 }
4200 }
Andy Hungfe726a62018-09-27 15:17:25 -07004201 if (track->isTerminated()) {
4202 // remove from our tracks vector
4203 removeTrack_l(track);
4204 }
jiabineb3bda02020-06-30 14:07:03 -07004205 if (mHapticChannelCount > 0 &&
4206 ((track->channelMask() & AUDIO_CHANNEL_HAPTIC_ALL) != AUDIO_CHANNEL_NONE
4207 || (chain != nullptr && chain->containsHapticGeneratingEffect_l()))) {
jiabin57303cc2018-12-18 15:45:57 -08004208 mLock.unlock();
4209 // Unlock due to VibratorService will lock for this call and will
4210 // call Tracks.mute/unmute which also require thread's lock.
4211 AudioFlinger::onExternalVibrationStop(track->getExternalVibration());
4212 mLock.lock();
jiabine70bc7f2020-06-30 22:07:55 -07004213
4214 // When the track is stop, set the haptic intensity as MUTE
4215 // for the HapticGenerator effect.
4216 if (chain != nullptr) {
4217 chain->setHapticIntensity_l(track->id(), static_cast<int>(os::HapticScale::MUTE));
4218 }
jiabin245cdd92018-12-07 17:55:15 -08004219 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004220 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004221}
Eric Laurent81784c32012-11-19 14:55:58 -08004222
Eric Laurentaccc1472013-09-20 09:36:34 -07004223status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
4224{
4225 if (mNormalSink != 0) {
Andy Hung818e7a32016-02-16 18:08:07 -08004226 ExtendedTimestamp ets;
4227 status_t status = mNormalSink->getTimestamp(ets);
4228 if (status == NO_ERROR) {
4229 status = ets.getBestTimestamp(&timestamp);
4230 }
4231 return status;
Eric Laurentaccc1472013-09-20 09:36:34 -07004232 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004233 if ((mType == OFFLOAD || mType == DIRECT) && mOutput != NULL) {
Dean Wheatley12473e92021-03-18 23:00:55 +11004234 collectTimestamps_l();
4235 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] <= 0) {
4236 return INVALID_OPERATION;
Eric Laurentaccc1472013-09-20 09:36:34 -07004237 }
Dean Wheatley12473e92021-03-18 23:00:55 +11004238 timestamp.mPosition = mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
4239 const int64_t timeNs = mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4240 timestamp.mTime.tv_sec = timeNs / NANOS_PER_SECOND;
4241 timestamp.mTime.tv_nsec = timeNs - (timestamp.mTime.tv_sec * NANOS_PER_SECOND);
4242 return NO_ERROR;
Eric Laurentaccc1472013-09-20 09:36:34 -07004243 }
4244 return INVALID_OPERATION;
4245}
Eric Laurent1c333e22014-05-20 10:48:17 -07004246
Eric Laurenteab90452019-06-24 15:17:46 -07004247// For dedicated VoIP outputs, let the HAL apply the stream volume. Track volume is
4248// still applied by the mixer.
4249// All tracks attached to a mixer with flag VOIP_RX are tied to the same
4250// stream type STREAM_VOICE_CALL so this will only change the HAL volume once even
4251// if more than one track are active
4252status_t AudioFlinger::PlaybackThread::handleVoipVolume_l(float *volume)
4253{
4254 status_t result = NO_ERROR;
4255 if ((mOutput->flags & AUDIO_OUTPUT_FLAG_VOIP_RX) != 0) {
4256 if (*volume != mLeftVolFloat) {
4257 result = mOutput->stream->setVolume(*volume, *volume);
4258 ALOGE_IF(result != OK,
4259 "Error when setting output stream volume: %d", result);
4260 if (result == NO_ERROR) {
4261 mLeftVolFloat = *volume;
4262 }
4263 }
4264 // if stream volume was successfully sent to the HAL, mLeftVolFloat == v here and we
4265 // remove stream volume contribution from software volume.
4266 if (mLeftVolFloat == *volume) {
4267 *volume = 1.0f;
4268 }
4269 }
4270 return result;
4271}
4272
Eric Laurent054d9d32015-04-24 08:48:48 -07004273status_t AudioFlinger::MixerThread::createAudioPatch_l(const struct audio_patch *patch,
4274 audio_patch_handle_t *handle)
4275{
Andy Hungf60abce2016-08-26 11:37:54 -07004276 status_t status;
4277 if (property_get_bool("af.patch_park", false /* default_value */)) {
4278 // Park FastMixer to avoid potential DOS issues with writing to the HAL
4279 // or if HAL does not properly lock against access.
4280 AutoPark<FastMixer> park(mFastMixer);
4281 status = PlaybackThread::createAudioPatch_l(patch, handle);
4282 } else {
4283 status = PlaybackThread::createAudioPatch_l(patch, handle);
4284 }
Eric Laurent054d9d32015-04-24 08:48:48 -07004285 return status;
4286}
4287
Eric Laurent1c333e22014-05-20 10:48:17 -07004288status_t AudioFlinger::PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
4289 audio_patch_handle_t *handle)
4290{
4291 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07004292
4293 // store new device and send to effects
4294 audio_devices_t type = AUDIO_DEVICE_NONE;
jiabinc52b1ff2019-10-31 17:20:42 -07004295 AudioDeviceTypeAddrVector deviceTypeAddrs;
Eric Laurent054d9d32015-04-24 08:48:48 -07004296 for (unsigned int i = 0; i < patch->num_sinks; i++) {
jiabinc52b1ff2019-10-31 17:20:42 -07004297 LOG_ALWAYS_FATAL_IF(popcount(patch->sinks[i].ext.device.type) > 1
4298 && !mOutput->audioHwDev->supportsAudioPatches(),
4299 "Enumerated device type(%#x) must not be used "
4300 "as it does not support audio patches",
4301 patch->sinks[i].ext.device.type);
Mikhail Naganov55773032020-10-01 15:08:13 -07004302 type = static_cast<audio_devices_t>(type | patch->sinks[i].ext.device.type);
jiabinc52b1ff2019-10-31 17:20:42 -07004303 deviceTypeAddrs.push_back(AudioDeviceTypeAddr(patch->sinks[i].ext.device.type,
4304 patch->sinks[i].ext.device.address));
Eric Laurent054d9d32015-04-24 08:48:48 -07004305 }
4306
François Gaffie0c280aa2018-07-25 10:02:15 +02004307 audio_port_handle_t sinkPortId = patch->sinks[0].id;
Eric Laurent054d9d32015-04-24 08:48:48 -07004308#ifdef ADD_BATTERY_DATA
4309 // when changing the audio output device, call addBatteryData to notify
4310 // the change
jiabinc52b1ff2019-10-31 17:20:42 -07004311 if (outDeviceTypes() != deviceTypes) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004312 uint32_t params = 0;
4313 // check whether speaker is on
jiabinc52b1ff2019-10-31 17:20:42 -07004314 if (deviceTypes.count(AUDIO_DEVICE_OUT_SPEAKER) > 0) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004315 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent1c333e22014-05-20 10:48:17 -07004316 }
4317
Eric Laurent054d9d32015-04-24 08:48:48 -07004318 // check if any other device (except speaker) is on
jiabinc52b1ff2019-10-31 17:20:42 -07004319 if (!isSingleDeviceType(deviceTypes, AUDIO_DEVICE_OUT_SPEAKER)) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004320 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
4321 }
4322
4323 if (params != 0) {
4324 addBatteryData(params);
4325 }
4326 }
4327#endif
4328
4329 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08004330 mEffectChains[i]->setDevices_l(deviceTypeAddrs);
Eric Laurent054d9d32015-04-24 08:48:48 -07004331 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07004332
jiabinc52b1ff2019-10-31 17:20:42 -07004333 // mPatch.num_sinks is not set when the thread is created so that
4334 // the first patch creation triggers an ioConfigChanged callback
4335 bool configChanged = (mPatch.num_sinks == 0) ||
4336 (mPatch.sinks[0].id != sinkPortId);
Eric Laurent296fb132015-05-01 11:38:42 -07004337 mPatch = *patch;
jiabinc52b1ff2019-10-31 17:20:42 -07004338 mOutDeviceTypeAddrs = deviceTypeAddrs;
jiabin0a957d32020-04-29 10:56:20 -07004339 checkSilentMode_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07004340
Mikhail Naganov9ee05402016-10-13 15:58:17 -07004341 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07004342 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
4343 status = hwDevice->createAudioPatch(patch->num_sources,
4344 patch->sources,
4345 patch->num_sinks,
4346 patch->sinks,
4347 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07004348 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07004349 char *address;
4350 if (strcmp(patch->sinks[0].ext.device.address, "") != 0) {
4351 //FIXME: we only support address on first sink with HAL version < 3.0
4352 address = audio_device_address_to_parameter(
4353 patch->sinks[0].ext.device.type,
4354 patch->sinks[0].ext.device.address);
4355 } else {
4356 address = (char *)calloc(1, 1);
4357 }
4358 AudioParameter param = AudioParameter(String8(address));
4359 free(address);
Mikhail Naganov00260b52016-10-13 12:54:24 -07004360 param.addInt(String8(AudioParameter::keyRouting), (int)type);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004361 status = mOutput->stream->setParameters(param.toString());
Eric Laurent054d9d32015-04-24 08:48:48 -07004362 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07004363 }
Andy Hungc2b11cb2020-04-22 09:04:01 -07004364 const std::string patchSinksAsString = patchSinksToString(patch);
Andy Hungcf10d742020-04-28 15:38:24 -07004365
4366 mThreadMetrics.logEndInterval();
Andy Hungea840382020-05-05 21:50:17 -07004367 mThreadMetrics.logCreatePatch(/* inDevices */ {}, patchSinksAsString);
Andy Hungcf10d742020-04-28 15:38:24 -07004368 mThreadMetrics.logBeginInterval();
Andy Hungc2b11cb2020-04-22 09:04:01 -07004369 // also dispatch to active AudioTracks for MediaMetrics
4370 for (const auto &track : mActiveTracks) {
4371 track->logEndInterval();
4372 track->logBeginInterval(patchSinksAsString);
4373 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08004374
Eric Laurente8726fe2015-06-26 09:39:24 -07004375 if (configChanged) {
4376 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
4377 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004378 return status;
4379}
4380
Eric Laurent054d9d32015-04-24 08:48:48 -07004381status_t AudioFlinger::MixerThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
4382{
Andy Hungf60abce2016-08-26 11:37:54 -07004383 status_t status;
4384 if (property_get_bool("af.patch_park", false /* default_value */)) {
4385 // Park FastMixer to avoid potential DOS issues with writing to the HAL
4386 // or if HAL does not properly lock against access.
4387 AutoPark<FastMixer> park(mFastMixer);
4388 status = PlaybackThread::releaseAudioPatch_l(handle);
4389 } else {
4390 status = PlaybackThread::releaseAudioPatch_l(handle);
4391 }
Eric Laurent054d9d32015-04-24 08:48:48 -07004392 return status;
4393}
4394
Eric Laurent1c333e22014-05-20 10:48:17 -07004395status_t AudioFlinger::PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
4396{
4397 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07004398
jiabinc52b1ff2019-10-31 17:20:42 -07004399 mPatch = audio_patch{};
4400 mOutDeviceTypeAddrs.clear();
Eric Laurent054d9d32015-04-24 08:48:48 -07004401
Mikhail Naganov9ee05402016-10-13 15:58:17 -07004402 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07004403 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
4404 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07004405 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07004406 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07004407 param.addInt(String8(AudioParameter::keyRouting), 0);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004408 status = mOutput->stream->setParameters(param.toString());
Eric Laurent1c333e22014-05-20 10:48:17 -07004409 }
4410 return status;
4411}
4412
Eric Laurent83b88082014-06-20 18:31:16 -07004413void AudioFlinger::PlaybackThread::addPatchTrack(const sp<PatchTrack>& track)
4414{
4415 Mutex::Autolock _l(mLock);
4416 mTracks.add(track);
4417}
4418
4419void AudioFlinger::PlaybackThread::deletePatchTrack(const sp<PatchTrack>& track)
4420{
4421 Mutex::Autolock _l(mLock);
4422 destroyTrack_l(track);
4423}
4424
Mikhail Naganovdc769682018-05-04 15:34:08 -07004425void AudioFlinger::PlaybackThread::toAudioPortConfig(struct audio_port_config *config)
Eric Laurent83b88082014-06-20 18:31:16 -07004426{
Mikhail Naganovdc769682018-05-04 15:34:08 -07004427 ThreadBase::toAudioPortConfig(config);
Eric Laurent83b88082014-06-20 18:31:16 -07004428 config->role = AUDIO_PORT_ROLE_SOURCE;
4429 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
4430 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07004431 if (mOutput && mOutput->flags != AUDIO_OUTPUT_FLAG_NONE) {
4432 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
4433 config->flags.output = mOutput->flags;
4434 }
Eric Laurent83b88082014-06-20 18:31:16 -07004435}
4436
Eric Laurent81784c32012-11-19 14:55:58 -08004437// ----------------------------------------------------------------------------
4438
4439AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
jiabinc52b1ff2019-10-31 17:20:42 -07004440 audio_io_handle_t id, bool systemReady, type_t type)
4441 : PlaybackThread(audioFlinger, output, id, type, systemReady),
Eric Laurent81784c32012-11-19 14:55:58 -08004442 // mAudioMixer below
4443 // mFastMixer below
Andy Hung2ddee192015-12-18 17:34:44 -08004444 mFastMixerFutex(0),
4445 mMasterMono(false)
Eric Laurent81784c32012-11-19 14:55:58 -08004446 // mOutputSink below
4447 // mPipeSink below
4448 // mNormalSink below
4449{
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01004450 setMasterBalance(audioFlinger->getMasterBalance_l());
jiabinc52b1ff2019-10-31 17:20:42 -07004451 ALOGV("MixerThread() id=%d type=%d", id, type);
Glenn Kasten49f36ba2017-12-06 13:02:02 -08004452 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%#x, mFrameSize=%zu, "
Glenn Kastenc42e9b42016-03-21 11:35:03 -07004453 "mFrameCount=%zu, mNormalFrameCount=%zu",
Eric Laurent81784c32012-11-19 14:55:58 -08004454 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
4455 mNormalFrameCount);
4456 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
4457
Andy Hungfbfc3952015-01-15 13:33:51 -08004458 if (type == DUPLICATING) {
4459 // The Duplicating thread uses the AudioMixer and delivers data to OutputTracks
4460 // (downstream MixerThreads) in DuplicatingThread::threadLoop_write().
4461 // Do not create or use mFastMixer, mOutputSink, mPipeSink, or mNormalSink.
4462 return;
4463 }
Eric Laurent81784c32012-11-19 14:55:58 -08004464 // create an NBAIO sink for the HAL output stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07004465 mOutputSink = new AudioStreamOutSink(output->stream);
Eric Laurent81784c32012-11-19 14:55:58 -08004466 size_t numCounterOffers = 0;
jiabin245cdd92018-12-07 17:55:15 -08004467 const NBAIO_Format offers[1] = {Format_from_SR_C(
4468 mSampleRate, mChannelCount + mHapticChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07004469#if !LOG_NDEBUG
4470 ssize_t index =
4471#else
4472 (void)
4473#endif
4474 mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08004475 ALOG_ASSERT(index == 0);
4476
4477 // initialize fast mixer depending on configuration
4478 bool initFastMixer;
4479 switch (kUseFastMixer) {
4480 case FastMixer_Never:
4481 initFastMixer = false;
4482 break;
4483 case FastMixer_Always:
4484 initFastMixer = true;
4485 break;
4486 case FastMixer_Static:
4487 case FastMixer_Dynamic:
Andy Hungfda69402017-02-15 14:33:12 -08004488 // FastMixer was designed to operate with a HAL that pulls at a regular rate,
4489 // where the period is less than an experimentally determined threshold that can be
4490 // scheduled reliably with CFS. However, the BT A2DP HAL is
4491 // bursty (does not pull at a regular rate) and so cannot operate with FastMixer.
4492 initFastMixer = mFrameCount < mNormalFrameCount
jiabinc52b1ff2019-10-31 17:20:42 -07004493 && Intersection(outDeviceTypes(), getAudioDeviceOutAllA2dpSet()).empty();
Eric Laurent81784c32012-11-19 14:55:58 -08004494 break;
4495 }
Andy Hungfda69402017-02-15 14:33:12 -08004496 ALOGW_IF(initFastMixer == false && mFrameCount < mNormalFrameCount,
4497 "FastMixer is preferred for this sink as frameCount %zu is less than threshold %zu",
4498 mFrameCount, mNormalFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08004499 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07004500 audio_format_t fastMixerFormat;
4501 if (mMixerBufferEnabled && mEffectBufferEnabled) {
4502 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
4503 } else {
4504 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
4505 }
4506 if (mFormat != fastMixerFormat) {
4507 // change our Sink format to accept our intermediate precision
4508 mFormat = fastMixerFormat;
4509 free(mSinkBuffer);
jiabin245cdd92018-12-07 17:55:15 -08004510 mFrameSize = audio_bytes_per_frame(mChannelCount + mHapticChannelCount, mFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07004511 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
4512 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
4513 }
Eric Laurent81784c32012-11-19 14:55:58 -08004514
4515 // create a MonoPipe to connect our submix to FastMixer
4516 NBAIO_Format format = mOutputSink->format();
Andy Hung8946a282018-04-19 20:04:56 -07004517
Andy Hung1258c1a2014-05-23 21:22:17 -07004518 // adjust format to match that of the Fast Mixer
Glenn Kasten49f36ba2017-12-06 13:02:02 -08004519 ALOGV("format changed from %#x to %#x", format.mFormat, fastMixerFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07004520 format.mFormat = fastMixerFormat;
4521 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
4522
Eric Laurent81784c32012-11-19 14:55:58 -08004523 // This pipe depth compensates for scheduling latency of the normal mixer thread.
4524 // When it wakes up after a maximum latency, it runs a few cycles quickly before
4525 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
4526 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
4527 const NBAIO_Format offers[1] = {format};
4528 size_t numCounterOffers = 0;
Andy Hung8946a282018-04-19 20:04:56 -07004529#if !LOG_NDEBUG
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07004530 ssize_t index =
4531#else
4532 (void)
4533#endif
4534 monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08004535 ALOG_ASSERT(index == 0);
4536 monoPipe->setAvgFrames((mScreenState & 1) ?
4537 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
4538 mPipeSink = monoPipe;
4539
Eric Laurent81784c32012-11-19 14:55:58 -08004540 // create fast mixer and configure it initially with just one fast track for our submix
Andy Hung8946a282018-04-19 20:04:56 -07004541 mFastMixer = new FastMixer(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08004542 FastMixerStateQueue *sq = mFastMixer->sq();
4543#ifdef STATE_QUEUE_DUMP
4544 sq->setObserverDump(&mStateQueueObserverDump);
4545 sq->setMutatorDump(&mStateQueueMutatorDump);
4546#endif
4547 FastMixerState *state = sq->begin();
4548 FastTrack *fastTrack = &state->mFastTracks[0];
4549 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
4550 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
4551 fastTrack->mVolumeProvider = NULL;
Mikhail Naganov55773032020-10-01 15:08:13 -07004552 fastTrack->mChannelMask = static_cast<audio_channel_mask_t>(
4553 mChannelMask | mHapticChannelMask); // mPipeSink channel mask for
4554 // audio to FastMixer
Andy Hunge8a1ced2014-05-09 15:02:21 -07004555 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
jiabin245cdd92018-12-07 17:55:15 -08004556 fastTrack->mHapticPlaybackEnabled = mHapticChannelMask != AUDIO_CHANNEL_NONE;
jiabine70bc7f2020-06-30 22:07:55 -07004557 fastTrack->mHapticIntensity = os::HapticScale::NONE;
Eric Laurent81784c32012-11-19 14:55:58 -08004558 fastTrack->mGeneration++;
4559 state->mFastTracksGen++;
4560 state->mTrackMask = 1;
4561 // fast mixer will use the HAL output sink
4562 state->mOutputSink = mOutputSink.get();
4563 state->mOutputSinkGen++;
4564 state->mFrameCount = mFrameCount;
jiabin245cdd92018-12-07 17:55:15 -08004565 // specify sink channel mask when haptic channel mask present as it can not
4566 // be calculated directly from channel count
4567 state->mSinkChannelMask = mHapticChannelMask == AUDIO_CHANNEL_NONE
Mikhail Naganov55773032020-10-01 15:08:13 -07004568 ? AUDIO_CHANNEL_NONE
4569 : static_cast<audio_channel_mask_t>(mChannelMask | mHapticChannelMask);
Eric Laurent81784c32012-11-19 14:55:58 -08004570 state->mCommand = FastMixerState::COLD_IDLE;
4571 // already done in constructor initialization list
4572 //mFastMixerFutex = 0;
4573 state->mColdFutexAddr = &mFastMixerFutex;
4574 state->mColdGen++;
4575 state->mDumpState = &mFastMixerDumpState;
Glenn Kasten9e58b552013-01-18 15:09:48 -08004576 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
4577 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08004578 sq->end();
4579 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
4580
Eric Tan0513b5d2018-09-17 10:32:48 -07004581 NBLog::thread_info_t info;
4582 info.id = mId;
4583 info.type = NBLog::FASTMIXER;
4584 mFastMixerNBLogWriter->log<NBLog::EVENT_THREAD_INFO>(info);
4585
Eric Laurent81784c32012-11-19 14:55:58 -08004586 // start the fast mixer
4587 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
4588 pid_t tid = mFastMixer->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07004589 sendPrioConfigEvent(getpid(), tid, kPriorityFastMixer, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08004590 stream()->setHalThreadPriority(kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08004591
4592#ifdef AUDIO_WATCHDOG
4593 // create and start the watchdog
4594 mAudioWatchdog = new AudioWatchdog();
4595 mAudioWatchdog->setDump(&mAudioWatchdogDump);
4596 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
4597 tid = mAudioWatchdog->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07004598 sendPrioConfigEvent(getpid(), tid, kPriorityFastMixer, false /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08004599#endif
Andy Hung8946a282018-04-19 20:04:56 -07004600 } else {
4601#ifdef TEE_SINK
4602 // Only use the MixerThread tee if there is no FastMixer.
4603 mTee.set(mOutputSink->format(), NBAIO_Tee::TEE_FLAG_OUTPUT_THREAD);
4604 mTee.setId(std::string("_") + std::to_string(mId) + "_M");
4605#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004606 }
4607
4608 switch (kUseFastMixer) {
4609 case FastMixer_Never:
4610 case FastMixer_Dynamic:
4611 mNormalSink = mOutputSink;
4612 break;
4613 case FastMixer_Always:
4614 mNormalSink = mPipeSink;
4615 break;
4616 case FastMixer_Static:
4617 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
4618 break;
4619 }
4620}
4621
4622AudioFlinger::MixerThread::~MixerThread()
4623{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004624 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004625 FastMixerStateQueue *sq = mFastMixer->sq();
4626 FastMixerState *state = sq->begin();
4627 if (state->mCommand == FastMixerState::COLD_IDLE) {
4628 int32_t old = android_atomic_inc(&mFastMixerFutex);
4629 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07004630 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08004631 }
4632 }
4633 state->mCommand = FastMixerState::EXIT;
4634 sq->end();
4635 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
4636 mFastMixer->join();
4637 // Though the fast mixer thread has exited, it's state queue is still valid.
4638 // We'll use that extract the final state which contains one remaining fast track
4639 // corresponding to our sub-mix.
4640 state = sq->begin();
4641 ALOG_ASSERT(state->mTrackMask == 1);
4642 FastTrack *fastTrack = &state->mFastTracks[0];
4643 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
4644 delete fastTrack->mBufferProvider;
4645 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004646 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08004647#ifdef AUDIO_WATCHDOG
4648 if (mAudioWatchdog != 0) {
4649 mAudioWatchdog->requestExit();
4650 mAudioWatchdog->requestExitAndWait();
4651 mAudioWatchdog.clear();
4652 }
4653#endif
4654 }
Glenn Kasten9e58b552013-01-18 15:09:48 -08004655 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08004656 delete mAudioMixer;
4657}
4658
4659
4660uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
4661{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004662 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004663 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
4664 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
4665 }
4666 return latency;
4667}
4668
Eric Laurentbfb1b832013-01-07 09:53:42 -08004669ssize_t AudioFlinger::MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08004670{
4671 // FIXME we should only do one push per cycle; confirm this is true
4672 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004673 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004674 FastMixerStateQueue *sq = mFastMixer->sq();
4675 FastMixerState *state = sq->begin();
4676 if (state->mCommand != FastMixerState::MIX_WRITE &&
4677 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
4678 if (state->mCommand == FastMixerState::COLD_IDLE) {
Eric Laurenta2ab4502015-09-09 12:25:51 -07004679
4680 // FIXME workaround for first HAL write being CPU bound on some devices
4681 ATRACE_BEGIN("write");
4682 mOutput->write((char *)mSinkBuffer, 0);
4683 ATRACE_END();
4684
Eric Laurent81784c32012-11-19 14:55:58 -08004685 int32_t old = android_atomic_inc(&mFastMixerFutex);
4686 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07004687 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08004688 }
4689#ifdef AUDIO_WATCHDOG
4690 if (mAudioWatchdog != 0) {
4691 mAudioWatchdog->resume();
4692 }
4693#endif
4694 }
4695 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kastend797a9d2015-03-02 14:19:25 -08004696#ifdef FAST_THREAD_STATISTICS
Glenn Kasten4182c4e2013-07-15 14:45:07 -07004697 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08004698 FastThreadDumpState::kSamplingNforLowRamDevice : FastThreadDumpState::kSamplingN);
Glenn Kastend797a9d2015-03-02 14:19:25 -08004699#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004700 sq->end();
4701 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
4702 if (kUseFastMixer == FastMixer_Dynamic) {
4703 mNormalSink = mPipeSink;
4704 }
4705 } else {
4706 sq->end(false /*didModify*/);
4707 }
4708 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004709 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08004710}
4711
4712void AudioFlinger::MixerThread::threadLoop_standby()
4713{
4714 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004715 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004716 FastMixerStateQueue *sq = mFastMixer->sq();
4717 FastMixerState *state = sq->begin();
4718 if (!(state->mCommand & FastMixerState::IDLE)) {
Andy Hung2148bf02016-11-28 19:01:02 -08004719 // Report any frames trapped in the Monopipe
4720 MonoPipe *monoPipe = (MonoPipe *)mPipeSink.get();
4721 const long long pipeFrames = monoPipe->maxFrames() - monoPipe->availableToWrite();
4722 mLocalLog.log("threadLoop_standby: framesWritten:%lld suspendedFrames:%lld "
4723 "monoPipeWritten:%lld monoPipeLeft:%lld",
4724 (long long)mFramesWritten, (long long)mSuspendedFrames,
4725 (long long)mPipeSink->framesWritten(), pipeFrames);
4726 mLocalLog.log("threadLoop_standby: %s", mTimestamp.toString().c_str());
4727
Eric Laurent81784c32012-11-19 14:55:58 -08004728 state->mCommand = FastMixerState::COLD_IDLE;
4729 state->mColdFutexAddr = &mFastMixerFutex;
4730 state->mColdGen++;
4731 mFastMixerFutex = 0;
4732 sq->end();
4733 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
4734 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
4735 if (kUseFastMixer == FastMixer_Dynamic) {
4736 mNormalSink = mOutputSink;
4737 }
4738#ifdef AUDIO_WATCHDOG
4739 if (mAudioWatchdog != 0) {
4740 mAudioWatchdog->pause();
4741 }
4742#endif
4743 } else {
4744 sq->end(false /*didModify*/);
4745 }
4746 }
4747 PlaybackThread::threadLoop_standby();
4748}
4749
Eric Laurentbfb1b832013-01-07 09:53:42 -08004750bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
4751{
4752 return false;
4753}
4754
4755bool AudioFlinger::PlaybackThread::shouldStandby_l()
4756{
4757 return !mStandby;
4758}
4759
4760bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
4761{
4762 Mutex::Autolock _l(mLock);
4763 return waitingAsyncCallback_l();
4764}
4765
Eric Laurent81784c32012-11-19 14:55:58 -08004766// shared by MIXER and DIRECT, overridden by DUPLICATING
4767void AudioFlinger::PlaybackThread::threadLoop_standby()
4768{
4769 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
Phil Burk062e67a2015-02-11 13:40:50 -08004770 mOutput->standby();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004771 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004772 // discard any pending drain or write ack by incrementing sequence
4773 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
4774 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004775 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004776 mCallbackThread->setWriteBlocked(mWriteAckSequence);
4777 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004778 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08004779 mHwPaused = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004780}
4781
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08004782void AudioFlinger::PlaybackThread::onAddNewTrack_l()
4783{
4784 ALOGV("signal playback thread");
4785 broadcast_l();
4786}
4787
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07004788void AudioFlinger::PlaybackThread::onAsyncError()
4789{
4790 for (int i = AUDIO_STREAM_SYSTEM; i < (int)AUDIO_STREAM_CNT; i++) {
4791 invalidateTracks((audio_stream_type_t)i);
4792 }
4793}
4794
Eric Laurent81784c32012-11-19 14:55:58 -08004795void AudioFlinger::MixerThread::threadLoop_mix()
4796{
Eric Laurent81784c32012-11-19 14:55:58 -08004797 // mix buffers...
Glenn Kastend79072e2016-01-06 08:41:20 -08004798 mAudioMixer->process();
Andy Hung25c2dac2014-02-27 14:56:00 -08004799 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004800 // increase sleep time progressively when application underrun condition clears.
4801 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
4802 // that a steady state of alternating ready/not ready conditions keeps the sleep time
4803 // such that we would underrun the audio HAL.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004804 if ((mSleepTimeUs == 0) && (sleepTimeShift > 0)) {
Eric Laurent81784c32012-11-19 14:55:58 -08004805 sleepTimeShift--;
4806 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004807 mSleepTimeUs = 0;
4808 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08004809 //TODO: delay standby when effects have a tail
Glenn Kasten4c053ea2014-09-28 14:41:07 -07004810
Eric Laurent81784c32012-11-19 14:55:58 -08004811}
4812
4813void AudioFlinger::MixerThread::threadLoop_sleepTime()
4814{
4815 // If no tracks are ready, sleep once for the duration of an output
4816 // buffer size, then write 0s to the output
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004817 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004818 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Andy Hung06d13222018-05-03 20:13:31 -07004819 if (mPipeSink.get() != nullptr && mPipeSink == mNormalSink) {
4820 // Using the Monopipe availableToWrite, we estimate the
4821 // sleep time to retry for more data (before we underrun).
4822 MonoPipe *monoPipe = static_cast<MonoPipe *>(mPipeSink.get());
4823 const ssize_t availableToWrite = mPipeSink->availableToWrite();
4824 const size_t pipeFrames = monoPipe->maxFrames();
4825 const size_t framesLeft = pipeFrames - max(availableToWrite, 0);
4826 // HAL_framecount <= framesDelay ~ framesLeft / 2 <= Normal_Mixer_framecount
4827 const size_t framesDelay = std::min(
4828 mNormalFrameCount, max(framesLeft / 2, mFrameCount));
4829 ALOGV("pipeFrames:%zu framesLeft:%zu framesDelay:%zu",
4830 pipeFrames, framesLeft, framesDelay);
4831 mSleepTimeUs = framesDelay * MICROS_PER_SECOND / mSampleRate;
4832 } else {
4833 mSleepTimeUs = mActiveSleepTimeUs >> sleepTimeShift;
4834 if (mSleepTimeUs < kMinThreadSleepTimeUs) {
4835 mSleepTimeUs = kMinThreadSleepTimeUs;
4836 }
4837 // reduce sleep time in case of consecutive application underruns to avoid
4838 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
4839 // duration we would end up writing less data than needed by the audio HAL if
4840 // the condition persists.
4841 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
4842 sleepTimeShift++;
4843 }
Eric Laurent81784c32012-11-19 14:55:58 -08004844 }
4845 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004846 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08004847 }
4848 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08004849 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
4850 // before effects processing or output.
4851 if (mMixerBufferValid) {
4852 memset(mMixerBuffer, 0, mMixerBufferSize);
4853 } else {
4854 memset(mSinkBuffer, 0, mSinkBufferSize);
4855 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004856 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08004857 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
4858 "anticipated start");
4859 }
4860 // TODO add standby time extension fct of effect tail
4861}
4862
4863// prepareTracks_l() must be called with ThreadBase::mLock held
4864AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
4865 Vector< sp<Track> > *tracksToRemove)
4866{
Andy Hungc0691382018-09-12 18:01:57 -07004867 // clean up deleted track ids in AudioMixer before allocating new tracks
4868 (void)mTracks.processDeletedTrackIds([this](int trackId) {
4869 // for each trackId, destroy it in the AudioMixer
4870 if (mAudioMixer->exists(trackId)) {
4871 mAudioMixer->destroy(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08004872 }
4873 });
Andy Hungc0691382018-09-12 18:01:57 -07004874 mTracks.clearDeletedTrackIds();
Eric Laurent81784c32012-11-19 14:55:58 -08004875
4876 mixer_state mixerStatus = MIXER_IDLE;
4877 // find out which tracks need to be processed
4878 size_t count = mActiveTracks.size();
4879 size_t mixedTracks = 0;
4880 size_t tracksWithEffect = 0;
4881 // counts only _active_ fast tracks
4882 size_t fastTracks = 0;
4883 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
4884
4885 float masterVolume = mMasterVolume;
4886 bool masterMute = mMasterMute;
4887
4888 if (masterMute) {
4889 masterVolume = 0;
4890 }
4891 // Delegate master volume control to effect in output mix effect chain if needed
4892 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
4893 if (chain != 0) {
4894 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
4895 chain->setVolume_l(&v, &v);
4896 masterVolume = (float)((v + (1 << 23)) >> 24);
4897 chain.clear();
4898 }
4899
4900 // prepare a new state to push
4901 FastMixerStateQueue *sq = NULL;
4902 FastMixerState *state = NULL;
4903 bool didModify = false;
4904 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Andy Hungf2285312017-02-14 18:31:59 -08004905 bool coldIdle = false;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004906 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004907 sq = mFastMixer->sq();
4908 state = sq->begin();
Andy Hungf2285312017-02-14 18:31:59 -08004909 coldIdle = state->mCommand == FastMixerState::COLD_IDLE;
Eric Laurent81784c32012-11-19 14:55:58 -08004910 }
4911
Andy Hung69aed5f2014-02-25 17:24:40 -08004912 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08004913 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08004914
Andy Hungbd3b2b02018-05-21 10:53:11 -07004915 // DeferredOperations handles statistics after setting mixerStatus.
4916 class DeferredOperations {
4917 public:
Andy Hungea840382020-05-05 21:50:17 -07004918 DeferredOperations(mixer_state *mixerStatus, ThreadMetrics *threadMetrics)
4919 : mMixerStatus(mixerStatus)
4920 , mThreadMetrics(threadMetrics) {}
Andy Hungbd3b2b02018-05-21 10:53:11 -07004921
4922 // when leaving scope, tally frames properly.
4923 ~DeferredOperations() {
4924 // Tally underrun frames only if we are actually mixing (MIXER_TRACKS_READY)
4925 // because that is when the underrun occurs.
4926 // We do not distinguish between FastTracks and NormalTracks here.
Andy Hungea840382020-05-05 21:50:17 -07004927 size_t maxUnderrunFrames = 0;
Andy Hungb68f5eb2019-12-03 16:49:17 -08004928 if (*mMixerStatus == MIXER_TRACKS_READY && mUnderrunFrames.size() > 0) {
Andy Hungbd3b2b02018-05-21 10:53:11 -07004929 for (const auto &underrun : mUnderrunFrames) {
Andy Hungc2b11cb2020-04-22 09:04:01 -07004930 underrun.first->tallyUnderrunFrames(underrun.second);
Andy Hungea840382020-05-05 21:50:17 -07004931 maxUnderrunFrames = max(underrun.second, maxUnderrunFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07004932 }
4933 }
Andy Hungea840382020-05-05 21:50:17 -07004934 // send the max underrun frames for this mixer period
4935 mThreadMetrics->logUnderrunFrames(maxUnderrunFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07004936 }
4937
4938 // tallyUnderrunFrames() is called to update the track counters
4939 // with the number of underrun frames for a particular mixer period.
4940 // We defer tallying until we know the final mixer status.
4941 void tallyUnderrunFrames(sp<Track> track, size_t underrunFrames) {
4942 mUnderrunFrames.emplace_back(track, underrunFrames);
4943 }
4944
4945 private:
4946 const mixer_state * const mMixerStatus;
Andy Hungea840382020-05-05 21:50:17 -07004947 ThreadMetrics * const mThreadMetrics;
Andy Hungbd3b2b02018-05-21 10:53:11 -07004948 std::vector<std::pair<sp<Track>, size_t>> mUnderrunFrames;
Andy Hungea840382020-05-05 21:50:17 -07004949 } deferredOperations(&mixerStatus, &mThreadMetrics);
Andy Hungb68f5eb2019-12-03 16:49:17 -08004950 // implicit nested scope for variable capture
Andy Hungbd3b2b02018-05-21 10:53:11 -07004951
jiabin245cdd92018-12-07 17:55:15 -08004952 bool noFastHapticTrack = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004953 for (size_t i=0 ; i<count ; i++) {
Andy Hungdae27702016-10-31 14:01:16 -07004954 const sp<Track> t = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08004955
4956 // this const just means the local variable doesn't change
4957 Track* const track = t.get();
4958
4959 // process fast tracks
4960 if (track->isFastTrack()) {
Andy Hungae22b482019-05-09 15:38:55 -07004961 LOG_ALWAYS_FATAL_IF(mFastMixer.get() == nullptr,
4962 "%s(%d): FastTrack(%d) present without FastMixer",
4963 __func__, id(), track->id());
4964
jiabin245cdd92018-12-07 17:55:15 -08004965 if (track->getHapticPlaybackEnabled()) {
4966 noFastHapticTrack = false;
4967 }
Eric Laurent81784c32012-11-19 14:55:58 -08004968
4969 // It's theoretically possible (though unlikely) for a fast track to be created
4970 // and then removed within the same normal mix cycle. This is not a problem, as
4971 // the track never becomes active so it's fast mixer slot is never touched.
4972 // The converse, of removing an (active) track and then creating a new track
4973 // at the identical fast mixer slot within the same normal mix cycle,
4974 // is impossible because the slot isn't marked available until the end of each cycle.
4975 int j = track->mFastIndex;
Glenn Kastendc2c50b2016-04-21 08:13:14 -07004976 ALOG_ASSERT(0 < j && j < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08004977 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
4978 FastTrack *fastTrack = &state->mFastTracks[j];
4979
4980 // Determine whether the track is currently in underrun condition,
4981 // and whether it had a recent underrun.
4982 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
4983 FastTrackUnderruns underruns = ftDump->mUnderruns;
4984 uint32_t recentFull = (underruns.mBitFields.mFull -
4985 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
4986 uint32_t recentPartial = (underruns.mBitFields.mPartial -
4987 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
4988 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
4989 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
4990 uint32_t recentUnderruns = recentPartial + recentEmpty;
4991 track->mObservedUnderruns = underruns;
4992 // don't count underruns that occur while stopping or pausing
4993 // or stopped which can occur when flush() is called while active
Andy Hungbd3b2b02018-05-21 10:53:11 -07004994 size_t underrunFrames = 0;
Glenn Kasten82aaf942013-07-17 16:05:07 -07004995 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
4996 recentUnderruns > 0) {
4997 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
Andy Hungbd3b2b02018-05-21 10:53:11 -07004998 underrunFrames = recentUnderruns * mFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08004999 }
Andy Hungbd3b2b02018-05-21 10:53:11 -07005000 // Immediately account for FastTrack underruns.
5001 track->mAudioTrackServerProxy->tallyUnderrunFrames(underrunFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08005002
5003 // This is similar to the state machine for normal tracks,
5004 // with a few modifications for fast tracks.
5005 bool isActive = true;
5006 switch (track->mState) {
5007 case TrackBase::STOPPING_1:
5008 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08005009 if (recentUnderruns > 0 || track->isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -08005010 track->mState = TrackBase::STOPPING_2;
5011 }
5012 break;
5013 case TrackBase::PAUSING:
5014 // ramp down is not yet implemented
5015 track->setPaused();
5016 break;
5017 case TrackBase::RESUMING:
5018 // ramp up is not yet implemented
5019 track->mState = TrackBase::ACTIVE;
5020 break;
5021 case TrackBase::ACTIVE:
5022 if (recentFull > 0 || recentPartial > 0) {
5023 // track has provided at least some frames recently: reset retry count
5024 track->mRetryCount = kMaxTrackRetries;
5025 }
5026 if (recentUnderruns == 0) {
5027 // no recent underruns: stay active
5028 break;
5029 }
5030 // there has recently been an underrun of some kind
5031 if (track->sharedBuffer() == 0) {
5032 // were any of the recent underruns "empty" (no frames available)?
5033 if (recentEmpty == 0) {
5034 // no, then ignore the partial underruns as they are allowed indefinitely
5035 break;
5036 }
5037 // there has recently been an "empty" underrun: decrement the retry counter
5038 if (--(track->mRetryCount) > 0) {
5039 break;
5040 }
5041 // indicate to client process that the track was disabled because of underrun;
5042 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08005043 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08005044 // remove from active list, but state remains ACTIVE [confusing but true]
5045 isActive = false;
5046 break;
5047 }
Chih-Hung Hsieh2b487032018-09-13 14:16:02 -07005048 FALLTHROUGH_INTENDED;
Eric Laurent81784c32012-11-19 14:55:58 -08005049 case TrackBase::STOPPING_2:
5050 case TrackBase::PAUSED:
Eric Laurent81784c32012-11-19 14:55:58 -08005051 case TrackBase::STOPPED:
5052 case TrackBase::FLUSHED: // flush() while active
5053 // Check for presentation complete if track is inactive
5054 // We have consumed all the buffers of this track.
5055 // This would be incomplete if we auto-paused on underrun
5056 {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005057 uint32_t latency = 0;
5058 status_t result = mOutput->stream->getLatency(&latency);
5059 ALOGE_IF(result != OK,
5060 "Error when retrieving output stream latency: %d", result);
5061 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08005062 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005063 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
5064 // track stays in active list until presentation is complete
5065 break;
5066 }
5067 }
5068 if (track->isStopping_2()) {
5069 track->mState = TrackBase::STOPPED;
5070 }
5071 if (track->isStopped()) {
5072 // Can't reset directly, as fast mixer is still polling this track
5073 // track->reset();
5074 // So instead mark this track as needing to be reset after push with ack
5075 resetMask |= 1 << i;
5076 }
5077 isActive = false;
5078 break;
5079 case TrackBase::IDLE:
5080 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08005081 LOG_ALWAYS_FATAL("unexpected track state %d", track->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08005082 }
5083
5084 if (isActive) {
5085 // was it previously inactive?
5086 if (!(state->mTrackMask & (1 << j))) {
5087 ExtendedAudioBufferProvider *eabp = track;
5088 VolumeProvider *vp = track;
5089 fastTrack->mBufferProvider = eabp;
5090 fastTrack->mVolumeProvider = vp;
Eric Laurent81784c32012-11-19 14:55:58 -08005091 fastTrack->mChannelMask = track->mChannelMask;
Andy Hunge8a1ced2014-05-09 15:02:21 -07005092 fastTrack->mFormat = track->mFormat;
jiabin245cdd92018-12-07 17:55:15 -08005093 fastTrack->mHapticPlaybackEnabled = track->getHapticPlaybackEnabled();
jiabin77270b82018-12-18 15:41:29 -08005094 fastTrack->mHapticIntensity = track->getHapticIntensity();
Eric Laurent81784c32012-11-19 14:55:58 -08005095 fastTrack->mGeneration++;
5096 state->mTrackMask |= 1 << j;
5097 didModify = true;
5098 // no acknowledgement required for newly active tracks
5099 }
Kevin Rocard12381092018-04-11 09:19:59 -07005100 sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
Eric Laurenteab90452019-06-24 15:17:46 -07005101 float volume;
5102 if (track->isPlaybackRestricted() || mStreamTypes[track->streamType()].mute) {
5103 volume = 0.f;
5104 } else {
5105 volume = masterVolume * mStreamTypes[track->streamType()].volume;
5106 }
5107
5108 handleVoipVolume_l(&volume);
5109
Eric Laurent81784c32012-11-19 14:55:58 -08005110 // cache the combined master volume and stream type volume for fast mixer; this
5111 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005112 const float vh = track->getVolumeHandler()->getVolume(
Eric Laurenteab90452019-06-24 15:17:46 -07005113 proxy->framesReleased()).first;
5114 volume *= vh;
Kevin Rocardb0eeaf122018-04-11 08:30:16 -07005115 track->mCachedVolume = volume;
Kevin Rocard12381092018-04-11 09:19:59 -07005116 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
5117 float vlf = volume * float_from_gain(gain_minifloat_unpack_left(vlr));
5118 float vrf = volume * float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurenteab90452019-06-24 15:17:46 -07005119
Kevin Rocard12381092018-04-11 09:19:59 -07005120 track->setFinalVolume((vlf + vrf) / 2.f);
Eric Laurent81784c32012-11-19 14:55:58 -08005121 ++fastTracks;
5122 } else {
5123 // was it previously active?
5124 if (state->mTrackMask & (1 << j)) {
5125 fastTrack->mBufferProvider = NULL;
5126 fastTrack->mGeneration++;
5127 state->mTrackMask &= ~(1 << j);
5128 didModify = true;
5129 // If any fast tracks were removed, we must wait for acknowledgement
5130 // because we're about to decrement the last sp<> on those tracks.
5131 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
5132 } else {
Glenn Kastenbf848af2017-12-22 11:55:01 -08005133 // ALOGW rather than LOG_ALWAYS_FATAL because it seems there are cases where an
5134 // AudioTrack may start (which may not be with a start() but with a write()
5135 // after underrun) and immediately paused or released. In that case the
5136 // FastTrack state hasn't had time to update.
5137 // TODO Remove the ALOGW when this theory is confirmed.
5138 ALOGW("fast track %d should have been active; "
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08005139 "mState=%d, mTrackMask=%#x, recentUnderruns=%u, isShared=%d",
5140 j, track->mState, state->mTrackMask, recentUnderruns,
5141 track->sharedBuffer() != 0);
Glenn Kastenbf848af2017-12-22 11:55:01 -08005142 // Since the FastMixer state already has the track inactive, do nothing here.
Eric Laurent81784c32012-11-19 14:55:58 -08005143 }
5144 tracksToRemove->add(track);
5145 // Avoids a misleading display in dumpsys
5146 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
5147 }
jiabin245cdd92018-12-07 17:55:15 -08005148 if (fastTrack->mHapticPlaybackEnabled != track->getHapticPlaybackEnabled()) {
5149 fastTrack->mHapticPlaybackEnabled = track->getHapticPlaybackEnabled();
5150 didModify = true;
5151 }
Eric Laurent81784c32012-11-19 14:55:58 -08005152 continue;
5153 }
5154
5155 { // local variable scope to avoid goto warning
5156
5157 audio_track_cblk_t* cblk = track->cblk();
5158
5159 // The first time a track is added we wait
5160 // for all its buffers to be filled before processing it
Andy Hungc0691382018-09-12 18:01:57 -07005161 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08005162
5163 // if an active track doesn't exist in the AudioMixer, create it.
Andy Hungc0691382018-09-12 18:01:57 -07005164 // use the trackId as the AudioMixer name.
5165 if (!mAudioMixer->exists(trackId)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08005166 status_t status = mAudioMixer->create(
Andy Hungc0691382018-09-12 18:01:57 -07005167 trackId,
Andy Hung1bc088a2018-02-09 15:57:31 -08005168 track->mChannelMask,
5169 track->mFormat,
5170 track->mSessionId);
5171 if (status != OK) {
Andy Hungc0691382018-09-12 18:01:57 -07005172 ALOGW("%s(): AudioMixer cannot create track(%d)"
5173 " mask %#x, format %#x, sessionId %d",
5174 __func__, trackId,
5175 track->mChannelMask, track->mFormat, track->mSessionId);
Andy Hung1bc088a2018-02-09 15:57:31 -08005176 tracksToRemove->add(track);
5177 track->invalidate(); // consider it dead.
5178 continue;
5179 }
5180 }
5181
Eric Laurent81784c32012-11-19 14:55:58 -08005182 // make sure that we have enough frames to mix one full buffer.
5183 // enforce this condition only once to enable draining the buffer in case the client
5184 // app does not call stop() and relies on underrun to stop:
5185 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
5186 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005187 size_t desiredFrames;
Andy Hung8edb8dc2015-03-26 19:13:55 -07005188 const uint32_t sampleRate = track->mAudioTrackServerProxy->getSampleRate();
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07005189 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07005190
5191 desiredFrames = sourceFramesNeededWithTimestretch(
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07005192 sampleRate, mNormalFrameCount, mSampleRate, playbackRate.mSpeed);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005193 // TODO: ONLY USED FOR LEGACY RESAMPLERS, remove when they are removed.
5194 // add frames already consumed but not yet released by the resampler
5195 // because mAudioTrackServerProxy->framesReady() will include these frames
Andy Hungc0691382018-09-12 18:01:57 -07005196 desiredFrames += mAudioMixer->getUnreleasedFrames(trackId);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005197
Eric Laurent81784c32012-11-19 14:55:58 -08005198 uint32_t minFrames = 1;
5199 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
5200 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005201 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08005202 }
Eric Laurent13e4c962013-12-20 17:36:01 -08005203
5204 size_t framesReady = track->framesReady();
Glenn Kastene7754022014-10-31 12:11:26 -07005205 if (ATRACE_ENABLED()) {
5206 // I wish we had formatted trace names
Andy Hung1bc088a2018-02-09 15:57:31 -08005207 std::string traceName("nRdy");
Andy Hungc0691382018-09-12 18:01:57 -07005208 traceName += std::to_string(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08005209 ATRACE_INT(traceName.c_str(), framesReady);
Glenn Kastene7754022014-10-31 12:11:26 -07005210 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005211 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08005212 !track->isPaused() && !track->isTerminated())
5213 {
Andy Hungc0691382018-09-12 18:01:57 -07005214 ALOGVV("track(%d) s=%08x [OK] on thread %p", trackId, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08005215
5216 mixedTracks++;
5217
Andy Hung69aed5f2014-02-25 17:24:40 -08005218 // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
5219 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08005220 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08005221 if (track->mainBuffer() != mSinkBuffer &&
5222 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08005223 if (mEffectBufferEnabled) {
5224 mEffectBufferValid = true; // Later can set directly.
5225 }
Eric Laurent81784c32012-11-19 14:55:58 -08005226 chain = getEffectChain_l(track->sessionId());
5227 // Delegate volume control to effect in track effect chain if needed
5228 if (chain != 0) {
5229 tracksWithEffect++;
5230 } else {
Andy Hungc0691382018-09-12 18:01:57 -07005231 ALOGW("prepareTracks_l(): track(%d) attached to effect but no chain found on "
Eric Laurent81784c32012-11-19 14:55:58 -08005232 "session %d",
Andy Hungc0691382018-09-12 18:01:57 -07005233 trackId, track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08005234 }
5235 }
5236
5237
5238 int param = AudioMixer::VOLUME;
5239 if (track->mFillingUpStatus == Track::FS_FILLED) {
5240 // no ramp for the first volume setting
5241 track->mFillingUpStatus = Track::FS_ACTIVE;
5242 if (track->mState == TrackBase::RESUMING) {
5243 track->mState = TrackBase::ACTIVE;
Revathi Uddaraju453bcb52017-08-14 14:19:40 +08005244 // If a new track is paused immediately after start, do not ramp on resume.
5245 if (cblk->mServer != 0) {
5246 param = AudioMixer::RAMP_VOLUME;
5247 }
Eric Laurent81784c32012-11-19 14:55:58 -08005248 }
Andy Hungc0691382018-09-12 18:01:57 -07005249 mAudioMixer->setParameter(trackId, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Eric Laurent7c29ec92017-09-20 17:54:22 -07005250 mLeftVolFloat = -1.0;
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005251 // FIXME should not make a decision based on mServer
5252 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005253 // If the track is stopped before the first frame was mixed,
5254 // do not apply ramp
5255 param = AudioMixer::RAMP_VOLUME;
5256 }
5257
5258 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07005259 uint32_t vl, vr; // in U8.24 integer format
5260 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Eric Laurent7c29ec92017-09-20 17:54:22 -07005261 // read original volumes with volume control
Eric Laurenteab90452019-06-24 15:17:46 -07005262 float v = masterVolume * mStreamTypes[track->streamType()].volume;
Andy Hung333ab962019-05-28 20:23:35 -07005263 // Always fetch volumeshaper volume to ensure state is updated.
5264 const sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
5265 const float vh = track->getVolumeHandler()->getVolume(
5266 track->mAudioTrackServerProxy->framesReleased()).first;
Eric Laurent7c29ec92017-09-20 17:54:22 -07005267
Eric Laurenteab90452019-06-24 15:17:46 -07005268 if (mStreamTypes[track->streamType()].mute || track->isPlaybackRestricted()) {
5269 v = 0;
5270 }
5271
5272 handleVoipVolume_l(&v);
5273
5274 if (track->isPausing()) {
Andy Hung6be49402014-05-30 10:42:03 -07005275 vl = vr = 0;
5276 vlf = vrf = vaf = 0.;
Eric Laurenteab90452019-06-24 15:17:46 -07005277 track->setPaused();
Eric Laurent81784c32012-11-19 14:55:58 -08005278 } else {
Glenn Kastenc56f3422014-03-21 17:53:17 -07005279 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07005280 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
5281 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08005282 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07005283 if (vlf > GAIN_FLOAT_UNITY) {
5284 ALOGV("Track left volume out of range: %.3g", vlf);
5285 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08005286 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07005287 if (vrf > GAIN_FLOAT_UNITY) {
5288 ALOGV("Track right volume out of range: %.3g", vrf);
5289 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08005290 }
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005291 // now apply the master volume and stream type volume and shaper volume
5292 vlf *= v * vh;
5293 vrf *= v * vh;
Eric Laurent81784c32012-11-19 14:55:58 -08005294 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07005295 // then derive vl and vr as U8.24 versions for the effect chain
5296 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
5297 vl = (uint32_t) (scaleto8_24 * vlf);
5298 vr = (uint32_t) (scaleto8_24 * vrf);
5299 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08005300 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08005301 // send level comes from shared memory and so may be corrupt
5302 if (sendLevel > MAX_GAIN_INT) {
5303 ALOGV("Track send level out of range: %04X", sendLevel);
5304 sendLevel = MAX_GAIN_INT;
5305 }
Andy Hung6be49402014-05-30 10:42:03 -07005306 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
5307 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08005308 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005309
Kevin Rocard12381092018-04-11 09:19:59 -07005310 track->setFinalVolume((vrf + vlf) / 2.f);
5311
Eric Laurent81784c32012-11-19 14:55:58 -08005312 // Delegate volume control to effect in track effect chain if needed
5313 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
5314 // Do not ramp volume if volume is controlled by effect
5315 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08005316 // Update remaining floating point volume levels
5317 vlf = (float)vl / (1 << 24);
5318 vrf = (float)vr / (1 << 24);
Eric Laurent81784c32012-11-19 14:55:58 -08005319 track->mHasVolumeController = true;
5320 } else {
5321 // force no volume ramp when volume controller was just disabled or removed
5322 // from effect chain to avoid volume spike
5323 if (track->mHasVolumeController) {
5324 param = AudioMixer::VOLUME;
5325 }
5326 track->mHasVolumeController = false;
5327 }
5328
Eric Laurent81784c32012-11-19 14:55:58 -08005329 // XXX: these things DON'T need to be done each time
Andy Hungc0691382018-09-12 18:01:57 -07005330 mAudioMixer->setBufferProvider(trackId, track);
5331 mAudioMixer->enable(trackId);
Eric Laurent81784c32012-11-19 14:55:58 -08005332
Andy Hungc0691382018-09-12 18:01:57 -07005333 mAudioMixer->setParameter(trackId, param, AudioMixer::VOLUME0, &vlf);
5334 mAudioMixer->setParameter(trackId, param, AudioMixer::VOLUME1, &vrf);
5335 mAudioMixer->setParameter(trackId, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08005336 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005337 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005338 AudioMixer::TRACK,
5339 AudioMixer::FORMAT, (void *)track->format());
5340 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005341 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005342 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00005343 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Andy Hung9a592762014-07-21 21:56:01 -07005344 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005345 trackId,
Andy Hung9a592762014-07-21 21:56:01 -07005346 AudioMixer::TRACK,
jiabin245cdd92018-12-07 17:55:15 -08005347 AudioMixer::MIXER_CHANNEL_MASK,
5348 (void *)(uintptr_t)(mChannelMask | mHapticChannelMask));
Glenn Kastene3aa6592012-12-04 12:22:46 -08005349 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07005350 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Andy Hung333ab962019-05-28 20:23:35 -07005351 uint32_t reqSampleRate = proxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08005352 if (reqSampleRate == 0) {
5353 reqSampleRate = mSampleRate;
5354 } else if (reqSampleRate > maxSampleRate) {
5355 reqSampleRate = maxSampleRate;
5356 }
Eric Laurent81784c32012-11-19 14:55:58 -08005357 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005358 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005359 AudioMixer::RESAMPLE,
5360 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00005361 (void *)(uintptr_t)reqSampleRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005362
Andy Hung333ab962019-05-28 20:23:35 -07005363 AudioPlaybackRate playbackRate = proxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07005364 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005365 trackId,
Andy Hung8edb8dc2015-03-26 19:13:55 -07005366 AudioMixer::TIMESTRETCH,
5367 AudioMixer::PLAYBACK_RATE,
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07005368 &playbackRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005369
Andy Hung69aed5f2014-02-25 17:24:40 -08005370 /*
5371 * Select the appropriate output buffer for the track.
5372 *
Andy Hung98ef9782014-03-04 14:46:50 -08005373 * Tracks with effects go into their own effects chain buffer
5374 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08005375 *
5376 * Other tracks can use mMixerBuffer for higher precision
5377 * channel accumulation. If this buffer is enabled
5378 * (mMixerBufferEnabled true), then selected tracks will accumulate
5379 * into it.
5380 *
5381 */
5382 if (mMixerBufferEnabled
5383 && (track->mainBuffer() == mSinkBuffer
5384 || track->mainBuffer() == mMixerBuffer)) {
5385 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005386 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08005387 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08005388 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
Andy Hung69aed5f2014-02-25 17:24:40 -08005389 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005390 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08005391 AudioMixer::TRACK,
5392 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
5393 // TODO: override track->mainBuffer()?
5394 mMixerBufferValid = true;
5395 } else {
5396 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005397 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08005398 AudioMixer::TRACK,
rago94a1ee82017-07-21 15:11:02 -07005399 AudioMixer::MIXER_FORMAT, (void *)EFFECT_BUFFER_FORMAT);
Andy Hung69aed5f2014-02-25 17:24:40 -08005400 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005401 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08005402 AudioMixer::TRACK,
5403 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
5404 }
Eric Laurent81784c32012-11-19 14:55:58 -08005405 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005406 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005407 AudioMixer::TRACK,
5408 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
jiabin245cdd92018-12-07 17:55:15 -08005409 mAudioMixer->setParameter(
5410 trackId,
5411 AudioMixer::TRACK,
5412 AudioMixer::HAPTIC_ENABLED, (void *)(uintptr_t)track->getHapticPlaybackEnabled());
jiabin77270b82018-12-18 15:41:29 -08005413 mAudioMixer->setParameter(
5414 trackId,
5415 AudioMixer::TRACK,
5416 AudioMixer::HAPTIC_INTENSITY, (void *)(uintptr_t)track->getHapticIntensity());
Eric Laurent81784c32012-11-19 14:55:58 -08005417
5418 // reset retry count
5419 track->mRetryCount = kMaxTrackRetries;
5420
5421 // If one track is ready, set the mixer ready if:
5422 // - the mixer was not ready during previous round OR
5423 // - no other track is not ready
5424 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
5425 mixerStatus != MIXER_TRACKS_ENABLED) {
5426 mixerStatus = MIXER_TRACKS_READY;
5427 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08005428
5429 // Enable the next few lines to instrument a test for underrun log handling.
5430 // TODO: Remove when we have a better way of testing the underrun log.
5431#if 0
5432 static int i;
5433 if ((++i & 0xf) == 0) {
5434 deferredOperations.tallyUnderrunFrames(track, 10 /* underrunFrames */);
5435 }
5436#endif
Eric Laurent81784c32012-11-19 14:55:58 -08005437 } else {
Andy Hungbd3b2b02018-05-21 10:53:11 -07005438 size_t underrunFrames = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005439 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Andy Hungb68f5eb2019-12-03 16:49:17 -08005440 ALOGV("track(%d) underrun, track state %s framesReady(%zu) < framesDesired(%zd)",
5441 trackId, track->getTrackStateAsString(), framesReady, desiredFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07005442 underrunFrames = desiredFrames;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005443 }
Andy Hungbd3b2b02018-05-21 10:53:11 -07005444 deferredOperations.tallyUnderrunFrames(track, underrunFrames);
Phil Burk2812d9e2016-01-04 10:34:30 -08005445
Eric Laurent81784c32012-11-19 14:55:58 -08005446 // clear effect chain input buffer if an active track underruns to avoid sending
5447 // previous audio buffer again to effects
5448 chain = getEffectChain_l(track->sessionId());
5449 if (chain != 0) {
5450 chain->clearInputBuffer();
5451 }
5452
Andy Hungc0691382018-09-12 18:01:57 -07005453 ALOGVV("track(%d) s=%08x [NOT READY] on thread %p", trackId, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08005454 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
5455 track->isStopped() || track->isPaused()) {
5456 // We have consumed all the buffers of this track.
5457 // Remove it from the list of active tracks.
5458 // TODO: use actual buffer filling status instead of latency when available from
5459 // audio HAL
5460 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08005461 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005462 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
5463 if (track->isStopped()) {
5464 track->reset();
5465 }
5466 tracksToRemove->add(track);
5467 }
5468 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08005469 // No buffers for this track. Give it a few chances to
5470 // fill a buffer, then remove it from active list.
5471 if (--(track->mRetryCount) <= 0) {
Andy Hungc0691382018-09-12 18:01:57 -07005472 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p",
5473 trackId, this);
Eric Laurent81784c32012-11-19 14:55:58 -08005474 tracksToRemove->add(track);
5475 // indicate to client process that the track was disabled because of underrun;
5476 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08005477 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08005478 // If one track is not ready, mark the mixer also not ready if:
5479 // - the mixer was ready during previous round OR
5480 // - no other track is ready
5481 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
5482 mixerStatus != MIXER_TRACKS_READY) {
5483 mixerStatus = MIXER_TRACKS_ENABLED;
5484 }
5485 }
Andy Hungc0691382018-09-12 18:01:57 -07005486 mAudioMixer->disable(trackId);
Eric Laurent81784c32012-11-19 14:55:58 -08005487 }
5488
5489 } // local variable scope to avoid goto warning
Eric Laurent81784c32012-11-19 14:55:58 -08005490
5491 }
5492
jiabin245cdd92018-12-07 17:55:15 -08005493 if (mHapticChannelMask != AUDIO_CHANNEL_NONE && sq != NULL) {
5494 // When there is no fast track playing haptic and FastMixer exists,
5495 // enabling the first FastTrack, which provides mixed data from normal
5496 // tracks, to play haptic data.
5497 FastTrack *fastTrack = &state->mFastTracks[0];
5498 if (fastTrack->mHapticPlaybackEnabled != noFastHapticTrack) {
5499 fastTrack->mHapticPlaybackEnabled = noFastHapticTrack;
5500 didModify = true;
5501 }
5502 }
5503
Eric Laurent81784c32012-11-19 14:55:58 -08005504 // Push the new FastMixer state if necessary
5505 bool pauseAudioWatchdog = false;
5506 if (didModify) {
5507 state->mFastTracksGen++;
5508 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
5509 if (kUseFastMixer == FastMixer_Dynamic &&
5510 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
5511 state->mCommand = FastMixerState::COLD_IDLE;
5512 state->mColdFutexAddr = &mFastMixerFutex;
5513 state->mColdGen++;
5514 mFastMixerFutex = 0;
5515 if (kUseFastMixer == FastMixer_Dynamic) {
5516 mNormalSink = mOutputSink;
5517 }
5518 // If we go into cold idle, need to wait for acknowledgement
5519 // so that fast mixer stops doing I/O.
5520 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
5521 pauseAudioWatchdog = true;
5522 }
Eric Laurent81784c32012-11-19 14:55:58 -08005523 }
5524 if (sq != NULL) {
5525 sq->end(didModify);
Andy Hungf2285312017-02-14 18:31:59 -08005526 // No need to block if the FastMixer is in COLD_IDLE as the FastThread
5527 // is not active. (We BLOCK_UNTIL_ACKED when entering COLD_IDLE
5528 // when bringing the output sink into standby.)
5529 //
5530 // We will get the latest FastMixer state when we come out of COLD_IDLE.
5531 //
5532 // This occurs with BT suspend when we idle the FastMixer with
5533 // active tracks, which may be added or removed.
5534 sq->push(coldIdle ? FastMixerStateQueue::BLOCK_NEVER : block);
Eric Laurent81784c32012-11-19 14:55:58 -08005535 }
5536#ifdef AUDIO_WATCHDOG
5537 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
5538 mAudioWatchdog->pause();
5539 }
5540#endif
5541
5542 // Now perform the deferred reset on fast tracks that have stopped
5543 while (resetMask != 0) {
5544 size_t i = __builtin_ctz(resetMask);
5545 ALOG_ASSERT(i < count);
5546 resetMask &= ~(1 << i);
Andy Hungdae27702016-10-31 14:01:16 -07005547 sp<Track> track = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08005548 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
5549 track->reset();
5550 }
5551
Andy Hung80d03d22018-04-10 10:32:11 -07005552 // Track destruction may occur outside of threadLoop once it is removed from active tracks.
5553 // Ensure the AudioMixer doesn't have a raw "buffer provider" pointer to the track if
5554 // it ceases to be active, to allow safe removal from the AudioMixer at the start
5555 // of prepareTracks_l(); this releases any outstanding buffer back to the track.
5556 // See also the implementation of destroyTrack_l().
5557 for (const auto &track : *tracksToRemove) {
Andy Hungc0691382018-09-12 18:01:57 -07005558 const int trackId = track->id();
5559 if (mAudioMixer->exists(trackId)) { // Normal tracks here, fast tracks in FastMixer.
5560 mAudioMixer->setBufferProvider(trackId, nullptr /* bufferProvider */);
Andy Hung80d03d22018-04-10 10:32:11 -07005561 }
5562 }
5563
Eric Laurent81784c32012-11-19 14:55:58 -08005564 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08005565 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08005566
Eric Laurent97d547d2014-09-02 14:45:53 -07005567 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0) {
5568 mEffectBufferValid = true;
Marco Nelissenac302142014-10-20 13:15:38 -07005569 }
5570
5571 if (mEffectBufferValid) {
Marco Nelissen57088b52014-10-17 16:39:39 -07005572 // as long as there are effects we should clear the effects buffer, to avoid
5573 // passing a non-clean buffer to the effect chain
5574 memset(mEffectBuffer, 0, mEffectBufferSize);
Eric Laurent97d547d2014-09-02 14:45:53 -07005575 }
Andy Hung69aed5f2014-02-25 17:24:40 -08005576 // sink or mix buffer must be cleared if all tracks are connected to an
5577 // effect chain as in this case the mixer will not write to the sink or mix buffer
5578 // and track effects will accumulate into it
Eric Laurentbfb1b832013-01-07 09:53:42 -08005579 if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
5580 (mixedTracks == 0 && fastTracks > 0))) {
Eric Laurent81784c32012-11-19 14:55:58 -08005581 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08005582 if (mMixerBufferValid) {
5583 memset(mMixerBuffer, 0, mMixerBufferSize);
5584 // TODO: In testing, mSinkBuffer below need not be cleared because
5585 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
5586 // after mixing.
5587 //
5588 // To enforce this guarantee:
5589 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
5590 // (mixedTracks == 0 && fastTracks > 0))
5591 // must imply MIXER_TRACKS_READY.
5592 // Later, we may clear buffers regardless, and skip much of this logic.
5593 }
Andy Hung98ef9782014-03-04 14:46:50 -08005594 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07005595 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08005596 }
5597
5598 // if any fast tracks, then status is ready
5599 mMixerStatusIgnoringFastTracks = mixerStatus;
5600 if (fastTracks > 0) {
5601 mixerStatus = MIXER_TRACKS_READY;
5602 }
5603 return mixerStatus;
5604}
5605
Eric Laurentad7dd962016-09-22 12:38:37 -07005606// trackCountForUid_l() must be called with ThreadBase::mLock held
Andy Hung1bc088a2018-02-09 15:57:31 -08005607uint32_t AudioFlinger::PlaybackThread::trackCountForUid_l(uid_t uid) const
Eric Laurentad7dd962016-09-22 12:38:37 -07005608{
5609 uint32_t trackCount = 0;
5610 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hung1f12a8a2016-11-07 16:10:30 -08005611 if (mTracks[i]->uid() == uid) {
Eric Laurentad7dd962016-09-22 12:38:37 -07005612 trackCount++;
5613 }
5614 }
5615 return trackCount;
5616}
5617
Andy Hung1bc088a2018-02-09 15:57:31 -08005618// isTrackAllowed_l() must be called with ThreadBase::mLock held
5619bool AudioFlinger::MixerThread::isTrackAllowed_l(
5620 audio_channel_mask_t channelMask, audio_format_t format,
5621 audio_session_t sessionId, uid_t uid) const
Eric Laurent81784c32012-11-19 14:55:58 -08005622{
Andy Hung1bc088a2018-02-09 15:57:31 -08005623 if (!PlaybackThread::isTrackAllowed_l(channelMask, format, sessionId, uid)) {
5624 return false;
Eric Laurentad7dd962016-09-22 12:38:37 -07005625 }
Andy Hung1bc088a2018-02-09 15:57:31 -08005626 // Check validity as we don't call AudioMixer::create() here.
Mikhail Naganov7ad7a252019-07-30 14:42:32 -07005627 if (!mAudioMixer->isValidFormat(format)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08005628 ALOGW("%s: invalid format: %#x", __func__, format);
5629 return false;
5630 }
Mikhail Naganov7ad7a252019-07-30 14:42:32 -07005631 if (!mAudioMixer->isValidChannelMask(channelMask)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08005632 ALOGW("%s: invalid channelMask: %#x", __func__, channelMask);
5633 return false;
5634 }
5635 return true;
Eric Laurent81784c32012-11-19 14:55:58 -08005636}
5637
Eric Laurent10351942014-05-08 18:49:52 -07005638// checkForNewParameter_l() must be called with ThreadBase::mLock held
5639bool AudioFlinger::MixerThread::checkForNewParameter_l(const String8& keyValuePair,
5640 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08005641{
Eric Laurent81784c32012-11-19 14:55:58 -08005642 bool reconfig = false;
Eric Laurent10351942014-05-08 18:49:52 -07005643 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08005644
Glenn Kastenc05b8d72016-03-24 09:48:17 -07005645 AutoPark<FastMixer> park(mFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08005646
Eric Laurent10351942014-05-08 18:49:52 -07005647 AudioParameter param = AudioParameter(keyValuePair);
5648 int value;
5649 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
5650 reconfig = true;
5651 }
5652 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07005653 if (!isValidPcmSinkFormat((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07005654 status = BAD_VALUE;
5655 } else {
5656 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08005657 reconfig = true;
5658 }
Eric Laurent10351942014-05-08 18:49:52 -07005659 }
5660 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07005661 if (!isValidPcmSinkChannelMask((audio_channel_mask_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07005662 status = BAD_VALUE;
5663 } else {
5664 // no need to save value, since it's constant
5665 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08005666 }
Eric Laurent10351942014-05-08 18:49:52 -07005667 }
5668 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
5669 // do not accept frame count changes if tracks are open as the track buffer
5670 // size depends on frame count and correct behavior would not be guaranteed
5671 // if frame count is changed after track creation
5672 if (!mTracks.isEmpty()) {
5673 status = INVALID_OPERATION;
5674 } else {
5675 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08005676 }
Eric Laurent10351942014-05-08 18:49:52 -07005677 }
5678 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07005679 LOG_FATAL("Should not set routing device in MixerThread");
Eric Laurent10351942014-05-08 18:49:52 -07005680 }
Eric Laurent81784c32012-11-19 14:55:58 -08005681
Eric Laurent10351942014-05-08 18:49:52 -07005682 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005683 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07005684 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08005685 mOutput->standby();
Andy Hungcf10d742020-04-28 15:38:24 -07005686 if (!mStandby) {
5687 mThreadMetrics.logEndInterval();
5688 mStandby = true;
5689 }
Eric Laurent10351942014-05-08 18:49:52 -07005690 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005691 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent81784c32012-11-19 14:55:58 -08005692 }
Eric Laurent10351942014-05-08 18:49:52 -07005693 if (status == NO_ERROR && reconfig) {
5694 readOutputParameters_l();
5695 delete mAudioMixer;
5696 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
Andy Hung1bc088a2018-02-09 15:57:31 -08005697 for (const auto &track : mTracks) {
Andy Hungc0691382018-09-12 18:01:57 -07005698 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08005699 status_t status = mAudioMixer->create(
Andy Hungc0691382018-09-12 18:01:57 -07005700 trackId,
Andy Hung1bc088a2018-02-09 15:57:31 -08005701 track->mChannelMask,
5702 track->mFormat,
5703 track->mSessionId);
5704 ALOGW_IF(status != NO_ERROR,
Andy Hungc0691382018-09-12 18:01:57 -07005705 "%s(): AudioMixer cannot create track(%d)"
5706 " mask %#x, format %#x, sessionId %d",
Andy Hung1bc088a2018-02-09 15:57:31 -08005707 __func__,
Andy Hungc0691382018-09-12 18:01:57 -07005708 trackId, track->mChannelMask, track->mFormat, track->mSessionId);
Eric Laurent10351942014-05-08 18:49:52 -07005709 }
Eric Laurent73e26b62015-04-27 16:55:58 -07005710 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07005711 }
Eric Laurent81784c32012-11-19 14:55:58 -08005712 }
5713
Dean Wheatley68918102021-03-19 22:09:19 +11005714 return reconfig;
Eric Laurent81784c32012-11-19 14:55:58 -08005715}
5716
5717
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07005718void AudioFlinger::MixerThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -08005719{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07005720 PlaybackThread::dumpInternals_l(fd, args);
Andy Hung40eb1a12015-06-18 13:42:02 -07005721 dprintf(fd, " Thread throttle time (msecs): %u\n", mThreadThrottleTimeMs);
Andy Hung8ed196a2018-01-05 13:21:11 -08005722 dprintf(fd, " AudioMixer tracks: %s\n", mAudioMixer->trackNames().c_str());
Andy Hung2ddee192015-12-18 17:34:44 -08005723 dprintf(fd, " Master mono: %s\n", mMasterMono ? "on" : "off");
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01005724 dprintf(fd, " Master balance: %f (%s)\n", mMasterBalance.load(),
5725 (hasFastMixer() ? std::to_string(mFastMixer->getMasterBalance())
5726 : mBalance.toString()).c_str());
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08005727 if (hasFastMixer()) {
5728 dprintf(fd, " FastMixer thread %p tid=%d", mFastMixer.get(), mFastMixer->getTid());
5729
5730 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
5731 // while we are dumping it. It may be inconsistent, but it won't mutate!
5732 // This is a large object so we place it on the heap.
5733 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
Eric Tan2942a4e2018-09-12 17:41:27 -07005734 const std::unique_ptr<FastMixerDumpState> copy =
5735 std::make_unique<FastMixerDumpState>(mFastMixerDumpState);
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08005736 copy->dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08005737
5738#ifdef STATE_QUEUE_DUMP
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08005739 // Similar for state queue
5740 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
5741 observerCopy.dump(fd);
5742 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
5743 mutatorCopy.dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08005744#endif
5745
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08005746#ifdef AUDIO_WATCHDOG
5747 if (mAudioWatchdog != 0) {
5748 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
5749 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
5750 wdCopy.dump(fd);
5751 }
5752#endif
5753
5754 } else {
5755 dprintf(fd, " No FastMixer\n");
5756 }
Eric Laurent81784c32012-11-19 14:55:58 -08005757}
5758
5759uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
5760{
5761 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
5762}
5763
5764uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
5765{
5766 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
5767}
5768
5769void AudioFlinger::MixerThread::cacheParameters_l()
5770{
5771 PlaybackThread::cacheParameters_l();
5772
5773 // FIXME: Relaxed timing because of a certain device that can't meet latency
5774 // Should be reduced to 2x after the vendor fixes the driver issue
5775 // increase threshold again due to low power audio mode. The way this warning
5776 // threshold is calculated and its usefulness should be reconsidered anyway.
5777 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
5778}
5779
5780// ----------------------------------------------------------------------------
5781
5782AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
jiabinc52b1ff2019-10-31 17:20:42 -07005783 AudioStreamOut* output, audio_io_handle_t id, ThreadBase::type_t type, bool systemReady)
5784 : PlaybackThread(audioFlinger, output, id, type, systemReady)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005785{
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01005786 setMasterBalance(audioFlinger->getMasterBalance_l());
Eric Laurentbfb1b832013-01-07 09:53:42 -08005787}
5788
Eric Laurent81784c32012-11-19 14:55:58 -08005789AudioFlinger::DirectOutputThread::~DirectOutputThread()
5790{
5791}
5792
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07005793void AudioFlinger::DirectOutputThread::dumpInternals_l(int fd, const Vector<String16>& args)
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01005794{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07005795 PlaybackThread::dumpInternals_l(fd, args);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01005796 dprintf(fd, " Master balance: %f Left: %f Right: %f\n",
5797 mMasterBalance.load(), mMasterBalanceLeft, mMasterBalanceRight);
5798}
5799
5800void AudioFlinger::DirectOutputThread::setMasterBalance(float balance)
5801{
5802 Mutex::Autolock _l(mLock);
5803 if (mMasterBalance != balance) {
5804 mMasterBalance.store(balance);
5805 mBalance.computeStereoBalance(balance, &mMasterBalanceLeft, &mMasterBalanceRight);
5806 broadcast_l();
5807 }
5808}
5809
Eric Laurent5850c4c2016-11-10 13:04:31 -08005810void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005811{
Eric Laurentbfb1b832013-01-07 09:53:42 -08005812 float left, right;
5813
Andy Hung333ab962019-05-28 20:23:35 -07005814 // Ensure volumeshaper state always advances even when muted.
5815 const sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
5816 const auto [shaperVolume, shaperActive] = track->getVolumeHandler()->getVolume(
5817 proxy->framesReleased());
5818 mVolumeShaperActive = shaperActive;
5819
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08005820 if (mMasterMute || mStreamTypes[track->streamType()].mute || track->isPlaybackRestricted()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08005821 left = right = 0;
5822 } else {
5823 float typeVolume = mStreamTypes[track->streamType()].volume;
Andy Hung333ab962019-05-28 20:23:35 -07005824 const float v = mMasterVolume * typeVolume * shaperVolume;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005825
Glenn Kastenc56f3422014-03-21 17:53:17 -07005826 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
5827 left = float_from_gain(gain_minifloat_unpack_left(vlr));
5828 if (left > GAIN_FLOAT_UNITY) {
5829 left = GAIN_FLOAT_UNITY;
5830 }
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01005831 left *= v * mMasterBalanceLeft; // DirectOutputThread balance applied as track volume
Glenn Kastenc56f3422014-03-21 17:53:17 -07005832 right = float_from_gain(gain_minifloat_unpack_right(vlr));
5833 if (right > GAIN_FLOAT_UNITY) {
5834 right = GAIN_FLOAT_UNITY;
5835 }
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01005836 right *= v * mMasterBalanceRight;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005837 }
5838
5839 if (lastTrack) {
Kevin Rocard12381092018-04-11 09:19:59 -07005840 track->setFinalVolume((left + right) / 2.f);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005841 if (left != mLeftVolFloat || right != mRightVolFloat) {
5842 mLeftVolFloat = left;
5843 mRightVolFloat = right;
5844
Eric Laurentbfb1b832013-01-07 09:53:42 -08005845 // Delegate volume control to effect in track effect chain if needed
5846 // only one effect chain can be present on DirectOutputThread, so if
5847 // there is one, the track is connected to it
5848 if (!mEffectChains.isEmpty()) {
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09005849 // if effect chain exists, volume is handled by it.
5850 // Convert volumes from float to 8.24
5851 uint32_t vl = (uint32_t)(left * (1 << 24));
5852 uint32_t vr = (uint32_t)(right * (1 << 24));
5853 // Direct/Offload effect chains set output volume in setVolume_l().
5854 (void)mEffectChains[0]->setVolume_l(&vl, &vr);
5855 } else {
5856 // otherwise we directly set the volume.
5857 setVolumeForOutput_l(left, right);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005858 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005859 }
5860 }
5861}
5862
Phil Burk43b4dcc2015-06-09 16:53:44 -07005863void AudioFlinger::DirectOutputThread::onAddNewTrack_l()
5864{
5865 sp<Track> previousTrack = mPreviousTrack.promote();
Andy Hungdae27702016-10-31 14:01:16 -07005866 sp<Track> latestTrack = mActiveTracks.getLatest();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005867
Eric Laurent0f0631e2015-07-06 18:01:25 -07005868 if (previousTrack != 0 && latestTrack != 0) {
5869 if (mType == DIRECT) {
5870 if (previousTrack.get() != latestTrack.get()) {
5871 mFlushPending = true;
5872 }
5873 } else /* mType == OFFLOAD */ {
5874 if (previousTrack->sessionId() != latestTrack->sessionId()) {
5875 mFlushPending = true;
5876 }
5877 }
Revathi Uddaraju20413a92016-10-13 17:16:14 +08005878 } else if (previousTrack == 0) {
5879 // there could be an old track added back during track transition for direct
5880 // output, so always issues flush to flush data of the previous track if it
5881 // was already destroyed with HAL paused, then flush can resume the playback
5882 mFlushPending = true;
Phil Burk43b4dcc2015-06-09 16:53:44 -07005883 }
5884 PlaybackThread::onAddNewTrack_l();
5885}
Eric Laurentbfb1b832013-01-07 09:53:42 -08005886
Eric Laurent81784c32012-11-19 14:55:58 -08005887AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
5888 Vector< sp<Track> > *tracksToRemove
5889)
5890{
Eric Laurentd595b7c2013-04-03 17:27:56 -07005891 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08005892 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005893 bool doHwPause = false;
5894 bool doHwResume = false;
Eric Laurent81784c32012-11-19 14:55:58 -08005895
5896 // find out which tracks need to be processed
Andy Hungdae27702016-10-31 14:01:16 -07005897 for (const sp<Track> &t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08005898 if (t->isInvalid()) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07005899 ALOGW("An invalidated track shouldn't be in active list");
Eric Laurent5850c4c2016-11-10 13:04:31 -08005900 tracksToRemove->add(t);
Phil Burk43b4dcc2015-06-09 16:53:44 -07005901 continue;
5902 }
5903
Eric Laurent5850c4c2016-11-10 13:04:31 -08005904 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005905#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurent81784c32012-11-19 14:55:58 -08005906 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005907#endif
Eric Laurentfd477972013-10-25 18:10:40 -07005908 // Only consider last track started for volume and mixer state control.
5909 // In theory an older track could underrun and restart after the new one starts
5910 // but as we only care about the transition phase between two tracks on a
5911 // direct output, it is not a problem to ignore the underrun case.
Andy Hungdae27702016-10-31 14:01:16 -07005912 sp<Track> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08005913 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08005914
Kuowei Li23666472021-01-20 10:23:25 +08005915 if (track->isPausePending()) {
5916 track->pauseAck();
5917 // It is possible a track might have been flushed or stopped.
5918 // Other operations such as flush pending might occur on the next prepare.
5919 if (track->isPausing()) {
5920 track->setPaused();
5921 }
5922 // Always perform pause, as an immediate flush will change
5923 // the pause state to be no longer isPausing().
Phil Burk6fc2a7c2015-04-30 16:08:10 -07005924 if (mHwSupportsPause && last && !mHwPaused) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005925 doHwPause = true;
5926 mHwPaused = true;
5927 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08005928 } else if (track->isFlushPending()) {
5929 track->flushAck();
5930 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07005931 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005932 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07005933 } else if (track->isResumePending()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005934 track->resumeAck();
Eric Laurent3df841a2016-07-15 15:15:40 -07005935 if (last) {
5936 mLeftVolFloat = mRightVolFloat = -1.0;
5937 if (mHwPaused) {
5938 doHwResume = true;
5939 mHwPaused = false;
5940 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08005941 }
5942 }
5943
Eric Laurent81784c32012-11-19 14:55:58 -08005944 // The first time a track is added we wait
Phil Burk99adee32014-12-10 16:46:30 -08005945 // for all its buffers to be filled before processing it.
5946 // Allow draining the buffer in case the client
5947 // app does not call stop() and relies on underrun to stop:
5948 // hence the test on (track->mRetryCount > 1).
Andy Hung455982f2021-04-27 17:46:12 -07005949 // If track->mRetryCount <= 1 then track is about to be disabled, paused, removed,
5950 // so we accept any nonzero amount of data delivered by the AudioTrack (which will
5951 // reset the retry counter).
Phil Burkca5e6142015-07-14 09:42:29 -07005952 // Do not use a high threshold for compressed audio.
Andy Hung455982f2021-04-27 17:46:12 -07005953
5954 // target retry count that we will use is based on the time we wait for retries.
5955 const int32_t targetRetryCount = kMaxTrackRetriesDirectMs * 1000 / mActiveSleepTimeUs;
5956 // the retry threshold is when we accept any size for PCM data. This is slightly
5957 // smaller than the retry count so we can push small bits of data without a glitch.
5958 const int32_t retryThreshold = targetRetryCount > 2 ? targetRetryCount - 1 : 1;
Eric Laurent81784c32012-11-19 14:55:58 -08005959 uint32_t minFrames;
Phil Burk99adee32014-12-10 16:46:30 -08005960 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
Andy Hung455982f2021-04-27 17:46:12 -07005961 && (track->mRetryCount > retryThreshold) && audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005962 minFrames = mNormalFrameCount;
5963 } else {
5964 minFrames = 1;
5965 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005966
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07005967 const size_t framesReady = track->framesReady();
5968 const int trackId = track->id();
5969 if (ATRACE_ENABLED()) {
5970 std::string traceName("nRdy");
5971 traceName += std::to_string(trackId);
5972 ATRACE_INT(traceName.c_str(), framesReady);
5973 }
5974 if ((framesReady >= minFrames) && track->isReady() && !track->isPaused() &&
Eric Laurentab5cdba2014-06-09 17:22:27 -07005975 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08005976 {
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07005977 ALOGVV("track(%d) s=%08x [OK]", trackId, cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08005978
5979 if (track->mFillingUpStatus == Track::FS_FILLED) {
5980 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07005981 if (last) {
5982 // make sure processVolume_l() will apply new volume even if 0
5983 mLeftVolFloat = mRightVolFloat = -1.0;
5984 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08005985 if (!mHwSupportsPause) {
5986 track->resumeAck();
Eric Laurent81784c32012-11-19 14:55:58 -08005987 }
5988 }
5989
5990 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08005991 processVolume_l(track, last);
5992 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07005993 sp<Track> previousTrack = mPreviousTrack.promote();
5994 if (previousTrack != 0) {
5995 if (track != previousTrack.get()) {
5996 // Flush any data still being written from last track
5997 mBytesRemaining = 0;
Eric Laurent0f0631e2015-07-06 18:01:25 -07005998 // Invalidate previous track to force a seek when resuming.
5999 previousTrack->invalidate();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006000 }
6001 }
6002 mPreviousTrack = track;
6003
Eric Laurentd595b7c2013-04-03 17:27:56 -07006004 // reset retry count
Andy Hung455982f2021-04-27 17:46:12 -07006005 track->mRetryCount = targetRetryCount;
Eric Laurent5850c4c2016-11-10 13:04:31 -08006006 mActiveTrack = t;
Eric Laurentd595b7c2013-04-03 17:27:56 -07006007 mixerStatus = MIXER_TRACKS_READY;
Eric Laurent5cff4032015-05-26 13:49:58 -07006008 if (mHwPaused) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08006009 doHwResume = true;
6010 mHwPaused = false;
6011 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07006012 }
Eric Laurent81784c32012-11-19 14:55:58 -08006013 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07006014 // clear effect chain input buffer if the last active track started underruns
6015 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07006016 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08006017 mEffectChains[0]->clearInputBuffer();
6018 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07006019 if (track->isStopping_1()) {
6020 track->mState = TrackBase::STOPPING_2;
Eric Laurentb369caf2015-03-30 20:51:47 -07006021 if (last && mHwPaused) {
6022 doHwResume = true;
6023 mHwPaused = false;
6024 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07006025 }
6026 if ((track->sharedBuffer() != 0) || track->isStopped() ||
6027 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08006028 // We have consumed all the buffers of this track.
6029 // Remove it from the list of active tracks.
Eric Laurentab5cdba2014-06-09 17:22:27 -07006030 size_t audioHALFrames;
Phil Burkfdb3c072016-02-09 10:47:02 -08006031 if (audio_has_proportional_frames(mFormat)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07006032 audioHALFrames = (latency_l() * mSampleRate) / 1000;
6033 } else {
6034 audioHALFrames = 0;
6035 }
6036
Andy Hung818e7a32016-02-16 18:08:07 -08006037 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurentfd477972013-10-25 18:10:40 -07006038 if (mStandby || !last ||
Aniket Kumar Lata179a0742019-01-30 14:16:16 -08006039 track->presentationComplete(framesWritten, audioHALFrames) ||
Jindong32dc26e2019-11-11 18:10:01 +08006040 track->isPaused() || mHwPaused) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07006041 if (track->isStopping_2()) {
6042 track->mState = TrackBase::STOPPED;
6043 }
Eric Laurent81784c32012-11-19 14:55:58 -08006044 if (track->isStopped()) {
6045 track->reset();
6046 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07006047 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08006048 }
6049 } else {
6050 // No buffers for this track. Give it a few chances to
6051 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07006052 // Only consider last track started for mixer state control
Eric Laurent81784c32012-11-19 14:55:58 -08006053 if (--(track->mRetryCount) <= 0) {
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07006054 ALOGV("BUFFER TIMEOUT: remove track(%d) from active list", trackId);
Eric Laurentd595b7c2013-04-03 17:27:56 -07006055 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08006056 // indicate to client process that the track was disabled because of underrun;
6057 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08006058 track->disable();
Haynes Mathew George5c6daae2017-01-24 20:06:05 -08006059 // only do hw pause when track is going to be removed due to BUFFER TIMEOUT.
6060 // unlike mixerthread, HAL can be paused for direct output
Phil Burkca5e6142015-07-14 09:42:29 -07006061 ALOGW("pause because of UNDERRUN, framesReady = %zu,"
6062 "minFrames = %u, mFormat = %#x",
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07006063 framesReady, minFrames, mFormat);
Haynes Mathew George5c6daae2017-01-24 20:06:05 -08006064 if (last && mHwSupportsPause && !mHwPaused && !mStandby) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08006065 doHwPause = true;
6066 mHwPaused = true;
6067 }
Haynes Mathew George5c6daae2017-01-24 20:06:05 -08006068 } else if (last) {
6069 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurent81784c32012-11-19 14:55:58 -08006070 }
6071 }
6072 }
6073 }
6074
Eric Laurentd1f69b02014-12-15 14:33:13 -08006075 // if an active track did not command a flush, check for pending flush on stopped tracks
Phil Burk43b4dcc2015-06-09 16:53:44 -07006076 if (!mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006077 for (size_t i = 0; i < mTracks.size(); i++) {
6078 if (mTracks[i]->isFlushPending()) {
6079 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006080 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006081 }
6082 }
6083 }
6084
6085 // make sure the pause/flush/resume sequence is executed in the right order.
6086 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
6087 // before flush and then resume HW. This can happen in case of pause/flush/resume
6088 // if resume is received before pause is executed.
6089 if (mHwSupportsPause && !mStandby &&
Phil Burk43b4dcc2015-06-09 16:53:44 -07006090 (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006091 status_t result = mOutput->stream->pause();
6092 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08006093 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07006094 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006095 flushHw_l();
6096 }
6097 if (mHwSupportsPause && !mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006098 status_t result = mOutput->stream->resume();
6099 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08006100 }
Eric Laurent81784c32012-11-19 14:55:58 -08006101 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08006102 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08006103
6104 return mixerStatus;
6105}
6106
6107void AudioFlinger::DirectOutputThread::threadLoop_mix()
6108{
Eric Laurent81784c32012-11-19 14:55:58 -08006109 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08006110 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08006111 // output audio to hardware
6112 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07006113 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08006114 buffer.frameCount = frameCount;
Phil Burk062e67a2015-02-11 13:40:50 -08006115 status_t status = mActiveTrack->getNextBuffer(&buffer);
6116 if (status != NO_ERROR || buffer.raw == NULL) {
Eric Laurent51716182016-02-29 18:00:56 -08006117 // no need to pad with 0 for compressed audio
6118 if (audio_has_proportional_frames(mFormat)) {
6119 memset(curBuf, 0, frameCount * mFrameSize);
6120 }
Eric Laurent81784c32012-11-19 14:55:58 -08006121 break;
6122 }
6123 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
6124 frameCount -= buffer.frameCount;
6125 curBuf += buffer.frameCount * mFrameSize;
6126 mActiveTrack->releaseBuffer(&buffer);
6127 }
Andy Hung2098f272014-02-27 14:00:06 -08006128 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006129 mSleepTimeUs = 0;
6130 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08006131 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08006132}
6133
6134void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
6135{
Eric Laurentd1f69b02014-12-15 14:33:13 -08006136 // do not write to HAL when paused
Eric Laurent0f7b5f22014-12-19 10:43:21 -08006137 if (mHwPaused || (usesHwAvSync() && mStandby)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006138 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006139 return;
6140 }
Andy Hung85ba3332021-04-27 17:40:26 -07006141 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
6142 mSleepTimeUs = mActiveSleepTimeUs;
6143 } else {
6144 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006145 }
Andy Hung85ba3332021-04-27 17:40:26 -07006146 // Note: In S or later, we do not write zeroes for
6147 // linear or proportional PCM direct tracks in underrun.
Eric Laurent81784c32012-11-19 14:55:58 -08006148}
6149
Eric Laurentd1f69b02014-12-15 14:33:13 -08006150void AudioFlinger::DirectOutputThread::threadLoop_exit()
6151{
6152 {
6153 Mutex::Autolock _l(mLock);
Eric Laurentd1f69b02014-12-15 14:33:13 -08006154 for (size_t i = 0; i < mTracks.size(); i++) {
6155 if (mTracks[i]->isFlushPending()) {
6156 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006157 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006158 }
6159 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07006160 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006161 flushHw_l();
6162 }
6163 }
6164 PlaybackThread::threadLoop_exit();
6165}
6166
6167// must be called with thread mutex locked
6168bool AudioFlinger::DirectOutputThread::shouldStandby_l()
6169{
6170 bool trackPaused = false;
Eric Laurentb369caf2015-03-30 20:51:47 -07006171 bool trackStopped = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006172
6173 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
6174 // after a timeout and we will enter standby then.
6175 if (mTracks.size() > 0) {
6176 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
Eric Laurentb369caf2015-03-30 20:51:47 -07006177 trackStopped = mTracks[mTracks.size() - 1]->isStopped() ||
6178 mTracks[mTracks.size() - 1]->mState == TrackBase::IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006179 }
6180
Eric Laurent5cff4032015-05-26 13:49:58 -07006181 return !mStandby && !(trackPaused || (mHwPaused && !trackStopped));
Eric Laurentd1f69b02014-12-15 14:33:13 -08006182}
6183
Eric Laurent10351942014-05-08 18:49:52 -07006184// checkForNewParameter_l() must be called with ThreadBase::mLock held
6185bool AudioFlinger::DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
6186 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08006187{
6188 bool reconfig = false;
Eric Laurent10351942014-05-08 18:49:52 -07006189 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006190
Eric Laurent10351942014-05-08 18:49:52 -07006191 AudioParameter param = AudioParameter(keyValuePair);
6192 int value;
6193 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07006194 LOG_FATAL("Should not set routing device in DirectOutputThread");
Eric Laurent81784c32012-11-19 14:55:58 -08006195 }
Eric Laurent10351942014-05-08 18:49:52 -07006196 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6197 // do not accept frame count changes if tracks are open as the track buffer
6198 // size depends on frame count and correct behavior would not be garantied
6199 // if frame count is changed after track creation
6200 if (!mTracks.isEmpty()) {
6201 status = INVALID_OPERATION;
6202 } else {
6203 reconfig = true;
6204 }
6205 }
6206 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006207 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07006208 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08006209 mOutput->standby();
Andy Hungcf10d742020-04-28 15:38:24 -07006210 if (!mStandby) {
6211 mThreadMetrics.logEndInterval();
6212 mStandby = true;
6213 }
Eric Laurent10351942014-05-08 18:49:52 -07006214 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006215 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07006216 }
6217 if (status == NO_ERROR && reconfig) {
6218 readOutputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07006219 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07006220 }
6221 }
6222
Dean Wheatley68918102021-03-19 22:09:19 +11006223 return reconfig;
Eric Laurent81784c32012-11-19 14:55:58 -08006224}
6225
6226uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
6227{
6228 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08006229 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006230 time = PlaybackThread::activeSleepTimeUs();
6231 } else {
Eric Laurent51716182016-02-29 18:00:56 -08006232 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006233 }
6234 return time;
6235}
6236
6237uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
6238{
6239 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08006240 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006241 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
6242 } else {
Eric Laurent51716182016-02-29 18:00:56 -08006243 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006244 }
6245 return time;
6246}
6247
6248uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
6249{
6250 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08006251 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006252 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
6253 } else {
Eric Laurent51716182016-02-29 18:00:56 -08006254 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006255 }
6256 return time;
6257}
6258
6259void AudioFlinger::DirectOutputThread::cacheParameters_l()
6260{
6261 PlaybackThread::cacheParameters_l();
6262
6263 // use shorter standby delay as on normal output to release
6264 // hardware resources as soon as possible
Eric Laurentb369caf2015-03-30 20:51:47 -07006265 // no delay on outputs with HW A/V sync
6266 if (usesHwAvSync()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006267 mStandbyDelayNs = 0;
Phil Burkfdb3c072016-02-09 10:47:02 -08006268 } else if ((mType == OFFLOAD) && !audio_has_proportional_frames(mFormat)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006269 mStandbyDelayNs = kOffloadStandbyDelayNs;
Eric Laurent5cff4032015-05-26 13:49:58 -07006270 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006271 mStandbyDelayNs = microseconds(mActiveSleepTimeUs*2);
Eric Laurent972a1732013-09-04 09:42:59 -07006272 }
Eric Laurent81784c32012-11-19 14:55:58 -08006273}
6274
Eric Laurente659ef42014-09-29 13:06:46 -07006275void AudioFlinger::DirectOutputThread::flushHw_l()
6276{
Phil Burk062e67a2015-02-11 13:40:50 -08006277 mOutput->flush();
Eric Laurentd1f69b02014-12-15 14:33:13 -08006278 mHwPaused = false;
Phil Burk43b4dcc2015-06-09 16:53:44 -07006279 mFlushPending = false;
Dean Wheatley12473e92021-03-18 23:00:55 +11006280 mTimestampVerifier.discontinuity(discontinuityForStandbyOrFlush());
Sampath Shetty999f0e82020-01-15 10:19:06 +11006281 mTimestamp.clear();
Eric Laurente659ef42014-09-29 13:06:46 -07006282}
6283
Andy Hung10cbff12017-02-21 17:30:14 -08006284int64_t AudioFlinger::DirectOutputThread::computeWaitTimeNs_l() const {
6285 // If a VolumeShaper is active, we must wake up periodically to update volume.
6286 const int64_t NS_PER_MS = 1000000;
6287 return mVolumeShaperActive ?
6288 kMinNormalSinkBufferSizeMs * NS_PER_MS : PlaybackThread::computeWaitTimeNs_l();
6289}
6290
Eric Laurent81784c32012-11-19 14:55:58 -08006291// ----------------------------------------------------------------------------
6292
Eric Laurentbfb1b832013-01-07 09:53:42 -08006293AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
Eric Laurent4de95592013-09-26 15:28:21 -07006294 const wp<AudioFlinger::PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006295 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07006296 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07006297 mWriteAckSequence(0),
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006298 mDrainSequence(0),
6299 mAsyncError(false)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006300{
6301}
6302
6303AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
6304{
6305}
6306
6307void AudioFlinger::AsyncCallbackThread::onFirstRef()
6308{
6309 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
6310}
6311
6312bool AudioFlinger::AsyncCallbackThread::threadLoop()
6313{
6314 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07006315 uint32_t writeAckSequence;
6316 uint32_t drainSequence;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006317 bool asyncError;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006318
6319 {
6320 Mutex::Autolock _l(mLock);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08006321 while (!((mWriteAckSequence & 1) ||
6322 (mDrainSequence & 1) ||
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006323 mAsyncError ||
Haynes Mathew George24a325d2013-12-03 21:26:02 -08006324 exitPending())) {
6325 mWaitWorkCV.wait(mLock);
6326 }
6327
Eric Laurentbfb1b832013-01-07 09:53:42 -08006328 if (exitPending()) {
6329 break;
6330 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07006331 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
6332 mWriteAckSequence, mDrainSequence);
6333 writeAckSequence = mWriteAckSequence;
6334 mWriteAckSequence &= ~1;
6335 drainSequence = mDrainSequence;
6336 mDrainSequence &= ~1;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006337 asyncError = mAsyncError;
6338 mAsyncError = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006339 }
6340 {
Eric Laurent4de95592013-09-26 15:28:21 -07006341 sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
6342 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07006343 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07006344 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006345 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07006346 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07006347 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006348 }
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006349 if (asyncError) {
6350 playbackThread->onAsyncError();
6351 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006352 }
6353 }
6354 }
6355 return false;
6356}
6357
6358void AudioFlinger::AsyncCallbackThread::exit()
6359{
6360 ALOGV("AsyncCallbackThread::exit");
6361 Mutex::Autolock _l(mLock);
6362 requestExit();
6363 mWaitWorkCV.broadcast();
6364}
6365
Eric Laurent3b4529e2013-09-05 18:09:19 -07006366void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006367{
6368 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07006369 // bit 0 is cleared
6370 mWriteAckSequence = sequence << 1;
6371}
6372
6373void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
6374{
6375 Mutex::Autolock _l(mLock);
6376 // ignore unexpected callbacks
6377 if (mWriteAckSequence & 2) {
6378 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006379 mWaitWorkCV.signal();
6380 }
6381}
6382
Eric Laurent3b4529e2013-09-05 18:09:19 -07006383void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006384{
6385 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07006386 // bit 0 is cleared
6387 mDrainSequence = sequence << 1;
6388}
6389
6390void AudioFlinger::AsyncCallbackThread::resetDraining()
6391{
6392 Mutex::Autolock _l(mLock);
6393 // ignore unexpected callbacks
6394 if (mDrainSequence & 2) {
6395 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006396 mWaitWorkCV.signal();
6397 }
6398}
6399
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006400void AudioFlinger::AsyncCallbackThread::setAsyncError()
6401{
6402 Mutex::Autolock _l(mLock);
6403 mAsyncError = true;
6404 mWaitWorkCV.signal();
6405}
6406
Eric Laurentbfb1b832013-01-07 09:53:42 -08006407
6408// ----------------------------------------------------------------------------
6409AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
jiabinc52b1ff2019-10-31 17:20:42 -07006410 AudioStreamOut* output, audio_io_handle_t id, bool systemReady)
6411 : DirectOutputThread(audioFlinger, output, id, OFFLOAD, systemReady),
Andy Hungf8044752016-07-27 14:58:11 -07006412 mPausedWriteLength(0), mPausedBytesRemaining(0), mKeepWakeLock(true),
6413 mOffloadUnderrunPosition(~0LL)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006414{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07006415 //FIXME: mStandby should be set to true by ThreadBase constructo
Eric Laurentfd477972013-10-25 18:10:40 -07006416 mStandby = true;
Eric Laurent64667972016-03-30 18:19:46 -07006417 mKeepWakeLock = property_get_bool("ro.audio.offload_wakelock", true /* default_value */);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006418}
6419
Eric Laurentbfb1b832013-01-07 09:53:42 -08006420void AudioFlinger::OffloadThread::threadLoop_exit()
6421{
6422 if (mFlushPending || mHwPaused) {
6423 // If a flush is pending or track was paused, just discard buffered data
6424 flushHw_l();
6425 } else {
6426 mMixerStatus = MIXER_DRAIN_ALL;
6427 threadLoop_drain();
6428 }
Uday Gupta56604aa2014-05-13 11:19:17 -07006429 if (mUseAsyncWrite) {
6430 ALOG_ASSERT(mCallbackThread != 0);
6431 mCallbackThread->exit();
6432 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006433 PlaybackThread::threadLoop_exit();
6434}
6435
6436AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
6437 Vector< sp<Track> > *tracksToRemove
6438)
6439{
Eric Laurentbfb1b832013-01-07 09:53:42 -08006440 size_t count = mActiveTracks.size();
6441
6442 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07006443 bool doHwPause = false;
6444 bool doHwResume = false;
6445
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006446 ALOGV("OffloadThread::prepareTracks_l active tracks %zu", count);
Eric Laurentede6c3b2013-09-19 14:37:46 -07006447
Eric Laurentbfb1b832013-01-07 09:53:42 -08006448 // find out which tracks need to be processed
Andy Hungdae27702016-10-31 14:01:16 -07006449 for (const sp<Track> &t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08006450 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006451#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurentbfb1b832013-01-07 09:53:42 -08006452 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006453#endif
Eric Laurentfd477972013-10-25 18:10:40 -07006454 // Only consider last track started for volume and mixer state control.
6455 // In theory an older track could underrun and restart after the new one starts
6456 // but as we only care about the transition phase between two tracks on a
6457 // direct output, it is not a problem to ignore the underrun case.
Andy Hungdae27702016-10-31 14:01:16 -07006458 sp<Track> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08006459 bool last = l.get() == track;
Eric Laurentfd477972013-10-25 18:10:40 -07006460
Haynes Mathew George7844f672014-01-15 12:32:55 -08006461 if (track->isInvalid()) {
6462 ALOGW("An invalidated track shouldn't be in active list");
6463 tracksToRemove->add(track);
6464 continue;
6465 }
6466
6467 if (track->mState == TrackBase::IDLE) {
6468 ALOGW("An idle track shouldn't be in active list");
6469 continue;
6470 }
6471
Kuowei Li23666472021-01-20 10:23:25 +08006472 if (track->isPausePending()) {
6473 track->pauseAck();
6474 // It is possible a track might have been flushed or stopped.
6475 // Other operations such as flush pending might occur on the next prepare.
6476 if (track->isPausing()) {
6477 track->setPaused();
6478 }
6479 // Always perform pause if last, as an immediate flush will change
6480 // the pause state to be no longer isPausing().
Eric Laurentbfb1b832013-01-07 09:53:42 -08006481 if (last) {
Eric Laurent5cff4032015-05-26 13:49:58 -07006482 if (mHwSupportsPause && !mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07006483 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006484 mHwPaused = true;
6485 }
6486 // If we were part way through writing the mixbuffer to
6487 // the HAL we must save this until we resume
6488 // BUG - this will be wrong if a different track is made active,
6489 // in that case we want to discard the pending data in the
6490 // mixbuffer and tell the client to present it again when the
6491 // track is resumed
6492 mPausedWriteLength = mCurrentWriteLength;
6493 mPausedBytesRemaining = mBytesRemaining;
6494 mBytesRemaining = 0; // stop writing
6495 }
6496 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08006497 } else if (track->isFlushPending()) {
Eric Laurente93cc032016-05-05 10:15:10 -07006498 if (track->isStopping_1()) {
6499 track->mRetryCount = kMaxTrackStopRetriesOffload;
6500 } else {
6501 track->mRetryCount = kMaxTrackRetriesOffload;
6502 }
Haynes Mathew George7844f672014-01-15 12:32:55 -08006503 track->flushAck();
6504 if (last) {
6505 mFlushPending = true;
6506 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08006507 } else if (track->isResumePending()){
6508 track->resumeAck();
6509 if (last) {
6510 if (mPausedBytesRemaining) {
6511 // Need to continue write that was interrupted
6512 mCurrentWriteLength = mPausedWriteLength;
6513 mBytesRemaining = mPausedBytesRemaining;
6514 mPausedBytesRemaining = 0;
6515 }
6516 if (mHwPaused) {
6517 doHwResume = true;
6518 mHwPaused = false;
6519 // threadLoop_mix() will handle the case that we need to
6520 // resume an interrupted write
6521 }
6522 // enable write to audio HAL
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006523 mSleepTimeUs = 0;
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08006524
Eric Laurent3df841a2016-07-15 15:15:40 -07006525 mLeftVolFloat = mRightVolFloat = -1.0;
6526
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08006527 // Do not handle new data in this iteration even if track->framesReady()
6528 mixerStatus = MIXER_TRACKS_ENABLED;
6529 }
6530 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07006531 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Andy Hungc0691382018-09-12 18:01:57 -07006532 ALOGVV("OffloadThread: track(%d) s=%08x [OK]", track->id(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006533 if (track->mFillingUpStatus == Track::FS_FILLED) {
6534 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07006535 if (last) {
6536 // make sure processVolume_l() will apply new volume even if 0
6537 mLeftVolFloat = mRightVolFloat = -1.0;
6538 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006539 }
6540
6541 if (last) {
Eric Laurentd7e59222013-11-15 12:02:28 -08006542 sp<Track> previousTrack = mPreviousTrack.promote();
6543 if (previousTrack != 0) {
6544 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08006545 // Flush any data still being written from last track
6546 mBytesRemaining = 0;
6547 if (mPausedBytesRemaining) {
6548 // Last track was paused so we also need to flush saved
6549 // mixbuffer state and invalidate track so that it will
6550 // re-submit that unwritten data when it is next resumed
6551 mPausedBytesRemaining = 0;
6552 // Invalidate is a bit drastic - would be more efficient
6553 // to have a flag to tell client that some of the
6554 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08006555 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08006556 }
6557 // flush data already sent to the DSP if changing audio session as audio
6558 // comes from a different source. Also invalidate previous track to force a
6559 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08006560 if (previousTrack->sessionId() != track->sessionId()) {
6561 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08006562 }
6563 }
6564 }
6565 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006566 // reset retry count
Eric Laurente93cc032016-05-05 10:15:10 -07006567 if (track->isStopping_1()) {
6568 track->mRetryCount = kMaxTrackStopRetriesOffload;
6569 } else {
6570 track->mRetryCount = kMaxTrackRetriesOffload;
6571 }
Eric Laurent5850c4c2016-11-10 13:04:31 -08006572 mActiveTrack = t;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006573 mixerStatus = MIXER_TRACKS_READY;
6574 }
6575 } else {
Andy Hungc0691382018-09-12 18:01:57 -07006576 ALOGVV("OffloadThread: track(%d) s=%08x [NOT READY]", track->id(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006577 if (track->isStopping_1()) {
Eric Laurente93cc032016-05-05 10:15:10 -07006578 if (--(track->mRetryCount) <= 0) {
6579 // Hardware buffer can hold a large amount of audio so we must
6580 // wait for all current track's data to drain before we say
6581 // that the track is stopped.
6582 if (mBytesRemaining == 0) {
6583 // Only start draining when all data in mixbuffer
6584 // has been written
6585 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
6586 track->mState = TrackBase::STOPPING_2; // so presentation completes after
6587 // drain do not drain if no data was ever sent to HAL (mStandby == true)
6588 if (last && !mStandby) {
6589 // do not modify drain sequence if we are already draining. This happens
6590 // when resuming from pause after drain.
6591 if ((mDrainSequence & 1) == 0) {
6592 mSleepTimeUs = 0;
6593 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
6594 mixerStatus = MIXER_DRAIN_TRACK;
6595 mDrainSequence += 2;
6596 }
6597 if (mHwPaused) {
6598 // It is possible to move from PAUSED to STOPPING_1 without
6599 // a resume so we must ensure hardware is running
6600 doHwResume = true;
6601 mHwPaused = false;
6602 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006603 }
6604 }
Eric Laurente93cc032016-05-05 10:15:10 -07006605 } else if (last) {
6606 ALOGV("stopping1 underrun retries left %d", track->mRetryCount);
6607 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006608 }
6609 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07006610 // Drain has completed or we are in standby, signal presentation complete
6611 if (!(mDrainSequence & 1) || !last || mStandby) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08006612 track->mState = TrackBase::STOPPED;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006613 uint32_t latency = 0;
6614 status_t result = mOutput->stream->getLatency(&latency);
6615 ALOGE_IF(result != OK,
6616 "Error when retrieving output stream latency: %d", result);
6617 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08006618 int64_t framesWritten =
Phil Burk062e67a2015-02-11 13:40:50 -08006619 mBytesWritten / mOutput->getFrameSize();
Eric Laurentbfb1b832013-01-07 09:53:42 -08006620 track->presentationComplete(framesWritten, audioHALFrames);
6621 track->reset();
6622 tracksToRemove->add(track);
Dean Wheatley12473e92021-03-18 23:00:55 +11006623 // OFFLOADED stop resets frame counts.
Andy Hungf3234512018-07-03 14:51:47 -07006624 if (!mUseAsyncWrite) {
6625 // If we don't get explicit drain notification we must
6626 // register discontinuity regardless of whether this is
6627 // the previous (!last) or the upcoming (last) track
6628 // to avoid skipping the discontinuity.
Dean Wheatley12473e92021-03-18 23:00:55 +11006629 mTimestampVerifier.discontinuity(
6630 mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Andy Hungf3234512018-07-03 14:51:47 -07006631 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006632 }
6633 } else {
6634 // No buffers for this track. Give it a few chances to
6635 // fill a buffer, then remove it from active list.
6636 if (--(track->mRetryCount) <= 0) {
Andy Hungf8044752016-07-27 14:58:11 -07006637 bool running = false;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006638 uint64_t position = 0;
6639 struct timespec unused;
6640 // The running check restarts the retry counter at least once.
6641 status_t ret = mOutput->stream->getPresentationPosition(&position, &unused);
6642 if (ret == NO_ERROR && position != mOffloadUnderrunPosition) {
6643 running = true;
6644 mOffloadUnderrunPosition = position;
6645 }
6646 if (ret == NO_ERROR) {
Andy Hungf8044752016-07-27 14:58:11 -07006647 ALOGVV("underrun counter, running(%d): %lld vs %lld", running,
6648 (long long)position, (long long)mOffloadUnderrunPosition);
6649 }
6650 if (running) { // still running, give us more time.
6651 track->mRetryCount = kMaxTrackRetriesOffload;
6652 } else {
Andy Hungc0691382018-09-12 18:01:57 -07006653 ALOGV("OffloadThread: BUFFER TIMEOUT: remove track(%d) from active list",
6654 track->id());
Andy Hungf8044752016-07-27 14:58:11 -07006655 tracksToRemove->add(track);
Glenn Kastend3bb6452016-12-05 18:14:37 -08006656 // tell client process that the track was disabled because of underrun;
Andy Hungf8044752016-07-27 14:58:11 -07006657 // it will then automatically call start() when data is available
6658 track->disable();
6659 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006660 } else if (last){
6661 mixerStatus = MIXER_TRACKS_ENABLED;
6662 }
6663 }
6664 }
6665 // compute volume for this track
Wenfeng Sun79458332019-05-29 20:12:43 +08006666 if (track->isReady()) { // check ready to prevent premature start.
6667 processVolume_l(track, last);
6668 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006669 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07006670
Eric Laurentea0fade2013-10-04 16:23:48 -07006671 // make sure the pause/flush/resume sequence is executed in the right order.
6672 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
6673 // before flush and then resume HW. This can happen in case of pause/flush/resume
6674 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07006675 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006676 status_t result = mOutput->stream->pause();
6677 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07006678 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07006679 if (mFlushPending) {
6680 flushHw_l();
Eric Laurent6bf9ae22013-08-30 15:12:37 -07006681 }
Eric Laurentfd477972013-10-25 18:10:40 -07006682 if (!mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006683 status_t result = mOutput->stream->resume();
6684 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07006685 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07006686
Eric Laurentbfb1b832013-01-07 09:53:42 -08006687 // remove all the tracks that need to be...
6688 removeTracks_l(*tracksToRemove);
6689
6690 return mixerStatus;
6691}
6692
Eric Laurentbfb1b832013-01-07 09:53:42 -08006693// must be called with thread mutex locked
6694bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
6695{
Eric Laurent3b4529e2013-09-05 18:09:19 -07006696 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
6697 mWriteAckSequence, mDrainSequence);
6698 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08006699 return true;
6700 }
6701 return false;
6702}
6703
Eric Laurentbfb1b832013-01-07 09:53:42 -08006704bool AudioFlinger::OffloadThread::waitingAsyncCallback()
6705{
6706 Mutex::Autolock _l(mLock);
6707 return waitingAsyncCallback_l();
6708}
6709
6710void AudioFlinger::OffloadThread::flushHw_l()
6711{
Eric Laurente659ef42014-09-29 13:06:46 -07006712 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08006713 // Flush anything still waiting in the mixbuffer
6714 mCurrentWriteLength = 0;
6715 mBytesRemaining = 0;
6716 mPausedWriteLength = 0;
6717 mPausedBytesRemaining = 0;
Eric Laurent3eaf66b2016-04-01 14:44:17 -07006718 // reset bytes written count to reflect that DSP buffers are empty after flush.
6719 mBytesWritten = 0;
Andy Hungf8044752016-07-27 14:58:11 -07006720 mOffloadUnderrunPosition = ~0LL;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08006721
Eric Laurentbfb1b832013-01-07 09:53:42 -08006722 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07006723 // discard any pending drain or write ack by incrementing sequence
6724 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
6725 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006726 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07006727 mCallbackThread->setWriteBlocked(mWriteAckSequence);
6728 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006729 }
6730}
6731
Haynes Mathew George05317d22016-05-03 16:34:26 -07006732void AudioFlinger::OffloadThread::invalidateTracks(audio_stream_type_t streamType)
6733{
6734 Mutex::Autolock _l(mLock);
Eric Laurent13084622016-05-17 10:51:49 -07006735 if (PlaybackThread::invalidateTracks_l(streamType)) {
6736 mFlushPending = true;
6737 }
Haynes Mathew George05317d22016-05-03 16:34:26 -07006738}
6739
Eric Laurentbfb1b832013-01-07 09:53:42 -08006740// ----------------------------------------------------------------------------
6741
Eric Laurent81784c32012-11-19 14:55:58 -08006742AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurent72e3f392015-05-20 14:43:50 -07006743 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id, bool systemReady)
jiabinc52b1ff2019-10-31 17:20:42 -07006744 : MixerThread(audioFlinger, mainThread->getOutput(), id,
Eric Laurent72e3f392015-05-20 14:43:50 -07006745 systemReady, DUPLICATING),
Eric Laurent81784c32012-11-19 14:55:58 -08006746 mWaitTimeMs(UINT_MAX)
6747{
6748 addOutputTrack(mainThread);
6749}
6750
6751AudioFlinger::DuplicatingThread::~DuplicatingThread()
6752{
6753 for (size_t i = 0; i < mOutputTracks.size(); i++) {
6754 mOutputTracks[i]->destroy();
6755 }
6756}
6757
6758void AudioFlinger::DuplicatingThread::threadLoop_mix()
6759{
6760 // mix buffers...
6761 if (outputsReady(outputTracks)) {
Glenn Kastend79072e2016-01-06 08:41:20 -08006762 mAudioMixer->process();
Eric Laurent81784c32012-11-19 14:55:58 -08006763 } else {
Eric Laurent02b57082014-11-07 17:28:28 -08006764 if (mMixerBufferValid) {
6765 memset(mMixerBuffer, 0, mMixerBufferSize);
6766 } else {
6767 memset(mSinkBuffer, 0, mSinkBufferSize);
6768 }
Eric Laurent81784c32012-11-19 14:55:58 -08006769 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006770 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08006771 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08006772 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006773 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08006774}
6775
6776void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
6777{
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006778 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006779 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006780 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006781 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006782 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006783 }
6784 } else if (mBytesWritten != 0) {
6785 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
6786 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08006787 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08006788 } else {
6789 // flush remaining overflow buffers in output tracks
6790 writeFrames = 0;
6791 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006792 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08006793 }
6794}
6795
Eric Laurentbfb1b832013-01-07 09:53:42 -08006796ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08006797{
6798 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hung1c86ebe2018-05-29 20:29:08 -07006799 const ssize_t actualWritten = outputTracks[i]->write(mSinkBuffer, writeFrames);
6800
6801 // Consider the first OutputTrack for timestamp and frame counting.
6802
6803 // The threadLoop() generally assumes writing a full sink buffer size at a time.
6804 // Here, we correct for writeFrames of 0 (a stop) or underruns because
6805 // we always claim success.
6806 if (i == 0) {
6807 const ssize_t correction = mSinkBufferSize / mFrameSize - actualWritten;
6808 ALOGD_IF(correction != 0 && writeFrames != 0,
6809 "%s: writeFrames:%u actualWritten:%zd correction:%zd mFramesWritten:%lld",
6810 __func__, writeFrames, actualWritten, correction, (long long)mFramesWritten);
6811 mFramesWritten -= correction;
6812 }
6813
6814 // TODO: Report correction for the other output tracks and show in the dump.
Eric Laurent81784c32012-11-19 14:55:58 -08006815 }
Andy Hungcf10d742020-04-28 15:38:24 -07006816 if (mStandby) {
6817 mThreadMetrics.logBeginInterval();
6818 mStandby = false;
6819 }
Andy Hung25c2dac2014-02-27 14:56:00 -08006820 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08006821}
6822
6823void AudioFlinger::DuplicatingThread::threadLoop_standby()
6824{
6825 // DuplicatingThread implements standby by stopping all tracks
6826 for (size_t i = 0; i < outputTracks.size(); i++) {
6827 outputTracks[i]->stop();
6828 }
6829}
6830
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07006831void AudioFlinger::DuplicatingThread::dumpInternals_l(int fd, const Vector<String16>& args __unused)
Andy Hung1bc088a2018-02-09 15:57:31 -08006832{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07006833 MixerThread::dumpInternals_l(fd, args);
Andy Hung1bc088a2018-02-09 15:57:31 -08006834
6835 std::stringstream ss;
6836 const size_t numTracks = mOutputTracks.size();
6837 ss << " " << numTracks << " OutputTracks";
6838 if (numTracks > 0) {
6839 ss << ":";
6840 for (const auto &track : mOutputTracks) {
6841 const sp<ThreadBase> thread = track->thread().promote();
Andy Hungc0691382018-09-12 18:01:57 -07006842 ss << " (" << track->id() << " : ";
Andy Hung1bc088a2018-02-09 15:57:31 -08006843 if (thread.get() != nullptr) {
6844 ss << thread.get() << ", " << thread->id();
6845 } else {
6846 ss << "null";
6847 }
6848 ss << ")";
6849 }
6850 }
6851 ss << "\n";
6852 std::string result = ss.str();
6853 write(fd, result.c_str(), result.size());
6854}
6855
Eric Laurent81784c32012-11-19 14:55:58 -08006856void AudioFlinger::DuplicatingThread::saveOutputTracks()
6857{
6858 outputTracks = mOutputTracks;
6859}
6860
6861void AudioFlinger::DuplicatingThread::clearOutputTracks()
6862{
6863 outputTracks.clear();
6864}
6865
6866void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
6867{
6868 Mutex::Autolock _l(mLock);
Andy Hungc25b84a2015-01-14 19:04:10 -08006869 // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
6870 // Adjust for thread->sampleRate() to determine minimum buffer frame count.
6871 // Then triple buffer because Threads do not run synchronously and may not be clock locked.
6872 const size_t frameCount =
6873 3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
6874 // TODO: Consider asynchronous sample rate conversion to handle clock disparity
6875 // from different OutputTracks and their associated MixerThreads (e.g. one may
6876 // nearly empty and the other may be dropping data).
6877
Philip P. Moltmannbda45752020-07-17 16:41:18 -07006878 // TODO b/182392769: use identity util, move to server edge
6879 Identity identity = Identity();
6880 identity.uid = VALUE_OR_FATAL(legacy2aidl_uid_t_int32_t(
6881 IPCThreadState::self()->getCallingUid()));
6882 identity.pid = VALUE_OR_FATAL(legacy2aidl_pid_t_int32_t(
6883 IPCThreadState::self()->getCallingPid()));
Andy Hungc25b84a2015-01-14 19:04:10 -08006884 sp<OutputTrack> outputTrack = new OutputTrack(thread,
Eric Laurent81784c32012-11-19 14:55:58 -08006885 this,
6886 mSampleRate,
Andy Hungc25b84a2015-01-14 19:04:10 -08006887 mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08006888 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08006889 frameCount,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07006890 identity);
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07006891 status_t status = outputTrack != 0 ? outputTrack->initCheck() : (status_t) NO_MEMORY;
6892 if (status != NO_ERROR) {
6893 ALOGE("addOutputTrack() initCheck failed %d", status);
6894 return;
Eric Laurent81784c32012-11-19 14:55:58 -08006895 }
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07006896 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
6897 mOutputTracks.add(outputTrack);
6898 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
6899 updateWaitTime_l();
Eric Laurent81784c32012-11-19 14:55:58 -08006900}
6901
6902void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
6903{
6904 Mutex::Autolock _l(mLock);
6905 for (size_t i = 0; i < mOutputTracks.size(); i++) {
6906 if (mOutputTracks[i]->thread() == thread) {
6907 mOutputTracks[i]->destroy();
6908 mOutputTracks.removeAt(i);
6909 updateWaitTime_l();
Eric Laurentf6870ae2015-05-08 10:50:03 -07006910 if (thread->getOutput() == mOutput) {
6911 mOutput = NULL;
6912 }
Eric Laurent81784c32012-11-19 14:55:58 -08006913 return;
6914 }
6915 }
Eric Laurentf6870ae2015-05-08 10:50:03 -07006916 ALOGV("removeOutputTrack(): unknown thread: %p", thread);
Eric Laurent81784c32012-11-19 14:55:58 -08006917}
6918
6919// caller must hold mLock
6920void AudioFlinger::DuplicatingThread::updateWaitTime_l()
6921{
6922 mWaitTimeMs = UINT_MAX;
6923 for (size_t i = 0; i < mOutputTracks.size(); i++) {
6924 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
6925 if (strong != 0) {
6926 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
6927 if (waitTimeMs < mWaitTimeMs) {
6928 mWaitTimeMs = waitTimeMs;
6929 }
6930 }
6931 }
6932}
6933
6934
6935bool AudioFlinger::DuplicatingThread::outputsReady(
6936 const SortedVector< sp<OutputTrack> > &outputTracks)
6937{
6938 for (size_t i = 0; i < outputTracks.size(); i++) {
6939 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
6940 if (thread == 0) {
6941 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
6942 outputTracks[i].get());
6943 return false;
6944 }
6945 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
6946 // see note at standby() declaration
6947 if (playbackThread->standby() && !playbackThread->isSuspended()) {
6948 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
6949 thread.get());
6950 return false;
6951 }
6952 }
6953 return true;
6954}
6955
Kevin Rocard12381092018-04-11 09:19:59 -07006956void AudioFlinger::DuplicatingThread::sendMetadataToBackend_l(
6957 const StreamOutHalInterface::SourceMetadata& metadata)
Kevin Rocard069c2712018-03-29 19:09:14 -07006958{
Kevin Rocard12381092018-04-11 09:19:59 -07006959 for (auto& outputTrack : outputTracks) { // not mOutputTracks
6960 outputTrack->setMetadatas(metadata.tracks);
6961 }
Kevin Rocard069c2712018-03-29 19:09:14 -07006962}
6963
Eric Laurent81784c32012-11-19 14:55:58 -08006964uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
6965{
6966 return (mWaitTimeMs * 1000) / 2;
6967}
6968
6969void AudioFlinger::DuplicatingThread::cacheParameters_l()
6970{
6971 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
6972 updateWaitTime_l();
6973
6974 MixerThread::cacheParameters_l();
6975}
6976
Eric Laurent6acd1d42017-01-04 14:23:29 -08006977
Eric Laurent81784c32012-11-19 14:55:58 -08006978// ----------------------------------------------------------------------------
6979// Record
6980// ----------------------------------------------------------------------------
6981
6982AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
6983 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08006984 audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -07006985 bool systemReady
Glenn Kasten46909e72013-02-26 09:20:22 -08006986 ) :
Andy Hungcf10d742020-04-28 15:38:24 -07006987 ThreadBase(audioFlinger, id, RECORD, systemReady, false /* isOut */),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07006988 mInput(input),
Mikhail Naganov2534b382019-09-25 13:05:02 -07006989 mSource(mInput),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07006990 mActiveTracks(&this->mLocalLog),
6991 mRsmpInBuffer(NULL),
Glenn Kasten1b291842016-07-18 14:55:21 -07006992 // mRsmpInFrames, mRsmpInFramesP2, and mRsmpInFramesOA are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006993 mRsmpInRear(0)
Glenn Kastenb880f5e2014-05-07 08:43:45 -07006994 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
6995 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006996 // mFastCapture below
6997 , mFastCaptureFutex(0)
6998 // mInputSource
6999 // mPipeSink
7000 // mPipeSource
7001 , mPipeFramesP2(0)
7002 // mPipeMemory
7003 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07007004 , mFastTrackAvail(false)
Eric Laurentd8365c52017-07-16 15:27:05 -07007005 , mBtNrecSuspended(false)
Eric Laurent81784c32012-11-19 14:55:58 -08007006{
Glenn Kastend7dca052015-03-05 16:05:54 -08007007 snprintf(mThreadName, kThreadNameLength, "AudioIn_%X", id);
7008 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08007009
George Burgess IVa8f90c12020-05-14 11:27:19 -07007010 if (mInput->audioHwDev != nullptr) {
Andy Hungc8fddf32018-08-08 18:32:37 -07007011 mIsMsdDevice = strcmp(
7012 mInput->audioHwDev->moduleName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0;
7013 }
7014
Glenn Kastendeca2ae2014-02-07 10:25:56 -08007015 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007016
Andy Hungc8fddf32018-08-08 18:32:37 -07007017 // TODO: We may also match on address as well as device type for
7018 // AUDIO_DEVICE_IN_BUS, AUDIO_DEVICE_IN_BLUETOOTH_A2DP, AUDIO_DEVICE_IN_REMOTE_SUBMIX
jiabinc52b1ff2019-10-31 17:20:42 -07007019 // TODO: This property should be ensure that only contains one single device type.
7020 mTimestampCorrectedDevice = (audio_devices_t)property_get_int64(
7021 "audio.timestamp.corrected_input_device",
Andy Hungc8fddf32018-08-08 18:32:37 -07007022 (int64_t)(mIsMsdDevice ? AUDIO_DEVICE_IN_BUS // turn on by default for MSD
7023 : AUDIO_DEVICE_NONE));
7024
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007025 // create an NBAIO source for the HAL input stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07007026 mInputSource = new AudioStreamInSource(input->stream);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007027 size_t numCounterOffers = 0;
7028 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07007029#if !LOG_NDEBUG
7030 ssize_t index =
7031#else
7032 (void)
7033#endif
7034 mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007035 ALOG_ASSERT(index == 0);
7036
7037 // initialize fast capture depending on configuration
7038 bool initFastCapture;
7039 switch (kUseFastCapture) {
7040 case FastCapture_Never:
7041 initFastCapture = false;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007042 ALOGV("%p kUseFastCapture = Never, initFastCapture = false", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007043 break;
7044 case FastCapture_Always:
7045 initFastCapture = true;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007046 ALOGV("%p kUseFastCapture = Always, initFastCapture = true", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007047 break;
7048 case FastCapture_Static:
Glenn Kasteneb9487e2015-07-22 09:15:17 -07007049 initFastCapture = (mFrameCount * 1000) / mSampleRate < kMinNormalCaptureBufferSizeMs;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007050 ALOGV("%p kUseFastCapture = Static, (%lld * 1000) / %u vs %u, initFastCapture = %d",
7051 this, (long long)mFrameCount, mSampleRate, kMinNormalCaptureBufferSizeMs,
7052 initFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007053 break;
7054 // case FastCapture_Dynamic:
7055 }
7056
7057 if (initFastCapture) {
Glenn Kastend198b852015-03-16 14:55:53 -07007058 // create a Pipe for FastCapture to write to, and for us and fast tracks to read from
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007059 NBAIO_Format format = mInputSource->format();
Glenn Kasten1b291842016-07-18 14:55:21 -07007060 // quadruple-buffering of 20 ms each; this ensures we can sleep for 20ms in RecordThread
7061 size_t pipeFramesP2 = roundup(4 * FMS_20 * mSampleRate / 1000);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007062 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007063 void *pipeBuffer = nullptr;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007064 const sp<MemoryDealer> roHeap(readOnlyHeap());
7065 sp<IMemory> pipeMemory;
7066 if ((roHeap == 0) ||
7067 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07007068 (pipeBuffer = pipeMemory->unsecurePointer()) == nullptr) {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007069 ALOGE("not enough memory for pipe buffer size=%zu; "
7070 "roHeap=%p, pipeMemory=%p, pipeBuffer=%p; roHeapSize: %lld",
7071 pipeSize, roHeap.get(), pipeMemory.get(), pipeBuffer,
7072 (long long)kRecordThreadReadOnlyHeapSize);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007073 goto failed;
7074 }
7075 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
7076 memset(pipeBuffer, 0, pipeSize);
7077 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
7078 const NBAIO_Format offers[1] = {format};
7079 size_t numCounterOffers = 0;
7080 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
7081 ALOG_ASSERT(index == 0);
7082 mPipeSink = pipe;
7083 PipeReader *pipeReader = new PipeReader(*pipe);
7084 numCounterOffers = 0;
7085 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
7086 ALOG_ASSERT(index == 0);
7087 mPipeSource = pipeReader;
7088 mPipeFramesP2 = pipeFramesP2;
7089 mPipeMemory = pipeMemory;
7090
7091 // create fast capture
7092 mFastCapture = new FastCapture();
7093 FastCaptureStateQueue *sq = mFastCapture->sq();
7094#ifdef STATE_QUEUE_DUMP
7095 // FIXME
7096#endif
7097 FastCaptureState *state = sq->begin();
7098 state->mCblk = NULL;
7099 state->mInputSource = mInputSource.get();
7100 state->mInputSourceGen++;
7101 state->mPipeSink = pipe;
7102 state->mPipeSinkGen++;
7103 state->mFrameCount = mFrameCount;
7104 state->mCommand = FastCaptureState::COLD_IDLE;
7105 // already done in constructor initialization list
7106 //mFastCaptureFutex = 0;
7107 state->mColdFutexAddr = &mFastCaptureFutex;
7108 state->mColdGen++;
7109 state->mDumpState = &mFastCaptureDumpState;
7110#ifdef TEE_SINK
7111 // FIXME
7112#endif
7113 mFastCaptureNBLogWriter = audioFlinger->newWriter_l(kFastCaptureLogSize, "FastCapture");
7114 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
7115 sq->end();
7116 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
7117
7118 // start the fast capture
7119 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
7120 pid_t tid = mFastCapture->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07007121 sendPrioConfigEvent(getpid(), tid, kPriorityFastCapture, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08007122 stream()->setHalThreadPriority(kPriorityFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007123#ifdef AUDIO_WATCHDOG
7124 // FIXME
7125#endif
7126
Glenn Kasten6e6704c2014-07-03 10:20:00 -07007127 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007128 }
Andy Hung8946a282018-04-19 20:04:56 -07007129#ifdef TEE_SINK
7130 mTee.set(mInputSource->format(), NBAIO_Tee::TEE_FLAG_INPUT_THREAD);
7131 mTee.setId(std::string("_") + std::to_string(mId) + "_C");
7132#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007133failed: ;
7134
7135 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08007136}
7137
Eric Laurent81784c32012-11-19 14:55:58 -08007138AudioFlinger::RecordThread::~RecordThread()
7139{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007140 if (mFastCapture != 0) {
7141 FastCaptureStateQueue *sq = mFastCapture->sq();
7142 FastCaptureState *state = sq->begin();
7143 if (state->mCommand == FastCaptureState::COLD_IDLE) {
7144 int32_t old = android_atomic_inc(&mFastCaptureFutex);
7145 if (old == -1) {
7146 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
7147 }
7148 }
7149 state->mCommand = FastCaptureState::EXIT;
7150 sq->end();
7151 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
7152 mFastCapture->join();
7153 mFastCapture.clear();
7154 }
7155 mAudioFlinger->unregisterWriter(mFastCaptureNBLogWriter);
Glenn Kasten481fb672013-09-30 14:39:28 -07007156 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung57446612015-04-19 23:56:46 -07007157 free(mRsmpInBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08007158}
7159
7160void AudioFlinger::RecordThread::onFirstRef()
7161{
Glenn Kastend7dca052015-03-05 16:05:54 -08007162 run(mThreadName, PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08007163}
7164
Eric Laurent555530a2017-02-07 18:17:24 -08007165void AudioFlinger::RecordThread::preExit()
7166{
7167 ALOGV(" preExit()");
7168 Mutex::Autolock _l(mLock);
7169 for (size_t i = 0; i < mTracks.size(); i++) {
7170 sp<RecordTrack> track = mTracks[i];
7171 track->invalidate();
7172 }
7173 mActiveTracks.clear();
7174 mStartStopCond.broadcast();
7175}
7176
Eric Laurent81784c32012-11-19 14:55:58 -08007177bool AudioFlinger::RecordThread::threadLoop()
7178{
Eric Laurent81784c32012-11-19 14:55:58 -08007179 nsecs_t lastWarning = 0;
7180
7181 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08007182
Glenn Kastenf10ffec2013-11-20 16:40:08 -08007183reacquire_wakelock:
7184 sp<RecordTrack> activeTrack;
7185 {
7186 Mutex::Autolock _l(mLock);
Andy Hungdae27702016-10-31 14:01:16 -07007187 acquireWakeLock_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08007188 }
7189
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007190 // used to request a deferred sleep, to be executed later while mutex is unlocked
7191 uint32_t sleepUs = 0;
7192
Andy Hung446f4df2019-02-21 12:26:41 -08007193 int64_t lastLoopCountRead = -2; // never matches "previous" loop, when loopCount = 0.
7194
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007195 // loop while there is work to do
Andy Hung446f4df2019-02-21 12:26:41 -08007196 for (int64_t loopCount = 0;; ++loopCount) { // loopCount used for statistics tracking
Glenn Kastenc527a7c2013-08-13 15:43:49 -07007197 Vector< sp<EffectChain> > effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07007198
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007199 // activeTracks accumulates a copy of a subset of mActiveTracks
7200 Vector< sp<RecordTrack> > activeTracks;
7201
Glenn Kasten735f45f2014-08-18 15:51:59 -07007202 // reference to the (first and only) active fast track
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007203 sp<RecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07007204
Glenn Kasten735f45f2014-08-18 15:51:59 -07007205 // reference to a fast track which is about to be removed
7206 sp<RecordTrack> fastTrackToRemove;
7207
Eric Laurent33403f02020-05-29 18:35:06 -07007208 bool silenceFastCapture = false;
7209
Eric Laurent81784c32012-11-19 14:55:58 -08007210 { // scope for mLock
7211 Mutex::Autolock _l(mLock);
Eric Laurent000a4192014-01-29 15:17:32 -08007212
Eric Laurent021cf962014-05-13 10:18:14 -07007213 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08007214
Eric Laurent000a4192014-01-29 15:17:32 -08007215 // check exitPending here because checkForNewParameters_l() and
7216 // checkForNewParameters_l() can temporarily release mLock
7217 if (exitPending()) {
7218 break;
7219 }
7220
Eric Laurent5c25d562016-07-13 17:17:45 -07007221 // sleep with mutex unlocked
7222 if (sleepUs > 0) {
Glenn Kastenf9715e42016-07-13 14:02:03 -07007223 ATRACE_BEGIN("sleepC");
Eric Laurent5c25d562016-07-13 17:17:45 -07007224 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)sleepUs));
7225 ATRACE_END();
7226 sleepUs = 0;
7227 continue;
7228 }
7229
Glenn Kasten2b806402013-11-20 16:37:38 -08007230 // if no active track(s), then standby and release wakelock
7231 size_t size = mActiveTracks.size();
7232 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07007233 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07007234 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08007235 releaseWakeLock_l();
7236 ALOGV("RecordThread: loop stopping");
7237 // go to sleep
7238 mWaitWorkCV.wait(mLock);
7239 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08007240 goto reacquire_wakelock;
7241 }
7242
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007243 bool doBroadcast = false;
Eric Laurent5c25d562016-07-13 17:17:45 -07007244 bool allStopped = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007245 for (size_t i = 0; i < size; ) {
Glenn Kasten9e982352013-08-14 14:39:50 -07007246
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007247 activeTrack = mActiveTracks[i];
7248 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07007249 if (activeTrack->isFastTrack()) {
7250 ALOG_ASSERT(fastTrackToRemove == 0);
7251 fastTrackToRemove = activeTrack;
7252 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007253 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08007254 mActiveTracks.remove(activeTrack);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007255 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07007256 continue;
7257 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007258
7259 TrackBase::track_state activeTrackState = activeTrack->mState;
7260 switch (activeTrackState) {
7261
7262 case TrackBase::PAUSING:
7263 mActiveTracks.remove(activeTrack);
Andy Hungce685402018-10-05 17:23:27 -07007264 activeTrack->mState = TrackBase::PAUSED;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007265 doBroadcast = true;
7266 size--;
7267 continue;
7268
7269 case TrackBase::STARTING_1:
7270 sleepUs = 10000;
7271 i++;
Eric Laurent5c25d562016-07-13 17:17:45 -07007272 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007273 continue;
7274
7275 case TrackBase::STARTING_2:
7276 doBroadcast = true;
Andy Hungcf10d742020-04-28 15:38:24 -07007277 if (mStandby) {
7278 mThreadMetrics.logBeginInterval();
7279 mStandby = false;
7280 }
Glenn Kasten9e982352013-08-14 14:39:50 -07007281 activeTrack->mState = TrackBase::ACTIVE;
Eric Laurent5c25d562016-07-13 17:17:45 -07007282 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007283 break;
7284
7285 case TrackBase::ACTIVE:
Eric Laurent5c25d562016-07-13 17:17:45 -07007286 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007287 break;
7288
Andy Hungce685402018-10-05 17:23:27 -07007289 case TrackBase::IDLE: // cannot be on ActiveTracks if idle
7290 case TrackBase::PAUSED: // cannot be on ActiveTracks if paused
7291 case TrackBase::STOPPED: // cannot be on ActiveTracks if destroyed/terminated
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007292 default:
Andy Hungce685402018-10-05 17:23:27 -07007293 LOG_ALWAYS_FATAL("%s: Unexpected active track state:%d, id:%d, tracks:%zu",
7294 __func__, activeTrackState, activeTrack->id(), size);
Glenn Kasten9e982352013-08-14 14:39:50 -07007295 }
Glenn Kasten9e982352013-08-14 14:39:50 -07007296
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007297 if (activeTrack->isFastTrack()) {
7298 ALOG_ASSERT(!mFastTrackAvail);
7299 ALOG_ASSERT(fastTrack == 0);
Eric Laurent33403f02020-05-29 18:35:06 -07007300 // if the active fast track is silenced either:
7301 // 1) silence the whole capture from fast capture buffer if this is
7302 // the only active track
7303 // 2) invalidate this track: this will cause the client to reconnect and possibly
7304 // be invalidated again until unsilenced
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02007305 bool invalidate = false;
Eric Laurent33403f02020-05-29 18:35:06 -07007306 if (activeTrack->isSilenced()) {
7307 if (size > 1) {
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02007308 invalidate = true;
Eric Laurent33403f02020-05-29 18:35:06 -07007309 } else {
7310 silenceFastCapture = true;
7311 }
7312 }
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02007313 // Invalidate fast tracks if access to audio history is required as this is not
7314 // possible with fast tracks. Once the fast track has been invalidated, no new
7315 // fast track will be created until mMaxSharedAudioHistoryMs is cleared.
7316 if (mMaxSharedAudioHistoryMs != 0) {
7317 invalidate = true;
7318 }
7319 if (invalidate) {
7320 activeTrack->invalidate();
7321 ALOG_ASSERT(fastTrackToRemove == 0);
7322 fastTrackToRemove = activeTrack;
7323 removeTrack_l(activeTrack);
7324 mActiveTracks.remove(activeTrack);
7325 size--;
7326 continue;
7327 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007328 fastTrack = activeTrack;
7329 }
Eric Laurent33403f02020-05-29 18:35:06 -07007330
7331 activeTracks.add(activeTrack);
7332 i++;
7333
Glenn Kasten9e982352013-08-14 14:39:50 -07007334 }
Eric Laurent5c25d562016-07-13 17:17:45 -07007335
Andy Hungdae27702016-10-31 14:01:16 -07007336 mActiveTracks.updatePowerState(this);
7337
Kevin Rocard069c2712018-03-29 19:09:14 -07007338 updateMetadata_l();
7339
Eric Laurent5c25d562016-07-13 17:17:45 -07007340 if (allStopped) {
7341 standbyIfNotAlreadyInStandby();
7342 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007343 if (doBroadcast) {
7344 mStartStopCond.broadcast();
7345 }
7346
7347 // sleep if there are no active tracks to process
Eric Tan39ec8d62018-07-24 09:49:29 -07007348 if (activeTracks.isEmpty()) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007349 if (sleepUs == 0) {
7350 sleepUs = kRecordThreadSleepUs;
7351 }
7352 continue;
7353 }
7354 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07007355
Eric Laurent81784c32012-11-19 14:55:58 -08007356 lockEffectChains_l(effectChains);
7357 }
7358
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007359 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07007360
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007361 size_t size = effectChains.size();
7362 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07007363 // thread mutex is not locked, but effect chain is locked
7364 effectChains[i]->process_l();
7365 }
7366
Glenn Kasten735f45f2014-08-18 15:51:59 -07007367 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007368 if (mFastCapture != 0) {
7369 FastCaptureStateQueue *sq = mFastCapture->sq();
7370 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07007371 bool didModify = false;
7372 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007373 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
7374 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
7375 if (state->mCommand == FastCaptureState::COLD_IDLE) {
7376 int32_t old = android_atomic_inc(&mFastCaptureFutex);
7377 if (old == -1) {
7378 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
7379 }
7380 }
7381 state->mCommand = FastCaptureState::READ_WRITE;
7382#if 0 // FIXME
7383 mFastCaptureDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08007384 FastThreadDumpState::kSamplingNforLowRamDevice :
7385 FastThreadDumpState::kSamplingN);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007386#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07007387 didModify = true;
7388 }
7389 audio_track_cblk_t *cblkOld = state->mCblk;
7390 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
7391 if (cblkNew != cblkOld) {
7392 state->mCblk = cblkNew;
7393 // block until acked if removing a fast track
7394 if (cblkOld != NULL) {
7395 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
7396 }
7397 didModify = true;
7398 }
jiabin01c8f562018-07-19 17:47:28 -07007399 AudioBufferProvider* abp = (fastTrack != 0 && fastTrack->isPatchTrack()) ?
7400 reinterpret_cast<AudioBufferProvider*>(fastTrack.get()) : nullptr;
7401 if (state->mFastPatchRecordBufferProvider != abp) {
7402 state->mFastPatchRecordBufferProvider = abp;
7403 state->mFastPatchRecordFormat = fastTrack == 0 ?
7404 AUDIO_FORMAT_INVALID : fastTrack->format();
7405 didModify = true;
7406 }
Eric Laurent33403f02020-05-29 18:35:06 -07007407 if (state->mSilenceCapture != silenceFastCapture) {
7408 state->mSilenceCapture = silenceFastCapture;
7409 didModify = true;
7410 }
Glenn Kasten735f45f2014-08-18 15:51:59 -07007411 sq->end(didModify);
7412 if (didModify) {
7413 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007414#if 0
7415 if (kUseFastCapture == FastCapture_Dynamic) {
7416 mNormalSource = mPipeSource;
7417 }
7418#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007419 }
7420 }
7421
Glenn Kasten735f45f2014-08-18 15:51:59 -07007422 // now run the fast track destructor with thread mutex unlocked
7423 fastTrackToRemove.clear();
7424
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007425 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
7426 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
7427 // slow, then this RecordThread will overrun by not calling HAL read often enough.
7428 // If destination is non-contiguous, first read past the nominal end of buffer, then
7429 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07007430
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007431 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007432 ssize_t framesRead;
Andy Hung446f4df2019-02-21 12:26:41 -08007433 const int64_t lastIoBeginNs = systemTime(); // start IO timing
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007434
7435 // If an NBAIO source is present, use it to read the normal capture's data
7436 if (mPipeSource != 0) {
Andy Hung156317a2018-08-02 11:49:29 -07007437 size_t framesToRead = min(mRsmpInFramesOA - rear, mRsmpInFramesP2 / 2);
Andy Hungd5b638f2018-04-30 13:56:10 -07007438
7439 // The audio fifo read() returns OVERRUN on overflow, and advances the read pointer
7440 // to the full buffer point (clearing the overflow condition). Upon OVERRUN error,
7441 // we immediately retry the read() to get data and prevent another overflow.
7442 for (int retries = 0; retries <= 2; ++retries) {
7443 ALOGW_IF(retries > 0, "overrun on read from pipe, retry #%d", retries);
7444 framesRead = mPipeSource->read((uint8_t*)mRsmpInBuffer + rear * mFrameSize,
7445 framesToRead);
7446 if (framesRead != OVERRUN) break;
7447 }
7448
Andy Hung7a3dc6b2018-05-01 16:39:51 -07007449 const ssize_t availableToRead = mPipeSource->availableToRead();
7450 if (availableToRead >= 0) {
Glenn Kastena2f59b32020-08-03 16:37:24 -07007451 // PipeSource is the primary clock. It is up to the AudioRecord client to keep up.
Andy Hung7a3dc6b2018-05-01 16:39:51 -07007452 LOG_ALWAYS_FATAL_IF((size_t)availableToRead > mPipeFramesP2,
7453 "more frames to read than fifo size, %zd > %zu",
7454 availableToRead, mPipeFramesP2);
7455 const size_t pipeFramesFree = mPipeFramesP2 - availableToRead;
7456 const size_t sleepFrames = min(pipeFramesFree, mRsmpInFramesP2) / 2;
7457 ALOGVV("mPipeFramesP2:%zu mRsmpInFramesP2:%zu sleepFrames:%zu availableToRead:%zd",
7458 mPipeFramesP2, mRsmpInFramesP2, sleepFrames, availableToRead);
Glenn Kasten1b291842016-07-18 14:55:21 -07007459 sleepUs = (sleepFrames * 1000000LL) / mSampleRate;
7460 }
7461 if (framesRead < 0) {
7462 status_t status = (status_t) framesRead;
7463 switch (status) {
7464 case OVERRUN:
7465 ALOGW("overrun on read from pipe");
7466 framesRead = 0;
7467 break;
7468 case NEGOTIATE:
7469 ALOGE("re-negotiation is needed");
7470 framesRead = -1; // Will cause an attempt to recover.
7471 break;
7472 default:
7473 ALOGE("unknown error %d on read from pipe", status);
7474 break;
7475 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007476 }
7477 // otherwise use the HAL / AudioStreamIn directly
7478 } else {
Glenn Kastenec6a7032016-03-14 07:40:23 -07007479 ATRACE_BEGIN("read");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007480 size_t bytesRead;
Mikhail Naganov2534b382019-09-25 13:05:02 -07007481 status_t result = mSource->read(
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007482 (uint8_t*)mRsmpInBuffer + rear * mFrameSize, mBufferSize, &bytesRead);
Glenn Kastenec6a7032016-03-14 07:40:23 -07007483 ATRACE_END();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007484 if (result < 0) {
7485 framesRead = result;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007486 } else {
7487 framesRead = bytesRead / mFrameSize;
7488 }
7489 }
7490
Andy Hung446f4df2019-02-21 12:26:41 -08007491 const int64_t lastIoEndNs = systemTime(); // end IO timing
7492
Andy Hung3f0c9022016-01-15 17:49:46 -08007493 // Update server timestamp with server stats
7494 // systemTime() is optional if the hardware supports timestamps.
Andy Hung743f6402020-06-03 13:17:04 -07007495 if (framesRead >= 0) {
7496 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += framesRead;
7497 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = lastIoEndNs;
7498 }
Andy Hung3f0c9022016-01-15 17:49:46 -08007499
7500 // Update server timestamp with kernel stats
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007501 if (mPipeSource.get() == nullptr /* don't obtain for FastCapture, could block */) {
Andy Hung3f0c9022016-01-15 17:49:46 -08007502 int64_t position, time;
Andy Hung2e2c0bb2018-06-11 19:13:11 -07007503 if (mStandby) {
Dean Wheatley12473e92021-03-18 23:00:55 +11007504 mTimestampVerifier.discontinuity(audio_is_linear_pcm(mFormat) ?
7505 mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS :
7506 mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Mikhail Naganov2534b382019-09-25 13:05:02 -07007507 } else if (mSource->getCapturePosition(&position, &time) == NO_ERROR
Andy Hungc8fddf32018-08-08 18:32:37 -07007508 && time > mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]) {
7509
7510 mTimestampVerifier.add(position, time, mSampleRate);
7511
7512 // Correct timestamps
7513 if (isTimestampCorrectionEnabled()) {
Dean Wheatley56a583e2020-05-08 15:12:17 +10007514 ALOGVV("TS_BEFORE: %d %lld %lld",
Andy Hungc8fddf32018-08-08 18:32:37 -07007515 id(), (long long)time, (long long)position);
7516 auto correctedTimestamp = mTimestampVerifier.getLastCorrectedTimestamp();
7517 position = correctedTimestamp.mFrames;
7518 time = correctedTimestamp.mTimeNs;
Dean Wheatley56a583e2020-05-08 15:12:17 +10007519 ALOGVV("TS_AFTER: %d %lld %lld",
Andy Hungc8fddf32018-08-08 18:32:37 -07007520 id(), (long long)time, (long long)position);
7521 }
7522
Andy Hung3f0c9022016-01-15 17:49:46 -08007523 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = position;
7524 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] = time;
7525 // Note: In general record buffers should tend to be empty in
7526 // a properly running pipeline.
7527 //
7528 // Also, it is not advantageous to call get_presentation_position during the read
7529 // as the read obtains a lock, preventing the timestamp call from executing.
Andy Hung2e2c0bb2018-06-11 19:13:11 -07007530 } else {
7531 mTimestampVerifier.error();
Andy Hung3f0c9022016-01-15 17:49:46 -08007532 }
7533 }
Andy Hunge6c37112019-02-26 17:38:10 -08007534
7535 // From the timestamp, input read latency is negative output write latency.
7536 const audio_input_flags_t flags = mInput != NULL ? mInput->flags : AUDIO_INPUT_FLAG_NONE;
7537 const double latencyMs = RecordTrack::checkServerLatencySupported(mFormat, flags)
7538 ? - mTimestamp.getOutputServerLatencyMs(mSampleRate) : 0.;
7539 if (latencyMs != 0.) { // note 0. means timestamp is empty.
7540 mLatencyMs.add(latencyMs);
7541 }
7542
Andy Hung3f0c9022016-01-15 17:49:46 -08007543 // Use this to track timestamp information
7544 // ALOGD("%s", mTimestamp.toString().c_str());
7545
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007546 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07007547 ALOGE("read failed: framesRead=%zd", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007548 // Force input into standby so that it tries to recover at next read attempt
7549 inputStandBy();
7550 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007551 }
7552 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07007553 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07007554 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007555 ALOG_ASSERT(framesRead > 0);
Andy Hung6427e442018-08-09 12:51:02 -07007556 mFramesRead += framesRead;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007557
Andy Hung8946a282018-04-19 20:04:56 -07007558#ifdef TEE_SINK
7559 (void)mTee.write((uint8_t*)mRsmpInBuffer + rear * mFrameSize, framesRead);
7560#endif
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007561 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07007562 {
7563 size_t part1 = mRsmpInFramesP2 - rear;
7564 if ((size_t) framesRead > part1) {
Andy Hung57446612015-04-19 23:56:46 -07007565 memcpy(mRsmpInBuffer, (uint8_t*)mRsmpInBuffer + mRsmpInFramesP2 * mFrameSize,
Glenn Kasten3d61bc12014-06-16 10:25:20 -07007566 (framesRead - part1) * mFrameSize);
7567 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007568 }
Dean Wheatleyfd56e812020-11-06 22:32:21 +11007569 mRsmpInRear = audio_utils::safe_add_overflow(mRsmpInRear, (int32_t)framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007570
7571 size = activeTracks.size();
Svet Ganovf4ddfef2018-01-16 07:37:58 -08007572
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007573 // loop over each active track
7574 for (size_t i = 0; i < size; i++) {
7575 activeTrack = activeTracks[i];
7576
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007577 // skip fast tracks, as those are handled directly by FastCapture
7578 if (activeTrack->isFastTrack()) {
7579 continue;
7580 }
7581
Andy Hung73c02e42015-03-29 01:13:58 -07007582 // TODO: This code probably should be moved to RecordTrack.
Andy Hung97a893e2015-03-29 01:03:07 -07007583 // TODO: Update the activeTrack buffer converter in case of reconfigure.
7584
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007585 enum {
7586 OVERRUN_UNKNOWN,
7587 OVERRUN_TRUE,
7588 OVERRUN_FALSE
7589 } overrun = OVERRUN_UNKNOWN;
7590
7591 // loop over getNextBuffer to handle circular sink
7592 for (;;) {
7593
7594 activeTrack->mSink.frameCount = ~0;
7595 status_t status = activeTrack->getNextBuffer(&activeTrack->mSink);
7596 size_t framesOut = activeTrack->mSink.frameCount;
7597 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
7598
Andy Hung73c02e42015-03-29 01:13:58 -07007599 // check available frames and handle overrun conditions
7600 // if the record track isn't draining fast enough.
7601 bool hasOverrun;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007602 size_t framesIn;
Andy Hung73c02e42015-03-29 01:13:58 -07007603 activeTrack->mResamplerBufferProvider->sync(&framesIn, &hasOverrun);
7604 if (hasOverrun) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007605 overrun = OVERRUN_TRUE;
7606 }
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007607 if (framesOut == 0 || framesIn == 0) {
7608 break;
7609 }
7610
Andy Hung6770c6f2015-04-07 13:43:36 -07007611 // Don't allow framesOut to be larger than what is possible with resampling
7612 // from framesIn.
7613 // This isn't strictly necessary but helps limit buffer resizing in
7614 // RecordBufferConverter. TODO: remove when no longer needed.
7615 framesOut = min(framesOut,
7616 destinationFramesPossible(
7617 framesIn, mSampleRate, activeTrack->mSampleRate));
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07007618
7619 if (activeTrack->isDirect()) {
Daniel Van Veen9e2376e2018-09-27 14:37:58 +10007620 // No RecordBufferConverter used for direct streams. Pass
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07007621 // straight from RecordThread buffer to RecordTrack buffer.
7622 AudioBufferProvider::Buffer buffer;
7623 buffer.frameCount = framesOut;
7624 status_t status = activeTrack->mResamplerBufferProvider->getNextBuffer(&buffer);
7625 if (status == OK && buffer.frameCount != 0) {
7626 ALOGV_IF(buffer.frameCount != framesOut,
7627 "%s() read less than expected (%zu vs %zu)",
7628 __func__, buffer.frameCount, framesOut);
7629 framesOut = buffer.frameCount;
Daniel Van Veen9e2376e2018-09-27 14:37:58 +10007630 memcpy(activeTrack->mSink.raw, buffer.raw, buffer.frameCount * mFrameSize);
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07007631 activeTrack->mResamplerBufferProvider->releaseBuffer(&buffer);
7632 } else {
7633 framesOut = 0;
7634 ALOGE("%s() cannot fill request, status: %d, frameCount: %zu",
7635 __func__, status, buffer.frameCount);
7636 }
7637 } else {
7638 // process frames from the RecordThread buffer provider to the RecordTrack
7639 // buffer
7640 framesOut = activeTrack->mRecordBufferConverter->convert(
7641 activeTrack->mSink.raw,
7642 activeTrack->mResamplerBufferProvider,
7643 framesOut);
7644 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007645
7646 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
7647 overrun = OVERRUN_FALSE;
7648 }
7649
7650 if (activeTrack->mFramesToDrop == 0) {
7651 if (framesOut > 0) {
7652 activeTrack->mSink.frameCount = framesOut;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08007653 // Sanitize before releasing if the track has no access to the source data
7654 // An idle UID receives silence from non virtual devices until active
7655 if (activeTrack->isSilenced()) {
Jean-Michel Trividdf87ef2019-08-20 15:42:04 -07007656 memset(activeTrack->mSink.raw, 0, framesOut * activeTrack->frameSize());
Svet Ganovf4ddfef2018-01-16 07:37:58 -08007657 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007658 activeTrack->releaseBuffer(&activeTrack->mSink);
7659 }
7660 } else {
7661 // FIXME could do a partial drop of framesOut
7662 if (activeTrack->mFramesToDrop > 0) {
Mikhail Naganov6d91ba52019-03-26 14:35:28 -07007663 activeTrack->mFramesToDrop -= (ssize_t)framesOut;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007664 if (activeTrack->mFramesToDrop <= 0) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08007665 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007666 }
7667 } else {
7668 activeTrack->mFramesToDrop += framesOut;
7669 if (activeTrack->mFramesToDrop >= 0 || activeTrack->mSyncStartEvent == 0 ||
7670 activeTrack->mSyncStartEvent->isCancelled()) {
7671 ALOGW("Synced record %s, session %d, trigger session %d",
7672 (activeTrack->mFramesToDrop >= 0) ? "timed out" : "cancelled",
7673 activeTrack->sessionId(),
7674 (activeTrack->mSyncStartEvent != 0) ?
Glenn Kastend848eb42016-03-08 13:42:11 -08007675 activeTrack->mSyncStartEvent->triggerSession() :
7676 AUDIO_SESSION_NONE);
Glenn Kasten25f4aa82014-02-07 10:50:43 -08007677 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007678 }
7679 }
7680 }
7681
7682 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007683 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07007684 }
7685 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007686
7687 switch (overrun) {
7688 case OVERRUN_TRUE:
7689 // client isn't retrieving buffers fast enough
7690 if (!activeTrack->setOverflow()) {
7691 nsecs_t now = systemTime();
7692 // FIXME should lastWarning per track?
7693 if ((now - lastWarning) > kWarningThrottleNs) {
7694 ALOGW("RecordThread: buffer overflow");
7695 lastWarning = now;
7696 }
7697 }
7698 break;
7699 case OVERRUN_FALSE:
7700 activeTrack->clearOverflow();
7701 break;
7702 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007703 break;
7704 }
7705
Andy Hung3f0c9022016-01-15 17:49:46 -08007706 // update frame information and push timestamp out
7707 activeTrack->updateTrackFrameInfo(
Andy Hung6ae58432016-02-16 18:32:24 -08007708 activeTrack->mServerProxy->framesReleased(),
Andy Hung3f0c9022016-01-15 17:49:46 -08007709 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER],
7710 mSampleRate, mTimestamp);
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07007711 }
7712
Glenn Kasten3d61bc12014-06-16 10:25:20 -07007713unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08007714 // enable changes in effect chain
7715 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07007716 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurentcccbc762019-04-05 14:20:05 -07007717 if (audio_has_proportional_frames(mFormat)
7718 && loopCount == lastLoopCountRead + 1) {
7719 const int64_t readPeriodNs = lastIoEndNs - mLastIoEndNs;
7720 const double jitterMs =
7721 TimestampVerifier<int64_t, int64_t>::computeJitterMs(
7722 {framesRead, readPeriodNs},
7723 {0, 0} /* lastTimestamp */, mSampleRate);
7724 const double processMs = (lastIoBeginNs - mLastIoEndNs) * 1e-6;
7725
7726 Mutex::Autolock _l(mLock);
7727 mIoJitterMs.add(jitterMs);
7728 mProcessTimeMs.add(processMs);
7729 }
7730 // update timing info.
7731 mLastIoBeginNs = lastIoBeginNs;
7732 mLastIoEndNs = lastIoEndNs;
7733 lastLoopCountRead = loopCount;
Eric Laurent81784c32012-11-19 14:55:58 -08007734 }
7735
Glenn Kasten93e471f2013-08-19 08:40:07 -07007736 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08007737
7738 {
7739 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07007740 for (size_t i = 0; i < mTracks.size(); i++) {
7741 sp<RecordTrack> track = mTracks[i];
7742 track->invalidate();
7743 }
Glenn Kasten2b806402013-11-20 16:37:38 -08007744 mActiveTracks.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08007745 mStartStopCond.broadcast();
7746 }
7747
7748 releaseWakeLock();
7749
7750 ALOGV("RecordThread %p exiting", this);
7751 return false;
7752}
7753
Glenn Kasten93e471f2013-08-19 08:40:07 -07007754void AudioFlinger::RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08007755{
7756 if (!mStandby) {
7757 inputStandBy();
Andy Hungcf10d742020-04-28 15:38:24 -07007758 mThreadMetrics.logEndInterval();
Eric Laurent81784c32012-11-19 14:55:58 -08007759 mStandby = true;
7760 }
7761}
7762
7763void AudioFlinger::RecordThread::inputStandBy()
7764{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007765 // Idle the fast capture if it's currently running
7766 if (mFastCapture != 0) {
7767 FastCaptureStateQueue *sq = mFastCapture->sq();
7768 FastCaptureState *state = sq->begin();
7769 if (!(state->mCommand & FastCaptureState::IDLE)) {
7770 state->mCommand = FastCaptureState::COLD_IDLE;
7771 state->mColdFutexAddr = &mFastCaptureFutex;
7772 state->mColdGen++;
7773 mFastCaptureFutex = 0;
7774 sq->end();
7775 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
7776 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
7777#if 0
7778 if (kUseFastCapture == FastCapture_Dynamic) {
7779 // FIXME
7780 }
7781#endif
7782#ifdef AUDIO_WATCHDOG
7783 // FIXME
7784#endif
7785 } else {
7786 sq->end(false /*didModify*/);
7787 }
7788 }
Mikhail Naganov2534b382019-09-25 13:05:02 -07007789 status_t result = mSource->standby();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007790 ALOGE_IF(result != OK, "Error when putting input stream into standby: %d", result);
Andy Hungad6d52d2016-07-18 13:42:03 -07007791
7792 // If going into standby, flush the pipe source.
7793 if (mPipeSource.get() != nullptr) {
7794 const ssize_t flushed = mPipeSource->flush();
7795 if (flushed > 0) {
7796 ALOGV("Input standby flushed PipeSource %zd frames", flushed);
7797 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += flushed;
7798 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
7799 }
7800 }
Eric Laurent81784c32012-11-19 14:55:58 -08007801}
7802
Glenn Kasten05997e22014-03-13 15:08:33 -07007803// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastene198c362013-08-13 09:13:36 -07007804sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
Eric Laurent81784c32012-11-19 14:55:58 -08007805 const sp<AudioFlinger::Client>& client,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07007806 const audio_attributes_t& attr,
Eric Laurentf14db3c2017-12-08 14:20:36 -08007807 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08007808 audio_format_t format,
7809 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08007810 size_t *pFrameCount,
Glenn Kastend848eb42016-03-08 13:42:11 -08007811 audio_session_t sessionId,
Eric Laurentf14db3c2017-12-08 14:20:36 -08007812 size_t *pNotificationFrameCount,
Eric Laurent09f1ed22019-04-24 17:45:17 -07007813 pid_t creatorPid,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07007814 const Identity& identity,
Eric Laurent05067782016-06-01 18:27:28 -07007815 audio_input_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08007816 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08007817 status_t *status,
Eric Laurentec376dc2021-04-08 20:41:22 +02007818 audio_port_handle_t portId,
7819 int32_t maxSharedAudioHistoryMs)
Eric Laurent81784c32012-11-19 14:55:58 -08007820{
Glenn Kasten74935e42013-12-19 08:56:45 -08007821 size_t frameCount = *pFrameCount;
Eric Laurentf14db3c2017-12-08 14:20:36 -08007822 size_t notificationFrameCount = *pNotificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08007823 sp<RecordTrack> track;
7824 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07007825 audio_input_flags_t inputFlags = mInput->flags;
Eric Laurentf14db3c2017-12-08 14:20:36 -08007826 audio_input_flags_t requestedFlags = *flags;
7827 uint32_t sampleRate;
Eric Laurentec376dc2021-04-08 20:41:22 +02007828 Identity checkedIdentity = AudioFlinger::checkIdentityPackage(identity);
Eric Laurentf14db3c2017-12-08 14:20:36 -08007829
7830 lStatus = initCheck();
7831 if (lStatus != NO_ERROR) {
7832 ALOGE("createRecordTrack_l() audio driver not initialized");
7833 goto Exit;
7834 }
7835
Mikhail Naganovce9f2652018-07-16 11:09:24 -07007836 if (!audio_is_linear_pcm(mFormat) && (*flags & AUDIO_INPUT_FLAG_DIRECT) == 0) {
7837 ALOGE("createRecordTrack_l() on an encoded stream requires AUDIO_INPUT_FLAG_DIRECT");
7838 lStatus = BAD_VALUE;
7839 goto Exit;
7840 }
7841
Eric Laurentec376dc2021-04-08 20:41:22 +02007842 if (maxSharedAudioHistoryMs != 0) {
7843 if (!captureHotwordAllowed(checkedIdentity)) {
7844 lStatus = PERMISSION_DENIED;
7845 goto Exit;
7846 }
Eric Laurentec376dc2021-04-08 20:41:22 +02007847 if (maxSharedAudioHistoryMs < 0
7848 || maxSharedAudioHistoryMs > AudioFlinger::kMaxSharedAudioHistoryMs) {
7849 lStatus = BAD_VALUE;
7850 goto Exit;
7851 }
7852 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08007853 if (*pSampleRate == 0) {
7854 *pSampleRate = mSampleRate;
7855 }
7856 sampleRate = *pSampleRate;
Eric Laurent05067782016-06-01 18:27:28 -07007857
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02007858 // special case for FAST flag considered OK if fast capture is present and access to
7859 // audio history is not required
7860 if (hasFastCapture() && mMaxSharedAudioHistoryMs == 0) {
Eric Laurent05067782016-06-01 18:27:28 -07007861 inputFlags = (audio_input_flags_t)(inputFlags | AUDIO_INPUT_FLAG_FAST);
7862 }
7863
Eric Laurentf14db3c2017-12-08 14:20:36 -08007864 // Check if requested flags are compatible with input stream flags
Eric Laurent05067782016-06-01 18:27:28 -07007865 if ((*flags & inputFlags) != *flags) {
7866 ALOGW("createRecordTrack_l(): mismatch between requested flags (%08x) and"
7867 " input flags (%08x)",
7868 *flags, inputFlags);
7869 *flags = (audio_input_flags_t)(*flags & inputFlags);
7870 }
Eric Laurent81784c32012-11-19 14:55:58 -08007871
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02007872 // client expresses a preference for FAST and no access to audio history,
7873 // but we get the final say
7874 if (*flags & AUDIO_INPUT_FLAG_FAST && maxSharedAudioHistoryMs == 0) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07007875 if (
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07007876 // we formerly checked for a callback handler (non-0 tid),
7877 // but that is no longer required for TRANSFER_OBTAIN mode
7878 //
Phil Burk7ed66a12019-04-18 13:20:30 -07007879 // Frame count is not specified (0), or is less than or equal the pipe depth.
7880 // It is OK to provide a higher capacity than requested.
7881 // We will force it to mPipeFramesP2 below.
7882 (frameCount <= mPipeFramesP2) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07007883 // PCM data
7884 audio_is_linear_pcm(format) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08007885 // hardware format
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007886 (format == mFormat) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08007887 // hardware channel mask
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007888 (channelMask == mChannelMask) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08007889 // hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07007890 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07007891 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007892 hasFastCapture() &&
7893 // there are sufficient fast track slots available
7894 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07007895 ) {
Eric Laurent4c415062016-06-17 16:14:16 -07007896 // check compatibility with audio effects.
7897 Mutex::Autolock _l(mLock);
7898 // Do not accept FAST flag if the session has software effects
7899 sp<EffectChain> chain = getEffectChain_l(sessionId);
7900 if (chain != 0) {
Andy Hungd3bb0ad2016-10-11 17:16:43 -07007901 audio_input_flags_t old = *flags;
7902 chain->checkInputFlagCompatibility(flags);
7903 if (old != *flags) {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007904 ALOGV("%p AUDIO_INPUT_FLAGS denied by effect old=%#x new=%#x",
7905 this, (int)old, (int)*flags);
Eric Laurent4c415062016-06-17 16:14:16 -07007906 }
7907 }
Eric Laurent122f7e72016-06-29 11:53:29 -07007908 ALOGV_IF((*flags & AUDIO_INPUT_FLAG_FAST) != 0,
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007909 "%p AUDIO_INPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
7910 this, frameCount, mFrameCount);
Glenn Kasten90e58b12013-07-31 16:16:02 -07007911 } else {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007912 ALOGV("%p AUDIO_INPUT_FLAG_FAST denied: frameCount=%zu mFrameCount=%zu mPipeFramesP2=%zu "
7913 "format=%#x isLinear=%d mFormat=%#x channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007914 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007915 this, frameCount, mFrameCount, mPipeFramesP2,
7916 format, audio_is_linear_pcm(format), mFormat, channelMask, sampleRate, mSampleRate,
Glenn Kasten74105912014-07-03 12:28:53 -07007917 hasFastCapture(), tid, mFastTrackAvail);
Eric Laurent05067782016-06-01 18:27:28 -07007918 *flags = (audio_input_flags_t)(*flags & ~AUDIO_INPUT_FLAG_FAST);
Glenn Kasten74105912014-07-03 12:28:53 -07007919 }
7920 }
7921
Eric Laurentf14db3c2017-12-08 14:20:36 -08007922 // If FAST or RAW flags were corrected, ask caller to request new input from audio policy
7923 if ((*flags & AUDIO_INPUT_FLAG_FAST) !=
7924 (requestedFlags & AUDIO_INPUT_FLAG_FAST)) {
7925 *flags = (audio_input_flags_t) (*flags & ~(AUDIO_INPUT_FLAG_FAST | AUDIO_INPUT_FLAG_RAW));
7926 lStatus = BAD_TYPE;
7927 goto Exit;
7928 }
7929
Glenn Kasten74105912014-07-03 12:28:53 -07007930 // compute track buffer size in frames, and suggest the notification frame count
Eric Laurent05067782016-06-01 18:27:28 -07007931 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten74105912014-07-03 12:28:53 -07007932 // fast track: frame count is exactly the pipe depth
7933 frameCount = mPipeFramesP2;
7934 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
Eric Laurentf14db3c2017-12-08 14:20:36 -08007935 notificationFrameCount = mFrameCount;
Glenn Kasten74105912014-07-03 12:28:53 -07007936 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07007937 // not fast track: max notification period is resampled equivalent of one HAL buffer time
7938 // or 20 ms if there is a fast capture
7939 // TODO This could be a roundupRatio inline, and const
7940 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
7941 * sampleRate + mSampleRate - 1) / mSampleRate;
7942 // minimum number of notification periods is at least kMinNotifications,
7943 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
7944 static const size_t kMinNotifications = 3;
7945 static const uint32_t kMinMs = 30;
7946 // TODO This could be a roundupRatio inline
7947 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
7948 // TODO This could be a roundupRatio inline
7949 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
7950 maxNotificationFrames;
7951 const size_t minFrameCount = maxNotificationFrames *
7952 max(kMinNotifications, minNotificationsByMs);
7953 frameCount = max(frameCount, minFrameCount);
Eric Laurentf14db3c2017-12-08 14:20:36 -08007954 if (notificationFrameCount == 0 || notificationFrameCount > maxNotificationFrames) {
7955 notificationFrameCount = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07007956 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07007957 }
Glenn Kasten74935e42013-12-19 08:56:45 -08007958 *pFrameCount = frameCount;
Eric Laurentf14db3c2017-12-08 14:20:36 -08007959 *pNotificationFrameCount = notificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08007960
7961 { // scope for mLock
7962 Mutex::Autolock _l(mLock);
Eric Laurent2407ce32021-04-26 14:56:03 +02007963 int32_t startFrames = -1;
Eric Laurentec376dc2021-04-08 20:41:22 +02007964 if (!mSharedAudioPackageName.empty()
7965 && mSharedAudioPackageName == checkedIdentity.packageName
7966 && mSharedAudioSessionId == sessionId
7967 && captureHotwordAllowed(checkedIdentity)) {
Eric Laurent2407ce32021-04-26 14:56:03 +02007968 startFrames = mSharedAudioStartFrames;
Eric Laurentec376dc2021-04-08 20:41:22 +02007969 }
Eric Laurent81784c32012-11-19 14:55:58 -08007970
Kevin Rocard1f564ac2018-03-29 13:53:10 -07007971 track = new RecordTrack(this, client, attr, sampleRate,
Andy Hung8fe68032017-06-05 16:17:51 -07007972 format, channelMask, frameCount,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07007973 nullptr /* buffer */, (size_t)0 /* bufferSize */, sessionId, creatorPid,
Eric Laurent2407ce32021-04-26 14:56:03 +02007974 checkedIdentity, *flags, TrackBase::TYPE_DEFAULT, portId, startFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08007975
Glenn Kasten03003332013-08-06 15:40:54 -07007976 lStatus = track->initCheck();
7977 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07007978 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08007979 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08007980 goto Exit;
7981 }
7982 mTracks.add(track);
7983
Eric Laurent05067782016-06-01 18:27:28 -07007984 if ((*flags & AUDIO_INPUT_FLAG_FAST) && (tid != -1)) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07007985 pid_t callingPid = IPCThreadState::self()->getCallingPid();
7986 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
7987 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07007988 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Glenn Kasten90e58b12013-07-31 16:16:02 -07007989 }
Eric Laurentec376dc2021-04-08 20:41:22 +02007990
7991 if (maxSharedAudioHistoryMs != 0) {
7992 sendResizeBufferConfigEvent_l(maxSharedAudioHistoryMs);
7993 }
Eric Laurent81784c32012-11-19 14:55:58 -08007994 }
Glenn Kasten05997e22014-03-13 15:08:33 -07007995
Eric Laurent81784c32012-11-19 14:55:58 -08007996 lStatus = NO_ERROR;
7997
7998Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07007999 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08008000 return track;
8001}
8002
8003status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
8004 AudioSystem::sync_event_t event,
Glenn Kastend848eb42016-03-08 13:42:11 -08008005 audio_session_t triggerSession)
Eric Laurent81784c32012-11-19 14:55:58 -08008006{
8007 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
8008 sp<ThreadBase> strongMe = this;
8009 status_t status = NO_ERROR;
8010
8011 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08008012 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08008013 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008014 recordTrack->mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
Eric Laurent81784c32012-11-19 14:55:58 -08008015 triggerSession,
8016 recordTrack->sessionId(),
8017 syncStartEventCallback,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008018 recordTrack);
Eric Laurent81784c32012-11-19 14:55:58 -08008019 // Sync event can be cancelled by the trigger session if the track is not in a
8020 // compatible state in which case we start record immediately
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008021 if (recordTrack->mSyncStartEvent->isCancelled()) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08008022 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08008023 } else {
8024 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
Ivan Lozano1b35dd62017-12-06 16:55:10 -08008025 recordTrack->mFramesToDrop = -(ssize_t)
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08008026 ((AudioSystem::kSyncRecordStartTimeOutMs * recordTrack->mSampleRate) / 1000);
Eric Laurent81784c32012-11-19 14:55:58 -08008027 }
8028 }
8029
8030 {
Glenn Kasten47c20702013-08-13 15:37:35 -07008031 // This section is a rendezvous between binder thread executing start() and RecordThread
Eric Laurent81784c32012-11-19 14:55:58 -08008032 AutoMutex lock(mLock);
Andy Hungce685402018-10-05 17:23:27 -07008033 if (recordTrack->isInvalid()) {
8034 recordTrack->clearSyncStartEvent();
Eric Laurentd52a28c2020-08-21 17:10:39 -07008035 ALOGW("%s track %d: invalidated before startInput", __func__, recordTrack->portId());
8036 return DEAD_OBJECT;
Andy Hungce685402018-10-05 17:23:27 -07008037 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008038 if (mActiveTracks.indexOf(recordTrack) >= 0) {
8039 if (recordTrack->mState == TrackBase::PAUSING) {
Andy Hungce685402018-10-05 17:23:27 -07008040 // We haven't stopped yet (moved to PAUSED and not in mActiveTracks)
8041 // so no need to startInput().
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008042 ALOGV("active record track PAUSING -> ACTIVE");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008043 recordTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008044 } else {
8045 ALOGV("active record track state %d", recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08008046 }
8047 return status;
8048 }
8049
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08008050 // TODO consider other ways of handling this, such as changing the state to :STARTING and
8051 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
8052 // or using a separate command thread
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008053 recordTrack->mState = TrackBase::STARTING_1;
Glenn Kasten2b806402013-11-20 16:37:38 -08008054 mActiveTracks.add(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07008055 status_t status = NO_ERROR;
8056 if (recordTrack->isExternalTrack()) {
8057 mLock.unlock();
Eric Laurent4eb58f12018-12-07 16:41:02 -08008058 status = AudioSystem::startInput(recordTrack->portId());
Eric Laurent83b88082014-06-20 18:31:16 -07008059 mLock.lock();
Andy Hungce685402018-10-05 17:23:27 -07008060 if (recordTrack->isInvalid()) {
8061 recordTrack->clearSyncStartEvent();
8062 if (status == NO_ERROR && recordTrack->mState == TrackBase::STARTING_1) {
8063 recordTrack->mState = TrackBase::STARTING_2;
8064 // STARTING_2 forces destroy to call stopInput.
8065 }
Eric Laurentd52a28c2020-08-21 17:10:39 -07008066 ALOGW("%s track %d: invalidated after startInput", __func__, recordTrack->portId());
8067 return DEAD_OBJECT;
Andy Hungce685402018-10-05 17:23:27 -07008068 }
8069 if (recordTrack->mState != TrackBase::STARTING_1) {
8070 ALOGW("%s(%d): unsynchronized mState:%d change",
8071 __func__, recordTrack->id(), recordTrack->mState);
8072 // Someone else has changed state, let them take over,
8073 // leave mState in the new state.
8074 recordTrack->clearSyncStartEvent();
8075 return INVALID_OPERATION;
8076 }
8077 // we're ok, but perhaps startInput has failed
Eric Laurent83b88082014-06-20 18:31:16 -07008078 if (status != NO_ERROR) {
Andy Hungce685402018-10-05 17:23:27 -07008079 ALOGW("%s(%d): startInput failed, status %d",
8080 __func__, recordTrack->id(), status);
8081 // We are in ActiveTracks if STARTING_1 and valid, so remove from ActiveTracks,
8082 // leave in STARTING_1, so destroy() will not call stopInput.
Eric Laurent83b88082014-06-20 18:31:16 -07008083 mActiveTracks.remove(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07008084 recordTrack->clearSyncStartEvent();
Eric Laurent83b88082014-06-20 18:31:16 -07008085 return status;
8086 }
Eric Laurent09f1ed22019-04-24 17:45:17 -07008087 sendIoConfigEvent_l(
8088 AUDIO_CLIENT_STARTED, recordTrack->creatorPid(), recordTrack->portId());
Eric Laurent81784c32012-11-19 14:55:58 -08008089 }
Andy Hungc2b11cb2020-04-22 09:04:01 -07008090
8091 recordTrack->logBeginInterval(patchSourcesToString(&mPatch)); // log to MediaMetrics
8092
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008093 // Catch up with current buffer indices if thread is already running.
8094 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
8095 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
8096 // see previously buffered data before it called start(), but with greater risk of overrun.
8097
Andy Hung73c02e42015-03-29 01:13:58 -07008098 recordTrack->mResamplerBufferProvider->reset();
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008099 if (!recordTrack->isDirect()) {
8100 // clear any converter state as new data will be discontinuous
8101 recordTrack->mRecordBufferConverter->reset();
8102 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008103 recordTrack->mState = TrackBase::STARTING_2;
Eric Laurent81784c32012-11-19 14:55:58 -08008104 // signal thread to start
Eric Laurent81784c32012-11-19 14:55:58 -08008105 mWaitWorkCV.broadcast();
Eric Laurent81784c32012-11-19 14:55:58 -08008106 return status;
8107 }
Eric Laurent81784c32012-11-19 14:55:58 -08008108}
8109
Eric Laurent81784c32012-11-19 14:55:58 -08008110void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
8111{
8112 sp<SyncEvent> strongEvent = event.promote();
8113
8114 if (strongEvent != 0) {
Eric Laurent8ea16e42014-02-20 16:26:11 -08008115 sp<RefBase> ptr = strongEvent->cookie().promote();
8116 if (ptr != 0) {
8117 RecordTrack *recordTrack = (RecordTrack *)ptr.get();
8118 recordTrack->handleSyncStartEvent(strongEvent);
8119 }
Eric Laurent81784c32012-11-19 14:55:58 -08008120 }
8121}
8122
Glenn Kastena8356f62013-07-25 14:37:52 -07008123bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08008124 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07008125 AutoMutex _l(mLock);
Andy Hungce685402018-10-05 17:23:27 -07008126 // if we're invalid, we can't be on the ActiveTracks.
Jean-Michel Trivi38f86712017-04-11 14:10:17 -07008127 if (mActiveTracks.indexOf(recordTrack) < 0 || recordTrack->mState == TrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08008128 return false;
8129 }
Glenn Kasten47c20702013-08-13 15:37:35 -07008130 // note that threadLoop may still be processing the track at this point [without lock]
Eric Laurent81784c32012-11-19 14:55:58 -08008131 recordTrack->mState = TrackBase::PAUSING;
Andy Hungce685402018-10-05 17:23:27 -07008132
Andy Hungabfab202019-03-07 19:45:54 -08008133 // NOTE: Waiting here is important to keep stop synchronous.
8134 // This is needed for proper patchRecord peer release.
Andy Hungce685402018-10-05 17:23:27 -07008135 while (recordTrack->mState == TrackBase::PAUSING && !recordTrack->isInvalid()) {
8136 mWaitWorkCV.broadcast(); // signal thread to stop
8137 mStartStopCond.wait(mLock);
Eric Laurent81784c32012-11-19 14:55:58 -08008138 }
Andy Hungce685402018-10-05 17:23:27 -07008139
8140 if (recordTrack->mState == TrackBase::PAUSED) { // successful stop
Eric Laurent81784c32012-11-19 14:55:58 -08008141 ALOGV("Record stopped OK");
8142 return true;
8143 }
Andy Hungce685402018-10-05 17:23:27 -07008144
8145 // don't handle anything - we've been invalidated or restarted and in a different state
8146 ALOGW_IF("%s(%d): unsynchronized stop, state: %d",
8147 __func__, recordTrack->id(), recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08008148 return false;
8149}
8150
Glenn Kasten0f11b512014-01-31 16:18:54 -08008151bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
Eric Laurent81784c32012-11-19 14:55:58 -08008152{
8153 return false;
8154}
8155
Glenn Kasten0f11b512014-01-31 16:18:54 -08008156status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08008157{
8158#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
8159 if (!isValidSyncEvent(event)) {
8160 return BAD_VALUE;
8161 }
8162
Glenn Kastend848eb42016-03-08 13:42:11 -08008163 audio_session_t eventSession = event->triggerSession();
Eric Laurent81784c32012-11-19 14:55:58 -08008164 status_t ret = NAME_NOT_FOUND;
8165
8166 Mutex::Autolock _l(mLock);
8167
8168 for (size_t i = 0; i < mTracks.size(); i++) {
8169 sp<RecordTrack> track = mTracks[i];
8170 if (eventSession == track->sessionId()) {
8171 (void) track->setSyncEvent(event);
8172 ret = NO_ERROR;
8173 }
8174 }
8175 return ret;
8176#else
8177 return BAD_VALUE;
8178#endif
8179}
8180
jiabin653cc0a2018-01-17 17:54:10 -08008181status_t AudioFlinger::RecordThread::getActiveMicrophones(
8182 std::vector<media::MicrophoneInfo>* activeMicrophones)
8183{
8184 ALOGV("RecordThread::getActiveMicrophones");
8185 AutoMutex _l(mLock);
Jasmine Chaeaa10e42021-05-11 10:11:14 +08008186 if (!isStreamInitialized()) {
Paul McLean8a661a32021-04-12 10:21:42 -06008187 return NO_INIT;
8188 }
jiabin9ff780e2018-03-19 18:19:52 -07008189 status_t status = mInput->stream->getActiveMicrophones(activeMicrophones);
8190 return status;
jiabin653cc0a2018-01-17 17:54:10 -08008191}
8192
Paul McLean12340082019-03-19 09:35:05 -06008193status_t AudioFlinger::RecordThread::setPreferredMicrophoneDirection(
8194 audio_microphone_direction_t direction)
Paul McLean03a6e6a2018-12-04 10:54:13 -07008195{
Paul McLean12340082019-03-19 09:35:05 -06008196 ALOGV("setPreferredMicrophoneDirection(%d)", direction);
Paul McLean03a6e6a2018-12-04 10:54:13 -07008197 AutoMutex _l(mLock);
Jasmine Chaeaa10e42021-05-11 10:11:14 +08008198 if (!isStreamInitialized()) {
Paul McLean8a661a32021-04-12 10:21:42 -06008199 return NO_INIT;
8200 }
Paul McLean12340082019-03-19 09:35:05 -06008201 return mInput->stream->setPreferredMicrophoneDirection(direction);
Paul McLean03a6e6a2018-12-04 10:54:13 -07008202}
8203
Paul McLean12340082019-03-19 09:35:05 -06008204status_t AudioFlinger::RecordThread::setPreferredMicrophoneFieldDimension(float zoom)
Paul McLean03a6e6a2018-12-04 10:54:13 -07008205{
Paul McLean12340082019-03-19 09:35:05 -06008206 ALOGV("setPreferredMicrophoneFieldDimension(%f)", zoom);
Paul McLean03a6e6a2018-12-04 10:54:13 -07008207 AutoMutex _l(mLock);
Jasmine Chaeaa10e42021-05-11 10:11:14 +08008208 if (!isStreamInitialized()) {
Paul McLean8a661a32021-04-12 10:21:42 -06008209 return NO_INIT;
8210 }
Paul McLean12340082019-03-19 09:35:05 -06008211 return mInput->stream->setPreferredMicrophoneFieldDimension(zoom);
Paul McLean03a6e6a2018-12-04 10:54:13 -07008212}
8213
Eric Laurentec376dc2021-04-08 20:41:22 +02008214status_t AudioFlinger::RecordThread::shareAudioHistory(
8215 const std::string& sharedAudioPackageName, audio_session_t sharedSessionId,
8216 int64_t sharedAudioStartMs) {
8217 AutoMutex _l(mLock);
8218 return shareAudioHistory_l(sharedAudioPackageName, sharedSessionId, sharedAudioStartMs);
8219}
8220
8221status_t AudioFlinger::RecordThread::shareAudioHistory_l(
8222 const std::string& sharedAudioPackageName, audio_session_t sharedSessionId,
8223 int64_t sharedAudioStartMs) {
Eric Laurentec376dc2021-04-08 20:41:22 +02008224 if ((hasAudioSession_l(sharedSessionId) & ThreadBase::TRACK_SESSION) == 0) {
8225 return BAD_VALUE;
8226 }
Eric Laurent2407ce32021-04-26 14:56:03 +02008227
8228 if (sharedAudioStartMs < 0
8229 || sharedAudioStartMs > INT64_MAX / mSampleRate) {
Eric Laurentec376dc2021-04-08 20:41:22 +02008230 return BAD_VALUE;
8231 }
8232
Eric Laurent2407ce32021-04-26 14:56:03 +02008233 // Current implementation of the input resampling buffer wraps around indexes at 32 bit.
8234 // As we cannot detect more than one wraparound, only accept values up current write position
8235 // after one wraparound
8236 // We assume recent wraparounds on mRsmpInRear only given it is unlikely that the requesting
8237 // app waits several hours after the start time was computed.
8238 const int64_t sharedAudioStartFrames = sharedAudioStartMs * mSampleRate / 1000;
8239 const int32_t sharedOffset = audio_utils::safe_sub_overflow(mRsmpInRear,
8240 (int32_t)sharedAudioStartFrames);
8241 if (sharedOffset < 0
8242 || sharedOffset > mRsmpInFrames) {
8243 return BAD_VALUE;
8244 }
8245
Eric Laurentec376dc2021-04-08 20:41:22 +02008246 mSharedAudioPackageName = sharedAudioPackageName;
8247 if (mSharedAudioPackageName.empty()) {
8248 mSharedAudioSessionId = AUDIO_SESSION_NONE;
Eric Laurent2407ce32021-04-26 14:56:03 +02008249 mSharedAudioStartFrames = -1;
Eric Laurentec376dc2021-04-08 20:41:22 +02008250 } else {
8251 mSharedAudioSessionId = sharedSessionId;
Eric Laurent2407ce32021-04-26 14:56:03 +02008252 mSharedAudioStartFrames = (int32_t)sharedAudioStartFrames;
Eric Laurentec376dc2021-04-08 20:41:22 +02008253 }
8254 return NO_ERROR;
8255}
8256
Kevin Rocard069c2712018-03-29 19:09:14 -07008257void AudioFlinger::RecordThread::updateMetadata_l()
8258{
Jasmine Chaeaa10e42021-05-11 10:11:14 +08008259 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
8260 return; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -07008261 }
8262 StreamInHalInterface::SinkMetadata metadata;
8263 for (const sp<RecordTrack> &track : mActiveTracks) {
Eric Laurentb9cc0ab2021-01-29 11:46:52 +01008264 // Do not forward PatchRecord metadata to audio HAL
8265 if (track->isPatchTrack()) {
8266 continue;
8267 }
Kevin Rocard069c2712018-03-29 19:09:14 -07008268 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurent94579172020-11-20 18:41:04 +01008269 record_track_metadata_v7_t trackMetadata;
8270 trackMetadata.base = {
Kevin Rocard069c2712018-03-29 19:09:14 -07008271 .source = track->attributes().source,
8272 .gain = 1, // capture tracks do not have volumes
Eric Laurent94579172020-11-20 18:41:04 +01008273 };
8274 trackMetadata.channel_mask = track->channelMask(),
8275 strncpy(trackMetadata.tags, track->attributes().tags, AUDIO_ATTRIBUTES_TAGS_MAX_SIZE);
8276
8277 metadata.tracks.push_back(trackMetadata);
Kevin Rocard069c2712018-03-29 19:09:14 -07008278 }
8279 mInput->stream->updateSinkMetadata(metadata);
8280}
8281
Eric Laurent81784c32012-11-19 14:55:58 -08008282// destroyTrack_l() must be called with ThreadBase::mLock held
8283void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
8284{
Eric Laurentbfb1b832013-01-07 09:53:42 -08008285 track->terminate();
8286 track->mState = TrackBase::STOPPED;
Eric Laurentec376dc2021-04-08 20:41:22 +02008287
Eric Laurent81784c32012-11-19 14:55:58 -08008288 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08008289 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08008290 removeTrack_l(track);
8291 }
8292}
8293
8294void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
8295{
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008296 String8 result;
8297 track->appendDump(result, false /* active */);
8298 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.string());
8299
Eric Laurent81784c32012-11-19 14:55:58 -08008300 mTracks.remove(track);
8301 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008302 if (track->isFastTrack()) {
8303 ALOG_ASSERT(!mFastTrackAvail);
8304 mFastTrackAvail = true;
8305 }
Eric Laurent81784c32012-11-19 14:55:58 -08008306}
8307
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07008308void AudioFlinger::RecordThread::dumpInternals_l(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08008309{
Mikhail Naganov913d06c2016-11-01 12:49:22 -07008310 AudioStreamIn *input = mInput;
8311 audio_input_flags_t flags = input != NULL ? input->flags : AUDIO_INPUT_FLAG_NONE;
8312 dprintf(fd, " AudioStreamIn: %p flags %#x (%s)\n",
Andy Hung9b181952019-02-25 14:53:36 -08008313 input, flags, toString(flags).c_str());
Andy Hung6427e442018-08-09 12:51:02 -07008314 dprintf(fd, " Frames read: %lld\n", (long long)mFramesRead);
Eric Tan39ec8d62018-07-24 09:49:29 -07008315 if (mActiveTracks.isEmpty()) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07008316 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08008317 }
Andy Hungbfa64962017-06-12 14:43:19 -07008318
8319 if (input != nullptr) {
8320 dprintf(fd, " Hal stream dump:\n");
8321 (void)input->stream->dump(fd);
8322 }
8323
Glenn Kasten6e6704c2014-07-03 10:20:00 -07008324 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008325 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Glenn Kasten17c9c992015-03-02 15:53:01 -08008326
Glenn Kasten2f90c512015-12-02 11:40:09 -08008327 // Make a non-atomic copy of fast capture dump state so it won't change underneath us
8328 // while we are dumping it. It may be inconsistent, but it won't mutate!
8329 // This is a large object so we place it on the heap.
8330 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
Eric Tan2942a4e2018-09-12 17:41:27 -07008331 const std::unique_ptr<FastCaptureDumpState> copy =
8332 std::make_unique<FastCaptureDumpState>(mFastCaptureDumpState);
Glenn Kasten2f90c512015-12-02 11:40:09 -08008333 copy->dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08008334}
8335
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07008336void AudioFlinger::RecordThread::dumpTracks_l(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08008337{
Eric Laurent81784c32012-11-19 14:55:58 -08008338 String8 result;
Marco Nelissenb2208842014-02-07 14:00:50 -08008339 size_t numtracks = mTracks.size();
8340 size_t numactive = mActiveTracks.size();
8341 size_t numactiveseen = 0;
Glenn Kastenc42e9b42016-03-21 11:35:03 -07008342 dprintf(fd, " %zu Tracks", numtracks);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008343 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08008344 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07008345 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008346 result.append(prefix);
Andy Hung000adb52018-06-01 15:43:26 -07008347 mTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08008348 for (size_t i = 0; i < numtracks ; ++i) {
8349 sp<RecordTrack> track = mTracks[i];
8350 if (track != 0) {
8351 bool active = mActiveTracks.indexOf(track) >= 0;
8352 if (active) {
8353 numactiveseen++;
8354 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008355 result.append(prefix);
8356 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08008357 }
Eric Laurent81784c32012-11-19 14:55:58 -08008358 }
Marco Nelissenb2208842014-02-07 14:00:50 -08008359 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07008360 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08008361 }
8362
Marco Nelissenb2208842014-02-07 14:00:50 -08008363 if (numactiveseen != numactive) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008364 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08008365 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008366 result.append(prefix);
Andy Hung000adb52018-06-01 15:43:26 -07008367 mActiveTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08008368 for (size_t i = 0; i < numactive; ++i) {
Glenn Kasten2b806402013-11-20 16:37:38 -08008369 sp<RecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08008370 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008371 result.append(prefix);
8372 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08008373 }
Glenn Kasten2b806402013-11-20 16:37:38 -08008374 }
Eric Laurent81784c32012-11-19 14:55:58 -08008375
8376 }
8377 write(fd, result.string(), result.size());
8378}
8379
Eric Laurent5ada82e2019-08-29 17:53:54 -07008380void AudioFlinger::RecordThread::setRecordSilenced(audio_port_handle_t portId, bool silenced)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008381{
8382 Mutex::Autolock _l(mLock);
8383 for (size_t i = 0; i < mTracks.size() ; i++) {
8384 sp<RecordTrack> track = mTracks[i];
Eric Laurent5ada82e2019-08-29 17:53:54 -07008385 if (track != 0 && track->portId() == portId) {
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008386 track->setSilenced(silenced);
8387 }
8388 }
8389}
Andy Hung73c02e42015-03-29 01:13:58 -07008390
8391void AudioFlinger::RecordThread::ResamplerBufferProvider::reset()
8392{
8393 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
8394 RecordThread *recordThread = (RecordThread *) threadBase.get();
Andy Hung73c02e42015-03-29 01:13:58 -07008395 mRsmpInUnrel = 0;
Eric Laurentec376dc2021-04-08 20:41:22 +02008396 const int32_t rear = recordThread->mRsmpInRear;
8397 ssize_t deltaFrames = 0;
Eric Laurent2407ce32021-04-26 14:56:03 +02008398 if (mRecordTrack->startFrames() >= 0) {
8399 int32_t startFrames = mRecordTrack->startFrames();
8400 // Accept a recent wraparound of mRsmpInRear
8401 if (startFrames <= rear) {
8402 deltaFrames = rear - startFrames;
8403 } else {
8404 deltaFrames = (int32_t)((int64_t)rear + UINT32_MAX + 1 - startFrames);
Eric Laurentec376dc2021-04-08 20:41:22 +02008405 }
Eric Laurentec376dc2021-04-08 20:41:22 +02008406 // start frame cannot be further in the past than start of resampling buffer
8407 if ((size_t) deltaFrames > recordThread->mRsmpInFrames) {
8408 deltaFrames = recordThread->mRsmpInFrames;
8409 }
8410 }
8411 mRsmpInFront = audio_utils::safe_sub_overflow(rear, static_cast<int32_t>(deltaFrames));
Andy Hung73c02e42015-03-29 01:13:58 -07008412}
8413
8414void AudioFlinger::RecordThread::ResamplerBufferProvider::sync(
8415 size_t *framesAvailable, bool *hasOverrun)
8416{
8417 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
8418 RecordThread *recordThread = (RecordThread *) threadBase.get();
8419 const int32_t rear = recordThread->mRsmpInRear;
8420 const int32_t front = mRsmpInFront;
Hongwei Wang95e37682019-04-12 11:13:36 -07008421 const ssize_t filled = audio_utils::safe_sub_overflow(rear, front);
Andy Hung73c02e42015-03-29 01:13:58 -07008422
8423 size_t framesIn;
8424 bool overrun = false;
8425 if (filled < 0) {
8426 // should not happen, but treat like a massive overrun and re-sync
8427 framesIn = 0;
8428 mRsmpInFront = rear;
8429 overrun = true;
8430 } else if ((size_t) filled <= recordThread->mRsmpInFrames) {
8431 framesIn = (size_t) filled;
8432 } else {
8433 // client is not keeping up with server, but give it latest data
8434 framesIn = recordThread->mRsmpInFrames;
Hongwei Wang95e37682019-04-12 11:13:36 -07008435 mRsmpInFront = /* front = */ audio_utils::safe_sub_overflow(
8436 rear, static_cast<int32_t>(framesIn));
Andy Hung73c02e42015-03-29 01:13:58 -07008437 overrun = true;
8438 }
8439 if (framesAvailable != NULL) {
8440 *framesAvailable = framesIn;
8441 }
8442 if (hasOverrun != NULL) {
8443 *hasOverrun = overrun;
8444 }
8445}
8446
Eric Laurent81784c32012-11-19 14:55:58 -08008447// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008448status_t AudioFlinger::RecordThread::ResamplerBufferProvider::getNextBuffer(
Glenn Kastend79072e2016-01-06 08:41:20 -08008449 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08008450{
Andy Hung73c02e42015-03-29 01:13:58 -07008451 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008452 if (threadBase == 0) {
8453 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08008454 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008455 return NOT_ENOUGH_DATA;
8456 }
8457 RecordThread *recordThread = (RecordThread *) threadBase.get();
8458 int32_t rear = recordThread->mRsmpInRear;
Andy Hung73c02e42015-03-29 01:13:58 -07008459 int32_t front = mRsmpInFront;
Hongwei Wang95e37682019-04-12 11:13:36 -07008460 ssize_t filled = audio_utils::safe_sub_overflow(rear, front);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008461 // FIXME should not be P2 (don't want to increase latency)
8462 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08008463 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07008464 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008465
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008466 front &= recordThread->mRsmpInFramesP2 - 1;
8467 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07008468 if (part1 > (size_t) filled) {
8469 part1 = filled;
8470 }
8471 size_t ask = buffer->frameCount;
8472 ALOG_ASSERT(ask > 0);
8473 if (part1 > ask) {
8474 part1 = ask;
8475 }
8476 if (part1 == 0) {
Andy Hung73c02e42015-03-29 01:13:58 -07008477 // out of data is fine since the resampler will return a short-count.
Glenn Kasten85948432013-08-19 12:09:05 -07008478 buffer->raw = NULL;
8479 buffer->frameCount = 0;
Andy Hung73c02e42015-03-29 01:13:58 -07008480 mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07008481 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08008482 }
8483
Andy Hung57446612015-04-19 23:56:46 -07008484 buffer->raw = (uint8_t*)recordThread->mRsmpInBuffer + front * recordThread->mFrameSize;
Glenn Kasten85948432013-08-19 12:09:05 -07008485 buffer->frameCount = part1;
Andy Hung73c02e42015-03-29 01:13:58 -07008486 mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08008487 return NO_ERROR;
8488}
8489
8490// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008491void AudioFlinger::RecordThread::ResamplerBufferProvider::releaseBuffer(
8492 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08008493{
Hongwei Wang95e37682019-04-12 11:13:36 -07008494 int32_t stepCount = static_cast<int32_t>(buffer->frameCount);
Glenn Kasten85948432013-08-19 12:09:05 -07008495 if (stepCount == 0) {
8496 return;
8497 }
Andy Hung73c02e42015-03-29 01:13:58 -07008498 ALOG_ASSERT(stepCount <= mRsmpInUnrel);
8499 mRsmpInUnrel -= stepCount;
Hongwei Wang95e37682019-04-12 11:13:36 -07008500 mRsmpInFront = audio_utils::safe_add_overflow(mRsmpInFront, stepCount);
Glenn Kasten85948432013-08-19 12:09:05 -07008501 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08008502 buffer->frameCount = 0;
8503}
8504
Eric Laurentd8365c52017-07-16 15:27:05 -07008505void AudioFlinger::RecordThread::checkBtNrec()
8506{
8507 Mutex::Autolock _l(mLock);
8508 checkBtNrec_l();
8509}
8510
8511void AudioFlinger::RecordThread::checkBtNrec_l()
8512{
8513 // disable AEC and NS if the device is a BT SCO headset supporting those
8514 // pre processings
jiabinc52b1ff2019-10-31 17:20:42 -07008515 bool suspend = audio_is_bluetooth_sco_device(inDeviceType()) &&
Eric Laurentd8365c52017-07-16 15:27:05 -07008516 mAudioFlinger->btNrecIsOff();
8517 if (mBtNrecSuspended.exchange(suspend) != suspend) {
8518 for (size_t i = 0; i < mEffectChains.size(); i++) {
8519 setEffectSuspended_l(FX_IID_AEC, suspend, mEffectChains[i]->sessionId());
8520 setEffectSuspended_l(FX_IID_NS, suspend, mEffectChains[i]->sessionId());
8521 }
8522 }
8523}
8524
Andy Hung97a893e2015-03-29 01:03:07 -07008525
Eric Laurent10351942014-05-08 18:49:52 -07008526bool AudioFlinger::RecordThread::checkForNewParameter_l(const String8& keyValuePair,
8527 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08008528{
8529 bool reconfig = false;
8530
Eric Laurent10351942014-05-08 18:49:52 -07008531 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08008532
Eric Laurent10351942014-05-08 18:49:52 -07008533 audio_format_t reqFormat = mFormat;
8534 uint32_t samplingRate = mSampleRate;
Glenn Kastene1635ec2015-06-08 15:46:49 -07008535 // 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 -07008536 audio_channel_mask_t channelMask = audio_channel_in_mask_from_count(mChannelCount);
8537
8538 AudioParameter param = AudioParameter(keyValuePair);
8539 int value;
Haynes Mathew George9ce67b52015-09-30 11:40:47 -07008540
8541 // scope for AutoPark extends to end of method
8542 AutoPark<FastCapture> park(mFastCapture);
8543
Eric Laurent10351942014-05-08 18:49:52 -07008544 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
8545 // channel count change can be requested. Do we mandate the first client defines the
8546 // HAL sampling rate and channel count or do we allow changes on the fly?
8547 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
8548 samplingRate = value;
8549 reconfig = true;
8550 }
8551 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung97a893e2015-03-29 01:03:07 -07008552 if (!audio_is_linear_pcm((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07008553 status = BAD_VALUE;
8554 } else {
8555 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08008556 reconfig = true;
8557 }
Eric Laurent10351942014-05-08 18:49:52 -07008558 }
8559 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
8560 audio_channel_mask_t mask = (audio_channel_mask_t) value;
Andy Hungd330ee42015-04-20 13:23:41 -07008561 if (!audio_is_input_channel(mask) ||
8562 audio_channel_count_from_in_mask(mask) > FCC_8) {
Eric Laurent10351942014-05-08 18:49:52 -07008563 status = BAD_VALUE;
8564 } else {
8565 channelMask = mask;
8566 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08008567 }
Eric Laurent10351942014-05-08 18:49:52 -07008568 }
8569 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
8570 // do not accept frame count changes if tracks are open as the track buffer
8571 // size depends on frame count and correct behavior would not be guaranteed
8572 // if frame count is changed after track creation
8573 if (mActiveTracks.size() > 0) {
8574 status = INVALID_OPERATION;
8575 } else {
8576 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08008577 }
Eric Laurent10351942014-05-08 18:49:52 -07008578 }
8579 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07008580 LOG_FATAL("Should not set routing device in RecordThread");
Eric Laurent10351942014-05-08 18:49:52 -07008581 }
8582 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
8583 mAudioSource != (audio_source_t)value) {
jiabinc52b1ff2019-10-31 17:20:42 -07008584 LOG_FATAL("Should not set audio source in RecordThread");
Eric Laurent10351942014-05-08 18:49:52 -07008585 }
Glenn Kastene198c362013-08-13 09:13:36 -07008586
Eric Laurent10351942014-05-08 18:49:52 -07008587 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008588 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07008589 if (status == INVALID_OPERATION) {
8590 inputStandBy();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008591 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07008592 }
8593 if (reconfig) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008594 if (status == BAD_VALUE) {
Mikhail Naganov560637e2021-03-31 22:40:13 +00008595 audio_config_base_t config = AUDIO_CONFIG_BASE_INITIALIZER;
8596 if (mInput->stream->getAudioProperties(&config) == OK &&
8597 audio_is_linear_pcm(config.format) && audio_is_linear_pcm(reqFormat) &&
8598 config.sample_rate <= (AUDIO_RESAMPLER_DOWN_RATIO_MAX * samplingRate) &&
8599 audio_channel_count_from_in_mask(config.channel_mask) <= FCC_8) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008600 status = NO_ERROR;
8601 }
Eric Laurent81784c32012-11-19 14:55:58 -08008602 }
Eric Laurent10351942014-05-08 18:49:52 -07008603 if (status == NO_ERROR) {
8604 readInputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07008605 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08008606 }
8607 }
Eric Laurent81784c32012-11-19 14:55:58 -08008608 }
Eric Laurent10351942014-05-08 18:49:52 -07008609
Eric Laurent81784c32012-11-19 14:55:58 -08008610 return reconfig;
8611}
8612
8613String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
8614{
Eric Laurent81784c32012-11-19 14:55:58 -08008615 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008616 if (initCheck() == NO_ERROR) {
8617 String8 out_s8;
8618 if (mInput->stream->getParameters(keys, &out_s8) == OK) {
8619 return out_s8;
8620 }
Eric Laurent81784c32012-11-19 14:55:58 -08008621 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008622 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08008623}
8624
Eric Laurent09f1ed22019-04-24 17:45:17 -07008625void AudioFlinger::RecordThread::ioConfigChanged(audio_io_config_event event, pid_t pid,
8626 audio_port_handle_t portId) {
Eric Laurent73e26b62015-04-27 16:55:58 -07008627 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
8628
8629 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08008630
8631 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07008632 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07008633 case AUDIO_INPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07008634 case AUDIO_INPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07008635 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07008636 desc->mChannelMask = mChannelMask;
8637 desc->mSamplingRate = mSampleRate;
8638 desc->mFormat = mFormat;
8639 desc->mFrameCount = mFrameCount;
Glenn Kasten4a8308b2016-04-18 14:10:01 -07008640 desc->mFrameCountHAL = mFrameCount;
Eric Laurent73e26b62015-04-27 16:55:58 -07008641 desc->mLatency = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08008642 break;
Eric Laurent09f1ed22019-04-24 17:45:17 -07008643 case AUDIO_CLIENT_STARTED:
8644 desc->mPatch = mPatch;
8645 desc->mPortId = portId;
8646 break;
Eric Laurent73e26b62015-04-27 16:55:58 -07008647 case AUDIO_INPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08008648 default:
8649 break;
8650 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07008651 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08008652}
8653
Glenn Kastendeca2ae2014-02-07 10:25:56 -08008654void AudioFlinger::RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08008655{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008656 status_t result = mInput->stream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
8657 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
Andy Hung463be252014-07-10 16:56:07 -07008658 mFormat = mHALFormat;
Mikhail Naganovce9f2652018-07-16 11:09:24 -07008659 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
8660 if (audio_is_linear_pcm(mFormat)) {
8661 LOG_ALWAYS_FATAL_IF(mChannelCount > FCC_8, "HAL channel count %d > %d",
8662 mChannelCount, FCC_8);
8663 } else {
8664 // Can have more that FCC_8 channels in encoded streams.
8665 ALOGI("HAL format %#x is not linear pcm", mFormat);
8666 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008667 result = mInput->stream->getFrameSize(&mFrameSize);
8668 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
Hayden Gomes1a89ab32020-06-12 11:05:47 -07008669 LOG_ALWAYS_FATAL_IF(mFrameSize <= 0, "Error frame size was %zu but must be greater than zero",
8670 mFrameSize);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008671 result = mInput->stream->getBufferSize(&mBufferSize);
8672 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
Glenn Kasten548efc92012-11-29 08:48:51 -08008673 mFrameCount = mBufferSize / mFrameSize;
Hayden Gomes1a89ab32020-06-12 11:05:47 -07008674 ALOGV("%p RecordThread params: mChannelCount=%u, mFormat=%#x, mFrameSize=%zu, "
8675 "mBufferSize=%zu, mFrameCount=%zu",
8676 this, mChannelCount, mFormat, mFrameSize, mBufferSize, mFrameCount);
Glenn Kasten49d00ad2014-07-21 11:22:03 -07008677
Eric Laurentec376dc2021-04-08 20:41:22 +02008678 // mRsmpInFrames must be 0 before calling resizeInputBuffer_l for the first time
8679 mRsmpInFrames = 0;
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008680 resizeInputBuffer_l(0 /*maxSharedAudioHistoryMs*/);
Eric Laurent81784c32012-11-19 14:55:58 -08008681
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08008682 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
8683 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Andy Hungea840382020-05-05 21:50:17 -07008684
8685 audio_input_flags_t flags = mInput->flags;
8686 mediametrics::LogItem item(mThreadMetrics.getMetricsId());
8687 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
8688 .set(AMEDIAMETRICS_PROP_ENCODING, formatToString(mFormat).c_str())
8689 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
8690 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
8691 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
8692 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
8693 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mFrameCount)
8694 .record();
Eric Laurent81784c32012-11-19 14:55:58 -08008695}
8696
Glenn Kasten5f972c02014-01-13 09:59:31 -08008697uint32_t AudioFlinger::RecordThread::getInputFramesLost()
Eric Laurent81784c32012-11-19 14:55:58 -08008698{
8699 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008700 uint32_t result;
8701 if (initCheck() == NO_ERROR && mInput->stream->getInputFramesLost(&result) == OK) {
8702 return result;
Eric Laurent81784c32012-11-19 14:55:58 -08008703 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008704 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08008705}
8706
Glenn Kastend848eb42016-03-08 13:42:11 -08008707KeyedVector<audio_session_t, bool> AudioFlinger::RecordThread::sessionIds() const
Eric Laurent81784c32012-11-19 14:55:58 -08008708{
Glenn Kastend848eb42016-03-08 13:42:11 -08008709 KeyedVector<audio_session_t, bool> ids;
Eric Laurent81784c32012-11-19 14:55:58 -08008710 Mutex::Autolock _l(mLock);
8711 for (size_t j = 0; j < mTracks.size(); ++j) {
8712 sp<RecordThread::RecordTrack> track = mTracks[j];
Glenn Kastend848eb42016-03-08 13:42:11 -08008713 audio_session_t sessionId = track->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08008714 if (ids.indexOfKey(sessionId) < 0) {
8715 ids.add(sessionId, true);
8716 }
8717 }
8718 return ids;
8719}
8720
8721AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
8722{
8723 Mutex::Autolock _l(mLock);
8724 AudioStreamIn *input = mInput;
8725 mInput = NULL;
8726 return input;
8727}
8728
8729// this method must always be called either with ThreadBase mLock held or inside the thread loop
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008730sp<StreamHalInterface> AudioFlinger::RecordThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08008731{
8732 if (mInput == NULL) {
8733 return NULL;
8734 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008735 return mInput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08008736}
8737
8738status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
8739{
Eric Laurent81784c32012-11-19 14:55:58 -08008740 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurentaaa44472014-09-12 17:41:50 -07008741 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08008742 chain->setInBuffer(NULL);
8743 chain->setOutBuffer(NULL);
8744
8745 checkSuspendOnAddEffectChain_l(chain);
8746
Eric Laurent1b928682014-10-02 19:41:47 -07008747 // make sure enabled pre processing effects state is communicated to the HAL as we
8748 // just moved them to a new input stream.
8749 chain->syncHalEffectsState();
8750
Eric Laurent81784c32012-11-19 14:55:58 -08008751 mEffectChains.add(chain);
8752
8753 return NO_ERROR;
8754}
8755
8756size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
8757{
8758 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
Eric Laurentb20cf7d2019-04-05 19:37:34 -07008759
8760 for (size_t i = 0; i < mEffectChains.size(); i++) {
8761 if (chain == mEffectChains[i]) {
8762 mEffectChains.removeAt(i);
8763 break;
8764 }
Eric Laurent81784c32012-11-19 14:55:58 -08008765 }
Eric Laurentb20cf7d2019-04-05 19:37:34 -07008766 return mEffectChains.size();
Eric Laurent81784c32012-11-19 14:55:58 -08008767}
8768
Eric Laurent1c333e22014-05-20 10:48:17 -07008769status_t AudioFlinger::RecordThread::createAudioPatch_l(const struct audio_patch *patch,
8770 audio_patch_handle_t *handle)
8771{
8772 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07008773
8774 // store new device and send to effects
jiabinc52b1ff2019-10-31 17:20:42 -07008775 mInDeviceTypeAddr.mType = patch->sources[0].ext.device.type;
jiabin0a488932020-08-07 17:32:40 -07008776 mInDeviceTypeAddr.setAddress(patch->sources[0].ext.device.address);
François Gaffie0c280aa2018-07-25 10:02:15 +02008777 audio_port_handle_t deviceId = patch->sources[0].id;
Eric Laurent054d9d32015-04-24 08:48:48 -07008778 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08008779 mEffectChains[i]->setInputDevice_l(inDeviceTypeAddr());
Eric Laurent054d9d32015-04-24 08:48:48 -07008780 }
8781
Eric Laurentd8365c52017-07-16 15:27:05 -07008782 checkBtNrec_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07008783
8784 // store new source and send to effects
8785 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
8786 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent1c333e22014-05-20 10:48:17 -07008787 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent054d9d32015-04-24 08:48:48 -07008788 mEffectChains[i]->setAudioSource_l(mAudioSource);
Eric Laurent1c333e22014-05-20 10:48:17 -07008789 }
Eric Laurent054d9d32015-04-24 08:48:48 -07008790 }
Eric Laurent1c333e22014-05-20 10:48:17 -07008791
Mikhail Naganov9ee05402016-10-13 15:58:17 -07008792 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07008793 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
8794 status = hwDevice->createAudioPatch(patch->num_sources,
8795 patch->sources,
8796 patch->num_sinks,
8797 patch->sinks,
8798 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07008799 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07008800 char *address;
8801 if (strcmp(patch->sources[0].ext.device.address, "") != 0) {
8802 address = audio_device_address_to_parameter(
8803 patch->sources[0].ext.device.type,
8804 patch->sources[0].ext.device.address);
8805 } else {
8806 address = (char *)calloc(1, 1);
8807 }
8808 AudioParameter param = AudioParameter(String8(address));
8809 free(address);
Mikhail Naganov00260b52016-10-13 12:54:24 -07008810 param.addInt(String8(AudioParameter::keyRouting),
Eric Laurent054d9d32015-04-24 08:48:48 -07008811 (int)patch->sources[0].ext.device.type);
Mikhail Naganov00260b52016-10-13 12:54:24 -07008812 param.addInt(String8(AudioParameter::keyInputSource),
Eric Laurent054d9d32015-04-24 08:48:48 -07008813 (int)patch->sinks[0].ext.mix.usecase.source);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008814 status = mInput->stream->setParameters(param.toString());
Eric Laurent054d9d32015-04-24 08:48:48 -07008815 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07008816 }
Eric Laurent054d9d32015-04-24 08:48:48 -07008817
jiabinc52b1ff2019-10-31 17:20:42 -07008818 if ((mPatch.num_sources == 0) || (mPatch.sources[0].id != deviceId)) {
Eric Laurente8726fe2015-06-26 09:39:24 -07008819 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
jiabinc52b1ff2019-10-31 17:20:42 -07008820 mPatch = *patch;
Eric Laurente8726fe2015-06-26 09:39:24 -07008821 }
Eric Laurent296fb132015-05-01 11:38:42 -07008822
Andy Hungc2b11cb2020-04-22 09:04:01 -07008823 const std::string pathSourcesAsString = patchSourcesToString(patch);
Andy Hungcf10d742020-04-28 15:38:24 -07008824 mThreadMetrics.logEndInterval();
Andy Hungea840382020-05-05 21:50:17 -07008825 mThreadMetrics.logCreatePatch(pathSourcesAsString, /* outDevices */ {});
Andy Hungcf10d742020-04-28 15:38:24 -07008826 mThreadMetrics.logBeginInterval();
Andy Hungc2b11cb2020-04-22 09:04:01 -07008827 // also dispatch to active AudioRecords
8828 for (const auto &track : mActiveTracks) {
8829 track->logEndInterval();
8830 track->logBeginInterval(pathSourcesAsString);
8831 }
Eric Laurent1c333e22014-05-20 10:48:17 -07008832 return status;
8833}
8834
8835status_t AudioFlinger::RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
8836{
8837 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07008838
jiabinc52b1ff2019-10-31 17:20:42 -07008839 mPatch = audio_patch{};
8840 mInDeviceTypeAddr.reset();
Eric Laurent054d9d32015-04-24 08:48:48 -07008841
Mikhail Naganov9ee05402016-10-13 15:58:17 -07008842 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07008843 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
8844 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07008845 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07008846 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07008847 param.addInt(String8(AudioParameter::keyRouting), 0);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008848 status = mInput->stream->setParameters(param.toString());
Eric Laurent1c333e22014-05-20 10:48:17 -07008849 }
8850 return status;
8851}
8852
jiabinc52b1ff2019-10-31 17:20:42 -07008853void AudioFlinger::RecordThread::updateOutDevices(const DeviceDescriptorBaseVector& outDevices)
8854{
wendy lin56aa82b2020-12-02 15:19:55 +08008855 Mutex::Autolock _l(mLock);
jiabinc52b1ff2019-10-31 17:20:42 -07008856 mOutDevices = outDevices;
8857 mOutDeviceTypeAddrs = deviceTypeAddrsFromDescriptors(mOutDevices);
8858 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08008859 mEffectChains[i]->setDevices_l(outDeviceTypeAddrs());
jiabinc52b1ff2019-10-31 17:20:42 -07008860 }
8861}
8862
Eric Laurentec376dc2021-04-08 20:41:22 +02008863int32_t AudioFlinger::RecordThread::getOldestFront_l()
8864{
8865 if (mTracks.size() == 0) {
8866 return 0;
8867 }
Eric Laurent2407ce32021-04-26 14:56:03 +02008868 int32_t oldestFront = mRsmpInRear;
8869 int32_t maxFilled = 0;
Eric Laurentec376dc2021-04-08 20:41:22 +02008870 for (size_t i = 0; i < mTracks.size(); i++) {
Eric Laurent2407ce32021-04-26 14:56:03 +02008871 int32_t front = mTracks[i]->mResamplerBufferProvider->getFront();
8872 int32_t filled;
8873 if (front <= mRsmpInRear) {
8874 filled = mRsmpInRear - front;
8875 } else {
8876 filled = (int32_t)((int64_t)mRsmpInRear + UINT32_MAX + 1 - front);
8877 }
8878 if (filled > maxFilled) {
8879 oldestFront = front;
8880 maxFilled = filled;
8881 }
Eric Laurentec376dc2021-04-08 20:41:22 +02008882 }
Eric Laurent2407ce32021-04-26 14:56:03 +02008883 return oldestFront;
Eric Laurentec376dc2021-04-08 20:41:22 +02008884}
8885
8886void AudioFlinger::RecordThread::updateFronts_l(int32_t offset)
8887{
8888 if (offset == 0) {
8889 return;
8890 }
8891 for (size_t i = 0; i < mTracks.size(); i++) {
8892 int32_t front = mTracks[i]->mResamplerBufferProvider->getFront();
8893 front = audio_utils::safe_sub_overflow(front, offset);
8894 mTracks[i]->mResamplerBufferProvider->setFront(front);
8895 }
8896}
8897
8898void AudioFlinger::RecordThread::resizeInputBuffer_l(int32_t maxSharedAudioHistoryMs)
8899{
8900 // This is the formula for calculating the temporary buffer size.
8901 // With 7 HAL buffers, we can guarantee ability to down-sample the input by ratio of 6:1 to
8902 // 1 full output buffer, regardless of the alignment of the available input.
8903 // The value is somewhat arbitrary, and could probably be even larger.
8904 // A larger value should allow more old data to be read after a track calls start(),
8905 // without increasing latency.
8906 //
8907 // Note this is independent of the maximum downsampling ratio permitted for capture.
8908 size_t minRsmpInFrames = mFrameCount * 7;
8909
8910 // maxSharedAudioHistoryMs != 0 indicates a request to possibly make some part of the audio
8911 // capture history available to another client using the same session ID:
8912 // dimension the resampler input buffer accordingly.
8913
8914 // Get oldest client read position: getOldestFront_l() must be called before altering
8915 // mRsmpInRear, or mRsmpInFrames
8916 int32_t previousFront = getOldestFront_l();
8917 size_t previousRsmpInFramesP2 = mRsmpInFramesP2;
8918 int32_t previousRear = mRsmpInRear;
8919 mRsmpInRear = 0;
8920
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008921 ALOG_ASSERT(maxSharedAudioHistoryMs >= 0
8922 && maxSharedAudioHistoryMs <= AudioFlinger::kMaxSharedAudioHistoryMs,
8923 "resizeInputBuffer_l() called with invalid max shared history %d",
8924 maxSharedAudioHistoryMs);
Eric Laurentec376dc2021-04-08 20:41:22 +02008925 if (maxSharedAudioHistoryMs != 0) {
8926 // resizeInputBuffer_l should never be called with a non zero shared history if the
8927 // buffer was not already allocated
8928 ALOG_ASSERT(mRsmpInBuffer != nullptr && mRsmpInFrames != 0,
8929 "resizeInputBuffer_l() called with shared history and unallocated buffer");
8930 size_t rsmpInFrames = (size_t)maxSharedAudioHistoryMs * mSampleRate / 1000;
8931 // never reduce resampler input buffer size
8932 if (rsmpInFrames < mRsmpInFrames) {
8933 return;
8934 }
8935 mRsmpInFrames = rsmpInFrames;
8936 }
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008937 mMaxSharedAudioHistoryMs = maxSharedAudioHistoryMs;
Eric Laurentec376dc2021-04-08 20:41:22 +02008938 // Note: mRsmpInFrames is 0 when called with maxSharedAudioHistoryMs equals to 0 so it is always
8939 // initialized
8940 if (mRsmpInFrames < minRsmpInFrames) {
8941 mRsmpInFrames = minRsmpInFrames;
8942 }
8943 mRsmpInFramesP2 = roundup(mRsmpInFrames);
8944
8945 // TODO optimize audio capture buffer sizes ...
8946 // Here we calculate the size of the sliding buffer used as a source
8947 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
8948 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
8949 // be better to have it derived from the pipe depth in the long term.
8950 // The current value is higher than necessary. However it should not add to latency.
8951
8952 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
8953 mRsmpInFramesOA = mRsmpInFramesP2 + mFrameCount - 1;
8954
8955 void *rsmpInBuffer;
8956 (void)posix_memalign(&rsmpInBuffer, 32, mRsmpInFramesOA * mFrameSize);
8957 // if posix_memalign fails, will segv here.
8958 memset(rsmpInBuffer, 0, mRsmpInFramesOA * mFrameSize);
8959
8960 // Copy audio history if any from old buffer before freeing it
8961 if (previousRear != 0) {
8962 ALOG_ASSERT(mRsmpInBuffer != nullptr,
8963 "resizeInputBuffer_l() called with null buffer but frames already read from HAL");
8964
8965 ssize_t unread = audio_utils::safe_sub_overflow(previousRear, previousFront);
8966 previousFront &= previousRsmpInFramesP2 - 1;
8967 size_t part1 = previousRsmpInFramesP2 - previousFront;
8968 if (part1 > (size_t) unread) {
8969 part1 = unread;
8970 }
8971 if (part1 != 0) {
8972 memcpy(rsmpInBuffer, (const uint8_t*)mRsmpInBuffer + previousFront * mFrameSize,
8973 part1 * mFrameSize);
8974 mRsmpInRear = part1;
8975 part1 = unread - part1;
8976 if (part1 != 0) {
8977 memcpy((uint8_t*)rsmpInBuffer + mRsmpInRear * mFrameSize,
8978 (const uint8_t*)mRsmpInBuffer, part1 * mFrameSize);
8979 mRsmpInRear += part1;
8980 }
8981 }
8982 // Update front for all clients according to new rear
8983 updateFronts_l(audio_utils::safe_sub_overflow(previousRear, mRsmpInRear));
8984 } else {
8985 mRsmpInRear = 0;
8986 }
8987 free(mRsmpInBuffer);
8988 mRsmpInBuffer = rsmpInBuffer;
8989}
8990
Mikhail Naganov444ecc32018-05-01 17:40:05 -07008991void AudioFlinger::RecordThread::addPatchTrack(const sp<PatchRecord>& record)
Eric Laurent83b88082014-06-20 18:31:16 -07008992{
8993 Mutex::Autolock _l(mLock);
8994 mTracks.add(record);
Mikhail Naganov2534b382019-09-25 13:05:02 -07008995 if (record->getSource()) {
8996 mSource = record->getSource();
8997 }
Eric Laurent83b88082014-06-20 18:31:16 -07008998}
8999
Mikhail Naganov444ecc32018-05-01 17:40:05 -07009000void AudioFlinger::RecordThread::deletePatchTrack(const sp<PatchRecord>& record)
Eric Laurent83b88082014-06-20 18:31:16 -07009001{
9002 Mutex::Autolock _l(mLock);
Mikhail Naganov2534b382019-09-25 13:05:02 -07009003 if (mSource == record->getSource()) {
9004 mSource = mInput;
9005 }
Eric Laurent83b88082014-06-20 18:31:16 -07009006 destroyTrack_l(record);
9007}
9008
Mikhail Naganovdc769682018-05-04 15:34:08 -07009009void AudioFlinger::RecordThread::toAudioPortConfig(struct audio_port_config *config)
Eric Laurent83b88082014-06-20 18:31:16 -07009010{
Mikhail Naganovdc769682018-05-04 15:34:08 -07009011 ThreadBase::toAudioPortConfig(config);
Eric Laurent83b88082014-06-20 18:31:16 -07009012 config->role = AUDIO_PORT_ROLE_SINK;
9013 config->ext.mix.hw_module = mInput->audioHwDev->handle();
9014 config->ext.mix.usecase.source = mAudioSource;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07009015 if (mInput && mInput->flags != AUDIO_INPUT_FLAG_NONE) {
9016 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
9017 config->flags.input = mInput->flags;
9018 }
Eric Laurent83b88082014-06-20 18:31:16 -07009019}
Eric Laurent1c333e22014-05-20 10:48:17 -07009020
Eric Laurent6acd1d42017-01-04 14:23:29 -08009021// ----------------------------------------------------------------------------
9022// Mmap
9023// ----------------------------------------------------------------------------
9024
9025AudioFlinger::MmapThreadHandle::MmapThreadHandle(const sp<MmapThread>& thread)
9026 : mThread(thread)
9027{
Phil Burk9fabbf82017-08-03 12:02:00 -07009028 assert(thread != 0); // thread must start non-null and stay non-null
Eric Laurent6acd1d42017-01-04 14:23:29 -08009029}
9030
9031AudioFlinger::MmapThreadHandle::~MmapThreadHandle()
9032{
Phil Burk9fabbf82017-08-03 12:02:00 -07009033 mThread->disconnect();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009034}
9035
9036status_t AudioFlinger::MmapThreadHandle::createMmapBuffer(int32_t minSizeFrames,
9037 struct audio_mmap_buffer_info *info)
9038{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009039 return mThread->createMmapBuffer(minSizeFrames, info);
9040}
9041
9042status_t AudioFlinger::MmapThreadHandle::getMmapPosition(struct audio_mmap_position *position)
9043{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009044 return mThread->getMmapPosition(position);
9045}
9046
jiabinb7d8c5a2020-08-26 17:24:52 -07009047status_t AudioFlinger::MmapThreadHandle::getExternalPosition(uint64_t *position,
9048 int64_t *timeNanos) {
9049 return mThread->getExternalPosition(position, timeNanos);
9050}
9051
Eric Laurenta54f1282017-07-01 19:39:32 -07009052status_t AudioFlinger::MmapThreadHandle::start(const AudioClient& client,
jiabind1f1cb62020-03-24 11:57:57 -07009053 const audio_attributes_t *attr, audio_port_handle_t *handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009054
9055{
jiabind1f1cb62020-03-24 11:57:57 -07009056 return mThread->start(client, attr, handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009057}
9058
9059status_t AudioFlinger::MmapThreadHandle::stop(audio_port_handle_t handle)
9060{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009061 return mThread->stop(handle);
9062}
9063
Eric Laurent18b57012017-02-13 16:23:52 -08009064status_t AudioFlinger::MmapThreadHandle::standby()
9065{
Eric Laurent18b57012017-02-13 16:23:52 -08009066 return mThread->standby();
9067}
9068
Eric Laurent6acd1d42017-01-04 14:23:29 -08009069
9070AudioFlinger::MmapThread::MmapThread(
9071 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
Andy Hungcf10d742020-04-28 15:38:24 -07009072 AudioHwDevice *hwDev, sp<StreamHalInterface> stream, bool systemReady, bool isOut)
Andy Hungea840382020-05-05 21:50:17 -07009073 : ThreadBase(audioFlinger, id, (isOut ? MMAP_PLAYBACK : MMAP_CAPTURE), systemReady, isOut),
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009074 mSessionId(AUDIO_SESSION_NONE),
François Gaffie0c280aa2018-07-25 10:02:15 +02009075 mPortId(AUDIO_PORT_HANDLE_NONE),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009076 mHalStream(stream), mHalDevice(hwDev->hwDevice()), mAudioHwDev(hwDev),
Eric Laurent67f97292018-04-20 18:05:41 -07009077 mActiveTracks(&this->mLocalLog),
9078 mHalVolFloat(-1.0f), // Initialize to illegal value so it always gets set properly later.
9079 mNoCallbackWarningCount(0)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009080{
Eric Laurent18b57012017-02-13 16:23:52 -08009081 mStandby = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009082 readHalParameters_l();
9083}
9084
9085AudioFlinger::MmapThread::~MmapThread()
9086{
9087}
9088
9089void AudioFlinger::MmapThread::onFirstRef()
9090{
9091 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
9092}
9093
9094void AudioFlinger::MmapThread::disconnect()
9095{
Eric Laurent331679c2018-04-16 17:03:16 -07009096 ActiveTracks<MmapTrack> activeTracks;
9097 {
9098 Mutex::Autolock _l(mLock);
9099 for (const sp<MmapTrack> &t : mActiveTracks) {
9100 activeTracks.add(t);
9101 }
9102 }
9103 for (const sp<MmapTrack> &t : activeTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08009104 stop(t->portId());
9105 }
Phil Burk9fabbf82017-08-03 12:02:00 -07009106 // This will decrement references and may cause the destruction of this thread.
Eric Laurent6acd1d42017-01-04 14:23:29 -08009107 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07009108 AudioSystem::releaseOutput(mPortId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009109 } else {
Eric Laurentfee19762018-01-29 18:44:13 -08009110 AudioSystem::releaseInput(mPortId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009111 }
9112}
9113
9114
9115void AudioFlinger::MmapThread::configure(const audio_attributes_t *attr,
9116 audio_stream_type_t streamType __unused,
9117 audio_session_t sessionId,
9118 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009119 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -08009120 audio_port_handle_t portId)
9121{
9122 mAttr = *attr;
9123 mSessionId = sessionId;
9124 mCallback = callback;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009125 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009126 mPortId = portId;
9127}
9128
9129status_t AudioFlinger::MmapThread::createMmapBuffer(int32_t minSizeFrames,
9130 struct audio_mmap_buffer_info *info)
9131{
9132 if (mHalStream == 0) {
9133 return NO_INIT;
9134 }
Eric Laurent18b57012017-02-13 16:23:52 -08009135 mStandby = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009136 return mHalStream->createMmapBuffer(minSizeFrames, info);
9137}
9138
9139status_t AudioFlinger::MmapThread::getMmapPosition(struct audio_mmap_position *position)
9140{
9141 if (mHalStream == 0) {
9142 return NO_INIT;
9143 }
9144 return mHalStream->getMmapPosition(position);
9145}
9146
Eric Laurent331679c2018-04-16 17:03:16 -07009147status_t AudioFlinger::MmapThread::exitStandby()
9148{
9149 status_t ret = mHalStream->start();
9150 if (ret != NO_ERROR) {
9151 ALOGE("%s: error mHalStream->start() = %d for first track", __FUNCTION__, ret);
9152 return ret;
9153 }
Andy Hungcf10d742020-04-28 15:38:24 -07009154 if (mStandby) {
9155 mThreadMetrics.logBeginInterval();
9156 mStandby = false;
9157 }
Eric Laurent331679c2018-04-16 17:03:16 -07009158 return NO_ERROR;
9159}
9160
Eric Laurenta54f1282017-07-01 19:39:32 -07009161status_t AudioFlinger::MmapThread::start(const AudioClient& client,
jiabind1f1cb62020-03-24 11:57:57 -07009162 const audio_attributes_t *attr,
Eric Laurent6acd1d42017-01-04 14:23:29 -08009163 audio_port_handle_t *handle)
9164{
Eric Laurenta54f1282017-07-01 19:39:32 -07009165 ALOGV("%s clientUid %d mStandby %d mPortId %d *handle %d", __FUNCTION__,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07009166 client.identity.uid, mStandby, mPortId, *handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009167 if (mHalStream == 0) {
9168 return NO_INIT;
9169 }
9170
9171 status_t ret;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009172
Eric Laurenta54f1282017-07-01 19:39:32 -07009173 if (*handle == mPortId) {
Phil Burk98ab4082020-09-25 21:46:34 +00009174 // For the first track, reuse portId and session allocated when the stream was opened.
9175 ret = exitStandby();
9176 if (ret == NO_ERROR) {
9177 acquireWakeLock();
9178 }
9179 return ret;
Eric Laurenta54f1282017-07-01 19:39:32 -07009180 }
9181
9182 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
9183
9184 audio_io_handle_t io = mId;
9185 if (isOutput()) {
9186 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
9187 config.sample_rate = mSampleRate;
9188 config.channel_mask = mChannelMask;
9189 config.format = mFormat;
9190 audio_stream_type_t stream = streamType();
9191 audio_output_flags_t flags =
9192 (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009193 audio_port_handle_t deviceId = mDeviceId;
Kevin Rocard153f92d2018-12-18 18:33:28 -08009194 std::vector<audio_io_handle_t> secondaryOutputs;
Eric Laurenta54f1282017-07-01 19:39:32 -07009195 ret = AudioSystem::getOutputForAttr(&mAttr, &io,
9196 mSessionId,
9197 &stream,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07009198 client.identity,
Eric Laurenta54f1282017-07-01 19:39:32 -07009199 &config,
9200 flags,
9201 &deviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -08009202 &portId,
9203 &secondaryOutputs);
9204 ALOGD_IF(!secondaryOutputs.empty(),
9205 "MmapThread::start does not support secondary outputs, ignoring them");
Eric Laurent6acd1d42017-01-04 14:23:29 -08009206 } else {
Eric Laurenta54f1282017-07-01 19:39:32 -07009207 audio_config_base_t config;
9208 config.sample_rate = mSampleRate;
9209 config.channel_mask = mChannelMask;
9210 config.format = mFormat;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009211 audio_port_handle_t deviceId = mDeviceId;
Eric Laurenta54f1282017-07-01 19:39:32 -07009212 ret = AudioSystem::getInputForAttr(&mAttr, &io,
Mikhail Naganov2996f672019-04-18 12:29:59 -07009213 RECORD_RIID_INVALID,
Eric Laurenta54f1282017-07-01 19:39:32 -07009214 mSessionId,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07009215 client.identity,
Eric Laurenta54f1282017-07-01 19:39:32 -07009216 &config,
9217 AUDIO_INPUT_FLAG_MMAP_NOIRQ,
9218 &deviceId,
9219 &portId);
9220 }
9221 // APM should not chose a different input or output stream for the same set of attributes
9222 // and audo configuration
9223 if (ret != NO_ERROR || io != mId) {
9224 ALOGE("%s: error getting output or input from APM (error %d, io %d expected io %d)",
9225 __FUNCTION__, ret, io, mId);
9226 return BAD_VALUE;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009227 }
9228
9229 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07009230 ret = AudioSystem::startOutput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009231 } else {
Eric Laurent4eb58f12018-12-07 16:41:02 -08009232 ret = AudioSystem::startInput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009233 }
9234
Eric Laurent331679c2018-04-16 17:03:16 -07009235 Mutex::Autolock _l(mLock);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009236 // abort if start is rejected by audio policy manager
9237 if (ret != NO_ERROR) {
Phil Burk7f6b40d2017-02-09 13:18:38 -08009238 ALOGE("%s: error start rejected by AudioPolicyManager = %d", __FUNCTION__, ret);
Eric Tan39ec8d62018-07-24 09:49:29 -07009239 if (!mActiveTracks.isEmpty()) {
Eric Laurent331679c2018-04-16 17:03:16 -07009240 mLock.unlock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009241 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07009242 AudioSystem::releaseOutput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009243 } else {
Eric Laurentfee19762018-01-29 18:44:13 -08009244 AudioSystem::releaseInput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009245 }
Eric Laurent331679c2018-04-16 17:03:16 -07009246 mLock.lock();
Eric Laurent18b57012017-02-13 16:23:52 -08009247 } else {
9248 mHalStream->stop();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009249 }
9250 return PERMISSION_DENIED;
9251 }
9252
Kevin Rocard1f564ac2018-03-29 13:53:10 -07009253 // Given that MmapThread::mAttr is mutable, should a MmapTrack have attributes ?
jiabind1f1cb62020-03-24 11:57:57 -07009254 sp<MmapTrack> track = new MmapTrack(this, attr == nullptr ? mAttr : *attr, mSampleRate, mFormat,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07009255 mChannelMask, mSessionId, isOutput(), client.identity,
9256 IPCThreadState::self()->getCallingPid(), portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009257
Eric Laurent4eb58f12018-12-07 16:41:02 -08009258 if (isOutput()) {
9259 // force volume update when a new track is added
9260 mHalVolFloat = -1.0f;
9261 } else if (!track->isSilenced_l()) {
9262 for (const sp<MmapTrack> &t : mActiveTracks) {
Philip P. Moltmannbda45752020-07-17 16:41:18 -07009263 if (t->isSilenced_l() && t->uid() != client.identity.uid)
Eric Laurent4eb58f12018-12-07 16:41:02 -08009264 t->invalidate();
9265 }
9266 }
9267
9268
Eric Laurent6acd1d42017-01-04 14:23:29 -08009269 mActiveTracks.add(track);
Eric Laurenta54f1282017-07-01 19:39:32 -07009270 sp<EffectChain> chain = getEffectChain_l(mSessionId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009271 if (chain != 0) {
9272 chain->setStrategy(AudioSystem::getStrategyForStream(streamType()));
9273 chain->incTrackCnt();
9274 chain->incActiveTrackCnt();
9275 }
9276
Andy Hungc2b11cb2020-04-22 09:04:01 -07009277 track->logBeginInterval(patchSinksToString(&mPatch)); // log to MediaMetrics
Eric Laurent6acd1d42017-01-04 14:23:29 -08009278 *handle = portId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009279 broadcast_l();
9280
Eric Laurenta54f1282017-07-01 19:39:32 -07009281 ALOGV("%s DONE handle %d stream %p", __FUNCTION__, *handle, mHalStream.get());
Eric Laurent6acd1d42017-01-04 14:23:29 -08009282
9283 return NO_ERROR;
9284}
9285
9286status_t AudioFlinger::MmapThread::stop(audio_port_handle_t handle)
9287{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009288 ALOGV("%s handle %d", __FUNCTION__, handle);
9289
9290 if (mHalStream == 0) {
9291 return NO_INIT;
9292 }
9293
Eric Laurenta54f1282017-07-01 19:39:32 -07009294 if (handle == mPortId) {
9295 mHalStream->stop();
Phil Burk98ab4082020-09-25 21:46:34 +00009296 releaseWakeLock();
Eric Laurenta54f1282017-07-01 19:39:32 -07009297 return NO_ERROR;
9298 }
9299
Eric Laurent331679c2018-04-16 17:03:16 -07009300 Mutex::Autolock _l(mLock);
9301
Eric Laurent6acd1d42017-01-04 14:23:29 -08009302 sp<MmapTrack> track;
9303 for (const sp<MmapTrack> &t : mActiveTracks) {
9304 if (handle == t->portId()) {
9305 track = t;
9306 break;
9307 }
9308 }
9309 if (track == 0) {
9310 return BAD_VALUE;
9311 }
9312
9313 mActiveTracks.remove(track);
9314
Eric Laurent331679c2018-04-16 17:03:16 -07009315 mLock.unlock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009316 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07009317 AudioSystem::stopOutput(track->portId());
9318 AudioSystem::releaseOutput(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -08009319 } else {
Eric Laurentfee19762018-01-29 18:44:13 -08009320 AudioSystem::stopInput(track->portId());
9321 AudioSystem::releaseInput(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -08009322 }
Eric Laurent331679c2018-04-16 17:03:16 -07009323 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009324
9325 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
9326 if (chain != 0) {
9327 chain->decActiveTrackCnt();
9328 chain->decTrackCnt();
9329 }
9330
9331 broadcast_l();
9332
Eric Laurent6acd1d42017-01-04 14:23:29 -08009333 return NO_ERROR;
9334}
9335
Eric Laurent18b57012017-02-13 16:23:52 -08009336status_t AudioFlinger::MmapThread::standby()
9337{
9338 ALOGV("%s", __FUNCTION__);
9339
9340 if (mHalStream == 0) {
9341 return NO_INIT;
9342 }
Eric Tan39ec8d62018-07-24 09:49:29 -07009343 if (!mActiveTracks.isEmpty()) {
Eric Laurent18b57012017-02-13 16:23:52 -08009344 return INVALID_OPERATION;
9345 }
9346 mHalStream->standby();
Andy Hungcf10d742020-04-28 15:38:24 -07009347 if (!mStandby) {
9348 mThreadMetrics.logEndInterval();
9349 mStandby = true;
9350 }
Eric Laurent18b57012017-02-13 16:23:52 -08009351 releaseWakeLock();
9352 return NO_ERROR;
9353}
9354
Eric Laurent6acd1d42017-01-04 14:23:29 -08009355
9356void AudioFlinger::MmapThread::readHalParameters_l()
9357{
9358 status_t result = mHalStream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
9359 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
9360 mFormat = mHALFormat;
9361 LOG_ALWAYS_FATAL_IF(!audio_is_linear_pcm(mFormat), "HAL format %#x is not linear pcm", mFormat);
9362 result = mHalStream->getFrameSize(&mFrameSize);
9363 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
Hayden Gomes1a89ab32020-06-12 11:05:47 -07009364 LOG_ALWAYS_FATAL_IF(mFrameSize <= 0, "Error frame size was %zu but must be greater than zero",
9365 mFrameSize);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009366 result = mHalStream->getBufferSize(&mBufferSize);
9367 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
9368 mFrameCount = mBufferSize / mFrameSize;
Andy Hungc2b11cb2020-04-22 09:04:01 -07009369
Andy Hungcf10d742020-04-28 15:38:24 -07009370 // TODO: make a readHalParameters call?
9371 mediametrics::LogItem item(mThreadMetrics.getMetricsId());
Andy Hungc2b11cb2020-04-22 09:04:01 -07009372 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
9373 .set(AMEDIAMETRICS_PROP_ENCODING, formatToString(mFormat).c_str())
9374 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
9375 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
9376 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
9377 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mFrameCount)
9378 /*
9379 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
9380 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELMASK,
9381 (int32_t)mHapticChannelMask)
9382 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELCOUNT,
9383 (int32_t)mHapticChannelCount)
9384 */
9385 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_ENCODING,
9386 formatToString(mHALFormat).c_str())
9387 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_FRAMECOUNT,
9388 (int32_t)mFrameCount) // sic - added HAL
9389 .record();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009390}
9391
9392bool AudioFlinger::MmapThread::threadLoop()
9393{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009394 checkSilentMode_l();
9395
9396 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
9397
9398 while (!exitPending())
9399 {
Eric Laurent6acd1d42017-01-04 14:23:29 -08009400 Vector< sp<EffectChain> > effectChains;
9401
Andy Hung13850be2019-03-14 11:33:09 -07009402 { // under Thread lock
9403 Mutex::Autolock _l(mLock);
9404
Eric Laurent6acd1d42017-01-04 14:23:29 -08009405 if (mSignalPending) {
9406 // A signal was raised while we were unlocked
9407 mSignalPending = false;
9408 } else {
9409 if (mConfigEvents.isEmpty()) {
9410 // we're about to wait, flush the binder command buffer
9411 IPCThreadState::self()->flushCommands();
9412
9413 if (exitPending()) {
9414 break;
9415 }
9416
Eric Laurent6acd1d42017-01-04 14:23:29 -08009417 // wait until we have something to do...
9418 ALOGV("%s going to sleep", myName.string());
9419 mWaitWorkCV.wait(mLock);
9420 ALOGV("%s waking up", myName.string());
Eric Laurent6acd1d42017-01-04 14:23:29 -08009421
9422 checkSilentMode_l();
9423
9424 continue;
9425 }
9426 }
9427
9428 processConfigEvents_l();
9429
9430 processVolume_l();
9431
9432 checkInvalidTracks_l();
9433
9434 mActiveTracks.updatePowerState(this);
9435
Kevin Rocard069c2712018-03-29 19:09:14 -07009436 updateMetadata_l();
9437
Eric Laurent6acd1d42017-01-04 14:23:29 -08009438 lockEffectChains_l(effectChains);
Andy Hung13850be2019-03-14 11:33:09 -07009439 } // release Thread lock
9440
Eric Laurent6acd1d42017-01-04 14:23:29 -08009441 for (size_t i = 0; i < effectChains.size(); i ++) {
Andy Hung13850be2019-03-14 11:33:09 -07009442 effectChains[i]->process_l(); // Thread is not locked, but effect chain is locked
Eric Laurent6acd1d42017-01-04 14:23:29 -08009443 }
Andy Hung13850be2019-03-14 11:33:09 -07009444
9445 // enable changes in effect chain, including moving to another thread.
Eric Laurent6acd1d42017-01-04 14:23:29 -08009446 unlockEffectChains(effectChains);
9447 // Effect chains will be actually deleted here if they were removed from
9448 // mEffectChains list during mixing or effects processing
9449 }
9450
9451 threadLoop_exit();
9452
9453 if (!mStandby) {
9454 threadLoop_standby();
9455 mStandby = true;
9456 }
9457
Eric Laurent6acd1d42017-01-04 14:23:29 -08009458 ALOGV("Thread %p type %d exiting", this, mType);
9459 return false;
9460}
9461
9462// checkForNewParameter_l() must be called with ThreadBase::mLock held
9463bool AudioFlinger::MmapThread::checkForNewParameter_l(const String8& keyValuePair,
9464 status_t& status)
9465{
9466 AudioParameter param = AudioParameter(keyValuePair);
9467 int value;
Eric Laurente6e9a482017-07-25 19:26:02 -07009468 bool sendToHal = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009469 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07009470 LOG_FATAL("Should not happen set routing device in MmapThread");
Eric Laurent6acd1d42017-01-04 14:23:29 -08009471 }
Eric Laurente6e9a482017-07-25 19:26:02 -07009472 if (sendToHal) {
9473 status = mHalStream->setParameters(keyValuePair);
9474 } else {
9475 status = NO_ERROR;
9476 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08009477
9478 return false;
9479}
9480
9481String8 AudioFlinger::MmapThread::getParameters(const String8& keys)
9482{
9483 Mutex::Autolock _l(mLock);
9484 String8 out_s8;
9485 if (initCheck() == NO_ERROR && mHalStream->getParameters(keys, &out_s8) == OK) {
9486 return out_s8;
9487 }
9488 return String8();
9489}
9490
Eric Laurent09f1ed22019-04-24 17:45:17 -07009491void AudioFlinger::MmapThread::ioConfigChanged(audio_io_config_event event, pid_t pid,
9492 audio_port_handle_t portId __unused) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08009493 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
9494
9495 desc->mIoHandle = mId;
9496
9497 switch (event) {
9498 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07009499 case AUDIO_INPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -08009500 case AUDIO_INPUT_CONFIG_CHANGED:
9501 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07009502 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -08009503 case AUDIO_OUTPUT_CONFIG_CHANGED:
9504 desc->mPatch = mPatch;
9505 desc->mChannelMask = mChannelMask;
9506 desc->mSamplingRate = mSampleRate;
9507 desc->mFormat = mFormat;
9508 desc->mFrameCount = mFrameCount;
9509 desc->mFrameCountHAL = mFrameCount;
9510 desc->mLatency = 0;
9511 break;
9512
9513 case AUDIO_INPUT_CLOSED:
9514 case AUDIO_OUTPUT_CLOSED:
9515 default:
9516 break;
9517 }
9518 mAudioFlinger->ioConfigChanged(event, desc, pid);
9519}
9520
9521status_t AudioFlinger::MmapThread::createAudioPatch_l(const struct audio_patch *patch,
9522 audio_patch_handle_t *handle)
9523{
9524 status_t status = NO_ERROR;
9525
9526 // store new device and send to effects
9527 audio_devices_t type = AUDIO_DEVICE_NONE;
9528 audio_port_handle_t deviceId;
jiabinc52b1ff2019-10-31 17:20:42 -07009529 AudioDeviceTypeAddrVector sinkDeviceTypeAddrs;
9530 AudioDeviceTypeAddr sourceDeviceTypeAddr;
9531 uint32_t numDevices = 0;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009532 if (isOutput()) {
9533 for (unsigned int i = 0; i < patch->num_sinks; i++) {
jiabinc52b1ff2019-10-31 17:20:42 -07009534 LOG_ALWAYS_FATAL_IF(popcount(patch->sinks[i].ext.device.type) > 1
9535 && !mAudioHwDev->supportsAudioPatches(),
9536 "Enumerated device type(%#x) must not be used "
9537 "as it does not support audio patches",
9538 patch->sinks[i].ext.device.type);
Mikhail Naganov55773032020-10-01 15:08:13 -07009539 type = static_cast<audio_devices_t>(type | patch->sinks[i].ext.device.type);
jiabinc52b1ff2019-10-31 17:20:42 -07009540 sinkDeviceTypeAddrs.push_back(AudioDeviceTypeAddr(patch->sinks[i].ext.device.type,
9541 patch->sinks[i].ext.device.address));
Eric Laurent6acd1d42017-01-04 14:23:29 -08009542 }
9543 deviceId = patch->sinks[0].id;
jiabinc52b1ff2019-10-31 17:20:42 -07009544 numDevices = mPatch.num_sinks;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009545 } else {
9546 type = patch->sources[0].ext.device.type;
9547 deviceId = patch->sources[0].id;
jiabinc52b1ff2019-10-31 17:20:42 -07009548 numDevices = mPatch.num_sources;
9549 sourceDeviceTypeAddr.mType = patch->sources[0].ext.device.type;
jiabin0a488932020-08-07 17:32:40 -07009550 sourceDeviceTypeAddr.setAddress(patch->sources[0].ext.device.address);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009551 }
9552
9553 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08009554 if (isOutput()) {
9555 mEffectChains[i]->setDevices_l(sinkDeviceTypeAddrs);
9556 } else {
9557 mEffectChains[i]->setInputDevice_l(sourceDeviceTypeAddr);
9558 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08009559 }
9560
jiabinc52b1ff2019-10-31 17:20:42 -07009561 if (!isOutput()) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08009562 // store new source and send to effects
9563 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
9564 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
9565 for (size_t i = 0; i < mEffectChains.size(); i++) {
9566 mEffectChains[i]->setAudioSource_l(mAudioSource);
9567 }
9568 }
9569 }
9570
9571 if (mAudioHwDev->supportsAudioPatches()) {
9572 status = mHalDevice->createAudioPatch(patch->num_sources,
9573 patch->sources,
9574 patch->num_sinks,
9575 patch->sinks,
9576 handle);
9577 } else {
9578 char *address;
9579 if (strcmp(patch->sinks[0].ext.device.address, "") != 0) {
9580 //FIXME: we only support address on first sink with HAL version < 3.0
9581 address = audio_device_address_to_parameter(
9582 patch->sinks[0].ext.device.type,
9583 patch->sinks[0].ext.device.address);
9584 } else {
9585 address = (char *)calloc(1, 1);
9586 }
9587 AudioParameter param = AudioParameter(String8(address));
9588 free(address);
9589 param.addInt(String8(AudioParameter::keyRouting), (int)type);
9590 if (!isOutput()) {
9591 param.addInt(String8(AudioParameter::keyInputSource),
9592 (int)patch->sinks[0].ext.mix.usecase.source);
9593 }
9594 status = mHalStream->setParameters(param.toString());
9595 *handle = AUDIO_PATCH_HANDLE_NONE;
9596 }
9597
jiabinc52b1ff2019-10-31 17:20:42 -07009598 if (numDevices == 0 || mDeviceId != deviceId) {
9599 if (isOutput()) {
9600 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
9601 mOutDeviceTypeAddrs = sinkDeviceTypeAddrs;
jiabin0a957d32020-04-29 10:56:20 -07009602 checkSilentMode_l();
jiabinc52b1ff2019-10-31 17:20:42 -07009603 } else {
9604 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
9605 mInDeviceTypeAddr = sourceDeviceTypeAddr;
9606 }
Phil Burk7f6b40d2017-02-09 13:18:38 -08009607 sp<MmapStreamCallback> callback = mCallback.promote();
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009608 if (mDeviceId != deviceId && callback != 0) {
Eric Laurent734046e2018-04-16 14:50:52 -07009609 mLock.unlock();
Phil Burk7f6b40d2017-02-09 13:18:38 -08009610 callback->onRoutingChanged(deviceId);
Eric Laurent734046e2018-04-16 14:50:52 -07009611 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009612 }
jiabinc52b1ff2019-10-31 17:20:42 -07009613 mPatch = *patch;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009614 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009615 }
9616 return status;
9617}
9618
9619status_t AudioFlinger::MmapThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
9620{
9621 status_t status = NO_ERROR;
9622
jiabinc52b1ff2019-10-31 17:20:42 -07009623 mPatch = audio_patch{};
9624 mOutDeviceTypeAddrs.clear();
9625 mInDeviceTypeAddr.reset();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009626
9627 bool supportsAudioPatches = mHalDevice->supportsAudioPatches(&supportsAudioPatches) == OK ?
9628 supportsAudioPatches : false;
9629
9630 if (supportsAudioPatches) {
9631 status = mHalDevice->releaseAudioPatch(handle);
9632 } else {
9633 AudioParameter param;
9634 param.addInt(String8(AudioParameter::keyRouting), 0);
9635 status = mHalStream->setParameters(param.toString());
9636 }
9637 return status;
9638}
9639
Mikhail Naganovdc769682018-05-04 15:34:08 -07009640void AudioFlinger::MmapThread::toAudioPortConfig(struct audio_port_config *config)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009641{
Mikhail Naganovdc769682018-05-04 15:34:08 -07009642 ThreadBase::toAudioPortConfig(config);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009643 if (isOutput()) {
9644 config->role = AUDIO_PORT_ROLE_SOURCE;
9645 config->ext.mix.hw_module = mAudioHwDev->handle();
9646 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
9647 } else {
9648 config->role = AUDIO_PORT_ROLE_SINK;
9649 config->ext.mix.hw_module = mAudioHwDev->handle();
9650 config->ext.mix.usecase.source = mAudioSource;
9651 }
9652}
9653
9654status_t AudioFlinger::MmapThread::addEffectChain_l(const sp<EffectChain>& chain)
9655{
9656 audio_session_t session = chain->sessionId();
9657
9658 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
9659 // Attach all tracks with same session ID to this chain.
9660 // indicate all active tracks in the chain
9661 for (const sp<MmapTrack> &track : mActiveTracks) {
9662 if (session == track->sessionId()) {
9663 chain->incTrackCnt();
9664 chain->incActiveTrackCnt();
9665 }
9666 }
9667
9668 chain->setThread(this);
9669 chain->setInBuffer(nullptr);
9670 chain->setOutBuffer(nullptr);
9671 chain->syncHalEffectsState();
9672
9673 mEffectChains.add(chain);
9674 checkSuspendOnAddEffectChain_l(chain);
9675 return NO_ERROR;
9676}
9677
9678size_t AudioFlinger::MmapThread::removeEffectChain_l(const sp<EffectChain>& chain)
9679{
9680 audio_session_t session = chain->sessionId();
9681
9682 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
9683
9684 for (size_t i = 0; i < mEffectChains.size(); i++) {
9685 if (chain == mEffectChains[i]) {
9686 mEffectChains.removeAt(i);
9687 // detach all active tracks from the chain
9688 // detach all tracks with same session ID from this chain
9689 for (const sp<MmapTrack> &track : mActiveTracks) {
9690 if (session == track->sessionId()) {
9691 chain->decActiveTrackCnt();
9692 chain->decTrackCnt();
9693 }
9694 }
9695 break;
9696 }
9697 }
9698 return mEffectChains.size();
9699}
9700
Eric Laurent6acd1d42017-01-04 14:23:29 -08009701void AudioFlinger::MmapThread::threadLoop_standby()
9702{
9703 mHalStream->standby();
9704}
9705
9706void AudioFlinger::MmapThread::threadLoop_exit()
9707{
Phil Burk7dce7282017-09-27 13:51:41 -07009708 // Do not call callback->onTearDown() because it is redundant for thread exit
9709 // and because it can cause a recursive mutex lock on stop().
Eric Laurent6acd1d42017-01-04 14:23:29 -08009710}
9711
9712status_t AudioFlinger::MmapThread::setSyncEvent(const sp<SyncEvent>& event __unused)
9713{
9714 return BAD_VALUE;
9715}
9716
9717bool AudioFlinger::MmapThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
9718{
9719 return false;
9720}
9721
9722status_t AudioFlinger::MmapThread::checkEffectCompatibility_l(
9723 const effect_descriptor_t *desc, audio_session_t sessionId)
9724{
9725 // No global effect sessions on mmap threads
Eric Laurent3f75a5b2019-11-12 15:55:51 -08009726 if (audio_is_global_session(sessionId)) {
9727 ALOGW("checkEffectCompatibility_l(): global effect %s on MMAP thread %s",
Eric Laurent6acd1d42017-01-04 14:23:29 -08009728 desc->name, mThreadName);
9729 return BAD_VALUE;
9730 }
9731
9732 if (!isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC)) {
9733 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on capture mmap thread",
9734 desc->name);
9735 return BAD_VALUE;
9736 }
9737 if (isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Glenn Kastend3bb6452016-12-05 18:14:37 -08009738 ALOGW("checkEffectCompatibility_l(): pre processing effect %s created on playback mmap "
9739 "thread", desc->name);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009740 return BAD_VALUE;
9741 }
9742
9743 // Only allow effects without processing load or latency
9744 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) != EFFECT_FLAG_NO_PROCESS) {
9745 return BAD_VALUE;
9746 }
9747
jiabineb3bda02020-06-30 14:07:03 -07009748 if (EffectModule::isHapticGenerator(&desc->type)) {
9749 ALOGE("%s(): HapticGenerator is not supported for MmapThread", __func__);
9750 return BAD_VALUE;
9751 }
9752
Eric Laurent6acd1d42017-01-04 14:23:29 -08009753 return NO_ERROR;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009754}
9755
9756void AudioFlinger::MmapThread::checkInvalidTracks_l()
9757{
9758 for (const sp<MmapTrack> &track : mActiveTracks) {
9759 if (track->isInvalid()) {
Phil Burk7f6b40d2017-02-09 13:18:38 -08009760 sp<MmapStreamCallback> callback = mCallback.promote();
9761 if (callback != 0) {
Eric Laurent734046e2018-04-16 14:50:52 -07009762 mLock.unlock();
Eric Laurent331679c2018-04-16 17:03:16 -07009763 callback->onTearDown(track->portId());
Eric Laurent734046e2018-04-16 14:50:52 -07009764 mLock.lock();
Eric Laurent331679c2018-04-16 17:03:16 -07009765 } else if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
9766 ALOGW("Could not notify MMAP stream tear down: no onTearDown callback!");
9767 mNoCallbackWarningCount++;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009768 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08009769 }
9770 }
9771}
9772
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07009773void AudioFlinger::MmapThread::dumpInternals_l(int fd, const Vector<String16>& args __unused)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009774{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009775 dprintf(fd, " Attributes: content type %d usage %d source %d\n",
9776 mAttr.content_type, mAttr.usage, mAttr.source);
9777 dprintf(fd, " Session: %d port Id: %d\n", mSessionId, mPortId);
Eric Tan39ec8d62018-07-24 09:49:29 -07009778 if (mActiveTracks.isEmpty()) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08009779 dprintf(fd, " No active clients\n");
9780 }
9781}
9782
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07009783void AudioFlinger::MmapThread::dumpTracks_l(int fd, const Vector<String16>& args __unused)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009784{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009785 String8 result;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009786 size_t numtracks = mActiveTracks.size();
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009787 dprintf(fd, " %zu Tracks\n", numtracks);
9788 const char *prefix = " ";
Eric Laurent6acd1d42017-01-04 14:23:29 -08009789 if (numtracks) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009790 result.append(prefix);
Kevin Rocard5f2136e2018-05-11 22:03:00 -07009791 mActiveTracks[0]->appendDumpHeader(result);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009792 for (size_t i = 0; i < numtracks ; ++i) {
9793 sp<MmapTrack> track = mActiveTracks[i];
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009794 result.append(prefix);
9795 track->appendDump(result, true /* active */);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009796 }
9797 } else {
9798 dprintf(fd, "\n");
9799 }
9800 write(fd, result.string(), result.size());
9801}
9802
9803AudioFlinger::MmapPlaybackThread::MmapPlaybackThread(
9804 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
jiabinc52b1ff2019-10-31 17:20:42 -07009805 AudioHwDevice *hwDev, AudioStreamOut *output, bool systemReady)
Andy Hungcf10d742020-04-28 15:38:24 -07009806 : MmapThread(audioFlinger, id, hwDev, output->stream, systemReady, true /* isOut */),
Eric Laurent6acd1d42017-01-04 14:23:29 -08009807 mStreamType(AUDIO_STREAM_MUSIC),
Phil Burk56ecf3e2018-03-12 15:38:17 -07009808 mStreamVolume(1.0),
9809 mStreamMute(false),
Phil Burk56ecf3e2018-03-12 15:38:17 -07009810 mOutput(output)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009811{
9812 snprintf(mThreadName, kThreadNameLength, "AudioMmapOut_%X", id);
9813 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
9814 mMasterVolume = audioFlinger->masterVolume_l();
9815 mMasterMute = audioFlinger->masterMute_l();
9816 if (mAudioHwDev) {
9817 if (mAudioHwDev->canSetMasterVolume()) {
9818 mMasterVolume = 1.0;
9819 }
9820
9821 if (mAudioHwDev->canSetMasterMute()) {
9822 mMasterMute = false;
9823 }
9824 }
9825}
9826
9827void AudioFlinger::MmapPlaybackThread::configure(const audio_attributes_t *attr,
9828 audio_stream_type_t streamType,
9829 audio_session_t sessionId,
9830 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009831 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -08009832 audio_port_handle_t portId)
9833{
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009834 MmapThread::configure(attr, streamType, sessionId, callback, deviceId, portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009835 mStreamType = streamType;
9836}
9837
9838AudioStreamOut* AudioFlinger::MmapPlaybackThread::clearOutput()
9839{
9840 Mutex::Autolock _l(mLock);
9841 AudioStreamOut *output = mOutput;
9842 mOutput = NULL;
9843 return output;
9844}
9845
9846void AudioFlinger::MmapPlaybackThread::setMasterVolume(float value)
9847{
9848 Mutex::Autolock _l(mLock);
9849 // Don't apply master volume in SW if our HAL can do it for us.
9850 if (mAudioHwDev &&
9851 mAudioHwDev->canSetMasterVolume()) {
9852 mMasterVolume = 1.0;
9853 } else {
9854 mMasterVolume = value;
9855 }
9856}
9857
9858void AudioFlinger::MmapPlaybackThread::setMasterMute(bool muted)
9859{
9860 Mutex::Autolock _l(mLock);
9861 // Don't apply master mute in SW if our HAL can do it for us.
9862 if (mAudioHwDev && mAudioHwDev->canSetMasterMute()) {
9863 mMasterMute = false;
9864 } else {
9865 mMasterMute = muted;
9866 }
9867}
9868
9869void AudioFlinger::MmapPlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
9870{
9871 Mutex::Autolock _l(mLock);
9872 if (stream == mStreamType) {
9873 mStreamVolume = value;
9874 broadcast_l();
9875 }
9876}
9877
9878float AudioFlinger::MmapPlaybackThread::streamVolume(audio_stream_type_t stream) const
9879{
9880 Mutex::Autolock _l(mLock);
9881 if (stream == mStreamType) {
9882 return mStreamVolume;
9883 }
9884 return 0.0f;
9885}
9886
9887void AudioFlinger::MmapPlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
9888{
9889 Mutex::Autolock _l(mLock);
9890 if (stream == mStreamType) {
9891 mStreamMute= muted;
9892 broadcast_l();
9893 }
9894}
9895
9896void AudioFlinger::MmapPlaybackThread::invalidateTracks(audio_stream_type_t streamType)
9897{
9898 Mutex::Autolock _l(mLock);
9899 if (streamType == mStreamType) {
9900 for (const sp<MmapTrack> &track : mActiveTracks) {
9901 track->invalidate();
9902 }
9903 broadcast_l();
9904 }
9905}
9906
9907void AudioFlinger::MmapPlaybackThread::processVolume_l()
9908{
9909 float volume;
9910
9911 if (mMasterMute || mStreamMute) {
9912 volume = 0;
9913 } else {
9914 volume = mMasterVolume * mStreamVolume;
9915 }
9916
9917 if (volume != mHalVolFloat) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08009918
9919 // Convert volumes from float to 8.24
9920 uint32_t vol = (uint32_t)(volume * (1 << 24));
9921
9922 // Delegate volume control to effect in track effect chain if needed
9923 // only one effect chain can be present on DirectOutputThread, so if
9924 // there is one, the track is connected to it
9925 if (!mEffectChains.isEmpty()) {
9926 mEffectChains[0]->setVolume_l(&vol, &vol);
9927 volume = (float)vol / (1 << 24);
9928 }
Eric Laurentdff774a2017-04-21 15:29:38 -07009929 // Try to use HW volume control and fall back to SW control if not implemented
Phil Burk56ecf3e2018-03-12 15:38:17 -07009930 if (mOutput->stream->setVolume(volume, volume) == NO_ERROR) {
9931 mHalVolFloat = volume; // HW volume control worked, so update value.
9932 mNoCallbackWarningCount = 0;
9933 } else {
Eric Laurentdff774a2017-04-21 15:29:38 -07009934 sp<MmapStreamCallback> callback = mCallback.promote();
9935 if (callback != 0) {
9936 int channelCount;
9937 if (isOutput()) {
9938 channelCount = audio_channel_count_from_out_mask(mChannelMask);
9939 } else {
9940 channelCount = audio_channel_count_from_in_mask(mChannelMask);
9941 }
9942 Vector<float> values;
9943 for (int i = 0; i < channelCount; i++) {
9944 values.add(volume);
9945 }
Phil Burk56ecf3e2018-03-12 15:38:17 -07009946 mHalVolFloat = volume; // SW volume control worked, so update value.
9947 mNoCallbackWarningCount = 0;
Eric Laurent734046e2018-04-16 14:50:52 -07009948 mLock.unlock();
9949 callback->onVolumeChanged(mChannelMask, values);
9950 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009951 } else {
Phil Burk56ecf3e2018-03-12 15:38:17 -07009952 if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
9953 ALOGW("Could not set MMAP stream volume: no volume callback!");
9954 mNoCallbackWarningCount++;
9955 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08009956 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08009957 }
Jasmine Chaeaa10e42021-05-11 10:11:14 +08009958 for (const sp<MmapTrack> &track : mActiveTracks) {
9959 track->setMetadataHasChanged();
9960 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08009961 }
9962}
9963
Kevin Rocard069c2712018-03-29 19:09:14 -07009964void AudioFlinger::MmapPlaybackThread::updateMetadata_l()
9965{
Jasmine Chaeaa10e42021-05-11 10:11:14 +08009966 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
9967 return; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -07009968 }
9969 StreamOutHalInterface::SourceMetadata metadata;
9970 for (const sp<MmapTrack> &track : mActiveTracks) {
9971 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurent94579172020-11-20 18:41:04 +01009972 playback_track_metadata_v7_t trackMetadata;
9973 trackMetadata.base = {
Kevin Rocard069c2712018-03-29 19:09:14 -07009974 .usage = track->attributes().usage,
9975 .content_type = track->attributes().content_type,
9976 .gain = mHalVolFloat, // TODO: propagate from aaudio pre-mix volume
Eric Laurent94579172020-11-20 18:41:04 +01009977 };
9978 trackMetadata.channel_mask = track->channelMask(),
9979 strncpy(trackMetadata.tags, track->attributes().tags, AUDIO_ATTRIBUTES_TAGS_MAX_SIZE);
9980 metadata.tracks.push_back(trackMetadata);
Kevin Rocard069c2712018-03-29 19:09:14 -07009981 }
9982 mOutput->stream->updateSourceMetadata(metadata);
9983}
9984
Eric Laurent6acd1d42017-01-04 14:23:29 -08009985void AudioFlinger::MmapPlaybackThread::checkSilentMode_l()
9986{
9987 if (!mMasterMute) {
9988 char value[PROPERTY_VALUE_MAX];
9989 if (property_get("ro.audio.silent", value, "0") > 0) {
9990 char *endptr;
9991 unsigned long ul = strtoul(value, &endptr, 0);
9992 if (*endptr == '\0' && ul != 0) {
9993 ALOGD("Silence is golden");
9994 // The setprop command will not allow a property to be changed after
9995 // the first time it is set, so we don't have to worry about un-muting.
9996 setMasterMute_l(true);
9997 }
9998 }
9999 }
10000}
10001
Mikhail Naganov32abc2b2018-05-24 12:57:11 -070010002void AudioFlinger::MmapPlaybackThread::toAudioPortConfig(struct audio_port_config *config)
10003{
10004 MmapThread::toAudioPortConfig(config);
10005 if (mOutput && mOutput->flags != AUDIO_OUTPUT_FLAG_NONE) {
10006 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
10007 config->flags.output = mOutput->flags;
10008 }
10009}
10010
jiabinb7d8c5a2020-08-26 17:24:52 -070010011status_t AudioFlinger::MmapPlaybackThread::getExternalPosition(uint64_t *position,
10012 int64_t *timeNanos)
10013{
10014 if (mOutput == nullptr) {
10015 return NO_INIT;
10016 }
10017 struct timespec timestamp;
10018 status_t status = mOutput->getPresentationPosition(position, &timestamp);
10019 if (status == NO_ERROR) {
10020 *timeNanos = timestamp.tv_sec * NANOS_PER_SECOND + timestamp.tv_nsec;
10021 }
10022 return status;
10023}
10024
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -070010025void AudioFlinger::MmapPlaybackThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010026{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -070010027 MmapThread::dumpInternals_l(fd, args);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010028
Glenn Kastend3bb6452016-12-05 18:14:37 -080010029 dprintf(fd, " Stream type: %d Stream volume: %f HAL volume: %f Stream mute %d\n",
10030 mStreamType, mStreamVolume, mHalVolFloat, mStreamMute);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010031 dprintf(fd, " Master volume: %f Master mute %d\n", mMasterVolume, mMasterMute);
10032}
10033
10034AudioFlinger::MmapCaptureThread::MmapCaptureThread(
10035 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
jiabinc52b1ff2019-10-31 17:20:42 -070010036 AudioHwDevice *hwDev, AudioStreamIn *input, bool systemReady)
Andy Hungcf10d742020-04-28 15:38:24 -070010037 : MmapThread(audioFlinger, id, hwDev, input->stream, systemReady, false /* isOut */),
Eric Laurent6acd1d42017-01-04 14:23:29 -080010038 mInput(input)
10039{
10040 snprintf(mThreadName, kThreadNameLength, "AudioMmapIn_%X", id);
10041 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
10042}
10043
Eric Laurent331679c2018-04-16 17:03:16 -070010044status_t AudioFlinger::MmapCaptureThread::exitStandby()
10045{
Phil Burkf054fc32018-12-06 09:45:59 -080010046 {
10047 // mInput might have been cleared by clearInput()
10048 Mutex::Autolock _l(mLock);
10049 if (mInput != nullptr && mInput->stream != nullptr) {
10050 mInput->stream->setGain(1.0f);
10051 }
10052 }
Eric Laurent331679c2018-04-16 17:03:16 -070010053 return MmapThread::exitStandby();
10054}
10055
Eric Laurent6acd1d42017-01-04 14:23:29 -080010056AudioFlinger::AudioStreamIn* AudioFlinger::MmapCaptureThread::clearInput()
10057{
10058 Mutex::Autolock _l(mLock);
10059 AudioStreamIn *input = mInput;
10060 mInput = NULL;
10061 return input;
10062}
Kevin Rocard069c2712018-03-29 19:09:14 -070010063
Eric Laurent331679c2018-04-16 17:03:16 -070010064
10065void AudioFlinger::MmapCaptureThread::processVolume_l()
10066{
10067 bool changed = false;
10068 bool silenced = false;
10069
10070 sp<MmapStreamCallback> callback = mCallback.promote();
10071 if (callback == 0) {
10072 if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
10073 ALOGW("Could not set MMAP stream silenced: no onStreamSilenced callback!");
10074 mNoCallbackWarningCount++;
10075 }
10076 }
10077
10078 // After a change occurred in track silenced state, mute capture in audio DSP if at least one
10079 // track is silenced and unmute otherwise
10080 for (size_t i = 0; i < mActiveTracks.size() && !silenced; i++) {
10081 if (!mActiveTracks[i]->getAndSetSilencedNotified_l()) {
10082 changed = true;
10083 silenced = mActiveTracks[i]->isSilenced_l();
10084 }
10085 }
10086
10087 if (changed) {
10088 mInput->stream->setGain(silenced ? 0.0f: 1.0f);
10089 }
10090}
10091
Kevin Rocard069c2712018-03-29 19:09:14 -070010092void AudioFlinger::MmapCaptureThread::updateMetadata_l()
10093{
Jasmine Chaeaa10e42021-05-11 10:11:14 +080010094 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
10095 return; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -070010096 }
10097 StreamInHalInterface::SinkMetadata metadata;
10098 for (const sp<MmapTrack> &track : mActiveTracks) {
10099 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurent94579172020-11-20 18:41:04 +010010100 record_track_metadata_v7_t trackMetadata;
10101 trackMetadata.base = {
Kevin Rocard069c2712018-03-29 19:09:14 -070010102 .source = track->attributes().source,
10103 .gain = 1, // capture tracks do not have volumes
Eric Laurent94579172020-11-20 18:41:04 +010010104 };
10105 trackMetadata.channel_mask = track->channelMask(),
10106 strncpy(trackMetadata.tags, track->attributes().tags, AUDIO_ATTRIBUTES_TAGS_MAX_SIZE);
10107 metadata.tracks.push_back(trackMetadata);
Kevin Rocard069c2712018-03-29 19:09:14 -070010108 }
10109 mInput->stream->updateSinkMetadata(metadata);
10110}
10111
Eric Laurent5ada82e2019-08-29 17:53:54 -070010112void AudioFlinger::MmapCaptureThread::setRecordSilenced(audio_port_handle_t portId, bool silenced)
Eric Laurent331679c2018-04-16 17:03:16 -070010113{
10114 Mutex::Autolock _l(mLock);
10115 for (size_t i = 0; i < mActiveTracks.size() ; i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -070010116 if (mActiveTracks[i]->portId() == portId) {
Eric Laurent331679c2018-04-16 17:03:16 -070010117 mActiveTracks[i]->setSilenced_l(silenced);
10118 broadcast_l();
10119 }
10120 }
10121}
10122
Mikhail Naganov32abc2b2018-05-24 12:57:11 -070010123void AudioFlinger::MmapCaptureThread::toAudioPortConfig(struct audio_port_config *config)
10124{
10125 MmapThread::toAudioPortConfig(config);
10126 if (mInput && mInput->flags != AUDIO_INPUT_FLAG_NONE) {
10127 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
10128 config->flags.input = mInput->flags;
10129 }
10130}
10131
jiabinb7d8c5a2020-08-26 17:24:52 -070010132status_t AudioFlinger::MmapCaptureThread::getExternalPosition(
10133 uint64_t *position, int64_t *timeNanos)
10134{
10135 if (mInput == nullptr) {
10136 return NO_INIT;
10137 }
10138 return mInput->getCapturePosition((int64_t*)position, timeNanos);
10139}
10140
Glenn Kasten63238ef2015-03-02 15:50:29 -080010141} // namespace android